From aa7401a18908c1ca4678db7e58741d49b8c775e2 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 21:11:36 -0500 Subject: [PATCH 1/5] fix(loaders): retry lazy chunks under a cache-busted URL A failed dynamic import is remembered in the browser's module map for the page's lifetime (Chromium 136 and WebKit 26.5 both reject a re-import of the same URL without a request), so one dropped download of the 10 MB EvoSDK chunk made registration fail for good, with WebKit's bare "Importing a module script failed.". - createChunkLoader: memoized, 3 attempts with 0.5/1.5 s backoff; retries import the chunk's built URL with a ?retry= query (a new module map entry), log each failure with the chunk name, clear the memo and throw a ChunkLoadError naming the chunk. - virtual:chunk-url: (Vite plugin) gives the built URL of a dynamic-import chunk; emitted with implicitlyLoadedAfterOneOf so the chunk graph is unchanged. - loadPlatformForFunding loads the SDK and platform chunks for the funding gate. - experimentalMinChunkSize merges the 0.24 kB commonjs helper the islock and evo-sdk chunks shared into the entry: WebKit keeps a failed fetch of such a static dependency across reloads, which no retry or reload could recover. The build check now fails if a lazy chunk imports anything but the entry. Co-Authored-By: Claude Sonnet 5.5 --- scripts/check-build-artifacts.mjs | 18 ++++- src/config/vite-chunk-url.ts | 62 ++++++++++++++++++ src/platform/chunk-loader.test.ts | 105 ++++++++++++++++++++++++++++++ src/platform/chunk-loader.ts | 100 ++++++++++++++++++++++++++++ src/platform/loaders.test.ts | 41 ------------ src/platform/loaders.ts | 59 +++++++++++------ src/platform/sdkModule.ts | 5 +- src/vite-env.d.ts | 6 ++ vite.config.ts | 13 ++++ vitest.config.ts | 2 + 10 files changed, 347 insertions(+), 64 deletions(-) create mode 100644 src/config/vite-chunk-url.ts create mode 100644 src/platform/chunk-loader.test.ts create mode 100644 src/platform/chunk-loader.ts delete mode 100644 src/platform/loaders.test.ts diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index ab2fe74..c11aa6d 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; // Guard the Lighthouse fix: the initial page must not preload or statically @@ -62,6 +62,22 @@ if (staticImportPattern.test(entryChunk)) { fail('entry chunk statically imports a heavy Dash chunk'); } +// Lazy chunks may statically import only the entry chunk, which is already +// loaded. A shared dependency chunk can fail to download on its own, and +// WebKit keeps that failure across reloads, which would make every lazy chunk +// importing it unloadable (see experimentalMinChunkSize in vite.config.ts). +const entryFile = entryRelativePath.replace(/^assets\//, ''); +const assetsDir = join(distDir.pathname, 'assets'); +for (const file of readdirSync(assetsDir).filter((f) => f.endsWith('.js') && f !== entryFile)) { + const code = readFileSync(join(assetsDir, file), 'utf8'); + const staticDeps = [...code.matchAll(/(?:^|[;}\s])import\s*(?:[\w*{}\s,$]+from\s*)?["']\.\/([^"']+)["']/g)] + .map((m) => m[1]) + .filter((dep) => dep !== entryFile); + if (staticDeps.length > 0) { + fail(`assets/${file} statically imports ${staticDeps.join(', ')}; lazy chunks may only import the entry chunk`); + } +} + // The embeddable widget SDK (docs/widget.md) must ship, stay tiny, and never // pull in the Dash SDK or other heavy dependencies. const WIDGET_MAX_BYTES = 30 * 1024; diff --git a/src/config/vite-chunk-url.ts b/src/config/vite-chunk-url.ts new file mode 100644 index 0000000..ae5974f --- /dev/null +++ b/src/config/vite-chunk-url.ts @@ -0,0 +1,62 @@ +import type { Plugin } from 'vite'; + +/** + * `import url from 'virtual:chunk-url:'` gives the built URL of + * the chunk that `import('')` loads (resolved like an import from + * the importing file), or null outside a production build. + * + * Why: a failed dynamic import is remembered in the browser's module map for + * the page's lifetime (Chromium, per the HTML spec), so retrying the same + * `import()` never re-fetches. Importing the same chunk under a URL with a + * query string is a new module map entry and does re-fetch (see + * platform/chunk-loader.ts). + * + * Only use it for modules that are already loaded lazily (dynamic import + * targets): the chunk is emitted explicitly (loaded after its importer), so a + * module that is statically imported elsewhere would be split out of the + * chunk it lives in now. + */ +export const CHUNK_URL_PREFIX = 'virtual:chunk-url:'; +const RESOLVED_PREFIX = '\0virtual:chunk-url:'; +// The dev server and vitest serve modules unbundled: there is no chunk to +// name. One id for all, which also keeps target paths out of dev request URLs. +const RESOLVED_DEV_ID = '\0virtual:chunk-url-dev'; + +export function chunkUrlPlugin(): Plugin { + let isBuild = false; + // Resolved virtual id -> the module that imports it. + const importers = new Map(); + return { + name: 'dash-bridge:chunk-url', + configResolved(config) { + isBuild = config.command === 'build'; + }, + async resolveId(source, importer) { + if (!source.startsWith(CHUNK_URL_PREFIX)) return null; + if (!isBuild) return RESOLVED_DEV_ID; + const target = source.slice(CHUNK_URL_PREFIX.length); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved || resolved.external) { + this.error(`chunk-url: cannot resolve "${target}" from ${importer ?? '(unknown)'}`); + } + const id = RESOLVED_PREFIX + resolved.id; + if (importer) importers.set(id, importer); + return id; + }, + load(id) { + if (id === RESOLVED_DEV_ID) return 'export default null;'; + if (!id.startsWith(RESOLVED_PREFIX)) return null; + const importer = importers.get(id); + const ref = this.emitFile({ + type: 'chunk', + id: id.slice(RESOLVED_PREFIX.length), + // The chunk is only ever loaded after its importer, as with the + // dynamic import it mirrors. Without this Rollup must assume it can + // load first and splits every module it shares with the main bundle + // out into separate chunks. + ...(importer ? { implicitlyLoadedAfterOneOf: [importer] } : {}), + }); + return `export default import.meta.ROLLUP_FILE_URL_${ref};`; + }, + }; +} diff --git a/src/platform/chunk-loader.test.ts b/src/platform/chunk-loader.test.ts new file mode 100644 index 0000000..3098313 --- /dev/null +++ b/src/platform/chunk-loader.test.ts @@ -0,0 +1,105 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ChunkLoadError, cacheBustedUrl, createChunkLoader, isChunkLoadError } from './chunk-loader.js'; + +const noSleep = { sleep: async () => {} }; + +describe('createChunkLoader', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('reuses one in-flight promise for concurrent calls', async () => { + let calls = 0; + let resolveLoad: ((value: string) => void) | undefined; + const loader = createChunkLoader('x', null, () => { + calls += 1; + return new Promise((resolve) => { + resolveLoad = resolve; + }); + }); + + const first = loader(); + const second = loader(); + + expect(first).toBe(second); + expect(calls).toBe(1); + + resolveLoad?.('ready'); + await expect(first).resolves.toBe('ready'); + await expect(second).resolves.toBe('ready'); + }); + + it('retries the plain import with backoff when the chunk URL is unknown', async () => { + const sleeps: number[] = []; + let calls = 0; + const loader = createChunkLoader('x', null, async () => { + calls += 1; + if (calls < 3) throw new TypeError('Importing a module script failed.'); + return 'loaded'; + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + await expect(loader()).resolves.toBe('loaded'); + expect(calls).toBe(3); + expect(sleeps).toEqual([500, 1500]); + }); + + it('retries under a cache-busted chunk URL, because a failed import() is remembered per URL', async () => { + const importUrl = vi.fn(async (url: string) => ({ from: url })); + const load = vi.fn(async () => { + throw new TypeError('Failed to fetch dynamically imported module'); + }); + const loader = createChunkLoader( + 'evo-sdk', + 'https://bridge.example/assets/evo-sdk.module-abc.js', + load, + { ...noSleep, importUrl } + ); + + const mod = (await loader()) as unknown as { from: string }; + expect(load).toHaveBeenCalledTimes(1); + expect(importUrl).toHaveBeenCalledTimes(1); + const url = new URL(mod.from); + expect(url.origin + url.pathname).toBe('https://bridge.example/assets/evo-sdk.module-abc.js'); + expect(url.searchParams.get('retry')).toMatch(/^1\./); + }); + + it('gives up after 3 attempts with a ChunkLoadError naming the chunk, logs each failure, then lets a later call start over', async () => { + let calls = 0; + const loader = createChunkLoader('evo-sdk', null, async () => { + calls += 1; + if (calls <= 3) throw new TypeError('Importing a module script failed.'); + return 'recovered'; + }, noSleep); + + const error = await loader().catch((e: unknown) => e); + expect(isChunkLoadError(error)).toBe(true); + expect(error).toBeInstanceOf(ChunkLoadError); + expect((error as ChunkLoadError).chunk).toBe('evo-sdk'); + expect((error as ChunkLoadError).attempts).toBe(3); + expect((error as ChunkLoadError).message).toBe( + 'Could not load the "evo-sdk" component after 3 attempts: Importing a module script failed.' + ); + const warn = vi.mocked(console.warn); + expect(warn).toHaveBeenCalledTimes(3); + expect(String(warn.mock.calls[0][0])).toContain('Chunk "evo-sdk" failed to load (attempt 1/3); retrying in 500 ms'); + expect(String(warn.mock.calls[2][0])).toContain('(attempt 3/3)'); + + await expect(loader()).resolves.toBe('recovered'); + expect(calls).toBe(4); + }); +}); + +describe('cacheBustedUrl', () => { + it('keeps the path, adds a per-attempt retry parameter and preserves other query params', () => { + const a = new URL(cacheBustedUrl('https://h.example/a/chunk.js?x=1', 1)); + const b = new URL(cacheBustedUrl('https://h.example/a/chunk.js?x=1', 2)); + expect(a.pathname).toBe('/a/chunk.js'); + expect(a.searchParams.get('x')).toBe('1'); + expect(a.searchParams.get('retry')).not.toBe(b.searchParams.get('retry')); + }); +}); diff --git a/src/platform/chunk-loader.ts b/src/platform/chunk-loader.ts new file mode 100644 index 0000000..0581762 --- /dev/null +++ b/src/platform/chunk-loader.ts @@ -0,0 +1,100 @@ +/** + * Lazy chunk loading that survives a dropped download. + * + * Browsers remember a failed `import()` for the page's lifetime (Chromium + * follows the HTML spec's module map; iOS WebKit may too), so retrying the same + * import rejects again without touching the network. Retries therefore import + * the chunk's built URL with a query string, which is a new module map entry. + * The chunk's own static imports still resolve to the shared, already-loaded + * modules, so nothing is instantiated twice. + */ + +/** Thrown when a lazily loaded part of the app could not be downloaded. */ +export class ChunkLoadError extends Error { + readonly chunk: string; + readonly attempts: number; + + constructor(chunk: string, attempts: number, cause: unknown) { + const reason = cause instanceof Error ? cause.message : String(cause); + super(`Could not load the "${chunk}" component after ${attempts} attempt${attempts === 1 ? '' : 's'}: ${reason}`); + this.name = 'ChunkLoadError'; + this.chunk = chunk; + this.attempts = attempts; + (this as { cause?: unknown }).cause = cause; + } +} + +export function isChunkLoadError(error: unknown): error is ChunkLoadError { + return error instanceof ChunkLoadError; +} + +export interface ChunkLoaderOptions { + /** Delay before each retry; its length + 1 is the attempt count. */ + retryDelaysMs?: readonly number[]; + sleep?: (ms: number) => Promise; + /** Imports a URL (overridable for tests). */ + importUrl?: (url: string) => Promise; +} + +export const CHUNK_RETRY_DELAYS_MS = [500, 1500] as const; + +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const defaultImportUrl = (url: string) => import(/* @vite-ignore */ url); + +/** Unique per page load, so a CDN cannot answer the retry from a cached error. */ +const pageToken = Date.now().toString(36); + +export function cacheBustedUrl(url: string, attempt: number): string { + const parsed = new URL(url, globalThis.location?.href); + parsed.searchParams.set('retry', `${attempt}.${pageToken}`); + return parsed.href; +} + +/** + * Memoized loader for a lazily imported chunk. Concurrent callers share one + * load; a failed load is retried with backoff (re-fetching under a cache-busted + * URL when the chunk URL is known), then the memo is cleared so a later call + * starts over, and a ChunkLoadError naming the chunk is thrown. + * + * @param chunk name for logs and the error screen + * @param chunkUrl built URL of the chunk (virtual:chunk-url), null in dev + * @param load the plain dynamic import + */ +export function createChunkLoader( + chunk: string, + chunkUrl: string | null, + load: () => Promise, + options: ChunkLoaderOptions = {} +): () => Promise { + const retryDelays = options.retryDelaysMs ?? CHUNK_RETRY_DELAYS_MS; + const sleep = options.sleep ?? defaultSleep; + const importUrl = options.importUrl ?? defaultImportUrl; + const attempts = retryDelays.length + 1; + + const loadWithRetries = async (): Promise => { + let lastError: unknown; + for (let attempt = 0; attempt < attempts; attempt++) { + if (attempt > 0) await sleep(retryDelays[attempt - 1]); + try { + if (attempt === 0 || !chunkUrl) return await load(); + return (await importUrl(cacheBustedUrl(chunkUrl, attempt))) as T; + } catch (error) { + lastError = error; + const next = attempt + 1 < attempts ? `; retrying in ${retryDelays[attempt]} ms` : ''; + console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${attempts})${next}:`, error); + } + } + throw new ChunkLoadError(chunk, attempts, lastError); + }; + + let promise: Promise | null = null; + return () => { + if (!promise) { + promise = loadWithRetries().catch((err) => { + promise = null; + throw err; + }); + } + return promise; + }; +} diff --git a/src/platform/loaders.test.ts b/src/platform/loaders.test.ts deleted file mode 100644 index 7296055..0000000 --- a/src/platform/loaders.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { createCachedLoader } from './loaders.js'; - -describe('createCachedLoader', () => { - it('reuses one in-flight promise for concurrent calls', async () => { - let calls = 0; - let resolveLoad: ((value: string) => void) | undefined; - const loader = createCachedLoader(() => { - calls += 1; - return new Promise((resolve) => { - resolveLoad = resolve; - }); - }); - - const first = loader(); - const second = loader(); - - expect(first).toBe(second); - expect(calls).toBe(1); - - resolveLoad?.('ready'); - await expect(first).resolves.toBe('ready'); - await expect(second).resolves.toBe('ready'); - }); - - it('clears a rejected promise so a later call can retry', async () => { - let calls = 0; - const loader = createCachedLoader(async () => { - calls += 1; - if (calls === 1) { - throw new Error('chunk failed'); - } - return 'recovered'; - }); - - await expect(loader()).rejects.toThrow('chunk failed'); - await expect(loader()).resolves.toBe('recovered'); - expect(calls).toBe(2); - }); -}); diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index 09a9123..af2a4e5 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -1,25 +1,30 @@ +import platformChunkUrl from 'virtual:chunk-url:./index.js'; +import dpnsChunkUrl from 'virtual:chunk-url:./dpns.js'; +import contractChunkUrl from 'virtual:chunk-url:./contract.js'; +import usernameTransferChunkUrl from 'virtual:chunk-url:./username-transfer.js'; +import feeEstimatorChunkUrl from 'virtual:chunk-url:dash-contract-fee-estimator'; +import islockChunkUrl from 'virtual:chunk-url:../api/islock.js'; import { getNetwork } from '../config.js'; +import { createChunkLoader } from './chunk-loader.js'; +import { loadSdkModule } from './sdkModule.js'; -export function createCachedLoader(load: () => Promise): () => Promise { - let promise: Promise | null = null; - return () => { - if (!promise) { - promise = load().catch((err) => { - promise = null; - throw err; - }); - } - return promise; - }; -} - -export const loadPlatformModule = createCachedLoader(() => import('./index.js')); -export const loadDpnsModule = createCachedLoader(() => import('./dpns.js')); -export const loadContractModule = createCachedLoader(() => import('./contract.js')); -export const loadUsernameTransferModule = createCachedLoader(() => import('./username-transfer.js')); -export const loadPlatformClientModule = createCachedLoader(() => import('./client.js')); -export const loadFeeEstimatorModule = createCachedLoader(() => import('dash-contract-fee-estimator')); -export const loadIslockModule = createCachedLoader(() => import('../api/islock.js')); +export const loadPlatformModule = createChunkLoader('platform', platformChunkUrl, () => import('./index.js')); +export const loadDpnsModule = createChunkLoader('dpns', dpnsChunkUrl, () => import('./dpns.js')); +export const loadContractModule = createChunkLoader('contract', contractChunkUrl, () => import('./contract.js')); +export const loadUsernameTransferModule = createChunkLoader( + 'username-transfer', + usernameTransferChunkUrl, + () => import('./username-transfer.js') +); +// client.ts is statically imported by other platform modules, so it lives in +// the main chunk and this import never fetches anything: no chunk URL needed. +export const loadPlatformClientModule = createChunkLoader('platform-client', null, () => import('./client.js')); +export const loadFeeEstimatorModule = createChunkLoader( + 'fee-estimator', + feeEstimatorChunkUrl, + () => import('dash-contract-fee-estimator') +); +export const loadIslockModule = createChunkLoader('islock', islockChunkUrl, () => import('../api/islock.js')); export function warmDashModules(): Promise[]> { return Promise.allSettled([ @@ -33,6 +38,20 @@ export function warmDashModules(): Promise[]> { ]); } +/** + * Load everything a Platform submission needs (the EvoSDK chunk and the + * platform operations chunk) before a funding flow shows its deposit address. + * Once funds are committed the submission must not depend on a download, which + * can fail (e.g. iOS suspends a backgrounded tab's network while the user pays + * from a wallet app) and, once failed, is remembered by the browser. + * + * Every network: registration needs the SDK everywhere. Rejects with a + * ChunkLoadError when a chunk still fails after the loaders' retries. + */ +export async function loadPlatformForFunding(): Promise { + await Promise.all([loadSdkModule(), loadPlatformModule()]); +} + /** * Start connecting the EvoSDK when the user enters a funding flow (create, * top-up, send-to-address), before any funds can be committed. Registration diff --git a/src/platform/sdkModule.ts b/src/platform/sdkModule.ts index 679e652..41134a2 100644 --- a/src/platform/sdkModule.ts +++ b/src/platform/sdkModule.ts @@ -1,5 +1,6 @@ -import { createCachedLoader } from './loaders.js'; +import evoSdkChunkUrl from 'virtual:chunk-url:@dashevo/evo-sdk'; +import { createChunkLoader } from './chunk-loader.js'; export type SdkModule = typeof import('@dashevo/evo-sdk'); -export const loadSdkModule = createCachedLoader(() => import('@dashevo/evo-sdk')); +export const loadSdkModule = createChunkLoader('evo-sdk', evoSdkChunkUrl, () => import('@dashevo/evo-sdk')); diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe..a8d8167 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,7 @@ /// + +/** Built URL of a lazily imported chunk; null in dev and tests. See src/config/vite-chunk-url.ts. */ +declare module 'virtual:chunk-url:*' { + const url: string | null; + export default url; +} diff --git a/vite.config.ts b/vite.config.ts index 01aff52..1ac9495 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,10 +1,12 @@ import { defineConfig } from 'vite'; import { nodePolyfills } from 'vite-plugin-node-polyfills'; import { shouldPreloadDashChunk } from './src/config/vite-preload.js'; +import { chunkUrlPlugin } from './src/config/vite-chunk-url.js'; export default defineConfig({ base: process.env.BASE_PATH || '/', plugins: [ + chunkUrlPlugin(), nodePolyfills({ include: ['util', 'stream', 'events', 'buffer', 'process', 'path', 'os', 'string_decoder', 'crypto'], globals: { @@ -23,6 +25,17 @@ export default defineConfig({ commonjsOptions: { transformMixedEsModules: true, }, + rollupOptions: { + output: { + // Merge tiny shared chunks (the 0.24 kB commonjs helper the islock and + // evo-sdk chunks share) into a chunk that is always loaded with them: + // the entry. A lazy chunk then depends only on the already loaded + // entry. WebKit keeps a failed fetch of a static dependency across + // reloads, so a dropped download of such a shared chunk would make + // the lazy chunks that import it unloadable until the tab is closed. + experimentalMinChunkSize: 1024, + }, + }, }, optimizeDeps: { esbuildOptions: { diff --git a/vitest.config.ts b/vitest.config.ts index 9fa19e1..9474403 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,6 +1,8 @@ import { defineConfig } from 'vitest/config'; +import { chunkUrlPlugin } from './src/config/vite-chunk-url.js'; export default defineConfig({ + plugins: [chunkUrlPlugin()], test: { exclude: [ 'e2e/**', From 2c3b875feea7d6e866f267a556faf0727f6600d5 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 21:11:45 -0500 Subject: [PATCH 2/5] fix(bridge): load the Platform SDK before showing a deposit address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owners on iPhone reached "Creating identity..." with the InstantSend lock in hand and then failed with "Importing a module script failed.": the EvoSDK chunk was only warmed in the background (failure swallowed) and first needed after the funds were locked. The error screen then said "InstantSend didn't go through", which was false. - Every funding flow (create, top-up, send to address; all networks) now waits on a "Preparing…" screen until the SDK and platform chunks are loaded. On testnet it also starts the SDK connect and waits for it at most 5 s (health indicator semantics unchanged). If a chunk still fails after the loader's retries, ERR-1017 explains that a required component failed to load, that no funds were sent, and offers Reload. - After the lock arrived, a failed Platform submission now says so ("the InstantSend lock arrived, but ..."), names a chunk that failed to load, and offers Retry Registration / Top-up / Send with the proof in state, next to the chain lock proof option. "InstantSend didn't go through" is kept only for a missing lock. - Technical Details show the chunk that failed to load. - Mock-mode e2e: failure injection (window.__e2eMockFailures) drives the real retrying loader and the post-lock retry. Co-Authored-By: Claude Sonnet 5.5 --- e2e/deterministic.spec.ts | 92 ++++++++++++++++++ src/main.ts | 115 ++++++++++++++++++---- src/ui/components.error-recovery.test.ts | 81 +++++++++++++++ src/ui/components.ts | 72 +++++++++++--- src/ui/state.error-recovery.test.ts | 119 +++++++++++++++++++++++ src/ui/state.ts | 61 +++++++++++- 6 files changed, 501 insertions(+), 39 deletions(-) create mode 100644 src/ui/components.error-recovery.test.ts create mode 100644 src/ui/state.error-recovery.test.ts diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index 0e241f1..bd358c6 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -87,6 +87,98 @@ test.describe('Deterministic UI E2E (mock mode)', () => { await expect(page.getByText('Registration Complete!')).toBeVisible(); }); + test.describe('Platform component gate before funding', () => { + const injectFailures = (page: import('@playwright/test').Page, failures: Record) => + page.addInitScript((f) => { + (window as { __e2eMockFailures?: Record }).__e2eMockFailures = f; + }, failures); + const advance = async (page: import('@playwright/test').Page) => { + await expect.poll(async () => { + return page.evaluate(() => typeof (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance); + }).toBe('function'); + await page.evaluate(() => (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance?.()); + }; + + test('a dropped SDK download is retried and the flow reaches the deposit address', async ({ page }) => { + const warnings: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warning') warnings.push(msg.text()); + }); + await injectFailures(page, { sdkLoadFailures: 2 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + + // The retries' backoff (0.5 + 1.5 s) keeps the gate on screen. + await expect(page.locator('.preparing-step')).toContainText('Preparing…'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + expect(warnings.filter((w) => w.includes('Chunk "evo-sdk" failed to load'))).toHaveLength(2); + }); + + for (const flow of ['create', 'topup'] as const) { + test(`${flow}: an SDK that cannot load stops the flow before any deposit address, with Reload`, async ({ page }) => { + await injectFailures(page, { sdkLoadFailures: 3 }); + await page.goto(MOCK_QUERY); + if (flow === 'create') { + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + } else { + await page.click('#mode-manage-btn'); + await page.click('#manage-action-topup-btn'); + await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); + await page.click('#continue-topup-btn'); + } + + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1017'); + await expect(page.locator('.error-step')).toContainText('The page failed to load a required component "evo-sdk"'); + await expect(page.locator('.error-step')).toContainText('No funds have been sent'); + await expect(page.locator('.deposit-headline')).toHaveCount(0); + await expect(page.locator('#download-keys-btn')).toHaveCount(0); + await page.locator('.error-technical summary').click(); + await expect(page.locator('.error-technical-content')).toContainText('Failed to load: evo-sdk'); + + // Reload is safe here: nothing was funded. The reloaded page starts over. + await page.click('#reload-page-btn'); + await expect(page.locator('#mode-create-btn')).toBeVisible(); + }); + } + + test('registration failing after the lock arrived says so, and Retry Registration completes it', async ({ page }) => { + await injectFailures(page, { submissionFailures: 1 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + await advance(page); + + const errorStep = page.locator('.error-step'); + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1006'); + await expect(errorStep).toContainText('the InstantSend lock arrived'); + await expect(errorStep).not.toContainText("InstantSend didn't go through"); + await expect(page.locator('#download-keys-btn')).toBeVisible(); + + await page.click('#retry-registration-btn'); + await expect(page.getByText('Save your keys')).toBeVisible(); + await expect(page.locator('.contract-id-section', { hasText: 'Your Identity ID' }).locator('.identity-id')).toHaveText(E2E_MOCK_IDENTITY_ID); + }); + + test('top-up failing after the lock arrived offers Retry Top-up, which completes it', async ({ page }) => { + await injectFailures(page, { submissionFailures: 1 }); + await page.goto(MOCK_QUERY); + await page.click('#mode-manage-btn'); + await page.click('#manage-action-topup-btn'); + await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); + await page.click('#continue-topup-btn'); + await expect(page.locator('.deposit-headline')).toBeVisible(); + await advance(page); + + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1007'); + await expect(page.locator('#retry-registration-btn')).toHaveText('Retry Top-up'); + await page.click('#retry-registration-btn'); + await expect(page.getByText('Top-up complete!')).toBeVisible(); + }); + }); + test('top up flow validates identity input and reaches completion', async ({ page }) => { await page.goto(MOCK_QUERY); diff --git a/src/main.ts b/src/main.ts index 0aca256..9bb5488 100644 --- a/src/main.ts +++ b/src/main.ts @@ -207,10 +207,12 @@ import { loadIslockModule, loadPlatformClientModule, loadPlatformModule, + loadPlatformForFunding, loadUsernameTransferModule, warmDashModules, warmPlatformSdkForFunding, } from './platform/loaders.js'; +import { ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; import { deriveCandidateKeys, explainKeyIneligibility, @@ -340,17 +342,33 @@ function preloadDashWarmup(): void { void ensureClients().catch((err) => console.warn('Dash warmup failed:', err)); } +/** How long a funding flow waits for the testnet SDK connect before showing its deposit address anyway. */ +const FUNDING_SDK_CONNECT_WAIT_MS = 5000; + /** - * Funding is about to start: begin connecting the SDK (testnet only), so the - * health indicator reads Platform before the asset lock is broadcast. Polls - * right after the connect settles instead of waiting for the next 30 s tick. + * Gate in front of every funding flow's deposit address (shown as "Preparing + * Dash Platform..."). Loads the chunks the Platform submission needs, with + * retries, so that once funds are committed nothing depends on a download; + * when they still fail this throws a ChunkLoadError while nothing is at risk + * (error screen with Reload). + * + * Testnet also starts connecting the SDK, so the health indicator reads + * Platform before the asset lock is broadcast (polls right after the connect + * settles instead of waiting for the next 30 s tick). The flow waits for that + * connect at most FUNDING_SDK_CONNECT_WAIT_MS; it continues in the background + * and a failure stays a health-indicator matter, as before. */ -function startPlatformSdkForFunding(): void { +async function preparePlatformForFunding(): Promise { // Mock-mode flows must not touch the network. - if (isE2EMockMode()) return; - void warmPlatformSdkForFunding(state.network).then((attempted) => { + if (isE2EMockMode()) { + await loadE2EMockPlatform(); + return; + } + await loadPlatformForFunding(); + const connect = warmPlatformSdkForFunding(state.network).then((attempted) => { if (attempted) pollNetworkStatusNow?.(); }); + await Promise.race([connect, delay(FUNDING_SDK_CONNECT_WAIT_MS)]); } // ── Network-status polling ────────────────────────────────────────────────── @@ -516,6 +534,45 @@ function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +/** + * Failure injection for mock-mode e2e tests, set with page.addInitScript: + * `sdkLoadFailures` failed SDK chunk loads before the gate's loader succeeds + * (3 or more exhausts its retries), `submissionFailures` failed Platform + * submissions after the InstantSend lock arrived. + */ +interface E2EMockFailures { + sdkLoadFailures?: number; + submissionFailures?: number; +} + +function e2eMockFailures(): E2EMockFailures { + const w = window as typeof window & { __e2eMockFailures?: E2EMockFailures }; + w.__e2eMockFailures ??= {}; + return w.__e2eMockFailures; +} + +const mockImportFailure = () => new TypeError('Importing a module script failed.'); + +// The real retrying loader around a fake import, so the e2e suite exercises +// its retries and error. +const loadE2EMockPlatform = createChunkLoader('evo-sdk', null, async () => { + const failures = e2eMockFailures(); + if ((failures.sdkLoadFailures ?? 0) > 0) { + failures.sdkLoadFailures! -= 1; + throw mockImportFailure(); + } + return {}; +}); + +async function runE2EMockSubmission(): Promise { + await delay(120); + const failures = e2eMockFailures(); + if ((failures.submissionFailures ?? 0) > 0) { + failures.submissionFailures! -= 1; + throw new ChunkLoadError('evo-sdk', 3, mockImportFailure()); + } +} + function createE2EMockUtxo(): UTXO { return { txid: 'a'.repeat(64), @@ -1126,15 +1183,21 @@ function setupEventListeners(container: HTMLElement) { }); } - // Retry registration (offered on the error screen when an identity - // registration was submitted but could not be confirmed) + // Retry the Platform submission with the lock already received (offered on + // the error screen when the submission failed after the lock arrived) const retryRegistrationBtn = container.querySelector('#retry-registration-btn'); if (retryRegistrationBtn) { retryRegistrationBtn.addEventListener('click', () => { - void retryIdentityRegistration(); + void retryPlatformSubmission(); }); } + // Reload (offered when a required chunk failed to load before any deposit + // address was shown, so nothing is lost by reloading) + container.querySelector('#reload-page-btn')?.addEventListener('click', () => { + window.location.reload(); + }); + // Chainlock fallback button (offered on the error screen when applicable) const chainlockFallbackBtn = container.querySelector('#chainlock-fallback-btn'); if (chainlockFallbackBtn) { @@ -2714,6 +2777,7 @@ async function startTopUp() { updateState(setStep(state, 'generating_keys')); await delay(120); + await preparePlatformForFunding(); updateState(setOneTimeKeyPair(state, assetLockKeyPair, depositAddress)); updateState(setStep(state, 'detecting_deposit')); clearE2EMockAdvanceHook(); @@ -2731,14 +2795,14 @@ async function startTopUp() { outputIndex: 0, })); updateState(setStep(state, 'topping_up')); - await delay(120); + await runE2EMockSubmission(); updateState(setTopUpComplete(state)); return; } updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2863,7 +2927,7 @@ async function startSendToAddress() { try { updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2970,14 +3034,15 @@ async function startSendToAddress() { } /** - * Resubmit identity registration with the asset lock proof already in - * state. Offered on the error screen after an unconfirmed submission: the - * asset lock can only be consumed once and the identity ID is - * deterministic, so resubmitting can't create a second identity. + * Resubmit the Platform operation (registration, top-up or send) with the + * asset lock proof already in state. Offered on the error screen when the + * submission failed after the lock arrived: the asset lock can only be + * consumed once and the identity ID is deterministic, so resubmitting can't + * spend the deposit twice or create a second identity. */ -async function retryIdentityRegistration(): Promise { +async function retryPlatformSubmission(): Promise { if (!state.assetLockProof || !state.assetLockKeyPair) { - console.error('Retry registration unavailable: missing asset lock proof or key'); + console.error('Retry submission unavailable: missing asset lock proof or key'); return; } try { @@ -2987,7 +3052,7 @@ async function retryIdentityRegistration(): Promise { ); await runPlatformSubmission(state.assetLockProof, assetLockPrivateKeyWif); } catch (error) { - console.error('Retry registration error:', error); + console.error('Retry submission error:', error); updateState(setError(state, toError(error))); } } @@ -3005,6 +3070,7 @@ async function startBridge() { clearE2EMockAdvanceHook(); updateState(setStep(state, 'generating_keys')); await delay(120); + await preparePlatformForFunding(); updateState(setKeyPairs(state, assetLockKeyPair, depositAddress)); updateState(setStep(state, 'detecting_deposit')); await waitForE2EMockAdvance(); @@ -3020,7 +3086,7 @@ async function startBridge() { instantLockBytes: new Uint8Array([5, 6, 7, 8]), outputIndex: 0, })); - await delay(120); + await runE2EMockSubmission(); updateState(setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); return; } @@ -3035,7 +3101,7 @@ async function startBridge() { // Step 1: Derive asset lock key from mnemonic (identity keys are pre-configured in state) updateState(setStep(state, 'generating_keys')); await ensureClients(); - startPlatformSdkForFunding(); + await preparePlatformForFunding(); const islock = islockService!; const { privateKey, publicKey } = deriveAssetLockKeyPair(state.mnemonic, state.network); @@ -3316,6 +3382,13 @@ async function runPlatformSubmission( assetLockProof: AssetLockProofData, assetLockPrivateKeyWif: string ): Promise { + if (isE2EMockMode()) { + updateState(setStep(state, state.mode === 'topup' ? 'topping_up' : 'registering_identity')); + await runE2EMockSubmission(); + updateState(state.mode === 'topup' ? setTopUpComplete(state) : setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); + return; + } + if (state.mode === 'topup') { updateState(setStep(state, 'topping_up')); const { topUpIdentity } = await loadPlatformModule(); diff --git a/src/ui/components.error-recovery.test.ts b/src/ui/components.error-recovery.test.ts new file mode 100644 index 0000000..228e633 --- /dev/null +++ b/src/ui/components.error-recovery.test.ts @@ -0,0 +1,81 @@ +// @vitest-environment happy-dom +import { describe, it, expect, vi } from 'vitest'; + +// QR rendering needs a canvas, which happy-dom does not provide. +vi.mock('./qrcode.js', () => ({ + generateQRCodeDataUrl: () => new Promise(() => {}), +})); + +import { render } from './components.js'; +import { createInitialState, setError } from './state.js'; +import type { BridgeState } from '../types.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; + +const importFailure = () => new ChunkLoadError('evo-sdk', 3, new TypeError('Importing a module script failed.')); + +function renderError(state: BridgeState, error: Error): HTMLElement { + const container = document.createElement('div'); + render(setError(state, error), container); + return container; +} + +const lockReceived: BridgeState = { + ...createInitialState('testnet'), + step: 'registering_identity', + depositAddress: 'yAddr', + txid: 'ab'.repeat(32), + signedTxBytes: new Uint8Array([0]), + assetLockKeyPair: { privateKey: new Uint8Array(32), publicKey: new Uint8Array(33) }, + assetLockProof: { type: 'instant', transactionBytes: new Uint8Array([1]), instantLockBytes: new Uint8Array([2]), outputIndex: 0 }, +}; + +describe('error screen recovery copy', () => { + it('after the lock arrived: says so, offers Retry Registration and the chain lock proof, names the failed chunk', () => { + const el = renderError(lockReceived, importFailure()); + const text = el.textContent ?? ''; + expect(text).toContain('Identity registration failed'); + expect(text).not.toContain("InstantSend didn't go through"); + expect(text).toContain('the InstantSend lock arrived'); + expect(text).toContain('could not load the "evo-sdk" component'); + expect(el.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Registration'); + expect(el.querySelector('#chainlock-fallback-btn')).not.toBeNull(); + expect(el.querySelector('#reload-page-btn')).toBeNull(); + expect(el.querySelector('.error-technical-content')?.textContent).toContain('Failed to load: evo-sdk'); + }); + + it('labels the retry for top-up', () => { + const el = renderError({ ...lockReceived, mode: 'topup', step: 'topping_up' }, new Error('platform reject')); + expect(el.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Top-up'); + expect(el.textContent).toContain('the Platform step failed'); + }); + + it('still says InstantSend did not go through when the lock never arrived', () => { + const el = renderError( + { ...lockReceived, step: 'waiting_islock', assetLockProof: undefined }, + new Error('Timed out waiting for InstantSend lock') + ); + expect(el.textContent).toContain("InstantSend didn't go through"); + expect(el.querySelector('#retry-registration-btn')).toBeNull(); + }); + + it('before the deposit address: explains the failed component and offers Reload, no funding UI', () => { + const el = renderError({ ...createInitialState('testnet'), step: 'generating_keys' }, importFailure()); + const text = el.textContent ?? ''; + expect(text).toContain('ERR-1017'); + expect(text).toContain('The page failed to load a required component "evo-sdk"'); + expect(text).toContain('No funds have been sent'); + expect(el.querySelector('#reload-page-btn')?.textContent).toBe('Reload'); + expect(el.querySelector('#retry-registration-btn')).toBeNull(); + expect(el.querySelector('#chainlock-fallback-btn')).toBeNull(); + expect(el.querySelector('#download-keys-btn')).toBeNull(); + }); +}); + +describe('funding gate screen', () => { + it('shows Preparing… (not a blank page) while the Platform components load', () => { + const container = document.createElement('div'); + render({ ...createInitialState('testnet'), step: 'generating_keys' }, container); + expect(container.querySelector('.preparing-step')?.textContent).toContain('Preparing…'); + expect(container.querySelector('.address')).toBeNull(); + }); +}); diff --git a/src/ui/components.ts b/src/ui/components.ts index 28db465..91ef74f 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -1,6 +1,6 @@ import type { BridgeState, KeyType, KeyPurpose, SecurityLevel, NetworkHealth, NetworkStatus, EmbedNotice, NearIntentsState, NearIntentsSwap } from '../types.js'; import { canCancel } from '../embed/bridge.js'; -import { getStepProgress, getStepDescription, ErrorCodes, ErrorCodeLabels } from './state.js'; +import { getStepProgress, getStepDescription, getErrorRecovery, ErrorCodes, ErrorCodeLabels } from './state.js'; import { formatUnits, formatUnitsShort, @@ -274,6 +274,10 @@ export function render(state: BridgeState, container: HTMLElement): void { content.appendChild(renderEnterRecipientAddressStep(state)); break; + case 'generating_keys': + content.appendChild(renderPreparingStep()); + break; + case 'awaiting_deposit': case 'detecting_deposit': content.appendChild(renderDepositStep(state)); @@ -1557,6 +1561,21 @@ function renderNearSwap(swap: NearIntentsSwap): HTMLElement { return el; } +/** + * Shown while a funding flow loads the Platform components it needs before + * showing a deposit address (the SDK is several MB, slow on mobile networks). + */ +function renderPreparingStep(): HTMLElement { + const div = document.createElement('div'); + div.className = 'processing-step preparing-step'; + div.innerHTML = ` +

