@fatstack/x402 0.1.0 → 0.1.1
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/dist/{chunk-6LSPHKJ7.js → chunk-C4BASAUA.js} +25 -2
- package/dist/chunk-C4BASAUA.js.map +1 -0
- package/dist/{chunk-7DVR574O.js → chunk-PY25VKHS.js} +13 -7
- package/dist/chunk-PY25VKHS.js.map +1 -0
- package/dist/{chunk-HCN75CTX.js → chunk-ZGVPNFNS.js} +30 -11
- package/dist/chunk-ZGVPNFNS.js.map +1 -0
- package/dist/{client-C8_arVa4.d.cts → client-BBsrY6gC.d.cts} +26 -1
- package/dist/{client-C8_arVa4.d.ts → client-BBsrY6gC.d.ts} +26 -1
- package/dist/client.cjs +47 -11
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +6 -4
- package/dist/index.cjs +65 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -2
- package/dist/index.d.ts +12 -2
- package/dist/index.js +16 -4
- package/dist/index.js.map +1 -1
- package/dist/provider.cjs +21 -5
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-6LSPHKJ7.js.map +0 -1
- package/dist/chunk-7DVR574O.js.map +0 -1
- package/dist/chunk-HCN75CTX.js.map +0 -1
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// src/constants.ts
|
|
2
2
|
var NETWORKS = {
|
|
3
|
-
base: {
|
|
3
|
+
base: {
|
|
4
|
+
caip2: "eip155:8453",
|
|
5
|
+
chainId: 8453,
|
|
6
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
7
|
+
},
|
|
4
8
|
"base-sepolia": {
|
|
5
9
|
caip2: "eip155:84532",
|
|
6
10
|
chainId: 84532,
|
|
@@ -11,6 +15,15 @@ var USDC_DECIMALS = 6;
|
|
|
11
15
|
var NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.";
|
|
12
16
|
var DOCS_URL = "https://fatstack.net/docs/payments";
|
|
13
17
|
var PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
18
|
+
var SETTLEMENT_HEADERS = ["payment-response", "x-payment-response"];
|
|
19
|
+
var PAYMENT_SIGNATURE_HEADERS = ["payment-signature", "x-payment"];
|
|
20
|
+
function readSettlementHeader(headers) {
|
|
21
|
+
for (const name of SETTLEMENT_HEADERS) {
|
|
22
|
+
const value = headers.get(name);
|
|
23
|
+
if (value) return value;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
14
27
|
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
15
28
|
|
|
16
29
|
// src/errors.ts
|
|
@@ -36,6 +49,12 @@ var MissingAdapterError = class extends Error {
|
|
|
36
49
|
super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);
|
|
37
50
|
}
|
|
38
51
|
};
|
|
52
|
+
var UnreadableQuoteError = class extends Error {
|
|
53
|
+
name = "UnreadableQuoteError";
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
39
58
|
|
|
40
59
|
// src/money.ts
|
|
41
60
|
var UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);
|
|
@@ -77,12 +96,16 @@ export {
|
|
|
77
96
|
NO_REFUNDS_NOTICE,
|
|
78
97
|
DOCS_URL,
|
|
79
98
|
PAYMENT_REF_HEADER,
|
|
99
|
+
SETTLEMENT_HEADERS,
|
|
100
|
+
PAYMENT_SIGNATURE_HEADERS,
|
|
101
|
+
readSettlementHeader,
|
|
80
102
|
DEFAULT_FACILITATOR_URL,
|
|
81
103
|
SpendGuardError,
|
|
82
104
|
NotImplementedError,
|
|
83
105
|
MissingAdapterError,
|
|
106
|
+
UnreadableQuoteError,
|
|
84
107
|
parseUsdc,
|
|
85
108
|
formatUsdc,
|
|
86
109
|
quoteToUsd
|
|
87
110
|
};
|
|
88
|
-
//# sourceMappingURL=chunk-
|
|
111
|
+
//# sourceMappingURL=chunk-C4BASAUA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/errors.ts","../src/money.ts"],"sourcesContent":["/** Base networks in CAIP-2 form, which is what x402 v2 speaks. */\n/**\n * The EIP-712 domain a payer signs the EIP-3009 authorisation against is **not** listed\n * here on purpose: it differs per network (mainnet USDC is \"USD Coin\", the Sepolia\n * deployment is \"USDC\"), and the EVM scheme owns the authoritative table. Quoting a\n * dollar price lets it resolve the asset and publish that domain in the 402; naming an\n * explicit asset bypasses the lookup and emits `extra: {}`, which no payer can sign\n * against.\n */\nexport const NETWORKS = {\n base: {\n caip2: 'eip155:8453',\n chainId: 8453,\n usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n },\n 'base-sepolia': {\n caip2: 'eip155:84532',\n chainId: 84532,\n usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n} as const;\n\nexport type NetworkName = keyof typeof NETWORKS;\n\n/** USDC is 6 decimals on Base. */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Required on every 402 body and every payment-facing doc page. A payment is a direct\n * on-chain transfer between two wallets: once settled nobody, Fatstack included, can\n * reverse it.\n */\nexport const NO_REFUNDS_NOTICE =\n 'Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.';\n\nexport const DOCS_URL = 'https://fatstack.net/docs/payments';\n\n/** Correlates a settled payment with the indexer's view of the on-chain transfer. */\nexport const PAYMENT_REF_HEADER = 'X-Fatstack-Payment-Ref';\n\n/**\n * x402 v2 dropped the `X-` prefix: the settlement receipt is `PAYMENT-RESPONSE` and the\n * payer's payload is `PAYMENT-SIGNATURE`. The v1 spellings are still read so a v1 payer\n * or resource keeps working. Header names are case-insensitive; these are lowercase\n * because `Headers.get` normalises.\n */\nexport const SETTLEMENT_HEADERS = ['payment-response', 'x-payment-response'] as const;\nexport const PAYMENT_SIGNATURE_HEADERS = ['payment-signature', 'x-payment'] as const;\n\n/** First settlement receipt present on a response, in either spelling. */\nexport function readSettlementHeader(headers: Headers): string | null {\n for (const name of SETTLEMENT_HEADERS) {\n const value = headers.get(name);\n if (value) return value;\n }\n return null;\n}\n\nexport const DEFAULT_FACILITATOR_URL = 'https://x402.org/facilitator';\n","/** Names of the spend guards an agent can set. */\nexport type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';\n\n/**\n * Thrown before anything is signed when a call would breach a spend guard.\n *\n * Payments are final, so the only place to stop an unwanted spend is before the\n * signature exists. Every guard raises this, and it is never thrown after a payment\n * payload has been created.\n */\nexport class SpendGuardError extends Error {\n override readonly name = 'SpendGuardError';\n\n constructor(\n readonly guard: GuardName,\n message: string,\n readonly detail: { limitUsd?: number; attemptedUsd?: number; host?: string } = {},\n ) {\n super(message);\n }\n}\n\n/** Thrown by seams that are typed and reachable but deliberately not built yet. */\nexport class NotImplementedError extends Error {\n override readonly name = 'NotImplementedError';\n\n constructor(feature: string) {\n super(`${feature} is not implemented in this build.`);\n }\n}\n\n/** Thrown when an optional framework adapter is used without its package installed. */\nexport class MissingAdapterError extends Error {\n override readonly name = 'MissingAdapterError';\n\n constructor(pkg: string) {\n super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);\n }\n}\n\n/**\n * A 402 arrived whose payment requirements could not be read, so the call cannot be\n * priced and therefore cannot be checked against a spend cap. Refusing is the safe\n * outcome: paying blind is irreversible.\n */\nexport class UnreadableQuoteError extends Error {\n override readonly name = 'UnreadableQuoteError';\n\n constructor(message: string) {\n super(message);\n }\n}\n","import { NETWORKS, USDC_DECIMALS } from './constants.js';\n\nconst UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);\n\n/** \"1.25\" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */\nexport function parseUsdc(input: string): bigint {\n const match = /^(\\d+)(?:\\.(\\d{1,6}))?$/.exec(input.trim());\n if (!match) {\n throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);\n }\n const whole = BigInt(match[1] ?? '0');\n const fraction = BigInt((match[2] ?? '').padEnd(USDC_DECIMALS, '0') || '0');\n return whole * UNITS_PER_USDC + fraction;\n}\n\n/** 1250000n -> \"1.25\". Trailing zeros trimmed. */\nexport function formatUsdc(atomic: bigint): string {\n if (atomic < 0n) throw new RangeError('USDC amounts are never negative');\n const whole = atomic / UNITS_PER_USDC;\n const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, '0');\n const trimmed = fraction.replace(/0+$/, '');\n return trimmed ? `${whole}.${trimmed}` : whole.toString();\n}\n\nconst USDC_ADDRESSES = new Set(\n Object.values(NETWORKS).map((network) => network.usdc.toLowerCase()),\n);\n\n/**\n * Converts a quoted amount to USD for guard evaluation.\n *\n * Fails closed: if the asset is not a USDC contract we recognise and the quote carries no\n * usable `decimals`, this throws rather than guessing. Guessing here would let an\n * unrecognised token slip past a spend cap, and the payment is irreversible.\n */\nexport function quoteToUsd(quote: {\n amountAtomic: string;\n asset: string;\n decimals?: number | undefined;\n}): number {\n const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;\n\n if (decimals === undefined || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n throw new RangeError(\n `Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`,\n );\n }\n\n if (!/^\\d+$/.test(quote.amountAtomic)) {\n throw new RangeError(`Quoted amount is not an integer atomic value: ${quote.amountAtomic}`);\n }\n\n return Number(quote.amountAtomic) / 10 ** decimals;\n}\n"],"mappings":";AASO,IAAM,WAAW;AAAA,EACtB,MAAM;AAAA,IACJ,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA,gBAAgB;AAAA,IACd,OAAO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CAAC,KAAK,IAAI,OAAO,eAAe,GAAG,KAAK,GAAG;AAC1E,SAAO,QAAQ,iBAAiB;AAClC;AAGO,SAAS,WAAW,QAAwB;AACjD,MAAI,SAAS,GAAI,OAAM,IAAI,WAAW,iCAAiC;AACvE,QAAM,QAAQ,SAAS;AACvB,QAAM,YAAY,SAAS,gBAAgB,SAAS,EAAE,SAAS,eAAe,GAAG;AACjF,QAAM,UAAU,SAAS,QAAQ,OAAO,EAAE;AAC1C,SAAO,UAAU,GAAG,KAAK,IAAI,OAAO,KAAK,MAAM,SAAS;AAC1D;AAEA,IAAM,iBAAiB,IAAI;AAAA,EACzB,OAAO,OAAO,QAAQ,EAAE,IAAI,CAAC,YAAY,QAAQ,KAAK,YAAY,CAAC;AACrE;AASO,SAAS,WAAW,OAIhB;AACT,QAAM,WAAW,eAAe,IAAI,MAAM,MAAM,YAAY,CAAC,IAAI,gBAAgB,MAAM;AAEvF,MAAI,aAAa,UAAa,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,KAAK,WAAW,IAAI;AAC1F,UAAM,IAAI;AAAA,MACR,sBAAsB,MAAM,KAAK;AAAA,IACnC;AAAA,EACF;AAEA,MAAI,CAAC,QAAQ,KAAK,MAAM,YAAY,GAAG;AACrC,UAAM,IAAI,WAAW,iDAAiD,MAAM,YAAY,EAAE;AAAA,EAC5F;AAEA,SAAO,OAAO,MAAM,YAAY,IAAI,MAAM;AAC5C;","names":[]}
|
|
@@ -6,9 +6,11 @@ import {
|
|
|
6
6
|
NO_REFUNDS_NOTICE,
|
|
7
7
|
NotImplementedError,
|
|
8
8
|
PAYMENT_REF_HEADER,
|
|
9
|
+
SETTLEMENT_HEADERS,
|
|
9
10
|
formatUsdc,
|
|
10
|
-
parseUsdc
|
|
11
|
-
|
|
11
|
+
parseUsdc,
|
|
12
|
+
readSettlementHeader
|
|
13
|
+
} from "./chunk-C4BASAUA.js";
|
|
12
14
|
|
|
13
15
|
// src/provider.ts
|
|
14
16
|
import { decodePaymentResponseHeader } from "@x402/core/http";
|
|
@@ -99,7 +101,11 @@ function paywall(options) {
|
|
|
99
101
|
payTo,
|
|
100
102
|
// An explicit asset+amount pins USDC and the exact atomic amount, rather than
|
|
101
103
|
// leaving the quote to a price feed.
|
|
102
|
-
price
|
|
104
|
+
// A dollar price, not an explicit { asset, amount }: the EVM scheme resolves the
|
|
105
|
+
// network's default asset (USDC) and publishes its EIP-712 domain in `extra`, which
|
|
106
|
+
// the payer needs to sign the EIP-3009 authorisation. Naming the asset directly
|
|
107
|
+
// skips that lookup and emits `extra: {}`, which nobody can pay against.
|
|
108
|
+
price: `$${priceUsdc}`,
|
|
103
109
|
maxTimeoutSeconds: config.maxTimeoutSeconds
|
|
104
110
|
},
|
|
105
111
|
description: config.description ?? `Fatstack tool ${config.toolId}`,
|
|
@@ -142,7 +148,7 @@ function paywall(options) {
|
|
|
142
148
|
const middleware = cached;
|
|
143
149
|
const result = await middleware(c, next);
|
|
144
150
|
const carrier = result instanceof Response ? result : c.res;
|
|
145
|
-
const ref = paymentRef(carrier
|
|
151
|
+
const ref = paymentRef(carrier ? readSettlementHeader(carrier.headers) : null);
|
|
146
152
|
if (ref) carrier.headers.set(PAYMENT_REF_HEADER, ref);
|
|
147
153
|
return result;
|
|
148
154
|
};
|
|
@@ -162,7 +168,7 @@ function paywall(options) {
|
|
|
162
168
|
const originalSetHeader = response.setHeader.bind(response);
|
|
163
169
|
response.setHeader = (name, value) => {
|
|
164
170
|
const out = originalSetHeader(name, value);
|
|
165
|
-
if (String(name).toLowerCase()
|
|
171
|
+
if (SETTLEMENT_HEADERS.includes(String(name).toLowerCase())) {
|
|
166
172
|
const ref = paymentRef(String(value));
|
|
167
173
|
if (ref) originalSetHeader(PAYMENT_REF_HEADER, ref);
|
|
168
174
|
}
|
|
@@ -185,7 +191,7 @@ function paywall(options) {
|
|
|
185
191
|
const wrapped = cached;
|
|
186
192
|
const result = await wrapped(request);
|
|
187
193
|
if (result instanceof Response) {
|
|
188
|
-
const ref = paymentRef(result.headers
|
|
194
|
+
const ref = paymentRef(readSettlementHeader(result.headers));
|
|
189
195
|
if (ref) result.headers.set(PAYMENT_REF_HEADER, ref);
|
|
190
196
|
}
|
|
191
197
|
return result;
|
|
@@ -210,4 +216,4 @@ export {
|
|
|
210
216
|
readPaywallEnv,
|
|
211
217
|
paywall
|
|
212
218
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
219
|
+
//# sourceMappingURL=chunk-PY25VKHS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts","../src/env.ts","../src/fee-mode.ts"],"sourcesContent":["import { decodePaymentResponseHeader } from '@x402/core/http';\nimport { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';\nimport type { FacilitatorClient, RouteConfig } from '@x402/core/server';\nimport { ExactEvmScheme } from '@x402/evm/exact/server';\nimport { z } from 'zod';\n\nimport {\n DOCS_URL,\n NETWORKS,\n NO_REFUNDS_NOTICE,\n PAYMENT_REF_HEADER,\n readSettlementHeader,\n} from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { readPaywallEnv } from './env.js';\nimport { SETTLEMENT_HEADERS } from './constants.js';\nimport { MissingAdapterError } from './errors.js';\nimport { resolvePayee } from './fee-mode.js';\nimport { formatUsdc, parseUsdc } from './money.js';\n\nconst optionsSchema = z.object({\n /** Price per call in USD, as a decimal string: \"0.002\". */\n price: z.string().regex(/^\\d+(?:\\.\\d{1,6})?$/, 'price must be USD with at most 6 decimals'),\n /** The provider's own wallet. Under FEE_MODE=direct this is the sole payee. */\n wallet: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'wallet must be a 20-byte address'),\n toolId: z.string().min(1).max(128),\n network: z.enum(['base', 'base-sepolia']).default('base'),\n description: z.string().optional(),\n docsUrl: z.string().url().default(DOCS_URL),\n mimeType: z.string().default('application/json'),\n maxTimeoutSeconds: z.number().int().positive().default(60),\n});\n\nexport interface PaywallOptions extends z.input<typeof optionsSchema> {\n /** Defaults to process.env. */\n env?: Record<string, string | undefined>;\n /** Injects a facilitator instead of building an HTTP one. Used by tests. */\n facilitator?: FacilitatorClient;\n}\n\n/** The 402 body an agent reads before deciding to pay. */\nexport interface UnpaidBody {\n error: 'payment_required';\n tool: string;\n price: { usdc: string; amountAtomic: string; asset: string; network: string };\n payTo: string;\n terms: { refundable: false; notice: string };\n docs: string;\n message: string;\n}\n\n/** Structurally compatible with Hono's `MiddlewareHandler`, without importing hono. */\nexport interface HonoContextLike {\n json: (body: unknown, status?: number) => Response;\n res: Response;\n req: { raw: Request };\n}\nexport type HonoMiddleware = (\n c: HonoContextLike,\n next: () => Promise<void>,\n) => Promise<Response | void>;\n\n/** Structurally compatible with an Express request handler. */\nexport interface ExpressResponseLike {\n status: (code: number) => { json: (body: unknown) => void };\n setHeader: (name: string, value: string | number | readonly string[]) => unknown;\n}\nexport type ExpressMiddleware = (\n req: unknown,\n res: ExpressResponseLike,\n next: (err?: unknown) => void,\n) => Promise<void>;\n\nexport interface Paywall {\n /** Hono middleware. Requires @x402/hono. */\n hono(): HonoMiddleware;\n /** Express middleware. Requires @x402/express. */\n express(): ExpressMiddleware;\n /** Wraps a Next.js route handler. Requires @x402/next (which needs Next >= 16.2.6). */\n next<T>(handler: (request: never) => Promise<T>): (request: never) => Promise<T>;\n /** The x402 route config, for advanced use with the official adapters directly. */\n routeConfig: RouteConfig;\n /** Resolved payee. Always the provider wallet while FEE_MODE=direct. */\n payTo: string;\n}\n\n/** Minimal shapes of the optional adapter packages, so their types are not required. */\ninterface HonoAdapterModule {\n paymentMiddleware: (routes: RouteConfig, server: x402ResourceServer) => unknown;\n}\ninterface ExpressAdapterModule {\n paymentMiddleware: (routes: RouteConfig, server: x402ResourceServer) => unknown;\n}\ninterface NextAdapterModule {\n withX402: (handler: unknown, routeConfig: RouteConfig, server: x402ResourceServer) => unknown;\n}\n\nconst KILLSWITCH_BODY = {\n error: 'service_unavailable',\n message:\n 'This tool is temporarily disabled by its operator (KILLSWITCH). No payment was taken. Try again later.',\n} as const;\n\n/**\n * Paywalls a route with x402: USDC on Base, paid directly to the provider's wallet.\n *\n * Verification and settlement are delegated to the official x402 packages against the\n * hosted facilitator — this module does not sign or verify anything itself.\n *\n * Throws immediately when FEE_MODE=splitter: there is no splitter contract in this build,\n * and silently falling back to `direct` would pay the wrong party.\n */\nexport function paywall(options: PaywallOptions): Paywall {\n const config = optionsSchema.parse(options);\n const env = readPaywallEnv(options.env);\n const network = NETWORKS[config.network as NetworkName];\n\n // Throws for FEE_MODE=splitter, at construction time rather than mid-request.\n const { payTo } = resolvePayee(env.FEE_MODE, config.wallet);\n\n const amountAtomic = parseUsdc(config.price).toString();\n const priceUsdc = formatUsdc(parseUsdc(config.price));\n\n const unpaidBody: UnpaidBody = {\n error: 'payment_required',\n tool: config.toolId,\n price: {\n usdc: priceUsdc,\n amountAtomic,\n asset: network.usdc,\n network: network.caip2,\n },\n payTo,\n terms: { refundable: false, notice: NO_REFUNDS_NOTICE },\n docs: config.docsUrl,\n message: `This call costs ${priceUsdc} USDC on ${config.network}, paid directly to the provider. ${NO_REFUNDS_NOTICE} See ${config.docsUrl}`,\n };\n\n const routeConfig: RouteConfig = {\n accepts: {\n scheme: 'exact',\n network: network.caip2,\n payTo,\n // An explicit asset+amount pins USDC and the exact atomic amount, rather than\n // leaving the quote to a price feed.\n // A dollar price, not an explicit { asset, amount }: the EVM scheme resolves the\n // network's default asset (USDC) and publishes its EIP-712 domain in `extra`, which\n // the payer needs to sign the EIP-3009 authorisation. Naming the asset directly\n // skips that lookup and emits `extra: {}`, which nobody can pay against.\n price: `$${priceUsdc}`,\n maxTimeoutSeconds: config.maxTimeoutSeconds,\n },\n description: config.description ?? `Fatstack tool ${config.toolId}`,\n mimeType: config.mimeType,\n unpaidResponseBody: () => ({ contentType: 'application/json', body: unpaidBody }),\n };\n\n const facilitator: FacilitatorClient =\n options.facilitator ??\n new HTTPFacilitatorClient({\n url: env.FACILITATOR_URL,\n ...(env.FACILITATOR_API_KEY\n ? {\n createAuthHeaders: async () => ({\n verify: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },\n settle: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },\n supported: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },\n }),\n }\n : {}),\n });\n\n const server = new x402ResourceServer(facilitator).register(network.caip2, new ExactEvmScheme());\n\n const killed = env.KILLSWITCH === '1';\n\n /** Derives the indexing reference from the settlement receipt the adapter emitted. */\n function paymentRef(paymentResponseHeader: string | null | undefined): string | null {\n if (!paymentResponseHeader) return null;\n try {\n const settled = decodePaymentResponseHeader(paymentResponseHeader);\n const transaction = (settled as { transaction?: string }).transaction;\n return transaction ? `${config.toolId}:${network.caip2}:${transaction}` : null;\n } catch {\n return null;\n }\n }\n\n return {\n routeConfig,\n payTo,\n\n hono(): HonoMiddleware {\n let cached: unknown;\n return async (c, next) => {\n if (killed) return c.json(KILLSWITCH_BODY, 503);\n\n if (!cached) {\n const mod = await importOptional<HonoAdapterModule>('@x402/hono');\n cached = mod.paymentMiddleware(routeConfig, server);\n }\n const middleware = cached as (\n ctx: HonoContextLike,\n n: () => Promise<void>,\n ) => Promise<Response | void>;\n const result = await middleware(c, next);\n\n // c.res carries the response Hono will send, whether the middleware set it or\n // the downstream handler did.\n const carrier = result instanceof Response ? result : c.res;\n const ref = paymentRef(carrier ? readSettlementHeader(carrier.headers) : null);\n if (ref) carrier.headers.set(PAYMENT_REF_HEADER, ref);\n return result;\n };\n },\n\n express(): ExpressMiddleware {\n let cached: unknown;\n return async (req, res, next) => {\n const response = res;\n if (killed) {\n response.status(503).json(KILLSWITCH_BODY);\n return;\n }\n\n if (!cached) {\n const mod = await importOptional<ExpressAdapterModule>('@x402/express');\n cached = mod.paymentMiddleware(routeConfig, server);\n }\n\n // Headers must be attached before the response flushes, so mirror the settlement\n // receipt onto the ref header the moment the adapter sets it.\n const originalSetHeader = response.setHeader.bind(response);\n response.setHeader = (name, value) => {\n const out = originalSetHeader(name, value);\n if (SETTLEMENT_HEADERS.includes(String(name).toLowerCase() as never)) {\n const ref = paymentRef(String(value));\n if (ref) originalSetHeader(PAYMENT_REF_HEADER, ref);\n }\n return out;\n };\n\n const middleware = cached as (\n q: unknown,\n s: unknown,\n n: (err?: unknown) => void,\n ) => Promise<void>;\n await middleware(req, res, next);\n };\n },\n\n next<T>(handler: (request: never) => Promise<T>) {\n let cached: unknown;\n return async (request: never): Promise<T> => {\n if (killed) {\n return Response.json(KILLSWITCH_BODY, { status: 503 }) as T;\n }\n\n if (!cached) {\n const mod = await importOptional<NextAdapterModule>('@x402/next');\n cached = mod.withX402(handler as never, routeConfig, server);\n }\n const wrapped = cached as (r: never) => Promise<T>;\n const result = await wrapped(request);\n\n if (result instanceof Response) {\n const ref = paymentRef(readSettlementHeader(result.headers));\n if (ref) result.headers.set(PAYMENT_REF_HEADER, ref);\n }\n return result;\n };\n },\n };\n}\n\nasync function importOptional<T>(specifier: string): Promise<T> {\n try {\n return (await import(/* @vite-ignore */ specifier)) as T;\n } catch {\n throw new MissingAdapterError(specifier);\n }\n}\n\nexport type { FacilitatorClient, RouteConfig } from '@x402/core/server';\n","import { z } from 'zod';\n\nimport { DEFAULT_FACILITATOR_URL } from './constants.js';\n\n/**\n * Environment the paywall reads. Parsed lazily inside `paywall()`, never at module load,\n * so importing this package never throws in a build step.\n */\nexport const paywallEnvSchema = z.object({\n /** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */\n FACILITATOR_URL: z.string().url().default(DEFAULT_FACILITATOR_URL),\n FACILITATOR_API_KEY: z.string().min(1).optional(),\n /**\n * `1` takes every paywalled route offline with a 503. Intended for an incident where\n * continuing to take irreversible payments would be worse than being down.\n */\n KILLSWITCH: z.enum(['0', '1']).default('0'),\n /**\n * direct = agent pays the provider wallet, 0% platform fee (the launch build)\n * splitter = reserved for the fee-splitting contract; not implemented\n */\n FEE_MODE: z.enum(['direct', 'splitter']).default('direct'),\n});\n\nexport type PaywallEnv = z.infer<typeof paywallEnvSchema>;\n\nexport function readPaywallEnv(\n source: Record<string, string | undefined> = process.env,\n): PaywallEnv {\n return paywallEnvSchema.parse({\n FACILITATOR_URL: source.FACILITATOR_URL,\n FACILITATOR_API_KEY: source.FACILITATOR_API_KEY,\n KILLSWITCH: source.KILLSWITCH,\n FEE_MODE: source.FEE_MODE,\n });\n}\n","import { NotImplementedError } from './errors.js';\n\nexport type FeeMode = 'direct' | 'splitter';\n\nexport interface PayeeResolution {\n /** The single address that receives the transfer. */\n payTo: string;\n /** Platform fee in basis points. Always 0 while FEE_MODE=direct. */\n feeBps: number;\n}\n\n/**\n * Resolves who is paid for a call. Under `direct` this is always, and only, the\n * provider's own wallet — the platform is never a payee and never custodies funds.\n *\n * `splitter` is a reserved seam for the fee-splitting contract. It is typed and reachable\n * so the shape is settled, but it throws: there is no splitter contract in this build.\n */\nexport function resolvePayee(mode: FeeMode, providerWallet: string): PayeeResolution {\n switch (mode) {\n case 'direct':\n return { payTo: providerWallet, feeBps: 0 };\n case 'splitter':\n throw new NotImplementedError(\n 'FEE_MODE=splitter (no splitter contract ships in the launch build)',\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,mCAAmC;AAC5C,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,sBAAsB;AAC/B,SAAS,KAAAA,UAAS;;;ACJlB,SAAS,SAAS;AAQX,IAAM,mBAAmB,EAAE,OAAO;AAAA;AAAA,EAEvC,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,uBAAuB;AAAA,EACjE,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKhD,YAAY,EAAE,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,QAAQ,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA,EAK1C,UAAU,EAAE,KAAK,CAAC,UAAU,UAAU,CAAC,EAAE,QAAQ,QAAQ;AAC3D,CAAC;AAIM,SAAS,eACd,SA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AM,MAAM,WAAW,OAAO,KAAK,CAAC;AACpC,gBAAI,IAAK,mBAAkB,oBAAoB,GAAG;AAAA,UACpD;AACA,iBAAO;AAAA,QACT;AAEA,cAAM,aAAa;AAKnB,cAAM,WAAW,KAAK,KAAK,IAAI;AAAA,MACjC;AAAA,IACF;AAAA,IAEA,KAAQ,SAAyC;AAC/C,UAAI;AACJ,aAAO,OAAO,YAA+B;AAC3C,YAAI,QAAQ;AACV,iBAAO,SAAS,KAAK,iBAAiB,EAAE,QAAQ,IAAI,CAAC;AAAA,QACvD;AAEA,YAAI,CAAC,QAAQ;AACX,gBAAM,MAAM,MAAM,eAAkC,YAAY;AAChE,mBAAS,IAAI,SAAS,SAAkB,aAAa,MAAM;AAAA,QAC7D;AACA,cAAM,UAAU;AAChB,cAAM,SAAS,MAAM,QAAQ,OAAO;AAEpC,YAAI,kBAAkB,UAAU;AAC9B,gBAAM,MAAM,WAAW,qBAAqB,OAAO,OAAO,CAAC;AAC3D,cAAI,IAAK,QAAO,QAAQ,IAAI,oBAAoB,GAAG;AAAA,QACrD;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAe,eAAkB,WAA+B;AAC9D,MAAI;AACF,WAAQ,MAAM;AAAA;AAAA,MAA0B;AAAA;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI,oBAAoB,SAAS;AAAA,EACzC;AACF;","names":["z","z"]}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
NETWORKS,
|
|
3
3
|
SpendGuardError,
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
UnreadableQuoteError,
|
|
5
|
+
quoteToUsd,
|
|
6
|
+
readSettlementHeader
|
|
7
|
+
} from "./chunk-C4BASAUA.js";
|
|
6
8
|
|
|
7
9
|
// src/client.ts
|
|
8
10
|
import { x402Client } from "@x402/core/client";
|
|
11
|
+
import { decodePaymentRequiredHeader } from "@x402/core/http";
|
|
9
12
|
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
10
13
|
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
11
14
|
|
|
@@ -72,6 +75,19 @@ async function evaluateGuards(quoteUsd, guards, store, now) {
|
|
|
72
75
|
}
|
|
73
76
|
}
|
|
74
77
|
}
|
|
78
|
+
async function readQuotedRequirements(response) {
|
|
79
|
+
const header = response.headers.get("payment-required");
|
|
80
|
+
if (header) {
|
|
81
|
+
try {
|
|
82
|
+
const decoded = decodePaymentRequiredHeader(header);
|
|
83
|
+
if (Array.isArray(decoded.accepts) && decoded.accepts.length > 0) return decoded.accepts;
|
|
84
|
+
} catch {
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const body = await response.clone().json().catch(() => null);
|
|
88
|
+
const accepts = body?.accepts;
|
|
89
|
+
return Array.isArray(accepts) ? accepts : [];
|
|
90
|
+
}
|
|
75
91
|
function quoteUsdOf(requirements) {
|
|
76
92
|
const asRecord = requirements;
|
|
77
93
|
const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;
|
|
@@ -117,19 +133,21 @@ async function payFetch(url, init, options) {
|
|
|
117
133
|
const guarded = async (input, requestInit) => {
|
|
118
134
|
const response2 = await baseFetch(input, requestInit);
|
|
119
135
|
if (response2.status !== 402) return response2;
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
136
|
+
const accepts = await readQuotedRequirements(response2);
|
|
137
|
+
if (accepts.length === 0) {
|
|
138
|
+
throw new UnreadableQuoteError(
|
|
139
|
+
"Received a 402 with no readable payment requirements (no payment-required header, no accepts body). Refusing to pay blind."
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const cheapest = accepts.map((requirement) => quoteUsdOf(requirement)).sort((a, b) => a - b)[0];
|
|
143
|
+
if (cheapest !== void 0) {
|
|
144
|
+
await evaluateGuards(cheapest, guards, store, now());
|
|
127
145
|
}
|
|
128
146
|
return response2;
|
|
129
147
|
};
|
|
130
148
|
const paying = wrapFetchWithPayment(guarded, client);
|
|
131
149
|
const response = await paying(url, init);
|
|
132
|
-
if (response.headers
|
|
150
|
+
if (readSettlementHeader(response.headers) && quotedUsd !== null) {
|
|
133
151
|
await store.record({ at: now(), usd: quotedUsd });
|
|
134
152
|
}
|
|
135
153
|
return response;
|
|
@@ -138,7 +156,8 @@ async function payFetch(url, init, options) {
|
|
|
138
156
|
export {
|
|
139
157
|
createMemorySpendStore,
|
|
140
158
|
evaluateGuards,
|
|
159
|
+
readQuotedRequirements,
|
|
141
160
|
quoteUsdOf,
|
|
142
161
|
payFetch
|
|
143
162
|
};
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
163
|
+
//# sourceMappingURL=chunk-ZGVPNFNS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["import { x402Client } from '@x402/core/client';\nimport { decodePaymentRequiredHeader } from '@x402/core/http';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { wrapFetchWithPayment } from '@x402/fetch';\n\nimport { NETWORKS, PAYMENT_REF_HEADER, readSettlementHeader } from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { SpendGuardError, UnreadableQuoteError } from './errors.js';\nimport { quoteToUsd } from './money.js';\nimport { createMemorySpendStore } from './store.js';\nimport type { SpendStore } from './store.js';\n\n/** The signer the official EVM scheme expects: address + signTypedData, no key handling. */\nexport type EvmWallet = ConstructorParameters<typeof ExactEvmScheme>[0];\n\nexport interface SpendGuards {\n /** Hard USD ceiling for a single call. */\n maxPerCall?: number;\n /** Rolling 60-minute USD ceiling. */\n maxPerHour?: number;\n /** Rolling 24-hour USD ceiling. */\n maxPerDay?: number;\n /** Hostnames this agent may pay. Checked before any network call. */\n allowedHosts?: string[];\n}\n\nexport interface PayFetchOptions {\n wallet: EvmWallet;\n guards?: SpendGuards;\n /** Defaults to a process-local in-memory store. */\n store?: SpendStore;\n networks?: NetworkName[];\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction hostOf(input: RequestInfo | URL): string | null {\n try {\n const raw =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** `example.com` in allowedHosts also authorises `tool.example.com`. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const candidate = entry.trim().toLowerCase().replace(/^\\*\\./, '');\n return host === candidate || host.endsWith(`.${candidate}`);\n });\n}\n\n/**\n * Checks every guard against a quote. Returns the USD value if the call may proceed,\n * throws SpendGuardError otherwise. Called before a payment payload exists.\n */\nexport async function evaluateGuards(\n quoteUsd: number,\n guards: SpendGuards,\n store: SpendStore,\n now: number,\n): Promise<void> {\n if (guards.maxPerCall !== undefined && quoteUsd > guards.maxPerCall) {\n throw new SpendGuardError(\n 'maxPerCall',\n `Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,\n { limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd },\n );\n }\n\n if (guards.maxPerHour !== undefined) {\n const spent = await store.totalSince(now - HOUR_MS);\n if (spent + quoteUsd > guards.maxPerHour) {\n throw new SpendGuardError(\n 'maxPerHour',\n `Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,\n { limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n\n if (guards.maxPerDay !== undefined) {\n const spent = await store.totalSince(now - DAY_MS);\n if (spent + quoteUsd > guards.maxPerDay) {\n throw new SpendGuardError(\n 'maxPerDay',\n `Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,\n { limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n}\n\n/**\n * Reads the offered requirements from a 402.\n *\n * x402 v2 carries them in the base64 `payment-required` header, not the body — the body\n * is the resource's own, and may be anything. v1 put them in the body, so both are read.\n */\nexport async function readQuotedRequirements(response: Response): Promise<PaymentRequirements[]> {\n const header = response.headers.get('payment-required');\n if (header) {\n try {\n const decoded = decodePaymentRequiredHeader(header);\n if (Array.isArray(decoded.accepts) && decoded.accepts.length > 0) return decoded.accepts;\n } catch {\n // Fall through to the body form.\n }\n }\n\n const body: unknown = await response\n .clone()\n .json()\n .catch(() => null);\n const accepts = (body as { accepts?: PaymentRequirements[] } | null)?.accepts;\n return Array.isArray(accepts) ? accepts : [];\n}\n\n/** Reads the quoted amount out of x402 payment requirements. */\ninterface PriceableRequirement {\n maxAmountRequired?: string;\n amount?: string;\n asset?: string;\n extra?: { decimals?: number };\n}\n\nexport function quoteUsdOf(requirements: PaymentRequirements): number {\n const asRecord: PriceableRequirement = requirements;\n const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;\n if (!amountAtomic || !asRecord.asset) {\n throw new RangeError('Payment requirements carry no priceable amount; refusing to pay.');\n }\n return quoteToUsd({\n amountAtomic,\n asset: asRecord.asset,\n decimals: asRecord.extra?.decimals,\n });\n}\n\n/**\n * A `fetch` that pays for 402 responses, under spend guards.\n *\n * The 402 handling, signing and retry are the official x402 packages' work. What this adds\n * is refusal: guards are evaluated inside the payment-policy hook, which runs after the\n * quote is known and before any payload is signed, so exceeding a guard throws\n * SpendGuardError with nothing signed and nothing spent.\n */\nexport async function payFetch(\n url: RequestInfo | URL,\n init: RequestInit | undefined,\n options: PayFetchOptions,\n): Promise<Response> {\n const guards = options.guards ?? {};\n const store = options.store ?? createMemorySpendStore();\n const now = options.now ?? Date.now;\n const baseFetch = options.fetch ?? globalThis.fetch;\n const networks = options.networks ?? (['base'] as NetworkName[]);\n\n // Host allowlist is checked first: an unauthorised host should cost no request at all.\n if (guards.allowedHosts) {\n const host = hostOf(url);\n if (!host || !hostAllowed(host, guards.allowedHosts)) {\n throw new SpendGuardError(\n 'allowedHosts',\n `Host ${host ?? '<unparseable>'} is not in allowedHosts`,\n { host: host ?? undefined },\n );\n }\n }\n\n let quotedUsd: number | null = null;\n\n const client = new x402Client((_version, requirements) => {\n // Runs before the payment payload is created. Throwing here means no signature.\n const affordable = requirements.filter((requirement) => {\n const usd = quoteUsdOf(requirement);\n return guards.maxPerCall === undefined || usd <= guards.maxPerCall;\n });\n\n const chosen = (affordable.length > 0 ? affordable : requirements)[0];\n if (!chosen) throw new RangeError('Resource offered no payment requirements');\n\n quotedUsd = quoteUsdOf(chosen);\n return chosen;\n });\n\n for (const name of networks) {\n client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));\n }\n\n const guarded: typeof globalThis.fetch = async (input, requestInit) => {\n const response = await baseFetch(input, requestInit);\n if (response.status !== 402) return response;\n\n // Peek at the quote and apply guards before the wrapper signs anything.\n const accepts = await readQuotedRequirements(response);\n if (accepts.length === 0) {\n // A 402 whose requirements we cannot read is a 402 we cannot price, and an\n // unpriced call cannot be checked against a spend cap. Refuse rather than let it\n // through unguarded.\n throw new UnreadableQuoteError(\n 'Received a 402 with no readable payment requirements (no payment-required header, no accepts body). Refusing to pay blind.',\n );\n }\n\n const cheapest = accepts.map((requirement) => quoteUsdOf(requirement)).sort((a, b) => a - b)[0];\n if (cheapest !== undefined) {\n await evaluateGuards(cheapest, guards, store, now());\n }\n return response;\n };\n\n const paying = wrapFetchWithPayment(guarded, client);\n const response = await paying(url as RequestInfo, init);\n\n // Record the spend only once a payment actually settled.\n if (readSettlementHeader(response.headers) && quotedUsd !== null) {\n await store.record({ at: now(), usd: quotedUsd });\n }\n\n return response;\n}\n\nexport { PAYMENT_REF_HEADER };\n","/** One recorded spend, in USD, at a wall-clock millisecond. */\nexport interface SpendRecord {\n at: number;\n usd: number;\n}\n\n/**\n * Where rolling spend totals live. The default is in-memory and per-process; swap in a\n * shared implementation (Redis, Durable Object, Postgres) when an agent runs as more\n * than one process, otherwise each process enforces its own separate budget.\n */\nexport interface SpendStore {\n record(entry: SpendRecord): Promise<void> | void;\n /** Total USD recorded at or after `sinceMs`. */\n totalSince(sinceMs: number): Promise<number> | number;\n}\n\n/** Process-local store. Entries older than the longest window are dropped on write. */\nexport function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1000): SpendStore {\n let entries: SpendRecord[] = [];\n\n return {\n record(entry) {\n entries.push(entry);\n const cutoff = entry.at - retentionMs;\n if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);\n },\n totalSince(sinceMs) {\n let total = 0;\n for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;\n return total;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,mCAAmC;AAE5C,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;;;ACc9B,SAAS,uBAAuB,cAAc,KAAK,KAAK,KAAK,KAAkB;AACpF,MAAI,UAAyB,CAAC;AAE9B,SAAO;AAAA,IACL,OAAO,OAAO;AACZ,cAAQ,KAAK,KAAK;AAClB,YAAM,SAAS,MAAM,KAAK;AAC1B,UAAI,QAAQ,SAAS,GAAI,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,MAAM,MAAM;AAAA,IACzE;AAAA,IACA,WAAW,SAAS;AAClB,UAAI,QAAQ;AACZ,iBAAW,SAAS,QAAS,KAAI,MAAM,MAAM,QAAS,UAAS,MAAM;AACrE,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;ADIA,IAAM,UAAU,KAAK,KAAK;AAC1B,IAAM,SAAS,KAAK;AAEpB,SAAS,OAAO,OAAyC;AACvD,MAAI;AACF,UAAM,MACJ,OAAO,UAAU,WACb,QACA,iBAAiB,MACf,MAAM,SAAS,IACd,MAAkB;AAC3B,WAAO,IAAI,IAAI,GAAG,EAAE,SAAS,YAAY;AAAA,EAC3C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,YA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AAI,CAAC,OAAQ,OAAM,IAAI,WAAW,0CAA0C;AAE5E,gBAAY,WAAW,MAAM;AAC7B,WAAO;AAAA,EACT,CAAC;AAED,aAAW,QAAQ,UAAU;AAC3B,WAAO,SAAS,SAAS,IAAI,EAAE,OAAO,IAAI,eAAe,QAAQ,MAAM,CAAC;AAAA,EAC1E;AAEA,QAAM,UAAmC,OAAO,OAAO,gBAAgB;AACrE,UAAMA,YAAW,MAAM,UAAU,OAAO,WAAW;AACnD,QAAIA,UAAS,WAAW,IAAK,QAAOA;AAGpC,UAAM,UAAU,MAAM,uBAAuBA,SAAQ;AACrD,QAAI,QAAQ,WAAW,GAAG;AAIxB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW,QAAQ,IAAI,CAAC,gBAAgB,WAAW,WAAW,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC;AAC9F,QAAI,aAAa,QAAW;AAC1B,YAAM,eAAe,UAAU,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AACA,WAAOA;AAAA,EACT;AAEA,QAAM,SAAS,qBAAqB,SAAS,MAAM;AACnD,QAAM,WAAW,MAAM,OAAO,KAAoB,IAAI;AAGtD,MAAI,qBAAqB,SAAS,OAAO,KAAK,cAAc,MAAM;AAChE,UAAM,MAAM,OAAO,EAAE,IAAI,IAAI,GAAG,KAAK,UAAU,CAAC;AAAA,EAClD;AAEA,SAAO;AACT;","names":["response"]}
|
|
@@ -2,6 +2,14 @@ import { PaymentRequirements } from '@x402/core/types';
|
|
|
2
2
|
import { ExactEvmScheme } from '@x402/evm/exact/client';
|
|
3
3
|
|
|
4
4
|
/** Base networks in CAIP-2 form, which is what x402 v2 speaks. */
|
|
5
|
+
/**
|
|
6
|
+
* The EIP-712 domain a payer signs the EIP-3009 authorisation against is **not** listed
|
|
7
|
+
* here on purpose: it differs per network (mainnet USDC is "USD Coin", the Sepolia
|
|
8
|
+
* deployment is "USDC"), and the EVM scheme owns the authoritative table. Quoting a
|
|
9
|
+
* dollar price lets it resolve the asset and publish that domain in the 402; naming an
|
|
10
|
+
* explicit asset bypasses the lookup and emits `extra: {}`, which no payer can sign
|
|
11
|
+
* against.
|
|
12
|
+
*/
|
|
5
13
|
declare const NETWORKS: {
|
|
6
14
|
readonly base: {
|
|
7
15
|
readonly caip2: "eip155:8453";
|
|
@@ -26,6 +34,16 @@ declare const NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the
|
|
|
26
34
|
declare const DOCS_URL = "https://fatstack.net/docs/payments";
|
|
27
35
|
/** Correlates a settled payment with the indexer's view of the on-chain transfer. */
|
|
28
36
|
declare const PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
37
|
+
/**
|
|
38
|
+
* x402 v2 dropped the `X-` prefix: the settlement receipt is `PAYMENT-RESPONSE` and the
|
|
39
|
+
* payer's payload is `PAYMENT-SIGNATURE`. The v1 spellings are still read so a v1 payer
|
|
40
|
+
* or resource keeps working. Header names are case-insensitive; these are lowercase
|
|
41
|
+
* because `Headers.get` normalises.
|
|
42
|
+
*/
|
|
43
|
+
declare const SETTLEMENT_HEADERS: readonly ["payment-response", "x-payment-response"];
|
|
44
|
+
declare const PAYMENT_SIGNATURE_HEADERS: readonly ["payment-signature", "x-payment"];
|
|
45
|
+
/** First settlement receipt present on a response, in either spelling. */
|
|
46
|
+
declare function readSettlementHeader(headers: Headers): string | null;
|
|
29
47
|
declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
30
48
|
|
|
31
49
|
/** One recorded spend, in USD, at a wall-clock millisecond. */
|
|
@@ -72,6 +90,13 @@ interface PayFetchOptions {
|
|
|
72
90
|
* throws SpendGuardError otherwise. Called before a payment payload exists.
|
|
73
91
|
*/
|
|
74
92
|
declare function evaluateGuards(quoteUsd: number, guards: SpendGuards, store: SpendStore, now: number): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Reads the offered requirements from a 402.
|
|
95
|
+
*
|
|
96
|
+
* x402 v2 carries them in the base64 `payment-required` header, not the body — the body
|
|
97
|
+
* is the resource's own, and may be anything. v1 put them in the body, so both are read.
|
|
98
|
+
*/
|
|
99
|
+
declare function readQuotedRequirements(response: Response): Promise<PaymentRequirements[]>;
|
|
75
100
|
declare function quoteUsdOf(requirements: PaymentRequirements): number;
|
|
76
101
|
/**
|
|
77
102
|
* A `fetch` that pays for 402 responses, under spend guards.
|
|
@@ -83,4 +108,4 @@ declare function quoteUsdOf(requirements: PaymentRequirements): number;
|
|
|
83
108
|
*/
|
|
84
109
|
declare function payFetch(url: RequestInfo | URL, init: RequestInit | undefined, options: PayFetchOptions): Promise<Response>;
|
|
85
110
|
|
|
86
|
-
export { DEFAULT_FACILITATOR_URL as D, type EvmWallet as E, NETWORKS as N, PAYMENT_REF_HEADER as P,
|
|
111
|
+
export { DEFAULT_FACILITATOR_URL as D, type EvmWallet as E, NETWORKS as N, PAYMENT_REF_HEADER as P, SETTLEMENT_HEADERS as S, USDC_DECIMALS as U, DOCS_URL as a, NO_REFUNDS_NOTICE as b, type NetworkName as c, PAYMENT_SIGNATURE_HEADERS as d, type PayFetchOptions as e, type SpendGuards as f, type SpendRecord as g, type SpendStore as h, createMemorySpendStore as i, evaluateGuards as j, readQuotedRequirements as k, payFetch as p, quoteUsdOf as q, readSettlementHeader as r };
|
|
@@ -2,6 +2,14 @@ import { PaymentRequirements } from '@x402/core/types';
|
|
|
2
2
|
import { ExactEvmScheme } from '@x402/evm/exact/client';
|
|
3
3
|
|
|
4
4
|
/** Base networks in CAIP-2 form, which is what x402 v2 speaks. */
|
|
5
|
+
/**
|
|
6
|
+
* The EIP-712 domain a payer signs the EIP-3009 authorisation against is **not** listed
|
|
7
|
+
* here on purpose: it differs per network (mainnet USDC is "USD Coin", the Sepolia
|
|
8
|
+
* deployment is "USDC"), and the EVM scheme owns the authoritative table. Quoting a
|
|
9
|
+
* dollar price lets it resolve the asset and publish that domain in the 402; naming an
|
|
10
|
+
* explicit asset bypasses the lookup and emits `extra: {}`, which no payer can sign
|
|
11
|
+
* against.
|
|
12
|
+
*/
|
|
5
13
|
declare const NETWORKS: {
|
|
6
14
|
readonly base: {
|
|
7
15
|
readonly caip2: "eip155:8453";
|
|
@@ -26,6 +34,16 @@ declare const NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the
|
|
|
26
34
|
declare const DOCS_URL = "https://fatstack.net/docs/payments";
|
|
27
35
|
/** Correlates a settled payment with the indexer's view of the on-chain transfer. */
|
|
28
36
|
declare const PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
37
|
+
/**
|
|
38
|
+
* x402 v2 dropped the `X-` prefix: the settlement receipt is `PAYMENT-RESPONSE` and the
|
|
39
|
+
* payer's payload is `PAYMENT-SIGNATURE`. The v1 spellings are still read so a v1 payer
|
|
40
|
+
* or resource keeps working. Header names are case-insensitive; these are lowercase
|
|
41
|
+
* because `Headers.get` normalises.
|
|
42
|
+
*/
|
|
43
|
+
declare const SETTLEMENT_HEADERS: readonly ["payment-response", "x-payment-response"];
|
|
44
|
+
declare const PAYMENT_SIGNATURE_HEADERS: readonly ["payment-signature", "x-payment"];
|
|
45
|
+
/** First settlement receipt present on a response, in either spelling. */
|
|
46
|
+
declare function readSettlementHeader(headers: Headers): string | null;
|
|
29
47
|
declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
30
48
|
|
|
31
49
|
/** One recorded spend, in USD, at a wall-clock millisecond. */
|
|
@@ -72,6 +90,13 @@ interface PayFetchOptions {
|
|
|
72
90
|
* throws SpendGuardError otherwise. Called before a payment payload exists.
|
|
73
91
|
*/
|
|
74
92
|
declare function evaluateGuards(quoteUsd: number, guards: SpendGuards, store: SpendStore, now: number): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Reads the offered requirements from a 402.
|
|
95
|
+
*
|
|
96
|
+
* x402 v2 carries them in the base64 `payment-required` header, not the body — the body
|
|
97
|
+
* is the resource's own, and may be anything. v1 put them in the body, so both are read.
|
|
98
|
+
*/
|
|
99
|
+
declare function readQuotedRequirements(response: Response): Promise<PaymentRequirements[]>;
|
|
75
100
|
declare function quoteUsdOf(requirements: PaymentRequirements): number;
|
|
76
101
|
/**
|
|
77
102
|
* A `fetch` that pays for 402 responses, under spend guards.
|
|
@@ -83,4 +108,4 @@ declare function quoteUsdOf(requirements: PaymentRequirements): number;
|
|
|
83
108
|
*/
|
|
84
109
|
declare function payFetch(url: RequestInfo | URL, init: RequestInit | undefined, options: PayFetchOptions): Promise<Response>;
|
|
85
110
|
|
|
86
|
-
export { DEFAULT_FACILITATOR_URL as D, type EvmWallet as E, NETWORKS as N, PAYMENT_REF_HEADER as P,
|
|
111
|
+
export { DEFAULT_FACILITATOR_URL as D, type EvmWallet as E, NETWORKS as N, PAYMENT_REF_HEADER as P, SETTLEMENT_HEADERS as S, USDC_DECIMALS as U, DOCS_URL as a, NO_REFUNDS_NOTICE as b, type NetworkName as c, PAYMENT_SIGNATURE_HEADERS as d, type PayFetchOptions as e, type SpendGuards as f, type SpendRecord as g, type SpendStore as h, createMemorySpendStore as i, evaluateGuards as j, readQuotedRequirements as k, payFetch as p, quoteUsdOf as q, readSettlementHeader as r };
|
package/dist/client.cjs
CHANGED
|
@@ -23,16 +23,22 @@ __export(client_exports, {
|
|
|
23
23
|
PAYMENT_REF_HEADER: () => PAYMENT_REF_HEADER,
|
|
24
24
|
evaluateGuards: () => evaluateGuards,
|
|
25
25
|
payFetch: () => payFetch,
|
|
26
|
-
quoteUsdOf: () => quoteUsdOf
|
|
26
|
+
quoteUsdOf: () => quoteUsdOf,
|
|
27
|
+
readQuotedRequirements: () => readQuotedRequirements
|
|
27
28
|
});
|
|
28
29
|
module.exports = __toCommonJS(client_exports);
|
|
29
30
|
var import_client = require("@x402/core/client");
|
|
31
|
+
var import_http = require("@x402/core/http");
|
|
30
32
|
var import_client2 = require("@x402/evm/exact/client");
|
|
31
33
|
var import_fetch = require("@x402/fetch");
|
|
32
34
|
|
|
33
35
|
// src/constants.ts
|
|
34
36
|
var NETWORKS = {
|
|
35
|
-
base: {
|
|
37
|
+
base: {
|
|
38
|
+
caip2: "eip155:8453",
|
|
39
|
+
chainId: 8453,
|
|
40
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
41
|
+
},
|
|
36
42
|
"base-sepolia": {
|
|
37
43
|
caip2: "eip155:84532",
|
|
38
44
|
chainId: 84532,
|
|
@@ -41,6 +47,14 @@ var NETWORKS = {
|
|
|
41
47
|
};
|
|
42
48
|
var USDC_DECIMALS = 6;
|
|
43
49
|
var PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
50
|
+
var SETTLEMENT_HEADERS = ["payment-response", "x-payment-response"];
|
|
51
|
+
function readSettlementHeader(headers) {
|
|
52
|
+
for (const name of SETTLEMENT_HEADERS) {
|
|
53
|
+
const value = headers.get(name);
|
|
54
|
+
if (value) return value;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
44
58
|
|
|
45
59
|
// src/errors.ts
|
|
46
60
|
var SpendGuardError = class extends Error {
|
|
@@ -53,6 +67,12 @@ var SpendGuardError = class extends Error {
|
|
|
53
67
|
detail;
|
|
54
68
|
name = "SpendGuardError";
|
|
55
69
|
};
|
|
70
|
+
var UnreadableQuoteError = class extends Error {
|
|
71
|
+
name = "UnreadableQuoteError";
|
|
72
|
+
constructor(message) {
|
|
73
|
+
super(message);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
56
76
|
|
|
57
77
|
// src/money.ts
|
|
58
78
|
var UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);
|
|
@@ -135,6 +155,19 @@ async function evaluateGuards(quoteUsd, guards, store, now) {
|
|
|
135
155
|
}
|
|
136
156
|
}
|
|
137
157
|
}
|
|
158
|
+
async function readQuotedRequirements(response) {
|
|
159
|
+
const header = response.headers.get("payment-required");
|
|
160
|
+
if (header) {
|
|
161
|
+
try {
|
|
162
|
+
const decoded = (0, import_http.decodePaymentRequiredHeader)(header);
|
|
163
|
+
if (Array.isArray(decoded.accepts) && decoded.accepts.length > 0) return decoded.accepts;
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const body = await response.clone().json().catch(() => null);
|
|
168
|
+
const accepts = body?.accepts;
|
|
169
|
+
return Array.isArray(accepts) ? accepts : [];
|
|
170
|
+
}
|
|
138
171
|
function quoteUsdOf(requirements) {
|
|
139
172
|
const asRecord = requirements;
|
|
140
173
|
const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;
|
|
@@ -180,19 +213,21 @@ async function payFetch(url, init, options) {
|
|
|
180
213
|
const guarded = async (input, requestInit) => {
|
|
181
214
|
const response2 = await baseFetch(input, requestInit);
|
|
182
215
|
if (response2.status !== 402) return response2;
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
216
|
+
const accepts = await readQuotedRequirements(response2);
|
|
217
|
+
if (accepts.length === 0) {
|
|
218
|
+
throw new UnreadableQuoteError(
|
|
219
|
+
"Received a 402 with no readable payment requirements (no payment-required header, no accepts body). Refusing to pay blind."
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
const cheapest = accepts.map((requirement) => quoteUsdOf(requirement)).sort((a, b) => a - b)[0];
|
|
223
|
+
if (cheapest !== void 0) {
|
|
224
|
+
await evaluateGuards(cheapest, guards, store, now());
|
|
190
225
|
}
|
|
191
226
|
return response2;
|
|
192
227
|
};
|
|
193
228
|
const paying = (0, import_fetch.wrapFetchWithPayment)(guarded, client);
|
|
194
229
|
const response = await paying(url, init);
|
|
195
|
-
if (response.headers
|
|
230
|
+
if (readSettlementHeader(response.headers) && quotedUsd !== null) {
|
|
196
231
|
await store.record({ at: now(), usd: quotedUsd });
|
|
197
232
|
}
|
|
198
233
|
return response;
|
|
@@ -202,6 +237,7 @@ async function payFetch(url, init, options) {
|
|
|
202
237
|
PAYMENT_REF_HEADER,
|
|
203
238
|
evaluateGuards,
|
|
204
239
|
payFetch,
|
|
205
|
-
quoteUsdOf
|
|
240
|
+
quoteUsdOf,
|
|
241
|
+
readQuotedRequirements
|
|
206
242
|
});
|
|
207
243
|
//# sourceMappingURL=client.cjs.map
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/constants.ts","../src/errors.ts","../src/money.ts","../src/store.ts"],"sourcesContent":["import { x402Client } from '@x402/core/client';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { wrapFetchWithPayment } from '@x402/fetch';\n\nimport { NETWORKS, PAYMENT_REF_HEADER } from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { SpendGuardError } from './errors.js';\nimport { quoteToUsd } from './money.js';\nimport { createMemorySpendStore } from './store.js';\nimport type { SpendStore } from './store.js';\n\n/** The signer the official EVM scheme expects: address + signTypedData, no key handling. */\nexport type EvmWallet = ConstructorParameters<typeof ExactEvmScheme>[0];\n\nexport interface SpendGuards {\n /** Hard USD ceiling for a single call. */\n maxPerCall?: number;\n /** Rolling 60-minute USD ceiling. */\n maxPerHour?: number;\n /** Rolling 24-hour USD ceiling. */\n maxPerDay?: number;\n /** Hostnames this agent may pay. Checked before any network call. */\n allowedHosts?: string[];\n}\n\nexport interface PayFetchOptions {\n wallet: EvmWallet;\n guards?: SpendGuards;\n /** Defaults to a process-local in-memory store. */\n store?: SpendStore;\n networks?: NetworkName[];\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction hostOf(input: RequestInfo | URL): string | null {\n try {\n const raw =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** `example.com` in allowedHosts also authorises `tool.example.com`. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const candidate = entry.trim().toLowerCase().replace(/^\\*\\./, '');\n return host === candidate || host.endsWith(`.${candidate}`);\n });\n}\n\n/**\n * Checks every guard against a quote. Returns the USD value if the call may proceed,\n * throws SpendGuardError otherwise. Called before a payment payload exists.\n */\nexport async function evaluateGuards(\n quoteUsd: number,\n guards: SpendGuards,\n store: SpendStore,\n now: number,\n): Promise<void> {\n if (guards.maxPerCall !== undefined && quoteUsd > guards.maxPerCall) {\n throw new SpendGuardError(\n 'maxPerCall',\n `Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,\n { limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd },\n );\n }\n\n if (guards.maxPerHour !== undefined) {\n const spent = await store.totalSince(now - HOUR_MS);\n if (spent + quoteUsd > guards.maxPerHour) {\n throw new SpendGuardError(\n 'maxPerHour',\n `Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,\n { limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n\n if (guards.maxPerDay !== undefined) {\n const spent = await store.totalSince(now - DAY_MS);\n if (spent + quoteUsd > guards.maxPerDay) {\n throw new SpendGuardError(\n 'maxPerDay',\n `Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,\n { limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n}\n\n/** Reads the quoted amount out of x402 payment requirements. */\ninterface PriceableRequirement {\n maxAmountRequired?: string;\n amount?: string;\n asset?: string;\n extra?: { decimals?: number };\n}\n\nexport function quoteUsdOf(requirements: PaymentRequirements): number {\n const asRecord: PriceableRequirement = requirements;\n const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;\n if (!amountAtomic || !asRecord.asset) {\n throw new RangeError('Payment requirements carry no priceable amount; refusing to pay.');\n }\n return quoteToUsd({\n amountAtomic,\n asset: asRecord.asset,\n decimals: asRecord.extra?.decimals,\n });\n}\n\n/**\n * A `fetch` that pays for 402 responses, under spend guards.\n *\n * The 402 handling, signing and retry are the official x402 packages' work. What this adds\n * is refusal: guards are evaluated inside the payment-policy hook, which runs after the\n * quote is known and before any payload is signed, so exceeding a guard throws\n * SpendGuardError with nothing signed and nothing spent.\n */\nexport async function payFetch(\n url: RequestInfo | URL,\n init: RequestInit | undefined,\n options: PayFetchOptions,\n): Promise<Response> {\n const guards = options.guards ?? {};\n const store = options.store ?? createMemorySpendStore();\n const now = options.now ?? Date.now;\n const baseFetch = options.fetch ?? globalThis.fetch;\n const networks = options.networks ?? (['base'] as NetworkName[]);\n\n // Host allowlist is checked first: an unauthorised host should cost no request at all.\n if (guards.allowedHosts) {\n const host = hostOf(url);\n if (!host || !hostAllowed(host, guards.allowedHosts)) {\n throw new SpendGuardError(\n 'allowedHosts',\n `Host ${host ?? '<unparseable>'} is not in allowedHosts`,\n { host: host ?? undefined },\n );\n }\n }\n\n let quotedUsd: number | null = null;\n\n const client = new x402Client((_version, requirements) => {\n // Runs before the payment payload is created. Throwing here means no signature.\n const affordable = requirements.filter((requirement) => {\n const usd = quoteUsdOf(requirement);\n return guards.maxPerCall === undefined || usd <= guards.maxPerCall;\n });\n\n const chosen = (affordable.length > 0 ? affordable : requirements)[0];\n if (!chosen) throw new RangeError('Resource offered no payment requirements');\n\n quotedUsd = quoteUsdOf(chosen);\n return chosen;\n });\n\n for (const name of networks) {\n client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));\n }\n\n const guarded: typeof globalThis.fetch = async (input, requestInit) => {\n const response = await baseFetch(input, requestInit);\n if (response.status !== 402) return response;\n\n // Peek at the quote and apply guards before the wrapper signs anything.\n const body = await response\n .clone()\n .json()\n .catch(() => null);\n const accepts = (body as { accepts?: PaymentRequirements[] } | null)?.accepts;\n if (Array.isArray(accepts) && accepts.length > 0) {\n const cheapest = accepts\n .map((requirement) => quoteUsdOf(requirement))\n .sort((a, b) => a - b)[0];\n if (cheapest !== undefined) {\n await evaluateGuards(cheapest, guards, store, now());\n }\n }\n return response;\n };\n\n const paying = wrapFetchWithPayment(guarded, client);\n const response = await paying(url as RequestInfo, init);\n\n // Record the spend only once a payment actually settled.\n if (response.headers.get('x-payment-response') && quotedUsd !== null) {\n await store.record({ at: now(), usd: quotedUsd });\n }\n\n return response;\n}\n\nexport { PAYMENT_REF_HEADER };\n","/** Base networks in CAIP-2 form, which is what x402 v2 speaks. */\nexport const NETWORKS = {\n base: { caip2: 'eip155:8453', chainId: 8453, usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' },\n 'base-sepolia': {\n caip2: 'eip155:84532',\n chainId: 84532,\n usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n} as const;\n\nexport type NetworkName = keyof typeof NETWORKS;\n\n/** USDC is 6 decimals on Base. */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Required on every 402 body and every payment-facing doc page. A payment is a direct\n * on-chain transfer between two wallets: once settled nobody, Fatstack included, can\n * reverse it.\n */\nexport const NO_REFUNDS_NOTICE =\n 'Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.';\n\nexport const DOCS_URL = 'https://fatstack.net/docs/payments';\n\n/** Correlates a settled payment with the indexer's view of the on-chain transfer. */\nexport const PAYMENT_REF_HEADER = 'X-Fatstack-Payment-Ref';\n\nexport const DEFAULT_FACILITATOR_URL = 'https://x402.org/facilitator';\n","/** Names of the spend guards an agent can set. */\nexport type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';\n\n/**\n * Thrown before anything is signed when a call would breach a spend guard.\n *\n * Payments are final, so the only place to stop an unwanted spend is before the\n * signature exists. Every guard raises this, and it is never thrown after a payment\n * payload has been created.\n */\nexport class SpendGuardError extends Error {\n override readonly name = 'SpendGuardError';\n\n constructor(\n readonly guard: GuardName,\n message: string,\n readonly detail: { limitUsd?: number; attemptedUsd?: number; host?: string } = {},\n ) {\n super(message);\n }\n}\n\n/** Thrown by seams that are typed and reachable but deliberately not built yet. */\nexport class NotImplementedError extends Error {\n override readonly name = 'NotImplementedError';\n\n constructor(feature: string) {\n super(`${feature} is not implemented in this build.`);\n }\n}\n\n/** Thrown when an optional framework adapter is used without its package installed. */\nexport class MissingAdapterError extends Error {\n override readonly name = 'MissingAdapterError';\n\n constructor(pkg: string) {\n super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);\n }\n}\n","import { NETWORKS, USDC_DECIMALS } from './constants.js';\n\nconst UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);\n\n/** \"1.25\" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */\nexport function parseUsdc(input: string): bigint {\n const match = /^(\\d+)(?:\\.(\\d{1,6}))?$/.exec(input.trim());\n if (!match) {\n throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);\n }\n const whole = BigInt(match[1] ?? '0');\n const fraction = BigInt((match[2] ?? '').padEnd(USDC_DECIMALS, '0') || '0');\n return whole * UNITS_PER_USDC + fraction;\n}\n\n/** 1250000n -> \"1.25\". Trailing zeros trimmed. */\nexport function formatUsdc(atomic: bigint): string {\n if (atomic < 0n) throw new RangeError('USDC amounts are never negative');\n const whole = atomic / UNITS_PER_USDC;\n const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, '0');\n const trimmed = fraction.replace(/0+$/, '');\n return trimmed ? `${whole}.${trimmed}` : whole.toString();\n}\n\nconst USDC_ADDRESSES = new Set(\n Object.values(NETWORKS).map((network) => network.usdc.toLowerCase()),\n);\n\n/**\n * Converts a quoted amount to USD for guard evaluation.\n *\n * Fails closed: if the asset is not a USDC contract we recognise and the quote carries no\n * usable `decimals`, this throws rather than guessing. Guessing here would let an\n * unrecognised token slip past a spend cap, and the payment is irreversible.\n */\nexport function quoteToUsd(quote: {\n amountAtomic: string;\n asset: string;\n decimals?: number | undefined;\n}): number {\n const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;\n\n if (decimals === undefined || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n throw new RangeError(\n `Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`,\n );\n }\n\n if (!/^\\d+$/.test(quote.amountAtomic)) {\n throw new RangeError(`Quoted amount is not an integer atomic value: ${quote.amountAtomic}`);\n }\n\n return Number(quote.amountAtomic) / 10 ** decimals;\n}\n","/** One recorded spend, in USD, at a wall-clock millisecond. */\nexport interface SpendRecord {\n at: number;\n usd: number;\n}\n\n/**\n * Where rolling spend totals live. The default is in-memory and per-process; swap in a\n * shared implementation (Redis, Durable Object, Postgres) when an agent runs as more\n * than one process, otherwise each process enforces its own separate budget.\n */\nexport interface SpendStore {\n record(entry: SpendRecord): Promise<void> | void;\n /** Total USD recorded at or after `sinceMs`. */\n totalSince(sinceMs: number): Promise<number> | number;\n}\n\n/** Process-local store. Entries older than the longest window are dropped on write. */\nexport function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1000): SpendStore {\n let entries: SpendRecord[] = [];\n\n return {\n record(entry) {\n entries.push(entry);\n const cutoff = entry.at - retentionMs;\n if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);\n },\n totalSince(sinceMs) {\n let total = 0;\n for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;\n return total;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAE3B,IAAAA,iBAA+B;AAC/B,mBAAqC;;;ACF9B,IAAM,WAAW;AAAA,EACtB,MAAM,EAAE,OAAO,eAAe,SAAS,MAAM,MAAM,6CAA6C;AAAA,EAChG,gBAAgB;AAAA,IACd,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AACF;AAKO,IAAM,gBAAgB;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M,CAAC;AAAA,EAC1E;AAEA,QAAM,UAAmC,OAAO,OAAO,gBAAgB;AACrE,UAAMC,YAAW,MAAM,UAAU,OAAO,WAAW;AACnD,QAAIA,UAAS,WAAW,IAAK,QAAOA;AAGpC,UAAM,OAAO,MAAMA,UAChB,MAAM,EACN,KAAK,EACL,MAAM,MAAM,IAAI;AACnB,UAAM,UAAW,MAAqD;AACtE,QAAI,MAAM,QAAQ,OAAO,KAAK,QAAQ,SAAS,GAAG;AAChD,YAAM,WAAW,QACd,IAAI,CAAC,gBAAgB,WAAW,WAAW,CAAC,EAC5C,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC;AAC1B,UAAI,aAAa,QAAW;AAC1B,cAAM,eAAe,UAAU,QAAQ,OAAO,IAAI,CAAC;AAAA,MACrD;AAAA,IACF;AACA,WAAOA;AAAA,EACT;AAEA,QAAM,aAAS,mCAAqB,SAAS,MAAM;AACnD,QAAM,WAAW,MAAM,OAAO,KAAoB,IAAI;AAGtD,MAAI,SAAS,QAAQ,IAAI,oBAAoB,KAAK,cAAc,MAAM;AACpE,UAAM,MAAM,OAAO,EAAE,IAAI,IAAI,GAAG,KAAK,UAAU,CAAC;AAAA,EAClD;AAEA,SAAO;AACT;","names":["import_client","response"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/constants.ts","../src/errors.ts","../src/money.ts","../src/store.ts"],"sourcesContent":["import { x402Client } from '@x402/core/client';\nimport { decodePaymentRequiredHeader } from '@x402/core/http';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { wrapFetchWithPayment } from '@x402/fetch';\n\nimport { NETWORKS, PAYMENT_REF_HEADER, readSettlementHeader } from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { SpendGuardError, UnreadableQuoteError } from './errors.js';\nimport { quoteToUsd } from './money.js';\nimport { createMemorySpendStore } from './store.js';\nimport type { SpendStore } from './store.js';\n\n/** The signer the official EVM scheme expects: address + signTypedData, no key handling. */\nexport type EvmWallet = ConstructorParameters<typeof ExactEvmScheme>[0];\n\nexport interface SpendGuards {\n /** Hard USD ceiling for a single call. */\n maxPerCall?: number;\n /** Rolling 60-minute USD ceiling. */\n maxPerHour?: number;\n /** Rolling 24-hour USD ceiling. */\n maxPerDay?: number;\n /** Hostnames this agent may pay. Checked before any network call. */\n allowedHosts?: string[];\n}\n\nexport interface PayFetchOptions {\n wallet: EvmWallet;\n guards?: SpendGuards;\n /** Defaults to a process-local in-memory store. */\n store?: SpendStore;\n networks?: NetworkName[];\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction hostOf(input: RequestInfo | URL): string | null {\n try {\n const raw =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** `example.com` in allowedHosts also authorises `tool.example.com`. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const candidate = entry.trim().toLowerCase().replace(/^\\*\\./, '');\n return host === candidate || host.endsWith(`.${candidate}`);\n });\n}\n\n/**\n * Checks every guard against a quote. Returns the USD value if the call may proceed,\n * throws SpendGuardError otherwise. Called before a payment payload exists.\n */\nexport async function evaluateGuards(\n quoteUsd: number,\n guards: SpendGuards,\n store: SpendStore,\n now: number,\n): Promise<void> {\n if (guards.maxPerCall !== undefined && quoteUsd > guards.maxPerCall) {\n throw new SpendGuardError(\n 'maxPerCall',\n `Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,\n { limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd },\n );\n }\n\n if (guards.maxPerHour !== undefined) {\n const spent = await store.totalSince(now - HOUR_MS);\n if (spent + quoteUsd > guards.maxPerHour) {\n throw new SpendGuardError(\n 'maxPerHour',\n `Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,\n { limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n\n if (guards.maxPerDay !== undefined) {\n const spent = await store.totalSince(now - DAY_MS);\n if (spent + quoteUsd > guards.maxPerDay) {\n throw new SpendGuardError(\n 'maxPerDay',\n `Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,\n { limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n}\n\n/**\n * Reads the offered requirements from a 402.\n *\n * x402 v2 carries them in the base64 `payment-required` header, not the body — the body\n * is the resource's own, and may be anything. v1 put them in the body, so both are read.\n */\nexport async function readQuotedRequirements(response: Response): Promise<PaymentRequirements[]> {\n const header = response.headers.get('payment-required');\n if (header) {\n try {\n const decoded = decodePaymentRequiredHeader(header);\n if (Array.isArray(decoded.accepts) && decoded.accepts.length > 0) return decoded.accepts;\n } catch {\n // Fall through to the body form.\n }\n }\n\n const body: unknown = await response\n .clone()\n .json()\n .catch(() => null);\n const accepts = (body as { accepts?: PaymentRequirements[] } | null)?.accepts;\n return Array.isArray(accepts) ? accepts : [];\n}\n\n/** Reads the quoted amount out of x402 payment requirements. */\ninterface PriceableRequirement {\n maxAmountRequired?: string;\n amount?: string;\n asset?: string;\n extra?: { decimals?: number };\n}\n\nexport function quoteUsdOf(requirements: PaymentRequirements): number {\n const asRecord: PriceableRequirement = requirements;\n const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;\n if (!amountAtomic || !asRecord.asset) {\n throw new RangeError('Payment requirements carry no priceable amount; refusing to pay.');\n }\n return quoteToUsd({\n amountAtomic,\n asset: asRecord.asset,\n decimals: asRecord.extra?.decimals,\n });\n}\n\n/**\n * A `fetch` that pays for 402 responses, under spend guards.\n *\n * The 402 handling, signing and retry are the official x402 packages' work. What this adds\n * is refusal: guards are evaluated inside the payment-policy hook, which runs after the\n * quote is known and before any payload is signed, so exceeding a guard throws\n * SpendGuardError with nothing signed and nothing spent.\n */\nexport async function payFetch(\n url: RequestInfo | URL,\n init: RequestInit | undefined,\n options: PayFetchOptions,\n): Promise<Response> {\n const guards = options.guards ?? {};\n const store = options.store ?? createMemorySpendStore();\n const now = options.now ?? Date.now;\n const baseFetch = options.fetch ?? globalThis.fetch;\n const networks = options.networks ?? (['base'] as NetworkName[]);\n\n // Host allowlist is checked first: an unauthorised host should cost no request at all.\n if (guards.allowedHosts) {\n const host = hostOf(url);\n if (!host || !hostAllowed(host, guards.allowedHosts)) {\n throw new SpendGuardError(\n 'allowedHosts',\n `Host ${host ?? '<unparseable>'} is not in allowedHosts`,\n { host: host ?? undefined },\n );\n }\n }\n\n let quotedUsd: number | null = null;\n\n const client = new x402Client((_version, requirements) => {\n // Runs before the payment payload is created. Throwing here means no signature.\n const affordable = requirements.filter((requirement) => {\n const usd = quoteUsdOf(requirement);\n return guards.maxPerCall === undefined || usd <= guards.maxPerCall;\n });\n\n const chosen = (affordable.length > 0 ? affordable : requirements)[0];\n if (!chosen) throw new RangeError('Resource offered no payment requirements');\n\n quotedUsd = quoteUsdOf(chosen);\n return chosen;\n });\n\n for (const name of networks) {\n client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));\n }\n\n const guarded: typeof globalThis.fetch = async (input, requestInit) => {\n const response = await baseFetch(input, requestInit);\n if (response.status !== 402) return response;\n\n // Peek at the quote and apply guards before the wrapper signs anything.\n const accepts = await readQuotedRequirements(response);\n if (accepts.length === 0) {\n // A 402 whose requirements we cannot read is a 402 we cannot price, and an\n // unpriced call cannot be checked against a spend cap. Refuse rather than let it\n // through unguarded.\n throw new UnreadableQuoteError(\n 'Received a 402 with no readable payment requirements (no payment-required header, no accepts body). Refusing to pay blind.',\n );\n }\n\n const cheapest = accepts.map((requirement) => quoteUsdOf(requirement)).sort((a, b) => a - b)[0];\n if (cheapest !== undefined) {\n await evaluateGuards(cheapest, guards, store, now());\n }\n return response;\n };\n\n const paying = wrapFetchWithPayment(guarded, client);\n const response = await paying(url as RequestInfo, init);\n\n // Record the spend only once a payment actually settled.\n if (readSettlementHeader(response.headers) && quotedUsd !== null) {\n await store.record({ at: now(), usd: quotedUsd });\n }\n\n return response;\n}\n\nexport { PAYMENT_REF_HEADER };\n","/** Base networks in CAIP-2 form, which is what x402 v2 speaks. */\n/**\n * The EIP-712 domain a payer signs the EIP-3009 authorisation against is **not** listed\n * here on purpose: it differs per network (mainnet USDC is \"USD Coin\", the Sepolia\n * deployment is \"USDC\"), and the EVM scheme owns the authoritative table. Quoting a\n * dollar price lets it resolve the asset and publish that domain in the 402; naming an\n * explicit asset bypasses the lookup and emits `extra: {}`, which no payer can sign\n * against.\n */\nexport const NETWORKS = {\n base: {\n caip2: 'eip155:8453',\n chainId: 8453,\n usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n },\n 'base-sepolia': {\n caip2: 'eip155:84532',\n chainId: 84532,\n usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n} as const;\n\nexport type NetworkName = keyof typeof NETWORKS;\n\n/** USDC is 6 decimals on Base. */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Required on every 402 body and every payment-facing doc page. A payment is a direct\n * on-chain transfer between two wallets: once settled nobody, Fatstack included, can\n * reverse it.\n */\nexport const NO_REFUNDS_NOTICE =\n 'Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.';\n\nexport const DOCS_URL = 'https://fatstack.net/docs/payments';\n\n/** Correlates a settled payment with the indexer's view of the on-chain transfer. */\nexport const PAYMENT_REF_HEADER = 'X-Fatstack-Payment-Ref';\n\n/**\n * x402 v2 dropped the `X-` prefix: the settlement receipt is `PAYMENT-RESPONSE` and the\n * payer's payload is `PAYMENT-SIGNATURE`. The v1 spellings are still read so a v1 payer\n * or resource keeps working. Header names are case-insensitive; these are lowercase\n * because `Headers.get` normalises.\n */\nexport const SETTLEMENT_HEADERS = ['payment-response', 'x-payment-response'] as const;\nexport const PAYMENT_SIGNATURE_HEADERS = ['payment-signature', 'x-payment'] as const;\n\n/** First settlement receipt present on a response, in either spelling. */\nexport function readSettlementHeader(headers: Headers): string | null {\n for (const name of SETTLEMENT_HEADERS) {\n const value = headers.get(name);\n if (value) return value;\n }\n return null;\n}\n\nexport const DEFAULT_FACILITATOR_URL = 'https://x402.org/facilitator';\n","/** Names of the spend guards an agent can set. */\nexport type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';\n\n/**\n * Thrown before anything is signed when a call would breach a spend guard.\n *\n * Payments are final, so the only place to stop an unwanted spend is before the\n * signature exists. Every guard raises this, and it is never thrown after a payment\n * payload has been created.\n */\nexport class SpendGuardError extends Error {\n override readonly name = 'SpendGuardError';\n\n constructor(\n readonly guard: GuardName,\n message: string,\n readonly detail: { limitUsd?: number; attemptedUsd?: number; host?: string } = {},\n ) {\n super(message);\n }\n}\n\n/** Thrown by seams that are typed and reachable but deliberately not built yet. */\nexport class NotImplementedError extends Error {\n override readonly name = 'NotImplementedError';\n\n constructor(feature: string) {\n super(`${feature} is not implemented in this build.`);\n }\n}\n\n/** Thrown when an optional framework adapter is used without its package installed. */\nexport class MissingAdapterError extends Error {\n override readonly name = 'MissingAdapterError';\n\n constructor(pkg: string) {\n super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);\n }\n}\n\n/**\n * A 402 arrived whose payment requirements could not be read, so the call cannot be\n * priced and therefore cannot be checked against a spend cap. Refusing is the safe\n * outcome: paying blind is irreversible.\n */\nexport class UnreadableQuoteError extends Error {\n override readonly name = 'UnreadableQuoteError';\n\n constructor(message: string) {\n super(message);\n }\n}\n","import { NETWORKS, USDC_DECIMALS } from './constants.js';\n\nconst UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);\n\n/** \"1.25\" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */\nexport function parseUsdc(input: string): bigint {\n const match = /^(\\d+)(?:\\.(\\d{1,6}))?$/.exec(input.trim());\n if (!match) {\n throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);\n }\n const whole = BigInt(match[1] ?? '0');\n const fraction = BigInt((match[2] ?? '').padEnd(USDC_DECIMALS, '0') || '0');\n return whole * UNITS_PER_USDC + fraction;\n}\n\n/** 1250000n -> \"1.25\". Trailing zeros trimmed. */\nexport function formatUsdc(atomic: bigint): string {\n if (atomic < 0n) throw new RangeError('USDC amounts are never negative');\n const whole = atomic / UNITS_PER_USDC;\n const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, '0');\n const trimmed = fraction.replace(/0+$/, '');\n return trimmed ? `${whole}.${trimmed}` : whole.toString();\n}\n\nconst USDC_ADDRESSES = new Set(\n Object.values(NETWORKS).map((network) => network.usdc.toLowerCase()),\n);\n\n/**\n * Converts a quoted amount to USD for guard evaluation.\n *\n * Fails closed: if the asset is not a USDC contract we recognise and the quote carries no\n * usable `decimals`, this throws rather than guessing. Guessing here would let an\n * unrecognised token slip past a spend cap, and the payment is irreversible.\n */\nexport function quoteToUsd(quote: {\n amountAtomic: string;\n asset: string;\n decimals?: number | undefined;\n}): number {\n const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;\n\n if (decimals === undefined || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n throw new RangeError(\n `Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`,\n );\n }\n\n if (!/^\\d+$/.test(quote.amountAtomic)) {\n throw new RangeError(`Quoted amount is not an integer atomic value: ${quote.amountAtomic}`);\n }\n\n return Number(quote.amountAtomic) / 10 ** decimals;\n}\n","/** One recorded spend, in USD, at a wall-clock millisecond. */\nexport interface SpendRecord {\n at: number;\n usd: number;\n}\n\n/**\n * Where rolling spend totals live. The default is in-memory and per-process; swap in a\n * shared implementation (Redis, Durable Object, Postgres) when an agent runs as more\n * than one process, otherwise each process enforces its own separate budget.\n */\nexport interface SpendStore {\n record(entry: SpendRecord): Promise<void> | void;\n /** Total USD recorded at or after `sinceMs`. */\n totalSince(sinceMs: number): Promise<number> | number;\n}\n\n/** Process-local store. Entries older than the longest window are dropped on write. */\nexport function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1000): SpendStore {\n let entries: SpendRecord[] = [];\n\n return {\n record(entry) {\n entries.push(entry);\n const cutoff = entry.at - retentionMs;\n if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);\n },\n totalSince(sinceMs) {\n let total = 0;\n for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;\n return total;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,kBAA4C;AAE5C,IAAAA,iBAA+B;AAC/B,mBAAqC;;;ACK9B,IAAM,WAAW;AAAA,EACtB,MAAM;AAAA,IACJ,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA,gBAAgB;AAAA,IACd,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AACF;AAKO,IAAM,gBAAgB;AAatB,IAAM,qBAAqB;AAQ3B,IAAM,qBAAqB,CAAC,oBAAoB,oBAAoB;AAIpE,SAAS,qBAAqB,SAAiC;AACpE,aAAW,QAAQ,oBAAoB;AACrC,UAAM,QAAQ,QAAQ,IAAI,IAAI;AAC9B,QAAI,MAAO,QAAO;AAAA,EACpB;AACA,SAAO;AACT;;;AC9CO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAGzC,YACW,OACT,SACS,SAAsE,CAAC,GAChF;AACA,UAAM,OAAO;AAJJ;AAEA;AAAA,EAGX;AAAA,EALW;AAAA,EAEA;AAAA,EALO,OAAO;AAS3B;AAyBO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC5B,OAAO;AAAA,EAEzB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AAAA,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AW,SAAS,IAAI,aAAa,cAAc,CAAC;AACpE,QAAI,CAAC,OAAQ,OAAM,IAAI,WAAW,0CAA0C;AAE5E,gBAAY,WAAW,MAAM;AAC7B,WAAO;AAAA,EACT,CAAC;AAED,aAAW,QAAQ,UAAU;AAC3B,WAAO,SAAS,SAAS,IAAI,EAAE,OAAO,IAAI,8BAAe,QAAQ,MAAM,CAAC;AAAA,EAC1E;AAEA,QAAM,UAAmC,OAAO,OAAO,gBAAgB;AACrE,UAAMC,YAAW,MAAM,UAAU,OAAO,WAAW;AACnD,QAAIA,UAAS,WAAW,IAAK,QAAOA;AAGpC,UAAM,UAAU,MAAM,uBAAuBA,SAAQ;AACrD,QAAI,QAAQ,WAAW,GAAG;AAIxB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW,QAAQ,IAAI,CAAC,gBAAgB,WAAW,WAAW,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC;AAC9F,QAAI,aAAa,QAAW;AAC1B,YAAM,eAAe,UAAU,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AACA,WAAOA;AAAA,EACT;AAEA,QAAM,aAAS,mCAAqB,SAAS,MAAM;AACnD,QAAM,WAAW,MAAM,OAAO,KAAoB,IAAI;AAGtD,MAAI,qBAAqB,SAAS,OAAO,KAAK,cAAc,MAAM;AAChE,UAAM,MAAM,OAAO,EAAE,IAAI,IAAI,GAAG,KAAK,UAAU,CAAC;AAAA,EAClD;AAEA,SAAO;AACT;","names":["import_client","response"]}
|
package/dist/client.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import '@x402/core/types';
|
|
2
2
|
import '@x402/evm/exact/client';
|
|
3
|
-
export { E as EvmWallet, P as PAYMENT_REF_HEADER,
|
|
3
|
+
export { E as EvmWallet, P as PAYMENT_REF_HEADER, e as PayFetchOptions, f as SpendGuards, j as evaluateGuards, p as payFetch, q as quoteUsdOf, k as readQuotedRequirements } from './client-BBsrY6gC.cjs';
|
package/dist/client.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import '@x402/core/types';
|
|
2
2
|
import '@x402/evm/exact/client';
|
|
3
|
-
export { E as EvmWallet, P as PAYMENT_REF_HEADER,
|
|
3
|
+
export { E as EvmWallet, P as PAYMENT_REF_HEADER, e as PayFetchOptions, f as SpendGuards, j as evaluateGuards, p as payFetch, q as quoteUsdOf, k as readQuotedRequirements } from './client-BBsrY6gC.js';
|