diff --git a/api/qie_receipt_anchor.ts b/api/qie_receipt_anchor.ts new file mode 100644 index 0000000..a2cd568 --- /dev/null +++ b/api/qie_receipt_anchor.ts @@ -0,0 +1,180 @@ +import { buildUniversalReceipt } from "../crosschain/standards/index.js"; +import { hashObject } from "../lib/core/hash.js"; +import type { Ledger } from "../lib/ledger/index.js"; +import type { ExternalReceiptProofStore } from "../lib/x402/external_receipt_proof_store.js"; + +/** + * QIE x402 receipt anchoring — mirrors `algorand_receipt_anchor.ts` exactly, + * EVM-shaped: turns a settled QIE credit-report payment into the same + * Casper-rooted Universal Receipt used by the other satellite chains (Algorand, + * and whatever Base/Solana/Cosmos routes exist), plus the durable proof + * persistence and public usage aggregation that back the paid endpoint. + */ +export interface QieAnchorContext { + /** The current live ledger (rebuilt on reset — always pass the fresh one). */ + readonly ledger: Ledger; + /** Durable public receipt proofs (enabled with the production data dir). */ + readonly externalReceiptProofs?: ExternalReceiptProofStore; + /** The Cred402 seller agent id that receives the anchored credit-score revenue. */ + readonly sellerAgentId: string; +} + +/** A settled QIE credit-report payment awaiting a Casper-rooted anchor. */ +export interface QieCreditScoreSettlement { + agentId: string; + network: string; // CAIP-2, e.g. "eip155:1983" + networkName: string; // "testnet" | "mainnet" + assetAddress: string; // the QUSDC/test ERC-20 contract address on QIE + amountBaseUnits: string; + payer?: string; // 0x address + receiver: string; // 0x address + transaction?: string; // 0x tx hash + report: unknown; +} + +/** + * Convert a successful QIE x402 credit-report payment into the same + * Casper-rooted Universal Receipt used by the other satellite chains. + * + * The facilitator authenticates the payer address and transaction, but it + * does not assert a Cred402 agent id. Preserve that boundary by using an + * address-derived external identity. Repeated delivery of the same settled + * transaction returns the existing receipt without crediting revenue twice. + */ +export function anchorQieCreditScoreSettlement( + ctx: QieAnchorContext, + input: QieCreditScoreSettlement, +): { receipt_id: string } | null { + const payer = input.payer?.trim(); + const transaction = input.transaction?.trim(); + if (!payer || !transaction || !/^\d+$/.test(input.amountBaseUnits)) { + return null; + } + + const existing = ctx.ledger.externalReceipts.list().find( + (receipt) => + receipt.origin_chain === input.network && + receipt.settlement_tx_hash === transaction, + ); + if (existing) { + const sameSettlement = + existing.payer_agent_id === `qie:${payer}` && + existing.seller_agent_id === ctx.sellerAgentId && + existing.envelope.seller_address === input.receiver && + existing.asset === `qie-erc20:${input.assetAddress}` && + existing.amount === input.amountBaseUnits; + if (sameSettlement) { + persistExternalReceiptProof(ctx, existing.receipt_id); + return { receipt_id: existing.receipt_id }; + } + return null; + } + + const { envelope, receipt_id } = buildUniversalReceipt({ + origin_chain: input.network, + settlement_network: input.networkName, + payer_agent_id: `qie:${payer}`, + seller_agent_id: ctx.sellerAgentId, + payer_address: payer, + seller_address: input.receiver, + asset: `qie-erc20:${input.assetAddress}`, + amount: input.amountBaseUnits, + service_type: "credit-score", + request_hash: hashObject({ + method: "GET", + route: "/v1/x402/qie/credit-score/:agentId", + agent_id: input.agentId, + }), + result_hash: hashObject(input.report), + payment_proof_hash: hashObject({ + network: input.network, + transaction, + payer, + receiver: input.receiver, + amount_base_units: input.amountBaseUnits, + }), + settlement_tx_hash: transaction, + nonce: transaction, + created_at: ctx.ledger.clock.now(), + }); + + if (ctx.ledger.externalReceipts.get(receipt_id)) { + persistExternalReceiptProof(ctx, receipt_id); + return { receipt_id }; + } + + try { + // QIE settlement is provisional until independently confirmed against the + // configured QIE RPC (no Indexer-equivalent is confirmed to exist); only + // finalized receipts affect credit signals. + const anchored = ctx.ledger.anchorExternalReceipt(envelope, { finalize: false }); + persistExternalReceiptProof(ctx, anchored.receipt_id); + return anchored; + } catch { + // Payment delivery must not fail if the local/indexing layer is + // temporarily unavailable. The on-chain transaction remains canonical. + return null; + } +} + +export function finalizeQieExternalReceipt(ctx: QieAnchorContext, receiptId: string): void { + ctx.ledger.finalizeExternalReceipt(receiptId); + persistExternalReceiptProof(ctx, receiptId); +} + +export function challengeQieExternalReceipt(ctx: QieAnchorContext, receiptId: string): void { + ctx.ledger.challengeExternalReceipt(receiptId); + persistExternalReceiptProof(ctx, receiptId); +} + +/** Public, aggregate-only usage proof for the QIE challenge endpoint. */ +export function qieX402Usage(ctx: QieAnchorContext, network: string, assetAddress: string) { + const asset = `qie-erc20:${assetAddress}`; + const byId = new Map( + (ctx.externalReceiptProofs?.list() ?? []).map((receipt) => [receipt.receipt_id, receipt]), + ); + for (const receipt of ctx.ledger.externalReceipts.list()) byId.set(receipt.receipt_id, receipt); + const receipts = [...byId.values()] + .filter((receipt) => + receipt.origin_chain === network && + receipt.asset === asset && + receipt.service_type === "credit-score" && + receipt.status === "finalized", + ) + .sort((a, b) => b.anchored_at - a.anchored_at); + const totalBaseUnits = receipts.reduce( + (total, receipt) => total + BigInt(receipt.amount), + 0n, + ); + + return { + schema_version: "cred402.qie-x402-usage.v1", + network, + asset_address: assetAddress, + paid_requests: receipts.length, + unique_payers: new Set(receipts.map((receipt) => receipt.payer_agent_id)).size, + total_base_units: totalBaseUnits.toString(), + latest_payment_at: receipts[0] + ? new Date(receipts[0].anchored_at * 1000).toISOString() + : null, + latest_receipts: receipts.slice(0, 10).map((receipt) => ({ + receipt_id: receipt.receipt_id, + transaction: receipt.settlement_tx_hash, + amount_base_units: receipt.amount, + anchored_at: new Date(receipt.anchored_at * 1000).toISOString(), + })), + }; +} + +export function persistExternalReceiptProof(ctx: QieAnchorContext, receiptId: string): void { + if (!ctx.externalReceiptProofs) return; + const receipt = ctx.ledger.externalReceipts.get(receiptId); + if (!receipt) return; + try { + ctx.externalReceiptProofs.put(receipt); + } catch { + // The paid response and live ledger anchor remain valid even if the + // durability volume is temporarily unavailable. The proof endpoint can + // still serve the live registry until storage recovers. + } +} diff --git a/api/qie_x402_routes.ts b/api/qie_x402_routes.ts index 1dabdcc..8af905d 100644 --- a/api/qie_x402_routes.ts +++ b/api/qie_x402_routes.ts @@ -36,13 +36,16 @@ const qiePaymentAttempts = new QiePaymentAttemptStore( qieX402Config.enabled ? process.env.CRED402_DATA_DIR?.trim() : undefined, ); -async function reconcileQiePayment(paymentProofHash: string) { +async function reconcileQiePayment(state: State, paymentProofHash: string) { const attempt = qiePaymentAttempts.getByProofHash(paymentProofHash); if (!attempt?.settlement || !qieX402Config.enabled) return attempt; if (attempt.finality?.status === "confirmed" || attempt.finality?.status === "mismatch") return attempt; const { settlement } = attempt; if (!settlement.transaction) { + if (settlement.externalReceiptId) { + state.challengeQieExternalReceipt(settlement.externalReceiptId); + } return qiePaymentAttempts.recordFinality(paymentProofHash, { status: "mismatch", checkedAt: new Date().toISOString(), @@ -63,16 +66,32 @@ async function reconcileQiePayment(paymentProofHash: string) { amountBaseUnits: settlement.amountBaseUnits, }, ); - return qiePaymentAttempts.recordFinality(paymentProofHash, result); + const updated = qiePaymentAttempts.recordFinality(paymentProofHash, result); + if (result.status === "confirmed" && settlement.externalReceiptId) { + state.finalizeQieExternalReceipt(settlement.externalReceiptId); + } else if (result.status === "mismatch" && settlement.externalReceiptId) { + state.challengeQieExternalReceipt(settlement.externalReceiptId); + } + return updated; } -async function respondPaymentAttempt(res: ServerResponse, attemptId: string): Promise { +async function respondPaymentAttempt( + req: IncomingMessage, + res: ServerResponse, + state: State, + attemptId: string, + port: number, +): Promise { const attempt = qiePaymentAttempts.getByAttemptId(attemptId); if (!attempt) { json(res, 404, { error: "payment_attempt_not_found" }, { "Cache-Control": "no-store" }); return; } - const reconciled = attempt.status === "settled" ? await reconcileQiePayment(attempt.paymentProofHash) : attempt; + const reconciled = attempt.status === "settled" ? await reconcileQiePayment(state, attempt.paymentProofHash) : attempt; + const origin = qieX402Config.enabled + ? qieX402Config.config.publicBaseUrl ?? `http://${req.headers.host ?? `localhost:${port}`}` + : `http://${req.headers.host ?? `localhost:${port}`}`; + const receiptId = reconciled?.settlement?.externalReceiptId; json(res, 200, { schema_version: "cred402.qie-payment-attempt.v1", attempt_id: reconciled?.attemptId, @@ -86,6 +105,9 @@ async function respondPaymentAttempt(res: ServerResponse, attemptId: string): Pr } : null, transaction: reconciled?.settlement?.transaction ?? null, + external_receipt_url: receiptId + ? new URL(`/v1/x402/external-receipts/${encodeURIComponent(receiptId)}`, origin).href + : null, guidance: reconciled?.status === "indeterminate" ? "Do not submit another payment. Reconciliation against the configured QIE RPC is required." : undefined, @@ -238,8 +260,11 @@ async function respondCreditScore( amount_base_units: amountBaseUnits, payer: settlement.payer, transaction: settlement.transaction, + external_receipt_id: null, + external_receipt_url: null, payment_attempt_url: paymentAttemptUrl(claim.attempt.attemptId), qie_finality: "pending", + casper_anchor_status: "not_recorded", }; qiePaymentAttempts.settle(paymentProofHash, { network: settlement.network, @@ -251,13 +276,47 @@ async function respondCreditScore( responseHeaders: settlement.headers, resourceResponse: { ...report, payment: basePayment }, }); - const reconciled = settlement.transaction ? await reconcileQiePayment(paymentProofHash) : undefined; + const anchoredReceipt = state.anchorQieCreditScoreSettlement({ + agentId, + network: settlement.network, + networkName: qieX402Config.config.networkName, + assetAddress: qieX402Config.config.assetAddress, + amountBaseUnits, + payer: settlement.payer, + receiver: qieX402Config.config.payTo, + transaction: settlement.transaction, + report, + }); + const externalReceiptUrl = anchoredReceipt + ? new URL( + `/v1/x402/external-receipts/${encodeURIComponent(anchoredReceipt.receipt_id)}`, + publicUrl, + ).href + : null; + qiePaymentAttempts.settle(paymentProofHash, { + network: settlement.network, + asset: qieX402Config.config.assetAddress, + amountBaseUnits, + payer: settlement.payer, + receiver: qieX402Config.config.payTo, + transaction: settlement.transaction, + externalReceiptId: anchoredReceipt?.receipt_id, + responseHeaders: settlement.headers, + resourceResponse: { ...report, payment: basePayment }, + }); + const reconciled = settlement.transaction ? await reconcileQiePayment(state, paymentProofHash) : undefined; + const receiptStatus = anchoredReceipt + ? state.externalReceiptProof(anchoredReceipt.receipt_id)?.status ?? "anchored" + : "not_recorded"; const response = { ...report, payment: { ...basePayment, + external_receipt_id: anchoredReceipt?.receipt_id ?? null, + external_receipt_url: externalReceiptUrl, qie_finality: reconciled?.finality?.status ?? "unavailable", confirmations: reconciled?.finality?.confirmations ?? null, + casper_anchor_status: receiptStatus, }, }; qiePaymentAttempts.settle(paymentProofHash, { @@ -267,6 +326,7 @@ async function respondCreditScore( payer: settlement.payer, receiver: qieX402Config.config.payTo, transaction: settlement.transaction, + externalReceiptId: anchoredReceipt?.receipt_id, responseHeaders: settlement.headers, resourceResponse: response, }); @@ -296,7 +356,7 @@ export async function handleQieX402( const qieAttemptMatch = pathname.match(/^\/v1\/x402\/qie\/payments\/(payqie_[0-9a-f]{32})$/); if (qieAttemptMatch && req.method === "GET") { - await respondPaymentAttempt(res, qieAttemptMatch[1]!); + await respondPaymentAttempt(req, res, state, qieAttemptMatch[1]!, port); return true; } diff --git a/api/state.ts b/api/state.ts index 6a1053f..c3af0ed 100644 --- a/api/state.ts +++ b/api/state.ts @@ -79,6 +79,14 @@ import { type AlgorandAnchorContext, type AlgorandCreditScoreSettlement, } from "./algorand_receipt_anchor.js"; +import { + anchorQieCreditScoreSettlement, + finalizeQieExternalReceipt, + challengeQieExternalReceipt, + qieX402Usage, + type QieAnchorContext, + type QieCreditScoreSettlement, +} from "./qie_receipt_anchor.js"; /** * Server state — one persistent ledger + economy shared across all HTTP requests @@ -425,6 +433,37 @@ export class ServerState { algorandX402Usage(network: string, usdcAsset: string) { return algorandX402Usage(this.algorandAnchorContext(), network, usdcAsset); } + + /** Dependencies for the QIE x402 receipt-anchoring sub-domain, rebuilt + * fresh per call so the (reset-swappable) ledger + live seller id are current. */ + private qieAnchorContext(): QieAnchorContext { + return { + ledger: this.ledger, + externalReceiptProofs: this.externalReceiptProofs, + sellerAgentId: this.economy.seller.agent_id, + }; + } + + /** + * Convert a successful QIE x402 credit-report payment into the same + * Casper-rooted Universal Receipt used by the other satellite chains. + */ + anchorQieCreditScoreSettlement(input: QieCreditScoreSettlement): { receipt_id: string } | null { + return anchorQieCreditScoreSettlement(this.qieAnchorContext(), input); + } + + finalizeQieExternalReceipt(receiptId: string): void { + finalizeQieExternalReceipt(this.qieAnchorContext(), receiptId); + } + + challengeQieExternalReceipt(receiptId: string): void { + challengeQieExternalReceipt(this.qieAnchorContext(), receiptId); + } + + /** Public, aggregate-only usage proof for the QIE challenge endpoint. */ + qieX402Usage(network: string, assetAddress: string) { + return qieX402Usage(this.qieAnchorContext(), network, assetAddress); + } /** Anonymized, k-anonymous public credit-data commons snapshot (p6 data moat). */ dataCommons() { return new CreditDataCommons(this.ledger).snapshot(); diff --git a/docs/SUBMISSIONS.md b/docs/SUBMISSIONS.md index 94adccf..ad34cd9 100644 --- a/docs/SUBMISSIONS.md +++ b/docs/SUBMISSIONS.md @@ -260,6 +260,23 @@ unverified: [`qie_x402.md`](qie_x402.md). (`test/qie_x402.test.ts`) cover config fail-closing, the unpaid challenge shape, the client selector, the attempt store, and both finality outcomes; `npm test` and `npm run typecheck` are green with this code in the tree. Full write-up: [`qie_x402.md`](qie_x402.md). +- **Casper-anchoring: now built.** `api/qie_receipt_anchor.ts` mirrors + `algorand_receipt_anchor.ts` exactly — a settled QIE payment becomes the same + Casper-rooted Universal Receipt Envelope used by every other satellite chain + (`qie:` identity, `qie-erc20:` asset id), anchored provisional + (`finalize: false`) until `reconcileQiePayment`'s RPC check confirms it, then + finalized or challenged exactly like the Algorand path. Wired into + `api/state.ts` (`anchorQieCreditScoreSettlement` / + `finalizeQieExternalReceipt` / `challengeQieExternalReceipt` / + `qieX402Usage`) and `api/qie_x402_routes.ts` (the credit-score response now + carries `external_receipt_id`, `external_receipt_url`, and + `casper_anchor_status`, served through the same + `/v1/x402/external-receipts/:id` endpoint Algorand uses — receipt ids are a + shared, chain-agnostic content hash). 6 new unit tests + (`test/qie_receipt_anchor.test.ts`) exercise the anchor function directly + against a real `Ledger` (idempotent replay, conflicting-replay rejection, + finalize/challenge transitions, and usage aggregation); `npm test` (408/408) + and `npm run typecheck` stay green. - **Deliberately fails closed, not invented:** `CRED402_QIE_ASSET_ADDRESS` (QUSDC's ERC-20 contract address on QIE could not be independently confirmed by research — the route returns `503` rather than guessing one) and `CRED402_QIE_FACILITATOR_URL` (no default x402 diff --git a/docs/qie_x402.md b/docs/qie_x402.md index 8eca4e6..0a86859 100644 --- a/docs/qie_x402.md +++ b/docs/qie_x402.md @@ -132,11 +132,17 @@ facilitator — it mirrors `/v1/x402/algorand/status`. ## Known gaps vs. the Algorand integration (tracked, not hidden) -- No Casper anchoring of QIE settlements yet (the Algorand route anchors a - content-addressed external receipt proof to Casper via - `state.anchorAlgorandCreditScoreSettlement`; QIE settlements are durable in - the local attempt store but not yet anchored). Candidate follow-up: extract - a chain-agnostic version of that anchoring path. +- ~~No Casper anchoring of QIE settlements yet~~ **Built.** `api/qie_receipt_anchor.ts` + mirrors `algorand_receipt_anchor.ts`: `state.anchorQieCreditScoreSettlement` + turns a settled QIE payment into the same Casper-rooted Universal Receipt + Envelope every other satellite chain uses (`qie:` identity, + `qie-erc20:` asset), anchored provisional until + `reconcileQiePayment`'s RPC finality check confirms it, then finalized or + challenged. The credit-score response carries `external_receipt_id` / + `external_receipt_url` / `casper_anchor_status`; the proof is public at + `GET /v1/x402/external-receipts/:id` (the same endpoint Algorand's receipts + use — receipt ids are a shared content hash, not chain-specific). Covered + by `test/qie_receipt_anchor.test.ts` (6 tests, against a real `Ledger`). - No combined release-check / readiness script yet (Algorand has `x402:algorand:ready` and `x402:algorand:release-check`, which fetch live payer/receiver balances and write a signed evidence artifact). QIE has the diff --git a/lib/x402/qie_payment_attempt_store.ts b/lib/x402/qie_payment_attempt_store.ts index c800b0e..c8f9ba2 100644 --- a/lib/x402/qie_payment_attempt_store.ts +++ b/lib/x402/qie_payment_attempt_store.ts @@ -26,6 +26,7 @@ export interface StoredQieSettlement { payer?: string; receiver: string; transaction?: string; // 0x tx hash + externalReceiptId?: string; responseHeaders: Record; resourceResponse: unknown; } diff --git a/test/qie_receipt_anchor.test.ts b/test/qie_receipt_anchor.test.ts new file mode 100644 index 0000000..5790848 --- /dev/null +++ b/test/qie_receipt_anchor.test.ts @@ -0,0 +1,169 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { Ledger } from "../lib/ledger/index.js"; +import { + anchorQieCreditScoreSettlement, + finalizeQieExternalReceipt, + challengeQieExternalReceipt, + qieX402Usage, + type QieAnchorContext, +} from "../api/qie_receipt_anchor.js"; + +const SELLER = "cred402-seller"; +const NETWORK = "eip155:1983"; // QIE testnet +const ASSET = "0x00000000000000000000000000000000000001"; +const PAYER = "0x00000000000000000000000000000000000002"; +const RECEIVER = "0x00000000000000000000000000000000000003"; +const TX = "0x" + "a".repeat(64); + +function ctx(): QieAnchorContext { + return { ledger: new Ledger(), sellerAgentId: SELLER }; +} + +test("anchorQieCreditScoreSettlement rejects an incomplete settlement (no payer/transaction/amount) without touching the ledger", () => { + const c = ctx(); + assert.equal( + anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + receiver: RECEIVER, + report: { ok: true }, + }), + null, + ); + assert.equal(c.ledger.externalReceipts.list().length, 0); +}); + +test("anchorQieCreditScoreSettlement anchors a real settlement as provisional (anchored, not finalized)", () => { + const c = ctx(); + const result = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + }); + assert.ok(result); + const receipt = c.ledger.externalReceipts.get(result!.receipt_id); + assert.ok(receipt); + assert.equal(receipt!.status, "anchored"); + assert.equal(receipt!.origin_chain, NETWORK); + assert.equal(receipt!.payer_agent_id, `qie:${PAYER}`); + assert.equal(receipt!.seller_agent_id, SELLER); + assert.equal(receipt!.asset, `qie-erc20:${ASSET}`); + assert.equal(receipt!.amount, "10000"); + assert.equal(receipt!.settlement_tx_hash, TX); +}); + +test("anchorQieCreditScoreSettlement is idempotent for the same settled transaction (no double-credit)", () => { + const c = ctx(); + const first = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + }); + const second = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true, replayed: true }, + }); + assert.ok(first); + assert.ok(second); + assert.equal(first!.receipt_id, second!.receipt_id); + assert.equal(c.ledger.externalReceipts.list().length, 1); +}); + +test("anchorQieCreditScoreSettlement refuses a conflicting replay on the same transaction hash", () => { + const c = ctx(); + anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + }); + const conflict = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "99999", // different amount, same tx hash + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + }); + assert.equal(conflict, null); +}); + +test("finalizeQieExternalReceipt moves a provisional anchor to finalized, and only finalized receipts count toward usage", () => { + const c = ctx(); + const anchored = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + })!; + + let usage = qieX402Usage(c, NETWORK, ASSET); + assert.equal(usage.paid_requests, 0, "provisional (anchored, not finalized) receipts must not count yet"); + + finalizeQieExternalReceipt(c, anchored.receipt_id); + assert.equal(c.ledger.externalReceipts.get(anchored.receipt_id)!.status, "finalized"); + + usage = qieX402Usage(c, NETWORK, ASSET); + assert.equal(usage.paid_requests, 1); + assert.equal(usage.unique_payers, 1); + assert.equal(usage.total_base_units, "10000"); + assert.equal(usage.latest_receipts[0]!.receipt_id, anchored.receipt_id); +}); + +test("challengeQieExternalReceipt marks a finality mismatch, excluding it from usage even after finalize", () => { + const c = ctx(); + const anchored = anchorQieCreditScoreSettlement(c, { + agentId: "agent-1", + network: NETWORK, + networkName: "testnet", + assetAddress: ASSET, + amountBaseUnits: "10000", + payer: PAYER, + receiver: RECEIVER, + transaction: TX, + report: { ok: true }, + })!; + + challengeQieExternalReceipt(c, anchored.receipt_id); + assert.equal(c.ledger.externalReceipts.get(anchored.receipt_id)!.status, "challenged"); + + const usage = qieX402Usage(c, NETWORK, ASSET); + assert.equal(usage.paid_requests, 0); +});