@fatstack/x402 0.0.1 → 0.1.0
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-6LSPHKJ7.js +88 -0
- package/dist/chunk-6LSPHKJ7.js.map +1 -0
- package/dist/chunk-7DVR574O.js +213 -0
- package/dist/chunk-7DVR574O.js.map +1 -0
- package/dist/chunk-HCN75CTX.js +144 -0
- package/dist/chunk-HCN75CTX.js.map +1 -0
- package/dist/client-C8_arVa4.d.cts +86 -0
- package/dist/client-C8_arVa4.d.ts +86 -0
- package/dist/client.cjs +207 -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 +15 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +464 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +107 -0
- package/dist/index.d.ts +107 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/provider.cjs +273 -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,88 @@
|
|
|
1
|
+
// src/constants.ts
|
|
2
|
+
var NETWORKS = {
|
|
3
|
+
base: { caip2: "eip155:8453", chainId: 8453, usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" },
|
|
4
|
+
"base-sepolia": {
|
|
5
|
+
caip2: "eip155:84532",
|
|
6
|
+
chainId: 84532,
|
|
7
|
+
usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var USDC_DECIMALS = 6;
|
|
11
|
+
var NO_REFUNDS_NOTICE = "Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.";
|
|
12
|
+
var DOCS_URL = "https://fatstack.net/docs/payments";
|
|
13
|
+
var PAYMENT_REF_HEADER = "X-Fatstack-Payment-Ref";
|
|
14
|
+
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
15
|
+
|
|
16
|
+
// src/errors.ts
|
|
17
|
+
var SpendGuardError = class extends Error {
|
|
18
|
+
constructor(guard, message, detail = {}) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.guard = guard;
|
|
21
|
+
this.detail = detail;
|
|
22
|
+
}
|
|
23
|
+
guard;
|
|
24
|
+
detail;
|
|
25
|
+
name = "SpendGuardError";
|
|
26
|
+
};
|
|
27
|
+
var NotImplementedError = class extends Error {
|
|
28
|
+
name = "NotImplementedError";
|
|
29
|
+
constructor(feature) {
|
|
30
|
+
super(`${feature} is not implemented in this build.`);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var MissingAdapterError = class extends Error {
|
|
34
|
+
name = "MissingAdapterError";
|
|
35
|
+
constructor(pkg) {
|
|
36
|
+
super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// src/money.ts
|
|
41
|
+
var UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);
|
|
42
|
+
function parseUsdc(input) {
|
|
43
|
+
const match = /^(\d+)(?:\.(\d{1,6}))?$/.exec(input.trim());
|
|
44
|
+
if (!match) {
|
|
45
|
+
throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);
|
|
46
|
+
}
|
|
47
|
+
const whole = BigInt(match[1] ?? "0");
|
|
48
|
+
const fraction = BigInt((match[2] ?? "").padEnd(USDC_DECIMALS, "0") || "0");
|
|
49
|
+
return whole * UNITS_PER_USDC + fraction;
|
|
50
|
+
}
|
|
51
|
+
function formatUsdc(atomic) {
|
|
52
|
+
if (atomic < 0n) throw new RangeError("USDC amounts are never negative");
|
|
53
|
+
const whole = atomic / UNITS_PER_USDC;
|
|
54
|
+
const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, "0");
|
|
55
|
+
const trimmed = fraction.replace(/0+$/, "");
|
|
56
|
+
return trimmed ? `${whole}.${trimmed}` : whole.toString();
|
|
57
|
+
}
|
|
58
|
+
var USDC_ADDRESSES = new Set(
|
|
59
|
+
Object.values(NETWORKS).map((network) => network.usdc.toLowerCase())
|
|
60
|
+
);
|
|
61
|
+
function quoteToUsd(quote) {
|
|
62
|
+
const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;
|
|
63
|
+
if (decimals === void 0 || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {
|
|
64
|
+
throw new RangeError(
|
|
65
|
+
`Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
if (!/^\d+$/.test(quote.amountAtomic)) {
|
|
69
|
+
throw new RangeError(`Quoted amount is not an integer atomic value: ${quote.amountAtomic}`);
|
|
70
|
+
}
|
|
71
|
+
return Number(quote.amountAtomic) / 10 ** decimals;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export {
|
|
75
|
+
NETWORKS,
|
|
76
|
+
USDC_DECIMALS,
|
|
77
|
+
NO_REFUNDS_NOTICE,
|
|
78
|
+
DOCS_URL,
|
|
79
|
+
PAYMENT_REF_HEADER,
|
|
80
|
+
DEFAULT_FACILITATOR_URL,
|
|
81
|
+
SpendGuardError,
|
|
82
|
+
NotImplementedError,
|
|
83
|
+
MissingAdapterError,
|
|
84
|
+
parseUsdc,
|
|
85
|
+
formatUsdc,
|
|
86
|
+
quoteToUsd
|
|
87
|
+
};
|
|
88
|
+
//# sourceMappingURL=chunk-6LSPHKJ7.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. */\nexport const NETWORKS = {\n base: { caip2: 'eip155:8453', chainId: 8453, usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' },\n 'base-sepolia': {\n caip2: 'eip155:84532',\n chainId: 84532,\n usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n} as const;\n\nexport type NetworkName = keyof typeof NETWORKS;\n\n/** USDC is 6 decimals on Base. */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Required on every 402 body and every payment-facing doc page. A payment is a direct\n * on-chain transfer between two wallets: once settled nobody, Fatstack included, can\n * reverse it.\n */\nexport const NO_REFUNDS_NOTICE =\n 'Payments are final. Once settled on-chain the transfer cannot be reversed, and there are no refunds.';\n\nexport const DOCS_URL = 'https://fatstack.net/docs/payments';\n\n/** Correlates a settled payment with the indexer's view of the on-chain transfer. */\nexport const PAYMENT_REF_HEADER = 'X-Fatstack-Payment-Ref';\n\nexport const DEFAULT_FACILITATOR_URL = 'https://x402.org/facilitator';\n","/** Names of the spend guards an agent can set. */\nexport type GuardName = 'maxPerCall' | 'maxPerHour' | 'maxPerDay' | 'allowedHosts';\n\n/**\n * Thrown before anything is signed when a call would breach a spend guard.\n *\n * Payments are final, so the only place to stop an unwanted spend is before the\n * signature exists. Every guard raises this, and it is never thrown after a payment\n * payload has been created.\n */\nexport class SpendGuardError extends Error {\n override readonly name = 'SpendGuardError';\n\n constructor(\n readonly guard: GuardName,\n message: string,\n readonly detail: { limitUsd?: number; attemptedUsd?: number; host?: string } = {},\n ) {\n super(message);\n }\n}\n\n/** Thrown by seams that are typed and reachable but deliberately not built yet. */\nexport class NotImplementedError extends Error {\n override readonly name = 'NotImplementedError';\n\n constructor(feature: string) {\n super(`${feature} is not implemented in this build.`);\n }\n}\n\n/** Thrown when an optional framework adapter is used without its package installed. */\nexport class MissingAdapterError extends Error {\n override readonly name = 'MissingAdapterError';\n\n constructor(pkg: string) {\n super(`${pkg} is not installed. Add it to use this adapter: pnpm add ${pkg}`);\n }\n}\n","import { NETWORKS, USDC_DECIMALS } from './constants.js';\n\nconst UNITS_PER_USDC = 10n ** BigInt(USDC_DECIMALS);\n\n/** \"1.25\" -> 1250000n. Rejects anything that is not a plain non-negative decimal. */\nexport function parseUsdc(input: string): bigint {\n const match = /^(\\d+)(?:\\.(\\d{1,6}))?$/.exec(input.trim());\n if (!match) {\n throw new RangeError(`Not a USDC amount with at most ${USDC_DECIMALS} decimals: ${input}`);\n }\n const whole = BigInt(match[1] ?? '0');\n const fraction = BigInt((match[2] ?? '').padEnd(USDC_DECIMALS, '0') || '0');\n return whole * UNITS_PER_USDC + fraction;\n}\n\n/** 1250000n -> \"1.25\". Trailing zeros trimmed. */\nexport function formatUsdc(atomic: bigint): string {\n if (atomic < 0n) throw new RangeError('USDC amounts are never negative');\n const whole = atomic / UNITS_PER_USDC;\n const fraction = (atomic % UNITS_PER_USDC).toString().padStart(USDC_DECIMALS, '0');\n const trimmed = fraction.replace(/0+$/, '');\n return trimmed ? `${whole}.${trimmed}` : whole.toString();\n}\n\nconst USDC_ADDRESSES = new Set(\n Object.values(NETWORKS).map((network) => network.usdc.toLowerCase()),\n);\n\n/**\n * Converts a quoted amount to USD for guard evaluation.\n *\n * Fails closed: if the asset is not a USDC contract we recognise and the quote carries no\n * usable `decimals`, this throws rather than guessing. Guessing here would let an\n * unrecognised token slip past a spend cap, and the payment is irreversible.\n */\nexport function quoteToUsd(quote: {\n amountAtomic: string;\n asset: string;\n decimals?: number | undefined;\n}): number {\n const decimals = USDC_ADDRESSES.has(quote.asset.toLowerCase()) ? USDC_DECIMALS : quote.decimals;\n\n if (decimals === undefined || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n throw new RangeError(\n `Cannot price asset ${quote.asset}: unknown decimals. Refusing to evaluate spend guards against an unpriceable quote.`,\n );\n }\n\n if (!/^\\d+$/.test(quote.amountAtomic)) {\n throw new RangeError(`Qu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WAAW,iCAAiC;AACvE,QAAM,QAAQ,SAAS;AACvB,QAAM,YAAY,SAAS,gBAAgB,SAAS,EAAE,SAAS,eAAe,GAAG;AACjF,QAAM,UAAU,SAAS,QAAQ,OAAO,EAAE;AAC1C,SAAO,UAAU,GAAG,KAAK,IAAI,OAAO,KAAK,MAAM,SAAS;AAC1D;AAEA,IAAM,iBAAiB,IAAI;AAAA,EACzB,OAAO,OAAO,QAAQ,EAAE,IAAI,CAAC,YAAY,QAAQ,KAAK,YAAY,CAAC;AACrE;AASO,SAAS,WAAW,OAIhB;AACT,QAAM,WAAW,eAAe,IAAI,MAAM,MAAM,YAAY,CAAC,IAAI,gBAAgB,MAAM;AAEvF,MAAI,aAAa,UAAa,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,KAAK,WAAW,IAAI;AAC1F,UAAM,IAAI;AAAA,MACR,sBAAsB,MAAM,KAAK;AAAA,IACnC;AAAA,EACF;AAEA,MAAI,CAAC,QAAQ,KAAK,MAAM,YAAY,GAAG;AACrC,UAAM,IAAI,WAAW,iDAAiD,MAAM,YAAY,EAAE;AAAA,EAC5F;AAEA,SAAO,OAAO,MAAM,YAAY,IAAI,MAAM;AAC5C;","names":[]}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_FACILITATOR_URL,
|
|
3
|
+
DOCS_URL,
|
|
4
|
+
MissingAdapterError,
|
|
5
|
+
NETWORKS,
|
|
6
|
+
NO_REFUNDS_NOTICE,
|
|
7
|
+
NotImplementedError,
|
|
8
|
+
PAYMENT_REF_HEADER,
|
|
9
|
+
formatUsdc,
|
|
10
|
+
parseUsdc
|
|
11
|
+
} from "./chunk-6LSPHKJ7.js";
|
|
12
|
+
|
|
13
|
+
// src/provider.ts
|
|
14
|
+
import { decodePaymentResponseHeader } from "@x402/core/http";
|
|
15
|
+
import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server";
|
|
16
|
+
import { ExactEvmScheme } from "@x402/evm/exact/server";
|
|
17
|
+
import { z as z2 } from "zod";
|
|
18
|
+
|
|
19
|
+
// src/env.ts
|
|
20
|
+
import { z } from "zod";
|
|
21
|
+
var paywallEnvSchema = z.object({
|
|
22
|
+
/** Hosted facilitator (Coinbase CDP). Fatstack does not run its own. */
|
|
23
|
+
FACILITATOR_URL: z.string().url().default(DEFAULT_FACILITATOR_URL),
|
|
24
|
+
FACILITATOR_API_KEY: z.string().min(1).optional(),
|
|
25
|
+
/**
|
|
26
|
+
* `1` takes every paywalled route offline with a 503. Intended for an incident where
|
|
27
|
+
* continuing to take irreversible payments would be worse than being down.
|
|
28
|
+
*/
|
|
29
|
+
KILLSWITCH: z.enum(["0", "1"]).default("0"),
|
|
30
|
+
/**
|
|
31
|
+
* direct = agent pays the provider wallet, 0% platform fee (the launch build)
|
|
32
|
+
* splitter = reserved for the fee-splitting contract; not implemented
|
|
33
|
+
*/
|
|
34
|
+
FEE_MODE: z.enum(["direct", "splitter"]).default("direct")
|
|
35
|
+
});
|
|
36
|
+
function readPaywallEnv(source = process.env) {
|
|
37
|
+
return paywallEnvSchema.parse({
|
|
38
|
+
FACILITATOR_URL: source.FACILITATOR_URL,
|
|
39
|
+
FACILITATOR_API_KEY: source.FACILITATOR_API_KEY,
|
|
40
|
+
KILLSWITCH: source.KILLSWITCH,
|
|
41
|
+
FEE_MODE: source.FEE_MODE
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/fee-mode.ts
|
|
46
|
+
function resolvePayee(mode, providerWallet) {
|
|
47
|
+
switch (mode) {
|
|
48
|
+
case "direct":
|
|
49
|
+
return { payTo: providerWallet, feeBps: 0 };
|
|
50
|
+
case "splitter":
|
|
51
|
+
throw new NotImplementedError(
|
|
52
|
+
"FEE_MODE=splitter (no splitter contract ships in the launch build)"
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/provider.ts
|
|
58
|
+
var optionsSchema = z2.object({
|
|
59
|
+
/** Price per call in USD, as a decimal string: "0.002". */
|
|
60
|
+
price: z2.string().regex(/^\d+(?:\.\d{1,6})?$/, "price must be USD with at most 6 decimals"),
|
|
61
|
+
/** The provider's own wallet. Under FEE_MODE=direct this is the sole payee. */
|
|
62
|
+
wallet: z2.string().regex(/^0x[0-9a-fA-F]{40}$/, "wallet must be a 20-byte address"),
|
|
63
|
+
toolId: z2.string().min(1).max(128),
|
|
64
|
+
network: z2.enum(["base", "base-sepolia"]).default("base"),
|
|
65
|
+
description: z2.string().optional(),
|
|
66
|
+
docsUrl: z2.string().url().default(DOCS_URL),
|
|
67
|
+
mimeType: z2.string().default("application/json"),
|
|
68
|
+
maxTimeoutSeconds: z2.number().int().positive().default(60)
|
|
69
|
+
});
|
|
70
|
+
var KILLSWITCH_BODY = {
|
|
71
|
+
error: "service_unavailable",
|
|
72
|
+
message: "This tool is temporarily disabled by its operator (KILLSWITCH). No payment was taken. Try again later."
|
|
73
|
+
};
|
|
74
|
+
function paywall(options) {
|
|
75
|
+
const config = optionsSchema.parse(options);
|
|
76
|
+
const env = readPaywallEnv(options.env);
|
|
77
|
+
const network = NETWORKS[config.network];
|
|
78
|
+
const { payTo } = resolvePayee(env.FEE_MODE, config.wallet);
|
|
79
|
+
const amountAtomic = parseUsdc(config.price).toString();
|
|
80
|
+
const priceUsdc = formatUsdc(parseUsdc(config.price));
|
|
81
|
+
const unpaidBody = {
|
|
82
|
+
error: "payment_required",
|
|
83
|
+
tool: config.toolId,
|
|
84
|
+
price: {
|
|
85
|
+
usdc: priceUsdc,
|
|
86
|
+
amountAtomic,
|
|
87
|
+
asset: network.usdc,
|
|
88
|
+
network: network.caip2
|
|
89
|
+
},
|
|
90
|
+
payTo,
|
|
91
|
+
terms: { refundable: false, notice: NO_REFUNDS_NOTICE },
|
|
92
|
+
docs: config.docsUrl,
|
|
93
|
+
message: `This call costs ${priceUsdc} USDC on ${config.network}, paid directly to the provider. ${NO_REFUNDS_NOTICE} See ${config.docsUrl}`
|
|
94
|
+
};
|
|
95
|
+
const routeConfig = {
|
|
96
|
+
accepts: {
|
|
97
|
+
scheme: "exact",
|
|
98
|
+
network: network.caip2,
|
|
99
|
+
payTo,
|
|
100
|
+
// An explicit asset+amount pins USDC and the exact atomic amount, rather than
|
|
101
|
+
// leaving the quote to a price feed.
|
|
102
|
+
price: { asset: network.usdc, amount: amountAtomic },
|
|
103
|
+
maxTimeoutSeconds: config.maxTimeoutSeconds
|
|
104
|
+
},
|
|
105
|
+
description: config.description ?? `Fatstack tool ${config.toolId}`,
|
|
106
|
+
mimeType: config.mimeType,
|
|
107
|
+
unpaidResponseBody: () => ({ contentType: "application/json", body: unpaidBody })
|
|
108
|
+
};
|
|
109
|
+
const facilitator = options.facilitator ?? new HTTPFacilitatorClient({
|
|
110
|
+
url: env.FACILITATOR_URL,
|
|
111
|
+
...env.FACILITATOR_API_KEY ? {
|
|
112
|
+
createAuthHeaders: async () => ({
|
|
113
|
+
verify: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
114
|
+
settle: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` },
|
|
115
|
+
supported: { authorization: `Bearer ${env.FACILITATOR_API_KEY}` }
|
|
116
|
+
})
|
|
117
|
+
} : {}
|
|
118
|
+
});
|
|
119
|
+
const server = new x402ResourceServer(facilitator).register(network.caip2, new ExactEvmScheme());
|
|
120
|
+
const killed = env.KILLSWITCH === "1";
|
|
121
|
+
function paymentRef(paymentResponseHeader) {
|
|
122
|
+
if (!paymentResponseHeader) return null;
|
|
123
|
+
try {
|
|
124
|
+
const settled = decodePaymentResponseHeader(paymentResponseHeader);
|
|
125
|
+
const transaction = settled.transaction;
|
|
126
|
+
return transaction ? `${config.toolId}:${network.caip2}:${transaction}` : null;
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
routeConfig,
|
|
133
|
+
payTo,
|
|
134
|
+
hono() {
|
|
135
|
+
let cached;
|
|
136
|
+
return async (c, next) => {
|
|
137
|
+
if (killed) return c.json(KILLSWITCH_BODY, 503);
|
|
138
|
+
if (!cached) {
|
|
139
|
+
const mod = await importOptional("@x402/hono");
|
|
140
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
141
|
+
}
|
|
142
|
+
const middleware = cached;
|
|
143
|
+
const result = await middleware(c, next);
|
|
144
|
+
const carrier = result instanceof Response ? result : c.res;
|
|
145
|
+
const ref = paymentRef(carrier?.headers?.get("x-payment-response"));
|
|
146
|
+
if (ref) carrier.headers.set(PAYMENT_REF_HEADER, ref);
|
|
147
|
+
return result;
|
|
148
|
+
};
|
|
149
|
+
},
|
|
150
|
+
express() {
|
|
151
|
+
let cached;
|
|
152
|
+
return async (req, res, next) => {
|
|
153
|
+
const response = res;
|
|
154
|
+
if (killed) {
|
|
155
|
+
response.status(503).json(KILLSWITCH_BODY);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (!cached) {
|
|
159
|
+
const mod = await importOptional("@x402/express");
|
|
160
|
+
cached = mod.paymentMiddleware(routeConfig, server);
|
|
161
|
+
}
|
|
162
|
+
const originalSetHeader = response.setHeader.bind(response);
|
|
163
|
+
response.setHeader = (name, value) => {
|
|
164
|
+
const out = originalSetHeader(name, value);
|
|
165
|
+
if (String(name).toLowerCase() === "x-payment-response") {
|
|
166
|
+
const ref = paymentRef(String(value));
|
|
167
|
+
if (ref) originalSetHeader(PAYMENT_REF_HEADER, ref);
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
};
|
|
171
|
+
const middleware = cached;
|
|
172
|
+
await middleware(req, res, next);
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
next(handler) {
|
|
176
|
+
let cached;
|
|
177
|
+
return async (request) => {
|
|
178
|
+
if (killed) {
|
|
179
|
+
return Response.json(KILLSWITCH_BODY, { status: 503 });
|
|
180
|
+
}
|
|
181
|
+
if (!cached) {
|
|
182
|
+
const mod = await importOptional("@x402/next");
|
|
183
|
+
cached = mod.withX402(handler, routeConfig, server);
|
|
184
|
+
}
|
|
185
|
+
const wrapped = cached;
|
|
186
|
+
const result = await wrapped(request);
|
|
187
|
+
if (result instanceof Response) {
|
|
188
|
+
const ref = paymentRef(result.headers.get("x-payment-response"));
|
|
189
|
+
if (ref) result.headers.set(PAYMENT_REF_HEADER, ref);
|
|
190
|
+
}
|
|
191
|
+
return result;
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
async function importOptional(specifier) {
|
|
197
|
+
try {
|
|
198
|
+
return await import(
|
|
199
|
+
/* @vite-ignore */
|
|
200
|
+
specifier
|
|
201
|
+
);
|
|
202
|
+
} catch {
|
|
203
|
+
throw new MissingAdapterError(specifier);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export {
|
|
208
|
+
resolvePayee,
|
|
209
|
+
paywallEnvSchema,
|
|
210
|
+
readPaywallEnv,
|
|
211
|
+
paywall
|
|
212
|
+
};
|
|
213
|
+
//# sourceMappingURL=chunk-7DVR574O.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 { DOCS_URL, NETWORKS, NO_REFUNDS_NOTICE, PAYMENT_REF_HEADER } from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { readPaywallEnv } from './env.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 price: { asset: network.usdc, amount: amountAtomic },\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?.headers?.get('x-payment-response'));\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 (String(name).toLowerCase() === 'x-payment-response') {\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(result.headers.get('x-payment-response'));\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,K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client } from "@x402/core/client";
|
|
9
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
10
|
+
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
11
|
+
|
|
12
|
+
// src/store.ts
|
|
13
|
+
function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1e3) {
|
|
14
|
+
let entries = [];
|
|
15
|
+
return {
|
|
16
|
+
record(entry) {
|
|
17
|
+
entries.push(entry);
|
|
18
|
+
const cutoff = entry.at - retentionMs;
|
|
19
|
+
if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);
|
|
20
|
+
},
|
|
21
|
+
totalSince(sinceMs) {
|
|
22
|
+
let total = 0;
|
|
23
|
+
for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;
|
|
24
|
+
return total;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/client.ts
|
|
30
|
+
var HOUR_MS = 60 * 60 * 1e3;
|
|
31
|
+
var DAY_MS = 24 * HOUR_MS;
|
|
32
|
+
function hostOf(input) {
|
|
33
|
+
try {
|
|
34
|
+
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
35
|
+
return new URL(raw).hostname.toLowerCase();
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function hostAllowed(host, allowed) {
|
|
41
|
+
return allowed.some((entry) => {
|
|
42
|
+
const candidate = entry.trim().toLowerCase().replace(/^\*\./, "");
|
|
43
|
+
return host === candidate || host.endsWith(`.${candidate}`);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function evaluateGuards(quoteUsd, guards, store, now) {
|
|
47
|
+
if (guards.maxPerCall !== void 0 && quoteUsd > guards.maxPerCall) {
|
|
48
|
+
throw new SpendGuardError(
|
|
49
|
+
"maxPerCall",
|
|
50
|
+
`Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,
|
|
51
|
+
{ limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd }
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
if (guards.maxPerHour !== void 0) {
|
|
55
|
+
const spent = await store.totalSince(now - HOUR_MS);
|
|
56
|
+
if (spent + quoteUsd > guards.maxPerHour) {
|
|
57
|
+
throw new SpendGuardError(
|
|
58
|
+
"maxPerHour",
|
|
59
|
+
`Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,
|
|
60
|
+
{ limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd }
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (guards.maxPerDay !== void 0) {
|
|
65
|
+
const spent = await store.totalSince(now - DAY_MS);
|
|
66
|
+
if (spent + quoteUsd > guards.maxPerDay) {
|
|
67
|
+
throw new SpendGuardError(
|
|
68
|
+
"maxPerDay",
|
|
69
|
+
`Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,
|
|
70
|
+
{ limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd }
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function quoteUsdOf(requirements) {
|
|
76
|
+
const asRecord = requirements;
|
|
77
|
+
const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;
|
|
78
|
+
if (!amountAtomic || !asRecord.asset) {
|
|
79
|
+
throw new RangeError("Payment requirements carry no priceable amount; refusing to pay.");
|
|
80
|
+
}
|
|
81
|
+
return quoteToUsd({
|
|
82
|
+
amountAtomic,
|
|
83
|
+
asset: asRecord.asset,
|
|
84
|
+
decimals: asRecord.extra?.decimals
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async function payFetch(url, init, options) {
|
|
88
|
+
const guards = options.guards ?? {};
|
|
89
|
+
const store = options.store ?? createMemorySpendStore();
|
|
90
|
+
const now = options.now ?? Date.now;
|
|
91
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
92
|
+
const networks = options.networks ?? ["base"];
|
|
93
|
+
if (guards.allowedHosts) {
|
|
94
|
+
const host = hostOf(url);
|
|
95
|
+
if (!host || !hostAllowed(host, guards.allowedHosts)) {
|
|
96
|
+
throw new SpendGuardError(
|
|
97
|
+
"allowedHosts",
|
|
98
|
+
`Host ${host ?? "<unparseable>"} is not in allowedHosts`,
|
|
99
|
+
{ host: host ?? void 0 }
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
let quotedUsd = null;
|
|
104
|
+
const client = new x402Client((_version, requirements) => {
|
|
105
|
+
const affordable = requirements.filter((requirement) => {
|
|
106
|
+
const usd = quoteUsdOf(requirement);
|
|
107
|
+
return guards.maxPerCall === void 0 || usd <= guards.maxPerCall;
|
|
108
|
+
});
|
|
109
|
+
const chosen = (affordable.length > 0 ? affordable : requirements)[0];
|
|
110
|
+
if (!chosen) throw new RangeError("Resource offered no payment requirements");
|
|
111
|
+
quotedUsd = quoteUsdOf(chosen);
|
|
112
|
+
return chosen;
|
|
113
|
+
});
|
|
114
|
+
for (const name of networks) {
|
|
115
|
+
client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));
|
|
116
|
+
}
|
|
117
|
+
const guarded = async (input, requestInit) => {
|
|
118
|
+
const response2 = await baseFetch(input, requestInit);
|
|
119
|
+
if (response2.status !== 402) return response2;
|
|
120
|
+
const body = await response2.clone().json().catch(() => null);
|
|
121
|
+
const accepts = body?.accepts;
|
|
122
|
+
if (Array.isArray(accepts) && accepts.length > 0) {
|
|
123
|
+
const cheapest = accepts.map((requirement) => quoteUsdOf(requirement)).sort((a, b) => a - b)[0];
|
|
124
|
+
if (cheapest !== void 0) {
|
|
125
|
+
await evaluateGuards(cheapest, guards, store, now());
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return response2;
|
|
129
|
+
};
|
|
130
|
+
const paying = wrapFetchWithPayment(guarded, client);
|
|
131
|
+
const response = await paying(url, init);
|
|
132
|
+
if (response.headers.get("x-payment-response") && quotedUsd !== null) {
|
|
133
|
+
await store.record({ at: now(), usd: quotedUsd });
|
|
134
|
+
}
|
|
135
|
+
return response;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export {
|
|
139
|
+
createMemorySpendStore,
|
|
140
|
+
evaluateGuards,
|
|
141
|
+
quoteUsdOf,
|
|
142
|
+
payFetch
|
|
143
|
+
};
|
|
144
|
+
//# sourceMappingURL=chunk-HCN75CTX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["import { x402Client } from '@x402/core/client';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { wrapFetchWithPayment } from '@x402/fetch';\n\nimport { NETWORKS, PAYMENT_REF_HEADER } from './constants.js';\nimport type { NetworkName } from './constants.js';\nimport { SpendGuardError } from './errors.js';\nimport { quoteToUsd } from './money.js';\nimport { createMemorySpendStore } from './store.js';\nimport type { SpendStore } from './store.js';\n\n/** The signer the official EVM scheme expects: address + signTypedData, no key handling. */\nexport type EvmWallet = ConstructorParameters<typeof ExactEvmScheme>[0];\n\nexport interface SpendGuards {\n /** Hard USD ceiling for a single call. */\n maxPerCall?: number;\n /** Rolling 60-minute USD ceiling. */\n maxPerHour?: number;\n /** Rolling 24-hour USD ceiling. */\n maxPerDay?: number;\n /** Hostnames this agent may pay. Checked before any network call. */\n allowedHosts?: string[];\n}\n\nexport interface PayFetchOptions {\n wallet: EvmWallet;\n guards?: SpendGuards;\n /** Defaults to a process-local in-memory store. */\n store?: SpendStore;\n networks?: NetworkName[];\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction hostOf(input: RequestInfo | URL): string | null {\n try {\n const raw =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** `example.com` in allowedHosts also authorises `tool.example.com`. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const candidate = entry.trim().toLowerCase().replace(/^\\*\\./, '');\n return host === candidate || host.endsWith(`.${candidate}`);\n });\n}\n\n/**\n * Checks every guard against a quote. Returns the USD value if the call may proceed,\n * throws SpendGuardError otherwise. Called before a payment payload exists.\n */\nexport async function evaluateGuards(\n quoteUsd: number,\n guards: SpendGuards,\n store: SpendStore,\n now: number,\n): Promise<void> {\n if (guards.maxPerCall !== undefined && quoteUsd > guards.maxPerCall) {\n throw new SpendGuardError(\n 'maxPerCall',\n `Call costs $${quoteUsd} which exceeds the maxPerCall limit of $${guards.maxPerCall}`,\n { limitUsd: guards.maxPerCall, attemptedUsd: quoteUsd },\n );\n }\n\n if (guards.maxPerHour !== undefined) {\n const spent = await store.totalSince(now - HOUR_MS);\n if (spent + quoteUsd > guards.maxPerHour) {\n throw new SpendGuardError(\n 'maxPerHour',\n `Call costs $${quoteUsd} and $${spent} was already spent this hour, exceeding the maxPerHour limit of $${guards.maxPerHour}`,\n { limitUsd: guards.maxPerHour, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n\n if (guards.maxPerDay !== undefined) {\n const spent = await store.totalSince(now - DAY_MS);\n if (spent + quoteUsd > guards.maxPerDay) {\n throw new SpendGuardError(\n 'maxPerDay',\n `Call costs $${quoteUsd} and $${spent} was already spent today, exceeding the maxPerDay limit of $${guards.maxPerDay}`,\n { limitUsd: guards.maxPerDay, attemptedUsd: spent + quoteUsd },\n );\n }\n }\n}\n\n/** Reads the quoted amount out of x402 payment requirements. */\ninterface PriceableRequirement {\n maxAmountRequired?: string;\n amount?: string;\n asset?: string;\n extra?: { decimals?: number };\n}\n\nexport function quoteUsdOf(requirements: PaymentRequirements): number {\n const asRecord: PriceableRequirement = requirements;\n const amountAtomic = asRecord.maxAmountRequired ?? asRecord.amount;\n if (!amountAtomic || !asRecord.asset) {\n throw new RangeError('Payment requirements carry no priceable amount; refusing to pay.');\n }\n return quoteToUsd({\n amountAtomic,\n asset: asRecord.asset,\n decimals: asRecord.extra?.decimals,\n });\n}\n\n/**\n * A `fetch` that pays for 402 responses, under spend guards.\n *\n * The 402 handling, signing and retry are the official x402 packages' work. What this adds\n * is refusal: guards are evaluated inside the payment-policy hook, which runs after the\n * quote is known and before any payload is signed, so exceeding a guard throws\n * SpendGuardError with nothing signed and nothing spent.\n */\nexport async function payFetch(\n url: RequestInfo | URL,\n init: RequestInit | undefined,\n options: PayFetchOptions,\n): Promise<Response> {\n const guards = options.guards ?? {};\n const store = options.store ?? createMemorySpendStore();\n const now = options.now ?? Date.now;\n const baseFetch = options.fetch ?? globalThis.fetch;\n const networks = options.networks ?? (['base'] as NetworkName[]);\n\n // Host allowlist is checked first: an unauthorised host should cost no request at all.\n if (guards.allowedHosts) {\n const host = hostOf(url);\n if (!host || !hostAllowed(host, guards.allowedHosts)) {\n throw new SpendGuardError(\n 'allowedHosts',\n `Host ${host ?? '<unparseable>'} is not in allowedHosts`,\n { host: host ?? undefined },\n );\n }\n }\n\n let quotedUsd: number | null = null;\n\n const client = new x402Client((_version, requirements) => {\n // Runs before the payment payload is created. Throwing here means no signature.\n const affordable = requirements.filter((requirement) => {\n const usd = quoteUsdOf(requirement);\n return guards.maxPerCall === undefined || usd <= guards.maxPerCall;\n });\n\n const chosen = (affordable.length > 0 ? affordable : requirements)[0];\n if (!chosen) throw new RangeError('Resource offered no payment requirements');\n\n quotedUsd = quoteUsdOf(chosen);\n return chosen;\n });\n\n for (const name of networks) {\n client.register(NETWORKS[name].caip2, new ExactEvmScheme(options.wallet));\n }\n\n const guarded: typeof globalThis.fetch = async (input, requestInit) => {\n const response = await baseFetch(input, requestInit);\n if (response.status !== 402) return response;\n\n // Peek at the quote and apply guards before the wrapper signs anything.\n const body = await response\n .clone()\n .json()\n .catch(() => null);\n const accepts = (body as { accepts?: PaymentRequirements[] } | null)?.accepts;\n if (Array.isArray(accepts) && accepts.length > 0) {\n const cheapest = accepts\n .map((requirement) => quoteUsdOf(requirement))\n .sort((a, b) => a - b)[0];\n if (cheapest !== undefined) {\n await evaluateGuards(cheapest, guards, store, now());\n }\n }\n return response;\n };\n\n const paying = wrapFetchWithPayment(guarded, client);\n const response = await paying(url as RequestInfo, init);\n\n // Record the spend only once a payment actually settled.\n if (response.headers.get('x-payment-response') && quotedUsd !== null) {\n await store.record({ at: now(), usd: quotedUsd });\n }\n\n return response;\n}\n\nexport { PAYMENT_REF_HEADER };\n","/** One recorded spend, in USD, at a wall-clock millisecond. */\nexport interface SpendRecord {\n at: number;\n usd: number;\n}\n\n/**\n * Where rolling spend totals live. The default is in-memory and per-process; swap in a\n * shared implementation (Redis, Durable Object, Postgres) when an agent runs as more\n * than one process, otherwise each process enforces its own separate budget.\n */\nexport interface SpendStore {\n record(entry: SpendRecord): Promise<void> | void;\n /** Total USD recorded at or after `sinceMs`. */\n totalSince(sinceMs: number): Promise<number> | number;\n}\n\n/** Process-local store. Entries older than the longest window are dropped on write. */\nexport function createMemorySpendStore(retentionMs = 24 * 60 * 60 * 1000): SpendStore {\n let entries: SpendRecord[] = [];\n\n return {\n record(entry) {\n entries.push(entry);\n const cutoff = entry.at - retentionMs;\n if (entries.length > 64) entries = entries.filter((e) => e.at >= cutoff);\n },\n totalSince(sinceMs) {\n let total = 0;\n for (const entry of entries) if (entry.at >= sinceMs) total += entry.usd;\n return total;\n },\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,kBAAkB;AAE3B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;;;ACe9B,SAAS,uBAAuB,cAAc,KAAK,KAAK,KAAK,KAAkB;AACpF,MAAI,UAAyB,CAAC;AAE9B,SAAO;AAAA,IACL,OAAO,OAAO;AACZ,cAAQ,KAAK,KAAK;AAClB,YAAM,SAAS,MAA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