@absol-labs/agent 0.11.0 → 0.12.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -51
- package/dist/capability/invocation-capability.d.ts +2 -2
- package/dist/capability/probe-capability.d.ts +225 -0
- package/dist/capability/probe-capability.d.ts.map +1 -0
- package/dist/capability/probe-capability.js +248 -0
- package/dist/capability/probe-capability.js.map +1 -0
- package/dist/cli/args.d.ts +11 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +23 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/commands/claim.d.ts +32 -0
- package/dist/cli/commands/claim.d.ts.map +1 -1
- package/dist/cli/commands/claim.js +116 -28
- package/dist/cli/commands/claim.js.map +1 -1
- package/dist/cli/commands/close.d.ts.map +1 -1
- package/dist/cli/commands/close.js +35 -3
- package/dist/cli/commands/close.js.map +1 -1
- package/dist/cli/commands/invoke.d.ts +2 -0
- package/dist/cli/commands/invoke.d.ts.map +1 -1
- package/dist/cli/commands/invoke.js +2 -2
- package/dist/cli/commands/invoke.js.map +1 -1
- package/dist/cli/commands/mcp.d.ts.map +1 -1
- package/dist/cli/commands/mcp.js +15 -2
- package/dist/cli/commands/mcp.js.map +1 -1
- package/dist/cli/commands/open.d.ts.map +1 -1
- package/dist/cli/commands/open.js +58 -4
- package/dist/cli/commands/open.js.map +1 -1
- package/dist/cli/commands/pay.d.ts +34 -0
- package/dist/cli/commands/pay.d.ts.map +1 -0
- package/dist/cli/commands/pay.js +479 -0
- package/dist/cli/commands/pay.js.map +1 -0
- package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
- package/dist/cli/commands/reclaim-unverified.js +3 -2
- package/dist/cli/commands/reclaim-unverified.js.map +1 -1
- package/dist/cli/commands/reclaim.d.ts +23 -2
- package/dist/cli/commands/reclaim.d.ts.map +1 -1
- package/dist/cli/commands/reclaim.js +204 -20
- package/dist/cli/commands/reclaim.js.map +1 -1
- package/dist/cli/commands/refund.d.ts +31 -0
- package/dist/cli/commands/refund.d.ts.map +1 -0
- package/dist/cli/commands/refund.js +397 -0
- package/dist/cli/commands/refund.js.map +1 -0
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +21 -2
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/commands/streams.js +8 -12
- package/dist/cli/commands/streams.js.map +1 -1
- package/dist/cli/commands/watch.d.ts.map +1 -1
- package/dist/cli/commands/watch.js +4 -1
- package/dist/cli/commands/watch.js.map +1 -1
- package/dist/cli/config.d.ts +44 -26
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +88 -38
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/context.d.ts +19 -0
- package/dist/cli/context.d.ts.map +1 -1
- package/dist/cli/deps.d.ts +53 -0
- package/dist/cli/deps.d.ts.map +1 -1
- package/dist/cli/deps.js +51 -1
- package/dist/cli/deps.js.map +1 -1
- package/dist/cli/errors.d.ts.map +1 -1
- package/dist/cli/errors.js +21 -1
- package/dist/cli/errors.js.map +1 -1
- package/dist/cli/escape-hatch.d.ts +6 -4
- package/dist/cli/escape-hatch.d.ts.map +1 -1
- package/dist/cli/escape-hatch.js +6 -2
- package/dist/cli/escape-hatch.js.map +1 -1
- package/dist/cli/listings.d.ts +18 -0
- package/dist/cli/listings.d.ts.map +1 -1
- package/dist/cli/listings.js +22 -12
- package/dist/cli/listings.js.map +1 -1
- package/dist/cli/preflight.d.ts +20 -14
- package/dist/cli/preflight.d.ts.map +1 -1
- package/dist/cli/preflight.js +34 -20
- package/dist/cli/preflight.js.map +1 -1
- package/dist/cli/privy.d.ts.map +1 -1
- package/dist/cli/privy.js +4 -2
- package/dist/cli/privy.js.map +1 -1
- package/dist/cli/progress.d.ts +13 -1
- package/dist/cli/progress.d.ts.map +1 -1
- package/dist/cli/progress.js +7 -1
- package/dist/cli/progress.js.map +1 -1
- package/dist/cli/reclaimability.d.ts +82 -0
- package/dist/cli/reclaimability.d.ts.map +1 -0
- package/dist/cli/reclaimability.js +80 -0
- package/dist/cli/reclaimability.js.map +1 -0
- package/dist/cli/run.d.ts +2 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +62 -21
- package/dist/cli/run.js.map +1 -1
- package/dist/cli/scan-range.d.ts +2 -2
- package/dist/cli/scan-range.js +2 -2
- package/dist/cli/status.d.ts +106 -1
- package/dist/cli/status.d.ts.map +1 -1
- package/dist/cli/status.js +325 -44
- package/dist/cli/status.js.map +1 -1
- package/dist/cli/wallet.d.ts +2 -2
- package/dist/cli/wallet.d.ts.map +1 -1
- package/dist/cli/wallet.js +29 -5
- package/dist/cli/wallet.js.map +1 -1
- package/dist/discovery/rate-band.d.ts +74 -0
- package/dist/discovery/rate-band.d.ts.map +1 -0
- package/dist/discovery/rate-band.js +114 -0
- package/dist/discovery/rate-band.js.map +1 -0
- package/dist/escrow-generation.d.ts +81 -0
- package/dist/escrow-generation.d.ts.map +1 -0
- package/dist/escrow-generation.js +76 -0
- package/dist/escrow-generation.js.map +1 -0
- package/dist/frameworks/agentkit.d.ts +8 -4
- package/dist/frameworks/agentkit.d.ts.map +1 -1
- package/dist/frameworks/agentkit.js +27 -10
- package/dist/frameworks/agentkit.js.map +1 -1
- package/dist/frameworks/eliza.d.ts +3 -3
- package/dist/frameworks/eliza.d.ts.map +1 -1
- package/dist/frameworks/eliza.js +15 -6
- package/dist/frameworks/eliza.js.map +1 -1
- package/dist/frameworks/langchain.d.ts.map +1 -1
- package/dist/frameworks/langchain.js +8 -0
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/gateway/caller-auth-gateway.d.ts +83 -31
- package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
- package/dist/gateway/caller-auth-gateway.js +180 -27
- package/dist/gateway/caller-auth-gateway.js.map +1 -1
- package/dist/gateway/http-server.d.ts +128 -44
- package/dist/gateway/http-server.d.ts.map +1 -1
- package/dist/gateway/http-server.js +506 -155
- package/dist/gateway/http-server.js.map +1 -1
- package/dist/gateway/probe-auth.d.ts +112 -0
- package/dist/gateway/probe-auth.d.ts.map +1 -0
- package/dist/gateway/probe-auth.js +127 -0
- package/dist/gateway/probe-auth.js.map +1 -0
- package/dist/gateway/signed-rate-bounds.d.ts +51 -0
- package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
- package/dist/gateway/signed-rate-bounds.js +94 -0
- package/dist/gateway/signed-rate-bounds.js.map +1 -0
- package/dist/gateway/x402-opener-mode.d.ts +252 -0
- package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
- package/dist/gateway/x402-opener-mode.js +772 -0
- package/dist/gateway/x402-opener-mode.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.d.ts +64 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +247 -37
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/x402-tools.d.ts +109 -0
- package/dist/mcp/x402-tools.d.ts.map +1 -0
- package/dist/mcp/x402-tools.js +554 -0
- package/dist/mcp/x402-tools.js.map +1 -0
- package/dist/network.d.ts +119 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +199 -0
- package/dist/network.js.map +1 -0
- package/dist/sdk/client.d.ts +13 -0
- package/dist/sdk/client.d.ts.map +1 -1
- package/dist/sdk/client.js +15 -0
- package/dist/sdk/client.js.map +1 -1
- package/dist/sdk/invoke.d.ts +4 -0
- package/dist/sdk/invoke.d.ts.map +1 -1
- package/dist/sdk/invoke.js +2 -5
- package/dist/sdk/invoke.js.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
- package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.js +27 -23
- package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
- package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.js +9 -2
- package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
- package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet.js +3 -2
- package/dist/wallet/autonomous-wallet.js.map +1 -1
- package/dist/wallet/broker-escrows.d.ts +222 -0
- package/dist/wallet/broker-escrows.d.ts.map +1 -0
- package/dist/wallet/broker-escrows.js +36 -0
- package/dist/wallet/broker-escrows.js.map +1 -0
- package/dist/wallet/lifecycle.d.ts +21 -5
- package/dist/wallet/lifecycle.d.ts.map +1 -1
- package/dist/wallet/lifecycle.js +32 -12
- package/dist/wallet/lifecycle.js.map +1 -1
- package/dist/wallet/privy-broker-server.d.ts.map +1 -1
- package/dist/wallet/privy-broker-server.js +31 -26
- package/dist/wallet/privy-broker-server.js.map +1 -1
- package/dist/wallet/privy-session-broker.d.ts +14 -5
- package/dist/wallet/privy-session-broker.d.ts.map +1 -1
- package/dist/wallet/privy-session-broker.js +29 -17
- package/dist/wallet/privy-session-broker.js.map +1 -1
- package/dist/wallet/privy-session-provider.d.ts +3 -1
- package/dist/wallet/privy-session-provider.d.ts.map +1 -1
- package/dist/wallet/privy-session-provider.js +5 -3
- package/dist/wallet/privy-session-provider.js.map +1 -1
- package/dist/wallet/provider.d.ts.map +1 -1
- package/dist/wallet/provider.js +15 -8
- package/dist/wallet/provider.js.map +1 -1
- package/dist/x402/facilitator.d.ts +3 -30
- package/dist/x402/facilitator.d.ts.map +1 -1
- package/dist/x402/facilitator.js +0 -27
- package/dist/x402/facilitator.js.map +1 -1
- package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
- package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
- package/dist/x402-buyer/guarded-fetch.js +147 -0
- package/dist/x402-buyer/guarded-fetch.js.map +1 -0
- package/dist/x402-buyer/index.d.ts +10 -0
- package/dist/x402-buyer/index.d.ts.map +1 -0
- package/dist/x402-buyer/index.js +10 -0
- package/dist/x402-buyer/index.js.map +1 -0
- package/dist/x402-buyer/pay.d.ts +157 -0
- package/dist/x402-buyer/pay.d.ts.map +1 -0
- package/dist/x402-buyer/pay.js +366 -0
- package/dist/x402-buyer/pay.js.map +1 -0
- package/dist/x402-opener/abi.d.ts +684 -0
- package/dist/x402-opener/abi.d.ts.map +1 -0
- package/dist/x402-opener/abi.js +880 -0
- package/dist/x402-opener/abi.js.map +1 -0
- package/dist/x402-opener/facilitator-entry.d.ts +3 -0
- package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-entry.js +40 -0
- package/dist/x402-opener/facilitator-entry.js.map +1 -0
- package/dist/x402-opener/facilitator-server.d.ts +209 -0
- package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-server.js +762 -0
- package/dist/x402-opener/facilitator-server.js.map +1 -0
- package/dist/x402-opener/index.d.ts +14 -0
- package/dist/x402-opener/index.d.ts.map +1 -0
- package/dist/x402-opener/index.js +14 -0
- package/dist/x402-opener/index.js.map +1 -0
- package/dist/x402-opener/listing-resolver.d.ts +55 -0
- package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
- package/dist/x402-opener/listing-resolver.js +125 -0
- package/dist/x402-opener/listing-resolver.js.map +1 -0
- package/dist/x402-opener/refund-relay.d.ts +266 -0
- package/dist/x402-opener/refund-relay.d.ts.map +1 -0
- package/dist/x402-opener/refund-relay.js +1341 -0
- package/dist/x402-opener/refund-relay.js.map +1 -0
- package/dist/x402-opener/relayer-queue.d.ts +14 -0
- package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
- package/dist/x402-opener/relayer-queue.js +18 -0
- package/dist/x402-opener/relayer-queue.js.map +1 -0
- package/dist/x402-opener/scheme.d.ts +296 -0
- package/dist/x402-opener/scheme.d.ts.map +1 -0
- package/dist/x402-opener/scheme.js +1035 -0
- package/dist/x402-opener/scheme.js.map +1 -0
- package/dist/x402-opener/terms.d.ts +165 -0
- package/dist/x402-opener/terms.d.ts.map +1 -0
- package/dist/x402-opener/terms.js +304 -0
- package/dist/x402-opener/terms.js.map +1 -0
- package/dist/zktls/reclaim.d.ts +2 -2
- package/dist/zktls/t2-delivery-proof.d.ts +6 -6
- package/docs/agent-layer.md +3 -2
- package/docs/autonomous-privy-wallet.md +188 -0
- package/docs/cli.md +265 -34
- package/docs/langchain.md +5 -0
- package/docs/mcp-reference.md +91 -5
- package/docs/probe-capability.md +191 -0
- package/docs/quickstart.md +39 -4
- package/docs/threat-model.md +20 -0
- package/docs/x402.md +766 -593
- package/package.json +19 -17
- package/src/capability/probe-capability.ts +355 -0
- package/src/cli/args.ts +29 -0
- package/src/cli/commands/claim.ts +168 -33
- package/src/cli/commands/close.ts +36 -3
- package/src/cli/commands/invoke.ts +5 -2
- package/src/cli/commands/mcp.ts +18 -2
- package/src/cli/commands/open.ts +75 -4
- package/src/cli/commands/pay.ts +584 -0
- package/src/cli/commands/reclaim-unverified.ts +8 -2
- package/src/cli/commands/reclaim.ts +277 -19
- package/src/cli/commands/refund.ts +475 -0
- package/src/cli/commands/status.ts +28 -2
- package/src/cli/commands/streams.ts +10 -14
- package/src/cli/commands/watch.ts +11 -1
- package/src/cli/config.ts +139 -52
- package/src/cli/context.ts +16 -0
- package/src/cli/deps.ts +111 -1
- package/src/cli/errors.ts +24 -1
- package/src/cli/escape-hatch.ts +19 -5
- package/src/cli/listings.ts +43 -10
- package/src/cli/preflight.ts +36 -21
- package/src/cli/privy.ts +4 -2
- package/src/cli/progress.ts +21 -2
- package/src/cli/reclaimability.ts +154 -0
- package/src/cli/run.ts +77 -21
- package/src/cli/scan-range.ts +2 -2
- package/src/cli/status.ts +454 -44
- package/src/cli/wallet.ts +45 -8
- package/src/discovery/rate-band.ts +172 -0
- package/src/escrow-generation.ts +135 -0
- package/src/frameworks/agentkit.ts +45 -11
- package/src/frameworks/eliza.ts +27 -5
- package/src/frameworks/langchain.ts +14 -0
- package/src/gateway/caller-auth-gateway.ts +320 -68
- package/src/gateway/http-server.ts +717 -220
- package/src/gateway/probe-auth.ts +191 -0
- package/src/gateway/signed-rate-bounds.ts +164 -0
- package/src/gateway/x402-opener-mode.ts +1171 -0
- package/src/index.ts +82 -19
- package/src/mcp/server.ts +351 -42
- package/src/mcp/x402-tools.ts +785 -0
- package/src/network.ts +302 -0
- package/src/sdk/client.ts +25 -0
- package/src/sdk/invoke.ts +6 -5
- package/src/wallet/autonomous-wallet-broker.ts +46 -20
- package/src/wallet/autonomous-wallet-protocol.ts +11 -2
- package/src/wallet/autonomous-wallet.ts +4 -2
- package/src/wallet/broker-escrows.ts +66 -0
- package/src/wallet/lifecycle.ts +53 -18
- package/src/wallet/privy-broker-server.ts +35 -25
- package/src/wallet/privy-session-broker.ts +58 -25
- package/src/wallet/privy-session-provider.ts +7 -3
- package/src/wallet/provider.ts +20 -15
- package/src/x402/facilitator.ts +3 -43
- package/src/x402-buyer/guarded-fetch.ts +213 -0
- package/src/x402-buyer/index.ts +9 -0
- package/src/x402-buyer/pay.ts +555 -0
- package/src/x402-opener/abi.ts +881 -0
- package/src/x402-opener/facilitator-entry.ts +48 -0
- package/src/x402-opener/facilitator-server.ts +1114 -0
- package/src/x402-opener/index.ts +13 -0
- package/src/x402-opener/listing-resolver.ts +202 -0
- package/src/x402-opener/refund-relay.ts +1873 -0
- package/src/x402-opener/relayer-queue.ts +18 -0
- package/src/x402-opener/scheme.ts +1551 -0
- package/src/x402-opener/terms.ts +453 -0
- package/dist/gateway/x402-mode.d.ts +0 -123
- package/dist/gateway/x402-mode.d.ts.map +0 -1
- package/dist/gateway/x402-mode.js +0 -212
- package/dist/gateway/x402-mode.js.map +0 -1
- package/dist/x402/delivery-oracle.d.ts +0 -108
- package/dist/x402/delivery-oracle.d.ts.map +0 -1
- package/dist/x402/delivery-oracle.js +0 -174
- package/dist/x402/delivery-oracle.js.map +0 -1
- package/dist/x402/facilitator-server-entry.d.ts +0 -3
- package/dist/x402/facilitator-server-entry.d.ts.map +0 -1
- package/dist/x402/facilitator-server-entry.js +0 -27
- package/dist/x402/facilitator-server-entry.js.map +0 -1
- package/dist/x402/facilitator-server.d.ts +0 -73
- package/dist/x402/facilitator-server.d.ts.map +0 -1
- package/dist/x402/facilitator-server.js +0 -305
- package/dist/x402/facilitator-server.js.map +0 -1
- package/dist/x402/payment-requirements.d.ts +0 -106
- package/dist/x402/payment-requirements.d.ts.map +0 -1
- package/dist/x402/payment-requirements.js +0 -138
- package/dist/x402/payment-requirements.js.map +0 -1
- package/dist/x402/relayer.d.ts +0 -41
- package/dist/x402/relayer.d.ts.map +0 -1
- package/dist/x402/relayer.js +0 -64
- package/dist/x402/relayer.js.map +0 -1
- package/dist/x402/resource-index.d.ts +0 -75
- package/dist/x402/resource-index.d.ts.map +0 -1
- package/dist/x402/resource-index.js +0 -126
- package/dist/x402/resource-index.js.map +0 -1
- package/dist/x402/verified-delivery-facilitator.d.ts +0 -285
- package/dist/x402/verified-delivery-facilitator.d.ts.map +0 -1
- package/dist/x402/verified-delivery-facilitator.js +0 -423
- package/dist/x402/verified-delivery-facilitator.js.map +0 -1
- package/src/gateway/x402-mode.ts +0 -350
- package/src/x402/delivery-oracle.ts +0 -285
- package/src/x402/facilitator-server-entry.ts +0 -35
- package/src/x402/facilitator-server.ts +0 -445
- package/src/x402/payment-requirements.ts +0 -231
- package/src/x402/relayer.ts +0 -122
- package/src/x402/resource-index.ts +0 -228
- package/src/x402/verified-delivery-facilitator.ts +0 -744
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
import { HTTPFacilitatorClient, SETTLEMENT_OVERRIDES_HEADER, withPrivateCacheControl, x402HTTPResourceServer, x402ResourceServer, } from "@x402/core/server";
|
|
2
|
+
import { decodePaymentSignatureHeader } from "@x402/core/http";
|
|
3
|
+
import { ExactEvmScheme } from "@x402/evm/exact/server";
|
|
4
|
+
import { createPublicClient, formatUnits, getAddress, http, isAddress, } from "viem";
|
|
5
|
+
import { predictUpfrontOpenerAddress, x402UpfrontStreamOpenerFactoryAbi, } from "@absol-labs/shared";
|
|
6
|
+
import { x402StreamOpenerFactoryAbi } from "../x402-opener/abi.js";
|
|
7
|
+
import { RegistryListingResolver, } from "../x402-opener/listing-resolver.js";
|
|
8
|
+
import { readOpenerFacilitatorMarker } from "../x402-opener/scheme.js";
|
|
9
|
+
import { assertValidPrice, assertValidTerms, assertValidUpfrontTerms, chainIdFromNetwork, assertSchemaDeclaration, DEFAULT_OPENER_DOCS_URL, isHttpLink, OPENER_EXTRA_KEY, OPENER_SCHEME, termsToExtra, termsTuple, upfrontTermsToExtra, upfrontTermsTuple, } from "../x402-opener/terms.js";
|
|
10
|
+
/**
|
|
11
|
+
* The gateway's x402 v2 mode (metrik-agent#116): answer an uncapabilitied
|
|
12
|
+
* request with a standard x402 v2 `402` whose `payTo` is the listing's
|
|
13
|
+
* `X402StreamOpener` address, and settle every accepted payment INTO a
|
|
14
|
+
* `StreamEscrowV2` stream through the Metrik opener facilitator.
|
|
15
|
+
*
|
|
16
|
+
* The wire format is the official `@x402/core` resource server's, not a
|
|
17
|
+
* re-implementation: `x402HTTPResourceServer` builds `PAYMENT-REQUIRED`,
|
|
18
|
+
* matches `PAYMENT-SIGNATURE`, verifies and settles through the facilitator and
|
|
19
|
+
* builds `PAYMENT-RESPONSE`.
|
|
20
|
+
*
|
|
21
|
+
* ## The opener payTo must ONLY ever be settled by the Metrik opener facilitator
|
|
22
|
+
*
|
|
23
|
+
* A stock x402 `exact` facilitator settles by calling
|
|
24
|
+
* `USDC.transferWithAuthorization(to = payTo)` directly. Pointed at an opener,
|
|
25
|
+
* that strands 100% of the payer's funds in the opener permanently (there is,
|
|
26
|
+
* deliberately, no sweep). So this mode:
|
|
27
|
+
*
|
|
28
|
+
* - refuses to START unless the configured facilitator's `GET /supported`
|
|
29
|
+
* advertises the opener marker for exactly this factory, escrow, token and
|
|
30
|
+
* chain; and re-checks that marker on a timer, failing CLOSED (503, no
|
|
31
|
+
* `payTo` quoted, nothing verified or settled) whenever it cannot;
|
|
32
|
+
* - uses exactly one facilitator client, never a fallback list;
|
|
33
|
+
* - registers no discovery (Bazaar) extension and never submits the route to
|
|
34
|
+
* any catalog. When (and only when) the operator configures an input/output
|
|
35
|
+
* schema, it is DECLARED in the 402 in the standard `extensions.bazaar`
|
|
36
|
+
* shape so a client can read what to send; only the Metrik opener
|
|
37
|
+
* facilitator ever sees the payment, and it catalogs nothing;
|
|
38
|
+
* - states plainly in the 402 `description` what is bought (the stream
|
|
39
|
+
* window, rate, that the seller earns only verified seconds, and that
|
|
40
|
+
* unearned money is refundable without ETH through the facilitator's
|
|
41
|
+
* refund relay) and refuses to start unless that facilitator advertises
|
|
42
|
+
* the relay (`refundRelay: true` in its marker) — the 402 never promises a
|
|
43
|
+
* refund path that is not there. Refunds are not automatic;
|
|
44
|
+
* - authenticates the opener only as `factory.predict(terms)` — never by code
|
|
45
|
+
* or codehash, which a clone outside the factory can reproduce;
|
|
46
|
+
* - serves one EIP-3009 authorization at most once: a `PAYMENT-SIGNATURE`
|
|
47
|
+
* whose authorization is in flight or already settled gets `409` WITHOUT an
|
|
48
|
+
* upstream call (in-memory, per gateway instance). A retry after
|
|
49
|
+
* `settlement_pending` is let through so it can reconcile;
|
|
50
|
+
* - refuses to start if its price is below the facilitator's advertised
|
|
51
|
+
* minimum, or if its facilitator timeout would not outlast the facilitator's
|
|
52
|
+
* receipt wait.
|
|
53
|
+
*
|
|
54
|
+
* ## Two opener kinds
|
|
55
|
+
*
|
|
56
|
+
* Without `upfrontAmount` the listing quotes the `X402StreamOpenerFactory`
|
|
57
|
+
* (`"stream"`): the whole price funds a metered stream. With `upfrontAmount`
|
|
58
|
+
* it quotes the `X402UpfrontStreamOpenerFactory` (`"upfront"`, the "minimum
|
|
59
|
+
* charge"): `amount == price`, `payTo = predict(6 terms)`, the
|
|
60
|
+
* `upfrontAmount` is paid to the seller at settlement and is NOT refundable,
|
|
61
|
+
* and only `price - upfrontAmount` funds a metered, refundable stream. The 402
|
|
62
|
+
* description states that split. `upfrontAmount == price` is an upfront-only
|
|
63
|
+
* listing: no stream opens (the settlement reports `streamId: null`), the
|
|
64
|
+
* response is served, and no metered session or refund exists for it.
|
|
65
|
+
*/
|
|
66
|
+
/** How long a successful `/supported` marker check is trusted, seconds. */
|
|
67
|
+
export const DEFAULT_FACILITATOR_MARKER_TTL_SECONDS = 300;
|
|
68
|
+
/** Default per-request facilitator HTTP timeout. Must outlast its receipt wait. */
|
|
69
|
+
export const DEFAULT_FACILITATOR_TIMEOUT_MS = 120_000;
|
|
70
|
+
/** Headroom the facilitator timeout must leave over the facilitator's receipt wait. */
|
|
71
|
+
const FACILITATOR_TIMEOUT_HEADROOM_MS = 30_000;
|
|
72
|
+
/**
|
|
73
|
+
* The plain statement of what one payment buys, used as the 402 resource
|
|
74
|
+
* `description`. It names the window, the rate, that the seller earns only for
|
|
75
|
+
* seconds Metrik's verifier confirms, and where unearned money is refundable
|
|
76
|
+
* without ETH. It says that refunds are not automatic, because they are not:
|
|
77
|
+
* someone has to call the refund relay.
|
|
78
|
+
*/
|
|
79
|
+
export function describeOpenerPurchase(input) {
|
|
80
|
+
const amount = (value) => `${formatUnits(value, input.assetDecimals)} ${input.assetSymbol}`;
|
|
81
|
+
const { ratePerSecond, maxDuration } = input.terms;
|
|
82
|
+
const prefix = input.serviceDescription === undefined ||
|
|
83
|
+
input.serviceDescription.trim().length === 0
|
|
84
|
+
? ""
|
|
85
|
+
: `${input.serviceDescription.trim()} `;
|
|
86
|
+
if (input.upfrontAmount !== undefined) {
|
|
87
|
+
const upfront = input.upfrontAmount;
|
|
88
|
+
const metered = input.price - upfront;
|
|
89
|
+
if (metered === 0n) {
|
|
90
|
+
return (`${prefix}Pays for one call: ${amount(input.price)}, charged in full at settlement as a NON-REFUNDABLE per-call charge ` +
|
|
91
|
+
"(paid to the seller whatever is delivered). No escrow stream is opened, so nothing is metered and there is nothing to refund or reclaim. " +
|
|
92
|
+
`Docs: ${input.docsUrl}`);
|
|
93
|
+
}
|
|
94
|
+
const meteredCap = metered < ratePerSecond * maxDuration
|
|
95
|
+
? ` (the seller can earn at most ${amount(metered)} of it)`
|
|
96
|
+
: "";
|
|
97
|
+
return (`${prefix}Pays for one call: ${amount(input.price)} in total. ` +
|
|
98
|
+
(upfront === 0n
|
|
99
|
+
? "Nothing of it is charged upfront. "
|
|
100
|
+
: `${amount(upfront)} is a NON-REFUNDABLE per-call charge, paid to the seller at settlement whatever is delivered. `) +
|
|
101
|
+
`The remaining ${amount(metered)} is metered and refundable: it funds a Metrik escrow stream of ` +
|
|
102
|
+
`${maxDuration.toString()} seconds at ${amount(ratePerSecond)}/s${meteredCap}; ` +
|
|
103
|
+
"the seller earns it only for seconds Metrik's verifier confirms the service is delivering, " +
|
|
104
|
+
`and any unearned part of it (at most ${amount(metered)}) is refundable to you (no ETH needed) via ${input.refundUrlTemplate}. ` +
|
|
105
|
+
"Refunds are not automatic: close the stream and reclaim there, using the streamId from the PAYMENT-RESPONSE. " +
|
|
106
|
+
`Docs: ${input.docsUrl}`);
|
|
107
|
+
}
|
|
108
|
+
const cap = input.price < ratePerSecond * maxDuration
|
|
109
|
+
? ` (the seller can earn at most ${amount(input.price)})`
|
|
110
|
+
: "";
|
|
111
|
+
return (`${prefix}Pays for one call. Your payment of ${amount(input.price)} funds a Metrik escrow stream of ` +
|
|
112
|
+
`${maxDuration.toString()} seconds at ${amount(ratePerSecond)}/s${cap}; ` +
|
|
113
|
+
"the seller earns only for seconds Metrik's verifier confirms the service is delivering, " +
|
|
114
|
+
`and anything unearned is refundable to you (no ETH needed) via ${input.refundUrlTemplate}. ` +
|
|
115
|
+
"Refunds are not automatic: close the stream and reclaim there, using the streamId from the PAYMENT-RESPONSE. " +
|
|
116
|
+
`Docs: ${input.docsUrl}`);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The stock `exact` server scheme, plus ONE additive settlement enrichment:
|
|
120
|
+
* the successful `PAYMENT-RESPONSE` gets `extra.metrikStreamOpener.refundUrl`
|
|
121
|
+
* for the opened stream. It never touches the settlement outcome fields
|
|
122
|
+
* (`@x402/core` enforces that the enrichment is additive).
|
|
123
|
+
*/
|
|
124
|
+
class OpenerExactServerScheme extends ExactEvmScheme {
|
|
125
|
+
refundBaseUrl;
|
|
126
|
+
constructor(refundBaseUrl) {
|
|
127
|
+
super();
|
|
128
|
+
this.refundBaseUrl = refundBaseUrl;
|
|
129
|
+
}
|
|
130
|
+
enrichSettlementResponse = async (context) => {
|
|
131
|
+
if (!context.result.success)
|
|
132
|
+
return undefined;
|
|
133
|
+
const opened = context.result.extra?.[OPENER_EXTRA_KEY];
|
|
134
|
+
const streamId = opened?.streamId;
|
|
135
|
+
// An upfront-only payment reports `streamId: null` (no stream): it gets no
|
|
136
|
+
// refund URL, since there is nothing to refund. bytes32(0) is treated the
|
|
137
|
+
// same, defensively.
|
|
138
|
+
if (typeof streamId !== "string" ||
|
|
139
|
+
!/^0x[0-9a-fA-F]{64}$/.test(streamId) ||
|
|
140
|
+
/^0x0{64}$/i.test(streamId) ||
|
|
141
|
+
opened?.refundUrl !== undefined) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
[OPENER_EXTRA_KEY]: {
|
|
146
|
+
refundUrl: `${this.refundBaseUrl}/streams/${streamId.toLowerCase()}`,
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const PAYMENT_SIGNATURE_HEADER = "payment-signature";
|
|
152
|
+
/**
|
|
153
|
+
* Per-gateway, in-memory record of EIP-3009 authorizations (chain + asset +
|
|
154
|
+
* payer + nonce): `in-flight` while a request is being verified/served/
|
|
155
|
+
* settled, `pending` after a `settlement_pending` (a retry may reconcile), and
|
|
156
|
+
* `settled` once a success was delivered. In-flight and settled
|
|
157
|
+
* authorizations are refused before the upstream is ever called. Entries are
|
|
158
|
+
* dropped once the authorization's `validBefore` has passed (plus a grace).
|
|
159
|
+
*/
|
|
160
|
+
export class GatewayAuthorizationLedger {
|
|
161
|
+
now;
|
|
162
|
+
maxEntries;
|
|
163
|
+
entries = new Map();
|
|
164
|
+
constructor(now, maxEntries = 100_000) {
|
|
165
|
+
this.now = now;
|
|
166
|
+
this.maxEntries = maxEntries;
|
|
167
|
+
}
|
|
168
|
+
/** Claims the authorization for one request; false if it is in flight or settled. */
|
|
169
|
+
claim(key, validBefore) {
|
|
170
|
+
this.prune();
|
|
171
|
+
const entry = this.entries.get(key);
|
|
172
|
+
if (entry !== undefined && entry.state !== "pending")
|
|
173
|
+
return false;
|
|
174
|
+
if (entry === undefined && this.entries.size >= this.maxEntries)
|
|
175
|
+
return false;
|
|
176
|
+
this.entries.set(key, { state: "in-flight", validBefore });
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
release(key) {
|
|
180
|
+
this.entries.delete(key);
|
|
181
|
+
}
|
|
182
|
+
markPending(key, validBefore) {
|
|
183
|
+
this.entries.set(key, { state: "pending", validBefore });
|
|
184
|
+
}
|
|
185
|
+
markSettled(key, validBefore) {
|
|
186
|
+
this.entries.set(key, { state: "settled", validBefore });
|
|
187
|
+
}
|
|
188
|
+
prune() {
|
|
189
|
+
const now = BigInt(this.now());
|
|
190
|
+
for (const [key, entry] of this.entries) {
|
|
191
|
+
if (entry.state !== "in-flight" && entry.validBefore + 600n < now) {
|
|
192
|
+
this.entries.delete(key);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** Ledger key for a `PAYMENT-SIGNATURE`, or undefined if it does not decode. */
|
|
198
|
+
function authorizationKey(header) {
|
|
199
|
+
try {
|
|
200
|
+
const payload = decodePaymentSignatureHeader(header);
|
|
201
|
+
const authorization = payload.payload.authorization;
|
|
202
|
+
const network = payload.accepted?.network;
|
|
203
|
+
const asset = payload.accepted?.asset;
|
|
204
|
+
if (typeof authorization?.from !== "string" ||
|
|
205
|
+
typeof authorization.nonce !== "string" ||
|
|
206
|
+
typeof authorization.validBefore !== "string" ||
|
|
207
|
+
!/^\d+$/.test(authorization.validBefore) ||
|
|
208
|
+
typeof network !== "string" ||
|
|
209
|
+
typeof asset !== "string") {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
key: [
|
|
214
|
+
network,
|
|
215
|
+
asset.toLowerCase(),
|
|
216
|
+
authorization.from.toLowerCase(),
|
|
217
|
+
authorization.nonce.toLowerCase(),
|
|
218
|
+
].join(":"),
|
|
219
|
+
validBefore: BigInt(authorization.validBefore),
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export class X402OpenerModeConfigError extends Error {
|
|
227
|
+
constructor(message) {
|
|
228
|
+
super(message);
|
|
229
|
+
this.name = "X402OpenerModeConfigError";
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
export class X402OpenerFacilitatorUnverifiedError extends Error {
|
|
233
|
+
constructor(message, options) {
|
|
234
|
+
super(message, options);
|
|
235
|
+
this.name = "X402OpenerFacilitatorUnverifiedError";
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Builds the x402 mode and proves, before returning, every fact it will quote:
|
|
240
|
+
* valid terms and price, one operator-signed listing for the terms, the
|
|
241
|
+
* factory's escrow and token, the predicted `payTo`, and the facilitator's
|
|
242
|
+
* opener marker. Throws on any doubt; the gateway then refuses to start.
|
|
243
|
+
*/
|
|
244
|
+
export async function buildGatewayX402OpenerMode(config, deps = {}) {
|
|
245
|
+
const kind = config.upfrontAmount === undefined ? "stream" : "upfront";
|
|
246
|
+
const upfrontTerms = config.upfrontAmount === undefined
|
|
247
|
+
? undefined
|
|
248
|
+
: {
|
|
249
|
+
...config.terms,
|
|
250
|
+
price: config.price,
|
|
251
|
+
upfrontAmount: config.upfrontAmount,
|
|
252
|
+
};
|
|
253
|
+
try {
|
|
254
|
+
if (upfrontTerms === undefined) {
|
|
255
|
+
assertValidTerms(config.terms);
|
|
256
|
+
assertValidPrice(config.price, config.terms);
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
// The factory's own validateTerms rules + amount == price + the metered
|
|
260
|
+
// part within rate * maxDuration: exactly what the SDK buyer requires.
|
|
261
|
+
assertValidUpfrontTerms(upfrontTerms);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
throw new X402OpenerModeConfigError(error instanceof Error ? error.message : String(error));
|
|
266
|
+
}
|
|
267
|
+
const chainId = chainIdFromNetwork(config.network);
|
|
268
|
+
for (const [name, value] of [
|
|
269
|
+
["factoryAddress", config.factoryAddress],
|
|
270
|
+
["escrowAddress", config.escrowAddress],
|
|
271
|
+
["asset", config.asset],
|
|
272
|
+
]) {
|
|
273
|
+
if (!isAddress(value)) {
|
|
274
|
+
throw new X402OpenerModeConfigError(`${name} must be an EVM address`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const maxTimeoutSeconds = config.maxTimeoutSeconds ?? 300;
|
|
278
|
+
if (!Number.isInteger(maxTimeoutSeconds) || maxTimeoutSeconds < 30) {
|
|
279
|
+
throw new X402OpenerModeConfigError("maxTimeoutSeconds must be an integer >= 30");
|
|
280
|
+
}
|
|
281
|
+
if (config.facilitatorToken.length === 0) {
|
|
282
|
+
throw new X402OpenerModeConfigError("facilitatorToken is required");
|
|
283
|
+
}
|
|
284
|
+
if (config.resourceBaseUrl !== undefined) {
|
|
285
|
+
// eslint-disable-next-line no-new -- validates the URL is well-formed.
|
|
286
|
+
new URL(config.resourceBaseUrl);
|
|
287
|
+
}
|
|
288
|
+
const refundBaseUrl = (config.refundBaseUrl ?? config.facilitatorUrl).replace(/\/+$/, "");
|
|
289
|
+
const docsUrl = config.docsUrl ?? DEFAULT_OPENER_DOCS_URL;
|
|
290
|
+
for (const [name, value] of [
|
|
291
|
+
["refundBaseUrl", refundBaseUrl],
|
|
292
|
+
["docsUrl", docsUrl],
|
|
293
|
+
]) {
|
|
294
|
+
if (!isHttpLink(value)) {
|
|
295
|
+
throw new X402OpenerModeConfigError(`${name} must be an http(s) URL`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const assetDecimals = config.assetDecimals ?? 6;
|
|
299
|
+
if (!Number.isInteger(assetDecimals) ||
|
|
300
|
+
assetDecimals < 0 ||
|
|
301
|
+
assetDecimals > 36) {
|
|
302
|
+
throw new X402OpenerModeConfigError("assetDecimals must be an integer in [0, 36]");
|
|
303
|
+
}
|
|
304
|
+
if (config.schemaDeclaration !== undefined) {
|
|
305
|
+
try {
|
|
306
|
+
assertSchemaDeclaration(config.schemaDeclaration);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
throw new X402OpenerModeConfigError(error instanceof Error ? error.message : String(error));
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const publicClient = deps.publicClient ??
|
|
313
|
+
(deps.rpcUrl === undefined
|
|
314
|
+
? undefined
|
|
315
|
+
: createPublicClient({ transport: http(deps.rpcUrl) }));
|
|
316
|
+
if (publicClient === undefined) {
|
|
317
|
+
throw new X402OpenerModeConfigError("an RPC (publicClient or rpcUrl) is required to predict the opener address");
|
|
318
|
+
}
|
|
319
|
+
const rpcChainId = await publicClient.getChainId();
|
|
320
|
+
if (rpcChainId !== chainId) {
|
|
321
|
+
throw new X402OpenerModeConfigError(`RPC chain id ${rpcChainId} does not match network ${config.network}`);
|
|
322
|
+
}
|
|
323
|
+
const factory = getAddress(config.factoryAddress);
|
|
324
|
+
const escrow = getAddress(config.escrowAddress);
|
|
325
|
+
const asset = getAddress(config.asset);
|
|
326
|
+
let factoryEscrow;
|
|
327
|
+
let factoryUsdc;
|
|
328
|
+
let predicted;
|
|
329
|
+
if (upfrontTerms === undefined) {
|
|
330
|
+
[factoryEscrow, factoryUsdc, predicted] = await Promise.all([
|
|
331
|
+
publicClient.readContract({
|
|
332
|
+
address: factory,
|
|
333
|
+
abi: x402StreamOpenerFactoryAbi,
|
|
334
|
+
functionName: "escrow",
|
|
335
|
+
}),
|
|
336
|
+
publicClient.readContract({
|
|
337
|
+
address: factory,
|
|
338
|
+
abi: x402StreamOpenerFactoryAbi,
|
|
339
|
+
functionName: "usdc",
|
|
340
|
+
}),
|
|
341
|
+
publicClient.readContract({
|
|
342
|
+
address: factory,
|
|
343
|
+
abi: x402StreamOpenerFactoryAbi,
|
|
344
|
+
functionName: "predict",
|
|
345
|
+
args: [termsTuple(config.terms)],
|
|
346
|
+
}),
|
|
347
|
+
]);
|
|
348
|
+
}
|
|
349
|
+
else {
|
|
350
|
+
let implementation;
|
|
351
|
+
[factoryEscrow, factoryUsdc, predicted, implementation] = await Promise.all([
|
|
352
|
+
publicClient.readContract({
|
|
353
|
+
address: factory,
|
|
354
|
+
abi: x402UpfrontStreamOpenerFactoryAbi,
|
|
355
|
+
functionName: "escrow",
|
|
356
|
+
}),
|
|
357
|
+
publicClient.readContract({
|
|
358
|
+
address: factory,
|
|
359
|
+
abi: x402UpfrontStreamOpenerFactoryAbi,
|
|
360
|
+
functionName: "usdc",
|
|
361
|
+
}),
|
|
362
|
+
publicClient.readContract({
|
|
363
|
+
address: factory,
|
|
364
|
+
abi: x402UpfrontStreamOpenerFactoryAbi,
|
|
365
|
+
functionName: "predict",
|
|
366
|
+
args: [upfrontTermsTuple(upfrontTerms)],
|
|
367
|
+
}),
|
|
368
|
+
publicClient.readContract({
|
|
369
|
+
address: factory,
|
|
370
|
+
abi: x402UpfrontStreamOpenerFactoryAbi,
|
|
371
|
+
functionName: "implementation",
|
|
372
|
+
}),
|
|
373
|
+
]).catch((error) => {
|
|
374
|
+
throw new X402OpenerModeConfigError(`factory ${factory} is not an X402UpfrontStreamOpenerFactory that accepts these upfront terms (${error instanceof Error ? (error.message.split("\n")[0] ?? "error") : String(error)})`);
|
|
375
|
+
});
|
|
376
|
+
if (config.upfrontImplementation !== undefined &&
|
|
377
|
+
getAddress(implementation) !== getAddress(config.upfrontImplementation)) {
|
|
378
|
+
throw new X402OpenerModeConfigError(`upfront factory ${factory} reports implementation ${implementation}, not the expected ${config.upfrontImplementation}`);
|
|
379
|
+
}
|
|
380
|
+
// The SDK buyer recomputes payTo OFFLINE; quote only a payTo both agree on.
|
|
381
|
+
const offline = predictUpfrontOpenerAddress({
|
|
382
|
+
factory,
|
|
383
|
+
implementation: getAddress(implementation),
|
|
384
|
+
terms: {
|
|
385
|
+
operator: getAddress(upfrontTerms.operator),
|
|
386
|
+
serviceRef: upfrontTerms.serviceRef.toLowerCase(),
|
|
387
|
+
ratePerSecond: upfrontTerms.ratePerSecond,
|
|
388
|
+
maxDuration: upfrontTerms.maxDuration,
|
|
389
|
+
price: upfrontTerms.price,
|
|
390
|
+
upfrontAmount: upfrontTerms.upfrontAmount,
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
if (getAddress(offline) !== getAddress(predicted)) {
|
|
394
|
+
throw new X402OpenerModeConfigError(`factory.predict(terms) = ${predicted} disagrees with the offline CREATE2 derivation ${offline}; refusing to quote it`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (getAddress(factoryEscrow) !== escrow) {
|
|
398
|
+
throw new X402OpenerModeConfigError(`factory ${factory} settles into ${factoryEscrow}, not this gateway's escrow ${escrow}`);
|
|
399
|
+
}
|
|
400
|
+
if (getAddress(factoryUsdc) !== asset) {
|
|
401
|
+
throw new X402OpenerModeConfigError(`factory token ${factoryUsdc} is not the configured asset ${asset}`);
|
|
402
|
+
}
|
|
403
|
+
const payTo = getAddress(predicted);
|
|
404
|
+
const resolver = deps.listingResolver ??
|
|
405
|
+
new RegistryListingResolver(config.registryUrl === undefined
|
|
406
|
+
? {}
|
|
407
|
+
: { registryUrl: config.registryUrl });
|
|
408
|
+
const listing = await resolver.resolve(config.terms);
|
|
409
|
+
if (!listing.ok) {
|
|
410
|
+
throw new X402OpenerModeConfigError(`listing check failed (${listing.reason}): ${listing.message}`);
|
|
411
|
+
}
|
|
412
|
+
const facilitatorTimeoutMs = config.facilitatorTimeoutMs ?? DEFAULT_FACILITATOR_TIMEOUT_MS;
|
|
413
|
+
if (!Number.isInteger(facilitatorTimeoutMs) || facilitatorTimeoutMs <= 0) {
|
|
414
|
+
throw new X402OpenerModeConfigError("facilitatorTimeoutMs must be a positive integer");
|
|
415
|
+
}
|
|
416
|
+
const facilitatorClient = deps.facilitatorClient ??
|
|
417
|
+
new HTTPFacilitatorClient({
|
|
418
|
+
url: config.facilitatorUrl,
|
|
419
|
+
timeoutMs: facilitatorTimeoutMs,
|
|
420
|
+
createAuthHeaders: async () => {
|
|
421
|
+
const headers = { Authorization: `Bearer ${config.facilitatorToken}` };
|
|
422
|
+
return { verify: headers, settle: headers, supported: headers };
|
|
423
|
+
},
|
|
424
|
+
});
|
|
425
|
+
const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
|
|
426
|
+
const markerTtl = config.markerTtlSeconds ?? DEFAULT_FACILITATOR_MARKER_TTL_SECONDS;
|
|
427
|
+
let markerCheckedAt;
|
|
428
|
+
const checkMarker = async () => {
|
|
429
|
+
let supported;
|
|
430
|
+
try {
|
|
431
|
+
supported = await facilitatorClient.getSupported();
|
|
432
|
+
}
|
|
433
|
+
catch (cause) {
|
|
434
|
+
throw new X402OpenerFacilitatorUnverifiedError(`the x402 facilitator at ${config.facilitatorUrl} is unreachable`, { cause });
|
|
435
|
+
}
|
|
436
|
+
const supportedKind = supported.kinds.find((candidate) => candidate.x402Version === 2 &&
|
|
437
|
+
candidate.scheme === OPENER_SCHEME &&
|
|
438
|
+
candidate.network === config.network);
|
|
439
|
+
const marker = readOpenerFacilitatorMarker(supportedKind?.extra);
|
|
440
|
+
if (marker === undefined ||
|
|
441
|
+
!markerSettles(marker, upfrontTerms === undefined ? "stream" : "upfront", factory, escrow) ||
|
|
442
|
+
marker.usdc !== asset ||
|
|
443
|
+
marker.chainId !== chainId) {
|
|
444
|
+
throw new X402OpenerFacilitatorUnverifiedError(`the x402 facilitator at ${config.facilitatorUrl} does not advertise Metrik ${upfrontTerms === undefined ? "" : "upfront "}opener settlement for factory ${factory} on ${config.network}. ` +
|
|
445
|
+
"Refusing to quote an opener payTo: a stock exact facilitator would transfer the payment straight to the opener and strand it permanently.");
|
|
446
|
+
}
|
|
447
|
+
if (marker.refundRelay !== true) {
|
|
448
|
+
throw new X402OpenerFacilitatorUnverifiedError(`the x402 facilitator at ${config.facilitatorUrl} does not advertise the gasless refund relay (refundRelay: true). ` +
|
|
449
|
+
"Refusing to quote: the 402 tells payers unearned money is refundable without ETH, which needs that relay.");
|
|
450
|
+
}
|
|
451
|
+
if (config.price < BigInt(marker.minAmount)) {
|
|
452
|
+
throw new X402OpenerModeConfigError(`price ${config.price} is below the facilitator minimum ${marker.minAmount}`);
|
|
453
|
+
}
|
|
454
|
+
if (facilitatorTimeoutMs <
|
|
455
|
+
marker.receiptTimeoutSeconds * 1000 + FACILITATOR_TIMEOUT_HEADROOM_MS) {
|
|
456
|
+
throw new X402OpenerModeConfigError(`the facilitator timeout ${facilitatorTimeoutMs}ms does not outlast the facilitator's ${marker.receiptTimeoutSeconds}s receipt wait by ${FACILITATOR_TIMEOUT_HEADROOM_MS / 1000}s`);
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
const resourceServer = new x402ResourceServer(facilitatorClient).register(config.network, new OpenerExactServerScheme(refundBaseUrl));
|
|
460
|
+
const description = describeOpenerPurchase({
|
|
461
|
+
terms: config.terms,
|
|
462
|
+
price: config.price,
|
|
463
|
+
...(config.upfrontAmount === undefined
|
|
464
|
+
? {}
|
|
465
|
+
: { upfrontAmount: config.upfrontAmount }),
|
|
466
|
+
assetDecimals,
|
|
467
|
+
assetSymbol: config.assetName,
|
|
468
|
+
refundUrlTemplate: `${refundBaseUrl}/streams/{streamId}`,
|
|
469
|
+
docsUrl,
|
|
470
|
+
...(config.description === undefined
|
|
471
|
+
? {}
|
|
472
|
+
: { serviceDescription: config.description }),
|
|
473
|
+
});
|
|
474
|
+
const route = {
|
|
475
|
+
accepts: {
|
|
476
|
+
scheme: OPENER_SCHEME,
|
|
477
|
+
network: config.network,
|
|
478
|
+
payTo,
|
|
479
|
+
price: {
|
|
480
|
+
asset,
|
|
481
|
+
amount: config.price.toString(),
|
|
482
|
+
extra: {
|
|
483
|
+
name: config.assetName,
|
|
484
|
+
version: config.assetVersion,
|
|
485
|
+
assetTransferMethod: "eip3009",
|
|
486
|
+
[OPENER_EXTRA_KEY]: upfrontTerms === undefined
|
|
487
|
+
? {
|
|
488
|
+
...termsToExtra(factory, config.terms),
|
|
489
|
+
refundUrl: `${refundBaseUrl}/streams/{streamId}`,
|
|
490
|
+
docsUrl,
|
|
491
|
+
}
|
|
492
|
+
: {
|
|
493
|
+
...upfrontTermsToExtra(factory, upfrontTerms),
|
|
494
|
+
// An upfront-only listing opens no stream: no refund URL.
|
|
495
|
+
...(upfrontTerms.upfrontAmount === upfrontTerms.price
|
|
496
|
+
? {}
|
|
497
|
+
: { refundUrl: `${refundBaseUrl}/streams/{streamId}` }),
|
|
498
|
+
docsUrl,
|
|
499
|
+
},
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
maxTimeoutSeconds,
|
|
503
|
+
},
|
|
504
|
+
description,
|
|
505
|
+
mimeType: "application/json",
|
|
506
|
+
...(config.schemaDeclaration === undefined
|
|
507
|
+
? {}
|
|
508
|
+
: { extensions: { bazaar: config.schemaDeclaration } }),
|
|
509
|
+
unpaidResponseBody: () => ({
|
|
510
|
+
contentType: "application/json",
|
|
511
|
+
body: { authorized: false, reason: "payment-required" },
|
|
512
|
+
}),
|
|
513
|
+
};
|
|
514
|
+
const httpServer = new x402HTTPResourceServer(resourceServer, route);
|
|
515
|
+
let initialized;
|
|
516
|
+
const ready = async () => {
|
|
517
|
+
const nowSeconds = now();
|
|
518
|
+
if (markerCheckedAt === undefined ||
|
|
519
|
+
nowSeconds - markerCheckedAt >= markerTtl) {
|
|
520
|
+
markerCheckedAt = undefined;
|
|
521
|
+
await checkMarker();
|
|
522
|
+
markerCheckedAt = nowSeconds;
|
|
523
|
+
}
|
|
524
|
+
if (initialized === undefined) {
|
|
525
|
+
initialized = httpServer.initialize().catch((error) => {
|
|
526
|
+
initialized = undefined;
|
|
527
|
+
throw new X402OpenerFacilitatorUnverifiedError("the x402 resource server could not initialize against the facilitator", { cause: error });
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
await initialized;
|
|
531
|
+
};
|
|
532
|
+
// Prove the facilitator at startup: refuse to start otherwise.
|
|
533
|
+
await ready();
|
|
534
|
+
if (refundBaseUrl !== config.facilitatorUrl.replace(/\/+$/, "")) {
|
|
535
|
+
await checkRefundRelayAt(refundBaseUrl, deps.fetch ?? fetch, {
|
|
536
|
+
kind,
|
|
537
|
+
factory,
|
|
538
|
+
escrow,
|
|
539
|
+
asset,
|
|
540
|
+
chainId,
|
|
541
|
+
network: config.network,
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
const mode = {
|
|
545
|
+
payTo,
|
|
546
|
+
network: config.network,
|
|
547
|
+
terms: config.terms,
|
|
548
|
+
price: config.price,
|
|
549
|
+
openerKind: kind,
|
|
550
|
+
upfrontAmount: config.upfrontAmount ?? null,
|
|
551
|
+
resourceBaseUrl: config.resourceBaseUrl,
|
|
552
|
+
description,
|
|
553
|
+
refundBaseUrl,
|
|
554
|
+
httpServer,
|
|
555
|
+
authorizations: new GatewayAuthorizationLedger(now),
|
|
556
|
+
ready,
|
|
557
|
+
handle: (io) => handleX402GatewayRequest(mode, io).catch((error) => {
|
|
558
|
+
io.logError("x402 request failed", error);
|
|
559
|
+
io.writeJson(500, "internal-error");
|
|
560
|
+
}),
|
|
561
|
+
};
|
|
562
|
+
return mode;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* A refund base URL other than the facilitator URL (e.g. the public origin of
|
|
566
|
+
* the same service) must serve the same opener marker with the relay on, so
|
|
567
|
+
* the 402 never points payers at a URL that cannot refund them.
|
|
568
|
+
*/
|
|
569
|
+
async function checkRefundRelayAt(refundBaseUrl, fetchImpl, expected) {
|
|
570
|
+
let supported;
|
|
571
|
+
try {
|
|
572
|
+
const response = await fetchImpl(`${refundBaseUrl}/supported`, {
|
|
573
|
+
signal: AbortSignal.timeout(10_000),
|
|
574
|
+
});
|
|
575
|
+
if (!response.ok)
|
|
576
|
+
throw new Error(`HTTP ${response.status}`);
|
|
577
|
+
supported = (await response.json());
|
|
578
|
+
}
|
|
579
|
+
catch (cause) {
|
|
580
|
+
throw new X402OpenerFacilitatorUnverifiedError(`the refund relay at ${refundBaseUrl} is unreachable`, { cause });
|
|
581
|
+
}
|
|
582
|
+
const kind = supported.kinds?.find((candidate) => candidate.x402Version === 2 &&
|
|
583
|
+
candidate.scheme === OPENER_SCHEME &&
|
|
584
|
+
candidate.network === expected.network);
|
|
585
|
+
const marker = readOpenerFacilitatorMarker(kind?.extra);
|
|
586
|
+
if (marker === undefined ||
|
|
587
|
+
!markerSettles(marker, expected.kind, expected.factory, expected.escrow) ||
|
|
588
|
+
marker.usdc !== expected.asset ||
|
|
589
|
+
marker.chainId !== expected.chainId ||
|
|
590
|
+
marker.refundRelay !== true) {
|
|
591
|
+
throw new X402OpenerFacilitatorUnverifiedError(`${refundBaseUrl} does not serve the Metrik opener refund relay for factory ${expected.factory}; refusing to advertise it as the refund URL`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Whether a facilitator marker settles THIS listing's opener kind: the stream
|
|
596
|
+
* factory is the marker's `factory`; the upfront factory its `upfrontOpener`.
|
|
597
|
+
*/
|
|
598
|
+
function markerSettles(marker, kind, factory, escrow) {
|
|
599
|
+
if (kind === "upfront") {
|
|
600
|
+
return (marker.upfrontOpener !== undefined &&
|
|
601
|
+
marker.upfrontOpener.factory === factory &&
|
|
602
|
+
marker.upfrontOpener.escrow === escrow &&
|
|
603
|
+
marker.escrow === escrow);
|
|
604
|
+
}
|
|
605
|
+
return marker.factory === factory && marker.escrow === escrow;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* One x402-mode request, mirroring the reference `@x402/*` middleware: verify
|
|
609
|
+
* via the facilitator, run the upstream, and settle ONLY when the upstream
|
|
610
|
+
* status is < 400 — before any upstream byte is sent. A failed settlement sends
|
|
611
|
+
* no upstream body. Every facilitator error fails closed: never a free call.
|
|
612
|
+
*/
|
|
613
|
+
async function handleX402GatewayRequest(mode, io) {
|
|
614
|
+
try {
|
|
615
|
+
await mode.ready();
|
|
616
|
+
}
|
|
617
|
+
catch (error) {
|
|
618
|
+
// The facilitator is not provably the Metrik opener facilitator right now:
|
|
619
|
+
// quote no payTo and verify nothing (a stock facilitator would strand it).
|
|
620
|
+
io.logError("x402 facilitator unverified", error);
|
|
621
|
+
io.writeJson(503, "x402-facilitator-unavailable");
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
const { requestUrl, method, headers } = io;
|
|
625
|
+
const origin = mode.resourceBaseUrl ?? `http://${headers.host ?? "localhost"}`;
|
|
626
|
+
const fullUrl = new URL(requestUrl.pathname + requestUrl.search, origin).toString();
|
|
627
|
+
const adapter = {
|
|
628
|
+
getHeader: (name) => headers[name.toLowerCase()],
|
|
629
|
+
getMethod: () => method,
|
|
630
|
+
getPath: () => requestUrl.pathname,
|
|
631
|
+
getUrl: () => fullUrl,
|
|
632
|
+
getAcceptHeader: () => headers.accept ?? "",
|
|
633
|
+
getUserAgent: () => headers["user-agent"] ?? "",
|
|
634
|
+
};
|
|
635
|
+
const paymentHeader = headers[PAYMENT_SIGNATURE_HEADER]?.trim();
|
|
636
|
+
const context = {
|
|
637
|
+
adapter,
|
|
638
|
+
path: requestUrl.pathname,
|
|
639
|
+
method,
|
|
640
|
+
...(paymentHeader === undefined || paymentHeader.length === 0
|
|
641
|
+
? {}
|
|
642
|
+
: { paymentHeader }),
|
|
643
|
+
};
|
|
644
|
+
// One authorization, at most one served response: claim it before verify so
|
|
645
|
+
// a concurrent duplicate never reaches the facilitator or the upstream.
|
|
646
|
+
const claim = paymentHeader === undefined || paymentHeader.length === 0
|
|
647
|
+
? undefined
|
|
648
|
+
: authorizationKey(paymentHeader);
|
|
649
|
+
if (claim !== undefined &&
|
|
650
|
+
!mode.authorizations.claim(claim.key, claim.validBefore)) {
|
|
651
|
+
io.writeJson(409, "x402-payment-already-used");
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const release = () => {
|
|
655
|
+
if (claim !== undefined)
|
|
656
|
+
mode.authorizations.release(claim.key);
|
|
657
|
+
};
|
|
658
|
+
let result;
|
|
659
|
+
try {
|
|
660
|
+
result = await mode.httpServer.processHTTPRequest(context);
|
|
661
|
+
}
|
|
662
|
+
catch (error) {
|
|
663
|
+
release();
|
|
664
|
+
io.logError("x402 verification failed", error);
|
|
665
|
+
io.writeJson(402, "x402-facilitator-unavailable");
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
if (result.type === "no-payment-required") {
|
|
669
|
+
// The route covers every path; reaching here is a misconfiguration.
|
|
670
|
+
release();
|
|
671
|
+
io.writeJson(500, "internal-error");
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (result.type === "payment-error") {
|
|
675
|
+
release();
|
|
676
|
+
writeInstructions(io, result.response);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
const { cancellationDispatcher, beforeHandlerSettlement, paymentPayload, paymentRequirements, declaredExtensions, } = result;
|
|
680
|
+
let upstream;
|
|
681
|
+
try {
|
|
682
|
+
upstream = await io.callUpstream();
|
|
683
|
+
}
|
|
684
|
+
catch (error) {
|
|
685
|
+
await cancellationDispatcher
|
|
686
|
+
.cancel({ reason: "handler_threw", error })
|
|
687
|
+
.catch(() => undefined);
|
|
688
|
+
release();
|
|
689
|
+
io.logError("upstream request failed", error);
|
|
690
|
+
io.writeJson(502, "upstream-unavailable");
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
// The seller's upstream must not steer settlement.
|
|
694
|
+
const upstreamHeaders = {};
|
|
695
|
+
for (const [key, value] of Object.entries(upstream.headers)) {
|
|
696
|
+
if (key.toLowerCase() === SETTLEMENT_OVERRIDES_HEADER.toLowerCase())
|
|
697
|
+
continue;
|
|
698
|
+
upstreamHeaders[key] = value;
|
|
699
|
+
}
|
|
700
|
+
if (upstream.status >= 400) {
|
|
701
|
+
// Nothing is settled for a failed upstream: the authorization is never
|
|
702
|
+
// submitted, so no funds move.
|
|
703
|
+
await cancellationDispatcher
|
|
704
|
+
.cancel({ reason: "handler_failed", responseStatus: upstream.status })
|
|
705
|
+
.catch(() => undefined);
|
|
706
|
+
release();
|
|
707
|
+
io.write(upstream.status, upstreamHeaders, upstream.body);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
let settled;
|
|
711
|
+
try {
|
|
712
|
+
settled = await mode.httpServer.processSettlement(paymentPayload, paymentRequirements, declaredExtensions, {
|
|
713
|
+
request: context,
|
|
714
|
+
responseBody: upstream.body,
|
|
715
|
+
responseHeaders: upstreamHeaders,
|
|
716
|
+
}, undefined, beforeHandlerSettlement);
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
// Unknown outcome (e.g. the facilitator timed out): let a retry of the same
|
|
720
|
+
// signature through so the facilitator's ledger can reconcile it — that
|
|
721
|
+
// ledger, not this one, guarantees at most one success.
|
|
722
|
+
if (claim !== undefined) {
|
|
723
|
+
mode.authorizations.markPending(claim.key, claim.validBefore);
|
|
724
|
+
}
|
|
725
|
+
io.logError("x402 settlement failed", error);
|
|
726
|
+
io.writeJson(402, "x402-settlement-failed");
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (!settled.success) {
|
|
730
|
+
if (claim !== undefined) {
|
|
731
|
+
if (settled.errorReason === "settlement_pending") {
|
|
732
|
+
mode.authorizations.markPending(claim.key, claim.validBefore);
|
|
733
|
+
}
|
|
734
|
+
else if (settled.errorReason === "duplicate_settlement") {
|
|
735
|
+
mode.authorizations.markSettled(claim.key, claim.validBefore);
|
|
736
|
+
}
|
|
737
|
+
else {
|
|
738
|
+
release();
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
// No upstream body on a failed settlement.
|
|
742
|
+
writeInstructions(io, settled.response);
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (claim !== undefined) {
|
|
746
|
+
mode.authorizations.markSettled(claim.key, claim.validBefore);
|
|
747
|
+
}
|
|
748
|
+
const responseHeaders = {};
|
|
749
|
+
let existingCacheControl = null;
|
|
750
|
+
for (const [key, value] of Object.entries(upstreamHeaders)) {
|
|
751
|
+
if (key.toLowerCase() === "cache-control") {
|
|
752
|
+
existingCacheControl = value;
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
responseHeaders[key] = value;
|
|
756
|
+
}
|
|
757
|
+
Object.assign(responseHeaders, settled.headers);
|
|
758
|
+
responseHeaders["Cache-Control"] =
|
|
759
|
+
withPrivateCacheControl(existingCacheControl);
|
|
760
|
+
io.write(upstream.status, responseHeaders, upstream.body);
|
|
761
|
+
}
|
|
762
|
+
function writeInstructions(io, response) {
|
|
763
|
+
const headers = { ...response.headers };
|
|
764
|
+
if (response.isHtml === true) {
|
|
765
|
+
headers["Content-Type"] = "text/html; charset=utf-8";
|
|
766
|
+
io.write(response.status, headers, String(response.body ?? ""));
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
headers["Content-Type"] = "application/json";
|
|
770
|
+
io.write(response.status, headers, JSON.stringify(response.body ?? {}));
|
|
771
|
+
}
|
|
772
|
+
//# sourceMappingURL=x402-opener-mode.js.map
|