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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 106 additions & 1 deletion e2e/deterministic.spec.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -12,6 +12,21 @@

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[] = [];
Expand Down Expand Up @@ -87,6 +102,96 @@
await expect(page.getByText('Registration Complete!')).toBeVisible();
});

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');
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);
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') {
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);
expect(downloads).toBe(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 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 advanceMockDeposit(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 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 advanceMockDeposit(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);

Expand Down Expand Up @@ -202,7 +307,7 @@

await page.fill('#withdraw-private-key-input', E2E_MOCK_WITHDRAW_WIF);
await page.locator('#withdraw-private-key-input').press('Tab');
await expect(page.getByText('Key matches key #3 (TRANSFER / CRITICAL)')).toBeVisible();

Check failure on line 310 in e2e/deterministic.spec.ts

View workflow job for this annotation

GitHub Actions / e2e

[chromium] › e2e/deterministic.spec.ts:285:3 › Deterministic UI E2E (mock mode) › withdraw flow validates inputs and completes with status tracking

1) [chromium] › e2e/deterministic.spec.ts:285:3 › Deterministic UI E2E (mock mode) › withdraw flow validates inputs and completes with status tracking Error: Timed out 5000ms waiting for expect(locator).toBeVisible() Locator: getByText('Key matches key #3 (TRANSFER / CRITICAL)') Expected: visible Received: <element(s) not found> Call log: - expect.toBeVisible with timeout 5000ms - waiting for getByText('Key matches key #3 (TRANSFER / CRITICAL)') 308 | await page.fill('#withdraw-private-key-input', E2E_MOCK_WITHDRAW_WIF); 309 | await page.locator('#withdraw-private-key-input').press('Tab'); > 310 | await expect(page.getByText('Key matches key #3 (TRANSFER / CRITICAL)')).toBeVisible(); | ^ 311 | 312 | // Bad address is rejected (real validation runs even in mock mode) 313 | await page.fill('#withdraw-address-input', 'not-an-address'); at /home/runner/work/dash-bridge/dash-bridge/e2e/deterministic.spec.ts:310:78

// Bad address is rejected (real validation runs even in mock mode)
await page.fill('#withdraw-address-input', 'not-an-address');
Expand Down
30 changes: 29 additions & 1 deletion scripts/check-build-artifacts.mjs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -62,6 +62,34 @@ 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`);
}
}

// 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;
Expand Down
62 changes: 62 additions & 0 deletions src/config/vite-chunk-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { Plugin } from 'vite';

/**
* `import url from 'virtual:chunk-url:<specifier>'` gives the built URL of
* the chunk that `import('<specifier>')` 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.
*/
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';

export function chunkUrlPlugin(): Plugin {
let isBuild = false;
// Resolved virtual id -> the module that imports it.
const importers = new Map<string, string>();
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};`;
},
};
}
Loading
Loading