Skip to content

feat(payment-anchor): verify an x402 anchor on chain, bound to its contract, once (shadow, default off) - #1572

Open
DealAppSeo wants to merge 3 commits into
mainfrom
claude/payment-anchor-verified-10203a
Open

DealAppSeo wants to merge 3 commits into
mainfrom
claude/payment-anchor-verified-10203a

Conversation

@DealAppSeo

Copy link
Copy Markdown
Owner

Owner action

Weight: MAJOR (money and anti-gaming, CLAUDE_RULES r31). You merge. Shipped shadow-only.

What changes on merge Nothing, unless PAYMENT_ANCHOR_VERIFY_MODE is set on the repid-engine service. Default is off: no read, no log, no write.
What shadow does Checks each payment anchor on chain and logs what it would refuse. Changes no delta, class or score.
What enforce does Refused in code. It runs as shadow and logs that it was refused. Turning it on is a separate MAJOR PR.
Draft migration (not applied) supabase/migrations/20261116130000_payment_anchor_claims.sql (replay table). Rollback is beside it. Until it is applied, a chain-verified anchor reports NOT_CHECKED replay_store_unreachable, never a pass.
Risk Shadow does one extra Base Sepolia receipt read per caller-supplied anchor, with a 10 s cap. It has no production caller today (see below), so the live cost is zero.
Rollback Unset the variable, or revert this PR.

Merge alone is safe. Applying the migration and setting shadow are separate decisions, and neither moves a score.


What this closes

E2E eval 2026-11-16, gap 4: a payment anchor was accepted on shape alone. linkPaymentProof checks for a 0x-prefixed 32-byte hash and a chain id, and nothing else unless the caller passes requireVerified. The eval passed a made-up hash through scripts/demo/trust-harness-e2e.mjs and an UNCERTAIN outcome became SUCCESS_AUDITED, delta +25.

What I re-verified before changing anything

  • The shape-only acceptance is real: x402-outcome-link.ts:88 (main: :79) only checks verified when asked.
  • One part of the eval's reading was wrong. It cites settled-interaction-scorer.ts:101 (requireVerifiedProof: false) as "the production caller". That line runs after resolvePaymentProof has read the receipt, and only a resolved proof gets past it. What the scorer lacked was contract binding, replay refusal and a clean RPC error. scoreSettledInteraction has no caller in src/ at all. So today no live score uses a caller-supplied anchor; the gap is in the shipped function and the demo, ahead of any caller.
  • Nothing refuses a replay anywhere. x402_settlements.tx_hash has a plain btree index, not a unique one. The grounding resolver's claims table, repid_grounding_claims, does not exist in prod (to_regclass = null), and no production caller passes it a chain reader.
  • The RPC error text leaked into score metadata, and into a script built to avoid exactly that. verifySettlement returned rpc error fetching receipt: ${e.message}, and the scorer writes that reason to metadata.payment.settlement_reason. Measured with ethers 6.16.0 against an RPC that answers 401: the message carries info={ "requestUrl": "<full URL, key included>" }. scripts/trust-loop/live-settlement-crosscheck.ts says it deliberately does not print the RPC URL, then prints result.reason. Fixed here: fixed codes only.
  • The payee is the provider's wallet_address, and the payer is not the buyer's own wallet. On the five most recent real settlements, every payee matched wallet_address, while erc8004_address held non-addresses (pending-mint:…, free text, a registry contract). Every payer was a custodian wallet, not the buyer agent's wallet_address. So the payer comes from x402_settlements.payer_address, which the facilitator verified from the signed authorization. Binding the payer to the buyer's wallet would have refused every real payment.

What the check does (src/services/payment-anchor-verify.ts)

