@lunora/x402 0.0.0 → 1.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +111 -0
- package/README.md +43 -28
- package/__assets__/package-og.svg +14 -0
- package/dist/charge/index.d.mts +76 -0
- package/dist/charge/index.d.ts +76 -0
- package/dist/charge/index.mjs +7 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.mjs +2 -0
- package/dist/packem_shared/DEFAULT_FACILITATOR_URL-Cbz6kIqa.mjs +4 -0
- package/dist/packem_shared/DEFAULT_STABLECOIN_DECIMALS-CSu5b5lD.mjs +85 -0
- package/dist/packem_shared/EVM_NETWORKS-BhnYWUQ4.mjs +26 -0
- package/dist/packem_shared/config.d-CddwCiBm.d.mts +325 -0
- package/dist/packem_shared/config.d-CddwCiBm.d.ts +325 -0
- package/dist/packem_shared/createChargeMiddleware-BJkYJeFf.mjs +148 -0
- package/dist/packem_shared/createFacilitatorClient-rXHBnCZm.mjs +16 -0
- package/dist/packem_shared/createPayFetch-O2vkvM1v.mjs +17 -0
- package/dist/packem_shared/createProcedureChargeGate-CV8ITlQP.mjs +19 -0
- package/dist/packem_shared/registerWallet-I4pVwq65.mjs +109 -0
- package/dist/packem_shared/toPaymentEventRow-DW4O9N7Y.mjs +22 -0
- package/dist/packem_shared/withX402-rUq0voT8.mjs +15 -0
- package/dist/pay/index.d.mts +77 -0
- package/dist/pay/index.d.ts +77 -0
- package/dist/pay/index.mjs +21 -0
- package/package.json +75 -7
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { ClientEvmSigner } from '@x402/evm';
|
|
2
|
+
import { ClientSvmSigner } from '@x402/svm';
|
|
3
|
+
import { ProcessSettleSuccessResponse } from '@x402/core/http';
|
|
4
|
+
import { BeforePaymentCreationHook, PaymentPolicy, AfterPaymentCreationHook } from '@x402/core/client';
|
|
5
|
+
import { PaymentRequirements } from '@x402/core/types';
|
|
6
|
+
/**
|
|
7
|
+
* A normalised record of one settled x402 payment. The settled `amount` is kept
|
|
8
|
+
* as its exact on-chain atomic-unit string (USDC has 6 decimals) — never coerced
|
|
9
|
+
* to a fractional-dollar number — so no precision is lost crossing the reporting
|
|
10
|
+
* seam.
|
|
11
|
+
*/
|
|
12
|
+
interface X402Receipt {
|
|
13
|
+
/** Settled amount in the asset's atomic base units (USDC: 6 decimals), as an exact string. */
|
|
14
|
+
readonly amount: string;
|
|
15
|
+
/** The settled asset's contract / mint address (e.g. Base USDC). */
|
|
16
|
+
readonly asset: string;
|
|
17
|
+
/** The payer's wallet address, when the facilitator reports it. */
|
|
18
|
+
readonly from: string | undefined;
|
|
19
|
+
/** The settlement network as a CAIP-2 id (e.g. `eip155:8453`). */
|
|
20
|
+
readonly network: string;
|
|
21
|
+
/** The gated resource this payment bought (a URL, or a procedure's `file:function` id). */
|
|
22
|
+
readonly resource: string;
|
|
23
|
+
/** The payout wallet the funds settled to (the merchant recipient). */
|
|
24
|
+
readonly to: string;
|
|
25
|
+
/** When the receipt was produced (epoch milliseconds). */
|
|
26
|
+
readonly ts: number;
|
|
27
|
+
/** On-chain settlement transaction id / hash. */
|
|
28
|
+
readonly tx: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A one-way, opt-in sink for settled-payment receipts. Wire it via
|
|
32
|
+
* `config.onReceipt`. It is best-effort telemetry — the middleware fires it after
|
|
33
|
+
* settlement, does not block the paid response on it, and swallows any error it
|
|
34
|
+
* throws — so a sink must never rely on being awaited or on its failures
|
|
35
|
+
* surfacing.
|
|
36
|
+
*/
|
|
37
|
+
type X402ReceiptSink = (receipt: X402Receipt) => Promise<void> | void;
|
|
38
|
+
/**
|
|
39
|
+
* Normalise a successful facilitator settlement into an {@link X402Receipt}.
|
|
40
|
+
* `resource` (the gated URL or procedure id) and `ts` are supplied by the caller —
|
|
41
|
+
* the settlement result carries neither. Prefers the actual settled `amount`
|
|
42
|
+
* (present for `upto`-scheme partial settlements) and falls back to the route's
|
|
43
|
+
* required amount for `exact`.
|
|
44
|
+
*/
|
|
45
|
+
declare const toReceipt: (settlement: ProcessSettleSuccessResponse, context: {
|
|
46
|
+
readonly resource: string;
|
|
47
|
+
readonly ts: number;
|
|
48
|
+
}) => X402Receipt;
|
|
49
|
+
/**
|
|
50
|
+
* A row for `@lunora/payment`'s durable `events` table. Deliberately a plain
|
|
51
|
+
* structural type — building one imports nothing from `@lunora/payment`, so the
|
|
52
|
+
* rails stay decoupled.
|
|
53
|
+
*/
|
|
54
|
+
interface PaymentEventRow {
|
|
55
|
+
/** Epoch milliseconds the settlement was recorded. */
|
|
56
|
+
readonly processedAt: number;
|
|
57
|
+
/** The rail that produced the event. */
|
|
58
|
+
readonly provider: "x402";
|
|
59
|
+
/** The settlement tx hash — the natural unique event id (the table is unique on `(provider, providerEventId)`). */
|
|
60
|
+
readonly providerEventId: string;
|
|
61
|
+
/** The event kind, namespaced to the x402 rail. */
|
|
62
|
+
readonly type: "x402.settled";
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Shape a receipt as a row for `@lunora/payment`'s durable `events` table, so a
|
|
66
|
+
* settled x402 payment shows in Studio's Payments panel (its recent-events card)
|
|
67
|
+
* with ZERO coupling: this returns a plain object matching that table's
|
|
68
|
+
* documented column contract (`provider` / `providerEventId` / `type` /
|
|
69
|
+
* `processedAt`, unique on `(provider, providerEventId)`) and imports nothing
|
|
70
|
+
* from `@lunora/payment`. Insert it from a mutation ctx:
|
|
71
|
+
*
|
|
72
|
+
* ```ts
|
|
73
|
+
* onReceipt: (receipt) => ctx.db.insert("events", toPaymentEventRow(receipt)),
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* The source of truth for the column contract is `@lunora/payment`'s `events`
|
|
77
|
+
* table (`packages/payment/src/schema.ts`). Amount / from / to / resource are
|
|
78
|
+
* intentionally not on this row — that card renders none of them; read them off
|
|
79
|
+
* the {@link X402Receipt} (e.g. into your own revenue table) if you need them.
|
|
80
|
+
*/
|
|
81
|
+
declare const toPaymentEventRow: (receipt: X402Receipt) => PaymentEventRow;
|
|
82
|
+
/**
|
|
83
|
+
* Network identity for `@lunora/x402`.
|
|
84
|
+
*
|
|
85
|
+
* `@x402/core` v2 speaks **CAIP-2** chain ids (`eip155:8453` for Base,
|
|
86
|
+
* `solana:5eyk…` for Solana mainnet) — `type Network = ` `${string}:${string}` ``.
|
|
87
|
+
* Lunora keeps ergonomic **friendly** names (`"base"`, `"base-sepolia"`) as the
|
|
88
|
+
* public surface and maps them to CAIP-2 here, at the single seam where we hand a
|
|
89
|
+
* network to the SDK. A raw CAIP-2 string is also accepted as a power-user escape
|
|
90
|
+
* hatch (e.g. a chain we don't yet have a friendly alias for).
|
|
91
|
+
*
|
|
92
|
+
* The friendly set is intentionally scoped to chains `@x402/evm` / `@x402/svm`
|
|
93
|
+
* can settle the ergonomic `price:"$0.01"` path on out of the box (i.e. chains in
|
|
94
|
+
* their `DEFAULT_STABLECOINS` registry). Notably that excludes Optimism and
|
|
95
|
+
* Avalanche today — advertising them would 500 at settlement — so they are not
|
|
96
|
+
* friendly aliases; a caller who needs them can still pass a raw CAIP-2 id with an
|
|
97
|
+
* explicit asset.
|
|
98
|
+
*/
|
|
99
|
+
/** A CAIP-2 chain identifier, e.g. `"eip155:8453"` (Base) or `"solana:5eyk…"`. */
|
|
100
|
+
type Caip2 = `${string}:${string}`;
|
|
101
|
+
/** Friendly network names Lunora maps to CAIP-2 for `@x402/core`. */
|
|
102
|
+
type FriendlyNetwork = "arbitrum" | "arbitrum-sepolia" | "base" | "base-sepolia" | "ethereum" | "polygon" | "solana" | "solana-devnet";
|
|
103
|
+
/**
|
|
104
|
+
* A network Lunora can settle on: a {@link FriendlyNetwork} alias (mapped to
|
|
105
|
+
* CAIP-2 internally) or a raw {@link Caip2} id for chains without a friendly name.
|
|
106
|
+
*/
|
|
107
|
+
type X402Network = Caip2 | FriendlyNetwork;
|
|
108
|
+
/**
|
|
109
|
+
* Friendly name → CAIP-2 id. Values verified against `@x402/evm` and `@x402/svm`
|
|
110
|
+
* `DEFAULT_STABLECOINS` at 2.17.0. `base` / `base-sepolia` are the primary
|
|
111
|
+
* prod / test pair.
|
|
112
|
+
*/
|
|
113
|
+
declare const NETWORK_TO_CAIP2: {
|
|
114
|
+
readonly arbitrum: "eip155:42161";
|
|
115
|
+
readonly "arbitrum-sepolia": "eip155:421614";
|
|
116
|
+
readonly base: "eip155:8453";
|
|
117
|
+
readonly "base-sepolia": "eip155:84532";
|
|
118
|
+
readonly ethereum: "eip155:1";
|
|
119
|
+
readonly polygon: "eip155:137";
|
|
120
|
+
readonly solana: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
121
|
+
readonly "solana-devnet": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
122
|
+
};
|
|
123
|
+
/** EVM friendly networks (signed via `@x402/evm` + viem). */
|
|
124
|
+
declare const EVM_NETWORKS: readonly ["arbitrum", "arbitrum-sepolia", "base", "base-sepolia", "ethereum", "polygon"];
|
|
125
|
+
/** Solana friendly networks (signed via `@x402/svm`). */
|
|
126
|
+
declare const SVM_NETWORKS: readonly ["solana", "solana-devnet"];
|
|
127
|
+
/**
|
|
128
|
+
* Resolve a network to its CAIP-2 id. Friendly aliases are looked up; a value
|
|
129
|
+
* that already looks like CAIP-2 (`namespace:reference`) passes through.
|
|
130
|
+
*/
|
|
131
|
+
declare const toCaip2: (network: X402Network) => Caip2;
|
|
132
|
+
/** True when `network` settles on an EVM chain (viem signer path). */
|
|
133
|
+
declare const isEvmNetwork: (network: X402Network) => boolean;
|
|
134
|
+
/** True when `network` settles on Solana (`@x402/svm` signer path). */
|
|
135
|
+
declare const isSvmNetwork: (network: X402Network) => boolean;
|
|
136
|
+
/**
|
|
137
|
+
* USDC — and every asset in `@x402/evm` / `@x402/svm`'s `DEFAULT_STABLECOINS` —
|
|
138
|
+
* uses 6 decimals, so a USD price converts to atomic base units at `10 ** 6`.
|
|
139
|
+
* Override per {@link SpendPolicy.decimals} only for a custom, non-6-decimal asset.
|
|
140
|
+
*/
|
|
141
|
+
declare const DEFAULT_STABLECOIN_DECIMALS = 6;
|
|
142
|
+
/**
|
|
143
|
+
* Spend limits and approval gates for an agent wallet. At least one bound must be
|
|
144
|
+
* set — see {@link assertBoundedPolicy} — or the pay rail refuses to build.
|
|
145
|
+
*
|
|
146
|
+
* Caps are denominated in USD (the stablecoin's dollar value); addresses and
|
|
147
|
+
* networks are matched against the requirement the server offers.
|
|
148
|
+
*/
|
|
149
|
+
interface SpendPolicy {
|
|
150
|
+
/** Network allowlist. When set, only these networks may be paid on. */
|
|
151
|
+
readonly allowedNetworks?: ReadonlyArray<X402Network>;
|
|
152
|
+
/** Recipient allowlist. When set, only these `payTo` addresses may be paid. */
|
|
153
|
+
readonly allowedRecipients?: ReadonlyArray<string>;
|
|
154
|
+
/** Stablecoin decimals for USD→atomic conversion (default {@link DEFAULT_STABLECOIN_DECIMALS}). */
|
|
155
|
+
readonly decimals?: number;
|
|
156
|
+
/** Hard ceiling on a single payment, in USD. */
|
|
157
|
+
readonly maxPerCall?: X402Price;
|
|
158
|
+
/** Hard ceiling on cumulative spend across this wallet's lifetime, in USD. */
|
|
159
|
+
readonly maxPerRun?: X402Price;
|
|
160
|
+
/**
|
|
161
|
+
* Approval gate. Called with the selected requirement before signing; return
|
|
162
|
+
* `false` (or reject) to refuse the payment. Use for human-in-the-loop or any
|
|
163
|
+
* dynamic rule the static caps can't express.
|
|
164
|
+
*/
|
|
165
|
+
readonly onPaymentRequired?: (requirement: PaymentRequirements) => Promise<boolean> | boolean;
|
|
166
|
+
}
|
|
167
|
+
/** A running spend ledger the per-run cap is measured against; the guard reads it, the recorder adds to it. */
|
|
168
|
+
interface SpendState {
|
|
169
|
+
/** Add a just-committed payment (atomic base units) to the total. */
|
|
170
|
+
readonly add: (amount: bigint) => void;
|
|
171
|
+
/** Cumulative spend so far, in atomic base units. */
|
|
172
|
+
readonly spentAtomic: bigint;
|
|
173
|
+
}
|
|
174
|
+
/** A fresh spend ledger. One per wallet instance; the guard + recorder share it. */
|
|
175
|
+
declare const createSpendState: () => SpendState;
|
|
176
|
+
/**
|
|
177
|
+
* Convert a USD amount (`0.01`, `"0.01"`, or the `"$0.01"` shorthand) to atomic
|
|
178
|
+
* stablecoin base units, exactly — parsed digit-by-digit so no binary-float drift
|
|
179
|
+
* can round a cap the wrong way. Throws on a malformed amount (including
|
|
180
|
+
* exponential notation like `"1e-7"`, which a decimal string never needs).
|
|
181
|
+
*/
|
|
182
|
+
declare const usdToAtomic: (usd: X402Price, decimals?: number) => bigint;
|
|
183
|
+
/**
|
|
184
|
+
* A `PaymentPolicy` that narrows the server's offered requirements to those a
|
|
185
|
+
* bounded wallet may pay: within the per-call cap, to an allowed recipient, on an
|
|
186
|
+
* allowed network. An empty result means the client cannot pay — fail-closed.
|
|
187
|
+
*/
|
|
188
|
+
declare const buildSpendPolicy: (policy: SpendPolicy) => PaymentPolicy;
|
|
189
|
+
/**
|
|
190
|
+
* A `BeforePaymentCreationHook` enforcing the stateful bounds the stateless
|
|
191
|
+
* {@link buildSpendPolicy} filter can't: the cumulative per-run cap and the async
|
|
192
|
+
* confirmation gate. Aborts (no signature) when either would be violated.
|
|
193
|
+
*/
|
|
194
|
+
declare const buildPaymentGuard: (policy: SpendPolicy, state: SpendState) => BeforePaymentCreationHook;
|
|
195
|
+
/**
|
|
196
|
+
* An `AfterPaymentCreationHook` that adds the just-created payment to `state`, so
|
|
197
|
+
* the next {@link buildPaymentGuard} call measures the per-run cap against it.
|
|
198
|
+
*/
|
|
199
|
+
declare const recordSpend: (state: SpendState) => AfterPaymentCreationHook;
|
|
200
|
+
/**
|
|
201
|
+
* Guard at wallet-build time: refuse a policy with no bound whatsoever. Signing
|
|
202
|
+
* money on an agent's behalf with unlimited spend authority is never the intent,
|
|
203
|
+
* so this fails loudly rather than defaulting to unbounded.
|
|
204
|
+
*/
|
|
205
|
+
declare const assertBoundedPolicy: (policy: SpendPolicy) => void;
|
|
206
|
+
/**
|
|
207
|
+
* The public, Coinbase-operated facilitator (verify + settle). It needs no API
|
|
208
|
+
* key. Override with a self-hosted or CDP facilitator via {@link FacilitatorConfig}.
|
|
209
|
+
*/
|
|
210
|
+
declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
211
|
+
/** How to reach a facilitator's `/verify` + `/settle` endpoints. */
|
|
212
|
+
interface FacilitatorConfig {
|
|
213
|
+
/** Extra headers for a private facilitator (e.g. a CDP bearer token). */
|
|
214
|
+
readonly headers?: Record<string, string>;
|
|
215
|
+
/** Base URL. Defaults to {@link DEFAULT_FACILITATOR_URL}. */
|
|
216
|
+
readonly url?: string;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* A resource's price, as a USD-denominated decimal string (`"0.01"`, or the
|
|
220
|
+
* `"$0.01"` shorthand) or a number of dollars (`0.01`). The scheme resolves it
|
|
221
|
+
* to the network's stablecoin base units (USDC has 6 decimals) at challenge
|
|
222
|
+
* time. (Kept `number | string` rather than a `` `$${string}` `` template
|
|
223
|
+
* member — the template is subsumed by `string`, so it only adds noise.)
|
|
224
|
+
*/
|
|
225
|
+
type X402Price = number | string;
|
|
226
|
+
/** An EVM recipient address (the merchant wallet that receives settlement). */
|
|
227
|
+
type EvmAddress = `0x${string}`;
|
|
228
|
+
/** Recipient wallet the facilitator settles payments to, per network family. */
|
|
229
|
+
interface X402Recipient {
|
|
230
|
+
/** EVM payout address (required for EVM networks). */
|
|
231
|
+
readonly evm?: EvmAddress;
|
|
232
|
+
/** Solana payout address, base58 (required for SVM networks). */
|
|
233
|
+
readonly svm?: string;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Server-side (charge rail) config. The server needs only a **recipient
|
|
237
|
+
* address** — no private key — because the facilitator performs settlement.
|
|
238
|
+
*/
|
|
239
|
+
interface X402ChargeConfig {
|
|
240
|
+
readonly facilitator?: FacilitatorConfig;
|
|
241
|
+
/** Network this resource settles on. */
|
|
242
|
+
readonly network: X402Network;
|
|
243
|
+
/**
|
|
244
|
+
* Opt-in, one-way telemetry sink fired once per settled payment. Best-effort:
|
|
245
|
+
* it runs after settlement, never blocks the paid response, and its errors are
|
|
246
|
+
* swallowed. Use it to mirror x402 revenue into a durable table / `@lunora/payment`'s
|
|
247
|
+
* `events` table (see `toPaymentEventRow`) so it surfaces in Studio.
|
|
248
|
+
*/
|
|
249
|
+
readonly onReceipt?: X402ReceiptSink;
|
|
250
|
+
/** Default price for a gated resource; per-resource overrides win. */
|
|
251
|
+
readonly price: X402Price;
|
|
252
|
+
/** Payout wallet(s). */
|
|
253
|
+
readonly recipient: X402Recipient;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Client-side (pay rail) config. The signer holds spending authority, so the
|
|
257
|
+
* pay rail is ActionCtx-only and MUST be paired with a spend `policy` — the pay
|
|
258
|
+
* rail refuses to build if the policy is unbounded.
|
|
259
|
+
*/
|
|
260
|
+
interface X402PayConfig {
|
|
261
|
+
/** Network to transact on. Determines the signer family (EVM vs SVM). */
|
|
262
|
+
readonly network: X402Network;
|
|
263
|
+
/** Mandatory spend limits + approval gates. An unbounded policy is refused. */
|
|
264
|
+
readonly policy: SpendPolicy;
|
|
265
|
+
/** How the agent wallet is custodied (raw key, a user-supplied signer, or CDP-managed). */
|
|
266
|
+
readonly signer: X402SignerConfig;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* CDP-managed wallet custody via `@coinbase/cdp-sdk` (an optional peer). The SDK
|
|
270
|
+
* gets-or-creates a named server account and signs the x402 EIP-712 payment
|
|
271
|
+
* authorization with it — no private key ever leaves Coinbase. Needs three CDP
|
|
272
|
+
* credentials, read from `ctx.secrets` under names that default to the SDK's own
|
|
273
|
+
* env-var names; override them if your secrets are named differently. (Note
|
|
274
|
+
* `@coinbase/x402` is a facilitator-auth helper, not a signer provider — CDP
|
|
275
|
+
* custody is `@coinbase/cdp-sdk`.) EVM only today; for CDP on Solana, build a
|
|
276
|
+
* `@solana/kit` signer around your CDP account and pass it via the `"signer"`
|
|
277
|
+
* escape hatch.
|
|
278
|
+
*/
|
|
279
|
+
interface X402CdpSignerConfig {
|
|
280
|
+
/** CDP account name to get-or-create and sign with. */
|
|
281
|
+
readonly account: string;
|
|
282
|
+
/** `ctx.secrets` name for the CDP API key id. Default `"CDP_API_KEY_ID"`. */
|
|
283
|
+
readonly apiKeyIdSecretName?: string;
|
|
284
|
+
/** `ctx.secrets` name for the CDP API key secret. Default `"CDP_API_KEY_SECRET"`. */
|
|
285
|
+
readonly apiKeySecretName?: string;
|
|
286
|
+
readonly type: "cdp";
|
|
287
|
+
/** `ctx.secrets` name for the CDP wallet secret. Default `"CDP_WALLET_SECRET"`. */
|
|
288
|
+
readonly walletSecretName?: string;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Wallet custody for the pay rail — three shapes.
|
|
292
|
+
*
|
|
293
|
+
* `"raw-key"` resolves a private key from `ctx.secrets` (viem for EVM, a
|
|
294
|
+
* `@solana/kit` keypair for Solana) — simplest, self-custodied.
|
|
295
|
+
*
|
|
296
|
+
* `"signer"` is the escape hatch: hand in a signer you already built — any
|
|
297
|
+
* `@x402/evm` `ClientEvmSigner` (a viem account from Turnkey, Privy, an AWS/GCP
|
|
298
|
+
* KMS `toAccount`, CDP's viem adapter, …) on an EVM network, or an `@x402/svm`
|
|
299
|
+
* `ClientSvmSigner` (a `@solana/kit` `TransactionSigner`) on Solana. Adapt any
|
|
300
|
+
* custody provider to the structural signer and pass it here; `@lunora/x402`
|
|
301
|
+
* takes no dependency on the provider's SDK.
|
|
302
|
+
*
|
|
303
|
+
* `"cdp"` is a Coinbase-managed wallet via `@coinbase/cdp-sdk`
|
|
304
|
+
* ({@link X402CdpSignerConfig}).
|
|
305
|
+
*
|
|
306
|
+
* Wired today: raw-key (EVM + SVM), the user-supplied signer (both families),
|
|
307
|
+
* and CDP-managed EVM custody. CDP on Solana is not yet wired — use the escape
|
|
308
|
+
* hatch.
|
|
309
|
+
*/
|
|
310
|
+
type X402SignerConfig = X402CdpSignerConfig | {
|
|
311
|
+
/** Name of the `ctx.secrets` entry holding the private key. */
|
|
312
|
+
readonly secretName: string;
|
|
313
|
+
readonly type: "raw-key";
|
|
314
|
+
} | {
|
|
315
|
+
/**
|
|
316
|
+
* A pre-built signer you own: an EVM `ClientEvmSigner` (viem account) on
|
|
317
|
+
* an EVM network, or an SVM `ClientSvmSigner` (`@solana/kit`
|
|
318
|
+
* `TransactionSigner`) on Solana. Must match the config `network`'s family.
|
|
319
|
+
*/
|
|
320
|
+
readonly signer: ClientEvmSigner | ClientSvmSigner;
|
|
321
|
+
readonly type: "signer";
|
|
322
|
+
};
|
|
323
|
+
/** Resolve a facilitator's base URL, applying the public default. */
|
|
324
|
+
declare const resolveFacilitatorUrl: (facilitator?: FacilitatorConfig) => string;
|
|
325
|
+
export { Caip2 as C, DEFAULT_FACILITATOR_URL as D, EVM_NETWORKS as E, FacilitatorConfig as F, NETWORK_TO_CAIP2 as N, PaymentEventRow as P, SVM_NETWORKS as S, X402CdpSignerConfig as X, EvmAddress as a, FriendlyNetwork as b, X402ChargeConfig as c, X402Network as d, X402PayConfig as e, X402Price as f, X402Receipt as g, X402ReceiptSink as h, X402Recipient as i, X402SignerConfig as j, isEvmNetwork as k, isSvmNetwork as l, DEFAULT_STABLECOIN_DECIMALS as m, SpendPolicy as n, SpendState as o, assertBoundedPolicy as p, buildPaymentGuard as q, resolveFacilitatorUrl as r, buildSpendPolicy as s, toCaip2 as t, createSpendState as u, recordSpend as v, usdToAtomic as w, toPaymentEventRow as x, toReceipt as y };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { x402HTTPResourceServer } from '@x402/core/http';
|
|
2
|
+
import { toCaip2, isEvmNetwork } from './EVM_NETWORKS-BhnYWUQ4.mjs';
|
|
3
|
+
import { toReceipt } from './toPaymentEventRow-DW4O9N7Y.mjs';
|
|
4
|
+
import { createFacilitatorClient } from './createFacilitatorClient-rXHBnCZm.mjs';
|
|
5
|
+
|
|
6
|
+
const buildResourceServer = async (config) => {
|
|
7
|
+
const { x402ResourceServer: ResourceServer } = await import('@x402/core/server');
|
|
8
|
+
const server = new ResourceServer(createFacilitatorClient(config.facilitator));
|
|
9
|
+
const network = toCaip2(config.network);
|
|
10
|
+
if (isEvmNetwork(config.network)) {
|
|
11
|
+
const { registerExactEvmScheme } = await import('@x402/evm/exact/server');
|
|
12
|
+
registerExactEvmScheme(server, { networks: [network] });
|
|
13
|
+
} else {
|
|
14
|
+
const { registerExactSvmScheme } = await import('@x402/svm/exact/server');
|
|
15
|
+
registerExactSvmScheme(server, { networks: [network] });
|
|
16
|
+
}
|
|
17
|
+
return server;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const PAYMENT_HEADER = "X-PAYMENT";
|
|
21
|
+
const headerRecord = (headers) => {
|
|
22
|
+
const record = {};
|
|
23
|
+
for (const [key, value] of headers) {
|
|
24
|
+
record[key] = value;
|
|
25
|
+
}
|
|
26
|
+
return record;
|
|
27
|
+
};
|
|
28
|
+
const reportReceipt = (sink, settlement, resource) => {
|
|
29
|
+
if (sink === void 0) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
Promise.resolve(sink(toReceipt(settlement, { resource, ts: Date.now() }))).catch(() => {
|
|
34
|
+
});
|
|
35
|
+
} catch {
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const resolvePayTo = (config) => {
|
|
39
|
+
const evm = isEvmNetwork(config.network);
|
|
40
|
+
const address = evm ? config.recipient.evm : config.recipient.svm;
|
|
41
|
+
if (address === void 0 || address.length === 0) {
|
|
42
|
+
throw new Error(`x402 charge on "${config.network}" needs recipient.${evm ? "evm" : "svm"} set.`);
|
|
43
|
+
}
|
|
44
|
+
return address;
|
|
45
|
+
};
|
|
46
|
+
const buildRoute = (config) => {
|
|
47
|
+
const accepts = {
|
|
48
|
+
network: toCaip2(config.network),
|
|
49
|
+
payTo: resolvePayTo(config),
|
|
50
|
+
price: config.price,
|
|
51
|
+
scheme: "exact"
|
|
52
|
+
};
|
|
53
|
+
return { accepts };
|
|
54
|
+
};
|
|
55
|
+
const createRequestAdapter = (request, url) => {
|
|
56
|
+
return {
|
|
57
|
+
getAcceptHeader: () => request.headers.get("accept") ?? "",
|
|
58
|
+
getHeader: (name) => request.headers.get(name) ?? void 0,
|
|
59
|
+
getMethod: () => request.method,
|
|
60
|
+
getPath: () => url.pathname,
|
|
61
|
+
getQueryParam: (name) => {
|
|
62
|
+
const values = url.searchParams.getAll(name);
|
|
63
|
+
if (values.length === 0) {
|
|
64
|
+
return void 0;
|
|
65
|
+
}
|
|
66
|
+
return values.length === 1 ? values[0] : values;
|
|
67
|
+
},
|
|
68
|
+
getQueryParams: () => {
|
|
69
|
+
const params = {};
|
|
70
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
71
|
+
const values = url.searchParams.getAll(key);
|
|
72
|
+
const [first, ...rest] = values;
|
|
73
|
+
if (first === void 0) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
params[key] = rest.length > 0 ? values : first;
|
|
77
|
+
}
|
|
78
|
+
return params;
|
|
79
|
+
},
|
|
80
|
+
getUrl: () => request.url,
|
|
81
|
+
getUserAgent: () => request.headers.get("user-agent") ?? ""
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
const toResponse = (instructions) => {
|
|
85
|
+
const headers = new Headers(instructions.headers);
|
|
86
|
+
const { body } = instructions;
|
|
87
|
+
if (body === void 0 || body === null) {
|
|
88
|
+
return new Response(void 0, { headers, status: instructions.status });
|
|
89
|
+
}
|
|
90
|
+
if (typeof body === "string") {
|
|
91
|
+
if (instructions.isHtml && !headers.has("content-type")) {
|
|
92
|
+
headers.set("content-type", "text/html; charset=utf-8");
|
|
93
|
+
}
|
|
94
|
+
return new Response(body, { headers, status: instructions.status });
|
|
95
|
+
}
|
|
96
|
+
return Response.json(body, { headers, status: instructions.status });
|
|
97
|
+
};
|
|
98
|
+
const withHeaders = (response, extra) => {
|
|
99
|
+
const headers = new Headers(response.headers);
|
|
100
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
101
|
+
headers.set(key, value);
|
|
102
|
+
}
|
|
103
|
+
return new Response(response.body, { headers, status: response.status, statusText: response.statusText });
|
|
104
|
+
};
|
|
105
|
+
const createChargeMiddleware = async (config, routeOverrides) => {
|
|
106
|
+
const server = await buildResourceServer(config);
|
|
107
|
+
const http = new x402HTTPResourceServer(server, { ...buildRoute(config), ...routeOverrides });
|
|
108
|
+
await http.initialize();
|
|
109
|
+
const handle = async (request, runHandler) => {
|
|
110
|
+
const url = new URL(request.url);
|
|
111
|
+
const context = {
|
|
112
|
+
adapter: createRequestAdapter(request, url),
|
|
113
|
+
method: request.method,
|
|
114
|
+
path: url.pathname,
|
|
115
|
+
paymentHeader: request.headers.get(PAYMENT_HEADER) ?? void 0
|
|
116
|
+
};
|
|
117
|
+
const result = await http.processHTTPRequest(context);
|
|
118
|
+
if (result.type === "no-payment-required") {
|
|
119
|
+
return runHandler();
|
|
120
|
+
}
|
|
121
|
+
if (result.type === "payment-error") {
|
|
122
|
+
return toResponse(result.response);
|
|
123
|
+
}
|
|
124
|
+
let response;
|
|
125
|
+
try {
|
|
126
|
+
response = await runHandler();
|
|
127
|
+
} catch (error) {
|
|
128
|
+
try {
|
|
129
|
+
await result.cancellationDispatcher.cancel({ error, reason: "handler_threw" });
|
|
130
|
+
} catch (cancelError) {
|
|
131
|
+
console.error("x402 charge: failed to cancel payment after the handler threw", cancelError);
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
const settlement = await http.processSettlement(result.paymentPayload, result.paymentRequirements, result.declaredExtensions, {
|
|
136
|
+
request: context,
|
|
137
|
+
responseHeaders: headerRecord(response.headers)
|
|
138
|
+
});
|
|
139
|
+
if (settlement.success) {
|
|
140
|
+
reportReceipt(config.onReceipt, settlement, routeOverrides?.resource ?? request.url);
|
|
141
|
+
return withHeaders(response, settlement.headers);
|
|
142
|
+
}
|
|
143
|
+
return toResponse(settlement.response);
|
|
144
|
+
};
|
|
145
|
+
return { handle };
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export { buildRoute, createChargeMiddleware, createRequestAdapter, reportReceipt, resolvePayTo, toResponse, withHeaders };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { HTTPFacilitatorClient } from '@x402/core/server';
|
|
2
|
+
import { resolveFacilitatorUrl } from './DEFAULT_FACILITATOR_URL-Cbz6kIqa.mjs';
|
|
3
|
+
|
|
4
|
+
const createFacilitatorClient = (config) => {
|
|
5
|
+
const url = resolveFacilitatorUrl(config);
|
|
6
|
+
if (config?.headers === void 0) {
|
|
7
|
+
return new HTTPFacilitatorClient({ url });
|
|
8
|
+
}
|
|
9
|
+
const headers = { ...config.headers };
|
|
10
|
+
return new HTTPFacilitatorClient({
|
|
11
|
+
createAuthHeaders: () => Promise.resolve({ settle: headers, supported: headers, verify: headers }),
|
|
12
|
+
url
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export { createFacilitatorClient };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { x402Client } from '@x402/core/client';
|
|
2
|
+
import { wrapFetchWithPayment } from '@x402/fetch';
|
|
3
|
+
import { assertBoundedPolicy, buildSpendPolicy, buildPaymentGuard, recordSpend, createSpendState } from './DEFAULT_STABLECOIN_DECIMALS-CSu5b5lD.mjs';
|
|
4
|
+
import { registerWallet } from './registerWallet-I4pVwq65.mjs';
|
|
5
|
+
|
|
6
|
+
const createPayFetch = async (config, deps) => {
|
|
7
|
+
assertBoundedPolicy(config.policy);
|
|
8
|
+
const client = new x402Client();
|
|
9
|
+
await registerWallet(client, config, deps);
|
|
10
|
+
const state = createSpendState();
|
|
11
|
+
client.registerPolicy(buildSpendPolicy(config.policy));
|
|
12
|
+
client.onBeforePaymentCreation(buildPaymentGuard(config.policy, state));
|
|
13
|
+
client.onAfterPaymentCreation(recordSpend(state));
|
|
14
|
+
return wrapFetchWithPayment(deps.fetch ?? globalThis.fetch, client);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export { createPayFetch };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createChargeMiddleware } from './createChargeMiddleware-BJkYJeFf.mjs';
|
|
2
|
+
|
|
3
|
+
const createProcedureChargeGate = (config) => {
|
|
4
|
+
const middlewareByFunction = /* @__PURE__ */ new Map();
|
|
5
|
+
return async (request, spec, dispatch) => {
|
|
6
|
+
let pending = middlewareByFunction.get(spec.functionPath);
|
|
7
|
+
if (pending === void 0) {
|
|
8
|
+
pending = createChargeMiddleware({ ...config, price: spec.price }, { resource: spec.functionPath }).catch((error) => {
|
|
9
|
+
middlewareByFunction.delete(spec.functionPath);
|
|
10
|
+
throw error;
|
|
11
|
+
});
|
|
12
|
+
middlewareByFunction.set(spec.functionPath, pending);
|
|
13
|
+
}
|
|
14
|
+
const middleware = await pending;
|
|
15
|
+
return middleware.handle(request, dispatch);
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export { createProcedureChargeGate };
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { LunoraError } from '@lunora/errors';
|
|
2
|
+
import { toCaip2, isEvmNetwork } from './EVM_NETWORKS-BhnYWUQ4.mjs';
|
|
3
|
+
|
|
4
|
+
const HEX_PRIVATE_KEY = /^0x[0-9a-fA-F]{64}$/;
|
|
5
|
+
const requireSecret = async (getSecret, name) => {
|
|
6
|
+
const value = await getSecret(name);
|
|
7
|
+
if (value === void 0 || value.length === 0) {
|
|
8
|
+
throw new LunoraError("ENV_INVALID", `x402 pay: secret "${name}" is not set — the agent wallet has no key to sign with.`);
|
|
9
|
+
}
|
|
10
|
+
return value;
|
|
11
|
+
};
|
|
12
|
+
const assertSignerFamily = (signer, evm) => {
|
|
13
|
+
const looksEvm = signer.address.startsWith("0x");
|
|
14
|
+
if (evm && !looksEvm) {
|
|
15
|
+
throw new LunoraError("ENV_INVALID", `x402 pay: the supplied signer address "${signer.address}" is not an EVM (0x…) address, but the network is EVM.`);
|
|
16
|
+
}
|
|
17
|
+
if (!evm && looksEvm) {
|
|
18
|
+
throw new LunoraError("ENV_INVALID", `x402 pay: the supplied signer address "${signer.address}" is an EVM (0x…) address, but the network is Solana.`);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const resolveCdpEvmAccount = async (signer, getSecret) => {
|
|
22
|
+
let cdpModule;
|
|
23
|
+
try {
|
|
24
|
+
cdpModule = await import('@coinbase/cdp-sdk');
|
|
25
|
+
} catch {
|
|
26
|
+
throw new LunoraError(
|
|
27
|
+
"ENV_INVALID",
|
|
28
|
+
'x402 pay: CDP-managed custody needs the optional @coinbase/cdp-sdk peer — install it, or use "raw-key"/"signer" custody instead.'
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const [apiKeyId, apiKeySecret, walletSecret] = await Promise.all([
|
|
32
|
+
requireSecret(getSecret, signer.apiKeyIdSecretName ?? "CDP_API_KEY_ID"),
|
|
33
|
+
requireSecret(getSecret, signer.apiKeySecretName ?? "CDP_API_KEY_SECRET"),
|
|
34
|
+
requireSecret(getSecret, signer.walletSecretName ?? "CDP_WALLET_SECRET")
|
|
35
|
+
]);
|
|
36
|
+
const cdp = new cdpModule.CdpClient({ apiKeyId, apiKeySecret, walletSecret });
|
|
37
|
+
return cdp.evm.getOrCreateAccount({ name: signer.account });
|
|
38
|
+
};
|
|
39
|
+
const resolveEvmAccount = async (privateKey) => {
|
|
40
|
+
const key = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
|
|
41
|
+
if (!HEX_PRIVATE_KEY.test(key)) {
|
|
42
|
+
throw new LunoraError("ENV_INVALID", "x402 pay: the EVM wallet key must be a 32-byte hex private key (64 hex chars, optional 0x prefix).");
|
|
43
|
+
}
|
|
44
|
+
const { privateKeyToAccount } = await import('viem/accounts');
|
|
45
|
+
return privateKeyToAccount(key);
|
|
46
|
+
};
|
|
47
|
+
const resolveSvmSigner = async (secret) => {
|
|
48
|
+
const trimmed = secret.trim();
|
|
49
|
+
const { createKeyPairSignerFromBytes, createKeyPairSignerFromPrivateKeyBytes, getBase58Encoder } = await import('@solana/kit');
|
|
50
|
+
let bytes;
|
|
51
|
+
if (trimmed.startsWith("[")) {
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = JSON.parse(trimmed);
|
|
55
|
+
} catch {
|
|
56
|
+
throw new LunoraError("ENV_INVALID", "x402 pay: the Solana wallet key looks like a JSON byte array but is not valid JSON.");
|
|
57
|
+
}
|
|
58
|
+
if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "number")) {
|
|
59
|
+
throw new LunoraError("ENV_INVALID", "x402 pay: the Solana wallet key JSON must be an array of byte values.");
|
|
60
|
+
}
|
|
61
|
+
bytes = Uint8Array.from(parsed);
|
|
62
|
+
} else {
|
|
63
|
+
try {
|
|
64
|
+
bytes = Uint8Array.from(getBase58Encoder().encode(trimmed));
|
|
65
|
+
} catch {
|
|
66
|
+
throw new LunoraError("ENV_INVALID", "x402 pay: the Solana wallet key must be a base58 secret key or a JSON byte array.");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (bytes.length === 64) {
|
|
70
|
+
return createKeyPairSignerFromBytes(bytes);
|
|
71
|
+
}
|
|
72
|
+
if (bytes.length === 32) {
|
|
73
|
+
return createKeyPairSignerFromPrivateKeyBytes(bytes);
|
|
74
|
+
}
|
|
75
|
+
throw new LunoraError(
|
|
76
|
+
"ENV_INVALID",
|
|
77
|
+
`x402 pay: the Solana wallet key must decode to 32 or 64 bytes (got ${String(bytes.length)}). Provide a base58 secret key or a JSON byte array.`
|
|
78
|
+
);
|
|
79
|
+
};
|
|
80
|
+
const registerWallet = async (client, config, deps) => {
|
|
81
|
+
const network = toCaip2(config.network);
|
|
82
|
+
const { signer } = config;
|
|
83
|
+
const evm = isEvmNetwork(config.network);
|
|
84
|
+
let account;
|
|
85
|
+
if (signer.type === "signer") {
|
|
86
|
+
assertSignerFamily(signer.signer, evm);
|
|
87
|
+
account = signer.signer;
|
|
88
|
+
} else if (signer.type === "cdp") {
|
|
89
|
+
if (!evm) {
|
|
90
|
+
throw new LunoraError(
|
|
91
|
+
"NOT_IMPLEMENTED",
|
|
92
|
+
`x402 pay: CDP-managed Solana custody (account "${signer.account}") is not wired — a CDP Solana account is not a @solana/kit signer. Build a @solana/kit signer around it and pass it via the { type: "signer" } escape hatch, or use "raw-key".`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
account = await resolveCdpEvmAccount(signer, deps.getSecret);
|
|
96
|
+
} else {
|
|
97
|
+
const secret = await requireSecret(deps.getSecret, signer.secretName);
|
|
98
|
+
account = evm ? await resolveEvmAccount(secret) : await resolveSvmSigner(secret);
|
|
99
|
+
}
|
|
100
|
+
if (evm) {
|
|
101
|
+
const { registerExactEvmScheme } = await import('@x402/evm/exact/client');
|
|
102
|
+
registerExactEvmScheme(client, { networks: [network], signer: account });
|
|
103
|
+
} else {
|
|
104
|
+
const { registerExactSvmScheme } = await import('@x402/svm/exact/client');
|
|
105
|
+
registerExactSvmScheme(client, { networks: [network], signer: account });
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export { registerWallet, resolveEvmAccount, resolveSvmSigner };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const toReceipt = (settlement, context) => {
|
|
2
|
+
return {
|
|
3
|
+
amount: settlement.amount ?? settlement.requirements.amount,
|
|
4
|
+
asset: settlement.requirements.asset,
|
|
5
|
+
from: settlement.payer,
|
|
6
|
+
network: settlement.network,
|
|
7
|
+
resource: context.resource,
|
|
8
|
+
to: settlement.requirements.payTo,
|
|
9
|
+
ts: context.ts,
|
|
10
|
+
tx: settlement.transaction
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
const toPaymentEventRow = (receipt) => {
|
|
14
|
+
return {
|
|
15
|
+
processedAt: receipt.ts,
|
|
16
|
+
provider: "x402",
|
|
17
|
+
providerEventId: receipt.tx,
|
|
18
|
+
type: "x402.settled"
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export { toPaymentEventRow, toReceipt };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createChargeMiddleware } from './createChargeMiddleware-BJkYJeFf.mjs';
|
|
2
|
+
|
|
3
|
+
const withX402 = (config, handler) => {
|
|
4
|
+
let pending;
|
|
5
|
+
return async (context, request) => {
|
|
6
|
+
pending ??= createChargeMiddleware(config).catch((error) => {
|
|
7
|
+
pending = void 0;
|
|
8
|
+
throw error;
|
|
9
|
+
});
|
|
10
|
+
const middleware = await pending;
|
|
11
|
+
return middleware.handle(request, () => handler(context, request));
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export { withX402 };
|