Files
patriothacks/e2e/fairDrawWalletCredit.e2e.mjs

381 lines
16 KiB
JavaScript

// Fair Draw -> real wallet credit acceptance test (plan todo 13). Self-
// contained Playwright runner, same shape as e2e/transactionHistorySignature.e2e.mjs:
// starts a real Vite dev server, opens a real browser page, and drives the
// real app UI through its real route - no mocks of the ledger/eventlog.
//
// HAPPY: a genuine draw is run to completion on the real `/miniapp/fair-draw`
// route. The device's own identity is deterministically forced to win (see
// `forceDrawOutcome` below - it overrides only `window.crypto.getRandomValues`,
// the one source of entropy `RevealDraw`'s production path uses; the real
// commit/reveal/verify/drawOutcome functions all still run for real). The
// WalletCard's compact balance chip (visible on the mini-app route itself,
// no navigation/reload) is asserted to update live from "No balance yet"
// (the honest starting state for a fresh identity) to the real
// FAIR_DRAW_PRIZE_AMOUNT, then a client-side-only navigation to "/" (same
// SPA, no page reload - the WalletCard <section> stays mounted the whole
// time per AppRoutes.test.tsx's own DOM-identity guarantee) reveals the
// full transaction history row for the real signed wallet.issue entry.
//
// FAILURE/non-winner: the same deterministic override instead forces a
// DIFFERENT participant ("Resident D") to win. The device's own wallet
// (WalletCard) must stay at "No balance yet / No transactions yet" - a
// losing participant's wallet is never touched.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import * as ed from "@noble/ed25519";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const VITE_PORT = 47000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
// Deterministic byte-fill values whose real drawOutcome(seed, 5) index
// (SHA-256("draw:" + seed) mod 5, exactly RevealDraw's production
// computation - precomputed offline against lib/fairdraw.ts's real
// algorithm, not asserted/trusted blindly) lands on a known participant
// index among DEFAULT_FAIR_DRAW_PARTICIPANTS = ["You", "Resident B",
// "Resident C", "Resident D", "Resident E"]. The SAME fill value is used
// for both the seed and the salt arrays (see `forceDrawOutcome` below) -
// drawOutcome only ever depends on the revealed seed, and commit/
// reveal/verify only require the committed and revealed seed+salt to be
// identical, which they always are since both calls return the exact same
// canned bytes.
const FILL_FOR_YOU_WINS = 0x02; // -> index 0 ("You")
const FILL_FOR_RESIDENT_D_WINS = 0x00; // -> index 3 ("Resident D")
/**
* Pre-seeds the real local-identity record directly into IndexedDB (same
* schema `src/lib/db.ts` defines) via `page.addInitScript` BEFORE the
* page's own React tree ever mounts - sidesteps the same known,
* pre-existing, out-of-scope StrictMode double-invoke race documented in
* transactionHistorySignature.e2e.mjs, not touched here.
*/
async function seedIdentity(context) {
const { secretKey, publicKey } = await ed.keygenAsync();
await context.addInitScript(
({ secretKey, publicKey }) => {
const openReq = indexedDB.open("the-commons-hollow", 4);
openReq.onupgradeneeded = () => {
const db = openReq.result;
if (!db.objectStoreNames.contains("identity")) db.createObjectStore("identity", { keyPath: "id" });
if (!db.objectStoreNames.contains("eventLog")) {
const store = db.createObjectStore("eventLog", { keyPath: "id", autoIncrement: true });
store.createIndex("lamportTs", "lamportTs", { unique: false });
}
if (!db.objectStoreNames.contains("miniappPackages")) {
const store = db.createObjectStore("miniappPackages", { keyPath: "id" });
store.createIndex("sourceBlobId", "sourceBlobId", { unique: true });
}
};
openReq.onsuccess = () => {
const db = openReq.result;
const tx = db.transaction("identity", "readwrite");
tx.objectStore("identity").put({
id: "local",
publicKey: new Uint8Array(publicKey),
secretKey: new Uint8Array(secretKey),
createdAt: Date.now(),
});
};
},
{ secretKey: Array.from(secretKey), publicKey: Array.from(publicKey) },
);
}
/**
* Overrides ONLY `window.crypto.getRandomValues` - the single entropy
* source `RevealDraw`'s production `randomSeedSalt()` calls - so every
* byte array it fills is deterministic. Every other real function in the
* commit-reveal chain (`commit`, `reveal`, `verify`, `drawOutcome`, the
* real SHA-256 via `crypto.subtle.digest`) runs completely unmodified:
* this is the one deliberate control a Playwright test can apply from
* outside the page to make an otherwise-genuinely-random draw
* reproducible, exactly as `generateSeedSalt` does for the Vitest unit
* tests (which can't reach the production route at all).
*
* Deliberately unconditional (not keyed to a call counter): some other
* real code path on this page may also call `getRandomValues` before or
* between RevealDraw's own two calls (confirmed empirically - a call-count
* based override shifted which call received which fill value and
* produced the wrong winner), so every call is simply filled with the
* same byte. That is harmless here: nothing else on this page's fair-draw
* route depends on unpredictable randomness.
*/
async function forceDrawOutcome(context, fill) {
await context.addInitScript((fill) => {
window.crypto.getRandomValues = function (arr) {
arr.fill(fill);
return arr;
};
}, fill);
}
async function runDraw(page) {
await page.goto(`${APP_URL}/miniapp/fair-draw`);
// FairDraw() shows "Loading identity..." until useActiveAccountId
// resolves - with the identity pre-seeded above this is effectively
// instant, but wait for the real button rather than assuming timing.
const startButton = page.getByRole("button", { name: "Start Draw" });
await startButton.waitFor();
await startButton.click();
const revealButton = page.getByRole("button", { name: "Reveal" });
await revealButton.waitFor();
await revealButton.click();
const revealed = page.getByTestId("reveal-draw-revealed");
await revealed.waitFor();
const winnerText = await page.getByTestId("reveal-draw-winner").innerText();
const badgeState = await page.getByTestId("reveal-draw-badge").getAttribute("data-state");
return { winnerText, badgeState };
}
async function runHappyPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "happy", steps: {} };
try {
await seedIdentity(context);
await forceDrawOutcome(context, FILL_FOR_YOU_WINS);
const page = await context.newPage();
await page.goto(`${APP_URL}/`);
await page.waitForFunction(
() => document.querySelector('[data-testid="wallet-balance"]')?.textContent !== "--",
{ timeout: 10000 },
);
const initialBalance = await page.getByTestId("wallet-balance").innerText();
evidence.steps.initialBalanceOnHome = { initialBalance };
const { winnerText, badgeState } = await runDraw(page);
evidence.steps.drawResolved = { winnerText, badgeState };
if (badgeState !== "verified") {
throw new Error(`happy: expected a verified draw, got badge state "${badgeState}"`);
}
if (winnerText !== "Winner: You") {
throw new Error(`happy: expected "Winner: You", got "${winnerText}"`);
}
// Assert on the SAME page, still on /miniapp/fair-draw, with no
// navigation and no reload: the compact WalletCard's balance updates
// live via Dexie liveQuery, proving this is not a page-refresh-only
// change.
const balanceLocator = page.getByTestId("wallet-balance");
await page.waitForFunction(
() => document.querySelector('[data-testid="wallet-balance"]')?.textContent === "10",
{ timeout: 10000 },
);
const balanceAfterWinLive = await balanceLocator.innerText();
evidence.steps.balanceUpdatedLiveWithoutReload = {
route: page.url(),
balanceAfterWinLive,
matchesRealPrizeAmount: balanceAfterWinLive === "10",
};
if (balanceAfterWinLive !== "10") {
throw new Error(`happy: expected live balance "10", got "${balanceAfterWinLive}"`);
}
// Client-side-only navigation (SPA route change, not page.goto/reload)
// to the home route, where the full (non-compact) WalletCard shows the
// real transaction history row for the same entry.
await page.getByRole("link", { name: "Back to home" }).click();
const historyRow = page.getByTestId("history-entry").first();
await historyRow.waitFor();
const historyRowText = await historyRow.innerText();
evidence.steps.transactionHistoryRowAfterClientSideNavigation = {
route: page.url(),
historyRowText,
showsIssuedCredit: historyRowText.includes("Issued") && historyRowText.includes("+10"),
};
if (!evidence.steps.transactionHistoryRowAfterClientSideNavigation.showsIssuedCredit) {
throw new Error(`happy: expected a real "Issued +10" history row, got "${historyRowText}"`);
}
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await context.close();
}
}
async function runNonWinnerPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "non-winner", steps: {} };
try {
await seedIdentity(context);
await forceDrawOutcome(context, FILL_FOR_RESIDENT_D_WINS);
const page = await context.newPage();
await page.goto(`${APP_URL}/`);
await page.waitForFunction(
() => document.querySelector('[data-testid="wallet-balance"]')?.textContent !== "--",
{ timeout: 10000 },
);
const initialBalance = await page.getByTestId("wallet-balance").innerText();
evidence.steps.initialBalanceOnHome = { initialBalance };
if (initialBalance !== "No balance yet") {
throw new Error(
`non-winner: expected a fresh identity's starting balance to read "No balance yet" (WalletCard never fabricates a "0" for an account the ledger has not seen), got "${initialBalance}"`,
);
}
const { winnerText, badgeState } = await runDraw(page);
evidence.steps.drawResolved = { winnerText, badgeState };
if (badgeState !== "verified") {
throw new Error(`non-winner: expected a verified draw, got badge state "${badgeState}"`);
}
if (winnerText !== "Winner: Resident D") {
throw new Error(`non-winner: expected "Winner: Resident D" (You must lose), got "${winnerText}"`);
}
// Give any (incorrect) wallet-credit side effect a real chance to land
// before asserting it never happened - same real Dexie liveQuery path
// the happy scenario's positive assertion relies on, just checked for
// absence instead of presence.
await page.waitForTimeout(300);
const balanceAfterLoss = await page.getByTestId("wallet-balance").innerText();
evidence.steps.ownWalletUnaffectedOnFairDrawRoute = {
balanceAfterLoss,
stillNoBalanceYet: balanceAfterLoss === "No balance yet",
};
if (balanceAfterLoss !== "No balance yet") {
throw new Error(
`non-winner: expected your own wallet to stay "No balance yet" after losing (no wallet.issue event ever touched this account), got "${balanceAfterLoss}"`,
);
}
await page.getByRole("link", { name: "Back to home" }).click();
const emptyHistory = page.getByText("No transactions yet");
await emptyHistory.waitFor();
evidence.steps.transactionHistoryStillEmptyAfterLoss = {
route: page.url(),
emptyStateVisible: await emptyHistory.isVisible(),
noHistoryEntryRows: (await page.getByTestId("history-entry").count()) === 0,
};
if (!evidence.steps.transactionHistoryStillEmptyAfterLoss.noHistoryEntryRows) {
throw new Error("non-winner: expected zero history-entry rows for the losing participant's own wallet");
}
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await context.close();
}
}
async function main() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const results = {};
let failed = false;
try {
try {
results.happy = await runHappyPath(browser);
} catch (e) {
failed = true;
results.happy = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
try {
results.nonWinner = await runNonWinnerPath(browser);
} catch (e) {
failed = true;
results.nonWinner = e.evidence ?? { scenario: "non-winner", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
}
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow-polish");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(evDir, "task-13-the-commons-hollow-polish.json"),
JSON.stringify(
{
task: "13. Make the wallet genuinely move (Fair Draw -> real wallet credit)",
qa: "happy",
description:
"A real Fair Draw commit-reveal-verify-drawOutcome round is run on the real '/miniapp/fair-draw' route with the device's own identity deterministically forced to win (only window.crypto.getRandomValues is overridden - the real commit/verify/drawOutcome functions from src/lib/fairdraw.ts all run unmodified). The compact WalletCard's balance updates live, with no navigation or reload, from '0' to the real FAIR_DRAW_PRIZE_AMOUNT (10), then a client-side-only SPA navigation to '/' (no page.goto/reload) reveals the real signed wallet.issue transaction in the full TransactionHistory.",
tool: "Playwright (chromium), real Vite dev server, real app UI ('/miniapp/fair-draw' -> RevealDraw, then '/' -> WalletCard/TransactionHistory)",
run_command: "node e2e/fairDrawWalletCredit.e2e.mjs",
selectors_used: [
"reveal-draw-revealed",
"reveal-draw-winner",
"reveal-draw-badge",
"wallet-balance",
"history-entry",
],
timestamp: now,
result: results.happy,
pass: Boolean(results.happy && results.happy.pass),
},
null,
2,
),
);
writeFileSync(
resolve(evDir, "task-13-the-commons-hollow-polish-non-winner.json"),
JSON.stringify(
{
task: "13. Make the wallet genuinely move (Fair Draw -> real wallet credit)",
qa: "failure/non-winner",
description:
"The same deterministic override instead forces a different participant ('Resident D') to win the real draw, so the device's own identity ('You') genuinely loses. Asserts the device's own WalletCard balance stays '0' (live, no reload) and the full TransactionHistory still shows zero real history-entry rows after navigating home - a losing participant's wallet is never touched, only the real winner's.",
tool: "Playwright (chromium), real Vite dev server, real app UI ('/miniapp/fair-draw' -> RevealDraw, then '/' -> WalletCard/TransactionHistory)",
run_command: "node e2e/fairDrawWalletCredit.e2e.mjs",
selectors_used: [
"reveal-draw-revealed",
"reveal-draw-winner",
"reveal-draw-badge",
"wallet-balance",
"history-entry",
],
timestamp: now,
result: results.nonWinner,
pass: Boolean(results.nonWinner && results.nonWinner.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULTS =====");
console.log(JSON.stringify(results, null, 2));
console.log(
`\nSUMMARY: happy=${results.happy && results.happy.pass ? "PASS" : "FAIL"} non-winner=${
results.nonWinner && results.nonWinner.pass ? "PASS" : "FAIL"
}`,
);
if (failed || !(results.happy && results.happy.pass) || !(results.nonWinner && results.nonWinner.pass)) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});