@fatstack/x402 0.0.1 → 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/README.md +114 -6
- package/dist/chunk-C4BASAUA.js +111 -0
- package/dist/chunk-C4BASAUA.js.map +1 -0
- package/dist/chunk-PY25VKHS.js +219 -0
- package/dist/chunk-PY25VKHS.js.map +1 -0
- package/dist/chunk-ZGVPNFNS.js +163 -0
- package/dist/chunk-ZGVPNFNS.js.map +1 -0
- package/dist/client-BBsrY6gC.d.cts +111 -0
- package/dist/client-BBsrY6gC.d.ts +111 -0
- package/dist/client.cjs +243 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +3 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +17 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +516 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +117 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.js +61 -0
- package/dist/index.js.map +1 -0
- package/dist/provider.cjs +289 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +99 -0
- package/dist/provider.d.ts +99 -0
- package/dist/provider.js +8 -0
- package/dist/provider.js.map +1 -0
- package/dist/testing.cjs +73 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +22 -0
- package/dist/testing.d.ts +22 -0
- package/dist/testing.js +48 -0
- package/dist/testing.js.map +1 -0
- package/package.json +84 -4
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
export { D as DEFAULT_FACILITATOR_URL, a as DOCS_URL, E as EvmWallet, N as NETWORKS, b as NO_REFUNDS_NOTICE, c as NetworkName, P as PAYMENT_REF_HEADER, d as PAYMENT_SIGNATURE_HEADERS, e as PayFetchOptions, S as SETTLEMENT_HEADERS, f as SpendGuards, g as SpendRecord, h as SpendStore, U as USDC_DECIMALS, i as createMemorySpendStore, j as evaluateGuards, p as payFetch, q as quoteUsdOf, r as readSettlementHeader } from './client-BBsrY6gC.cjs';
|
|
2
|
+
export { ExpressMiddleware, ExpressResponseLike, HonoContextLike, HonoMiddleware, Paywall, PaywallOptions, UnpaidBody, paywall } from './provider.cjs';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
export { decodePaymentResponseHeader } from '@x402/core/http';
|
|
5
|
+
export { FacilitatorClient, RouteConfig } from '@x402/core/server';
|
|
6
|
+
import '@x402/core/types';
|
|
7
|
+
import '@x402/evm/exact/client';
|
|
8
|
+
|
|
9
|
+
/** Names of the spend guards an agent can set. */
|
|
10
|
+
type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';
|
|
11
|
+
/**
|
|
12
|
+
* Thrown before anything is signed when a call would breach a spend guard.
|
|
13
|
+
*
|
|
14
|
+
* Payments are final, so the only place to stop an unwanted spend is before the
|
|
15
|
+
* signature exists. Every guard raises this, and it is never thrown after a payment
|
|
16
|
+
* payload has been created.
|
|
17
|
+
*/
|
|
18
|
+
declare class SpendGuardError extends Error {
|
|
19
|
+
readonly guard: GuardName;
|
|
20
|
+
readonly detail: {
|
|
21
|
+
limitUsd?: number;
|
|
22
|
+
attemptedUsd?: number;
|
|
23
|
+
host?: string;
|
|
24
|
+
};
|
|
25
|
+
readonly name = "SpendGuardError";
|
|
26
|
+
constructor(guard: GuardName, message: string, detail?: {
|
|
27
|
+
limitUsd?: number;
|
|
28
|
+
attemptedUsd?: number;
|
|
29
|
+
host?: string;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** Thrown by seams that are typed and reachable but deliberately not built yet. */
|
|
33
|
+
declare class NotImplementedError extends Error {
|
|
34
|
+
readonly name = "NotImplementedError";
|
|
35
|
+
constructor(feature: string);
|
|
36
|
+
}
|
|
37
|
+
/** Thrown when an optional framework adapter is used without its package installed. */
|
|
38
|
+
declare class MissingAdapterError extends Error {
|
|
39
|
+
readonly name = "MissingAdapterError";
|
|
40
|
+
constructor(pkg: string);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A 402 arrived whose payment requirements could not be read, so the call cannot be
|
|
44
|
+
* priced and therefore cannot be checked against a spend cap. Refusing is the safe
|
|
45
|
+
* outcome: paying blind is irreversible.
|
|
46
|
+
*/
|
|
47
|
+
declare class UnreadableQuoteError extends Error {
|
|
48
|
+
readonly name = "UnreadableQuoteError";
|
|
49
|
+
constructor(message: string);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type FeeMode = 'direct' | 'splitter';
|
|
53
|
+
interface PayeeResolution {
|
|
54
|
+
/** The single address that receives the transfer. */
|
|
55
|
+
payTo: string;
|
|
56
|
+
/** Platform fee in basis points. Always 0 while FEE_MODE=direct. */
|
|
57
|
+
feeBps: number;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Resolves who is paid for a call. Under `direct` this is always, and only, the
|
|
61
|
+
* provider's own wallet — the platform is never a payee and never custodies funds.
|
|
62
|
+
*
|
|
63
|
+
* `splitter` is a reserved seam for the fee-splitting contract. It is typed and reachable
|
|
64
|
+
* so the shape is settled, but it throws: there is no splitter contract in this build.
|
|
65
|
+
*/
|
|
66
|
+
declare function resolvePayee(mode: FeeMode, providerWallet: string): PayeeResolution;
|
|
67
|
+
|
|
68
|
+
/** "1.25" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */
|
|
69
|
+
declare function parseUsdc(input: string): bigint;
|
|
70
|
+
/** 1250000n -> "1.25". Trailing zeros trimmed. */
|
|
71
|
+
declare function formatUsdc(atomic: bigint): string;
|
|
72
|
+
/**
|
|
73
|
+
* Converts a quoted amount to USD for guard evaluation.
|
|
74
|
+
*
|
|
75
|
+
* Fails closed: if the asset is not a USDC contract we recognise and the quote carries no
|
|
76
|
+
* usable `decimals`, this throws rather than guessing. Guessing here would let an
|
|
77
|
+
* unrecognised token slip past a spend cap, and the payment is irreversible.
|
|
78
|
+
*/
|
|
79
|
+
declare function quoteToUsd(quote: {
|
|
80
|
+
amountAtomic: string;
|
|
81
|
+
asset: string;
|
|
82
|
+
decimals?: number | undefined;
|
|
83
|
+
}): number;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Environment the paywall reads. Parsed lazily inside `paywall()`, never at module load,
|
|
87
|
+
* so importing this package never throws in a build step.
|
|
88
|
+
*/
|
|
89
|
+
declare const paywallEnvSchema: z.ZodObject<{
|
|
90
|
+
/** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */
|
|
91
|
+
FACILITATOR_URL: z.ZodDefault<z.ZodString>;
|
|
92
|
+
FACILITATOR_API_KEY: z.ZodOptional<z.ZodString>;
|
|
93
|
+
/**
|
|
94
|
+
* `1` takes every paywalled route offline with a 503. Intended for an incident where
|
|
95
|
+
* continuing to take irreversible payments would be worse than being down.
|
|
96
|
+
*/
|
|
97
|
+
KILLSWITCH: z.ZodDefault<z.ZodEnum<["0", "1"]>>;
|
|
98
|
+
/**
|
|
99
|
+
* direct = agent pays the provider wallet, 0% platform fee (the launch build)
|
|
100
|
+
* splitter = reserved for the fee-splitting contract; not implemented
|
|
101
|
+
*/
|
|
102
|
+
FEE_MODE: z.ZodDefault<z.ZodEnum<["direct", "splitter"]>>;
|
|
103
|
+
}, "strip", z.ZodTypeAny, {
|
|
104
|
+
FACILITATOR_URL: string;
|
|
105
|
+
KILLSWITCH: "0" | "1";
|
|
106
|
+
FEE_MODE: "direct" | "splitter";
|
|
107
|
+
FACILITATOR_API_KEY?: string | undefined;
|
|
108
|
+
}, {
|
|
109
|
+
FACILITATOR_URL?: string | undefined;
|
|
110
|
+
FACILITATOR_API_KEY?: string | undefined;
|
|
111
|
+
KILLSWITCH?: "0" | "1" | undefined;
|
|
112
|
+
FEE_MODE?: "direct" | "splitter" | undefined;
|
|
113
|
+
}>;
|
|
114
|
+
type PaywallEnv = z.infer<typeof paywallEnvSchema>;
|
|
115
|
+
declare function readPaywallEnv(source?: Record<string, string | undefined>): PaywallEnv;
|
|
116
|
+
|
|
117
|
+
export { type FeeMode, type GuardName, MissingAdapterError, NotImplementedError, type PayeeResolution, type PaywallEnv, SpendGuardError, UnreadableQuoteError, formatUsdc, parseUsdc, paywallEnvSchema, quoteToUsd, readPaywallEnv, resolvePayee };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
export { D as DEFAULT_FACILITATOR_URL, a as DOCS_URL, E as EvmWallet, N as NETWORKS, b as NO_REFUNDS_NOTICE, c as NetworkName, P as PAYMENT_REF_HEADER, d as PAYMENT_SIGNATURE_HEADERS, e as PayFetchOptions, S as SETTLEMENT_HEADERS, f as SpendGuards, g as SpendRecord, h as SpendStore, U as USDC_DECIMALS, i as createMemorySpendStore, j as evaluateGuards, p as payFetch, q as quoteUsdOf, r as readSettlementHeader } from './client-BBsrY6gC.js';
|
|
2
|
+
export { ExpressMiddleware, ExpressResponseLike, HonoContextLike, HonoMiddleware, Paywall, PaywallOptions, UnpaidBody, paywall } from './provider.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
export { decodePaymentResponseHeader } from '@x402/core/http';
|
|
5
|
+
export { FacilitatorClient, RouteConfig } from '@x402/core/server';
|
|
6
|
+
import '@x402/core/types';
|
|
7
|
+
import '@x402/evm/exact/client';
|
|
8
|
+
|
|
9
|
+
/** Names of the spend guards an agent can set. */
|
|
10
|
+
type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';
|
|
11
|
+
/**
|
|
12
|
+
* Thrown before anything is signed when a call would breach a spend guard.
|
|
13
|
+
*
|
|
14
|
+
* Payments are final, so the only place to stop an unwanted spend is before the
|
|
15
|
+
* signature exists. Every guard raises this, and it is never thrown after a payment
|
|
16
|
+
* payload has been created.
|
|
17
|
+
*/
|
|
18
|
+
declare class SpendGuardError extends Error {
|
|
19
|
+
readonly guard: GuardName;
|
|
20
|
+
readonly detail: {
|
|
21
|
+
limitUsd?: number;
|
|
22
|
+
attemptedUsd?: number;
|
|
23
|
+
host?: string;
|
|
24
|
+
};
|
|
25
|
+
readonly name = "SpendGuardError";
|
|
26
|
+
constructor(guard: GuardName, message: string, detail?: {
|
|
27
|
+
limitUsd?: number;
|
|
28
|
+
attemptedUsd?: number;
|
|
29
|
+
host?: string;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** Thrown by seams that are typed and reachable but deliberately not built yet. */
|
|
33
|
+
declare class NotImplementedError extends Error {
|
|
34
|
+
readonly name = "NotImplementedError";
|
|
35
|
+
constructor(feature: string);
|
|
36
|
+
}
|
|
37
|
+
/** Thrown when an optional framework adapter is used without its package installed. */
|
|
38
|
+
declare class MissingAdapterError extends Error {
|
|
39
|
+
readonly name = "MissingAdapterError";
|
|
40
|
+
constructor(pkg: string);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A 402 arrived whose payment requirements could not be read, so the call cannot be
|
|
44
|
+
* priced and therefore cannot be checked against a spend cap. Refusing is the safe
|
|
45
|
+
* outcome: paying blind is irreversible.
|
|
46
|
+
*/
|
|
47
|
+
declare class UnreadableQuoteError extends Error {
|
|
48
|
+
readonly name = "UnreadableQuoteError";
|
|
49
|
+
constructor(message: string);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type FeeMode = 'direct' | 'splitter';
|
|
53
|
+
interface PayeeResolution {
|
|
54
|
+
/** The single address that receives the transfer. */
|
|
55
|
+
payTo: string;
|
|
56
|
+
/** Platform fee in basis points. Always 0 while FEE_MODE=direct. */
|
|
57
|
+
feeBps: number;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Resolves who is paid for a call. Under `direct` this is always, and only, the
|
|
61
|
+
* provider's own wallet — the platform is never a payee and never custodies funds.
|
|
62
|
+
*
|
|
63
|
+
* `splitter` is a reserved seam for the fee-splitting contract. It is typed and reachable
|
|
64
|
+
* so the shape is settled, but it throws: there is no splitter contract in this build.
|
|
65
|
+
*/
|
|
66
|
+
declare function resolvePayee(mode: FeeMode, providerWallet: string): PayeeResolution;
|
|
67
|
+
|
|
68
|
+
/** "1.25" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */
|
|
69
|
+
declare function parseUsdc(input: string): bigint;
|
|
70
|
+
/** 1250000n -> "1.25". Trailing zeros trimmed. */
|
|
71
|
+
declare function formatUsdc(atomic: bigint): string;
|
|
72
|
+
/**
|
|
73
|
+
* Converts a quoted amount to USD for guard evaluation.
|
|
74
|
+
*
|
|
75
|
+
* Fails closed: if the asset is not a USDC contract we recognise and the quote carries no
|
|
76
|
+
* usable `decimals`, this throws rather than guessing. Guessing here would let an
|
|
77
|
+
* unrecognised token slip past a spend cap, and the payment is irreversible.
|
|
78
|
+
*/
|
|
79
|
+
declare function quoteToUsd(quote: {
|
|
80
|
+
amountAtomic: string;
|
|
81
|
+
asset: string;
|
|
82
|
+
decimals?: number | undefined;
|
|
83
|
+
}): number;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Environment the paywall reads. Parsed lazily inside `paywall()`, never at module load,
|
|
87
|
+
* so importing this package never throws in a build step.
|
|
88
|
+
*/
|
|
89
|
+
declare const paywallEnvSchema: z.ZodObject<{
|
|
90
|
+
/** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */
|
|
91
|
+
FACILITATOR_URL: z.ZodDefault<z.ZodString>;
|
|
92
|
+
FACILITATOR_API_KEY: z.ZodOptional<z.ZodString>;
|
|
93
|
+
/**
|
|
94
|
+
* `1` takes every paywalled route offline with a 503. Intended for an incident where
|
|
95
|
+
* continuing to take irreversible payments would be worse than being down.
|
|
96
|
+
*/
|
|
97
|
+
KILLSWITCH: z.ZodDefault<z.ZodEnum<["0", "1"]>>;
|
|
98
|
+
/**
|
|
99
|
+
* direct = agent pays the provider wallet, 0% platform fee (the launch build)
|
|
100
|
+
* splitter = reserved for the fee-splitting contract; not implemented
|
|
101
|
+
*/
|
|
102
|
+
FEE_MODE: z.ZodDefault<z.ZodEnum<["direct", "splitter"]>>;
|
|
103
|
+
}, "strip", z.ZodTypeAny, {
|
|
104
|
+
FACILITATOR_URL: string;
|
|
105
|
+
KILLSWITCH: "0" | "1";
|
|
106
|
+
FEE_MODE: "direct" | "splitter";
|
|
107
|
+
FACILITATOR_API_KEY?: string | undefined;
|
|
108
|
+
}, {
|
|
109
|
+
FACILITATOR_URL?: string | undefined;
|
|
110
|
+
FACILITATOR_API_KEY?: string | undefined;
|
|
111
|
+
KILLSWITCH?: "0" | "1" | undefined;
|
|
112
|
+
FEE_MODE?: "direct" | "splitter" | undefined;
|
|
113
|
+
}>;
|
|
114
|
+
type PaywallEnv = z.infer<typeof paywallEnvSchema>;
|
|
115
|
+
declare function readPaywallEnv(source?: Record<string, string | undefined>): PaywallEnv;
|
|
116
|
+
|
|
117
|
+
export { type FeeMode, type GuardName, MissingAdapterError, NotImplementedError, type PayeeResolution, type PaywallEnv, SpendGuardError, UnreadableQuoteError, formatUsdc, parseUsdc, paywallEnvSchema, quoteToUsd, readPaywallEnv, resolvePayee };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createMemorySpendStore,
|
|
3
|
+
evaluateGuards,
|
|
4
|
+
payFetch,
|
|
5
|
+
quoteUsdOf
|
|
6
|
+
} from "./chunk-ZGVPNFNS.js";
|
|
7
|
+
import {
|
|
8
|
+
paywall,
|
|
9
|
+
paywallEnvSchema,
|
|
10
|
+
readPaywallEnv,
|
|
11
|
+
resolvePayee
|
|
12
|
+
} from "./chunk-PY25VKHS.js";
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_FACILITATOR_URL,
|
|
15
|
+
DOCS_URL,
|
|
16
|
+
MissingAdapterError,
|
|
17
|
+
NETWORKS,
|
|
18
|
+
NO_REFUNDS_NOTICE,
|
|
19
|
+
NotImplementedError,
|
|
20
|
+
PAYMENT_REF_HEADER,
|
|
21
|
+
PAYMENT_SIGNATURE_HEADERS,
|
|
22
|
+
SETTLEMENT_HEADERS,
|
|
23
|
+
SpendGuardError,
|
|
24
|
+
USDC_DECIMALS,
|
|
25
|
+
UnreadableQuoteError,
|
|
26
|
+
formatUsdc,
|
|
27
|
+
parseUsdc,
|
|
28
|
+
quoteToUsd,
|
|
29
|
+
readSettlementHeader
|
|
30
|
+
} from "./chunk-C4BASAUA.js";
|
|
31
|
+
|
|
32
|
+
// src/index.ts
|
|
33
|
+
import { decodePaymentResponseHeader } from "@x402/core/http";
|
|
34
|
+
export {
|
|
35
|
+
DEFAULT_FACILITATOR_URL,
|
|
36
|
+
DOCS_URL,
|
|
37
|
+
MissingAdapterError,
|
|
38
|
+
NETWORKS,
|
|
39
|
+
NO_REFUNDS_NOTICE,
|
|
40
|
+
NotImplementedError,
|
|
41
|
+
PAYMENT_REF_HEADER,
|
|
42
|
+
PAYMENT_SIGNATURE_HEADERS,
|
|
43
|
+
SETTLEMENT_HEADERS,
|
|
44
|
+
SpendGuardError,
|
|
45
|
+
USDC_DECIMALS,
|
|
46
|
+
UnreadableQuoteError,
|
|
47
|
+
createMemorySpendStore,
|
|
48
|
+
decodePaymentResponseHeader,
|
|
49
|
+
evaluateGuards,
|
|
50
|
+
formatUsdc,
|
|
51
|
+
parseUsdc,
|
|
52
|
+
payFetch,
|
|
53
|
+
paywall,
|
|
54
|
+
paywallEnvSchema,
|
|
55
|
+
quoteToUsd,
|
|
56
|
+
quoteUsdOf,
|
|
57
|
+
readPaywallEnv,
|
|
58
|
+
readSettlementHeader,
|
|
59
|
+
resolvePayee
|
|
60
|
+
};
|
|
61
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './constants.js';\nexport * from './errors.js';\nexport * from './fee-mode.js';\nexport * from './money.js';\nexport * from './store.js';\nexport { paywall } from './provider.js';\nexport type {\n Paywall,\n PaywallOptions,\n UnpaidBody,\n HonoMiddleware,\n HonoContextLike,\n ExpressMiddleware,\n ExpressResponseLike,\n FacilitatorClient,\n RouteConfig,\n} from './provider.js';\nexport { payFetch, evaluateGuards, quoteUsdOf } from './client.js';\nexport type { EvmWallet, PayFetchOptions, SpendGuards } from './client.js';\nexport { readPaywallEnv, paywallEnvSchema } from './env.js';\nexport type { PaywallEnv } from './env.js';\nexport { decodePaymentResponseHeader } from '@x402/core/http';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,mCAAmC;","names":[]}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/provider.ts
|
|
21
|
+
var provider_exports = {};
|
|
22
|
+
__export(provider_exports, {
|
|
23
|
+
paywall: () => paywall
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(provider_exports);
|
|
26
|
+
var import_http = require("@x402/core/http");
|
|
27
|
+
var import_server = require("@x402/core/server");
|
|
28
|
+
var import_server2 = require("@x402/evm/exact/server");
|
|
29
|
+
var import_zod2 = require("zod");
|
|
30
|
+
|
|
31
|
+
// src/constants.ts
|
|
32
|
+
var NETWORKS = {
|
|
33
|
+
base: {
|
|
34
|
+
caip2: "eip155:8453",
|
|
35
|
+
chainId: 8453,
|
|
36
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
37
|
+
},
|
|
38
|
+
"base-sepolia": {
|
|
39
|
+
caip2: "eip155:84532",
|
|
40
|
+
chainId: 84532,
|
|
41
|
+
usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var USDC_DECIMALS = 6;
|
|
45
|
+
var NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.";
|
|
46
|
+
var DOCS_URL = "https://fatstack.net/docs/payments";
|
|
47
|
+
var PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
48
|
+
var SETTLEMENT_HEADERS = ["payment-response", "x-payment-response"];
|
|
49
|
+
function readSettlementHeader(headers) {
|
|
50
|
+
for (const name of SETTLEMENT_HEADERS) {
|
|
51
|
+
const value = headers.get(name);
|
|
52
|
+
if (value) return value;
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
57
|
+
|
|
58
|
+
// src/env.ts
|
|
59
|
+
var import_zod = require("zod");
|
|
60
|
+
var paywallEnvSchema = import_zod.z.object({
|
|
61
|
+
/** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */
|
|
62
|
+
FACILITATOR_URL: import_zod.z.string().url().default(DEFAULT_FACILITATOR_URL),
|
|
63
|
+
FACILITATOR_API_KEY: import_zod.z.string().min(1).optional(),
|
|
64
|
+
/**
|
|
65
|
+
* `1` takes every paywalled route offline with a 503. Intended for an incident where
|
|
66
|
+
* continuing to take irreversible payments would be worse than being down.
|
|
67
|
+
*/
|
|
68
|
+
KILLSWITCH: import_zod.z.enum(["0", "1"]).default("0"),
|
|
69
|
+
/**
|
|
70
|
+
* direct = agent pays the provider wallet, 0% platform fee (the launch build)
|
|
71
|
+
* splitter = reserved for the fee-splitting contract; not implemented
|
|
72
|
+
*/
|
|
73
|
+
FEE_MODE: import_zod.z.enum(["direct", "splitter"]).default("direct")
|
|
74
|
+
});
|
|
75
|
+
function readPaywallEnv(source = process.env) {
|
|
76
|
+
return paywallEnvSchema.parse({
|
|
77
|
+
FACILITATOR_URL: source.FACILITATOR_URL,
|
|
78
|
+
FACILITATOR_API_KEY: source.FACILITATOR_API_KEY,
|
|
79
|
+
KILLSWITCH: source.KILLSWITCH,
|
|
80
|
+
FEE_MODE: source.FEE_MODE
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/errors.ts
|
|
85
|
+
var NotImplementedError = class extends Error {
|
|
86
|
+
name = "NotImplementedError";
|
|
87
|
+
constructor(feature) {
|
|
88
|
+
super(`${feature} is not implemented in this build.`);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var MissingAdapterError = class extends Error {
|
|
92
|
+
name = "MissingAdapterError";
|
|
93
|
+
constructor(pkg) {
|
|
94
|
+
super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// src/fee-mode.ts
|
|
99
|
+
function resolvePayee(mode, providerWallet) {
|
|
100
|
+
switch (mode) {
|
|
101
|
+
case "direct":
|
|
102
|
+
return { payTo: providerWallet, feeBps: 0 };
|
|
103
|
+
case "splitter":
|
|
104
|
+
throw new NotImplementedError(
|
|
105
|
+
"FEE_MODE=splitter (no splitter contract ships in the launch build)"
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/money.ts
|
|
111
|
+
var UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);
|
|
112
|
+
function parseUsdc(input) {
|
|
113
|
+
const match = /^(\d+)(?:\.(\d{1,6}))?$/.exec(input.trim());
|
|
114
|
+
if (!match) {
|
|
115
|
+
throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);
|
|
116
|
+
}
|
|
117
|
+
const whole = BigInt(match[1] ?? "0");
|
|
118
|
+
const fraction = BigInt((match[2] ?? "").padEnd(USDC_DECIMALS, "0") || "0");
|
|
119
|
+
return whole * UNITS_PER_USDC + fraction;
|
|
120
|
+
}
|
|
121
|
+
function formatUsdc(atomic) {
|
|
122
|
+
if (atomic < 0n) throw new RangeError("USDC amounts are never negative");
|
|
123
|
+
const whole = atomic / UNITS_PER_USDC;
|
|
124
|
+
const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, "0");
|
|
125
|
+
const trimmed = fraction.replace(/0+$/, "");
|
|
126
|
+
return trimmed ? `${whole}.${trimmed}` : whole.toString();
|
|
127
|
+
}
|
|
128
|
+
var USDC_ADDRESSES = new Set(
|
|
129
|
+
Object.values(NETWORKS).map((network) => network.usdc.toLowerCase())
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
// src/provider.ts
|
|
133
|
+
var optionsSchema = import_zod2.z.object({
|
|
134
|
+
/** Price per call in USD, as a decimal string: "0.002". */
|
|
135
|
+
price: import_zod2.z.string().regex(/^\d+(?:\.\d{1,6})?$/, "price must be USD with at most 6 decimals"),
|
|
136
|
+
/** The provider's own wallet. Under FEE_MODE=direct this is the sole payee. */
|
|
137
|
+
wallet: import_zod2.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "wallet must be a 20-byte address"),
|
|
138
|
+
toolId: import_zod2.z.string().min(1).max(128),
|
|
139
|
+
network: import_zod2.z.enum(["base", "base-sepolia"]).default("base"),
|
|
140
|
+
description: import_zod2.z.string().optional(),
|
|
141
|
+
docsUrl: import_zod2.z.string().url().default(DOCS_URL),
|
|
142
|
+
mimeType: import_zod2.z.string().default("application/json"),
|
|
143
|
+
maxTimeoutSeconds: import_zod2.z.number().int().positive().default(60)
|
|
144
|
+
});
|
|
145
|
+
var KILLSWITCH_BODY = {
|
|
146
|
+
error: "service_unavailable",
|
|
147
|
+
message: "This tool is temporarily disabled by its operator (KILLSWITCH). No payment was taken. Try again later."
|
|
148
|
+
};
|
|
149
|
+
function paywall(options) {
|
|
150
|
+
const config = optionsSchema.parse(options);
|
|
151
|
+
const env = readPaywallEnv(options.env);
|
|
152
|
+
const network = NETWORKS[config.network];
|
|
153
|
+
const { payTo } = resolvePayee(env.FEE_MODE, config.wallet);
|
|
154
|
+
const amountAtomic = parseUsdc(config.price).toString();
|
|
155
|
+
const priceUsdc = formatUsdc(parseUsdc(config.price));
|
|
156
|
+
const unpaidBody = {
|
|
157
|
+
error: "payment_required",
|
|
158
|
+
tool: config.toolId,
|
|
159
|
+
price: {
|
|
160
|
+
usdc: priceUsdc,
|
|
161
|
+
amountAtomic,
|
|
162
|
+
asset: network.usdc,
|
|
163
|
+
network: network.caip2
|
|
164
|
+
},
|
|
165
|
+
payTo,
|
|
166
|
+
terms: { refundable: false, notice: NO_REFUNDS_NOTICE },
|
|
167
|
+
docs: config.docsUrl,
|
|
168
|
+
message: `This call costs ${priceUsdc} USDC on ${config.network}, paid directly to the provider. ${NO_REFUNDS_NOTICE} See ${config.docsUrl}`
|
|
169
|
+
};
|
|
170
|
+
const routeConfig = {
|
|
171
|
+
accepts: {
|
|
172
|
+
scheme: "exact",
|
|
173
|
+
network: network.caip2,
|
|
174
|
+
payTo,
|
|
175
|
+
// An explicit asset+amount pins USDC and the exact atomic amount, rather than
|
|
176
|
+
// leaving the quote to a price feed.
|
|
177
|
+
// A dollar price, not an explicit { asset, amount }: the EVM scheme resolves the
|
|
178
|
+
// network's default asset (USDC) and publishes its EIP-712 domain in `extra`, which
|
|
179
|
+
// the payer needs to sign the EIP-3009 authorisation. Naming the asset directly
|
|
180
|
+
// skips that lookup and emits `extra: {}`, which nobody can pay against.
|
|
181
|
+
price: `$${priceUsdc}`,
|
|
182
|
+
maxTimeoutSeconds: config.maxTimeoutSeconds
|
|
183
|
+
},
|
|
184
|
+
description: config.description ?? `Fatstack tool ${config.toolId}`,
|
|
185
|
+
mimeType: config.mimeType,
|
|
186
|
+
unpaidResponseBody: () => ({ contentType: "application/json", body: unpaidBody })
|
|
187
|
+
};
|
|
188
|
+
const facilitator = options.facilitator ?? new import_server.HTTPFacilitatorClient({
|
|
189
|
+
url: env.FACILITATOR_URL,
|
|
190
|
+
...env.FACILITATOR_API_KEY ? {
|
|
191
|
+
createAuthHeaders: async () => ({
|
|
192
|
+
verify: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
193
|
+
settle: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
194
|
+
supported: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` }
|
|
195
|
+
})
|
|
196
|
+
} : {}
|
|
197
|
+
});
|
|
198
|
+
const server = new import_server.x402ResourceServer(facilitator).register(network.caip2, new import_server2.ExactEvmScheme());
|
|
199
|
+
const killed = env.KILLSWITCH === "1";
|
|
200
|
+
function paymentRef(paymentResponseHeader) {
|
|
201
|
+
if (!paymentResponseHeader) return null;
|
|
202
|
+
try {
|
|
203
|
+
const settled = (0, import_http.decodePaymentResponseHeader)(paymentResponseHeader);
|
|
204
|
+
const transaction = settled.transaction;
|
|
205
|
+
return transaction ? `${config.toolId}:${network.caip2}:${transaction}` : null;
|
|
206
|
+
} catch {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
routeConfig,
|
|
212
|
+
payTo,
|
|
213
|
+
hono() {
|
|
214
|
+
let cached;
|
|
215
|
+
return async (c, next) => {
|
|
216
|
+
if (killed) return c.json(KILLSWITCH_BODY, 503);
|
|
217
|
+
if (!cached) {
|
|
218
|
+
const mod = await importOptional("@x402/hono");
|
|
219
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
220
|
+
}
|
|
221
|
+
const middleware = cached;
|
|
222
|
+
const result = await middleware(c, next);
|
|
223
|
+
const carrier = result instanceof Response ? result : c.res;
|
|
224
|
+
const ref = paymentRef(carrier ? readSettlementHeader(carrier.headers) : null);
|
|
225
|
+
if (ref) carrier.headers.set(PAYMENT_REF_HEADER, ref);
|
|
226
|
+
return result;
|
|
227
|
+
};
|
|
228
|
+
},
|
|
229
|
+
express() {
|
|
230
|
+
let cached;
|
|
231
|
+
return async (req, res, next) => {
|
|
232
|
+
const response = res;
|
|
233
|
+
if (killed) {
|
|
234
|
+
response.status(503).json(KILLSWITCH_BODY);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (!cached) {
|
|
238
|
+
const mod = await importOptional("@x402/express");
|
|
239
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
240
|
+
}
|
|
241
|
+
const originalSetHeader = response.setHeader.bind(response);
|
|
242
|
+
response.setHeader = (name, value) => {
|
|
243
|
+
const out = originalSetHeader(name, value);
|
|
244
|
+
if (SETTLEMENT_HEADERS.includes(String(name).toLowerCase())) {
|
|
245
|
+
const ref = paymentRef(String(value));
|
|
246
|
+
if (ref) originalSetHeader(PAYMENT_REF_HEADER, ref);
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
};
|
|
250
|
+
const middleware = cached;
|
|
251
|
+
await middleware(req, res, next);
|
|
252
|
+
};
|
|
253
|
+
},
|
|
254
|
+
next(handler) {
|
|
255
|
+
let cached;
|
|
256
|
+
return async (request) => {
|
|
257
|
+
if (killed) {
|
|
258
|
+
return Response.json(KILLSWITCH_BODY, { status: 503 });
|
|
259
|
+
}
|
|
260
|
+
if (!cached) {
|
|
261
|
+
const mod = await importOptional("@x402/next");
|
|
262
|
+
cached = mod.withX402(handler, routeConfig, server);
|
|
263
|
+
}
|
|
264
|
+
const wrapped = cached;
|
|
265
|
+
const result = await wrapped(request);
|
|
266
|
+
if (result instanceof Response) {
|
|
267
|
+
const ref = paymentRef(readSettlementHeader(result.headers));
|
|
268
|
+
if (ref) result.headers.set(PAYMENT_REF_HEADER, ref);
|
|
269
|
+
}
|
|
270
|
+
return result;
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
async function importOptional(specifier) {
|
|
276
|
+
try {
|
|
277
|
+
return await import(
|
|
278
|
+
/* @vite-ignore */
|
|
279
|
+
specifier
|
|
280
|
+
);
|
|
281
|
+
} catch {
|
|
282
|
+
throw new MissingAdapterError(specifier);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
286
|
+
0 && (module.exports = {
|
|
287
|
+
paywall
|
|
288
|
+
});
|
|
289
|
+
//# sourceMappingURL=provider.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts","../src/constants.ts","../src/env.ts","../src/errors.ts","../src/fee-mode.ts","../src/money.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","/** 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","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","/** 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 { 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","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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAA4C;AAC5C,oBAA0D;AAE1D,IAAAA,iBAA+B;AAC/B,IAAAC,cAAkB;;;ACKX,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;AAOtB,IAAM,oBACX;AAEK,IAAM,WAAW;AAGjB,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;AAEO,IAAM,0BAA0B;;;AC1DvC,iBAAkB;AAQX,IAAM,mBAAmB,aAAE,OAAO;AAAA;AAAA,EAEvC,iBAAiB,aAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,uBAAuB;AAAA,EACjE,qBAAqB,aAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA;AAAA;AAA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