@routexcc/x402 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thalaxis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @routexcc/x402
2
+
3
+ x402 middleware wrapper for Routex.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @routexcc/x402
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { routexMiddleware, handlePaymentRequired } from "@routexcc/x402";
15
+ import { createRouter } from "@routexcc/core";
16
+
17
+ const router = createRouter({ chains: [baseAdapter] });
18
+
19
+ // Express middleware
20
+ app.use(routexMiddleware({ router }));
21
+
22
+ // Or handle 402 responses directly
23
+ const response = await handlePaymentRequired(req, {
24
+ router,
25
+ amount: "1.00",
26
+ currency: "USDC",
27
+ });
28
+ ```
29
+
30
+ ## Documentation
31
+
32
+ See the [main repo README](https://github.com/routexcc/routex) for full documentation.
33
+
34
+ Part of the [Routex](https://github.com/routexcc/routex) monorepo by [Thalaxis](https://thalaxis.com).
35
+
36
+ ## License
37
+
38
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ routexMiddleware: () => routexMiddleware
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/middleware.ts
28
+ var import_core = require("@routexcc/core");
29
+ function routexMiddleware(config) {
30
+ const router = (0, import_core.createRouter)(config.routeConfig);
31
+ return {
32
+ router,
33
+ async handlePaymentRequired(response) {
34
+ const routeResult = await router.route(response.paymentRequirement, config.signer);
35
+ if (config.onRouteSelected) {
36
+ config.onRouteSelected(routeResult);
37
+ }
38
+ return {
39
+ payload: routeResult.payload,
40
+ routeResult
41
+ };
42
+ },
43
+ parseResponse(status, body) {
44
+ if (status !== 402) {
45
+ return void 0;
46
+ }
47
+ const paymentRequirement = parsePaymentRequirement(body);
48
+ if (!paymentRequirement) {
49
+ return void 0;
50
+ }
51
+ return {
52
+ status: 402,
53
+ paymentRequirement
54
+ };
55
+ }
56
+ };
57
+ }
58
+ function parsePaymentRequirement(body) {
59
+ const source = body["paymentRequirement"] ?? body;
60
+ const chains = source["acceptedChains"];
61
+ if (!Array.isArray(chains) || chains.length === 0) {
62
+ return void 0;
63
+ }
64
+ const acceptedChains = [];
65
+ for (const chain of chains) {
66
+ if (typeof chain !== "object" || chain === null) {
67
+ continue;
68
+ }
69
+ const entry = chain;
70
+ const chainId = entry["chainId"];
71
+ const payTo = entry["payTo"];
72
+ const amount = entry["amount"];
73
+ const token = entry["token"];
74
+ if (typeof chainId !== "string" || typeof payTo !== "string" || typeof token !== "string") {
75
+ continue;
76
+ }
77
+ let parsedAmount;
78
+ if (typeof amount === "bigint") {
79
+ parsedAmount = amount;
80
+ } else if (typeof amount === "string") {
81
+ try {
82
+ parsedAmount = BigInt(amount);
83
+ } catch {
84
+ continue;
85
+ }
86
+ } else if (typeof amount === "number" && Number.isInteger(amount)) {
87
+ parsedAmount = BigInt(amount);
88
+ } else {
89
+ continue;
90
+ }
91
+ const extra = typeof entry["extra"] === "object" && entry["extra"] !== null ? entry["extra"] : void 0;
92
+ acceptedChains.push({
93
+ chainId,
94
+ payTo,
95
+ // BigInt: token amounts must never use floating point
96
+ amount: parsedAmount,
97
+ token,
98
+ ...extra ? { extra } : {}
99
+ });
100
+ }
101
+ if (acceptedChains.length === 0) {
102
+ return void 0;
103
+ }
104
+ return { acceptedChains };
105
+ }
106
+ // Annotate the CommonJS export names for ESM import in node:
107
+ 0 && (module.exports = {
108
+ routexMiddleware
109
+ });
@@ -0,0 +1,117 @@
1
+ import { PaymentPayload, RouteResult, PaymentRequirement, Router, RouteConfig, Signer, RouteExhaustedError } from '@routexcc/core';
2
+
3
+ /**
4
+ * Configuration for the Routex x402 middleware.
5
+ */
6
+ interface RoutexMiddlewareConfig {
7
+ /** Full Routex route configuration. */
8
+ readonly routeConfig: RouteConfig;
9
+ /** Signer instance for signing payment payloads. */
10
+ readonly signer: Signer;
11
+ /**
12
+ * Optional callback invoked after a successful route selection.
13
+ * Can be used for logging or telemetry.
14
+ */
15
+ readonly onRouteSelected?: (result: RouteResult) => void;
16
+ /**
17
+ * Optional callback invoked when routing fails.
18
+ * The caller can use this to fall back to direct payment.
19
+ */
20
+ readonly onRouteFailed?: (error: RoutexError) => void;
21
+ }
22
+ /** Re-export for convenience in error handling callbacks. */
23
+ type RoutexError = RouteExhaustedError | Error;
24
+ /**
25
+ * A parsed 402 response containing payment requirements.
26
+ */
27
+ interface ParsedX402Response {
28
+ /** HTTP status code (should be 402). */
29
+ readonly status: number;
30
+ /** Payment requirements extracted from the 402 response body. */
31
+ readonly paymentRequirement: PaymentRequirement;
32
+ }
33
+ /**
34
+ * Result of the middleware processing a 402 response.
35
+ */
36
+ interface MiddlewareResult {
37
+ /** The constructed payment payload ready for submission to the facilitator. */
38
+ readonly payload: PaymentPayload;
39
+ /** The full route result with scoring details. */
40
+ readonly routeResult: RouteResult;
41
+ }
42
+ /**
43
+ * The Routex x402 middleware instance.
44
+ */
45
+ interface RoutexMiddleware {
46
+ /**
47
+ * Handle a 402 response by routing and building a payment payload.
48
+ *
49
+ * @param response - The parsed 402 response with payment requirements.
50
+ * @returns The payment payload and route details.
51
+ * @throws {RouteExhaustedError} When no eligible route is found.
52
+ * @throws {PaymentConstructionError} When payload construction fails.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const result = await middleware.handlePaymentRequired(parsed402);
57
+ * // Forward result.payload to the facilitator
58
+ * ```
59
+ */
60
+ handlePaymentRequired(response: ParsedX402Response): Promise<MiddlewareResult>;
61
+ /**
62
+ * Parse a raw HTTP response into a ParsedX402Response.
63
+ * Returns undefined if the response is not a 402.
64
+ *
65
+ * @param status - HTTP status code.
66
+ * @param body - Response body (JSON-parsed).
67
+ * @returns Parsed 402 response, or undefined if not a 402.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const parsed = middleware.parseResponse(402, responseBody);
72
+ * if (parsed) {
73
+ * const result = await middleware.handlePaymentRequired(parsed);
74
+ * }
75
+ * ```
76
+ */
77
+ parseResponse(status: number, body: Record<string, unknown>): ParsedX402Response | undefined;
78
+ /** The underlying router instance. */
79
+ readonly router: Router;
80
+ }
81
+ /**
82
+ * Create a Routex x402 middleware instance.
83
+ *
84
+ * Intercepts 402 Payment Required responses, extracts payment requirements,
85
+ * selects the optimal chain via the Routex router, and builds a signed
86
+ * payment payload for submission to the facilitator.
87
+ *
88
+ * @param config - Middleware configuration including route config and signer.
89
+ * @returns A middleware instance for handling 402 responses.
90
+ * @throws {Error} When config is missing required fields.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { routexMiddleware } from '@routexcc/x402';
95
+ * import { createBaseAdapter } from '@routexcc/chain-base';
96
+ *
97
+ * const middleware = routexMiddleware({
98
+ * routeConfig: {
99
+ * adapters: new Map([['base', createBaseAdapter(client)]]),
100
+ * feeOracle: oracle,
101
+ * strategy: 'cheapest',
102
+ * maxFeeAgeMs: 60_000,
103
+ * },
104
+ * signer: mySigner,
105
+ * });
106
+ *
107
+ * // In your HTTP client interceptor:
108
+ * const parsed = middleware.parseResponse(response.status, response.data);
109
+ * if (parsed) {
110
+ * const { payload } = await middleware.handlePaymentRequired(parsed);
111
+ * // Forward payload to facilitator
112
+ * }
113
+ * ```
114
+ */
115
+ declare function routexMiddleware(config: RoutexMiddlewareConfig): RoutexMiddleware;
116
+
117
+ export { type MiddlewareResult, type ParsedX402Response, type RoutexMiddleware, type RoutexMiddlewareConfig, routexMiddleware };
@@ -0,0 +1,117 @@
1
+ import { PaymentPayload, RouteResult, PaymentRequirement, Router, RouteConfig, Signer, RouteExhaustedError } from '@routexcc/core';
2
+
3
+ /**
4
+ * Configuration for the Routex x402 middleware.
5
+ */
6
+ interface RoutexMiddlewareConfig {
7
+ /** Full Routex route configuration. */
8
+ readonly routeConfig: RouteConfig;
9
+ /** Signer instance for signing payment payloads. */
10
+ readonly signer: Signer;
11
+ /**
12
+ * Optional callback invoked after a successful route selection.
13
+ * Can be used for logging or telemetry.
14
+ */
15
+ readonly onRouteSelected?: (result: RouteResult) => void;
16
+ /**
17
+ * Optional callback invoked when routing fails.
18
+ * The caller can use this to fall back to direct payment.
19
+ */
20
+ readonly onRouteFailed?: (error: RoutexError) => void;
21
+ }
22
+ /** Re-export for convenience in error handling callbacks. */
23
+ type RoutexError = RouteExhaustedError | Error;
24
+ /**
25
+ * A parsed 402 response containing payment requirements.
26
+ */
27
+ interface ParsedX402Response {
28
+ /** HTTP status code (should be 402). */
29
+ readonly status: number;
30
+ /** Payment requirements extracted from the 402 response body. */
31
+ readonly paymentRequirement: PaymentRequirement;
32
+ }
33
+ /**
34
+ * Result of the middleware processing a 402 response.
35
+ */
36
+ interface MiddlewareResult {
37
+ /** The constructed payment payload ready for submission to the facilitator. */
38
+ readonly payload: PaymentPayload;
39
+ /** The full route result with scoring details. */
40
+ readonly routeResult: RouteResult;
41
+ }
42
+ /**
43
+ * The Routex x402 middleware instance.
44
+ */
45
+ interface RoutexMiddleware {
46
+ /**
47
+ * Handle a 402 response by routing and building a payment payload.
48
+ *
49
+ * @param response - The parsed 402 response with payment requirements.
50
+ * @returns The payment payload and route details.
51
+ * @throws {RouteExhaustedError} When no eligible route is found.
52
+ * @throws {PaymentConstructionError} When payload construction fails.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const result = await middleware.handlePaymentRequired(parsed402);
57
+ * // Forward result.payload to the facilitator
58
+ * ```
59
+ */
60
+ handlePaymentRequired(response: ParsedX402Response): Promise<MiddlewareResult>;
61
+ /**
62
+ * Parse a raw HTTP response into a ParsedX402Response.
63
+ * Returns undefined if the response is not a 402.
64
+ *
65
+ * @param status - HTTP status code.
66
+ * @param body - Response body (JSON-parsed).
67
+ * @returns Parsed 402 response, or undefined if not a 402.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const parsed = middleware.parseResponse(402, responseBody);
72
+ * if (parsed) {
73
+ * const result = await middleware.handlePaymentRequired(parsed);
74
+ * }
75
+ * ```
76
+ */
77
+ parseResponse(status: number, body: Record<string, unknown>): ParsedX402Response | undefined;
78
+ /** The underlying router instance. */
79
+ readonly router: Router;
80
+ }
81
+ /**
82
+ * Create a Routex x402 middleware instance.
83
+ *
84
+ * Intercepts 402 Payment Required responses, extracts payment requirements,
85
+ * selects the optimal chain via the Routex router, and builds a signed
86
+ * payment payload for submission to the facilitator.
87
+ *
88
+ * @param config - Middleware configuration including route config and signer.
89
+ * @returns A middleware instance for handling 402 responses.
90
+ * @throws {Error} When config is missing required fields.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { routexMiddleware } from '@routexcc/x402';
95
+ * import { createBaseAdapter } from '@routexcc/chain-base';
96
+ *
97
+ * const middleware = routexMiddleware({
98
+ * routeConfig: {
99
+ * adapters: new Map([['base', createBaseAdapter(client)]]),
100
+ * feeOracle: oracle,
101
+ * strategy: 'cheapest',
102
+ * maxFeeAgeMs: 60_000,
103
+ * },
104
+ * signer: mySigner,
105
+ * });
106
+ *
107
+ * // In your HTTP client interceptor:
108
+ * const parsed = middleware.parseResponse(response.status, response.data);
109
+ * if (parsed) {
110
+ * const { payload } = await middleware.handlePaymentRequired(parsed);
111
+ * // Forward payload to facilitator
112
+ * }
113
+ * ```
114
+ */
115
+ declare function routexMiddleware(config: RoutexMiddlewareConfig): RoutexMiddleware;
116
+
117
+ export { type MiddlewareResult, type ParsedX402Response, type RoutexMiddleware, type RoutexMiddlewareConfig, routexMiddleware };
package/dist/index.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // src/middleware.ts
2
+ import { createRouter } from "@routexcc/core";
3
+ function routexMiddleware(config) {
4
+ const router = createRouter(config.routeConfig);
5
+ return {
6
+ router,
7
+ async handlePaymentRequired(response) {
8
+ const routeResult = await router.route(response.paymentRequirement, config.signer);
9
+ if (config.onRouteSelected) {
10
+ config.onRouteSelected(routeResult);
11
+ }
12
+ return {
13
+ payload: routeResult.payload,
14
+ routeResult
15
+ };
16
+ },
17
+ parseResponse(status, body) {
18
+ if (status !== 402) {
19
+ return void 0;
20
+ }
21
+ const paymentRequirement = parsePaymentRequirement(body);
22
+ if (!paymentRequirement) {
23
+ return void 0;
24
+ }
25
+ return {
26
+ status: 402,
27
+ paymentRequirement
28
+ };
29
+ }
30
+ };
31
+ }
32
+ function parsePaymentRequirement(body) {
33
+ const source = body["paymentRequirement"] ?? body;
34
+ const chains = source["acceptedChains"];
35
+ if (!Array.isArray(chains) || chains.length === 0) {
36
+ return void 0;
37
+ }
38
+ const acceptedChains = [];
39
+ for (const chain of chains) {
40
+ if (typeof chain !== "object" || chain === null) {
41
+ continue;
42
+ }
43
+ const entry = chain;
44
+ const chainId = entry["chainId"];
45
+ const payTo = entry["payTo"];
46
+ const amount = entry["amount"];
47
+ const token = entry["token"];
48
+ if (typeof chainId !== "string" || typeof payTo !== "string" || typeof token !== "string") {
49
+ continue;
50
+ }
51
+ let parsedAmount;
52
+ if (typeof amount === "bigint") {
53
+ parsedAmount = amount;
54
+ } else if (typeof amount === "string") {
55
+ try {
56
+ parsedAmount = BigInt(amount);
57
+ } catch {
58
+ continue;
59
+ }
60
+ } else if (typeof amount === "number" && Number.isInteger(amount)) {
61
+ parsedAmount = BigInt(amount);
62
+ } else {
63
+ continue;
64
+ }
65
+ const extra = typeof entry["extra"] === "object" && entry["extra"] !== null ? entry["extra"] : void 0;
66
+ acceptedChains.push({
67
+ chainId,
68
+ payTo,
69
+ // BigInt: token amounts must never use floating point
70
+ amount: parsedAmount,
71
+ token,
72
+ ...extra ? { extra } : {}
73
+ });
74
+ }
75
+ if (acceptedChains.length === 0) {
76
+ return void 0;
77
+ }
78
+ return { acceptedChains };
79
+ }
80
+ export {
81
+ routexMiddleware
82
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@routexcc/x402",
3
+ "version": "1.0.0",
4
+ "description": "x402 middleware wrapper for Routex",
5
+ "license": "MIT",
6
+ "author": "Thalaxis <opensource@thalaxis.com> (https://thalaxis.com)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/routexcc/routex.git",
10
+ "directory": "packages/x402"
11
+ },
12
+ "homepage": "https://github.com/routexcc/routex#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/routexcc/routex/issues"
15
+ },
16
+ "keywords": [
17
+ "x402",
18
+ "middleware",
19
+ "payment",
20
+ "402",
21
+ "routex"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.mjs",
28
+ "require": "./dist/index.cjs"
29
+ }
30
+ },
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.mjs",
33
+ "types": "./dist/index.d.ts",
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "dependencies": {
41
+ "@routexcc/core": "1.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "tsup": "^8.4.0",
45
+ "typescript": "^5.7.0",
46
+ "vitest": "^3.0.0",
47
+ "@vitest/coverage-v8": "^3.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean --no-sourcemap",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vitest run",
53
+ "test:coverage": "vitest run --coverage",
54
+ "clean": "rm -rf dist coverage"
55
+ }
56
+ }