Preparing…

+

Loading the Dash Platform components needed to finish. Your deposit address appears next.

+
+ `; + return div; +} + function renderProcessingStep(state: BridgeState): HTMLElement { const div = document.createElement('div'); div.className = 'processing-step'; @@ -1794,6 +1813,8 @@ function buildErrorDiagnostics(state: BridgeState): Record { mode: state.mode, timestamp: new Date().toISOString(), }; + const { failedChunk } = getErrorRecovery(state); + if (failedChunk) diag.failedChunk = failedChunk; // Transaction context — critical for tracking on-chain state // NOTE: signedTxHex is intentionally excluded — if the error occurred before @@ -1880,6 +1901,7 @@ function renderErrorStep(state: BridgeState): HTMLElement { // Build a concise technical summary from the diagnostic object const techLines: string[] = []; if (diag.errorStep) techLines.push(`Step: ${diag.errorStep}`); + if (diag.failedChunk) techLines.push(`Failed to load: ${diag.failedChunk}`); if (diag.depositAddress) techLines.push(`Deposit: ${diag.depositAddress}`); if (diag.txid) techLines.push(`TxID: ${diag.txid}`); if (diag.identityId) techLines.push(`Identity: ${diag.identityId}`); @@ -1895,29 +1917,52 @@ function renderErrorStep(state: BridgeState): HTMLElement { ` : ''; + const recovery = getErrorRecovery(state); + const chunkName = recovery.failedChunk ? `"${recovery.failedChunk}" ` : ''; + + // Failed while preparing, before any deposit address: nothing is at risk. + const reloadHtml = recovery.reloadSafe + ? ` +
+