The caller supplies only a tx hash, a chain id and a contract id. Payee, payer and price come from our own records (service_contracts, repid_agents.wallet_address, x402_settlements).

  1. Shape, and Base Sepolia only.
  2. The anchor names a contract we know (contract_unbound, contract_unknown).
  3. If the contract has a recorded settlement tx, the anchor must be that tx (contract_tx_mismatch).
  4. The tx has not anchored anything before: replay_same_contract / replay_other_contract. This is checked before the chain, so a known replay is refused even while the RPC is down.
  5. On chain: a canonical-USDC Transfer (address pinned) to the payee, of at least the price, from the recorded payer, net of anything the payee sent back in the same tx (refunded_in_tx), and not a self-payment. An EIP-3009 AuthorizationUsed beside it labels it an x402 settlement (settlement_kind: eip3009). That event names no payee or amount, so it never verifies anything alone.
  6. The tx is bound to the contract. The unique key (chain_id, tx_hash) is the authority: two concurrent presentations race on it, and the loser is refused as a replay.

Three answers. VERIFIED; REFUSED (we looked, and the answer is no); or NOT_CHECKED (RPC error or timeout, contract table unreadable, replay table missing, too few confirmations). NOT_CHECKED is never a pass and never a refusal, and it would not earn under enforce.

Wired into: scoreSettledInteraction, which records metadata.payment.anchor_check and leaves the delta alone, and the demo harness, which now prints the shadow verdict for the anchor it attaches. The harness was the eval's reproduction. x402-settlement-verifier.ts gains a code on every result and a log analysis (inflow per sender, payee outflow, EIP-3009 authorizers). These are additive and existing callers are unchanged.

Evidence (outputs under E:\dev\reports\2026-11-16\pay-anchor\)

  • Real transfer: the positive control is a real Base Sepolia x402 settlement (1.000000 USDC, transferWithAuthorization), recorded once with read-only RPC into tests/fixtures/payment-anchor/ and replayed offline. Every other case changes one thing about it.
  • Main vs branch. main's src (af0a7461) with the branch's tests, against the branch (7f8a75c2), from jest --json:
case (through scoreSettledInteraction) main branch
1. real transfer: VERIFIED, EIP-3009 fails (no check) passes
2. wrong recipient (our record names another payee) fails passes
3. too little (contract price above what moved) fails passes
4. replay (one real payment, second contract) fails passes
5. RPC down: NOT_CHECKED, no RPC text in the row fails passes
5b. RPC down, check off: RPC URL and key absent from row metadata fails: the URL and key are in settlement_reason passes
an anchor naming no contract is refused before any read fails passes
inertness: refused anchor, replayed anchor, off writes nothing passes passes
enforce is refused: same record as shadow, same delta fails passes
payment-anchor-verify.test.ts (28 unit tests: real fixture, recipient, payer, self-pay, wrong token, too little, refund-in-tx, replay incl. concurrent and RPC-down, contract-tx binding, 401 from a real ethers provider, timeout, unreadable tables, modes) cannot load (module absent) 28/28

Branch 39/39. Existing related suites on the branch: x402-settlement-verifier, settled-interaction-scorer, x402-outcome-link, ops-flags and prod-fixture-guard all pass. One red, env-typo-guard "finds the control…", is a 5 s timeout on a whole-tree scan, and it is identical on main's src on this Windows box: ENV, not REAL.

