Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(x402): accept the delegated-wallet signatures OKX buyers actually send on X Layer

nirholas24d61a040a07
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb5a74850..216bc9755 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-04
- **A knock now holds the money until you actually get a reply**: Paying to reach someone used to send your money the instant the payment cleared, which meant an owner could take every knock and answer none, and you had no way to get it back. A new Solana program makes the payment conditional: it sits in a vault that only the knock itself controls, and exactly three things can happen to it. The owner answers inside the reply window and gets paid, the owner declines and you are refunded in full with no fee taken, or the window closes and anyone at all can trigger your refund. There is no admin key that can move a knock that is parked, the fee is capped at 10% in the program itself, and the fee you agreed to when you knocked cannot be raised on money that is already in escrow. Your message never touches the chain: only a fingerprint of it is stored, so either side can later prove what was sent without publishing it. Ten invariants covering every one of those promises run against the real compiled program on every test run. `[feature, security]`
+- **Agent wallets can pay three.ws on X Layer again**: Buying agents that pay for a 3D generation on X Layer sign their payment with a wallet that carries an on-chain delegation, which is how every OKX agent wallet is built. Our checker judged those signatures with a contract call that answers a different question, so it turned away correct, fully funded payments and quoted the price a second time instead of doing the work. Payments are now checked the same way the stablecoin itself checks them, so a signed authorization that the network would honour is one we accept. `[fix]`
- **Knock somebody's door and get your money back if they never answer**: Paying to reach a stranger has meant paying first and hoping. The money left your wallet the moment the payment cleared, and if the person never replied, that was that. Doors can now take escrowed knocks instead: your payment sits in a vault on Solana that the recipient cannot touch until they actually answer you. If they answer, they are paid. If they decline, you get everything back and are charged nothing, because reading something and passing on it is not a service. And if they simply never respond before the window they set, anyone at all can trigger the refund and every cent comes back to you, so it does not depend on you remembering to chase it. three.ws holds no key that can move that money, and neither does anyone else. Door owners can turn the lane on in their knock settings and choose how long they get to reply, from an hour to a month. (`/docs/knock`) `[feature, security]`
- **The 3D services we sell to other agents quote one clear price, however they are asked**: Our four paid 3D generation services on the OKX.AI agent marketplace answer every caller with a price quote before any work happens. Two flaws in that quote are fixed. A request that arrived with no body and no content type was turned away with a formatting complaint instead of a price, and that is exactly how the marketplace's own compatibility check asks, so the check saw four services that looked like they had no payment set up at all. Separately, a request that named no specific tool got a quote listing the same payment network twice at two different prices, one of them wrong. Every unpaid request now receives a single unambiguous quote at the service's listed price, on each payment network it accepts. `[fix]`
- **The IBM partnership demos arm wherever the page is opened**: The live demo pages loaded their own payment script across the network by full address, so on any address other than the main site (a preview, a local run, a copy published on a partner domain) the browser refused it and the paid demos never armed. Each page now loads the copy it ships with. The publish-once page IBM hosts got the opposite fix: every file it pulls now carries our full address, so its language switcher no longer looks for a file on the host's own domain and comes back empty. (`/ibm/hello`) `[fix]`
diff --git a/api/_lib/x402-xlayer-okx.js b/api/_lib/x402-xlayer-okx.js
index 871bd8859..b622f9ca1 100644
--- a/api/_lib/x402-xlayer-okx.js
+++ b/api/_lib/x402-xlayer-okx.js
@@ -20,7 +20,8 @@
// resource }, note `accepted`, not the standard x402 top-level
// scheme/network fields.
// 4. Verification is seller-side and on-chain: EIP-712 signature recovery
-// (ERC-1271-aware, OKX agentic wallets may be smart accounts), recipient/
+// first, then ERC-1271/6492 (OKX agentic wallets are EIP-7702 delegated
+// EOAs, so the order matters, see eip3009SignatureIsValid), recipient/
// amount/time-window checks, unused authorizationState, and a balanceOf
// check. Insufficient balance re-issues the 402 with top-level
// error:"insufficient_balance", the exact behavior captured from the
@@ -45,6 +46,7 @@ import {
fallback,
getAddress,
http,
+ recoverTypedDataAddress,
} from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { xLayer } from 'viem/chains';
@@ -271,6 +273,50 @@ function asBigInt(value, field) {
}
}
+// Is this EIP-3009 authorization signed by `from`, judged the way USD₮0's own
+// transferWithAuthorization judges it: recover the ECDSA signature first, and
+// only ask an on-chain contract when recovery does not name the payer.
+//
+// The order is load-bearing, not a micro-optimisation. Every OKX agentic wallet
+// on X Layer is an EIP-7702 delegated EOA: the address holds 23 bytes of
+// delegation code (`0xef0100 || implementation`), so viem's verifyTypedData
+// takes its contract branch, calls the delegate's ERC-1271 isValidSignature,
+// and returns false for a signature the EOA's own key produced. The delegate
+// answers 1271 over its own replay-safe wrapper hash, never the raw EIP-712
+// digest that EIP-3009 requires. That is what OKX's 2026-08-27 listing QA hit:
+// its buyer signed a correct, fully funded authorization from
+// 0xbc59eb75C55e3bF1E63aaeE653C2b8E02BFd2033 and we answered a second 402
+// ("EIP-3009 signature does not verify for authorization.from"), which the
+// review reported as the service failing its payment test. Recovery first
+// matches the token: it redeems on ecrecover, so any signature accepted here
+// is one the settlement transaction can actually spend.
+//
+// The ERC-1271/6492 branch stays for real smart accounts, whose proofs are not
+// recoverable ECDSA at all.
+async function eip3009SignatureIsValid({ client, from, domain, message, signature }) {
+ try {
+ const recovered = await recoverTypedDataAddress({
+ domain,
+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,
+ primaryType: 'TransferWithAuthorization',
+ message,
+ signature,
+ });
+ if (getAddress(recovered) === from) return true;
+ } catch {
+ // Not a 65-byte ECDSA signature (a smart account's proof can be any
+ // length or an ERC-6492 wrapper), so let the on-chain check answer.
+ }
+ return client.verifyTypedData({
+ address: from,
+ domain,
+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,
+ primaryType: 'TransferWithAuthorization',
+ message,
+ signature,
+ });
+}
+
// Verify an OKX/X Layer EIP-3009 payment end to end WITHOUT trusting any
// third party: typed-data signature (ERC-1271-aware via the public client, so
// smart-account agentic wallets verify too), recipient binding, amount, time
@@ -318,22 +364,22 @@ export async function verifyOkxXLayerPayment({ paymentPayload, requirement }) {
const asset = asAddress(requirement.asset || env.X402_ASSET_ADDRESS_XLAYER, 'requirement.asset');
const client = xlayerClient();
- // EIP-712 recovery. Domain name/version come from the requirement's extra
- // block (what the buyer signed against) with the on-chain-verified USD₮0
- // defaults. verifyTypedData on a PUBLIC client falls back to ERC-6492/1271
- // isValidSignature for contract accounts.
+ // EIP-712 signature check, in the order the TOKEN itself checks it (see
+ // eip3009SignatureIsValid): plain ECDSA recovery first, ERC-1271/6492 only
+ // when recovery does not name the payer. Domain name/version come from the
+ // requirement's extra block (what the buyer signed against) with the
+ // on-chain-verified USD₮0 defaults.
let sigOk = false;
try {
- sigOk = await client.verifyTypedData({
- address: from,
+ sigOk = await eip3009SignatureIsValid({
+ client,
+ from,
domain: {
name: requirement.extra?.name || USDT0_DOMAIN_NAME,
version: requirement.extra?.version || USDT0_DOMAIN_VERSION,
chainId: XLAYER_CHAIN_ID,
verifyingContract: asset,
},
- types: TRANSFER_WITH_AUTHORIZATION_TYPES,
- primaryType: 'TransferWithAuthorization',
message: {
from,
to,
diff --git a/data/changelog.json b/data/changelog.json
index 356841fa8..cf49f9dca 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -26400,6 +26400,14 @@
"fix",
"improvement"
]
+ },
+ {
+ "date": "2026-09-04",
+ "title": "Agent wallets can pay three.ws on X Layer again",
+ "summary": "Buying agents that pay for a 3D generation on X Layer sign their payment with a wallet that carries an on-chain delegation, which is how every OKX agent wallet is built. Our checker judged those signatures with a contract call that answers a different question, so it turned away correct, fully funded payments and quoted the price a second time instead of doing the work. Payments are now checked the same way the stablecoin itself checks them, so a signed authorization that the network would honour is one we accept.",
+ "tags": [
+ "fix"
+ ]
}
]
}
diff --git a/prompts/finish/okx-ai-PROGRESS.md b/prompts/finish/okx-ai-PROGRESS.md
index 5c8bd9249..f2af7ad6c 100644
--- a/prompts/finish/okx-ai-PROGRESS.md
+++ b/prompts/finish/okx-ai-PROGRESS.md
@@ -6,6 +6,83 @@ Work Order 04 session, no earlier entries existed because no earlier work order
---
+## 2026-09-04, the third defect: OKX's QA did reach the payment stage, and we rejected its signature
+
+Parallel session to the 402-shape work below, same rejection, different leg. The reviewer's
+internal note says the flow "has not entered the payment stage". The production access log
+says otherwise, and the log is the primary source: **OKX's listing QA presented a real,
+signed, funded payment on 2026-08-27 and every one of the four paid rows answered it with a
+second 402.**
+
+### What the wire says
+
+`Java-http-client/17.0.8.1` from `8.212.100.234` / `8.212.101.240` (Alibaba Cloud), 11
+requests in 18 seconds, exactly our five listed forge rows plus `/catalog` and `/health`,
+minutes after the 2026-08-27 resubmission. Two POSTs per paid row:
+
+| row | probe 1 | probe 2 |
+|---|---|---|
+| forge-draft | 569 B → 402 in 0.115 s | **1716 B → 402 in 0.468 s** |
+| forge-standard | 521 B → 402 in 0.154 s | **1676 B → 402 in 0.707 s** |
+| forge-hd | 478 B → 402 in 0.104 s | **1624 B → 402 in 0.402 s** |
+| forge-image | 683 B → 402 in 0.011 s | **1836 B → 402 in 0.416 s** |
+
+The second request of each pair is ~1.15 kB larger: a `PAYMENT-SIGNATURE` header. It cost
+0.4 s to 0.7 s of RPC where the unpaid probe cost milliseconds, so we ran chain work and
+then refused. And each paid response body is 65 to 69 bytes larger than its unpaid sibling,
+which after the base64 `PAYMENT-REQUIRED` mirror is a 57-character `error` string. The only
+57-character error our X Layer verifier can emit behind an RPC call is
+`EIP-3009 signature does not verify for authorization.from`.
+
+### Why a correct signature failed
+
+**Every OKX agentic wallet is an EIP-7702 delegated EOA.** `eth_getCode` for their audit
+address `0xbc59eb75C55e3bF1E63aaeE653C2b8E02BFd2033` returns
+`0xef0100e40ccb2d94975c51bff0c004efdfd9b3a5796fa4`, the 23-byte delegation designator, and
+the address holds **19.550213 USD₮0**, so it was funded the whole time. Our own buyer
+`0x75d0…cf69` carries the same shape.
+
+`verifyOkxXLayerPayment()` asked viem's `client.verifyTypedData`. With code at the address
+that helper takes its contract branch, calls the delegate's ERC-1271 `isValidSignature`
+(present in the delegate, confirmed by selector), and the delegate answers over its own
+replay-safe wrapper hash, not the raw EIP-712 digest EIP-3009 signs. It returns `false`
+cleanly, so viem never falls back to plain recovery, and we rejected a perfectly good
+authorization. Anyone paying us on this rail from an OKX wallet hit this, so funding our own
+buyer would NOT have fixed the listing: the WO-04 gauntlet would have failed the same way
+with money committed.
+
+**The token disagrees with the helper, and the token is the authority.** USD₮0's
+`transferWithAuthorization` recovers ECDSA first. Proven read-only against X Layer mainnet:
+simulating the redemption for a signer state-overridden with the OKX delegation designator
+is **accepted, no revert**, exactly like a plain EOA.
+
+### Fixed
+
+`eip3009SignatureIsValid()` in `api/_lib/x402-xlayer-okx.js` now checks the way the token
+checks: recover the EIP-712 signature and compare to `authorization.from` first (no RPC at
+all in the common case, so it is also a round trip cheaper), and fall back to the on-chain
+ERC-1271/6492 path only when recovery cannot name the payer, which is what a real smart
+account needs. Nothing else about the money changes: recipient, amount, time window, unused
+nonce and `balanceOf` are all still enforced, and there is still no per-address logic of any
+kind, so the note in the entry below stays true.
+
+Five regression tests in `tests/api/okx-xlayer-verify.test.js`, signing with a real key
+against USD₮0's real domain and mocking only the RPC boundary: a delegated payer whose
+ERC-1271 says no still verifies, a smart account that is not ECDSA-recoverable still
+verifies through 1271, a foreign signature is still refused, a wrong recipient still dies
+before any chain read, and an empty wallet still answers `insufficient_balance`.
+
+The rail contract is updated with the rule and the evidence: `specs/okx-agent-payments.md`
+§1.2a.
+
+### Next
+
+Deploy (owner-gated) alongside the 402-shape fixes below, then resubmit. On the resubmission
+the QA replay should settle for real, on-chain, from their funded audit wallet, which also
+makes it the first funded settlement this rail has ever taken.
+
+---
+
## 2026-09-04, listing rejection #3 root-caused on the wire: two defects in the 402, both fixed
OKX rejected the resubmission with the same sentence on all four paid rows ("failed the
diff --git a/public/changelog.json b/public/changelog.json
index 2542128c1..6b5827b10 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-04T01:54:47.940Z",
+ "generated_at": "2026-09-04T02:00:38.891Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -17,6 +17,16 @@
"security"
]
},
+ {
+ "date": "2026-09-04",
+ "type": "update",
+ "title": "Agent wallets can pay three.ws on X Layer again",
+ "summary": "Buying agents that pay for a 3D generation on X Layer sign their payment with a wallet that carries an on-chain delegation, which is how every OKX agent wallet is built. Our checker judged those signatures with a contract call that answers a different question, so it turned away correct, fully funded payments and quoted the price a second time instead of doing the work. Payments are now checked the same way the stablecoin itself checks them, so a signed authorization that the network would honour is one we accept.",
+ "link": null,
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-09-04",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1e7350f46..5e30c208d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>feature</category>
<description>Paying to reach someone used to send your money the instant the payment cleared, which meant an owner could take every knock and answer none, and you had no way to get it back. A new Solana program makes the payment conditional: it sits in a vault that only the knock itself controls, and exactly three things can happen to it. The owner answers inside the reply window and gets paid, the owner declines and you are refunded in full with no fee taken, or the window closes and anyone at all can trigger your refund. There is no admin key that can move a knock that is parked, the fee is capped at 10% in the program itself, and the fee you agreed to when you knocked cannot be raised on money that is already in escrow. Your message never touches the chain: only a fingerprint of it is stored, so either side can later prove what was sent without publishing it. Ten invariants covering every one of those promises run against the real compiled program on every test run.</description>
</item>
+ <item>
+ <title>Agent wallets can pay three.ws on X Layer again</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-09-04:Agent wallets can pay three.ws on X Layer again</guid>
+ <pubDate>Fri, 04 Sep 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Buying agents that pay for a 3D generation on X Layer sign their payment with a wallet that carries an on-chain delegation, which is how every OKX agent wallet is built. Our checker judged those signatures with a contract call that answers a different question, so it turned away correct, fully funded payments and quoted the price a second time instead of doing the work. Payments are now checked the same way the stablecoin itself checks them, so a signed authorization that the network would honour is one we accept.</description>
+ </item>
<item>
<title>Knock somebody's door and get your money back if they never answer</title>
<link>https://three.ws/docs/knock</link>
diff --git a/specs/okx-agent-payments.md b/specs/okx-agent-payments.md
index 4b1188c59..32620e01b 100644
--- a/specs/okx-agent-payments.md
+++ b/specs/okx-agent-payments.md
@@ -118,6 +118,44 @@ On a request that carries the payment header, the seller calls the **OKX facilit
Source: SDK-REPO `app-x402-core/src/facilitator/OKXFacilitatorClient.ts` (verify L92-115, settle L124-150), `app-x402-core/src/http/x402HTTPResourceServer.ts` (header read L1560, `PAYMENT-RESPONSE` emit L1663-1676), `app-x402-core/src/http/index.ts` (base64 codecs L17-80). Live-confirmed by PAY-LEG1/2.
+### 1.2a Signature check order: recover first, ERC-1271 second (EIP-7702 buyers)
+
+**Every OKX agentic wallet on X Layer is an EIP-7702 delegated EOA**, not a plain EOA and not
+a deployed smart account. `eth_getCode` on one returns the 23-byte delegation designator
+`0xef0100 || implementation`: verified 2026-09-04 for the OKX audit test address
+`0xbc59eb75C55e3bF1E63aaeE653C2b8E02BFd2033` (delegate `0xe40ccb2d…96fa4`, holding 19.550213
+USD₮0) and for our own buyer `0x75d0…cf69`.
+
+That makes verification-by-contract-call wrong for this rail. A seller that hands the
+authorization to a generic "is this signature valid for this address" helper (viem's
+`verifyTypedData`, ethers' `isValidSignature` wrappers) gets the **contract** branch, because
+the address has code: the helper calls the delegate's ERC-1271 `isValidSignature`, the
+delegate answers over its own replay-safe wrapper hash rather than the raw EIP-712 digest,
+and the check returns `false` for a signature the wallet's own key produced correctly.
+
+The token does not judge it that way, and the token is the authority: USD₮0's
+`transferWithAuthorization` recovers the ECDSA signature first (ERC-1271 is only its
+fallback). Proven read-only against mainnet on 2026-09-04 by simulating the redemption with
+a state-overridden delegated signer: **accepted, no revert**, identical to a plain EOA.
+
+**Rule: recover the EIP-712 signature and compare to `authorization.from` FIRST; only when
+recovery cannot name the payer (a real smart account, an ERC-6492 wrapper) fall back to the
+on-chain ERC-1271/6492 check.** Implemented in `eip3009SignatureIsValid()`
+([x402-xlayer-okx.js](../api/_lib/x402-xlayer-okx.js)), covered by
+`tests/api/okx-xlayer-verify.test.js`.
+
+**Wire evidence (why this is not theoretical).** OKX's listing QA ran against production on
+2026-08-27T00:53:47Z-00:53:58Z from `Java-http-client/17.0.8.1` (8.212.100.234 /
+8.212.101.240), two POSTs per paid row: an unpaid probe (402, ~480-680 B request) then a
+signed replay (~1.6-1.8 kB request, i.e. the `PAYMENT-SIGNATURE` header). Every replay was
+answered **402 again**, 0.40-0.71 s of RPC latency each, and each response body grew by
+exactly the bytes of a 57-character `error` over the unpaid one: the length of
+`EIP-3009 signature does not verify for authorization.from`. The 2026-09-04 rejection
+("failed the official test, we are unable to verify the availability of your service", plus
+the internal note that the flow "has not entered the payment stage") is that rejection,
+seen from their side.
+
+
### 1.3 The paid-replay header (buyer → seller)
The buyer replays the original request adding **`PAYMENT-SIGNATURE: <base64 PaymentPayload>`**. The decoded payload we must accept (from PAY-LEG1, our real signature):
@@ -236,7 +274,7 @@ of the presented payment. Spec → code map (file:line at landing commit `05de05
| §1.1 | Advertise the accept only when settlement is actually possible (never 402-then-502) | [`xlayerSettleable()`](../api/_lib/x402-xlayer-okx.js#L179-L185); wired into [`paymentRequirements()`](../api/_lib/x402-spec.js#L239-L246) after the Solana/Base/BSC accepts (multi-rail coexistence, requirement 4) |
| §1.1 amount | Advertised == verified == settled, all from `priceBatch`/`studioX402Amount` (requirement 6) | The X Layer accept takes `common.amount` (the per-tool price) unchanged, USD₮0 shares USDC's 6-decimal atomic scale, so `150000` = $0.15 across every rail. [x402-spec.js#L245](../api/_lib/x402-spec.js#L245) |
| §1.2 step 3, G6 | Route verify/settle to the OKX rail by network | [`facilitatorFor()` → `{okxXLayer:true}`](../api/_lib/x402-spec.js#L287-L292) for `eip155:196` |
-| §1.2 step 4, requirement 2 | Verify BEFORE work, real EIP-712 recovery (ERC-1271-aware for smart-account wallets), recipient/amount/time-window checks, unused-nonce + `balanceOf` on-chain, then the OKX facilitator `/verify` when credentialed | [`verifyOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L272-L416); dispatched from [`verifyPayment()`](../api/_lib/x402-spec.js#L1014-L1022). Invalid/underpaid/expired throws `X402Error` 402 → fresh challenge, tool does not run |
+| §1.2 step 4, §1.2a, requirement 2 | Verify BEFORE work: EIP-712 ECDSA recovery FIRST, ERC-1271/6492 only as the fallback (§1.2a, EIP-7702 buyers), recipient/amount/time-window checks, unused-nonce + `balanceOf` on-chain, then the OKX facilitator `/verify` when credentialed | [`verifyOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L272-L416); dispatched from [`verifyPayment()`](../api/_lib/x402-spec.js#L1014-L1022). Invalid/underpaid/expired throws `X402Error` 402 → fresh challenge, tool does not run |
| §1.2 step 6, §1.4, requirement 3 | Settle only after tool success; OKX facilitator `/settle` (`syncSettle:true`) primary, direct EIP-3009 redemption fallback; return `{success,status,transaction,payer,amount}` | [`settleOkxXLayerPayment()`](../api/_lib/x402-xlayer-okx.js#L442-L530); dispatched from [`settlePayment()`](../api/_lib/x402-spec.js#L1110-L1120). Called only after `anySuccess` in [mcp-3d.js](../api/mcp-3d.js#L103-L119) and [okx/3d/[service].js](../api/okx/3d/%5Bservice%5D.js#L377-L392) |
| §1.3, G7 | Read the buyer's `PAYMENT-SIGNATURE` (x402 v2) header; parse the OKX `{accepted, payload:{authorization,signature}}` dialect | [auth.js reads `payment-signature`](../api/_mcp/auth.js#L94-L97); [`selectRequirement()` matches `paymentPayload.accepted.network`](../api/_lib/x402-spec.js#L786-L792); [`extractAuthorization()`](../api/_lib/x402-xlayer-okx.js#L237-L249) |
| §1.4, G8 | Emit `PAYMENT-RESPONSE` (x402 v2) receipt with `status`+`amount`; keep `x-payment-response` (v1) as an alias | [`encodePaymentResponseHeader()`](../api/_lib/x402-spec.js#L1169-L1186) now passes through `status`/`amount`; both header names set in [mcp-3d.js#L108-L116](../api/mcp-3d.js#L108-L116) and [service].js; both added to the [CORS expose list](../api/_lib/http.js#L383-L386) |
diff --git a/tests/api/okx-xlayer-verify.test.js b/tests/api/okx-xlayer-verify.test.js
new file mode 100644
index 000000000..0dd235642
--- /dev/null
+++ b/tests/api/okx-xlayer-verify.test.js
@@ -0,0 +1,160 @@
+// The X Layer (OKX Agent Payments Protocol) EIP-3009 verifier, exercised with
+// REAL signatures from a real key: only the RPC boundary is mocked, so the
+// EIP-712 hashing, the signature and the recovery are the production ones.
+//
+// The case that matters is the first one. Every OKX agentic wallet is an
+// EIP-7702 delegated EOA, so the address carries delegation code and viem's
+// verifyTypedData answers false for the EOA's own signature (it asks the
+// delegate's ERC-1271, which hashes its own wrapper). Verifying that way
+// rejected OKX's own listing QA payment on 2026-08-27.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { privateKeyToAccount, generatePrivateKey } from 'viem/accounts';
+
+const h = vi.hoisted(() => ({
+ client: { verifyTypedData: vi.fn(), readContract: vi.fn() },
+}));
+
+vi.mock('viem', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, createPublicClient: vi.fn(() => h.client) };
+});
+
+process.env.X402_PAY_TO_XLAYER ||= '0x4022de2D36C334E73C7a108805Cea11C0564f402';
+process.env.X402_ASSET_ADDRESS_XLAYER ||= '0x779ded0c9e1022225f8e0630b35a9b54be713736';
+
+const { verifyOkxXLayerPayment, okxXLayerAccept } = await import('../../api/_lib/x402-xlayer-okx.js');
+
+const PAY_TO = '0x4022de2D36C334E73C7a108805Cea11C0564f402';
+const ASSET = '0x779ded0c9e1022225f8e0630b35a9b54be713736';
+const AMOUNT = '10000';
+
+const requirement = {
+ ...okxXLayerAccept('https://three.ws/api/okx/3d/forge-draft', AMOUNT),
+ payTo: PAY_TO,
+ asset: ASSET,
+};
+
+const TYPES = {
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+};
+
+// A real authorization, signed by a real key against USD₮0's real EIP-712 domain.
+async function signedPayment({ account, value = AMOUNT } = {}) {
+ const signer = account || privateKeyToAccount(generatePrivateKey());
+ const message = {
+ from: signer.address,
+ to: PAY_TO,
+ value: BigInt(value),
+ validAfter: 0n,
+ validBefore: BigInt(Math.floor(Date.now() / 1000) + 600),
+ nonce: `0x${'ab'.repeat(32)}`,
+ };
+ const signature = await signer.signTypedData({
+ domain: { name: 'USD₮0', version: '1', chainId: 196, verifyingContract: ASSET },
+ types: TYPES,
+ primaryType: 'TransferWithAuthorization',
+ message,
+ });
+ return {
+ signer,
+ payload: {
+ x402Version: 2,
+ accepted: requirement,
+ payload: {
+ authorization: {
+ from: message.from,
+ to: message.to,
+ value: message.value.toString(),
+ validAfter: '0',
+ validBefore: message.validBefore.toString(),
+ nonce: message.nonce,
+ },
+ signature,
+ },
+ },
+ };
+}
+
+// authorizationState → unused, balanceOf → funded.
+function chainStateOk() {
+ h.client.readContract.mockImplementation(({ functionName }) =>
+ functionName === 'authorizationState' ? Promise.resolve(false) : Promise.resolve(10n ** 18n),
+ );
+}
+
+beforeEach(() => {
+ h.client.verifyTypedData.mockReset();
+ h.client.readContract.mockReset();
+ chainStateOk();
+});
+
+describe('verifyOkxXLayerPayment', () => {
+ it('accepts an EIP-7702 delegated EOA whose ERC-1271 delegate rejects the raw digest', async () => {
+ // What X Layer actually answers for an OKX agentic wallet: the delegate's
+ // isValidSignature says no, because it signs over its own wrapper hash.
+ h.client.verifyTypedData.mockResolvedValue(false);
+ const { signer, payload } = await signedPayment();
+
+ const verified = await verifyOkxXLayerPayment({ paymentPayload: payload, requirement });
+
+ expect(verified.isValid).toBe(true);
+ expect(verified.payer).toBe(signer.address);
+ expect(verified.amount).toBe(AMOUNT);
+ // Recovery answered it, so no contract call was needed at all.
+ expect(h.client.verifyTypedData).not.toHaveBeenCalled();
+ });
+
+ it('still verifies a smart account through ERC-1271 when recovery cannot name the payer', async () => {
+ h.client.verifyTypedData.mockResolvedValue(true);
+ const { payload } = await signedPayment();
+ // A contract account's proof is not a recoverable ECDSA signature.
+ payload.payload.signature = `0x${'cd'.repeat(120)}`;
+
+ const verified = await verifyOkxXLayerPayment({ paymentPayload: payload, requirement });
+
+ expect(verified.isValid).toBe(true);
+ expect(h.client.verifyTypedData).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects a signature that neither recovers to the payer nor validates on-chain', async () => {
+ h.client.verifyTypedData.mockResolvedValue(false);
+ const { payload } = await signedPayment();
+ // Same shape, a different signer: recovery names someone else.
+ const other = await signedPayment();
+ payload.payload.signature = other.payload.payload.signature;
+
+ await expect(verifyOkxXLayerPayment({ paymentPayload: payload, requirement })).rejects.toThrow(
+ /signature does not verify/,
+ );
+ });
+
+ it('rejects an authorization paid to the wrong recipient before any chain read', async () => {
+ const { payload } = await signedPayment();
+ payload.payload.authorization.to = '0x1111111111111111111111111111111111111111';
+
+ await expect(verifyOkxXLayerPayment({ paymentPayload: payload, requirement })).rejects.toThrow(
+ /does not match required payTo/,
+ );
+ expect(h.client.readContract).not.toHaveBeenCalled();
+ });
+
+ it('reports insufficient_balance the way the approved sellers do', async () => {
+ h.client.verifyTypedData.mockResolvedValue(false);
+ h.client.readContract.mockImplementation(({ functionName }) =>
+ functionName === 'authorizationState' ? Promise.resolve(false) : Promise.resolve(0n),
+ );
+ const { payload } = await signedPayment();
+
+ await expect(verifyOkxXLayerPayment({ paymentPayload: payload, requirement })).rejects.toThrow(
+ 'insufficient_balance',
+ );
+ });
+});