The page failed to load a required component ${escapeHtml(chunkName)}(most likely a network interruption). No funds have been sent. Reload the page to try again.

+ +
+ ` + : ''; + + const chainlockFallbackHint = recovery.lockReceived + ? 'If Platform keeps rejecting the InstantSend proof, you can wait for a chain lock and submit a chain-based proof instead.' + : state.errorCode === ErrorCodes.ISLOCK + ? "InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead." + : 'You can wait for a chain lock and try again with a chain-based proof instead.'; const chainlockFallbackHtml = state.chainlockFallbackAvailable ? `
-

InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead.

+

${escapeHtml(chainlockFallbackHint)}

` : ''; - // An identity registration that was submitted but not confirmed can be - // resubmitted safely with the same asset lock proof. - const retryRegistrationHtml = - state.mode === 'create' && - isIdentityRegistrationUnconfirmedError(state.error) && - state.assetLockProof && - state.assetLockKeyPair - ? ` + // The asset lock can be consumed only once and the identity ID is derived + // from it, so resubmitting the proof in state cannot spend the deposit twice. + const retryLabel = + state.mode === 'topup' ? 'Retry Top-up' : state.mode === 'send_to_address' ? 'Retry Send' : 'Retry Registration'; + const retryHint = isIdentityRegistrationUnconfirmedError(state.error) + ? 'Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.' + : recovery.lockReceived && recovery.failedChunk + ? `Your deposit is safe: the InstantSend lock arrived, but the page could not load the ${chunkName}component needed to submit it to Platform (most likely a network interruption). Retry once you are back online — it reuses the same lock and cannot spend your deposit twice.` + : recovery.lockReceived + ? 'Your deposit is safe: the InstantSend lock arrived, but the Platform step failed. Retrying reuses the same lock and cannot spend your deposit twice.' + : 'Retrying reuses the same asset lock proof and cannot spend your deposit twice.'; + const retryRegistrationHtml = recovery.canRetrySubmission + ? `
-

Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.

- +

${escapeHtml(retryHint)}