Live, read-only (the verifier against https://sepolia.base.org, contract terms inline, replay table in memory, nothing written): the real settlement is VERIFIED (eip3009, 1000000). Replay to the same contract and to another contract: both REFUSED. Wrong recipient: REFUSED transfer_elsewhere. Too little: REFUSED below_claimed_value. The eval's 0xabab…ab: REFUSED tx_not_found when bound, and contract_unbound when not.

  • Mutation check. Each mutation breaks one property, and the two suites must go red. 13 of 13 went red.
mutation result
M1 no replay pre-check 1 failed, 37 passed, 38 total
M2 bind always ok (no unique key) 6 failed, 32 passed, 38 total
M3 ignore the recorded payer 1 failed, 37 passed, 38 total
M4 ignore a refund in the same tx 1 failed, 37 passed, 38 total
M5 no contract-tx binding 1 failed, 37 passed, 38 total
M6 an RPC error counts as a refusal 1 failed, 37 passed, 38 total
M7 echo the RPC error text (main's behaviour) 2 failed, 36 passed, 38 total
M6b an unreachable RPC (verifier code) counts as a refusal 3 failed, 35 passed, 38 total
M8 skip the self-payment check 1 failed, 37 passed, 38 total
M9 off still runs the check 1 failed, 37 passed, 38 total
M10 enforce honoured (not refused) 2 failed, 36 passed, 38 total
M11 below-price passes (> instead of <) 1 failed, 37 passed, 38 total
M12 pin removed: any token emitter counts 1 failed, 37 passed, 38 total
  • Inertness: with the mode off, shadow and enforce, a refused anchor and a replayed anchor get the same anchored, delta and class. These tests pass on main too, by design.

Not done here (follow-ups)

  • Enforce: strip a non-VERIFIED anchor before deltaFor. Sean's call, in its own PR.
  • A production caller for scoreSettledInteraction. Until one exists, this protects the seam rather than a live path.
  • repid_grounding_claims is missing in prod. dbGroundingStore.findClaimByEvidence ignores its read error, so its replay pre-check fails open, while insertClaim throws and the resolver fails closed to 0. Worth fixing before GROUNDING_MODE leaves off. I did not touch it.
  • usdcToSmallestUnit rounds a float up. The anchor check passes integer units (claimedUnits) so it never uses that path.

🤖 Generated with Claude Code

DealAppSeo and others added 3 commits November 16, 2026 12:33
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DealAppSeo DealAppSeo added the grok-review Ask the grok-review loop to review this PR (also drafts) label Nov 16, 2026
@DealAppSeo
DealAppSeo marked this pull request as ready for review November 17, 2026 01:20
@strix-security

strix-security Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Strix Security Review

To fix before merging (2)

PR summary: Adds a shadow-only, default-off payment-anchor verifier that re-reads an x402 settlement receipt and binds it to a contract's own recorded payee, payer and price, plus a draft replay table and a fixed-code rewrite of the settlement verifier's error handling.

Review summary

The new verifier is carefully built — payee, payer and price come from our own records, the RPC error text is now replaced with fixed codes on every path, the replay table's unique key is treated as the authority, and the mode stays inert by default. Two problems remain in how the anchor's evidence is actually accounted for.

verifySettlement counts a payee-to-payee USDC transfer as money received, so a gas-only self-transfer verifies a settlement and anchors a scored success — the receipt loop adds a transfer the payee made to itself to the observed total, so a zero-value movement returns verified and the scorer forwards it to the delta as an anchored outcome. The same case is correctly refused in the new anchor module, but that module is flag-gated and never touches the delta, so the guard that would matter is not on the path that pays.

Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated — the is_simulated flag nulls both the recorded tx and the payer, so the contract is graded against any sender's transfer rather than against its own settlement, and the answer is VERIFIED rather than a refusal. Our own record that no money moved ends up weakening the check instead of stopping it.

Both are capped by the fact that the scorer still has no production caller and the replay table is a draft, which is why the first is rated medium rather than high; neither is fixed by the flag being off.

Ruled out (2)
  • Can a caller's shadow-mode presentation bind a real payment to the wrong contract and permanently strand it for the rightful contract?
    The mechanism is real, but the only runtime caller is the demo harness with operator-supplied values, the mode defaults off, the replay table is an unapplied draft and the scorer has no production caller, so no non-staff trigger exists and shadow changes no score.
  • Can a newline in a caller-supplied tx hash or contract id forge payment-anchor log lines?
    The unsanitized interpolation into the warning is real, but nothing in the repository accepts a caller-supplied anchor today, the harness validates the hash shape before the check runs, and no code or alerting consumes those log lines.

Fixed the findings? re-run the review, or tag @strix-security in a PR comment to run a fresh review.

Review 1 on this PR · 7f8a75c · requested Nov 17 01:20 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

@strix-security strix-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strix flagged 2 new security findings below. See the pinned summary comment for the full PR status.

Comment on lines +69 to +75
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated

Severity: LOW

TL;DR: For a contract whose settlement row is is_simulated, dbAnchorTerms returns no recorded tx and no payer, so verifyPaymentAnchor skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.

Impact: Once the draft replay table is applied and enforce ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.

Root cause:

  • The binding strength is derived from the settlement row's is_simulated flag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse.
  • payment-anchor-db.ts:59-60,73 nulls recordedTxHash and gates payerAddress on it, so payment-anchor-verify.ts:271 never compares the anchor against the contract's own tx and :315-317 falls back to summing every sender's inflow in the receipt.
  • Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.
Suggested change
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
};
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
settlementSimulated: s ? (s as any).is_simulated !== false : false,
};
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated
Severity: LOW
CWE: CWE-345

