@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/README.md
CHANGED
|
@@ -1,10 +1,118 @@
|
|
|
1
1
|
# @fatstack/x402
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
Pay-per-call tooling for AI agents. **USDC on Base**, over the
|
|
4
|
+
[x402](https://x402.org) protocol.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
marketplace where AI agents discover and pay for API and MCP tool calls in USDC via the
|
|
7
|
-
x402 protocol on Base.
|
|
6
|
+
Two entry points: a **paywall** for providers, and a **spend-guarded fetch** for agents.
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
Protocol work — signing, verification, settlement — is delegated to the official
|
|
9
|
+
`@x402/*` packages. This package adds the parts they leave to you: a provider-shaped
|
|
10
|
+
config, a human-readable 402 body, a killswitch, an indexing reference, and spend guards
|
|
11
|
+
that refuse a call _before_ anything is signed.
|
|
12
|
+
|
|
13
|
+
> **Payments are final. There are no refunds.** A payment is a direct on-chain transfer
|
|
14
|
+
> between two wallets. Once settled, nobody — including Fatstack — can reverse it.
|
|
15
|
+
|
|
16
|
+
> **Non-custodial.** Funds move from the agent's wallet to the provider's wallet.
|
|
17
|
+
> This package never holds funds and never sees a private key.
|
|
18
|
+
|
|
19
|
+
## Providers: paywall a route
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { paywall } from '@fatstack/x402/provider';
|
|
23
|
+
|
|
24
|
+
const pay = paywall({ price: '0.002', wallet: '0xYourWallet', toolId: 'sentiment' });
|
|
25
|
+
|
|
26
|
+
app.use('*', pay.hono()); // Hono
|
|
27
|
+
app.use(pay.express()); // Express
|
|
28
|
+
export const POST = pay.next(handler); // Next.js route handler
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
That is the whole integration. Unpaid requests get a 402 quoting `0.002` USDC payable to
|
|
32
|
+
**your** wallet, with the no-refunds notice and a docs link. Paid requests are verified and
|
|
33
|
+
settled through the hosted facilitator, then passed through with an
|
|
34
|
+
`X-Fatstack-Payment-Ref` header for indexing.
|
|
35
|
+
|
|
36
|
+
## Agents: pay for a call, under guards
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { payFetch } from '@fatstack/x402/client';
|
|
40
|
+
|
|
41
|
+
const res = await payFetch(
|
|
42
|
+
'https://sentiment.fatstack.net/run',
|
|
43
|
+
{ method: 'POST' },
|
|
44
|
+
{
|
|
45
|
+
wallet: account, // any viem account; we never see your key
|
|
46
|
+
guards: {
|
|
47
|
+
maxPerCall: 0.01,
|
|
48
|
+
maxPerHour: 1,
|
|
49
|
+
maxPerDay: 10, // USD
|
|
50
|
+
allowedHosts: ['fatstack.net'],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
);
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Exceeding any guard throws `SpendGuardError` **before a payment is signed**. Because
|
|
57
|
+
payments are irreversible, the guard is the last point at which a spend can be stopped —
|
|
58
|
+
so it runs on the quote, not after the fact.
|
|
59
|
+
|
|
60
|
+
## Guards
|
|
61
|
+
|
|
62
|
+
| Guard | Enforced |
|
|
63
|
+
| -------------- | ----------------------------------------------------------------- |
|
|
64
|
+
| `allowedHosts` | Before any network call. A subdomain of a listed host is allowed. |
|
|
65
|
+
| `maxPerCall` | On the quoted price, before signing. |
|
|
66
|
+
| `maxPerHour` | Rolling 60 minutes, quote + prior spend, before signing. |
|
|
67
|
+
| `maxPerDay` | Rolling 24 hours, quote + prior spend, before signing. |
|
|
68
|
+
|
|
69
|
+
Counters live in a `SpendStore`. The default is in-memory and **per process** — an agent
|
|
70
|
+
running as several processes enforces a separate budget in each. Pass your own store
|
|
71
|
+
(Redis, a Durable Object, Postgres) to share one budget:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { createMemorySpendStore, type SpendStore } from '@fatstack/x402';
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
A quote in an asset the package cannot price fails closed: it throws rather than guess
|
|
78
|
+
decimals, because guessing could let an unknown token slip past a cap.
|
|
79
|
+
|
|
80
|
+
## Environment
|
|
81
|
+
|
|
82
|
+
| Variable | Meaning |
|
|
83
|
+
| --------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
84
|
+
| `FACILITATOR_URL` | Hosted facilitator. Defaults to `https://x402.org/facilitator`. |
|
|
85
|
+
| `FACILITATOR_API_KEY` | Sent as a bearer token to the facilitator, if set. |
|
|
86
|
+
| `KILLSWITCH` | `1` takes every paywalled route offline with a 503, taking no payment. |
|
|
87
|
+
| `FEE_MODE` | `direct` (default) pays the provider wallet with a 0% fee. `splitter` throws — there is no splitter contract in this build. |
|
|
88
|
+
|
|
89
|
+
## Framework adapters
|
|
90
|
+
|
|
91
|
+
`@x402/hono`, `@x402/express` and `@x402/next` are **optional peer dependencies**, loaded
|
|
92
|
+
only when you call that adapter. Install the one you use:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
pnpm add @fatstack/x402 @x402/hono
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`pay.next()` requires `@x402/next`, which needs **Next.js ≥ 16.2.6** (upstream peer
|
|
99
|
+
requirement). The Hono and Express adapters have no such constraint.
|
|
100
|
+
|
|
101
|
+
## Testing your integration
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { createMockFacilitator } from '@fatstack/x402/testing';
|
|
105
|
+
|
|
106
|
+
const pay = paywall({ ...config, facilitator: createMockFacilitator() });
|
|
107
|
+
// or: createMockFacilitator({ invalidReason: 'insufficient_funds' })
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Nothing in the mock touches a chain or a network.
|
|
111
|
+
|
|
112
|
+
## Local development
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
pnpm --filter @fatstack/x402 build # tsup -> dist (ESM + CJS + d.ts)
|
|
116
|
+
pnpm --filter @fatstack/x402 test
|
|
117
|
+
pnpm --filter @fatstack/x402 typecheck
|
|
118
|
+
```
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// src/constants.ts
|
|
2
|
+
var NETWORKS = {
|
|
3
|
+
base: {
|
|
4
|
+
caip2: "eip155:8453",
|
|
5
|
+
chainId: 8453,
|
|
6
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
7
|
+
},
|
|
8
|
+
"base-sepolia": {
|
|
9
|
+
caip2: "eip155:84532",
|
|
10
|
+
chainId: 84532,
|
|
11
|
+
usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var USDC_DECIMALS = 6;
|
|
15
|
+
var NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.";
|
|
16
|
+
var DOCS_URL = "https://fatstack.net/docs/payments";
|
|
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
|
+
}
|
|
27
|
+
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
28
|
+
|
|
29
|
+
// src/errors.ts
|
|
30
|
+
var SpendGuardError = class extends Error {
|
|
31
|
+
constructor(guard, message, detail = {}) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.guard = guard;
|
|
34
|
+
this.detail = detail;
|
|
35
|
+
}
|
|
36
|
+
guard;
|
|
37
|
+
detail;
|
|
38
|
+
name = "SpendGuardError";
|
|
39
|
+
};
|
|
40
|
+
var NotImplementedError = class extends Error {
|
|
41
|
+
name = "NotImplementedError";
|
|
42
|
+
constructor(feature) {
|
|
43
|
+
super(`${feature} is not implemented in this build.`);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var MissingAdapterError = class extends Error {
|
|
47
|
+
name = "MissingAdapterError";
|
|
48
|
+
constructor(pkg) {
|
|
49
|
+
super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var UnreadableQuoteError = class extends Error {
|
|
53
|
+
name = "UnreadableQuoteError";
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// src/money.ts
|
|
60
|
+
var UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);
|
|
61
|
+
function parseUsdc(input) {
|
|
62
|
+
const match = /^(\d+)(?:\.(\d{1,6}))?$/.exec(input.trim());
|
|
63
|
+
if (!match) {
|
|
64
|
+
throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);
|
|
65
|
+
}
|
|
66
|
+
const whole = BigInt(match[1] ?? "0");
|
|
67
|
+
const fraction = BigInt((match[2] ?? "").padEnd(USDC_DECIMALS, "0") || "0");
|
|
68
|
+
return whole * UNITS_PER_USDC + fraction;
|
|
69
|
+
}
|
|
70
|
+
function formatUsdc(atomic) {
|
|
71
|
+
if (atomic < 0n) throw new RangeError("USDC amounts are never negative");
|
|
72
|
+
const whole = atomic / UNITS_PER_USDC;
|
|
73
|
+
const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, "0");
|
|
74
|
+
const trimmed = fraction.replace(/0+$/, "");
|
|
75
|
+
return trimmed ? `${whole}.${trimmed}` : whole.toString();
|
|
76
|
+
}
|
|
77
|
+
var USDC_ADDRESSES = new Set(
|
|
78
|
+
Object.values(NETWORKS).map((network) => network.usdc.toLowerCase())
|
|
79
|
+
);
|
|
80
|
+
function quoteToUsd(quote) {
|
|
81
|
+
const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;
|
|
82
|
+
if (decimals === void 0 || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {
|
|
83
|
+
throw new RangeError(
|
|
84
|
+
`Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (!/^\d+$/.test(quote.amountAtomic)) {
|
|
88
|
+
throw new RangeError(`Quoted amount is not an integer atomic value: ${quote.amountAtomic}`);
|
|
89
|
+
}
|
|
90
|
+
return Number(quote.amountAtomic) / 10 ** decimals;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export {
|
|
94
|
+
NETWORKS,
|
|
95
|
+
USDC_DECIMALS,
|
|
96
|
+
NO_REFUNDS_NOTICE,
|
|
97
|
+
DOCS_URL,
|
|
98
|
+
PAYMENT_REF_HEADER,
|
|
99
|
+
SETTLEMENT_HEADERS,
|
|
100
|
+
PAYMENT_SIGNATURE_HEADERS,
|
|
101
|
+
readSettlementHeader,
|
|
102
|
+
DEFAULT_FACILITATOR_URL,
|
|
103
|
+
SpendGuardError,
|
|
104
|
+
NotImplementedError,
|
|
105
|
+
MissingAdapterError,
|
|
106
|
+
UnreadableQuoteError,
|
|
107
|
+
parseUsdc,
|
|
108
|
+
formatUsdc,
|
|
109
|
+
quoteToUsd
|
|
110
|
+
};
|
|
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;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;AACpE,IAAM,4BAA4B,CAAC,qBAAqB,WAAW;AAGnE,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;;;AChDhC,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;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC3B,OAAO;AAAA,EAEzB,YAAY,SAAiB;AAC3B,UAAM,GAAG,OAAO,oCAAoC;AAAA,EACtD;AACF;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC3B,OAAO;AAAA,EAEzB,YAAY,KAAa;AACvB,UAAM,GAAG,GAAG,2DAA2D,GAAG,EAAE;AAAA,EAC9E;AACF;AAOO,IAAM,uBAAN,cAAmC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AO,MAAM,YAAY,IAAI,MAAM;AAC5C;","names":[]}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_FACILITATOR_URL,
|
|
3
|
+
DOCS_URL,
|
|
4
|
+
MissingAdapterError,
|
|
5
|
+
NETWORKS,
|
|
6
|
+
NO_REFUNDS_NOTICE,
|
|
7
|
+
NotImplementedError,
|
|
8
|
+
PAYMENT_REF_HEADER,
|
|
9
|
+
SETTLEMENT_HEADERS,
|
|
10
|
+
formatUsdc,
|
|
11
|
+
parseUsdc,
|
|
12
|
+
readSettlementHeader
|
|
13
|
+
} from "./chunk-C4BASAUA.js";
|
|
14
|
+
|
|
15
|
+
// src/provider.ts
|
|
16
|
+
import { decodePaymentResponseHeader } from "@x402/core/http";
|
|
17
|
+
import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server";
|
|
18
|
+
import { ExactEvmScheme } from "@x402/evm/exact/server";
|
|
19
|
+
import { z as z2 } from "zod";
|
|
20
|
+
|
|
21
|
+
// src/env.ts
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
var paywallEnvSchema = z.object({
|
|
24
|
+
/** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */
|
|
25
|
+
FACILITATOR_URL: z.string().url().default(DEFAULT_FACILITATOR_URL),
|
|
26
|
+
FACILITATOR_API_KEY: z.string().min(1).optional(),
|
|
27
|
+
/**
|
|
28
|
+
* `1` takes every paywalled route offline with a 503. Intended for an incident where
|
|
29
|
+
* continuing to take irreversible payments would be worse than being down.
|
|
30
|
+
*/
|
|
31
|
+
KILLSWITCH: z.enum(["0", "1"]).default("0"),
|
|
32
|
+
/**
|
|
33
|
+
* direct = agent pays the provider wallet, 0% platform fee (the launch build)
|
|
34
|
+
* splitter = reserved for the fee-splitting contract; not implemented
|
|
35
|
+
*/
|
|
36
|
+
FEE_MODE: z.enum(["direct", "splitter"]).default("direct")
|
|
37
|
+
});
|
|
38
|
+
function readPaywallEnv(source = process.env) {
|
|
39
|
+
return paywallEnvSchema.parse({
|
|
40
|
+
FACILITATOR_URL: source.FACILITATOR_URL,
|
|
41
|
+
FACILITATOR_API_KEY: source.FACILITATOR_API_KEY,
|
|
42
|
+
KILLSWITCH: source.KILLSWITCH,
|
|
43
|
+
FEE_MODE: source.FEE_MODE
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/fee-mode.ts
|
|
48
|
+
function resolvePayee(mode, providerWallet) {
|
|
49
|
+
switch (mode) {
|
|
50
|
+
case "direct":
|
|
51
|
+
return { payTo: providerWallet, feeBps: 0 };
|
|
52
|
+
case "splitter":
|
|
53
|
+
throw new NotImplementedError(
|
|
54
|
+
"FEE_MODE=splitter (no splitter contract ships in the launch build)"
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/provider.ts
|
|
60
|
+
var optionsSchema = z2.object({
|
|
61
|
+
/** Price per call in USD, as a decimal string: "0.002". */
|
|
62
|
+
price: z2.string().regex(/^\d+(?:\.\d{1,6})?$/, "price must be USD with at most 6 decimals"),
|
|
63
|
+
/** The provider's own wallet. Under FEE_MODE=direct this is the sole payee. */
|
|
64
|
+
wallet: z2.string().regex(/^0x[0-9a-fA-F]{40}$/, "wallet must be a 20-byte address"),
|
|
65
|
+
toolId: z2.string().min(1).max(128),
|
|
66
|
+
network: z2.enum(["base", "base-sepolia"]).default("base"),
|
|
67
|
+
description: z2.string().optional(),
|
|
68
|
+
docsUrl: z2.string().url().default(DOCS_URL),
|
|
69
|
+
mimeType: z2.string().default("application/json"),
|
|
70
|
+
maxTimeoutSeconds: z2.number().int().positive().default(60)
|
|
71
|
+
});
|
|
72
|
+
var KILLSWITCH_BODY = {
|
|
73
|
+
error: "service_unavailable",
|
|
74
|
+
message: "This tool is temporarily disabled by its operator (KILLSWITCH). No payment was taken. Try again later."
|
|
75
|
+
};
|
|
76
|
+
function paywall(options) {
|
|
77
|
+
const config = optionsSchema.parse(options);
|
|
78
|
+
const env = readPaywallEnv(options.env);
|
|
79
|
+
const network = NETWORKS[config.network];
|
|
80
|
+
const { payTo } = resolvePayee(env.FEE_MODE, config.wallet);
|
|
81
|
+
const amountAtomic = parseUsdc(config.price).toString();
|
|
82
|
+
const priceUsdc = formatUsdc(parseUsdc(config.price));
|
|
83
|
+
const unpaidBody = {
|
|
84
|
+
error: "payment_required",
|
|
85
|
+
tool: config.toolId,
|
|
86
|
+
price: {
|
|
87
|
+
usdc: priceUsdc,
|
|
88
|
+
amountAtomic,
|
|
89
|
+
asset: network.usdc,
|
|
90
|
+
network: network.caip2
|
|
91
|
+
},
|
|
92
|
+
payTo,
|
|
93
|
+
terms: { refundable: false, notice: NO_REFUNDS_NOTICE },
|
|
94
|
+
docs: config.docsUrl,
|
|
95
|
+
message: `This call costs ${priceUsdc} USDC on ${config.network}, paid directly to the provider. ${NO_REFUNDS_NOTICE} See ${config.docsUrl}`
|
|
96
|
+
};
|
|
97
|
+
const routeConfig = {
|
|
98
|
+
accepts: {
|
|
99
|
+
scheme: "exact",
|
|
100
|
+
network: network.caip2,
|
|
101
|
+
payTo,
|
|
102
|
+
// An explicit asset+amount pins USDC and the exact atomic amount, rather than
|
|
103
|
+
// leaving the quote to a price feed.
|
|
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}`,
|
|
109
|
+
maxTimeoutSeconds: config.maxTimeoutSeconds
|
|
110
|
+
},
|
|
111
|
+
description: config.description ?? `Fatstack tool ${config.toolId}`,
|
|
112
|
+
mimeType: config.mimeType,
|
|
113
|
+
unpaidResponseBody: () => ({ contentType: "application/json", body: unpaidBody })
|
|
114
|
+
};
|
|
115
|
+
const facilitator = options.facilitator ?? new HTTPFacilitatorClient({
|
|
116
|
+
url: env.FACILITATOR_URL,
|
|
117
|
+
...env.FACILITATOR_API_KEY ? {
|
|
118
|
+
createAuthHeaders: async () => ({
|
|
119
|
+
verify: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
120
|
+
settle: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
121
|
+
supported: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` }
|
|
122
|
+
})
|
|
123
|
+
} : {}
|
|
124
|
+
});
|
|
125
|
+
const server = new x402ResourceServer(facilitator).register(network.caip2, new ExactEvmScheme());
|
|
126
|
+
const killed = env.KILLSWITCH === "1";
|
|
127
|
+
function paymentRef(paymentResponseHeader) {
|
|
128
|
+
if (!paymentResponseHeader) return null;
|
|
129
|
+
try {
|
|
130
|
+
const settled = decodePaymentResponseHeader(paymentResponseHeader);
|
|
131
|
+
const transaction = settled.transaction;
|
|
132
|
+
return transaction ? `${config.toolId}:${network.caip2}:${transaction}` : null;
|
|
133
|
+
} catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
routeConfig,
|
|
139
|
+
payTo,
|
|
140
|
+
hono() {
|
|
141
|
+
let cached;
|
|
142
|
+
return async (c, next) => {
|
|
143
|
+
if (killed) return c.json(KILLSWITCH_BODY, 503);
|
|
144
|
+
if (!cached) {
|
|
145
|
+
const mod = await importOptional("@x402/hono");
|
|
146
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
147
|
+
}
|
|
148
|
+
const middleware = cached;
|
|
149
|
+
const result = await middleware(c, next);
|
|
150
|
+
const carrier = result instanceof Response ? result : c.res;
|
|
151
|
+
const ref = paymentRef(carrier ? readSettlementHeader(carrier.headers) : null);
|
|
152
|
+
if (ref) carrier.headers.set(PAYMENT_REF_HEADER, ref);
|
|
153
|
+
return result;
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
express() {
|
|
157
|
+
let cached;
|
|
158
|
+
return async (req, res, next) => {
|
|
159
|
+
const response = res;
|
|
160
|
+
if (killed) {
|
|
161
|
+
response.status(503).json(KILLSWITCH_BODY);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (!cached) {
|
|
165
|
+
const mod = await importOptional("@x402/express");
|
|
166
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
167
|
+
}
|
|
168
|
+
const originalSetHeader = response.setHeader.bind(response);
|
|
169
|
+
response.setHeader = (name, value) => {
|
|
170
|
+
const out = originalSetHeader(name, value);
|
|
171
|
+
if (SETTLEMENT_HEADERS.includes(String(name).toLowerCase())) {
|
|
172
|
+
const ref = paymentRef(String(value));
|
|
173
|
+
if (ref) originalSetHeader(PAYMENT_REF_HEADER, ref);
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
};
|
|
177
|
+
const middleware = cached;
|
|
178
|
+
await middleware(req, res, next);
|
|
179
|
+
};
|
|
180
|
+
},
|
|
181
|
+
next(handler) {
|
|
182
|
+
let cached;
|
|
183
|
+
return async (request) => {
|
|
184
|
+
if (killed) {
|
|
185
|
+
return Response.json(KILLSWITCH_BODY, { status: 503 });
|
|
186
|
+
}
|
|
187
|
+
if (!cached) {
|
|
188
|
+
const mod = await importOptional("@x402/next");
|
|
189
|
+
cached = mod.withX402(handler, routeConfig, server);
|
|
190
|
+
}
|
|
191
|
+
const wrapped = cached;
|
|
192
|
+
const result = await wrapped(request);
|
|
193
|
+
if (result instanceof Response) {
|
|
194
|
+
const ref = paymentRef(readSettlementHeader(result.headers));
|
|
195
|
+
if (ref) result.headers.set(PAYMENT_REF_HEADER, ref);
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
async function importOptional(specifier) {
|
|
203
|
+
try {
|
|
204
|
+
return await import(
|
|
205
|
+
/* @vite-ignore */
|
|
206
|
+
specifier
|
|
207
|
+
);
|
|
208
|
+
} catch {
|
|
209
|
+
throw new MissingAdapterError(specifier);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export {
|
|
214
|
+
resolvePayee,
|
|
215
|
+
paywallEnvSchema,
|
|
216
|
+
readPaywallEnv,
|
|
217
|
+
paywall
|
|
218
|
+
};
|
|
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,SAA6C,QAAQ,KACzC;AACZ,SAAO,iBAAiB,MAAM;AAAA,IAC5B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AkB,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"]}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import {
|
|
2
|
+
NETWORKS,
|
|
3
|
+
SpendGuardError,
|
|
4
|
+
UnreadableQuoteError,
|
|
5
|
+
quoteToUsd,
|
|
6
|
+
readSettlementHeader
|
|
7
|
+
} from "./chunk-C4BASAUA.js";
|
|
8
|
+
|
|
9
|
+
// src/client.ts
|
|
10
|
+
import { x402Client } from "@x402/core/client";
|
|
11
|
+
import { decodePaymentRequiredHeader } from "@x402/core/http";
|
|
12
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
13
|
+
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
14
|
+
|
|
15
|
+
// src/store.ts
|
|
16
|
+
function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1e3) {
|
|
17
|
+
let entries = [];
|
|
18
|
+
return {
|
|
19
|
+
record(entry) {
|
|
20
|
+
entries.push(entry);
|
|
21
|
+
const cutoff = entry.at - retentionMs;
|
|
22
|
+
if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);
|
|
23
|
+
},
|
|
24
|
+
totalSince(sinceMs) {
|
|
25
|
+
let total = 0;
|
|
26
|
+
for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;
|
|
27
|
+
return total;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/client.ts
|
|
33
|
+
var HOUR_MS = 60 * 60 * 1e3;
|
|
34
|
+
var DAY_MS = 24 * HOUR_MS;
|
|
35
|
+
function hostOf(input) {
|
|
36
|
+
try {
|
|
37
|
+
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
38
|
+
return new URL(raw).hostname.toLowerCase();
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function hostAllowed(host, allowed) {
|
|
44
|
+
return allowed.some((entry) => {
|
|
45
|
+
const candidate = entry.trim().toLowerCase().replace(/^\*\./, "");
|
|
46
|
+
return host === candidate || host.endsWith(`.${candidate}`);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function evaluateGuards(quoteUsd, guards, store, now) {
|
|
50
|
+
if (guards.maxPerCall !== void 0 && quoteUsd > guards.maxPerCall) {
|
|
51
|
+
throw new SpendGuardError(
|
|
52
|
+
"maxPerCall",
|
|
53
|
+
`Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,
|
|
54
|
+
{ limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd }
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (guards.maxPerHour !== void 0) {
|
|
58
|
+
const spent = await store.totalSince(now - HOUR_MS);
|
|
59
|
+
if (spent + quoteUsd > guards.maxPerHour) {
|
|
60
|
+
throw new SpendGuardError(
|
|
61
|
+
"maxPerHour",
|
|
62
|
+
`Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,
|
|
63
|
+
{ limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd }
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (guards.maxPerDay !== void 0) {
|
|
68
|
+
const spent = await store.totalSince(now - DAY_MS);
|
|
69
|
+
if (spent + quoteUsd > guards.maxPerDay) {
|
|
70
|
+
throw new SpendGuardError(
|
|
71
|
+
"maxPerDay",
|
|
72
|
+
`Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,
|
|
73
|
+
{ limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd }
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
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
|
+
}
|
|
91
|
+
function quoteUsdOf(requirements) {
|
|
92
|
+
const asRecord = requirements;
|
|
93
|
+
const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;
|
|
94
|
+
if (!amountAtomic || !asRecord.asset) {
|
|
95
|
+
throw new RangeError("Payment requirements carry no priceable amount; refusing to pay.");
|
|
96
|
+
}
|
|
97
|
+
return quoteToUsd({
|
|
98
|
+
amountAtomic,
|
|
99
|
+
asset: asRecord.asset,
|
|
100
|
+
decimals: asRecord.extra?.decimals
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async function payFetch(url, init, options) {
|
|
104
|
+
const guards = options.guards ?? {};
|
|
105
|
+
const store = options.store ?? createMemorySpendStore();
|
|
106
|
+
const now = options.now ?? Date.now;
|
|
107
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
108
|
+
const networks = options.networks ?? ["base"];
|
|
109
|
+
if (guards.allowedHosts) {
|
|
110
|
+
const host = hostOf(url);
|
|
111
|
+
if (!host || !hostAllowed(host, guards.allowedHosts)) {
|
|
112
|
+
throw new SpendGuardError(
|
|
113
|
+
"allowedHosts",
|
|
114
|
+
`Host ${host ?? "<unparseable>"} is not in allowedHosts`,
|
|
115
|
+
{ host: host ?? void 0 }
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
let quotedUsd = null;
|
|
120
|
+
const client = new x402Client((_version, requirements) => {
|
|
121
|
+
const affordable = requirements.filter((requirement) => {
|
|
122
|
+
const usd = quoteUsdOf(requirement);
|
|
123
|
+
return guards.maxPerCall === void 0 || usd <= guards.maxPerCall;
|
|
124
|
+
});
|
|
125
|
+
const chosen = (affordable.length > 0 ? affordable : requirements)[0];
|
|
126
|
+
if (!chosen) throw new RangeError("Resource offered no payment requirements");
|
|
127
|
+
quotedUsd = quoteUsdOf(chosen);
|
|
128
|
+
return chosen;
|
|
129
|
+
});
|
|
130
|
+
for (const name of networks) {
|
|
131
|
+
client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));
|
|
132
|
+
}
|
|
133
|
+
const guarded = async (input, requestInit) => {
|
|
134
|
+
const response2 = await baseFetch(input, requestInit);
|
|
135
|
+
if (response2.status !== 402) return response2;
|
|
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());
|
|
145
|
+
}
|
|
146
|
+
return response2;
|
|
147
|
+
};
|
|
148
|
+
const paying = wrapFetchWithPayment(guarded, client);
|
|
149
|
+
const response = await paying(url, init);
|
|
150
|
+
if (readSettlementHeader(response.headers) && quotedUsd !== null) {
|
|
151
|
+
await store.record({ at: now(), usd: quotedUsd });
|
|
152
|
+
}
|
|
153
|
+
return response;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export {
|
|
157
|
+
createMemorySpendStore,
|
|
158
|
+
evaluateGuards,
|
|
159
|
+
readQuotedRequirements,
|
|
160
|
+
quoteUsdOf,
|
|
161
|
+
payFetch
|
|
162
|
+
};
|
|
163
|
+
//# sourceMappingURL=chunk-ZGVPNFNS.js.map
|