+
` - : ''; + : ''; // Once an asset lock key exists, funds may be in flight: keep the // recovery backup one click away on every error screen. @@ -1938,6 +1983,7 @@ function renderErrorStep(state: BridgeState): HTMLElement { ${failedStepHtml}

${escapeHtml(errorMessage)}

${techDetailsHtml} + ${reloadHtml} ${retryRegistrationHtml} ${chainlockFallbackHtml} ${keyBackupHtml} diff --git a/src/ui/state.error-recovery.test.ts b/src/ui/state.error-recovery.test.ts new file mode 100644 index 0000000..6c46538 --- /dev/null +++ b/src/ui/state.error-recovery.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect } from 'vitest'; + +import { ErrorCodes, createInitialState, getErrorRecovery, setError } from './state.js'; +import type { AssetLockProofData, BridgeState } from '../types.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; +import { + AssetLockConsumedElsewhereError, + IdentityRegistrationUnconfirmedError, +} from '../platform/identity-confirm.js'; + +const importFailure = () => new ChunkLoadError('evo-sdk', 3, new TypeError('Importing a module script failed.')); + +const instantProof: AssetLockProofData = { + type: 'instant', + transactionBytes: new Uint8Array([1]), + instantLockBytes: new Uint8Array([2]), + outputIndex: 0, +}; + +/** Create flow right after the InstantSend lock arrived (as setInstantLockReceived leaves it). */ +function lockReceived(overrides: Partial = {}): BridgeState { + return { + ...createInitialState('testnet'), + step: 'registering_identity', + depositAddress: 'yAddr', + txid: 'ab'.repeat(32), + signedTxBytes: new Uint8Array([0]), + assetLockKeyPair: { privateKey: new Uint8Array(32), publicKey: new Uint8Array(33) }, + instantLockBytes: new Uint8Array([2]), + assetLockProof: instantProof, + ...overrides, + }; +} + +describe('getErrorRecovery after the InstantSend lock arrived', () => { + it('reports the lock as received and offers both a retry and the chain lock proof when the SDK chunk failed', () => { + const errored = setError(lockReceived(), importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.REGISTER); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toEqual({ + lockReceived: true, + canRetrySubmission: true, + reloadSafe: false, + failedChunk: 'evo-sdk', + }); + }); + + it('offers a retry for every funding mode (top-up, send to address) with the proof in state', () => { + for (const [mode, step, code] of [ + ['topup', 'topping_up', ErrorCodes.TOPUP], + ['send_to_address', 'sending_to_address', ErrorCodes.SEND_ADDRESS], + ] as const) { + const errored = setError(lockReceived({ mode, step }), new Error('platform reject')); + expect(errored.errorCode).toBe(code); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: true, canRetrySubmission: true }); + } + }); + + it('keeps offering a retry for an unconfirmed registration', () => { + const errored = setError(lockReceived(), new IdentityRegistrationUnconfirmedError('someId')); + expect(getErrorRecovery(errored).canRetrySubmission).toBe(true); + expect(errored.chainlockFallbackAvailable).toBe(false); + }); + + it('offers no retry once the asset lock was consumed elsewhere', () => { + const errored = setError(lockReceived(), new AssetLockConsumedElsewhereError('someId')); + expect(getErrorRecovery(errored).canRetrySubmission).toBe(false); + }); + + it('offers no retry without the proof or the asset lock key', () => { + expect(getErrorRecovery(setError(lockReceived({ assetLockProof: undefined }), importFailure()))) + .toMatchObject({ lockReceived: false, canRetrySubmission: false }); + expect(getErrorRecovery(setError(lockReceived({ assetLockKeyPair: undefined }), importFailure()))) + .toMatchObject({ lockReceived: true, canRetrySubmission: false }); + }); + + it('does not call a chain proof an InstantSend lock', () => { + const chainProof: AssetLockProofData = { type: 'chain', coreChainLockedHeight: 10, txid: 'ab'.repeat(32), vout: 0 }; + const errored = setError(lockReceived({ assetLockProof: chainProof }), new Error('platform reject')); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: false, canRetrySubmission: true }); + }); +}); + +describe('getErrorRecovery for a missing InstantSend lock', () => { + it('is not a received lock and has nothing to retry', () => { + const waiting: BridgeState = { ...lockReceived(), step: 'waiting_islock', assetLockProof: undefined, instantLockBytes: undefined }; + const errored = setError(waiting, new Error('timeout')); + expect(errored.errorCode).toBe(ErrorCodes.ISLOCK); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: false, canRetrySubmission: false, reloadSafe: false }); + }); +}); + +describe('component load failure while preparing a funding flow', () => { + it('gets its own code and is safe to reload before any deposit address exists', () => { + const preparing: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys' }; + const errored = setError(preparing, importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.COMPONENT_LOAD); + expect(errored.chainlockFallbackAvailable).toBe(false); + expect(getErrorRecovery(errored)).toEqual({ + lockReceived: false, + canRetrySubmission: false, + reloadSafe: true, + failedChunk: 'evo-sdk', + }); + }); + + it('keeps the key generation code for other errors in that step', () => { + const preparing: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys' }; + expect(setError(preparing, new Error('boom')).errorCode).toBe(ErrorCodes.KEY_GEN); + }); + + it('is never "safe to reload" once a deposit address was shown', () => { + const shown: BridgeState = { ...createInitialState('testnet'), step: 'generating_keys', depositAddress: 'yAddr' }; + const errored = setError(shown, importFailure()); + expect(errored.errorCode).toBe(ErrorCodes.KEY_GEN); + expect(getErrorRecovery(errored).reloadSafe).toBe(false); + }); +}); diff --git a/src/ui/state.ts b/src/ui/state.ts index 082b1d1..af00578 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -38,6 +38,7 @@ import { isIdentityRegistrationUnconfirmedError, type IdentityRegistrationUnconfirmedError, } from '../platform/identity-confirm.js'; +import { isChunkLoadError } from '../platform/chunk-loader.js'; import { shouldRecommendMobileApp } from './mobile-app.js'; /** @@ -63,6 +64,7 @@ export const ErrorCodes = { CHAINLOCK: 'ERR-1014', WITHDRAW: 'ERR-1015', USERNAME_TRANSFER: 'ERR-1016', + COMPONENT_LOAD: 'ERR-1017', } as const; /** Human-readable labels for error codes */ @@ -84,6 +86,7 @@ export const ErrorCodeLabels: Record = { [ErrorCodes.CHAINLOCK]: 'Chain lock fallback failed', [ErrorCodes.WITHDRAW]: 'Credit withdrawal failed', [ErrorCodes.USERNAME_TRANSFER]: 'Username transfer failed', + [ErrorCodes.COMPONENT_LOAD]: 'A required component failed to load', }; /** Map a processing step to its error code */ @@ -596,8 +599,58 @@ function computeChainlockFallbackAvailable( return false; } +/** Error codes of the Platform submission that spends the asset lock. */ +const SUBMISSION_ERROR_CODES: readonly string[] = [ + ErrorCodes.REGISTER, + ErrorCodes.TOPUP, + ErrorCodes.SEND_ADDRESS, +]; + +/** + * A chunk that failed while a funding flow was still preparing (before its + * deposit address) gets its own code: nothing is at risk and reloading is safe. + */ +function resolveErrorCode(state: BridgeState, error: Error): string { + if (isChunkLoadError(error) && state.step === 'generating_keys' && !state.depositAddress) { + return ErrorCodes.COMPONENT_LOAD; + } + return StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; +} + +export interface ErrorRecovery { + /** + * The Platform submission failed while the InstantSend lock had arrived + * (its proof is in state): the error screen must not claim InstantSend failed. + */ + lockReceived: boolean; + /** The submission can be resubmitted with the asset lock proof in state. */ + canRetrySubmission: boolean; + /** Failed before any deposit address was shown, so reloading the page is safe. */ + reloadSafe: boolean; + /** Name of the lazily loaded chunk that could not be downloaded, if that was the cause. */ + failedChunk?: string; +} + +/** What the error screen can offer for the current error. */ +export function getErrorRecovery(state: BridgeState): ErrorRecovery { + const submissionFailed = SUBMISSION_ERROR_CODES.includes(state.errorCode ?? ''); + return { + lockReceived: submissionFailed && state.assetLockProof?.type === 'instant', + // Resubmitting is safe: the asset lock can be consumed only once and the + // identity ID is derived from it. Once Platform has consumed it elsewhere + // there is nothing left to retry. + canRetrySubmission: + submissionFailed && + !!state.assetLockProof && + !!state.assetLockKeyPair && + !isAssetLockConsumedElsewhereError(state.error), + reloadSafe: state.errorCode === ErrorCodes.COMPONENT_LOAD && !state.depositAddress && !state.txid, + failedChunk: isChunkLoadError(state.error) ? state.error.chunk : undefined, + }; +} + export function setError(state: BridgeState, error: Error, errorCode?: string): BridgeState { - const resolvedCode = errorCode ?? StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; + const resolvedCode = errorCode ?? resolveErrorCode(state, error); const unconfirmed = isIdentityRegistrationUnconfirmedError(error); return { ...state, @@ -606,10 +659,8 @@ export function setError(state: BridgeState, error: Error, errorCode?: string): errorCode: resolvedCode, errorStep: state.step, // Both errors mean the deposit's asset lock already reached Platform, so - // a chain-lock proof for the same asset lock can't change the outcome - // (and the fallback's "InstantSend didn't go through" hint would be - // wrong). Unconfirmed → Retry Registration; consumed elsewhere → nothing - // to retry. + // a chain-lock proof for the same asset lock can't change the outcome. + // Unconfirmed → Retry Registration; consumed elsewhere → nothing to retry. chainlockFallbackAvailable: !unconfirmed && !isAssetLockConsumedElsewhereError(error) && From 748ddf86bc88ebd58d52651d2dc4f33464b03cc3 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 21:18:06 -0500 Subject: [PATCH 3/5] refactor(bridge): simplify the chunk loader and error recovery copy No behaviour change. - Chunk loader: one retry loop without a lastError/offset dance, the retry delays private, CHUNK_LOAD_ATTEMPTS exported for the e2e mock, instanceof instead of an isChunkLoadError wrapper. - Error screen: the hint and label choices move into small functions instead of nested ternaries. - Mock failure injection: one consume helper; the e2e helpers live at file scope. Co-Authored-By: Claude Sonnet 5.5 --- e2e/deterministic.spec.ts | 40 ++++++++++-------- src/config/vite-chunk-url.ts | 4 +- src/main.ts | 52 +++++++++++------------ src/platform/chunk-loader.test.ts | 3 +- src/platform/chunk-loader.ts | 28 +++++-------- src/platform/loaders.ts | 11 ++--- src/ui/components.ts | 70 ++++++++++++++++++++----------- src/ui/state.ts | 19 +++++---- 8 files changed, 122 insertions(+), 105 deletions(-) diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index bd358c6..885f057 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test, type Page } from '@playwright/test'; import { bech32m } from '@scure/base'; import { E2E_MOCK_DPNS_WIF, @@ -12,6 +12,21 @@ import { const MOCK_QUERY = '/?network=testnet&e2e=mock'; +/** Failure injection read by the mock flows (E2EMockFailures in src/main.ts). */ +function injectMockFailures(page: Page, failures: { sdkLoadFailures?: number; submissionFailures?: number }) { + return page.addInitScript((f) => { + (window as { __e2eMockFailures?: typeof f }).__e2eMockFailures = f; + }, failures); +} + +/** Pretend the deposit arrived (the mock flows wait for this hook). */ +async function advanceMockDeposit(page: Page) { + await expect.poll(async () => { + return page.evaluate(() => typeof (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance); + }).toBe('function'); + await page.evaluate(() => (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance?.()); +} + test.describe('Deterministic UI E2E (mock mode)', () => { test('testnet discovers evonodes from the quorum service, never calls digitalcash.dev and does not load the SDK for the health poll', async ({ page }) => { const digitalcashRequests: string[] = []; @@ -88,23 +103,12 @@ test.describe('Deterministic UI E2E (mock mode)', () => { }); test.describe('Platform component gate before funding', () => { - const injectFailures = (page: import('@playwright/test').Page, failures: Record) => - page.addInitScript((f) => { - (window as { __e2eMockFailures?: Record }).__e2eMockFailures = f; - }, failures); - const advance = async (page: import('@playwright/test').Page) => { - await expect.poll(async () => { - return page.evaluate(() => typeof (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance); - }).toBe('function'); - await page.evaluate(() => (window as { __e2eMockAdvance?: () => void }).__e2eMockAdvance?.()); - }; - test('a dropped SDK download is retried and the flow reaches the deposit address', async ({ page }) => { const warnings: string[] = []; page.on('console', (msg) => { if (msg.type() === 'warning') warnings.push(msg.text()); }); - await injectFailures(page, { sdkLoadFailures: 2 }); + await injectMockFailures(page, { sdkLoadFailures: 2 }); await page.goto(MOCK_QUERY); await page.click('#mode-create-btn'); await page.click('#continue-btn'); @@ -117,7 +121,7 @@ test.describe('Deterministic UI E2E (mock mode)', () => { for (const flow of ['create', 'topup'] as const) { test(`${flow}: an SDK that cannot load stops the flow before any deposit address, with Reload`, async ({ page }) => { - await injectFailures(page, { sdkLoadFailures: 3 }); + await injectMockFailures(page, { sdkLoadFailures: 3 }); await page.goto(MOCK_QUERY); if (flow === 'create') { await page.click('#mode-create-btn'); @@ -144,12 +148,12 @@ test.describe('Deterministic UI E2E (mock mode)', () => { } test('registration failing after the lock arrived says so, and Retry Registration completes it', async ({ page }) => { - await injectFailures(page, { submissionFailures: 1 }); + await injectMockFailures(page, { submissionFailures: 1 }); await page.goto(MOCK_QUERY); await page.click('#mode-create-btn'); await page.click('#continue-btn'); await expect(page.locator('.deposit-headline')).toBeVisible(); - await advance(page); + await advanceMockDeposit(page); const errorStep = page.locator('.error-step'); await expect(page.locator('.error-code-badge')).toHaveText('ERR-1006'); @@ -163,14 +167,14 @@ test.describe('Deterministic UI E2E (mock mode)', () => { }); test('top-up failing after the lock arrived offers Retry Top-up, which completes it', async ({ page }) => { - await injectFailures(page, { submissionFailures: 1 }); + await injectMockFailures(page, { submissionFailures: 1 }); await page.goto(MOCK_QUERY); await page.click('#mode-manage-btn'); await page.click('#manage-action-topup-btn'); await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); await page.click('#continue-topup-btn'); await expect(page.locator('.deposit-headline')).toBeVisible(); - await advance(page); + await advanceMockDeposit(page); await expect(page.locator('.error-code-badge')).toHaveText('ERR-1007'); await expect(page.locator('#retry-registration-btn')).toHaveText('Retry Top-up'); diff --git a/src/config/vite-chunk-url.ts b/src/config/vite-chunk-url.ts index ae5974f..3ead7b7 100644 --- a/src/config/vite-chunk-url.ts +++ b/src/config/vite-chunk-url.ts @@ -16,8 +16,8 @@ import type { Plugin } from 'vite'; * module that is statically imported elsewhere would be split out of the * chunk it lives in now. */ -export const CHUNK_URL_PREFIX = 'virtual:chunk-url:'; -const RESOLVED_PREFIX = '\0virtual:chunk-url:'; +const CHUNK_URL_PREFIX = 'virtual:chunk-url:'; +const RESOLVED_PREFIX = '\0' + CHUNK_URL_PREFIX; // The dev server and vitest serve modules unbundled: there is no chunk to // name. One id for all, which also keeps target paths out of dev request URLs. const RESOLVED_DEV_ID = '\0virtual:chunk-url-dev'; diff --git a/src/main.ts b/src/main.ts index 9bb5488..733950d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -212,7 +212,7 @@ import { warmDashModules, warmPlatformSdkForFunding, } from './platform/loaders.js'; -import { ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; +import { CHUNK_LOAD_ATTEMPTS, ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; import { deriveCandidateKeys, explainKeyIneligibility, @@ -361,7 +361,7 @@ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; async function preparePlatformForFunding(): Promise { // Mock-mode flows must not touch the network. if (isE2EMockMode()) { - await loadE2EMockPlatform(); + await loadE2EMockSdk(); return; } await loadPlatformForFunding(); @@ -535,41 +535,41 @@ function delay(ms: number): Promise { } /** - * Failure injection for mock-mode e2e tests, set with page.addInitScript: - * `sdkLoadFailures` failed SDK chunk loads before the gate's loader succeeds - * (3 or more exhausts its retries), `submissionFailures` failed Platform - * submissions after the InstantSend lock arrived. + * Failure injection for mock-mode e2e tests, set with page.addInitScript as + * window.__e2eMockFailures: `sdkLoadFailures` failed SDK chunk loads before + * the gate's loader succeeds (CHUNK_LOAD_ATTEMPTS or more exhausts its + * retries), `submissionFailures` failed Platform submissions after the + * InstantSend lock arrived. */ interface E2EMockFailures { sdkLoadFailures?: number; submissionFailures?: number; } -function e2eMockFailures(): E2EMockFailures { - const w = window as typeof window & { __e2eMockFailures?: E2EMockFailures }; - w.__e2eMockFailures ??= {}; - return w.__e2eMockFailures; +/** Use up one injected failure of this kind; true if there was one left. */ +function consumeE2EMockFailure(kind: keyof E2EMockFailures): boolean { + const failures = (window as typeof window & { __e2eMockFailures?: E2EMockFailures }).__e2eMockFailures; + const remaining = failures?.[kind] ?? 0; + if (!failures || remaining <= 0) return false; + failures[kind] = remaining - 1; + return true; } -const mockImportFailure = () => new TypeError('Importing a module script failed.'); +function mockImportFailure(): TypeError { + return new TypeError('Importing a module script failed.'); +} -// The real retrying loader around a fake import, so the e2e suite exercises -// its retries and error. -const loadE2EMockPlatform = createChunkLoader('evo-sdk', null, async () => { - const failures = e2eMockFailures(); - if ((failures.sdkLoadFailures ?? 0) > 0) { - failures.sdkLoadFailures! -= 1; - throw mockImportFailure(); - } +// The real retrying loader around a fake SDK import, so the e2e suite +// exercises its retries and error. +const loadE2EMockSdk = createChunkLoader('evo-sdk', null, async () => { + if (consumeE2EMockFailure('sdkLoadFailures')) throw mockImportFailure(); return {}; }); async function runE2EMockSubmission(): Promise { await delay(120); - const failures = e2eMockFailures(); - if ((failures.submissionFailures ?? 0) > 0) { - failures.submissionFailures! -= 1; - throw new ChunkLoadError('evo-sdk', 3, mockImportFailure()); + if (consumeE2EMockFailure('submissionFailures')) { + throw new ChunkLoadError('evo-sdk', CHUNK_LOAD_ATTEMPTS, mockImportFailure()); } } @@ -1185,9 +1185,9 @@ function setupEventListeners(container: HTMLElement) { // Retry the Platform submission with the lock already received (offered on // the error screen when the submission failed after the lock arrived) - const retryRegistrationBtn = container.querySelector('#retry-registration-btn'); - if (retryRegistrationBtn) { - retryRegistrationBtn.addEventListener('click', () => { + const retrySubmissionBtn = container.querySelector('#retry-registration-btn'); + if (retrySubmissionBtn) { + retrySubmissionBtn.addEventListener('click', () => { void retryPlatformSubmission(); }); } diff --git a/src/platform/chunk-loader.test.ts b/src/platform/chunk-loader.test.ts index 3098313..ea19b89 100644 --- a/src/platform/chunk-loader.test.ts +++ b/src/platform/chunk-loader.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ChunkLoadError, cacheBustedUrl, createChunkLoader, isChunkLoadError } from './chunk-loader.js'; +import { ChunkLoadError, cacheBustedUrl, createChunkLoader } from './chunk-loader.js'; const noSleep = { sleep: async () => {} }; @@ -77,7 +77,6 @@ describe('createChunkLoader', () => { }, noSleep); const error = await loader().catch((e: unknown) => e); - expect(isChunkLoadError(error)).toBe(true); expect(error).toBeInstanceOf(ChunkLoadError); expect((error as ChunkLoadError).chunk).toBe('evo-sdk'); expect((error as ChunkLoadError).attempts).toBe(3); diff --git a/src/platform/chunk-loader.ts b/src/platform/chunk-loader.ts index 0581762..c3bdd69 100644 --- a/src/platform/chunk-loader.ts +++ b/src/platform/chunk-loader.ts @@ -24,19 +24,16 @@ export class ChunkLoadError extends Error { } } -export function isChunkLoadError(error: unknown): error is ChunkLoadError { - return error instanceof ChunkLoadError; -} - -export interface ChunkLoaderOptions { - /** Delay before each retry; its length + 1 is the attempt count. */ - retryDelaysMs?: readonly number[]; +interface ChunkLoaderOptions { + /** Overridable for tests. */ sleep?: (ms: number) => Promise; /** Imports a URL (overridable for tests). */ importUrl?: (url: string) => Promise; } -export const CHUNK_RETRY_DELAYS_MS = [500, 1500] as const; +/** Delay before each retry. */ +const RETRY_DELAYS_MS = [500, 1500] as const; +export const CHUNK_LOAD_ATTEMPTS = RETRY_DELAYS_MS.length + 1; const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const defaultImportUrl = (url: string) => import(/* @vite-ignore */ url); @@ -66,25 +63,22 @@ export function createChunkLoader( load: () => Promise, options: ChunkLoaderOptions = {} ): () => Promise { - const retryDelays = options.retryDelaysMs ?? CHUNK_RETRY_DELAYS_MS; const sleep = options.sleep ?? defaultSleep; const importUrl = options.importUrl ?? defaultImportUrl; - const attempts = retryDelays.length + 1; const loadWithRetries = async (): Promise => { - let lastError: unknown; - for (let attempt = 0; attempt < attempts; attempt++) { - if (attempt > 0) await sleep(retryDelays[attempt - 1]); + for (let attempt = 0; ; attempt++) { try { if (attempt === 0 || !chunkUrl) return await load(); return (await importUrl(cacheBustedUrl(chunkUrl, attempt))) as T; } catch (error) { - lastError = error; - const next = attempt + 1 < attempts ? `; retrying in ${retryDelays[attempt]} ms` : ''; - console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${attempts})${next}:`, error); + const retryDelay: number | undefined = RETRY_DELAYS_MS[attempt]; + const retrying = retryDelay === undefined ? '' : `; retrying in ${retryDelay} ms`; + console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${CHUNK_LOAD_ATTEMPTS})${retrying}:`, error); + if (retryDelay === undefined) throw new ChunkLoadError(chunk, CHUNK_LOAD_ATTEMPTS, error); + await sleep(retryDelay); } } - throw new ChunkLoadError(chunk, attempts, lastError); }; let promise: Promise | null = null; diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index af2a4e5..bed6a06 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -39,14 +39,9 @@ export function warmDashModules(): Promise[]> { } /** - * Load everything a Platform submission needs (the EvoSDK chunk and the - * platform operations chunk) before a funding flow shows its deposit address. - * Once funds are committed the submission must not depend on a download, which - * can fail (e.g. iOS suspends a backgrounded tab's network while the user pays - * from a wallet app) and, once failed, is remembered by the browser. - * - * Every network: registration needs the SDK everywhere. Rejects with a - * ChunkLoadError when a chunk still fails after the loaders' retries. + * Load the chunks a Platform submission needs (EvoSDK and platform + * operations), for the funding gate in main.ts. Rejects with a ChunkLoadError + * when a chunk still fails after the loaders' retries. */ export async function loadPlatformForFunding(): Promise { await Promise.all([loadSdkModule(), loadPlatformModule()]); diff --git a/src/ui/components.ts b/src/ui/components.ts index 91ef74f..0878822 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -1,6 +1,6 @@ import type { BridgeState, KeyType, KeyPurpose, SecurityLevel, NetworkHealth, NetworkStatus, EmbedNotice, NearIntentsState, NearIntentsSwap } from '../types.js'; import { canCancel } from '../embed/bridge.js'; -import { getStepProgress, getStepDescription, getErrorRecovery, ErrorCodes, ErrorCodeLabels } from './state.js'; +import { getStepProgress, getStepDescription, getErrorRecovery, ErrorCodes, ErrorCodeLabels, type ErrorRecovery } from './state.js'; import { formatUnits, formatUnitsShort, @@ -1884,6 +1884,44 @@ function buildErrorDiagnostics(state: BridgeState): Record { return diag; } +/** ` "evo-sdk"` (leading space) when a chunk failed to load, else empty. */ +function chunkLabel(recovery: ErrorRecovery): string { + return recovery.failedChunk ? ` "${recovery.failedChunk}"` : ''; +} + +function chainlockFallbackHint(state: BridgeState, recovery: ErrorRecovery): string { + if (recovery.lockReceived) { + return 'If Platform keeps rejecting the InstantSend proof, you can wait for a chain lock and submit a chain-based proof instead.'; + } + if (state.errorCode === ErrorCodes.ISLOCK) { + return "InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead."; + } + return 'You can wait for a chain lock and try again with a chain-based proof instead.'; +} + +function retrySubmissionLabel(mode: BridgeState['mode']): string { + switch (mode) { + case 'topup': return 'Retry Top-up'; + case 'send_to_address': return 'Retry Send'; + default: return 'Retry Registration'; + } +} + +// The asset lock can be consumed only once and the identity ID is derived +// from it, so resubmitting the proof in state cannot spend the deposit twice. +function retrySubmissionHint(state: BridgeState, recovery: ErrorRecovery): string { + if (isIdentityRegistrationUnconfirmedError(state.error)) { + return 'Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.'; + } + if (recovery.lockReceived && recovery.failedChunk) { + return `Your deposit is safe: the InstantSend lock arrived, but the page could not load the${chunkLabel(recovery)} component needed to submit it to Platform (most likely a network interruption). Retry once you are back online — it reuses the same lock and cannot spend your deposit twice.`; + } + if (recovery.lockReceived) { + return 'Your deposit is safe: the InstantSend lock arrived, but the Platform step failed. Retrying reuses the same lock and cannot spend your deposit twice.'; + } + return 'Retrying reuses the same asset lock proof and cannot spend your deposit twice.'; +} + function renderErrorStep(state: BridgeState): HTMLElement { const div = document.createElement('div'); div.className = 'error-step'; @@ -1918,48 +1956,32 @@ function renderErrorStep(state: BridgeState): HTMLElement { ` : ''; const recovery = getErrorRecovery(state); - const chunkName = recovery.failedChunk ? `"${recovery.failedChunk}" ` : ''; // Failed while preparing, before any deposit address: nothing is at risk. const reloadHtml = recovery.reloadSafe ? `
-