**TL;DR:** For a contract whose settlement row is `is_simulated`, `dbAnchorTerms` returns no recorded tx and no payer, so `verifyPaymentAnchor` skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.

**Impact:** Once the draft replay table is applied and `enforce` ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.

**Root cause:**
- The binding strength is derived from the settlement row's `is_simulated` flag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse.
- `payment-anchor-db.ts:59-60,73` nulls `recordedTxHash` and gates `payerAddress` on it, so `payment-anchor-verify.ts:271` never compares the anchor against the contract's own tx and `:315-317` falls back to summing every sender's inflow in the receipt.
- Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.

Location: src/services/payment-anchor-db.ts:69-75
Context: primary: carry the simulated flag instead of silently dropping both bindings
```
// Before:
  return {
    contractId,
    payeeAddress: (p as any)?.wallet_address ?? null,
    claimedUnits: units,
    payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
    recordedTxHash: recordedTx,
  };
// After:
  return {
    contractId,
    payeeAddress: (p as any)?.wallet_address ?? null,
    claimedUnits: units,
    payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
    recordedTxHash: recordedTx,
    settlementSimulated: s ? (s as any).is_simulated !== false : false,
  };
```

Location: src/services/payment-anchor-verify.ts:104-104
Context: terms type carries the simulated state
```
// Before:
  recordedTxHash: string | null;
// After:
  recordedTxHash: string | null;
  /** True when our own record says this contract was settled in simulation: no money moved. */
  settlementSimulated?: boolean;
```

Location: src/services/payment-anchor-verify.ts:163-163
Context: refusal reason
```
// Before:
  | 'refunded_in_tx'
// After:
  | 'refunded_in_tx'
  | 'settlement_simulated'
```

Location: src/services/payment-anchor-verify.ts:263-263
Context: refuse a contract our own record says was never paid
```
// Before:
  if (!terms) return refuse('contract_unknown');
// After:
  if (!terms) return refuse('contract_unknown');
  // Our own record says this contract was settled in simulation, so no money moved for it. An
  // anchor claiming otherwise contradicts that record and is refused, not graded against the chain.
  if (terms.settlementSimulated === true) return refuse('settlement_simulated');
```

How to fix:
Refuse an anchor for a contract whose own settlement record says the payment was simulated, instead of grading it against the payee's inbound transfers. Keep the payer binding independent of the tx binding so a recorded `payer_address` is still enforced when no chain tx is usable, and add a test that a simulated settlement row can never produce VERIFIED.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.

/** Who paid, when a settlement for this contract was recorded. Null otherwise. */
payerAddress: string | null;
/** The settlement tx recorded for this contract, when there is one. */
recordedTxHash: string | null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

terms type carries the simulated state

Suggested change
recordedTxHash: string | null;
recordedTxHash: string | null;
/** True when our own record says this contract was settled in simulation: no money moved. */
settlementSimulated?: boolean;

