@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.
@@ -0,0 +1,76 @@
1
+ import { F as FacilitatorConfig, c as X402ChargeConfig, f as X402Price } from "../packem_shared/config.d-CddwCiBm.mjs";
2
+ export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, type a as EvmAddress, type P as PaymentEventRow, type d as X402Network, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, x as toPaymentEventRow, y as toReceipt } from "../packem_shared/config.d-CddwCiBm.mjs";
3
+ import { HTTPFacilitatorClient } from '@x402/core/server';
4
+ import { RouteConfig } from '@x402/core/http';
5
+ import '@x402/evm';
6
+ import '@x402/svm';
7
+ import '@x402/core/client';
8
+ import '@x402/core/types';
9
+ /**
10
+ * Build an `@x402/core` facilitator client from Lunora's {@link FacilitatorConfig}.
11
+ *
12
+ * `config.headers` (e.g. a CDP bearer token) are applied to every facilitator
13
+ * call — `@x402/core` splits auth per endpoint (`verify` / `settle` /
14
+ * `supported`), so the same header map is handed to each. With no config the
15
+ * client points at the public {@link resolveFacilitatorUrl default} and sends no
16
+ * auth headers.
17
+ */
18
+ declare const createFacilitatorClient: (config?: FacilitatorConfig) => HTTPFacilitatorClient;
19
+ /** A handler shaped like a Lunora HTTP action: `(context, request) => Response`. */
20
+ type HttpActionHandler<Context> = (context: Context, request: Request) => Promise<Response> | Response;
21
+ /**
22
+ * Gate `handler` behind an x402 paywall described by `config`. Returns a handler
23
+ * of the same shape, ready to pass to `httpAction`.
24
+ */
25
+ declare const withX402: <Context>(config: X402ChargeConfig, handler: HttpActionHandler<Context>) => HttpActionHandler<Context>;
26
+ /** Runs the protected resource handler, producing the Response to gate. */
27
+ type ChargeHandler = () => Promise<Response> | Response;
28
+ /** A prepared, initialised paywall. Build once (it fetches facilitator support), reuse per request. */
29
+ interface ChargeMiddleware {
30
+ /** Gate `request`: challenge / verify / settle around `runHandler`. */
31
+ handle: (request: Request, runHandler: ChargeHandler) => Promise<Response>;
32
+ }
33
+ /**
34
+ * Route metadata a caller can layer onto the generated catch-all route. The
35
+ * procedure gate sets `resource` to the `functionPath` so the x402 challenge
36
+ * names the paid function (x402 core falls back to the request URL otherwise —
37
+ * every RPC POSTs to the same `/_lunora/rpc`, so the URL can't tell two paid
38
+ * procedures apart).
39
+ */
40
+ type ChargeRouteOverrides = Pick<RouteConfig, "description" | "resource">;
41
+ /**
42
+ * Build and initialise a {@link ChargeMiddleware} for `config`. Fetches
43
+ * facilitator support once (via `initialize()`), so call this once per config
44
+ * and reuse the result across requests. `routeOverrides` layers extra route
45
+ * metadata (e.g. `resource`) onto the generated catch-all route.
46
+ */
47
+ declare const createChargeMiddleware: (config: X402ChargeConfig, routeOverrides?: ChargeRouteOverrides) => Promise<ChargeMiddleware>;
48
+ /**
49
+ * Charge config for the procedure gate: the worker-level settlement vocabulary
50
+ * (network, recipient, facilitator) minus `price` — price is per-procedure and
51
+ * arrives with each {@link X402ProcedureSpec}.
52
+ */
53
+ type X402ProcedureChargeConfig = Omit<X402ChargeConfig, "price">;
54
+ /** The per-RPC charge spec the runtime passes the gate for each paid dispatch. */
55
+ interface X402ProcedureSpec {
56
+ /** The `file:function` id of the paid procedure; becomes the x402 challenge `resource`. */
57
+ readonly functionPath: string;
58
+ /** USD price declared by the procedure's `.x402({ price })` modifier. */
59
+ readonly price: X402Price;
60
+ }
61
+ /**
62
+ * Gate one paid RPC. Returns a real `402` + `PAYMENT-REQUIRED` challenge when the
63
+ * request is unpaid, or the dispatched response (with `X-PAYMENT-RESPONSE`
64
+ * attached) once the client's `X-PAYMENT` is verified and settled. `dispatch`
65
+ * runs the actual shard forward — it is only invoked after payment is verified.
66
+ */
67
+ type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispatch: () => Promise<Response>) => Promise<Response>;
68
+ /**
69
+ * Build the injectable procedure charge gate for `config`. One initialised
70
+ * {@link ChargeMiddleware} is memoised per `functionPath` (each bakes that
71
+ * function's price + `resource`), since `createChargeMiddleware` fetches
72
+ * facilitator support on first use. A failed init is not cached, so a transient
73
+ * facilitator outage retries on the next request.
74
+ */
75
+ declare const createProcedureChargeGate: (config: X402ProcedureChargeConfig) => X402ProcedureChargeGate;
76
+ export { type ChargeHandler, type ChargeMiddleware, type ChargeRouteOverrides, type FacilitatorConfig, type HttpActionHandler, type X402ChargeConfig, type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createFacilitatorClient, createProcedureChargeGate, withX402 };
@@ -0,0 +1,76 @@
1
+ import { F as FacilitatorConfig, c as X402ChargeConfig, f as X402Price } from "../packem_shared/config.d-CddwCiBm.js";
2
+ export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, type a as EvmAddress, type P as PaymentEventRow, type d as X402Network, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, x as toPaymentEventRow, y as toReceipt } from "../packem_shared/config.d-CddwCiBm.js";
3
+ import { HTTPFacilitatorClient } from '@x402/core/server';
4
+ import { RouteConfig } from '@x402/core/http';
5
+ import '@x402/evm';
6
+ import '@x402/svm';
7
+ import '@x402/core/client';
8
+ import '@x402/core/types';
9
+ /**
10
+ * Build an `@x402/core` facilitator client from Lunora's {@link FacilitatorConfig}.
11
+ *
12
+ * `config.headers` (e.g. a CDP bearer token) are applied to every facilitator
13
+ * call — `@x402/core` splits auth per endpoint (`verify` / `settle` /
14
+ * `supported`), so the same header map is handed to each. With no config the
15
+ * client points at the public {@link resolveFacilitatorUrl default} and sends no
16
+ * auth headers.
17
+ */
18
+ declare const createFacilitatorClient: (config?: FacilitatorConfig) => HTTPFacilitatorClient;
19
+ /** A handler shaped like a Lunora HTTP action: `(context, request) => Response`. */
20
+ type HttpActionHandler<Context> = (context: Context, request: Request) => Promise<Response> | Response;
21
+ /**
22
+ * Gate `handler` behind an x402 paywall described by `config`. Returns a handler
23
+ * of the same shape, ready to pass to `httpAction`.
24
+ */
25
+ declare const withX402: <Context>(config: X402ChargeConfig, handler: HttpActionHandler<Context>) => HttpActionHandler<Context>;
26
+ /** Runs the protected resource handler, producing the Response to gate. */
27
+ type ChargeHandler = () => Promise<Response> | Response;
28
+ /** A prepared, initialised paywall. Build once (it fetches facilitator support), reuse per request. */
29
+ interface ChargeMiddleware {
30
+ /** Gate `request`: challenge / verify / settle around `runHandler`. */
31
+ handle: (request: Request, runHandler: ChargeHandler) => Promise<Response>;
32
+ }
33
+ /**
34
+ * Route metadata a caller can layer onto the generated catch-all route. The
35
+ * procedure gate sets `resource` to the `functionPath` so the x402 challenge
36
+ * names the paid function (x402 core falls back to the request URL otherwise —
37
+ * every RPC POSTs to the same `/_lunora/rpc`, so the URL can't tell two paid
38
+ * procedures apart).
39
+ */
40
+ type ChargeRouteOverrides = Pick<RouteConfig, "description" | "resource">;
41
+ /**
42
+ * Build and initialise a {@link ChargeMiddleware} for `config`. Fetches
43
+ * facilitator support once (via `initialize()`), so call this once per config
44
+ * and reuse the result across requests. `routeOverrides` layers extra route
45
+ * metadata (e.g. `resource`) onto the generated catch-all route.
46
+ */
47
+ declare const createChargeMiddleware: (config: X402ChargeConfig, routeOverrides?: ChargeRouteOverrides) => Promise<ChargeMiddleware>;
48
+ /**
49
+ * Charge config for the procedure gate: the worker-level settlement vocabulary
50
+ * (network, recipient, facilitator) minus `price` — price is per-procedure and
51
+ * arrives with each {@link X402ProcedureSpec}.
52
+ */
53
+ type X402ProcedureChargeConfig = Omit<X402ChargeConfig, "price">;
54
+ /** The per-RPC charge spec the runtime passes the gate for each paid dispatch. */
55
+ interface X402ProcedureSpec {
56
+ /** The `file:function` id of the paid procedure; becomes the x402 challenge `resource`. */
57
+ readonly functionPath: string;
58
+ /** USD price declared by the procedure's `.x402({ price })` modifier. */
59
+ readonly price: X402Price;
60
+ }
61
+ /**
62
+ * Gate one paid RPC. Returns a real `402` + `PAYMENT-REQUIRED` challenge when the
63
+ * request is unpaid, or the dispatched response (with `X-PAYMENT-RESPONSE`
64
+ * attached) once the client's `X-PAYMENT` is verified and settled. `dispatch`
65
+ * runs the actual shard forward — it is only invoked after payment is verified.
66
+ */
67
+ type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispatch: () => Promise<Response>) => Promise<Response>;
68
+ /**
69
+ * Build the injectable procedure charge gate for `config`. One initialised
70
+ * {@link ChargeMiddleware} is memoised per `functionPath` (each bakes that
71
+ * function's price + `resource`), since `createChargeMiddleware` fetches
72
+ * facilitator support on first use. A failed init is not cached, so a transient
73
+ * facilitator outage retries on the next request.
74
+ */
75
+ declare const createProcedureChargeGate: (config: X402ProcedureChargeConfig) => X402ProcedureChargeGate;
76
+ export { type ChargeHandler, type ChargeMiddleware, type ChargeRouteOverrides, type FacilitatorConfig, type HttpActionHandler, type X402ChargeConfig, type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createFacilitatorClient, createProcedureChargeGate, withX402 };
@@ -0,0 +1,7 @@
1
+ export { DEFAULT_FACILITATOR_URL, resolveFacilitatorUrl } from '../packem_shared/DEFAULT_FACILITATOR_URL-Cbz6kIqa.mjs';
2
+ export { createFacilitatorClient } from '../packem_shared/createFacilitatorClient-rXHBnCZm.mjs';
3
+ export { isEvmNetwork, isSvmNetwork, toCaip2 } from '../packem_shared/EVM_NETWORKS-BhnYWUQ4.mjs';
4
+ export { withX402 } from '../packem_shared/withX402-rUq0voT8.mjs';
5
+ export { createChargeMiddleware } from '../packem_shared/createChargeMiddleware-BJkYJeFf.mjs';
6
+ export { createProcedureChargeGate } from '../packem_shared/createProcedureChargeGate-CV8ITlQP.mjs';
7
+ export { toPaymentEventRow, toReceipt } from '../packem_shared/toPaymentEventRow-DW4O9N7Y.mjs';
@@ -0,0 +1,6 @@
1
+ export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, E as EVM_NETWORKS, type a as EvmAddress, type F as FacilitatorConfig, type b as FriendlyNetwork, N as NETWORK_TO_CAIP2, S as SVM_NETWORKS, type X as X402CdpSignerConfig, type c as X402ChargeConfig, type d as X402Network, type e as X402PayConfig, type f as X402Price, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, type j as X402SignerConfig, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/config.d-CddwCiBm.mjs";
2
+ import '@x402/evm';
3
+ import '@x402/svm';
4
+ import '@x402/core/http';
5
+ import '@x402/core/client';
6
+ import '@x402/core/types';
@@ -0,0 +1,6 @@
1
+ export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, E as EVM_NETWORKS, type a as EvmAddress, type F as FacilitatorConfig, type b as FriendlyNetwork, N as NETWORK_TO_CAIP2, S as SVM_NETWORKS, type X as X402CdpSignerConfig, type c as X402ChargeConfig, type d as X402Network, type e as X402PayConfig, type f as X402Price, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, type j as X402SignerConfig, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/config.d-CddwCiBm.js";
2
+ import '@x402/evm';
3
+ import '@x402/svm';
4
+ import '@x402/core/http';
5
+ import '@x402/core/client';
6
+ import '@x402/core/types';
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export { DEFAULT_FACILITATOR_URL, resolveFacilitatorUrl } from './packem_shared/DEFAULT_FACILITATOR_URL-Cbz6kIqa.mjs';
2
+ export { EVM_NETWORKS, NETWORK_TO_CAIP2, SVM_NETWORKS, isEvmNetwork, isSvmNetwork, toCaip2 } from './packem_shared/EVM_NETWORKS-BhnYWUQ4.mjs';
@@ -0,0 +1,4 @@
1
+ const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
2
+ const resolveFacilitatorUrl = (facilitator) => facilitator?.url ?? DEFAULT_FACILITATOR_URL;
3
+
4
+ export { DEFAULT_FACILITATOR_URL, resolveFacilitatorUrl };
@@ -0,0 +1,85 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { toCaip2 } from './EVM_NETWORKS-BhnYWUQ4.mjs';
3
+
4
+ const USD_AMOUNT = /^\d+(?:\.\d+)?$/;
5
+ const normaliseAddress = (address, network) => network.startsWith("eip155:") ? address.toLowerCase() : address;
6
+ const DEFAULT_STABLECOIN_DECIMALS = 6;
7
+ const createSpendState = () => {
8
+ let spent = 0n;
9
+ return {
10
+ add: (amount) => {
11
+ spent += amount;
12
+ },
13
+ get spentAtomic() {
14
+ return spent;
15
+ }
16
+ };
17
+ };
18
+ const usdToAtomic = (usd, decimals = DEFAULT_STABLECOIN_DECIMALS) => {
19
+ if (!Number.isInteger(decimals) || decimals < 0) {
20
+ throw new LunoraError("BAD_REQUEST", `x402 policy: decimals must be a non-negative integer, got ${String(decimals)}.`);
21
+ }
22
+ const raw = (typeof usd === "number" ? usd.toString() : usd).trim();
23
+ const unsigned = raw.startsWith("$") ? raw.slice(1) : raw;
24
+ if (!USD_AMOUNT.test(unsigned)) {
25
+ throw new LunoraError("BAD_REQUEST", `x402 policy: "${String(usd)}" is not a valid USD amount (use a plain decimal like "0.01").`);
26
+ }
27
+ const [whole = "0", fraction = ""] = unsigned.split(".");
28
+ const scaled = fraction.slice(0, decimals).padEnd(decimals, "0");
29
+ return BigInt(whole) * 10n ** BigInt(decimals) + BigInt(scaled === "" ? "0" : scaled);
30
+ };
31
+ const buildSpendPolicy = (policy) => {
32
+ const decimals = policy.decimals ?? DEFAULT_STABLECOIN_DECIMALS;
33
+ const maxPerCall = policy.maxPerCall === void 0 ? void 0 : usdToAtomic(policy.maxPerCall, decimals);
34
+ const allowedNetworks = policy.allowedNetworks?.map((network) => toCaip2(network));
35
+ const { allowedRecipients } = policy;
36
+ return (_version, requirements) => requirements.filter((requirement) => {
37
+ if (maxPerCall !== void 0 && BigInt(requirement.amount) > maxPerCall) {
38
+ return false;
39
+ }
40
+ if (allowedNetworks !== void 0 && !allowedNetworks.includes(requirement.network)) {
41
+ return false;
42
+ }
43
+ if (allowedRecipients !== void 0) {
44
+ const payTo = normaliseAddress(requirement.payTo, requirement.network);
45
+ return allowedRecipients.some((allowed) => normaliseAddress(allowed, requirement.network) === payTo);
46
+ }
47
+ return true;
48
+ });
49
+ };
50
+ const buildPaymentGuard = (policy, state) => {
51
+ const decimals = policy.decimals ?? DEFAULT_STABLECOIN_DECIMALS;
52
+ const maxPerRun = policy.maxPerRun === void 0 ? void 0 : usdToAtomic(policy.maxPerRun, decimals);
53
+ return async (context) => {
54
+ const requirement = context.selectedRequirements;
55
+ const amount = BigInt(requirement.amount);
56
+ if (maxPerRun !== void 0 && state.spentAtomic + amount > maxPerRun) {
57
+ return {
58
+ abort: true,
59
+ reason: `x402 policy: this payment (${requirement.amount}) would exceed the per-run cap (already spent ${state.spentAtomic.toString()}, cap ${maxPerRun.toString()}, in atomic base units).`
60
+ };
61
+ }
62
+ if (policy.onPaymentRequired !== void 0) {
63
+ const approved = await policy.onPaymentRequired(requirement);
64
+ if (!approved) {
65
+ return { abort: true, reason: "x402 policy: payment was declined by onPaymentRequired." };
66
+ }
67
+ }
68
+ return void 0;
69
+ };
70
+ };
71
+ const recordSpend = (state) => (context) => {
72
+ state.add(BigInt(context.selectedRequirements.amount));
73
+ return Promise.resolve();
74
+ };
75
+ const assertBoundedPolicy = (policy) => {
76
+ const bounded = policy.maxPerCall !== void 0 || policy.maxPerRun !== void 0 || (policy.allowedRecipients?.length ?? 0) > 0 || (policy.allowedNetworks?.length ?? 0) > 0 || policy.onPaymentRequired !== void 0;
77
+ if (!bounded) {
78
+ throw new LunoraError(
79
+ "FORBIDDEN",
80
+ "x402 pay: refusing to build a wallet with an unbounded spend policy. Set at least one of maxPerCall, maxPerRun, allowedRecipients, allowedNetworks, or onPaymentRequired."
81
+ );
82
+ }
83
+ };
84
+
85
+ export { DEFAULT_STABLECOIN_DECIMALS, assertBoundedPolicy, buildPaymentGuard, buildSpendPolicy, createSpendState, recordSpend, usdToAtomic };
@@ -0,0 +1,26 @@
1
+ const NETWORK_TO_CAIP2 = {
2
+ arbitrum: "eip155:42161",
3
+ "arbitrum-sepolia": "eip155:421614",
4
+ base: "eip155:8453",
5
+ "base-sepolia": "eip155:84532",
6
+ ethereum: "eip155:1",
7
+ polygon: "eip155:137",
8
+ solana: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
9
+ "solana-devnet": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
10
+ };
11
+ const EVM_NETWORKS = ["arbitrum", "arbitrum-sepolia", "base", "base-sepolia", "ethereum", "polygon"];
12
+ const SVM_NETWORKS = ["solana", "solana-devnet"];
13
+ const toCaip2 = (network) => {
14
+ const mapped = NETWORK_TO_CAIP2[network];
15
+ if (mapped !== void 0) {
16
+ return mapped;
17
+ }
18
+ if (network.includes(":")) {
19
+ return network;
20
+ }
21
+ throw new Error(`Unknown x402 network "${network}". Use a friendly name (${EVM_NETWORKS.join(", ")}, ${SVM_NETWORKS.join(", ")}) or a raw CAIP-2 id.`);
22
+ };
23
+ const isEvmNetwork = (network) => toCaip2(network).startsWith("eip155:");
24
+ const isSvmNetwork = (network) => toCaip2(network).startsWith("solana:");
25
+
26
+ export { EVM_NETWORKS, NETWORK_TO_CAIP2, SVM_NETWORKS, isEvmNetwork, isSvmNetwork, toCaip2 };
@@ -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 };