The page failed to load a required component ${escapeHtml(chunkName)}(most likely a network interruption). No funds have been sent. Reload the page to try again.

+

The page failed to load a required component${escapeHtml(chunkLabel(recovery))} (most likely a network interruption). No funds have been sent. Reload the page to try again.

` : ''; - const chainlockFallbackHint = recovery.lockReceived - ? 'If Platform keeps rejecting the InstantSend proof, you can wait for a chain lock and submit a chain-based proof instead.' - : state.errorCode === ErrorCodes.ISLOCK - ? "InstantSend didn't go through. You can wait for a chain lock and try again with a chain-based proof instead." - : 'You can wait for a chain lock and try again with a chain-based proof instead.'; const chainlockFallbackHtml = state.chainlockFallbackAvailable ? `
-

${escapeHtml(chainlockFallbackHint)}

+

${escapeHtml(chainlockFallbackHint(state, recovery))}

` : ''; - // The asset lock can be consumed only once and the identity ID is derived - // from it, so resubmitting the proof in state cannot spend the deposit twice. - const retryLabel = - state.mode === 'topup' ? 'Retry Top-up' : state.mode === 'send_to_address' ? 'Retry Send' : 'Retry Registration'; - const retryHint = isIdentityRegistrationUnconfirmedError(state.error) - ? 'Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.' - : recovery.lockReceived && recovery.failedChunk - ? `Your deposit is safe: the InstantSend lock arrived, but the page could not load the ${chunkName}component needed to submit it to Platform (most likely a network interruption). Retry once you are back online — it reuses the same lock and cannot spend your deposit twice.` - : recovery.lockReceived - ? 'Your deposit is safe: the InstantSend lock arrived, but the Platform step failed. Retrying reuses the same lock and cannot spend your deposit twice.' - : 'Retrying reuses the same asset lock proof and cannot spend your deposit twice.'; - const retryRegistrationHtml = recovery.canRetrySubmission + // The DOM id predates top-up/send retries; kept for main.ts and the tests. + const retrySubmissionHtml = recovery.canRetrySubmission ? `
-

${escapeHtml(retryHint)}

- +

${escapeHtml(retrySubmissionHint(state, recovery))}

