import { BaseError, TransactionReceiptNotFoundError, zeroAddress, stringToHex, type Address, type EIP1193Provider, type Hash, type TransactionReceipt, type WalletClient, } from "viem"; import { CHAIN, CHAIN_ID, ESCROW, ESCROW_FROM_BLOCK, IMD, INTAKE, JOB_ACTION, erc20Abi, intakeAbi, publicClient } from "../config"; import { clientOrderId, escrowAbi, MAX_BODY_BYTES } from "../engine/sdk"; import { findOnchainDuplicate, getOrder, nonceOf, requestedIn, selectionIdOfBody, txState } from "../orders"; import { eventsOf, scanChunks } from "../swarm"; import { cancelNativeAttempt, nativeAttemptsOf, startNativeAttempt, updateNativeAttempt, type NativeAttempt, } from "./orders"; import { NATIVE_RESEARCH_OPEN } from "./policy"; const NO_CALLBACK = { target: zeroAddress, selector: "0x00000000" } as const; const PENDING = "The earlier request still needs confirmation on Ethereum. Check again before paying."; const same = (a?: string | null, b?: string | null) => !!a && !!b && a.toLowerCase() === b.toLowerCase(); type Reader = typeof publicClient; type Payment = { payer: Address; slipId: Hash; legacyId: Hash; body: string; amount: bigint; wallet: WalletClient; // Synchronous checks also run after a provider/RPC await, immediately before opening a wallet prompt. assertCurrent: () => void; assertFresh: () => void; checkSchedule: () => Promise; }; export type NativePaymentResult = | { kind: "submitted" | "reopen"; txHash: Hash } | { kind: "historical"; href: string } | { kind: "price"; amount: bigint }; export function validateNativeBody(body: string) { const bytes = new TextEncoder().encode(body); if (!bytes.length || bytes.length > MAX_BODY_BYTES) throw new Error("The research request exceeds the Intake body limit."); let input: { skill?: unknown; objective?: unknown }; try { input = JSON.parse(body); } catch { throw new Error("The research request must be JSON."); } if (input?.skill !== "research-report" || typeof input.objective !== "string" || !input.objective.trim() || input.objective.length > 8_000 || ["onchain", "steps", "template"].some((field) => Object.hasOwn(input, field))) { throw new Error("The research request needs a research-report objective of up to 8,000 characters."); } const events = eventsOf(body); const ids = new Set(events.map(({ path, espnId, start }) => `${path}/${espnId}@${Date.parse(start)}`)); if (events.length < 1 || events.length > 14 || ids.size !== events.length || events.some(({ path, espnId, start }) => !path || !espnId || !Number.isFinite(Date.parse(start)))) { throw new Error("The research request must contain 1 to 14 distinct scheduled events."); } return bytes.length; } const readPrice = (pc: Reader) => pc.readContract({ address: INTAKE, abi: intakeAbi, functionName: "priceOf", args: [JOB_ACTION, IMD] }); const readAllowance = (pc: Reader, payer: Address) => pc.readContract({ address: IMD, abi: erc20Abi, functionName: "allowance", args: [payer, INTAKE] }); const readBalance = (pc: Reader, payer: Address) => pc.readContract({ address: IMD, abi: erc20Abi, functionName: "balanceOf", args: [payer] }); const approvalCall = (payer: Address, amount: bigint) => ({ chain: CHAIN, account: payer, address: IMD, abi: erc20Abi, functionName: "approve", args: [INTAKE, amount], } as const); const requestCall = (payer: Address, body: string, amount: bigint) => ({ chain: CHAIN, account: payer, address: INTAKE, abi: intakeAbi, functionName: "request", args: [JOB_ACTION, stringToHex(body), NO_CALLBACK, IMD, amount], } as const); async function feeCap(pc: Reader) { const fees = await pc.estimateFeesPerGas().catch(() => undefined); return fees?.maxFeePerGas ?? pc.getGasPrice(); } export async function quoteNativePayment(payer: Address, body: string, pc = publicClient) { const bytes = validateNativeBody(body); const [amount, allowance, fee, balance, eth] = await Promise.all([ readPrice(pc), readAllowance(pc, payer), feeCap(pc), readBalance(pc, payer), pc.getBalance({ address: payer }), ]); // These fallbacks cover the measured approval and Intake requests when estimation is unavailable. const requestFallback = 30_000n + BigInt(bytes) * 40n; const needsApproval = amount > allowance; const units = needsApproval ? await pc.estimateContractGas(approvalCall(payer, amount)).catch(() => 55_000n) + requestFallback : await pc.estimateContractGas(requestCall(payer, body, amount)).catch(() => requestFallback); const gas = ((units * 6n + 4n) / 5n) * fee; return { amount, allowance, balance, eth, gas }; } async function checkWallet(p: Payment) { p.assertCurrent(); const [accounts, chain] = await Promise.all([p.wallet.getAddresses(), p.wallet.getChainId()]); p.assertCurrent(); if (chain !== CHAIN_ID || !same(accounts[0], p.payer)) { throw new Error("The wallet account or network changed. Review checkout again."); } } function nativeRequestIn(receipt: TransactionReceipt, payer: Address, body: string) { if (receipt.status !== "success" || !same(receipt.from, payer) || !same(receipt.to, INTAKE)) return null; const event = requestedIn(receipt)?.args; return event?.action === JOB_ACTION && same(event.payer, payer) && same(event.asset, IMD) && same(event.callbackTarget, NO_CALLBACK.target) && event.callbackSelector === NO_CALLBACK.selector && event.body === stringToHex(body) && event.amount > 0n ? event : null; } async function receiptOf(pc: Reader, hash: Hash) { try { return await pc.getTransactionReceipt({ hash }); } catch (error) { if (error instanceof TransactionReceiptNotFoundError) return null; throw error; } } /** Find the mined transaction occupying a known nonce, including replacements made while the tab was closed. */ async function minedAtNonce(pc: Reader, attempt: NativeAttempt, nonce: number) { const address = attempt.payer; let lo = BigInt(attempt.fromBlock); let hi = await pc.getBlockNumber({ cacheTime: 0 }); if (lo > hi || await pc.getTransactionCount({ address, blockNumber: hi }) <= nonce) return null; while (lo < hi) { const mid = (lo + hi) / 2n; if (await pc.getTransactionCount({ address, blockNumber: mid }) <= nonce) lo = mid + 1n; else hi = mid; } const block = await pc.getBlock({ blockNumber: lo, includeTransactions: true }); return block.transactions.find((tx) => same(tx.from, address) && tx.nonce === nonce) ?? null; } async function reconcile(pc: Reader, attempt: NativeAttempt) { const hash = attempt.txHash; if (!hash) { const [fromNonce, pendingNonce] = await Promise.all([ pc.getTransactionCount({ address: attempt.payer, blockNumber: BigInt(attempt.fromBlock) }), pc.getTransactionCount({ address: attempt.payer, blockTag: "pending" }), ]); return fromNonce === pendingNonce ? "retry" : "unknown"; } const original = await receiptOf(pc, hash); if (original) return original.status === "reverted" && same(original.from, attempt.payer) ? "retry" : "reopen"; const nonce = attempt.nonce ?? await nonceOf(hash); if (nonce === undefined) return "reopen"; if (attempt.nonce === undefined) updateNativeAttempt(attempt, { nonce }); const replacement = await minedAtNonce(pc, attempt, nonce); if (!replacement || same(replacement.hash, hash)) return "reopen"; const receipt = await receiptOf(pc, replacement.hash); if (!receipt) return "reopen"; updateNativeAttempt(attempt, { observedReplacementHash: replacement.hash }); const paid = nativeRequestIn(receipt, attempt.payer, attempt.body); if (paid?.amount === BigInt(attempt.amount)) { updateNativeAttempt(attempt, { replacementHash: replacement.hash }); return replacement.hash; } // Retry only after checking the selection against the historical ledger as well. return "retry"; } /** Resolve a replacement when reopening an order. A missing receipt can still be opened in the tracker. */ export async function reopenNativePayment(payer: Address, slipId: Hash, txHash: Hash, pc = publicClient) { const attempt = nativeAttemptsOf(payer, slipId).find((order) => same(order.txHash, txHash) || same(order.replacementHash, txHash)); if (!attempt) return txHash; const state = await reconcile(pc, attempt); return state.startsWith("0x") ? state as Hash : txHash; } async function findExistingOnchain(pc: Reader, p: Payment): Promise { // Intake logs for an escrow purchase name the escrow as payer. Read its historical OrderPaid ledger // for the customer and use the same eight attempt IDs as the legacy SDK. const escrow = ESCROW; const [direct, escrowOrders] = await Promise.all([ findOnchainDuplicate(p.payer, p.slipId, p.legacyId), escrow ? scanChunks((fromBlock, toBlock) => pc.getContractEvents({ address: escrow, abi: escrowAbi, eventName: "OrderPaid", args: { payer: p.payer }, fromBlock, toBlock, strict: true, }), ESCROW_FROM_BLOCK) : [], ]); p.assertCurrent(); const escrowIds = new Set(Array.from({ length: 8 }, (_, i) => clientOrderId(p.slipId, i))); if (escrowOrders.some((order) => escrowIds.has(order.args.clientOrderId))) return { kind: "historical", href: "#/mine" }; if (direct) { // The exact native body also lets this wallet reopen the tracker after clearing local storage. const receipt = await receiptOf(pc, direct.tx); const event = receipt && nativeRequestIn(receipt, p.payer, p.body); if (receipt && event) { const block = await pc.getBlock({ blockNumber: receipt.blockNumber }); p.assertCurrent(); const recovered = startNativeAttempt({ payer: p.payer, slipId: p.slipId, body: p.body, amount: event.amount.toString(), createdAt: Number(block.timestamp) * 1_000, }, receipt.blockNumber); updateNativeAttempt(recovered, { txHash: direct.tx }); return { kind: "reopen", txHash: direct.tx }; } p.assertCurrent(); return { kind: "historical", href: direct.block === undefined ? "#/mine" : `#/r/${direct.requestId}/${direct.block}` }; } const old = getOrder(p.slipId, p.payer, p.legacyId); if (old?.requestTx) { const { state } = await txState(old.requestTx, p.payer, old.nonces?.swarm, () => true); p.assertCurrent(); if (state !== "failed") return { kind: "historical", href: "#/mine" }; } return null; } async function earlierOrder(pc: Reader, p: Payment): Promise { const attempts = nativeAttemptsOf(p.payer, p.slipId); let uncertain = false; for (const attempt of attempts) { const state = await reconcile(pc, attempt); p.assertCurrent(); if (state === "unknown") uncertain = true; else if (state === "reopen") return { kind: "reopen", txHash: attempt.txHash! }; else if (state !== "retry") return { kind: "reopen", txHash: state }; } const historical = await findExistingOnchain(pc, p); if (historical) return historical; if (uncertain) throw new Error(PENDING); return null; } const inFlight = new Set(); async function withPaymentLock(payer: Address, run: () => Promise) { const key = "imd-picks:native-payment:" + payer.toLowerCase(); const busy = () => new Error("Checkout is already waiting for this wallet."); if (inFlight.has(key)) throw busy(); inFlight.add(key); try { const locks = globalThis.navigator?.locks; if (!locks) return await run(); return await locks.request(key, { ifAvailable: true }, (lock) => { if (!lock) throw busy(); return run(); }); } finally { inFlight.delete(key); } } const rejected = (error: unknown) => { const cause = error instanceof BaseError ? error.walk((e) => (e as { code?: number })?.code === 4001) : error; return (cause as { code?: number })?.code === 4001; }; export async function submitNativePayment(p: Payment, pc = publicClient): Promise { if (!NATIVE_RESEARCH_OPEN) throw new Error("New research purchases are paused."); validateNativeBody(p.body); if (selectionIdOfBody(p.body) !== p.slipId) throw new Error("The research request does not match the selection."); return withPaymentLock(p.payer, async () => { await checkWallet(p); const existing = await earlierOrder(pc, p); if (existing) return existing; await p.checkSchedule(); const quote = await quoteNativePayment(p.payer, p.body, pc); p.assertCurrent(); if (quote.amount !== p.amount) return { kind: "price", amount: quote.amount }; if (p.amount <= 0n) throw new Error("The Intake has no IMD quote for this request."); if (quote.balance < p.amount) throw new Error("Your wallet has insufficient IMD."); if (quote.eth < quote.gas) throw new Error("Your wallet has insufficient ETH for estimated gas."); if (quote.allowance < p.amount) { const beforeApproval = await readPrice(pc); p.assertCurrent(); if (beforeApproval !== p.amount) return { kind: "price", amount: beforeApproval }; await checkWallet(p); p.assertFresh(); const approval = await p.wallet.writeContract(approvalCall(p.payer, p.amount)); let cancelled = false; const receipt = await pc.waitForTransactionReceipt({ hash: approval, timeout: 120_000, onReplaced: ({ reason }) => { cancelled = reason === "cancelled"; }, }); if (cancelled || receipt.status !== "success") throw new Error("The IMD approval did not succeed."); await checkWallet(p); const earlier = await earlierOrder(pc, p); if (earlier) return earlier; await p.checkSchedule(); } const fresh = await quoteNativePayment(p.payer, p.body, pc); p.assertCurrent(); if (fresh.amount !== p.amount) return { kind: "price", amount: fresh.amount }; if (fresh.allowance < p.amount) throw new Error("The exact IMD approval is still required."); if (fresh.balance < p.amount) throw new Error("Your wallet has insufficient IMD."); if (fresh.eth < fresh.gas) { throw new Error("Your wallet has insufficient ETH for estimated gas."); } const simulation = await pc.simulateContract(requestCall(p.payer, p.body, p.amount)) .then((value) => ({ ok: true as const, value }), (error: unknown) => ({ ok: false as const, error })); const fromBlock = await pc.getBlockNumber({ cacheTime: 0 }); const pendingNonceOf = () => pc.getTransactionCount({ address: p.payer, blockTag: "pending" }).catch(() => undefined); const [price, beforeNonce] = await Promise.all([ readPrice(pc), pendingNonceOf(), ]); if (price !== p.amount) return { kind: "price", amount: price }; if (!simulation.ok) throw simulation.error; await checkWallet(p); p.assertFresh(); const attempt = startNativeAttempt({ payer: p.payer, slipId: p.slipId, amount: p.amount.toString(), body: p.body, createdAt: Date.now(), }, fromBlock); let hash: Hash; try { hash = await p.wallet.writeContract(simulation.value.request); } catch (error) { const declined = rejected(error); const afterNonce = declined || beforeNonce === undefined ? undefined : await pendingNonceOf(); if (declined || (afterNonce !== undefined && afterNonce === beforeNonce)) cancelNativeAttempt(attempt); throw error; } updateNativeAttempt(attempt, { txHash: hash }); // The hash is durable before any nonce lookup. Confirmation and job admission belong to the tracker. await rememberNonce(p.wallet, attempt, hash); return { kind: "submitted", txHash: hash }; }); } async function rememberNonce(wallet: WalletClient, attempt: NativeAttempt, hash: Hash) { const walletRpc = wallet.request as EIP1193Provider["request"]; const saved = nonceOf(hash, (h) => walletRpc({ method: "eth_getTransactionByHash", params: [h] })) .then((nonce) => { if (nonce !== undefined) updateNativeAttempt(attempt, { nonce }); }) .catch(() => { /* Reconciliation can recover the nonce later if the transaction becomes visible. */ }); // Give the wallet a short head start to provide the nonce without delaying tracker handoff on an RPC timeout. let timer: ReturnType | undefined; try { await Promise.race([saved, new Promise((resolve) => { timer = setTimeout(resolve, 1_500); })]); } finally { clearTimeout(timer); } }