| 'below_claimed_value'
| 'payer_mismatch'
| 'self_payment'
| 'refunded_in_tx'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refusal reason

Suggested change
| 'refunded_in_tx'
| 'refunded_in_tx'
| 'settlement_simulated'

} catch {
return notChecked('terms_unreadable');
}
if (!terms) return refuse('contract_unknown');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refuse a contract our own record says was never paid

Suggested change
if (!terms) return refuse('contract_unknown');
if (!terms) return refuse('contract_unknown');
// Our own record says this contract was settled in simulation, so no money moved for it. An
// anchor claiming otherwise contradicts that record and is refused, not graded against the chain.
if (terms.settlementSimulated === true) return refuse('settlement_simulated');

Comment on lines +287 to +292
if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
if (eqAddr(to, input.payeeAddress)) {
observed += value;
const sender = String(from).toLowerCase();
analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
} else sawTransferElsewhere = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 verifySettlement counts a payee-to-payee USDC transfer as money received, so a gas-only self-transfer verifies a settlement and anchors a scored success

Severity: MEDIUM

TL;DR: In verifySettlement, a Transfer log where both from and to are the payee is added to observed, so a self-transfer that moves no net value returns verified: true and the scorer passes that proof on to deltaFor as an anchored outcome.

Impact: A provider agent can attach the hash of a USDC transfer it sent to itself — no money leaves its wallet, only gas — and collect the anchored success delta (up to +25 per event) that deltaFor withholds from unanchored success above $10, so reputation can be farmed without moving value.

Root cause:

  • No layer of the anchor chain checks that value actually moved: the verifier sums gross inflow to the payee, and the scorer treats that boolean as sufficient evidence that a counterparty paid.
  • The loop this PR edits now records who sent each transfer and what the payee sent out, but observed still adds a transfer the payee made to itself, so verified stays true for a zero-value movement.
  • The identical case is correctly refused in the new payment-anchor-verify.ts (self_payment, net of outflowFromPayee), but that module runs only when PAYMENT_ANCHOR_VERIFY_MODE is set and never touches the delta, so the flag that actually gates the delta is unchanged.
Suggested change
if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
if (eqAddr(to, input.payeeAddress)) {
observed += value;
const sender = String(from).toLowerCase();
analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
} else sawTransferElsewhere = true;
if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
// A transfer the payee makes to itself names a transfer but moves no value: the
// balance is unchanged, so it must not count toward the claimed amount.
const selfTransfer = eqAddr(from, input.payeeAddress) && eqAddr(to, input.payeeAddress);
if (eqAddr(to, input.payeeAddress) && !selfTransfer) {
observed += value;
const sender = String(from).toLowerCase();
analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
} else if (!eqAddr(to, input.payeeAddress)) sawTransferElsewhere = true;
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: verifySettlement counts a payee-to-payee USDC transfer as money received, so a gas-only self-transfer verifies a settlement and anchors a scored success
Severity: MEDIUM
CWE: CWE-345

**TL;DR:** In `verifySettlement`, a `Transfer` log where both `from` and `to` are the payee is added to `observed`, so a self-transfer that moves no net value returns `verified: true` and the scorer passes that proof on to `deltaFor` as an anchored outcome.

**Impact:** A provider agent can attach the hash of a USDC transfer it sent to itself — no money leaves its wallet, only gas — and collect the anchored success delta (up to +25 per event) that `deltaFor` withholds from unanchored success above $10, so reputation can be farmed without moving value.

**Root cause:**
- No layer of the anchor chain checks that value actually moved: the verifier sums gross inflow to the payee, and the scorer treats that boolean as sufficient evidence that a counterparty paid.
- The loop this PR edits now records who sent each transfer and what the payee sent out, but `observed` still adds a transfer the payee made to itself, so `verified` stays true for a zero-value movement.
- The identical case is correctly refused in the new `payment-anchor-verify.ts` (`self_payment`, net of `outflowFromPayee`), but that module runs only when `PAYMENT_ANCHOR_VERIFY_MODE` is set and never touches the delta, so the flag that actually gates the delta is unchanged.

