# IMDPicks native checkout — failure and recovery browser test Tested [commit `40669c610dc527649625874cc0bca769ae6b1b2e`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/commit/40669c610dc527649625874cc0bca769ae6b1b2e). `npm ci` and `VITE_PAID_RESEARCH_OPEN=true npm run build` passed. The build runs `tsc --noEmit` and Vite, and writes to the checkout's top-level `dist/`. I served that directory over localhost and ran Playwright 1.65.1 with headless Chromium 159.0.8154.6. Chromium ran after supplying a writable temporary directory and missing runtime libraries. [Build script](https://raw.githubusercontent.com/identity-md-launches/goal-3534-imdpicks-critical-payment/40669c610dc527649625874cc0bca769ae6b1b2e/web/package.json) The production baseline at `741da4053db911b89b94b902c37c0df8460dadc2` mounts escrow checkout. The candidate uses the customer wallet on chain 1 for optional IMD approval and Intake `request` with `job.open@job-1`, then reads public RPC, IMD APIs and artifact hosts. Native checkout ran without an IMDPicks backend or verifier key. The guide reserves verifier authorization for historical escrow settlement. No Mainnet transaction or publication occurred. [Production entry point](https://github.com/AgentStewLC/launch-3500-imd-picks-complete/blob/741da4053db911b89b94b902c37c0df8460dadc2/web/src/main.tsx#L204) · [Signing and hosting guide](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/docs/IMD_NATIVE_FLOW.md#L19) ## Observed browser walk Each purchase branch began in a fresh browser context. I clicked “Select events,” selected “Fixture Owls at Fixture Foxes,” opened “Continue to IMD checkout,” connected “Browser wallet,” checked the age acknowledgement, and clicked “Pay 1 IMD and start research.” Recovery links opened directly in separate contexts. The fixture price was 1 IMD. Result text below comes from the rendered page, with shared chrome and repetitive labels omitted. “Yes” in the payment column means the literal **order** badge “Payment confirmed by IMD.” In those cases the fixture supplied a matching canonical receipt and IMD order status `paid`. No row showed the “Report ready” status or explicitly marked the report completed. The wrong-job row nevertheless displayed positive verification copy about a report it had rejected. | Step | Result | Visible text and observed behavior | Payment badge | Completed / report ready | |---|---|---|---|---| | Reject the IMD approval | Pass | “Research checkout” stayed open. “Request declined in the wallet.” “Your wallet will first ask you to approve the quoted IMD amount.” “Pay 1 IMD and start research” became enabled again. The wallet saw one approval request and zero Intake requests. | No | No / No | | Approve IMD, then reject the Intake payment | Fail | “Request declined in the wallet.” “Pay 1 IMD and start research” became enabled again, which is safe after this explicit rejection. Checkout incorrectly retained “Your wallet will first ask you to approve the quoted IMD amount.” The fixture had already mined the approval and set the allowance. The wallet saw one approval request and one rejected Intake request. | No | No / No | | Intake payment transaction reverts | Pass | “Research failed,” “Transaction · 0xbbbb…bbbb,” “request-reverted,” “Retry confirmation.” No Pay button or Intake API read. | No | No / No | | Intake entry is refused | Pass | “Research refused,” “request-refused,” “Retry confirmation.” The fixture included the matching transfer and request receipt, with the IMD order marked `refused`. No Pay button. | No | No / No | | Intake entry fails after payment, before admission | Pass | “Research failed · Payment confirmed by IMD,” “Your confirmed order: 0x1111111111111111111111111111111111111111,” “request-failed,” “Retry confirmation.” No Pay button. | Yes | No / No | | Job fails after admission | Pass | “Swarm research · Payment confirmed by IMD” appeared with “Job ID: 11111111-1111-4111-8111-111111111111.” I changed the two job responses from running to failed and clicked “Retry confirmation.” Then “Research failed · Payment confirmed by IMD” and “job-failed.” The job link kept the original transaction. No Pay button. | Yes | No / No | | API responds 429 | Pass | “Awaiting IMD confirmation,” “rate-limited,” “Confirmation may take time. Keep this link; do not pay again while it is pending.” “Retry confirmation.” No Pay button. With `Retry-After: 45`, there was no second Intake read at the 38-second clock checkpoint. | No | No / No | | API responds 500 on the next two polls | Pass | Both polls left “Awaiting IMD confirmation,” “api-unavailable,” the same “do not pay again” instruction, and “Retry confirmation.” No Pay button. | No | No / No | | API recovers | Pass | Automatic polling resumed without another click, the URL changed to the admitted job with the original transaction attached, and the page displayed “Swarm research · Payment confirmed by IMD” and “Job ID: 11111111-1111-4111-8111-111111111111.” The fixture's job was running. | Yes, after recovery | No / No | | Reopen checkout for the same selection while research is still running | Fail | “Earlier requests from this wallet” and “Open request 0xbbbb…bbbb” appeared alongside an enabled “Pay 1 IMD and start research.” Clicking Pay reopened the original job. The wallet log still had only the original Intake request. | Checkout had no badge, original job had the badge | No / No | | Complete result, wrong `report.json` hash | Pass | “Verifying report · Payment confirmed by IMD,” “Verified partial report. Completion is not confirmed yet.” “report.json: not verified (SHA-256 mismatch)” and “missing structured output: no verified report.json (historical Markdown-only delivery is shown as text only)” The ledger showed “hash verified · 98 bytes” for Markdown and “hash does not match, not shown · 13 bytes” for JSON. The page showed “Fixture research,” “Synthetic research excerpt. Fixture source.” and “Download report” for verified Markdown. No structured predictions or Pay button. All four gateway fixtures returned the same wrong JSON bytes. | Yes | No / No | | Completion snapshot names a different job | Fail | “Verifying report · Payment confirmed by IMD,” “snapshot is for job 22222222-2222-4222-8222-222222222222, not 11111111-1111-4111-8111-111111111111.” It still showed “Swarm report” and “Verified: the report's bytes match the hash the Swarm wrote on Ethereum. Open the original.” The tracker fetched only the snapshot. No artifact, predictions, or Pay button appeared. | Yes, for the original order | No / No | | Open `#/job/` without a transaction | Pass | “Recover research,” “A job ID alone does not confirm payment. Enter the Intake transaction hash.” “Intake transaction hash,” “Recover research.” The form had no usable submit action until a valid hash was entered. No IMD API call, wallet send, or Pay button. | No | No / No | | Open `#/tx/` that never appears in the fixture | Pass | Before and after “Retry confirmation,” “Awaiting IMD confirmation,” “Transaction · 0xeeee…eeee,” “Confirmation may take time. Keep this link; do not pay again while it is pending.” “read-unavailable.” The retry read the receipt again. No Intake API call, wallet send, or Pay button. | No | No / No | | Additional check with a failed Intake entry, existing admission and a still-running job/result | Fail | “Awaiting IMD confirmation · Payment confirmed by IMD,” “job-completion-disagreement,” and “Confirmation may take time. Keep this link; do not pay again while it is pending.” The fixture supplied a terminal Intake state. No Pay button. | Yes | No / No | Playwright advanced browser timers during API recovery. The synthetic completion snapshot matched the on-chain Keccak-256 fixture. Only the corrupt JSON bytes differed from the declared SHA-256, at the same length. The IPFS URLs were intercepted aliases. [Receipt and API reader](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/native/client.ts#L63) · [Artifact verification](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/swarm.ts#L789) ### Console errors The browser emitted these three errors during the API outage, in order. No other console errors or uncaught page errors were recorded in the completed run. ```text Failed to load resource: the server responded with a status of 429 (Too Many Requests) Failed to load resource: the server responded with a status of 500 (Internal Server Error) Failed to load resource: the server responded with a status of 500 (Internal Server Error) ``` ## Defects and causes 1. **An unfinished order still gets a Pay invitation.** Earlier orders are fetched for the recovery list, but `canPay` does not depend on a matching unresolved saved order. Checkout renders the enabled Pay control alongside the recovery button. Clicking Pay happened to be protected by `earlierOrder`, which runs before a wallet write and returned the existing transaction through reconciliation. The violation here was the invitation. The test recorded no duplicate wallet send. [`checkout.tsx:77`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/checkout.tsx#L77) · Related lines `checkout.tsx:97`, `checkout.tsx:219`, `native/payment.ts:185`, `native/payment.ts:228`. 2. **A rejected payment leaves stale approval copy.** The checkout quote refresh depends on address, body, and quote version. The rejection handler refreshes wallet balances and saved orders, leaving the original quote in place. The approval guidance still reads the pre-approval allowance from that quote, even though the payment code had already confirmed the approval and fetched a fresh allowance. [`checkout.tsx:63`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/checkout.tsx#L63) · Related lines `checkout.tsx:165`, `checkout.tsx:218`, `native/payment.ts:248`. 3. **Rejected wrong-job snapshot produces positive report verification copy.** The reader rejects the job identity and returns `complete: false` with zero artifacts, while preserving the snapshot's `hashOk: true`. The native view mounts `ReportView` even when there is no verified report content. `verifyNote` then uses its generic report-bytes success copy. Only the snapshot bytes matched, and the snapshot belonged to the other job. [`swarm.ts:798`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/swarm.ts#L798) · Related lines `native/view.tsx:193`, `pages.tsx:290`. 4. **A failed Intake entry with stale running job data looks pending.** With admission present, the reader reconciles the Intake state against the job and result. For a terminal Intake entry and a nonterminal job, it throws `job-completion-disagreement` and returns the pending snapshot. Keeping completion gated is appropriate. The UI loses the distinction between this conflict involving a failed order and ordinary pending confirmation. The fixture establishes the UI behavior under disagreement. It does not establish that production endpoints return this combination. [`native/client.ts:219`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/native/client.ts#L219) · Related lines `native/client.ts:237`, `native/client.ts:273`. 5. **A modern delivery with corrupt JSON gets a historical-delivery hint.** The partial-report behavior is correct, but the diagnostic hard-codes “historical Markdown-only delivery is shown as text only” whenever verified JSON is absent, including when a new snapshot declares JSON and the file fails integrity verification. [`swarm.ts:836`](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/web/src/swarm.ts#L836) ## What this run establishes Fixtures cannot prove live Ethereum payment, deployed Intake behavior or price, live indexing and authorization, real wallet prompts, production CORS or gateway availability, refunds, Swarm delivery or staffing, or research and citation quality. The recovery fixture stopped at a running job. A verified full report and a fresh live payment-to-report run were **not run** in this failure item. Production release remains unverified. The owner would need to identify and authorize the static deployment and authorize the payer and spend for a controlled live run on the merged candidate. [Operating guide and verification requirements](https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment/blob/40669c610dc527649625874cc0bca769ae6b1b2e/docs/IMD_NATIVE_FLOW.md#L25) ## Reproduction Run in scratch with Node, npm, Chromium OS libraries and a writable temporary directory. The harness serves localhost, intercepts upstream requests and fails on unmapped requests. Each context emits a JSON record of visible text, wallet calls, requests and errors. A zero exit means the harness completed, including reproducing the defects above. ```sh git clone https://github.com/identity-md-launches/goal-3534-imdpicks-critical-payment repo git -C repo checkout 40669c610dc527649625874cc0bca769ae6b1b2e (cd repo/web && npm ci && VITE_PAID_RESEARCH_OPEN=true npm run build) mkdir -p browser tmp npm install --prefix browser playwright@1.65.1 export TMPDIR="$PWD/tmp" export PLAYWRIGHT_BROWSERS_PATH="$PWD/browser/browsers" browser/node_modules/.bin/playwright install chromium # Save the following JavaScript block as walk.mjs beside repo/ and browser/. node walk.mjs > walk.jsonl ``` ```js import assert from 'node:assert/strict'; import { chromium } from './browser/node_modules/playwright/index.mjs'; import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; import { join, extname } from 'node:path'; import { parseAbi, toFunctionSelector, decodeFunctionData, encodeEventTopics, encodeAbiParameters, parseAbiParameters, keccak256, sha256, stringToHex, } from './repo/web/node_modules/viem/_esm/index.js'; const dir = new URL('./repo/dist/', import.meta.url).pathname; const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.json': 'application/json', '.png': 'image/png', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2' }; const server = createServer(async (req, res) => { const path = join(dir, new URL(req.url, 'http://localhost').pathname.replace(/^\/$/, '/index.html')); try { const bytes = await readFile(path); res.writeHead(200, { 'Content-Type': mime[extname(path)] ?? 'application/octet-stream' }); res.end(bytes); } catch { res.writeHead(404).end(); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const origin = 'http://127.0.0.1:' + server.address().port; const hash = x => '0x' + x.repeat(64); const address = x => '0x' + x.repeat(40); const qty = x => '0x' + BigInt(x).toString(16); const enc = (types, values) => encodeAbiParameters(parseAbiParameters(types), values); const payer = address('1'), treasury = address('2'); const intake = '0xa43e6f75ee006411f79ac1c84120606c2330de82'; const imd = '0xd34a99bc0f67ae1bbd63c660e6d0b0dd03e263b7'; const amount = 10n ** 18n, start = 26518000; const approval = hash('a'), payment = hash('b'), completion = hash('c'); const requestId = hash('d'), missing = hash('e'); const job = '11111111-1111-4111-8111-111111111111'; const other = '22222222-2222-4222-8222-222222222222'; const txFor = (id, n) => ({ hash: id, blockNumber: qty(n), blockHash: blockHash(n), from: payer, to: id === approval ? imd : intake, value: '0x0', chainId: '0x1', nonce: '0x1', transactionIndex: '0x0', type: '0x2' }); const blockHash = n => '0x' + BigInt(n).toString(16).padStart(64, '0'); const reqSig = 'request(bytes32,bytes,(address,bytes4),address,uint256)'; const abi = parseAbi([ 'function request(bytes32 action, bytes body, (address target, bytes4 selector) callback, address asset, uint256 amount) payable returns (bytes32)', 'event Requested(bytes32 indexed requestId, address indexed payer, bytes32 indexed action, bytes body, address callbackTarget, bytes4 callbackSelector, address asset, uint256 amount)', 'event Completed(bytes32 indexed requestId, uint8 status, bytes32 resultHash, string uri, bool delivered)', 'event Transfer(address indexed from, address indexed to, uint256 value)', ]); const log = (id, n, i, address, eventName, args, types, data) => ({ ...txFor(id,n), transactionHash: id, logIndex: qty(i), address, removed: false, topics: encodeEventTopics({ abi, eventName, args }), data: enc(types,data), }); const uri = 'ipfs://fixture/snapshot.json'; const md = '# Fixture research\n\nSynthetic research excerpt. [Fixture source](https://example.invalid/source).\n'; const json = '{"fixture":1}'; const file = (name, text, mediaType) => ({ name, mediaType, url: 'ipfs://fixture/' + name, bytes: Buffer.byteLength(text), hash: sha256(Buffer.from(text)) }); const eventStart = new Date(Date.now() + 86400000).toISOString(); const scoreboard = { events: [{ id: '401000001', competitions: [{ id: '401000001', date: eventStart, competitors: [ { homeAway: 'away', team: { displayName: 'Fixture Owls' } }, { homeAway: 'home', team: { displayName: 'Fixture Foxes' } }, ] }] }] }; const rpcHosts = new Set(['ethereum-rpc.publicnode.com', 'gateway.tenderly.co', 'rpc.mevblocker.io', 'eth.llamarpc.com', 'cloudflare-eth.com']); const gates = new Set(['ipfs.filebase.io','gateway.pinata.cloud','dweb.link','ipfs.io']); let browser; async function walk(mode) { const ctx = await browser.newContext({ locale: 'en-US', timezoneId: 'UTC', serviceWorkers: 'block' }); const page = await ctx.newPage(); const errors = [], unexpected = [], wallet = [], views = [], api = [], ipfs = []; let missingReads = 0; let allowance = mode.startsWith('reject') ? 0n : amount, sent, intakeHits = 0, jobFailed = false; const snapshot = JSON.stringify({ jobId: mode === 'wrong-job' ? other : job, state: 'completed', complete: true, files: [ file('report.md', md, 'text/markdown'), file('report.json', json, 'application/json'), ] }); const resultHash = keccak256(Buffer.from(snapshot)); const completing = ['bad-json', 'wrong-job'].includes(mode); const receipt = (id, n, reverted, logs) => ({ ...txFor(id,n), transactionHash: id, status: reverted ? '0x0' : '0x1', logs }); function paymentLogs() { const [action, body, callback, asset, value] = decodeFunctionData({ abi, data: sent.data }).args; assert.equal(action, stringToHex('job.open@job-1', { size: 32 })); assert.equal(asset.toLowerCase(), imd); assert.equal(value, amount); return [ log(payment,start,0,imd,'Transfer',[payer,treasury],'uint256',[value]), log(payment,start,1,intake,'Requested',[requestId,payer,action], 'bytes,address,bytes4,address,uint256',[body,callback.target,callback.selector,asset,value]), ]; } function rpc({ method, params = [] }) { switch (method) { case 'eth_chainId': return '0x1'; case 'eth_blockNumber': return qty(start + 10); case 'eth_gasPrice': return qty(1000000000); case 'eth_getBalance': return qty(10n * amount); case 'eth_getLogs': return []; case 'eth_getBlockByNumber': { const n = params[0] === 'latest' ? start + 10 : Number(params[0]); return { number: qty(n), hash: blockHash(n), timestamp: qty(Math.floor(Date.now()/1000)), transactions: [], baseFeePerGas: qty(1000000000) }; } case 'eth_getTransactionReceipt': if (params[0] === missing) missingReads++; if (params[0] === approval && allowance) return receipt(approval,start,false,[]); if (params[0] === payment && sent) return receipt(payment,start,mode === 'revert', mode === 'revert' ? [] : paymentLogs()); if (params[0] === completion && completing) return receipt(completion,start+1,false,[ log(completion,start+1,0,intake,'Completed',[requestId], 'uint8,bytes32,string,bool',[0,resultHash,uri,true]) ]); return null; case 'eth_getTransactionByHash': return params[0] === payment && sent ? { ...txFor(payment,start), input: sent.data } : null; case 'eth_call': { const sig = params[0].data.slice(0,10); if (sig === toFunctionSelector('priceOf(bytes32,address)')) return enc('uint256',[amount]); if (sig === toFunctionSelector('allowance(address,address)')) return enc('uint256',[allowance]); if (sig === toFunctionSelector('balanceOf(address)')) return enc('uint256',[10n*amount]); if (sig === toFunctionSelector('payTo()')) return enc('address',[treasury]); if (sig === toFunctionSelector(reqSig)) return requestId; throw Error('Unknown call ' + sig); } default: throw Error('Unknown RPC ' + method); } } page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); }); page.on('pageerror', e => errors.push('Uncaught: ' + e.message)); await ctx.exposeBinding('walletFixture', (_, call) => { const {method, params} = call; if (['eth_accounts','eth_requestAccounts'].includes(method)) return {result:[payer]}; if (method === 'eth_chainId') return {result:'0x1'}; if (method === 'eth_getTransactionByHash') return {result:rpc(call)}; if (method === 'eth_sendTransaction') { const tx = params[0]; const approve = tx.to.toLowerCase() === imd; assert.equal(tx.data.slice(0,10), toFunctionSelector(approve ? 'approve(address,uint256)' : reqSig)); assert.equal(tx.to.toLowerCase(), approve ? imd : intake); if (approve) assert.equal(tx.data.slice(10), enc('address,uint256',[intake, amount]).slice(2)); wallet.push(approve ? 'approve' : 'request'); if ((approve && mode === 'reject-approval') || (!approve && mode === 'reject-payment')) return {reject:true}; if (approve) { allowance = amount; return {result:approval}; } sent = tx; return {result:payment}; } unexpected.push('Wallet ' + method); return {reject:true}; }); await ctx.addInitScript(() => { window.labelsSeen = []; new MutationObserver(() => { const status = document.querySelector('main p[role=status]'); if (status && !window.labelsSeen.includes(status.textContent)) window.labelsSeen.push(status.textContent); }).observe(document, {subtree:true, childList:true, characterData:true}); window.ethereum = { request: async call => { const r = await window.walletFixture(call); if (r.reject) throw Object.assign(new Error('User rejected the request'), {code:4001}); return r.result; } }; }); const cors = {'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*', 'Access-Control-Allow-Methods':'GET,POST,OPTIONS', 'Access-Control-Expose-Headers':'Retry-After'}; await ctx.route('**/*', async route => { const req = route.request(), u = new URL(req.url()); if (u.origin === origin) return route.continue(); const send = (status, body, headers = {}) => route.fulfill({status, headers:{...cors,...headers}, contentType:'application/json', body:JSON.stringify(body)}); try { if (req.method() === 'OPTIONS') return route.fulfill({status:204,headers:cors}); if (u.hostname === 'site.api.espn.com') return send(200, u.pathname.endsWith('/basketball/nba/scoreboard') ? scoreboard : {events:[]}); if (rpcHosts.has(u.hostname)) { const call = req.postDataJSON(); return send(200,{jsonrpc:'2.0', id:call.id, result:rpc(call)}); } if (u.hostname === 'api.imd.fun') { api.push(u.pathname); if (u.pathname === '/intake/1/' + payment) { intakeHits++; if (mode === 'recover' && intakeHits <= 3) { return send(intakeHits === 1 ? 429 : 500, {}, {'Retry-After':'45'}); } const state = mode === 'refused' ? 'refused' : mode.startsWith('entry-fail') ? 'failed' : completing ? 'completed' : 'admitted'; const entry = { requestId, logIndex:1, intake, blockNumber:start, kind:'request', payer, action:'job.open', actionVersion:'job-1', asset:imd, amount:String(amount), state, order:{status:state === 'refused' ? 'refused' : 'paid'} }; if (!['refused','entry-fail'].includes(mode)) entry.admission = {result:{kind:'job',jobId:job}}; if (completing) entry.completion = {state:'confirmed',txHash:completion,status:0,resultHash,uri,delivered:true}; return send(200,{chainId:1,transactionHash:payment,entries:[entry]}); } const state = jobFailed ? 'failed' : completing ? 'completed' : 'running'; if (u.pathname === '/jobs/' + job) return send(200,{id:job,paidBy:payer,state}); if (u.pathname === '/jobs/' + job + '/result') return send(200,{jobId:job,state,complete:completing}); } if (gates.has(u.hostname) && u.pathname.startsWith('/ipfs/fixture/')) { ipfs.push(u.hostname + u.pathname); const body = { 'snapshot.json':snapshot,'report.md':md,'report.json':'{"fixture":2}' }[u.pathname.split('/').at(-1)]; if (body !== undefined) return route.fulfill({status:200,headers:cors,body}); } if (['fonts.googleapis.com','fonts.gstatic.com'].includes(u.hostname)) return route.fulfill({status:200,headers:cors,contentType:'text/css',body:''}); throw Error('Unmapped request ' + req.method() + ' ' + req.url()); } catch(e) { unexpected.push(e.message); return route.abort(); } }); async function capture(want) { await page.getByText(want,{exact:true}).first().waitFor({timeout:15000}); const target = await page.getByRole('dialog').isVisible() ? page.getByRole('dialog') : page.locator('main'); views.push({hash:new URL(page.url()).hash, text:await target.innerText(), enabledPay:await page.getByRole('button',{name:/^Pay .*IMD/}).evaluateAll(bs => bs.some(b => !b.disabled))}); } try { if (['recover','missing'].includes(mode)) await page.clock.install(); if (mode === 'job-link' || mode === 'missing') { await page.goto(origin + (mode === 'job-link' ? '/#/job/' + job : '/#/tx/' + missing)); await capture(mode === 'job-link' ? 'A job ID alone does not confirm payment. Enter the Intake transaction hash.' : 'read-unavailable'); if (mode === 'missing') { const seen = missingReads; const nextReceipt = page.waitForResponse(r => r.request().method() === 'POST' && r.request().postDataJSON()?.params?.[0] === missing); await page.getByRole('button',{name:'Retry confirmation'}).click(); await nextReceipt; await capture('read-unavailable'); assert(missingReads > seen); } assert.deepEqual(api,[]); } else { await page.goto(origin); await page.getByRole('link',{name:'Select events',exact:true}).first().click(); await page.locator('.game-hit').filter({hasText:'Fixture Owls'}).click(); const open = () => page.getByRole('button',{name:'Continue to IMD checkout'}).first().click(); await open(); await page.getByRole('button',{name:'Connect a wallet to pay'}).click(); await page.getByRole('button',{name:'Browser wallet'}).click(); const pay = page.getByRole('button',{name:'Pay 1 IMD and start research',exact:true}); await page.getByRole('checkbox').check(); await pay.click({timeout:15000}); if (mode.startsWith('reject')) { await capture('Request declined in the wallet.'); } else if (mode === 'recover') { await capture('rate-limited'); await page.clock.fastForward(38000); assert.equal(intakeHits,1); await page.clock.fastForward(8000); await capture('api-unavailable'); const second500 = page.waitForResponse(r => r.url().includes('/intake/1/') && r.status() === 500); await page.clock.fastForward(36000); await second500; await capture('api-unavailable'); assert.equal(intakeHits,3); await page.clock.fastForward(37000); await page.waitForURL('**/job/' + job + '?tx=' + payment); await capture('Swarm research'); // Reopen the same selection from Home while the admitted job is running. await page.getByRole('link',{name:'IMD PICKS home'}).click(); await open(); await page.getByRole('checkbox').check(); await capture('Pay 1 IMD and start research'); await pay.click(); await page.waitForURL('**/job/' + job + '?tx=' + payment); await capture('Swarm research'); assert.deepEqual(wallet,['request']); } else { const want = { revert:'request-reverted', refused:'request-refused', 'entry-fail':'request-failed', 'entry-fail-admitted':'job-completion-disagreement', 'job-fail':'job-failed', 'bad-json':'report.json: not verified (SHA-256 mismatch)', 'wrong-job':'snapshot is for job ' + other + ', not ' + job, }[mode]; if (['job-fail','entry-fail-admitted','bad-json','wrong-job'].includes(mode)) await page.waitForURL('**/job/' + job + '?tx=' + payment); if (mode === 'job-fail') { await capture('Swarm research'); jobFailed = true; await page.getByRole('button',{name:'Retry confirmation'}).click(); } await capture(want); } } assert(views.every(v => !v.enabledPay || mode.startsWith('reject') || (mode === 'recover' && v.hash === '#/'))); const labelsSeen = await page.evaluate(() => window.labelsSeen); assert(!labelsSeen.some(s => /Report ready|^Completed/.test(s))); if (['reject-approval','reject-payment','revert','refused','job-link','missing'].includes(mode)) assert(!labelsSeen.some(s => s.includes('Payment confirmed by IMD'))); if (mode === 'wrong-job') assert(ipfs.every(s => s.endsWith('/snapshot.json'))); if (mode === 'bad-json') assert.equal(ipfs.filter(s => s.endsWith('/report.json')).length, 4); assert.deepEqual(unexpected,[]); assert.deepEqual(wallet, ({ 'reject-approval':['approve'], 'reject-payment':['approve','request'], 'missing':[], 'job-link':[], })[mode] ?? ['request']); } catch (e) { unexpected.push(String(e)); views.push({hash:new URL(page.url()).hash,text:await page.locator('body').innerText().catch(()=> '')}); process.exitCode = 1; } finally { console.log(JSON.stringify({mode,views,wallet,api,ipfs,errors,unexpected,intakeHits,resultHash})); await ctx.close(); } } try { browser = await chromium.launch({headless:true}); console.error('Chromium ' + browser.version()); const modes = ['reject-approval','reject-payment','revert','refused','entry-fail', 'job-fail','recover','bad-json','wrong-job','job-link','missing','entry-fail-admitted']; for (const mode of process.argv.slice(2).length ? process.argv.slice(2) : modes) await walk(mode); } finally { await browser?.close(); server.close(); } ```