@lunora/x402 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,404 @@
1
+ import { ClientEvmSigner } from '@x402/evm';
2
+ import { ClientSvmSigner } from '@x402/svm';
3
+ import { ProcessSettleSuccessResponse } from '@x402/core/http';
4
+ import { BeforePaymentCreationHook, PaymentPolicy, OnPaymentCreationFailureHook } 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
+ * @experimental
12
+ */
13
+ interface X402Receipt {
14
+ /** Settled amount in the asset's atomic base units (USDC: 6 decimals), as an exact string. */
15
+ readonly amount: string;
16
+ /** The settled asset's contract / mint address (e.g. Base USDC). */
17
+ readonly asset: string;
18
+ /** The payer's wallet address, when the facilitator reports it. */
19
+ readonly from: string | undefined;
20
+ /** The settlement network as a CAIP-2 id (e.g. `eip155:8453`). */
21
+ readonly network: string;
22
+ /** The gated resource this payment bought (a URL, or a procedure's `file:function` id). */
23
+ readonly resource: string;
24
+ /** The payout wallet the funds settled to (the merchant recipient). */
25
+ readonly to: string;
26
+ /** When the receipt was produced (epoch milliseconds). */
27
+ readonly ts: number;
28
+ /** On-chain settlement transaction id / hash. */
29
+ readonly tx: string;
30
+ }
31
+ /**
32
+ * A one-way, opt-in sink for settled-payment receipts. Wire it via
33
+ * `config.onReceipt`. It is best-effort telemetry — the middleware fires it after
34
+ * settlement, does not block the paid response on it, and swallows any error it
35
+ * throws — so a sink must never rely on being awaited or on its failures
36
+ * surfacing.
37
+ * @experimental
38
+ */
39
+ type X402ReceiptSink = (receipt: X402Receipt) => Promise<void> | void;
40
+ /**
41
+ * Normalise a successful facilitator settlement into an {@link X402Receipt}.
42
+ * `resource` (the gated URL or procedure id) and `ts` are supplied by the caller —
43
+ * the settlement result carries neither. Prefers the actual settled `amount`
44
+ * (present for `upto`-scheme partial settlements) and falls back to the route's
45
+ * required amount for `exact`.
46
+ * @experimental
47
+ */
48
+ declare const toReceipt: (settlement: ProcessSettleSuccessResponse, context: {
49
+ readonly resource: string;
50
+ readonly ts: number;
51
+ }) => X402Receipt;
52
+ /**
53
+ * A row for `@lunora/payment`'s durable `events` table. Deliberately a plain
54
+ * structural type — building one imports nothing from `@lunora/payment`, so the
55
+ * rails stay decoupled.
56
+ * @experimental
57
+ */
58
+ interface PaymentEventRow {
59
+ /** Epoch milliseconds the settlement was recorded. */
60
+ readonly processedAt: number;
61
+ /** The rail that produced the event. */
62
+ readonly provider: "x402";
63
+ /** The settlement tx hash — the natural unique event id (the table is unique on `(provider, providerEventId)`). */
64
+ readonly providerEventId: string;
65
+ /** The event kind, namespaced to the x402 rail. */
66
+ readonly type: "x402.settled";
67
+ }
68
+ /**
69
+ * Shape a receipt as a row for `@lunora/payment`'s durable `events` table, so a
70
+ * settled x402 payment shows in Studio's Payments panel (its recent-events card)
71
+ * with ZERO coupling: this returns a plain object matching that table's
72
+ * documented column contract (`provider` / `providerEventId` / `type` /
73
+ * `processedAt`, unique on `(provider, providerEventId)`) and imports nothing
74
+ * from `@lunora/payment`. Insert it from a mutation ctx:
75
+ *
76
+ * ```ts
77
+ * onReceipt: (receipt) => ctx.db.insert("events", toPaymentEventRow(receipt)),
78
+ * ```
79
+ *
80
+ * The source of truth for the column contract is `@lunora/payment`'s `events`
81
+ * table (`packages/payment/src/schema.ts`). Amount / from / to / resource are
82
+ * intentionally not on this row — that card renders none of them; read them off
83
+ * the {@link X402Receipt} (e.g. into your own revenue table) if you need them.
84
+ * @experimental
85
+ */
86
+ declare const toPaymentEventRow: (receipt: X402Receipt) => PaymentEventRow;
87
+ /**
88
+ * Network identity for `@lunora/x402`.
89
+ *
90
+ * `@x402/core` v2 speaks **CAIP-2** chain ids (`eip155:8453` for Base,
91
+ * `solana:5eyk…` for Solana mainnet) — `type Network = ` `${string}:${string}` ``.
92
+ * Lunora keeps ergonomic **friendly** names (`"base"`, `"base-sepolia"`) as the
93
+ * public surface and maps them to CAIP-2 here, at the single seam where we hand a
94
+ * network to the SDK. A raw CAIP-2 string is also accepted as a power-user escape
95
+ * hatch (e.g. a chain we don't yet have a friendly alias for).
96
+ *
97
+ * The friendly set is intentionally scoped to chains `@x402/evm` / `@x402/svm`
98
+ * can settle the ergonomic `price:"$0.01"` path on out of the box (i.e. chains in
99
+ * their `DEFAULT_STABLECOINS` registry). Notably that excludes Optimism and
100
+ * Avalanche today — advertising them would 500 at settlement — so they are not
101
+ * friendly aliases; a caller who needs them can still pass a raw CAIP-2 id with an
102
+ * explicit asset.
103
+ */
104
+ /**
105
+ * A CAIP-2 chain identifier, e.g. `"eip155:8453"` (Base) or `"solana:5eyk…"`.
106
+ * @experimental
107
+ */
108
+ type Caip2 = `${string}:${string}`;
109
+ /**
110
+ * Friendly network names Lunora maps to CAIP-2 for `@x402/core`.
111
+ * @experimental
112
+ */
113
+ type FriendlyNetwork = "arbitrum" | "arbitrum-sepolia" | "base" | "base-sepolia" | "ethereum" | "polygon" | "solana" | "solana-devnet";
114
+ /**
115
+ * A network Lunora can settle on: a {@link FriendlyNetwork} alias (mapped to
116
+ * CAIP-2 internally) or a raw {@link Caip2} id for chains without a friendly name.
117
+ * @experimental
118
+ */
119
+ type X402Network = Caip2 | FriendlyNetwork;
120
+ /**
121
+ * Friendly name → CAIP-2 id. Values verified against `@x402/evm` and `@x402/svm`
122
+ * `DEFAULT_STABLECOINS` at 2.17.0. `base` / `base-sepolia` are the primary
123
+ * prod / test pair.
124
+ * @experimental
125
+ */
126
+ declare const NETWORK_TO_CAIP2: {
127
+ readonly arbitrum: "eip155:42161";
128
+ readonly "arbitrum-sepolia": "eip155:421614";
129
+ readonly base: "eip155:8453";
130
+ readonly "base-sepolia": "eip155:84532";
131
+ readonly ethereum: "eip155:1";
132
+ readonly polygon: "eip155:137";
133
+ readonly solana: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
134
+ readonly "solana-devnet": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
135
+ };
136
+ /**
137
+ * EVM friendly networks (signed via `@x402/evm` + viem).
138
+ * @experimental
139
+ */
140
+ declare const EVM_NETWORKS: readonly ["arbitrum", "arbitrum-sepolia", "base", "base-sepolia", "ethereum", "polygon"];
141
+ /**
142
+ * Solana friendly networks (signed via `@x402/svm`).
143
+ * @experimental
144
+ */
145
+ declare const SVM_NETWORKS: readonly ["solana", "solana-devnet"];
146
+ /**
147
+ * Resolve a network to its CAIP-2 id. Friendly aliases are looked up; a value
148
+ * that already looks like CAIP-2 (`namespace:reference`) passes through.
149
+ * @experimental
150
+ */
151
+ declare const toCaip2: (network: X402Network) => Caip2;
152
+ /**
153
+ * True when `network` settles on an EVM chain (viem signer path).
154
+ * @experimental
155
+ */
156
+ declare const isEvmNetwork: (network: X402Network) => boolean;
157
+ /**
158
+ * True when `network` settles on Solana (`@x402/svm` signer path).
159
+ * @experimental
160
+ */
161
+ declare const isSvmNetwork: (network: X402Network) => boolean;
162
+ /**
163
+ * USDC — and every asset in `@x402/evm` / `@x402/svm`'s `DEFAULT_STABLECOINS` —
164
+ * uses 6 decimals, so a USD price converts to atomic base units at `10 ** 6`.
165
+ * Override per {@link SpendPolicy.decimals} only for a custom, non-6-decimal asset.
166
+ * @experimental
167
+ */
168
+ declare const DEFAULT_STABLECOIN_DECIMALS = 6;
169
+ /**
170
+ * Spend limits and approval gates for an agent wallet. At least one bound must be
171
+ * set — see {@link assertBoundedPolicy} — or the pay rail refuses to build.
172
+ *
173
+ * Caps are denominated in USD (the stablecoin's dollar value); addresses and
174
+ * networks are matched against the requirement the server offers.
175
+ * @experimental
176
+ */
177
+ interface SpendPolicy {
178
+ /** Network allowlist. When set, only these networks may be paid on. */
179
+ readonly allowedNetworks?: ReadonlyArray<X402Network>;
180
+ /** Recipient allowlist. When set, only these `payTo` addresses may be paid. */
181
+ readonly allowedRecipients?: ReadonlyArray<string>;
182
+ /** Stablecoin decimals for USD→atomic conversion (default {@link DEFAULT_STABLECOIN_DECIMALS}). */
183
+ readonly decimals?: number;
184
+ /** Hard ceiling on a single payment, in USD. */
185
+ readonly maxPerCall?: X402Price;
186
+ /** Hard ceiling on cumulative spend across this wallet's lifetime, in USD. */
187
+ readonly maxPerRun?: X402Price;
188
+ /**
189
+ * Approval gate. Called with the selected requirement before signing; return
190
+ * `false` (or reject) to refuse the payment. Use for human-in-the-loop or any
191
+ * dynamic rule the static caps can't express.
192
+ */
193
+ readonly onPaymentRequired?: (requirement: PaymentRequirements) => Promise<boolean> | boolean;
194
+ }
195
+ /**
196
+ * A running spend ledger the per-run cap is measured (and reserved) against.
197
+ * @experimental
198
+ */
199
+ interface SpendState {
200
+ /** Reserve a payment (atomic base units) against the running total, before it is signed. */
201
+ readonly add: (amount: bigint) => void;
202
+ /** Release a previously reserved amount (atomic base units) — e.g. a declined or failed payment. Clamps at 0. */
203
+ readonly release: (amount: bigint) => void;
204
+ /** Cumulative spend so far, in atomic base units. */
205
+ readonly spentAtomic: bigint;
206
+ }
207
+ /**
208
+ * A fresh spend ledger. One per wallet instance; the guard reserves into it and
209
+ * releases from it.
210
+ * @experimental
211
+ */
212
+ declare const createSpendState: () => SpendState;
213
+ /**
214
+ * Convert a USD amount (`0.01`, `"0.01"`, or the `"$0.01"` shorthand) to atomic
215
+ * stablecoin base units, exactly — parsed digit-by-digit so no binary-float drift
216
+ * can round a cap the wrong way. Throws on a malformed amount (including
217
+ * exponential notation like `"1e-7"`, which a decimal string never needs).
218
+ * @experimental
219
+ */
220
+ declare const usdToAtomic: (usd: X402Price, decimals?: number) => bigint;
221
+ /**
222
+ * A `PaymentPolicy` that narrows the server's offered requirements to those a
223
+ * bounded wallet may pay: within the per-call cap, to an allowed recipient, on an
224
+ * allowed network. An empty result means the client cannot pay — fail-closed.
225
+ * @experimental
226
+ */
227
+ declare const buildSpendPolicy: (policy: SpendPolicy) => PaymentPolicy;
228
+ /**
229
+ * A `BeforePaymentCreationHook` enforcing the stateful bounds the stateless
230
+ * {@link buildSpendPolicy} filter can't: the cumulative per-run cap and the async
231
+ * confirmation gate. Aborts (no signature) when either would be violated.
232
+ *
233
+ * The per-run cap is *reserved* into `state` as soon as the check passes — before
234
+ * the `await policy.onPaymentRequired` below, and before `@x402/core` ever attempts
235
+ * to sign — not recorded afterwards. This closes a check-then-act race: without an
236
+ * atomic reserve, N concurrent payments could each read the same `spentAtomic`,
237
+ * all pass the cap check, and all record, overspending the cap by up to
238
+ * (N−1)×maxPerCall. A declined confirmation releases the reservation before this
239
+ * hook returns; {@link releaseSpendOnFailure} releases it if the signature itself
240
+ * later fails. The reservation is intentionally *not* released on success — a
241
+ * committed payment stays counted.
242
+ * @experimental
243
+ */
244
+ declare const buildPaymentGuard: (policy: SpendPolicy, state: SpendState) => BeforePaymentCreationHook;
245
+ /**
246
+ * An `OnPaymentCreationFailureHook` that releases a reservation
247
+ * {@link buildPaymentGuard} made when the scheme's signature creation itself
248
+ * throws (network error, wallet error, …) after the guard already approved and
249
+ * reserved the amount. Without this, a failed signature would permanently
250
+ * over-count against the per-run cap for the rest of the run — fail-closed, but
251
+ * needlessly so when the client (`wrapFetchWithPayment`) may retry.
252
+ * @experimental
253
+ */
254
+ declare const releaseSpendOnFailure: (state: SpendState) => OnPaymentCreationFailureHook;
255
+ /**
256
+ * Guard at wallet-build time: refuse a policy with no bound whatsoever. Signing
257
+ * money on an agent's behalf with unlimited spend authority is never the intent,
258
+ * so this fails loudly rather than defaulting to unbounded.
259
+ *
260
+ * `allowedNetworks` / `allowedRecipients` narrow *where* a payment can go, but
261
+ * neither caps *how much* — a policy with only an allowlist still authorises
262
+ * unlimited spend to any recipient it permits. Only `maxPerCall`, `maxPerRun`, or
263
+ * a dynamic `onPaymentRequired` gate actually bound spend, so only those count here.
264
+ * @experimental
265
+ */
266
+ declare const assertBoundedPolicy: (policy: SpendPolicy) => void;
267
+ /**
268
+ * The public, Coinbase-operated facilitator (verify + settle). It needs no API
269
+ * key. Override with a self-hosted or CDP facilitator via {@link FacilitatorConfig}.
270
+ * @experimental
271
+ */
272
+ declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
273
+ /**
274
+ * How to reach a facilitator's `/verify` + `/settle` endpoints.
275
+ * @experimental
276
+ */
277
+ interface FacilitatorConfig {
278
+ /** Extra headers for a private facilitator (e.g. a CDP bearer token). */
279
+ readonly headers?: Record<string, string>;
280
+ /** Base URL. Defaults to {@link DEFAULT_FACILITATOR_URL}. */
281
+ readonly url?: string;
282
+ }
283
+ /**
284
+ * A resource's price, as a USD-denominated decimal string (`"0.01"`, or the
285
+ * `"$0.01"` shorthand) or a number of dollars (`0.01`). The scheme resolves it
286
+ * to the network's stablecoin base units (USDC has 6 decimals) at challenge
287
+ * time. (Kept `number | string` rather than a `` `$${string}` `` template
288
+ * member — the template is subsumed by `string`, so it only adds noise.)
289
+ * @experimental
290
+ */
291
+ type X402Price = number | string;
292
+ /**
293
+ * An EVM recipient address (the merchant wallet that receives settlement).
294
+ * @experimental
295
+ */
296
+ type EvmAddress = `0x${string}`;
297
+ /**
298
+ * Recipient wallet the facilitator settles payments to, per network family.
299
+ * @experimental
300
+ */
301
+ interface X402Recipient {
302
+ /** EVM payout address (required for EVM networks). */
303
+ readonly evm?: EvmAddress;
304
+ /** Solana payout address, base58 (required for SVM networks). */
305
+ readonly svm?: string;
306
+ }
307
+ /**
308
+ * Server-side (charge rail) config. The server needs only a **recipient
309
+ * address** — no private key — because the facilitator performs settlement.
310
+ * @experimental
311
+ */
312
+ interface X402ChargeConfig {
313
+ readonly facilitator?: FacilitatorConfig;
314
+ /** Network this resource settles on. */
315
+ readonly network: X402Network;
316
+ /**
317
+ * Opt-in, one-way telemetry sink fired once per settled payment. Best-effort:
318
+ * it runs after settlement, never blocks the paid response, and its errors are
319
+ * swallowed. Use it to mirror x402 revenue into a durable table / `@lunora/payment`'s
320
+ * `events` table (see `toPaymentEventRow`) so it surfaces in Studio.
321
+ */
322
+ readonly onReceipt?: X402ReceiptSink;
323
+ /** Default price for a gated resource; per-resource overrides win. */
324
+ readonly price: X402Price;
325
+ /** Payout wallet(s). */
326
+ readonly recipient: X402Recipient;
327
+ }
328
+ /**
329
+ * Client-side (pay rail) config. The signer holds spending authority, so the
330
+ * pay rail is ActionCtx-only and MUST be paired with a spend `policy` — the pay
331
+ * rail refuses to build if the policy is unbounded.
332
+ * @experimental
333
+ */
334
+ interface X402PayConfig {
335
+ /** Network to transact on. Determines the signer family (EVM vs SVM). */
336
+ readonly network: X402Network;
337
+ /** Mandatory spend limits + approval gates. An unbounded policy is refused. */
338
+ readonly policy: SpendPolicy;
339
+ /** How the agent wallet is custodied (raw key, a user-supplied signer, or CDP-managed). */
340
+ readonly signer: X402SignerConfig;
341
+ }
342
+ /**
343
+ * CDP-managed wallet custody via `@coinbase/cdp-sdk` (an optional peer). The SDK
344
+ * gets-or-creates a named server account and signs the x402 EIP-712 payment
345
+ * authorization with it — no private key ever leaves Coinbase. Needs three CDP
346
+ * credentials, read from `ctx.secrets` under names that default to the SDK's own
347
+ * env-var names; override them if your secrets are named differently. (Note
348
+ * `@coinbase/x402` is a facilitator-auth helper, not a signer provider — CDP
349
+ * custody is `@coinbase/cdp-sdk`.) EVM only today; for CDP on Solana, build a
350
+ * `@solana/kit` signer around your CDP account and pass it via the `"signer"`
351
+ * escape hatch.
352
+ * @experimental
353
+ */
354
+ interface X402CdpSignerConfig {
355
+ /** CDP account name to get-or-create and sign with. */
356
+ readonly account: string;
357
+ /** `ctx.secrets` name for the CDP API key id. Default `"CDP_API_KEY_ID"`. */
358
+ readonly apiKeyIdSecretName?: string;
359
+ /** `ctx.secrets` name for the CDP API key secret. Default `"CDP_API_KEY_SECRET"`. */
360
+ readonly apiKeySecretName?: string;
361
+ readonly type: "cdp";
362
+ /** `ctx.secrets` name for the CDP wallet secret. Default `"CDP_WALLET_SECRET"`. */
363
+ readonly walletSecretName?: string;
364
+ }
365
+ /**
366
+ * Wallet custody for the pay rail — three shapes.
367
+ *
368
+ * `"raw-key"` resolves a private key from `ctx.secrets` (viem for EVM, a
369
+ * `@solana/kit` keypair for Solana) — simplest, self-custodied.
370
+ *
371
+ * `"signer"` is the escape hatch: hand in a signer you already built — any
372
+ * `@x402/evm` `ClientEvmSigner` (a viem account from Turnkey, Privy, an AWS/GCP
373
+ * KMS `toAccount`, CDP's viem adapter, …) on an EVM network, or an `@x402/svm`
374
+ * `ClientSvmSigner` (a `@solana/kit` `TransactionSigner`) on Solana. Adapt any
375
+ * custody provider to the structural signer and pass it here; `@lunora/x402`
376
+ * takes no dependency on the provider's SDK.
377
+ *
378
+ * `"cdp"` is a Coinbase-managed wallet via `@coinbase/cdp-sdk`
379
+ * ({@link X402CdpSignerConfig}).
380
+ *
381
+ * Wired today: raw-key (EVM + SVM), the user-supplied signer (both families),
382
+ * and CDP-managed EVM custody. CDP on Solana is not yet wired — use the escape
383
+ * hatch.
384
+ * @experimental
385
+ */
386
+ type X402SignerConfig = X402CdpSignerConfig | {
387
+ /** Name of the `ctx.secrets` entry holding the private key. */
388
+ readonly secretName: string;
389
+ readonly type: "raw-key";
390
+ } | {
391
+ /**
392
+ * A pre-built signer you own: an EVM `ClientEvmSigner` (viem account) on
393
+ * an EVM network, or an SVM `ClientSvmSigner` (`@solana/kit`
394
+ * `TransactionSigner`) on Solana. Must match the config `network`'s family.
395
+ */
396
+ readonly signer: ClientEvmSigner | ClientSvmSigner;
397
+ readonly type: "signer";
398
+ };
399
+ /**
400
+ * Resolve a facilitator's base URL, applying the public default.
401
+ * @experimental
402
+ */
403
+ declare const resolveFacilitatorUrl: (facilitator?: FacilitatorConfig) => string;
404
+ 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, releaseSpendOnFailure as v, usdToAtomic as w, toPaymentEventRow as x, toReceipt as y };