+
` : ''; @@ -1984,7 +2006,7 @@ function renderErrorStep(state: BridgeState): HTMLElement {

${escapeHtml(errorMessage)}

${techDetailsHtml} ${reloadHtml} - ${retryRegistrationHtml} + ${retrySubmissionHtml} ${chainlockFallbackHtml} ${keyBackupHtml}
diff --git a/src/ui/state.ts b/src/ui/state.ts index af00578..3c194ae 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -38,7 +38,7 @@ import { isIdentityRegistrationUnconfirmedError, type IdentityRegistrationUnconfirmedError, } from '../platform/identity-confirm.js'; -import { isChunkLoadError } from '../platform/chunk-loader.js'; +import { ChunkLoadError } from '../platform/chunk-loader.js'; import { shouldRecommendMobileApp } from './mobile-app.js'; /** @@ -600,18 +600,18 @@ function computeChainlockFallbackAvailable( } /** Error codes of the Platform submission that spends the asset lock. */ -const SUBMISSION_ERROR_CODES: readonly string[] = [ +const SUBMISSION_ERROR_CODES = new Set([ ErrorCodes.REGISTER, ErrorCodes.TOPUP, ErrorCodes.SEND_ADDRESS, -]; +]); /** * A chunk that failed while a funding flow was still preparing (before its * deposit address) gets its own code: nothing is at risk and reloading is safe. */ function resolveErrorCode(state: BridgeState, error: Error): string { - if (isChunkLoadError(error) && state.step === 'generating_keys' && !state.depositAddress) { + if (error instanceof ChunkLoadError && state.step === 'generating_keys' && !state.depositAddress) { return ErrorCodes.COMPONENT_LOAD; } return StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; @@ -633,7 +633,7 @@ export interface ErrorRecovery { /** What the error screen can offer for the current error. */ export function getErrorRecovery(state: BridgeState): ErrorRecovery { - const submissionFailed = SUBMISSION_ERROR_CODES.includes(state.errorCode ?? ''); + const submissionFailed = SUBMISSION_ERROR_CODES.has(state.errorCode); return { lockReceived: submissionFailed && state.assetLockProof?.type === 'instant', // Resubmitting is safe: the asset lock can be consumed only once and the @@ -644,8 +644,10 @@ export function getErrorRecovery(state: BridgeState): ErrorRecovery { !!state.assetLockProof && !!state.assetLockKeyPair && !isAssetLockConsumedElsewhereError(state.error), + // resolveErrorCode already implies no deposit address; re-checked because + // a wrong "safe to reload" could lose track of funds in flight. reloadSafe: state.errorCode === ErrorCodes.COMPONENT_LOAD && !state.depositAddress && !state.txid, - failedChunk: isChunkLoadError(state.error) ? state.error.chunk : undefined, + failedChunk: state.error instanceof ChunkLoadError ? state.error.chunk : undefined, }; } @@ -659,8 +661,9 @@ export function setError(state: BridgeState, error: Error, errorCode?: string): errorCode: resolvedCode, errorStep: state.step, // Both errors mean the deposit's asset lock already reached Platform, so - // a chain-lock proof for the same asset lock can't change the outcome. - // Unconfirmed → Retry Registration; consumed elsewhere → nothing to retry. + // a chain-lock proof for the same asset lock can't change the outcome + // (and offering it would suggest the lock was the problem). Unconfirmed → + // Retry Registration; consumed elsewhere → nothing to retry. chainlockFallbackAvailable: !unconfirmed && !isAssetLockConsumedElsewhereError(error) && From e0a205828ede225490780d0d47067df478ddc543 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 21:26:20 -0500 Subject: [PATCH 4/5] fix(bridge): keep the key backup download from failing the SDK load on iOS Root cause (reproduced in the iOS 26.5 Simulator): the create flow fired the EvoSDK warmup and, in the same step, the automatic key backup download. On iOS Safari that download asks "Do you want to download ...?", which cancels the page's in-flight loads and fails new ones until answered. The SDK chunk import was cancelled and Safari remembered the failure, so registration failed after the InstantSend lock arrived. - The deposit-step backup now always follows the funding gate (SDK and platform chunks in memory, testnet connect awaited up to 5 s), and the testnet connect is redone on focus or after 15 s in case the prompt cancelled it. - The final backup is downloaded after the contract auto-publish, not before it. - The backup's blob URL lives 5 minutes, so a prompt answered late still downloads it. - A chunk load failing within a minute of a download retries for about a minute, and the error explains the browser prompt. Review fixes: - Busted retry URLs are never reused across rounds (a second round would otherwise fail from the module map without a request), and failures other than a failed download are not retried. - The gate gives up after 120 s with the Reload error instead of "Preparing..." forever. - Retry Registration / Top-up / Send is offered only for transient failures (transport, load, unconfirmed); a Platform rejection keeps only the chain lock proof option. - The build check verifies the chunk URLs in the entry name real dynamic import targets. Co-Authored-By: Claude Sonnet 5.5 --- scripts/check-build-artifacts.mjs | 12 +++ src/main.ts | 106 +++++++++++++++++------ src/platform/chunk-loader.test.ts | 88 ++++++++++++++++++- src/platform/chunk-loader.ts | 74 +++++++++++++--- src/ui/components.error-recovery.test.ts | 19 +++- src/ui/components.ts | 16 +++- src/ui/state.error-recovery.test.ts | 14 ++- src/ui/state.ts | 20 ++++- 8 files changed, 304 insertions(+), 45 deletions(-) diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index c11aa6d..240dcf7 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -78,6 +78,18 @@ for (const file of readdirSync(assetsDir).filter((f) => f.endsWith('.js') && f ! } } +// Cache-busted chunk retries (src/platform/chunk-loader.ts) import the URL +// that virtual:chunk-url put in the entry: it must name an asset the entry +// also loads with import(), or the retry would fetch something else. +const chunkUrls = [...entryChunk.matchAll(/new URL\(["']([^"']+\.js)["'],\s*import\.meta\.url\)/g)].map((m) => m[1]); +if (!chunkUrls.some((u) => u.startsWith('evo-sdk'))) { + fail('entry chunk has no virtual:chunk-url URL for the evo-sdk chunk'); +} +for (const url of chunkUrls) { + if (!existsSync(join(assetsDir, url))) fail(`chunk URL ${url} in the entry names no file in dist/assets`); + if (!entryChunk.includes(`import("./${url}")`)) fail(`chunk URL ${url} is not a dynamic import() target of the entry`); +} + // The embeddable widget SDK (docs/widget.md) must ship, stay tiny, and never // pull in the Dash SDK or other heavy dependencies. const WIDGET_MAX_BYTES = 30 * 1024; diff --git a/src/main.ts b/src/main.ts index 733950d..4a5ca86 100644 --- a/src/main.ts +++ b/src/main.ts @@ -342,6 +342,35 @@ function preloadDashWarmup(): void { void ensureClients().catch((err) => console.warn('Dash warmup failed:', err)); } +/** + * The deposit-step key backup. Must run after preparePlatformForFunding: on + * iOS Safari the download raises "Do you want to download …?", which cancels + * the page's in-flight loads and fails new ones until answered. A chunk + * import cancelled that way stays failed for the page (that was the + * "Importing a module script failed." at registration). The testnet SDK + * connect may still be running past the gate's bounded wait and be cancelled + * too, so connect again once the page is back (focus) or after 15 s, for the + * health indicator; registration would reconnect anyway. + */ +function downloadFundingKeyBackup(backupState: BridgeState): void { + downloadKeyBackup(backupState); + if (isE2EMockMode()) return; + const network = backupState.network; + let timer: ReturnType | undefined; + const rewarm = () => { + window.removeEventListener('focus', rewarm); + clearTimeout(timer); + if (state.network !== network) return; + void warmPlatformSdkForFunding(network).then((attempted) => { + if (attempted) pollNetworkStatusNow?.(); + }); + }; + timer = setTimeout(rewarm, 15_000); + window.addEventListener('focus', rewarm); +} + +/** A stalled SDK download (it is several MB) ends in the Reload error instead of "Preparing…" forever. */ +const FUNDING_PREPARE_TIMEOUT_MS = 120_000; /** How long a funding flow waits for the testnet SDK connect before showing its deposit address anyway. */ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; @@ -364,7 +393,21 @@ async function preparePlatformForFunding(): Promise { await loadE2EMockSdk(); return; } - await loadPlatformForFunding(); + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new ChunkLoadError( + 'evo-sdk', + 1, + new Error(`still loading after ${FUNDING_PREPARE_TIMEOUT_MS / 1000} s`) + )), FUNDING_PREPARE_TIMEOUT_MS); + }); + try { + await Promise.race([loadPlatformForFunding(), timeout]); + } finally { + clearTimeout(timer); + } + // Connected before the deposit-step backup download, whose iOS prompt would + // cancel a connect still in flight (see downloadFundingKeyBackup). const connect = warmPlatformSdkForFunding(state.network).then((attempted) => { if (attempted) pollNetworkStatusNow?.(); }); @@ -2816,7 +2859,8 @@ async function startTopUp() { // Auto-download key backup immediately for safety // CRITICAL: User must have this to recover funds if something goes wrong - downloadKeyBackup(stateWithKeys); + // (after preparePlatformForFunding: see downloadFundingKeyBackup) + downloadFundingKeyBackup(stateWithKeys); // Step 2: Wait for deposit updateState(setStep(stateWithKeys, 'detecting_deposit')); @@ -2940,7 +2984,7 @@ async function startSendToAddress() { updateState(stateWithKeys); // Auto-download key backup for safety - downloadKeyBackup(stateWithKeys); + downloadFundingKeyBackup(stateWithKeys); // Step 2: Wait for deposit updateState(setStep(stateWithKeys, 'detecting_deposit')); @@ -3114,7 +3158,7 @@ async function startBridge() { // Auto-download key backup immediately for safety // This ensures users can recover funds if they reload the page - downloadKeyBackup(state); + downloadFundingKeyBackup(state); // Step 2: Wait for deposit updateState(setStep(state, 'detecting_deposit')); @@ -3204,15 +3248,7 @@ async function startBridge() { state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - - // Auto-download final key backup on "Save your keys" page - // This backup includes the identity ID in the filename - // (Earlier download at deposit step used pending filename) - downloadKeyBackup(state); - - // Auto-publish contract if this identity was created for contract registration - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); } catch (error) { if (isE2EMockMode()) { @@ -3347,12 +3383,7 @@ async function recheckDeposit() { state.identityKeys, state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - // Auto-download final key backup on "Save your keys" page - downloadKeyBackup(state); - - // Auto-publish contract if applicable - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); } else { throw new Error(`recheckDeposit: unexpected mode '${state.mode}'`); } @@ -3383,9 +3414,19 @@ async function runPlatformSubmission( assetLockPrivateKeyWif: string ): Promise { if (isE2EMockMode()) { - updateState(setStep(state, state.mode === 'topup' ? 'topping_up' : 'registering_identity')); - await runE2EMockSubmission(); - updateState(state.mode === 'topup' ? setTopUpComplete(state) : setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); + if (state.mode === 'topup') { + updateState(setStep(state, 'topping_up')); + await runE2EMockSubmission(); + updateState(setTopUpComplete(state)); + } else if (state.mode === 'send_to_address') { + updateState(setStep(state, 'sending_to_address')); + await runE2EMockSubmission(); + updateState(setSendToAddressComplete(state)); + } else { + updateState(setStep(state, 'registering_identity')); + await runE2EMockSubmission(); + updateState(setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); + } return; } @@ -3424,10 +3465,7 @@ async function runPlatformSubmission( state.identityKeys, state.network ); - updateState(setIdentityRegistered(state, result.identityId)); - downloadKeyBackup(state); - - if (await autoPublishContractIfNeeded(result.identityId)) return; + await completeIdentityCreation(result.identityId); return; } @@ -3593,6 +3631,22 @@ async function startChainlockFallback(): Promise { * for contract registration. Finds the first suitable auth key and publishes. * Returns true if contract publishing was initiated, false otherwise. */ +/** + * Identity registered: show it, publish the contract it was created for (if + * any), then download the final key backup (its filename has the identity + * ID; the deposit-step backup already holds the keys). The download goes + * last: on iOS Safari it raises a prompt that makes the page's requests fail + * until answered, which would fail the contract publish. + */ +async function completeIdentityCreation(identityId: string): Promise { + updateState(setIdentityRegistered(state, identityId)); + try { + await autoPublishContractIfNeeded(identityId); + } finally { + downloadKeyBackup(state); + } +} + async function autoPublishContractIfNeeded(identityId: string): Promise { if (!state.contractFromIdentityCreation || !state.contractJson) return false; diff --git a/src/platform/chunk-loader.test.ts b/src/platform/chunk-loader.test.ts index ea19b89..3afd641 100644 --- a/src/platform/chunk-loader.test.ts +++ b/src/platform/chunk-loader.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ChunkLoadError, cacheBustedUrl, createChunkLoader } from './chunk-loader.js'; +import { ChunkLoadError, cacheBustedUrl, createChunkLoader, noteDownloadStarted } from './chunk-loader.js'; const noSleep = { sleep: async () => {} }; @@ -68,6 +68,42 @@ describe('createChunkLoader', () => { expect(url.searchParams.get('retry')).toMatch(/^1\./); }); + it('never reuses a failed URL in a later round, as the browser would answer it from its module map', async () => { + const failed = new Set(); + let networkUp = false; + const requests: string[] = []; + const importUrl = async (url: string) => { + if (failed.has(url)) throw new TypeError('Importing a module script failed.'); // no request + requests.push(url); + if (!networkUp) { + failed.add(url); + throw new TypeError('Importing a module script failed.'); + } + return { url }; + }; + const chunkUrl = 'https://bridge.example/assets/evo-sdk.module-abc.js'; + const loader = createChunkLoader('evo-sdk', chunkUrl, () => importUrl(chunkUrl), { ...noSleep, importUrl }); + + await expect(loader()).rejects.toBeInstanceOf(ChunkLoadError); + expect(requests).toHaveLength(3); + networkUp = true; + await expect(loader()).resolves.toBeTruthy(); + expect(requests).toHaveLength(4); + expect(new Set(requests).size).toBe(4); + }); + + it('does not retry an error that is not a failed download', async () => { + let calls = 0; + const loader = createChunkLoader('x', 'https://h.example/x.js', async () => { + calls += 1; + throw new SyntaxError('Unexpected token'); + }, noSleep); + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.attempts).toBe(1); + expect(calls).toBe(1); + }); + it('gives up after 3 attempts with a ChunkLoadError naming the chunk, logs each failure, then lets a later call start over', async () => { let calls = 0; const loader = createChunkLoader('evo-sdk', null, async () => { @@ -93,6 +129,56 @@ describe('createChunkLoader', () => { }); }); +describe('createChunkLoader right after a file download started', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + noteDownloadStarted(0); // long ago: outside the prompt window again + vi.restoreAllMocks(); + }); + + it('keeps retrying for about a minute, since an open download prompt fails every load until answered', async () => { + noteDownloadStarted(); + const sleeps: number[] = []; + let calls = 0; + const loader = createChunkLoader('evo-sdk', null, async () => { + calls += 1; + if (calls < 5) throw new TypeError('Importing a module script failed.'); + return 'loaded'; + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + await expect(loader()).resolves.toBe('loaded'); + expect(sleeps).toEqual([2000, 5000, 10000, 15000]); + expect(String(vi.mocked(console.warn).mock.calls[0][0])).toContain('its prompt may be blocking loads'); + }); + + it('flags the download prompt on the error when it never clears', async () => { + noteDownloadStarted(); + const loader = createChunkLoader('evo-sdk', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, noSleep); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.attempts).toBe(6); + expect(error.downloadPromptSuspected).toBe(true); + }); + + it('uses the short backoff once the download is long past', async () => { + noteDownloadStarted(Date.now() - 61_000); + const sleeps: number[] = []; + const loader = createChunkLoader('x', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, { sleep: async (ms) => { sleeps.push(ms); } }); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(sleeps).toEqual([500, 1500]); + expect(error.downloadPromptSuspected).toBe(false); + }); +}); + describe('cacheBustedUrl', () => { it('keeps the path, adds a per-attempt retry parameter and preserves other query params', () => { const a = new URL(cacheBustedUrl('https://h.example/a/chunk.js?x=1', 1)); diff --git a/src/platform/chunk-loader.ts b/src/platform/chunk-loader.ts index c3bdd69..541b7ca 100644 --- a/src/platform/chunk-loader.ts +++ b/src/platform/chunk-loader.ts @@ -7,19 +7,28 @@ * the chunk's built URL with a query string, which is a new module map entry. * The chunk's own static imports still resolve to the shared, already-loaded * modules, so nothing is instantiated twice. + * + * iOS Safari: a programmatic file download (the key backup) raises "Do you + * want to download …?", and until the user answers it the page's loads fail. + * That is how the EvoSDK chunk got poisoned mid-flow. Funding flows therefore + * load their chunks before the first backup download; as a fallback, a load + * failing right after a download retries for about a minute and says why. */ /** Thrown when a lazily loaded part of the app could not be downloaded. */ export class ChunkLoadError extends Error { readonly chunk: string; readonly attempts: number; + /** A file download had just started, so a browser download prompt may have blocked the load. */ + readonly downloadPromptSuspected: boolean; - constructor(chunk: string, attempts: number, cause: unknown) { + constructor(chunk: string, attempts: number, cause: unknown, downloadPromptSuspected = false) { const reason = cause instanceof Error ? cause.message : String(cause); super(`Could not load the "${chunk}" component after ${attempts} attempt${attempts === 1 ? '' : 's'}: ${reason}`); this.name = 'ChunkLoadError'; this.chunk = chunk; this.attempts = attempts; + this.downloadPromptSuspected = downloadPromptSuspected; (this as { cause?: unknown }).cause = cause; } } @@ -32,8 +41,22 @@ interface ChunkLoaderOptions { } /** Delay before each retry. */ -const RETRY_DELAYS_MS = [500, 1500] as const; +const RETRY_DELAYS_MS: readonly number[] = [500, 1500]; export const CHUNK_LOAD_ATTEMPTS = RETRY_DELAYS_MS.length + 1; +/** Retry delays while a download prompt may be open (about a minute in total). */ +const PROMPT_RETRY_DELAYS_MS: readonly number[] = [2000, 5000, 10000, 15000, 30000]; +const DOWNLOAD_PROMPT_WINDOW_MS = 60_000; + +let lastDownloadStartedAt = -Infinity; + +/** Call when the page starts a file download (it may raise a prompt that blocks loads). */ +export function noteDownloadStarted(now = Date.now()): void { + lastDownloadStartedAt = now; +} + +function downloadPromptMayBeOpen(): boolean { + return Date.now() - lastDownloadStartedAt < DOWNLOAD_PROMPT_WINDOW_MS; +} const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const defaultImportUrl = (url: string) => import(/* @vite-ignore */ url); @@ -49,9 +72,13 @@ export function cacheBustedUrl(url: string, attempt: number): string { /** * Memoized loader for a lazily imported chunk. Concurrent callers share one - * load; a failed load is retried with backoff (re-fetching under a cache-busted - * URL when the chunk URL is known), then the memo is cleared so a later call - * starts over, and a ChunkLoadError naming the chunk is thrown. + * load; a failed download is retried with backoff (re-fetching under a + * cache-busted URL when the chunk URL is known), then the memo is cleared so a + * later call starts over, and a ChunkLoadError naming the chunk is thrown. + * Every cache-busted URL is used once per page: the browser remembers the ones + * that failed, so a later round must not repeat them. Errors other than a + * failed download (TypeError), e.g. a SyntaxError while evaluating, are not + * retried. * * @param chunk name for logs and the error screen * @param chunkUrl built URL of the chunk (virtual:chunk-url), null in dev @@ -65,17 +92,44 @@ export function createChunkLoader( ): () => Promise { const sleep = options.sleep ?? defaultSleep; const importUrl = options.importUrl ?? defaultImportUrl; + // Across rounds: once the plain import failed, the browser may answer it + // from its module map forever, and each busted URL is likewise good once. + let plainImportFailed = false; + let bustedUrls = 0; + + const loadOnce = async (): Promise => { + if (!chunkUrl || !plainImportFailed) { + try { + return await load(); + } catch (error) { + plainImportFailed = true; + throw error; + } + } + bustedUrls += 1; + return (await importUrl(cacheBustedUrl(chunkUrl, bustedUrls))) as T; + }; const loadWithRetries = async (): Promise => { + // Picked at the first failure: a download prompt that is open then keeps + // every load failing until the user answers it. + let delays = RETRY_DELAYS_MS; + let promptSuspected = false; for (let attempt = 0; ; attempt++) { try { - if (attempt === 0 || !chunkUrl) return await load(); - return (await importUrl(cacheBustedUrl(chunkUrl, attempt))) as T; + return await loadOnce(); } catch (error) { - const retryDelay: number | undefined = RETRY_DELAYS_MS[attempt]; + if (!(error instanceof TypeError)) throw new ChunkLoadError(chunk, attempt + 1, error); + if (attempt === 0 && downloadPromptMayBeOpen()) { + delays = PROMPT_RETRY_DELAYS_MS; + promptSuspected = true; + } + const attempts = delays.length + 1; + const retryDelay: number | undefined = delays[attempt]; const retrying = retryDelay === undefined ? '' : `; retrying in ${retryDelay} ms`; - console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${CHUNK_LOAD_ATTEMPTS})${retrying}:`, error); - if (retryDelay === undefined) throw new ChunkLoadError(chunk, CHUNK_LOAD_ATTEMPTS, error); + const why = promptSuspected ? ' (a file download just started; its prompt may be blocking loads)' : ''; + console.warn(`Chunk "${chunk}" failed to load (attempt ${attempt + 1}/${attempts})${why}${retrying}:`, error); + if (retryDelay === undefined) throw new ChunkLoadError(chunk, attempts, error, promptSuspected); await sleep(retryDelay); } } diff --git a/src/ui/components.error-recovery.test.ts b/src/ui/components.error-recovery.test.ts index 228e633..7be8025 100644 --- a/src/ui/components.error-recovery.test.ts +++ b/src/ui/components.error-recovery.test.ts @@ -43,10 +43,15 @@ describe('error screen recovery copy', () => { expect(el.querySelector('.error-technical-content')?.textContent).toContain('Failed to load: evo-sdk'); }); - it('labels the retry for top-up', () => { - const el = renderError({ ...lockReceived, mode: 'topup', step: 'topping_up' }, new Error('platform reject')); + it('labels the retry for top-up and send', () => { + const el = renderError( + { ...lockReceived, mode: 'topup', step: 'topping_up' }, + new Error('Dapi client error: transport error: grpc error: TypeError: Failed to fetch') + ); expect(el.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Top-up'); expect(el.textContent).toContain('the Platform step failed'); + const send = renderError({ ...lockReceived, mode: 'send_to_address', step: 'sending_to_address' }, importFailure()); + expect(send.querySelector('#retry-registration-btn')?.textContent).toBe('Retry Send'); }); it('still says InstantSend did not go through when the lock never arrived', () => { @@ -71,6 +76,16 @@ describe('error screen recovery copy', () => { }); }); +describe('component failure right after a backup download started', () => { + it('points at the browser download prompt instead of the network', () => { + const error = new ChunkLoadError('evo-sdk', 6, new TypeError('Importing a module script failed.'), true); + const el = renderError({ ...createInitialState('testnet'), step: 'generating_keys' }, error); + expect(el.textContent).toContain('asking whether to download the key backup file: answer that prompt first'); + expect(el.textContent).not.toContain('network interruption'); + expect(el.querySelector('#reload-page-btn')).not.toBeNull(); + }); +}); + describe('funding gate screen', () => { it('shows Preparing… (not a blank page) while the Platform components load', () => { const container = document.createElement('div'); diff --git a/src/ui/components.ts b/src/ui/components.ts index 0878822..78753c2 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -31,6 +31,7 @@ import { bytesToHex } from '../utils/hex.js'; import { getNetwork, getAvailableNetworks } from '../config.js'; import { getAssetLockDerivationPath } from '../crypto/hd.js'; import { formatAge } from '../api/network-status.js'; +import { noteDownloadStarted } from '../platform/chunk-loader.js'; /** Dot color + label for each network-health verdict. */ const NETWORK_HEALTH_META: Record< @@ -1889,6 +1890,12 @@ function chunkLabel(recovery: ErrorRecovery): string { return recovery.failedChunk ? ` "${recovery.failedChunk}"` : ''; } +function chunkFailureCause(recovery: ErrorRecovery): string { + return recovery.downloadPromptSuspected + ? 'most likely your browser was asking whether to download the key backup file: answer that prompt first' + : 'most likely a network interruption'; +} + function chainlockFallbackHint(state: BridgeState, recovery: ErrorRecovery): string { if (recovery.lockReceived) { return 'If Platform keeps rejecting the InstantSend proof, you can wait for a chain lock and submit a chain-based proof instead.'; @@ -1914,7 +1921,7 @@ function retrySubmissionHint(state: BridgeState, recovery: ErrorRecovery): strin return 'Platform may still be processing your registration. Wait a minute, then retry — it is safe and cannot spend your deposit twice.'; } if (recovery.lockReceived && recovery.failedChunk) { - return `Your deposit is safe: the InstantSend lock arrived, but the page could not load the${chunkLabel(recovery)} component needed to submit it to Platform (most likely a network interruption). Retry once you are back online — it reuses the same lock and cannot spend your deposit twice.`; + return `Your deposit is safe: the InstantSend lock arrived, but the page could not load the${chunkLabel(recovery)} component needed to submit it to Platform (${chunkFailureCause(recovery)}). Retry once that is resolved — it reuses the same lock and cannot spend your deposit twice.`; } if (recovery.lockReceived) { return 'Your deposit is safe: the InstantSend lock arrived, but the Platform step failed. Retrying reuses the same lock and cannot spend your deposit twice.'; @@ -1961,7 +1968,7 @@ function renderErrorStep(state: BridgeState): HTMLElement { const reloadHtml = recovery.reloadSafe ? `
-

The page failed to load a required component${escapeHtml(chunkLabel(recovery))} (most likely a network interruption). No funds have been sent. Reload the page to try again.

+

The page failed to load a required component${escapeHtml(chunkLabel(recovery))} (${escapeHtml(chunkFailureCause(recovery))}). No funds have been sent. Reload the page to try again.

` @@ -2127,9 +2134,12 @@ export function downloadKeyBackup(state: BridgeState): void { a.href = url; a.download = filename; document.body.appendChild(a); + noteDownloadStarted(); a.click(); document.body.removeChild(a); - URL.revokeObjectURL(url); + // iOS Safari reads the blob only once the user answers its download + // prompt, which can take a while. + setTimeout(() => URL.revokeObjectURL(url), 5 * 60_000); } // ============================================================================ diff --git a/src/ui/state.error-recovery.test.ts b/src/ui/state.error-recovery.test.ts index 6c46538..ae9b785 100644 --- a/src/ui/state.error-recovery.test.ts +++ b/src/ui/state.error-recovery.test.ts @@ -9,6 +9,8 @@ import { } from '../platform/identity-confirm.js'; const importFailure = () => new ChunkLoadError('evo-sdk', 3, new TypeError('Importing a module script failed.')); +/** What the SDK throws when the broadcast never reached Platform (seen in WebKit). */ +const transportFailure = () => new Error("Failed to create identity: Dapi client error: transport error: grpc error: code: 'Internal error', message: \"Failed to call gRPC service: JS API error: TypeError: Load failed\""); const instantProof: AssetLockProofData = { type: 'instant', @@ -42,6 +44,7 @@ describe('getErrorRecovery after the InstantSend lock arrived', () => { canRetrySubmission: true, reloadSafe: false, failedChunk: 'evo-sdk', + downloadPromptSuspected: false, }); }); @@ -50,7 +53,7 @@ describe('getErrorRecovery after the InstantSend lock arrived', () => { ['topup', 'topping_up', ErrorCodes.TOPUP], ['send_to_address', 'sending_to_address', ErrorCodes.SEND_ADDRESS], ] as const) { - const errored = setError(lockReceived({ mode, step }), new Error('platform reject')); + const errored = setError(lockReceived({ mode, step }), transportFailure()); expect(errored.errorCode).toBe(code); expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: true, canRetrySubmission: true }); } @@ -76,9 +79,15 @@ describe('getErrorRecovery after the InstantSend lock arrived', () => { it('does not call a chain proof an InstantSend lock', () => { const chainProof: AssetLockProofData = { type: 'chain', coreChainLockedHeight: 10, txid: 'ab'.repeat(32), vout: 0 }; - const errored = setError(lockReceived({ assetLockProof: chainProof }), new Error('platform reject')); + const errored = setError(lockReceived({ assetLockProof: chainProof }), transportFailure()); expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: false, canRetrySubmission: true }); }); + + it('offers no retry when Platform rejected the transition (same proof, same verdict), only the chain lock proof', () => { + const errored = setError(lockReceived(), new Error('Failed to create identity: invalid instant asset lock proof signature')); + expect(errored.chainlockFallbackAvailable).toBe(true); + expect(getErrorRecovery(errored)).toMatchObject({ lockReceived: true, canRetrySubmission: false }); + }); }); describe('getErrorRecovery for a missing InstantSend lock', () => { @@ -102,6 +111,7 @@ describe('component load failure while preparing a funding flow', () => { canRetrySubmission: false, reloadSafe: true, failedChunk: 'evo-sdk', + downloadPromptSuspected: false, }); }); diff --git a/src/ui/state.ts b/src/ui/state.ts index 3c194ae..567a19f 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -39,6 +39,7 @@ import { type IdentityRegistrationUnconfirmedError, } from '../platform/identity-confirm.js'; import { ChunkLoadError } from '../platform/chunk-loader.js'; +import { isRetryableError } from '../utils/retry.js'; import { shouldRecommendMobileApp } from './mobile-app.js'; /** @@ -617,6 +618,19 @@ function resolveErrorCode(state: BridgeState, error: Error): string { return StepErrorCodes[state.step] ?? ErrorCodes.UNKNOWN; } +/** + * Whether resubmitting the same proof can help: the submission did not reach + * Platform or its outcome is unknown. A rejection by Platform is not retried: + * resubmitting the same transition gets the same verdict. + */ +function isTransientSubmissionError(error: Error | undefined): boolean { + if (!error) return false; + if (error instanceof ChunkLoadError || isIdentityRegistrationUnconfirmedError(error)) return true; + // The SDK wraps transport failures: "Dapi client error: transport error: … + // TypeError: Failed to fetch" (Chromium) / "Load failed" (WebKit). + return isRetryableError(error) || /transport error|failed to fetch|load failed|deadline exceeded|unavailable/i.test(error.message); +} + export interface ErrorRecovery { /** * The Platform submission failed while the InstantSend lock had arrived @@ -629,6 +643,8 @@ export interface ErrorRecovery { reloadSafe: boolean; /** Name of the lazily loaded chunk that could not be downloaded, if that was the cause. */ failedChunk?: string; + /** That chunk failed right after a file download started (a download prompt may have blocked it). */ + downloadPromptSuspected: boolean; } /** What the error screen can offer for the current error. */ @@ -643,11 +659,13 @@ export function getErrorRecovery(state: BridgeState): ErrorRecovery { submissionFailed && !!state.assetLockProof && !!state.assetLockKeyPair && - !isAssetLockConsumedElsewhereError(state.error), + !isAssetLockConsumedElsewhereError(state.error) && + isTransientSubmissionError(state.error), // resolveErrorCode already implies no deposit address; re-checked because // a wrong "safe to reload" could lose track of funds in flight. reloadSafe: state.errorCode === ErrorCodes.COMPONENT_LOAD && !state.depositAddress && !state.txid, failedChunk: state.error instanceof ChunkLoadError ? state.error.chunk : undefined, + downloadPromptSuspected: state.error instanceof ChunkLoadError && state.error.downloadPromptSuspected, }; } From 3efeb048286601c229f01f6fdfacbb893068d801 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 22:02:28 -0500 Subject: [PATCH 5/5] fix(bridge): narrow submission retries, 5 min gate timeout, iOS-only prompt mode Review follow-ups: - Retry Registration / Top-up / Send now matches only transient texts: fetch/load failures, "no available addresses", gRPC Unavailable or Deadline exceeded, client timeouts (PlatformOperationTimeoutError) and the devnet polling window. It no longer goes through isRetryableError, whose bare "500"/"429"/"timeout" substrings also matched Platform rejections. - The gate times out after 5 min (7 MB gzipped at about 200 kbit/s) instead of 120 s, and names the chunk that stalled. - The long backoff and the download-prompt copy apply only on iOS (all WebKit), where the download prompt blocks loads. - Mock-mode create/top-up download the backup after the gate, as the real flows do; e2e asserts the download comes after the retried SDK load and never happens when the gate fails. - Small cleanups: withChunkTimeout, warmFundingConnect, DEFAULT_CHUNK_LOAD_ATTEMPTS, mock submission steps in one switch, JSDoc placement. Co-Authored-By: Claude Sonnet 5.5 --- e2e/deterministic.spec.ts | 9 +++ src/main.ts | 92 ++++++++++++++--------------- src/platform/chunk-loader.test.ts | 49 ++++++++++++++- src/platform/chunk-loader.ts | 25 +++++++- src/platform/loaders.ts | 13 ++-- src/ui/components.ts | 10 +++- src/ui/state.error-recovery.test.ts | 23 ++++++++ src/ui/state.ts | 26 +++++--- 8 files changed, 182 insertions(+), 65 deletions(-) diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index 885f057..0c3a5e1 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -105,9 +105,14 @@ test.describe('Deterministic UI E2E (mock mode)', () => { test.describe('Platform component gate before funding', () => { test('a dropped SDK download is retried and the flow reaches the deposit address', async ({ page }) => { const warnings: string[] = []; + const events: string[] = []; page.on('console', (msg) => { if (msg.type() === 'warning') warnings.push(msg.text()); + if (msg.text().includes('Chunk "evo-sdk" failed to load')) events.push('sdk-failure'); }); + // The key backup download must wait for the gate: on iOS its prompt + // cancels in-flight loads (that poisoned the SDK import in production). + page.on('download', () => events.push('backup-download')); await injectMockFailures(page, { sdkLoadFailures: 2 }); await page.goto(MOCK_QUERY); await page.click('#mode-create-btn'); @@ -117,10 +122,13 @@ test.describe('Deterministic UI E2E (mock mode)', () => { await expect(page.locator('.preparing-step')).toContainText('Preparing…'); await expect(page.locator('.deposit-headline')).toBeVisible(); expect(warnings.filter((w) => w.includes('Chunk "evo-sdk" failed to load'))).toHaveLength(2); + await expect.poll(() => events).toEqual(['sdk-failure', 'sdk-failure', 'backup-download']); }); for (const flow of ['create', 'topup'] as const) { test(`${flow}: an SDK that cannot load stops the flow before any deposit address, with Reload`, async ({ page }) => { + let downloads = 0; + page.on('download', () => { downloads += 1; }); await injectMockFailures(page, { sdkLoadFailures: 3 }); await page.goto(MOCK_QUERY); if (flow === 'create') { @@ -138,6 +146,7 @@ test.describe('Deterministic UI E2E (mock mode)', () => { await expect(page.locator('.error-step')).toContainText('No funds have been sent'); await expect(page.locator('.deposit-headline')).toHaveCount(0); await expect(page.locator('#download-keys-btn')).toHaveCount(0); + expect(downloads).toBe(0); await page.locator('.error-technical summary').click(); await expect(page.locator('.error-technical-content')).toContainText('Failed to load: evo-sdk'); diff --git a/src/main.ts b/src/main.ts index 4a5ca86..4ace06c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -212,7 +212,7 @@ import { warmDashModules, warmPlatformSdkForFunding, } from './platform/loaders.js'; -import { CHUNK_LOAD_ATTEMPTS, ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; +import { DEFAULT_CHUNK_LOAD_ATTEMPTS, ChunkLoadError, createChunkLoader } from './platform/chunk-loader.js'; import { deriveCandidateKeys, explainKeyIneligibility, @@ -356,21 +356,25 @@ function downloadFundingKeyBackup(backupState: BridgeState): void { downloadKeyBackup(backupState); if (isE2EMockMode()) return; const network = backupState.network; - let timer: ReturnType | undefined; const rewarm = () => { window.removeEventListener('focus', rewarm); clearTimeout(timer); - if (state.network !== network) return; - void warmPlatformSdkForFunding(network).then((attempted) => { - if (attempted) pollNetworkStatusNow?.(); - }); + if (state.network === network) void warmFundingConnect(network); }; - timer = setTimeout(rewarm, 15_000); + const timer = setTimeout(rewarm, 15_000); window.addEventListener('focus', rewarm); } -/** A stalled SDK download (it is several MB) ends in the Reload error instead of "Preparing…" forever. */ -const FUNDING_PREPARE_TIMEOUT_MS = 120_000; +/** + * Testnet: connect the SDK (shared with any connect in flight) and poll the + * health indicator as soon as it settles. Other networks: nothing. + */ +function warmFundingConnect(network: string): Promise { + return warmPlatformSdkForFunding(network).then((attempted) => { + if (attempted) pollNetworkStatusNow?.(); + }); +} + /** How long a funding flow waits for the testnet SDK connect before showing its deposit address anyway. */ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; @@ -378,8 +382,8 @@ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; * Gate in front of every funding flow's deposit address (shown as "Preparing * Dash Platform..."). Loads the chunks the Platform submission needs, with * retries, so that once funds are committed nothing depends on a download; - * when they still fail this throws a ChunkLoadError while nothing is at risk - * (error screen with Reload). + * when they still fail (or stall for 5 min) this throws a ChunkLoadError + * while nothing is at risk (error screen with Reload). * * Testnet also starts connecting the SDK, so the health indicator reads * Platform before the asset lock is broadcast (polls right after the connect @@ -393,25 +397,10 @@ async function preparePlatformForFunding(): Promise { await loadE2EMockSdk(); return; } - let timer: ReturnType | undefined; - const timeout = new Promise((_, reject) => { - timer = setTimeout(() => reject(new ChunkLoadError( - 'evo-sdk', - 1, - new Error(`still loading after ${FUNDING_PREPARE_TIMEOUT_MS / 1000} s`) - )), FUNDING_PREPARE_TIMEOUT_MS); - }); - try { - await Promise.race([loadPlatformForFunding(), timeout]); - } finally { - clearTimeout(timer); - } + await loadPlatformForFunding(); // Connected before the deposit-step backup download, whose iOS prompt would // cancel a connect still in flight (see downloadFundingKeyBackup). - const connect = warmPlatformSdkForFunding(state.network).then((attempted) => { - if (attempted) pollNetworkStatusNow?.(); - }); - await Promise.race([connect, delay(FUNDING_SDK_CONNECT_WAIT_MS)]); + await Promise.race([warmFundingConnect(state.network), delay(FUNDING_SDK_CONNECT_WAIT_MS)]); } // ── Network-status polling ────────────────────────────────────────────────── @@ -580,7 +569,7 @@ function delay(ms: number): Promise { /** * Failure injection for mock-mode e2e tests, set with page.addInitScript as * window.__e2eMockFailures: `sdkLoadFailures` failed SDK chunk loads before - * the gate's loader succeeds (CHUNK_LOAD_ATTEMPTS or more exhausts its + * the gate's loader succeeds (DEFAULT_CHUNK_LOAD_ATTEMPTS or more exhausts its * retries), `submissionFailures` failed Platform submissions after the * InstantSend lock arrived. */ @@ -609,10 +598,24 @@ const loadE2EMockSdk = createChunkLoader('evo-sdk', null, async () => { return {}; }); +function e2eMockSubmissionSteps(mode: BridgeState['mode']): { + step: BridgeStep; + complete: (s: BridgeState) => BridgeState; +} { + switch (mode) { + case 'topup': + return { step: 'topping_up', complete: setTopUpComplete }; + case 'send_to_address': + return { step: 'sending_to_address', complete: setSendToAddressComplete }; + default: + return { step: 'registering_identity', complete: (s) => setIdentityRegistered(s, E2E_MOCK_IDENTITY_ID) }; + } +} + async function runE2EMockSubmission(): Promise { await delay(120); if (consumeE2EMockFailure('submissionFailures')) { - throw new ChunkLoadError('evo-sdk', CHUNK_LOAD_ATTEMPTS, mockImportFailure()); + throw new ChunkLoadError('evo-sdk', DEFAULT_CHUNK_LOAD_ATTEMPTS, mockImportFailure()); } } @@ -2822,6 +2825,7 @@ async function startTopUp() { await delay(120); await preparePlatformForFunding(); updateState(setOneTimeKeyPair(state, assetLockKeyPair, depositAddress)); + downloadFundingKeyBackup(state); updateState(setStep(state, 'detecting_deposit')); clearE2EMockAdvanceHook(); await waitForE2EMockAdvance(); @@ -3116,6 +3120,7 @@ async function startBridge() { await delay(120); await preparePlatformForFunding(); updateState(setKeyPairs(state, assetLockKeyPair, depositAddress)); + downloadFundingKeyBackup(state); updateState(setStep(state, 'detecting_deposit')); await waitForE2EMockAdvance(); updateState(setUtxoDetected(state, createE2EMockUtxo())); @@ -3414,19 +3419,10 @@ async function runPlatformSubmission( assetLockPrivateKeyWif: string ): Promise { if (isE2EMockMode()) { - if (state.mode === 'topup') { - updateState(setStep(state, 'topping_up')); - await runE2EMockSubmission(); - updateState(setTopUpComplete(state)); - } else if (state.mode === 'send_to_address') { - updateState(setStep(state, 'sending_to_address')); - await runE2EMockSubmission(); - updateState(setSendToAddressComplete(state)); - } else { - updateState(setStep(state, 'registering_identity')); - await runE2EMockSubmission(); - updateState(setIdentityRegistered(state, E2E_MOCK_IDENTITY_ID)); - } + const { step, complete } = e2eMockSubmissionSteps(state.mode); + updateState(setStep(state, step)); + await runE2EMockSubmission(); + updateState(complete(state)); return; } @@ -3626,11 +3622,6 @@ async function startChainlockFallback(): Promise { // Contract Registration Functions // ============================================================================ -/** - * Auto-publish contract after identity creation if the identity was created - * for contract registration. Finds the first suitable auth key and publishes. - * Returns true if contract publishing was initiated, false otherwise. - */ /** * Identity registered: show it, publish the contract it was created for (if * any), then download the final key backup (its filename has the identity @@ -3647,6 +3638,11 @@ async function completeIdentityCreation(identityId: string): Promise { } } +/** + * Auto-publish contract after identity creation if the identity was created + * for contract registration. Finds the first suitable auth key and publishes. + * Returns true if contract publishing was initiated, false otherwise. + */ async function autoPublishContractIfNeeded(identityId: string): Promise { if (!state.contractFromIdentityCreation || !state.contractJson) return false; diff --git a/src/platform/chunk-loader.test.ts b/src/platform/chunk-loader.test.ts index 3afd641..89e0dd1 100644 --- a/src/platform/chunk-loader.test.ts +++ b/src/platform/chunk-loader.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ChunkLoadError, cacheBustedUrl, createChunkLoader, noteDownloadStarted } from './chunk-loader.js'; +import { ChunkLoadError, cacheBustedUrl, createChunkLoader, noteDownloadStarted, withChunkTimeout } from './chunk-loader.js'; const noSleep = { sleep: async () => {} }; @@ -92,6 +92,21 @@ describe('createChunkLoader', () => { expect(new Set(requests).size).toBe(4); }); + it('makes concurrent callers during a failing round share one request sequence and one error', async () => { + const requests: string[] = []; + const importUrl = async (url: string) => { + requests.push(url); + throw new TypeError('Importing a module script failed.'); + }; + const chunkUrl = 'https://bridge.example/assets/evo-sdk.module-abc.js'; + const loader = createChunkLoader('evo-sdk', chunkUrl, () => importUrl(chunkUrl), { ...noSleep, importUrl }); + + const [a, b] = await Promise.all([loader().catch((e: unknown) => e), loader().catch((e: unknown) => e)]); + expect(a).toBeInstanceOf(ChunkLoadError); + expect(b).toBe(a); + expect(requests).toHaveLength(3); + }); + it('does not retry an error that is not a failed download', async () => { let calls = 0; const loader = createChunkLoader('x', 'https://h.example/x.js', async () => { @@ -166,6 +181,18 @@ describe('createChunkLoader right after a file download started', () => { expect(error.downloadPromptSuspected).toBe(true); }); + it('picks the backoff at the first failure only: a download during the round does not stretch it', async () => { + const sleeps: number[] = []; + const loader = createChunkLoader('x', null, async () => { + throw new TypeError('Importing a module script failed.'); + }, { sleep: async (ms) => { sleeps.push(ms); noteDownloadStarted(); } }); + + const error = (await loader().catch((e: unknown) => e)) as ChunkLoadError; + expect(sleeps).toEqual([500, 1500]); + expect(error.attempts).toBe(3); + expect(error.downloadPromptSuspected).toBe(false); + }); + it('uses the short backoff once the download is long past', async () => { noteDownloadStarted(Date.now() - 61_000); const sleeps: number[] = []; @@ -188,3 +215,23 @@ describe('cacheBustedUrl', () => { expect(a.searchParams.get('retry')).not.toBe(b.searchParams.get('retry')); }); }); + +describe('withChunkTimeout', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('rejects with a ChunkLoadError naming the stalled chunk', async () => { + vi.useFakeTimers(); + const stalled = withChunkTimeout(new Promise(() => {}), 'platform', 300_000).catch((e: unknown) => e); + await vi.advanceTimersByTimeAsync(300_000); + const error = (await stalled) as ChunkLoadError; + expect(error).toBeInstanceOf(ChunkLoadError); + expect(error.chunk).toBe('platform'); + expect(error.message).toContain('still loading after 300 s'); + }); + + it('passes a load that finishes in time through', async () => { + await expect(withChunkTimeout(Promise.resolve('ok'), 'evo-sdk', 1000)).resolves.toBe('ok'); + }); +}); diff --git a/src/platform/chunk-loader.ts b/src/platform/chunk-loader.ts index 541b7ca..458bacc 100644 --- a/src/platform/chunk-loader.ts +++ b/src/platform/chunk-loader.ts @@ -42,14 +42,18 @@ interface ChunkLoaderOptions { /** Delay before each retry. */ const RETRY_DELAYS_MS: readonly number[] = [500, 1500]; -export const CHUNK_LOAD_ATTEMPTS = RETRY_DELAYS_MS.length + 1; +/** Attempts per round normally; a round right after a download prompt makes more. */ +export const DEFAULT_CHUNK_LOAD_ATTEMPTS = RETRY_DELAYS_MS.length + 1; /** Retry delays while a download prompt may be open (about a minute in total). */ const PROMPT_RETRY_DELAYS_MS: readonly number[] = [2000, 5000, 10000, 15000, 30000]; const DOWNLOAD_PROMPT_WINDOW_MS = 60_000; let lastDownloadStartedAt = -Infinity; -/** Call when the page starts a file download (it may raise a prompt that blocks loads). */ +/** + * Call when the page starts a file download that raises a prompt blocking the + * page's loads (iOS/iPadOS Safari and other iOS browsers, all WebKit). + */ export function noteDownloadStarted(now = Date.now()): void { lastDownloadStartedAt = now; } @@ -64,6 +68,23 @@ const defaultImportUrl = (url: string) => import(/* @vite-ignore */ url); /** Unique per page load, so a CDN cannot answer the retry from a cached error. */ const pageToken = Date.now().toString(36); +/** + * Reject with a ChunkLoadError naming `chunk` if `promise` has not settled + * within `ms` (a stalled download would otherwise wait forever). The load + * itself keeps going; a later call may still use it. + */ +export async function withChunkTimeout(promise: Promise, chunk: string, ms: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new ChunkLoadError(chunk, 1, new Error(`still loading after ${ms / 1000} s`))), ms); + }); + try { + return await Promise.race([promise, timeout]); + } finally { + clearTimeout(timer); + } +} + export function cacheBustedUrl(url: string, attempt: number): string { const parsed = new URL(url, globalThis.location?.href); parsed.searchParams.set('retry', `${attempt}.${pageToken}`); diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index bed6a06..8099b6c 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -5,7 +5,7 @@ import usernameTransferChunkUrl from 'virtual:chunk-url:./username-transfer.js'; import feeEstimatorChunkUrl from 'virtual:chunk-url:dash-contract-fee-estimator'; import islockChunkUrl from 'virtual:chunk-url:../api/islock.js'; import { getNetwork } from '../config.js'; -import { createChunkLoader } from './chunk-loader.js'; +import { createChunkLoader, withChunkTimeout } from './chunk-loader.js'; import { loadSdkModule } from './sdkModule.js'; export const loadPlatformModule = createChunkLoader('platform', platformChunkUrl, () => import('./index.js')); @@ -41,10 +41,15 @@ export function warmDashModules(): Promise[]> { /** * Load the chunks a Platform submission needs (EvoSDK and platform * operations), for the funding gate in main.ts. Rejects with a ChunkLoadError - * when a chunk still fails after the loaders' retries. + * naming the chunk when it still fails after the loaders' retries, or is + * still loading after `timeoutMs` (the SDK is ~7 MB gzipped: 5 min covers + * about 200 kbit/s; Reload would throw a partial download away). */ -export async function loadPlatformForFunding(): Promise { - await Promise.all([loadSdkModule(), loadPlatformModule()]); +export async function loadPlatformForFunding(timeoutMs = 5 * 60_000): Promise { + await Promise.all([ + withChunkTimeout(loadSdkModule(), 'evo-sdk', timeoutMs), + withChunkTimeout(loadPlatformModule(), 'platform', timeoutMs), + ]); } /** diff --git a/src/ui/components.ts b/src/ui/components.ts index 78753c2..5731afb 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -2134,11 +2134,15 @@ export function downloadKeyBackup(state: BridgeState): void { a.href = url; a.download = filename; document.body.appendChild(a); - noteDownloadStarted(); + // Only iOS browsers (all WebKit) ask before downloading, and block the + // page's loads while they ask; elsewhere a chunk failure is not the prompt. + if (getCurrentMobilePlatform() === 'ios') noteDownloadStarted(); a.click(); document.body.removeChild(a); - // iOS Safari reads the blob only once the user answers its download - // prompt, which can take a while. + // iOS Safari reads the blob only when the user answers its download prompt, + // which can be minutes later; revoking now would make that download fail. + // 5 min bounds how long the backup stays in memory; a later answer gets + // nothing, and the error screens keep a Download Key Backup button. setTimeout(() => URL.revokeObjectURL(url), 5 * 60_000); } diff --git a/src/ui/state.error-recovery.test.ts b/src/ui/state.error-recovery.test.ts index ae9b785..358d633 100644 --- a/src/ui/state.error-recovery.test.ts +++ b/src/ui/state.error-recovery.test.ts @@ -90,6 +90,29 @@ describe('getErrorRecovery after the InstantSend lock arrived', () => { }); }); +describe('which submission failures offer a retry', () => { + const offersRetry = (error: Error) => getErrorRecovery(setError(lockReceived(), error)).canRetrySubmission; + + it('retries a client-side timeout (PlatformOperationTimeoutError)', () => { + const timeout = new Error('Timed out while broadcasting identity create state transition'); + timeout.name = 'PlatformOperationTimeoutError'; + expect(offersRetry(timeout)).toBe(true); + expect(offersRetry(new Error('Failed to create identity: Timed out while waiting for the result'))).toBe(true); + }); + + it('retries when the SDK has no node left to use, and a devnet polling window that ran out', () => { + expect(offersRetry(new Error('Dapi client error: no available addresses to use'))).toBe(true); + expect(offersRetry(new Error('Identity 9Wz7 did not appear on Platform within 60s polling window. Check later.'))).toBe(true); + expect(offersRetry(new Error("grpc error: code: 'Unavailable', message: \"connection reset\""))).toBe(true); + }); + + it('does not retry Platform rejections that merely contain status-code digits or the word timeout', () => { + expect(offersRetry(new Error('Failed to create identity: insufficient asset lock balance 5030000 < 5029000'))).toBe(false); + expect(offersRetry(new Error('Invalid identity public key: signature verification timeout field 429'))).toBe(false); + expect(offersRetry(new Error('Failed to create identity: invalid instant asset lock proof signature'))).toBe(false); + }); +}); + describe('getErrorRecovery for a missing InstantSend lock', () => { it('is not a received lock and has nothing to retry', () => { const waiting: BridgeState = { ...lockReceived(), step: 'waiting_islock', assetLockProof: undefined, instantLockBytes: undefined }; diff --git a/src/ui/state.ts b/src/ui/state.ts index 567a19f..1b3c4f8 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -39,7 +39,6 @@ import { type IdentityRegistrationUnconfirmedError, } from '../platform/identity-confirm.js'; import { ChunkLoadError } from '../platform/chunk-loader.js'; -import { isRetryableError } from '../utils/retry.js'; import { shouldRecommendMobileApp } from './mobile-app.js'; /** @@ -619,16 +618,29 @@ function resolveErrorCode(state: BridgeState, error: Error): string { } /** - * Whether resubmitting the same proof can help: the submission did not reach - * Platform or its outcome is unknown. A rejection by Platform is not retried: - * resubmitting the same transition gets the same verdict. + * Failures where the submission did not reach Platform or its outcome is + * unknown. Deliberately narrow (no bare status codes or "timeout" substrings, + * which also occur in amounts, IDs and Platform's own rejection texts). + * - "Dapi client error: transport error: … TypeError: Failed to fetch" + * (Chromium) / "… Load failed" (WebKit): the request never got through + * - "no available addresses": the SDK banned every node after failures + * - gRPC "Unavailable" / "Deadline exceeded" + * - "Timed out while …" (PlatformOperationTimeoutError, client.ts) + * - "… did not appear on Platform within 60s polling window" (non-trusted + * devnets, identity.ts) + */ +const TRANSIENT_SUBMISSION_MESSAGE = + /failed to fetch|load failed|networkerror|no available addresses|\bunavailable\b|deadline exceeded|\btimed out while\b|did not appear on platform within/i; + +/** + * Whether resubmitting the same proof can help. A rejection by Platform is + * not retried: resubmitting the same transition gets the same verdict. */ function isTransientSubmissionError(error: Error | undefined): boolean { if (!error) return false; if (error instanceof ChunkLoadError || isIdentityRegistrationUnconfirmedError(error)) return true; - // The SDK wraps transport failures: "Dapi client error: transport error: … - // TypeError: Failed to fetch" (Chromium) / "Load failed" (WebKit). - return isRetryableError(error) || /transport error|failed to fetch|load failed|deadline exceeded|unavailable/i.test(error.message); + if (error.name === 'PlatformOperationTimeoutError') return true; + return TRANSIENT_SUBMISSION_MESSAGE.test(error.message); } export interface ErrorRecovery {