Location: src/services/x402-settlement-verifier.ts:287-292
Context: primary fix: do not credit a transfer the payee makes to itself
```
// Before:
    if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
    if (eqAddr(to, input.payeeAddress)) {
      observed += value;
      const sender = String(from).toLowerCase();
      analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
    } else sawTransferElsewhere = true;
// After:
    if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
    // A transfer the payee makes to itself names a transfer but moves no value: the
    // balance is unchanged, so it must not count toward the claimed amount.
    const selfTransfer = eqAddr(from, input.payeeAddress) && eqAddr(to, input.payeeAddress);
    if (eqAddr(to, input.payeeAddress) && !selfTransfer) {
      observed += value;
      const sender = String(from).toLowerCase();
      analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
    } else if (!eqAddr(to, input.payeeAddress)) sawTransferElsewhere = true;
```

Location: src/services/x402-settlement-verifier.ts:329-343
Context: second part: compare the claimed value against the net amount, not the gross inflow
```
// Before:
  if (claimed > 0n && observed < claimed) {
    // The claim is not merely unproven, it is CONTRADICTED. Value at risk picks
    // the risk band as well as scaling the delta, so an inflated claim would buy
    // both a larger movement and a self-selected level of scrutiny.
    return {
      verified: false,
      evidence: 'MEASURED',
      code: 'below_claimed_value',
      reason: `settlement moved ${observed} but the claimed service value is ${claimed} (smallest unit)`,
      observedAmount: observed,
      confirmations,
      blockNumber,
      analysis,
    };
  }
// After:
  const netReceived = observed - analysis.outflowFromPayee;
  if (claimed > 0n && netReceived < claimed) {
    // The claim is not merely unproven, it is CONTRADICTED. Value at risk picks
    // the risk band as well as scaling the delta, so an inflated claim would buy
    // both a larger movement and a self-selected level of scrutiny. The payee's
    // own same-tx outflow is netted, so a refund or a pass-through is not a receipt.
    return {
      verified: false,
      evidence: 'MEASURED',
      code: 'below_claimed_value',
      reason: `settlement moved ${netReceived} net but the claimed service value is ${claimed} (smallest unit)`,
      observedAmount: netReceived,
      confirmations,
      blockNumber,
      analysis,
    };
  }
```

Location: src/services/settled-interaction-scorer.ts:173-173
Context: the consumer: the verifier's boolean alone decides whether the proof is forwarded as an anchor
```
      paymentProof: result.verified ? proof : null,
```

Location: src/services/payment-anchor-verify.ts:314-314
Context: the same defect correctly refused, in the module that does not affect the delta
```
  if (a.inflowBySender[payee] !== undefined) return refuse('self_payment');
```

How to fix:
Make `verifySettlement`'s `verified` flag mean what it is consumed as: value received from someone other than the payee, net of anything the payee sent back in the same transaction, so a self-transfer or a round-trip refund can never satisfy the claimed amount. Keep the `analysis` fields as the richer view for callers that need per-sender detail. Add a regression case that drives a receipt containing only a payee-to-payee `Transfer` through `scoreSettledInteraction` and asserts `settlement.verified` is false and the outcome is unanchored (demoted) rather than anchored. Update the anchor module's self-payment expectation to whatever code the verifier now returns for that input, since the verifier refuses before that branch is reached.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.

blockNumber,
analysis,
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

second part: compare the claimed value against the net amount, not the gross inflow

// The total reached the payee. Now WHO paid, and whether it stayed there.
const a = settlement.analysis;
if (!a) return notChecked('rpc_unreachable'); // a verified result always carries its analysis
if (a.inflowBySender[payee] !== undefined) return refuse('self_payment');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the same defect correctly refused, in the module that does not affect the delta

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

grok-review Ask the grok-review loop to review this PR (also drafts)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant