crypto-quant-signal-mcp 1.23.2 → 1.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  </p>
12
12
 
13
13
  <p align="center">
14
- <span data-tr-field="pfe_wr">91.6%</span>% PFE win rate across <span data-tr-field="total_calls">374,696</span>+ verified calls. Merkle-verified on Base L2. Don't trust — verify. <!-- SNAPSHOT-LINE -->
14
+ <span data-tr-field="pfe_wr">91.6%</span>% PFE win rate across <span data-tr-field="total_calls">377,858</span>+ verified calls. Merkle-verified on Base L2. Don't trust — verify. <!-- SNAPSHOT-LINE -->
15
15
  </p>
16
16
 
17
17
  <p align="center">
@@ -60,6 +60,8 @@ No code. No API key. No install. The server speaks Streamable HTTP at `https://a
60
60
 
61
61
  Your Claude now has a quant analyst built in. Prefer local? Run `npx -y crypto-quant-signal-mcp`.
62
62
 
63
+ > Running locally on npm 12+? npm v12 disables dependency install scripts by default. AlgoVault's optional local SQLite mode uses the native `better-sqlite3` module — if you install it into a project, run `npm approve-scripts` (or `npm install --allow-scripts`) to build it. The hosted HTTP transport (`api.algovault.com/mcp`) needs no local build.
64
+
63
65
  ---
64
66
 
65
67
  ## What one call returns
@@ -110,7 +112,7 @@ The `_algovault` block makes outputs composable: downstream risk and backtest to
110
112
  scripts/snapshot-landing-data.mjs at npm-publish + Hetzner-deploy. Do NOT hand-edit the
111
113
  numbers; edit "What's new" by hand. Wired by OPS-NPM-README-SINGLE-SOT-W1 (2026-05-31). -->
112
114
  <p align="center">
113
- <strong><span data-tr-field="pfe_wr">91.6%</span>% PFE Win Rate</strong> · <strong><span data-tr-field="total_calls">374,696</span> trade calls</strong> · <strong><span data-tr-field="merkle_batches">98</span> on-chain batches</strong> · <strong><span data-tr-field="hold_rate">99.1%</span>% HOLD rate</strong> <!-- SNAPSHOT-LINE -->
115
+ <strong><span data-tr-field="pfe_wr">91.6%</span>% PFE Win Rate</strong> · <strong><span data-tr-field="total_calls">377,858</span> trade calls</strong> · <strong><span data-tr-field="merkle_batches">99</span> on-chain batches</strong> · <strong><span data-tr-field="hold_rate">99.1%</span>% HOLD rate</strong> <!-- SNAPSHOT-LINE -->
114
116
  </p>
115
117
 
116
118
  <p align="center">
@@ -224,7 +226,7 @@ Quota-only tiers. Every tier gets all venues, all assets, all timeframes — you
224
226
  | Feature | Free | Starter ($9.99/mo) | Pro ($49/mo) | Enterprise ($299/mo) | x402 (per call) |
225
227
  |---------|------|-------------------|-------------|---------------------|-----------------|
226
228
  | Exchanges | All 12 | All 12 | All 12 | All 12 | All 12 | <!-- SNAPSHOT-LINE-TABLE -->
227
- | Assets | All 1300+ | All 1300+ | All 1300+ | All 1300+ | All 1300+ | <!-- SNAPSHOT-LINE-TABLE -->
229
+ | Assets | All 1320+ | All 1320+ | All 1320+ | All 1320+ | All 1320+ | <!-- SNAPSHOT-LINE-TABLE -->
228
230
  | Asset classes | Crypto + TradFi | Crypto + TradFi | Crypto + TradFi | Crypto + TradFi | Crypto + TradFi |
229
231
  | Timeframes | All 11 | All 11 | All 11 | All 11 | All 11 |
230
232
  | Funding arb results | Top 5 | Unlimited | Unlimited | Unlimited | Unlimited |
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Circle Gateway Nanopayments — ADDITIVE x402 payment scheme (CIRCLE-GATEWAY-MIGRATE-W1).
3
+ *
4
+ * This is NOT a migration and NOT a second rail. Circle Gateway is a payment *method* on
5
+ * the SAME `exact` scheme our CDP rail already speaks — Circle's own facilitator advertises
6
+ * `"scheme":"exact"` on every supported kind (live-probed 2026-07-17). What distinguishes a
7
+ * Gateway kind from a CDP kind is the NETWORK plus `extra.name === 'GatewayWalletBatched'`
8
+ * (the EIP-712 *domain name*) and `extra.verifyingContract`.
9
+ *
10
+ * >>> `GatewayWalletBatched` IS NOT AN x402 SCHEME ID. <<<
11
+ * Anything asserting `accepts[].scheme === 'GatewayWalletBatched'` is wrong by construction.
12
+ * (R0 probe: SDK `CIRCLE_BATCHING_SCHEME === 'exact'` while `CIRCLE_BATCHING_NAME ===
13
+ * 'GatewayWalletBatched'`; Circle's seller quickstart shows `"scheme": "exact"`.)
14
+ *
15
+ * Integration shape = "Path B" (architect-ratified R0 Q2): the Circle facilitator joins the
16
+ * EXISTING `x402ResourceServer`'s facilitator array and `GatewayEvmScheme` registers on the
17
+ * Gateway network, so ONE 402 advertises both rails. The alternative (`createGatewayMiddleware`,
18
+ * Circle's quickstart default) is a standalone Express middleware owning its own 402 and CANNOT
19
+ * dual-advertise.
20
+ *
21
+ * SAFETY — why every failure path here is fail-open (R0 Q4, mandatory):
22
+ * `x402ResourceServer.initialize()` fans `getSupported()` across EVERY facilitator in its array.
23
+ * A throw propagates to x402.ts's catch, which sets `resourceServer = null` and disables payments
24
+ * ENTIRELY — i.e. a Circle outage would take the LIVE CDP mainnet revenue rail dark with it. That
25
+ * is the 2026-07-01 OKX crash-loop failure mode (system-map:284 — an uncaught async
26
+ * `RouteConfigurationError` at boot 502'd api.algovault.com for ~1-2min). So: this module NEVER
27
+ * throws into the boot path. It probes Circle in its OWN try/catch and, on ANY failure, returns
28
+ * null → the caller keeps the CDP-only array byte-unchanged.
29
+ *
30
+ * Two-flag firewall:
31
+ * outer `CIRCLE_GATEWAY_ENABLED` (default OFF) → facilitator is NEVER constructed
32
+ * inner config-present (`CIRCLE_GATEWAY_SELLER_ADDRESS`) → absent falls back to the Stub
33
+ */
34
+ import { GatewayEvmScheme } from '@circle-fin/x402-batching/server';
35
+ /** Circle Gateway testnet facilitator. Live-probed 2026-07-17 → HTTP 200. */
36
+ export declare const CIRCLE_TESTNET_FACILITATOR_URL = "https://gateway-api-testnet.circle.com";
37
+ /** Circle Gateway mainnet facilitator. NOT reachable from this wave — see MAINNET_BLOCKED. */
38
+ export declare const CIRCLE_MAINNET_FACILITATOR_URL = "https://gateway-api.circle.com";
39
+ /** The `extra.name` Circle stamps on every Gateway kind — the EIP-712 domain name. */
40
+ export declare const GATEWAY_EIP712_DOMAIN_NAME = "GatewayWalletBatched";
41
+ /** Marker prefix for stub-sourced values, so a stub can never be mistaken for a live rail. */
42
+ export declare const GATEWAY_STUB_PREFIX = "[STUB]";
43
+ /**
44
+ * Seller address used when the Gateway is enabled but unconfigured (Stub path). Deliberately the
45
+ * zero address: it is inert, obviously-not-real in logs, and can never receive value.
46
+ */
47
+ export declare const GATEWAY_STUB_SELLER_ADDRESS = "0x0000000000000000000000000000000000000000";
48
+ export interface CircleGatewayConfig {
49
+ /** Outer flag AND inner checks all passed — the scheme should be wired. */
50
+ enabled: boolean;
51
+ /** Facilitator base URL. Always explicit; never left to the SDK's mainnet default. */
52
+ facilitatorUrl: string;
53
+ /** CAIP-2 network the Gateway scheme advertises on. */
54
+ network: string;
55
+ /** Address receiving the Gateway seller balance. */
56
+ sellerAddress: string;
57
+ /** True when the real Circle config is absent and the Stub facilitator stands in (R2). */
58
+ useStub: boolean;
59
+ /** Human-readable reason when `enabled === false`. Surfaced in logs, never thrown. */
60
+ reason?: string;
61
+ }
62
+ /**
63
+ * Resolve the Gateway config from env. Pure + total: it NEVER throws and NEVER constructs a
64
+ * client — callers decide what to do with a disabled result.
65
+ *
66
+ * Default-deny at every step: an unset/typo'd flag, a bad address, a non-allow-listed host or
67
+ * network all resolve to `enabled: false` with a reason, not to a permissive fallback.
68
+ */
69
+ export declare function resolveCircleGatewayFromEnv(env?: NodeJS.ProcessEnv): CircleGatewayConfig;
70
+ /**
71
+ * The structural surface `x402ResourceServer` consumes from a facilitator. Declared locally so
72
+ * the Stub can implement it without importing Circle's internal (non-exported) interface.
73
+ */
74
+ export interface GatewayFacilitatorLike {
75
+ verify(paymentPayload: unknown, paymentRequirements: unknown): Promise<unknown>;
76
+ settle(paymentPayload: unknown, paymentRequirements: unknown): Promise<unknown>;
77
+ getSupported(): Promise<{
78
+ kinds: Array<{
79
+ x402Version: number;
80
+ scheme: string;
81
+ network: string;
82
+ extra?: Record<string, unknown>;
83
+ }>;
84
+ extensions: string[];
85
+ signers: Record<string, string[]>;
86
+ }>;
87
+ }
88
+ /**
89
+ * Stub Circle facilitator (R2). Returns a realistic `getSupported()` shape — same field names,
90
+ * same `scheme:'exact'`, same `extra.name`/`verifyingContract` keys as the live facilitator — so
91
+ * the 402 `accepts[]` has the true shape without any Circle account.
92
+ *
93
+ * It NEVER validates a payment: `verify` returns invalid and `settle` returns failure, both
94
+ * `[STUB]`-prefixed. A stub that "succeeded" would be a free-money bug.
95
+ */
96
+ export declare class GatewayStubFacilitator implements GatewayFacilitatorLike {
97
+ private readonly network;
98
+ /** Shape-accurate placeholder; NOT the live GatewayWallet. Live value comes from Circle. */
99
+ private readonly verifyingContract;
100
+ constructor(network: string,
101
+ /** Shape-accurate placeholder; NOT the live GatewayWallet. Live value comes from Circle. */
102
+ verifyingContract?: string);
103
+ getSupported(): Promise<{
104
+ kinds: {
105
+ x402Version: number;
106
+ scheme: string;
107
+ network: string;
108
+ extra: {
109
+ name: string;
110
+ version: string;
111
+ verifyingContract: string;
112
+ stub: boolean;
113
+ };
114
+ }[];
115
+ extensions: string[];
116
+ signers: Record<string, string[]>;
117
+ }>;
118
+ verify(): Promise<{
119
+ isValid: boolean;
120
+ invalidReason: string;
121
+ }>;
122
+ settle(): Promise<{
123
+ success: boolean;
124
+ errorReason: string;
125
+ transaction: string;
126
+ network: string;
127
+ }>;
128
+ }
129
+ /**
130
+ * Build the Circle facilitator for a resolved config. Stub when unconfigured, real
131
+ * `BatchFacilitatorClient` (explicit testnet URL) otherwise.
132
+ *
133
+ * Throws only on programmer error (disabled config). Callers in the boot path must still wrap —
134
+ * see `probeCircleFacilitator`.
135
+ */
136
+ export declare function createCircleFacilitator(config: CircleGatewayConfig): GatewayFacilitatorLike;
137
+ /** The Gateway server scheme. Extends ExactEvmScheme; merges `extra.verifyingContract` through. */
138
+ export declare function createGatewayScheme(): GatewayEvmScheme;
139
+ /**
140
+ * Construct + liveness-probe the Circle facilitator, fail-open (R0 Q4).
141
+ *
142
+ * Returns null on ANY failure — construction, network error, a facilitator that doesn't advertise
143
+ * our network, or a malformed response. Null means "carry on with CDP only, byte-unchanged".
144
+ * This function is the boot-path firewall: it must never throw, so a Circle outage can never
145
+ * reach x402.ts's `resourceServer = null` catch and take the live CDP rail down with it.
146
+ */
147
+ export declare function probeCircleFacilitator(config: CircleGatewayConfig,
148
+ /** Injectable for tests — lets a suite drive the real catch path with a throwing facilitator. */
149
+ factory?: (c: CircleGatewayConfig) => GatewayFacilitatorLike): Promise<{
150
+ facilitator: GatewayFacilitatorLike;
151
+ verifyingContract?: string;
152
+ } | null>;
153
+ //# sourceMappingURL=circle-gateway.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circle-gateway.d.ts","sourceRoot":"","sources":["../../src/lib/circle-gateway.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,EAA0B,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAI5F,6EAA6E;AAC7E,eAAO,MAAM,8BAA8B,2CAA2C,CAAC;AACvF,8FAA8F;AAC9F,eAAO,MAAM,8BAA8B,mCAAmC,CAAC;AAmB/E,sFAAsF;AACtF,eAAO,MAAM,0BAA0B,yBAAyB,CAAC;AAEjE,8FAA8F;AAC9F,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C;;;GAGG;AACH,eAAO,MAAM,2BAA2B,+CAA+C,CAAC;AAIxF,MAAM,WAAW,mBAAmB;IAClC,2EAA2E;IAC3E,OAAO,EAAE,OAAO,CAAC;IACjB,sFAAsF;IACtF,cAAc,EAAE,MAAM,CAAC;IACvB,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAC;IAChB,oDAAoD;IACpD,aAAa,EAAE,MAAM,CAAC;IACtB,0FAA0F;IAC1F,OAAO,EAAE,OAAO,CAAC;IACjB,sFAAsF;IACtF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAcD;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CAC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G,OAAO,GAAE,CAAC,CAAC,EAAE,mBAAmB,KAAK,sBAAgD,GACpF,OAAO,CAAC;IAAE,WAAW,EAAE,sBAAsB,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAwBrF"}
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayStubFacilitator = exports.GATEWAY_STUB_SELLER_ADDRESS = exports.GATEWAY_STUB_PREFIX = exports.GATEWAY_EIP712_DOMAIN_NAME = exports.CIRCLE_MAINNET_FACILITATOR_URL = exports.CIRCLE_TESTNET_FACILITATOR_URL = void 0;
4
+ exports.resolveCircleGatewayFromEnv = resolveCircleGatewayFromEnv;
5
+ exports.createCircleFacilitator = createCircleFacilitator;
6
+ exports.createGatewayScheme = createGatewayScheme;
7
+ exports.probeCircleFacilitator = probeCircleFacilitator;
8
+ /**
9
+ * Circle Gateway Nanopayments — ADDITIVE x402 payment scheme (CIRCLE-GATEWAY-MIGRATE-W1).
10
+ *
11
+ * This is NOT a migration and NOT a second rail. Circle Gateway is a payment *method* on
12
+ * the SAME `exact` scheme our CDP rail already speaks — Circle's own facilitator advertises
13
+ * `"scheme":"exact"` on every supported kind (live-probed 2026-07-17). What distinguishes a
14
+ * Gateway kind from a CDP kind is the NETWORK plus `extra.name === 'GatewayWalletBatched'`
15
+ * (the EIP-712 *domain name*) and `extra.verifyingContract`.
16
+ *
17
+ * >>> `GatewayWalletBatched` IS NOT AN x402 SCHEME ID. <<<
18
+ * Anything asserting `accepts[].scheme === 'GatewayWalletBatched'` is wrong by construction.
19
+ * (R0 probe: SDK `CIRCLE_BATCHING_SCHEME === 'exact'` while `CIRCLE_BATCHING_NAME ===
20
+ * 'GatewayWalletBatched'`; Circle's seller quickstart shows `"scheme": "exact"`.)
21
+ *
22
+ * Integration shape = "Path B" (architect-ratified R0 Q2): the Circle facilitator joins the
23
+ * EXISTING `x402ResourceServer`'s facilitator array and `GatewayEvmScheme` registers on the
24
+ * Gateway network, so ONE 402 advertises both rails. The alternative (`createGatewayMiddleware`,
25
+ * Circle's quickstart default) is a standalone Express middleware owning its own 402 and CANNOT
26
+ * dual-advertise.
27
+ *
28
+ * SAFETY — why every failure path here is fail-open (R0 Q4, mandatory):
29
+ * `x402ResourceServer.initialize()` fans `getSupported()` across EVERY facilitator in its array.
30
+ * A throw propagates to x402.ts's catch, which sets `resourceServer = null` and disables payments
31
+ * ENTIRELY — i.e. a Circle outage would take the LIVE CDP mainnet revenue rail dark with it. That
32
+ * is the 2026-07-01 OKX crash-loop failure mode (system-map:284 — an uncaught async
33
+ * `RouteConfigurationError` at boot 502'd api.algovault.com for ~1-2min). So: this module NEVER
34
+ * throws into the boot path. It probes Circle in its OWN try/catch and, on ANY failure, returns
35
+ * null → the caller keeps the CDP-only array byte-unchanged.
36
+ *
37
+ * Two-flag firewall:
38
+ * outer `CIRCLE_GATEWAY_ENABLED` (default OFF) → facilitator is NEVER constructed
39
+ * inner config-present (`CIRCLE_GATEWAY_SELLER_ADDRESS`) → absent falls back to the Stub
40
+ */
41
+ const server_1 = require("@circle-fin/x402-batching/server");
42
+ // ── Hosts ──
43
+ /** Circle Gateway testnet facilitator. Live-probed 2026-07-17 → HTTP 200. */
44
+ exports.CIRCLE_TESTNET_FACILITATOR_URL = 'https://gateway-api-testnet.circle.com';
45
+ /** Circle Gateway mainnet facilitator. NOT reachable from this wave — see MAINNET_BLOCKED. */
46
+ exports.CIRCLE_MAINNET_FACILITATOR_URL = 'https://gateway-api.circle.com';
47
+ /**
48
+ * Facilitator hosts this wave is ALLOWED to talk to. Allow-list, never deny-list.
49
+ *
50
+ * Two live traps this closes:
51
+ * 1. `BatchFacilitatorConfig.url` is OPTIONAL and the SDK defaults it to MAINNET
52
+ * (`gateway-api.circle.com`) — `new BatchFacilitatorClient()` with no args silently points at
53
+ * mainnet, contradicting "mainnet stays OFF". We always pass `url` explicitly AND verify it.
54
+ * 2. Circle's own `BatchFacilitatorClient` JSDoc example cites `https://gateway.circle.com`,
55
+ * which is NXDOMAIN (probed). Copying it verbatim yields a dead facilitator.
56
+ */
57
+ const ALLOWED_FACILITATOR_URLS = [exports.CIRCLE_TESTNET_FACILITATOR_URL];
58
+ /** CAIP-2 networks this wave is ALLOWED to advertise. Testnet only (architect R0 Q5a). */
59
+ const ALLOWED_GATEWAY_NETWORKS = [
60
+ 'eip155:84532', // Base Sepolia — our x402.ts already maps base-sepolia + holds the matching USDC
61
+ ];
62
+ /** The `extra.name` Circle stamps on every Gateway kind — the EIP-712 domain name. */
63
+ exports.GATEWAY_EIP712_DOMAIN_NAME = 'GatewayWalletBatched';
64
+ /** Marker prefix for stub-sourced values, so a stub can never be mistaken for a live rail. */
65
+ exports.GATEWAY_STUB_PREFIX = '[STUB]';
66
+ /**
67
+ * Seller address used when the Gateway is enabled but unconfigured (Stub path). Deliberately the
68
+ * zero address: it is inert, obviously-not-real in logs, and can never receive value.
69
+ */
70
+ exports.GATEWAY_STUB_SELLER_ADDRESS = '0x0000000000000000000000000000000000000000';
71
+ const DISABLED = (reason) => ({
72
+ enabled: false,
73
+ facilitatorUrl: exports.CIRCLE_TESTNET_FACILITATOR_URL,
74
+ network: ALLOWED_GATEWAY_NETWORKS[0],
75
+ sellerAddress: '',
76
+ useStub: false,
77
+ reason,
78
+ });
79
+ /** Strict EVM address shape. Untrusted env → validate before it reaches payTo. */
80
+ const isEvmAddress = (v) => /^0x[0-9a-fA-F]{40}$/.test(v);
81
+ /**
82
+ * Resolve the Gateway config from env. Pure + total: it NEVER throws and NEVER constructs a
83
+ * client — callers decide what to do with a disabled result.
84
+ *
85
+ * Default-deny at every step: an unset/typo'd flag, a bad address, a non-allow-listed host or
86
+ * network all resolve to `enabled: false` with a reason, not to a permissive fallback.
87
+ */
88
+ function resolveCircleGatewayFromEnv(env = process.env) {
89
+ // ── Outer flag ── default OFF. Anything but an exact 'true' keeps the rail inert.
90
+ if ((env.CIRCLE_GATEWAY_ENABLED || '').toLowerCase() !== 'true') {
91
+ return DISABLED('CIRCLE_GATEWAY_ENABLED is not "true" (default OFF)');
92
+ }
93
+ // ── Facilitator host ── explicit + allow-listed. Never inherit the SDK's mainnet default.
94
+ const facilitatorUrl = env.CIRCLE_GATEWAY_FACILITATOR_URL || exports.CIRCLE_TESTNET_FACILITATOR_URL;
95
+ if (!ALLOWED_FACILITATOR_URLS.includes(facilitatorUrl)) {
96
+ return DISABLED(`facilitator ${facilitatorUrl} is not testnet-allow-listed. This wave is testnet-only; ` +
97
+ `enabling mainnet (${exports.CIRCLE_MAINNET_FACILITATOR_URL}) is a separate dispatch after a real ` +
98
+ `testnet settle + operator go.`);
99
+ }
100
+ // ── Network ── testnet only.
101
+ const network = env.CIRCLE_GATEWAY_NETWORK || ALLOWED_GATEWAY_NETWORKS[0];
102
+ if (!ALLOWED_GATEWAY_NETWORKS.includes(network)) {
103
+ return DISABLED(`network ${network} is not testnet-allow-listed (allowed: ${ALLOWED_GATEWAY_NETWORKS.join(', ')})`);
104
+ }
105
+ // ── Inner flag: config-present ── absent → Stub (R2: the wave ships regardless of Circle
106
+ // account state). Present-but-malformed → default-deny rather than silently paying a bad addr.
107
+ const rawSeller = (env.CIRCLE_GATEWAY_SELLER_ADDRESS || '').trim();
108
+ if (!rawSeller) {
109
+ return {
110
+ enabled: true,
111
+ facilitatorUrl,
112
+ network,
113
+ sellerAddress: exports.GATEWAY_STUB_SELLER_ADDRESS,
114
+ useStub: true,
115
+ reason: 'CIRCLE_GATEWAY_SELLER_ADDRESS absent — Stub facilitator (no live Gateway settle)',
116
+ };
117
+ }
118
+ if (!isEvmAddress(rawSeller)) {
119
+ return DISABLED(`CIRCLE_GATEWAY_SELLER_ADDRESS is not a valid EVM address: ${rawSeller.slice(0, 10)}…`);
120
+ }
121
+ return { enabled: true, facilitatorUrl, network, sellerAddress: rawSeller, useStub: false };
122
+ }
123
+ /**
124
+ * Stub Circle facilitator (R2). Returns a realistic `getSupported()` shape — same field names,
125
+ * same `scheme:'exact'`, same `extra.name`/`verifyingContract` keys as the live facilitator — so
126
+ * the 402 `accepts[]` has the true shape without any Circle account.
127
+ *
128
+ * It NEVER validates a payment: `verify` returns invalid and `settle` returns failure, both
129
+ * `[STUB]`-prefixed. A stub that "succeeded" would be a free-money bug.
130
+ */
131
+ class GatewayStubFacilitator {
132
+ network;
133
+ verifyingContract;
134
+ constructor(network,
135
+ /** Shape-accurate placeholder; NOT the live GatewayWallet. Live value comes from Circle. */
136
+ verifyingContract = '0x0000000000000000000000000000000000000000') {
137
+ this.network = network;
138
+ this.verifyingContract = verifyingContract;
139
+ }
140
+ async getSupported() {
141
+ return {
142
+ kinds: [
143
+ {
144
+ x402Version: 2,
145
+ scheme: 'exact', // NOT 'GatewayWalletBatched' — see module header.
146
+ network: this.network,
147
+ extra: {
148
+ name: exports.GATEWAY_EIP712_DOMAIN_NAME,
149
+ version: '1',
150
+ verifyingContract: this.verifyingContract,
151
+ stub: true,
152
+ },
153
+ },
154
+ ],
155
+ extensions: [],
156
+ signers: {},
157
+ };
158
+ }
159
+ async verify() {
160
+ return { isValid: false, invalidReason: `${exports.GATEWAY_STUB_PREFIX} Circle Gateway stub cannot verify payments` };
161
+ }
162
+ async settle() {
163
+ return {
164
+ success: false,
165
+ errorReason: `${exports.GATEWAY_STUB_PREFIX} Circle Gateway stub cannot settle payments`,
166
+ transaction: '',
167
+ network: this.network,
168
+ };
169
+ }
170
+ }
171
+ exports.GatewayStubFacilitator = GatewayStubFacilitator;
172
+ // ── Factory ──
173
+ /**
174
+ * Build the Circle facilitator for a resolved config. Stub when unconfigured, real
175
+ * `BatchFacilitatorClient` (explicit testnet URL) otherwise.
176
+ *
177
+ * Throws only on programmer error (disabled config). Callers in the boot path must still wrap —
178
+ * see `probeCircleFacilitator`.
179
+ */
180
+ function createCircleFacilitator(config) {
181
+ if (!config.enabled) {
182
+ throw new Error('createCircleFacilitator called with a disabled config');
183
+ }
184
+ if (config.useStub) {
185
+ return new GatewayStubFacilitator(config.network);
186
+ }
187
+ // `url` is ALWAYS passed: the SDK's default is MAINNET (BatchFacilitatorConfig.url is optional).
188
+ return new server_1.BatchFacilitatorClient({ url: config.facilitatorUrl });
189
+ }
190
+ /** The Gateway server scheme. Extends ExactEvmScheme; merges `extra.verifyingContract` through. */
191
+ function createGatewayScheme() {
192
+ return new server_1.GatewayEvmScheme();
193
+ }
194
+ /**
195
+ * Construct + liveness-probe the Circle facilitator, fail-open (R0 Q4).
196
+ *
197
+ * Returns null on ANY failure — construction, network error, a facilitator that doesn't advertise
198
+ * our network, or a malformed response. Null means "carry on with CDP only, byte-unchanged".
199
+ * This function is the boot-path firewall: it must never throw, so a Circle outage can never
200
+ * reach x402.ts's `resourceServer = null` catch and take the live CDP rail down with it.
201
+ */
202
+ async function probeCircleFacilitator(config,
203
+ /** Injectable for tests — lets a suite drive the real catch path with a throwing facilitator. */
204
+ factory = createCircleFacilitator) {
205
+ if (!config.enabled)
206
+ return null;
207
+ try {
208
+ const facilitator = factory(config);
209
+ const supported = await facilitator.getSupported();
210
+ const kind = supported?.kinds?.find((k) => k.network === config.network && k.scheme === 'exact');
211
+ if (!kind) {
212
+ console.warn(`circle-gateway: facilitator ${config.facilitatorUrl} does not advertise exact on ` +
213
+ `${config.network} — Gateway scheme NOT registered; CDP rail unaffected.`);
214
+ return null;
215
+ }
216
+ return { facilitator, verifyingContract: kind.extra?.verifyingContract };
217
+ }
218
+ catch (err) {
219
+ // Fail-open, always. A Circle problem is never allowed to become a CDP problem.
220
+ console.warn('circle-gateway: probe failed — Gateway scheme NOT registered; CDP rail unaffected:', err instanceof Error ? err.message : err);
221
+ return null;
222
+ }
223
+ }
224
+ //# sourceMappingURL=circle-gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circle-gateway.js","sourceRoot":"","sources":["../../src/lib/circle-gateway.ts"],"names":[],"mappings":";;;AA2GA,kEA0CC;AA4ED,0DASC;AAGD,kDAEC;AAUD,wDA4BC;AArRD;;;;;;;;;;;;;;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AAC3B,iGAAiG;AACjG,UAA8D,uBAAuB;IAErF,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IACjC,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;QACpC,MAAM,SAAS,GAAG,MAAM,WAAW,CAAC,YAAY,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,IAAI,CACjC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC,MAAM,KAAK,OAAO,CAC5D,CAAC;QACF,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,CAAC,IAAI,CACV,+BAA+B,MAAM,CAAC,cAAc,+BAA+B;gBACjF,GAAG,MAAM,CAAC,OAAO,wDAAwD,CAC5E,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,IAAI,CAAC,KAAK,EAAE,iBAAuC,EAAE,CAAC;IACjG,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,gFAAgF;QAChF,OAAO,CAAC,IAAI,CACV,oFAAoF,EACpF,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CACzC,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Gas-wallet balance quorum — OPS-GAS-WALLET-RPC-QUORUM-W1.
3
+ *
4
+ * Why this exists: the monitor used to page "Gas wallet low" off the FIRST
5
+ * valid-looking RPC read. Public Base RPCs intermittently return a well-formed
6
+ * { result: "0x0" } when the backend node behind their load balancer is pruned
7
+ * or lagging — that passes a `0x`-prefix check and reads as 0.000000 ETH. On
8
+ * 2026-07-17 this produced 28 false "Gas wallet low: 0.000000 ETH" readings
9
+ * (one paged Telegram) while the wallet held ~0.0471 ETH at every Base block.
10
+ *
11
+ * Fix: a LOW verdict requires independent corroboration from >= N distinct
12
+ * endpoints and must not be outnumbered by healthy reads. Trust is
13
+ * deliberately asymmetric — public nodes fail by UNDER-reporting (pruned state
14
+ * -> 0x0), not by fabricating a high balance — so a single healthy read is
15
+ * enough to refute a lone low read, while a genuine drain (every endpoint
16
+ * agrees) still pages on the very next 2-minute cycle.
17
+ *
18
+ * Parsing is kept separate from trusting: parseGasBalanceResult() accepts 0x0
19
+ * as a legitimately-parsed zero, and evaluateGasQuorum() decides whether to
20
+ * believe it.
21
+ */
22
+ /** Low-water mark, in ETH, below which the facilitator gas wallet is "low". */
23
+ export declare const GAS_WALLET_MIN_ETH = 0.005;
24
+ /** Distinct endpoints that must independently agree before a low verdict pages. */
25
+ export declare const GAS_LOW_CONFIRMATIONS = 2;
26
+ export type GasRead = {
27
+ endpoint: string;
28
+ ok: true;
29
+ eth: number;
30
+ } | {
31
+ endpoint: string;
32
+ ok: false;
33
+ error: string;
34
+ };
35
+ export type GasQuorumVerdict = 'healthy' | 'low' | 'unconfirmed' | 'no-data';
36
+ export interface GasQuorumResult {
37
+ verdict: GasQuorumVerdict;
38
+ /** Operator-facing alert text. Non-null ONLY for a corroborated low. */
39
+ error: string | null;
40
+ balance: number;
41
+ detail: string;
42
+ }
43
+ export interface GasQuorumOptions {
44
+ minEth?: number;
45
+ requiredConfirmations?: number;
46
+ }
47
+ /** Parse an eth_getBalance JSON-RPC body into ETH. Never coerces junk to 0. */
48
+ export declare function parseGasBalanceResult(data: unknown): {
49
+ ok: true;
50
+ eth: number;
51
+ } | {
52
+ ok: false;
53
+ error: string;
54
+ };
55
+ /**
56
+ * Decide the gas-wallet verdict from a set of per-endpoint reads.
57
+ *
58
+ * - `low` — >= requiredConfirmations distinct endpoints agree it is
59
+ * below the floor, and they are not outnumbered. Pages.
60
+ * - `unconfirmed` — at least one low read, but not corroborated. Never pages;
61
+ * the caller should log `detail` for forensics.
62
+ * - `healthy` — no endpoint reported below the floor.
63
+ * - `no-data` — zero valid reads; caller reports the RPC-exhausted error.
64
+ */
65
+ export declare function evaluateGasQuorum(reads: readonly GasRead[], opts?: GasQuorumOptions): GasQuorumResult;
66
+ //# sourceMappingURL=gas-wallet-quorum.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas-wallet-quorum.d.ts","sourceRoot":"","sources":["../../src/lib/gas-wallet-quorum.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,+EAA+E;AAC/E,eAAO,MAAM,kBAAkB,QAAQ,CAAC;AAExC,mFAAmF;AACnF,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAEvC,MAAM,MAAM,OAAO,GACf;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnD,MAAM,MAAM,gBAAgB,GAAG,SAAS,GAAG,KAAK,GAAG,aAAa,GAAG,SAAS,CAAC;AAE7E,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,wEAAwE;IACxE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AASD,+EAA+E;AAC/E,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,OAAO,GACZ;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAkB1D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,SAAS,OAAO,EAAE,EACzB,IAAI,GAAE,gBAAqB,GAC1B,eAAe,CAqDjB"}
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * Gas-wallet balance quorum — OPS-GAS-WALLET-RPC-QUORUM-W1.
4
+ *
5
+ * Why this exists: the monitor used to page "Gas wallet low" off the FIRST
6
+ * valid-looking RPC read. Public Base RPCs intermittently return a well-formed
7
+ * { result: "0x0" } when the backend node behind their load balancer is pruned
8
+ * or lagging — that passes a `0x`-prefix check and reads as 0.000000 ETH. On
9
+ * 2026-07-17 this produced 28 false "Gas wallet low: 0.000000 ETH" readings
10
+ * (one paged Telegram) while the wallet held ~0.0471 ETH at every Base block.
11
+ *
12
+ * Fix: a LOW verdict requires independent corroboration from >= N distinct
13
+ * endpoints and must not be outnumbered by healthy reads. Trust is
14
+ * deliberately asymmetric — public nodes fail by UNDER-reporting (pruned state
15
+ * -> 0x0), not by fabricating a high balance — so a single healthy read is
16
+ * enough to refute a lone low read, while a genuine drain (every endpoint
17
+ * agrees) still pages on the very next 2-minute cycle.
18
+ *
19
+ * Parsing is kept separate from trusting: parseGasBalanceResult() accepts 0x0
20
+ * as a legitimately-parsed zero, and evaluateGasQuorum() decides whether to
21
+ * believe it.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.GAS_LOW_CONFIRMATIONS = exports.GAS_WALLET_MIN_ETH = void 0;
25
+ exports.parseGasBalanceResult = parseGasBalanceResult;
26
+ exports.evaluateGasQuorum = evaluateGasQuorum;
27
+ /** Low-water mark, in ETH, below which the facilitator gas wallet is "low". */
28
+ exports.GAS_WALLET_MIN_ETH = 0.005;
29
+ /** Distinct endpoints that must independently agree before a low verdict pages. */
30
+ exports.GAS_LOW_CONFIRMATIONS = 2;
31
+ /**
32
+ * A JSON-RPC QUANTITY: 0x followed by at least one hex digit. Deliberately
33
+ * stricter than `startsWith('0x')` — '0x', '0xzz' and a bare decimal string
34
+ * must be rejected outright rather than coerced toward 0.
35
+ */
36
+ const HEX_QUANTITY = /^0x[0-9a-fA-F]+$/;
37
+ /** Parse an eth_getBalance JSON-RPC body into ETH. Never coerces junk to 0. */
38
+ function parseGasBalanceResult(data) {
39
+ if (data === null || typeof data !== 'object') {
40
+ return { ok: false, error: 'RPC returned non-JSON response' };
41
+ }
42
+ const body = data;
43
+ if (body.error) {
44
+ return {
45
+ ok: false,
46
+ error: `RPC error: ${body.error.message ?? JSON.stringify(body.error)}`,
47
+ };
48
+ }
49
+ if (typeof body.result !== 'string' || !HEX_QUANTITY.test(body.result)) {
50
+ return {
51
+ ok: false,
52
+ error: `Invalid RPC response (no usable hex result): ${JSON.stringify(data).slice(0, 200)}`,
53
+ };
54
+ }
55
+ return { ok: true, eth: Number(BigInt(body.result)) / 1e18 };
56
+ }
57
+ /**
58
+ * Decide the gas-wallet verdict from a set of per-endpoint reads.
59
+ *
60
+ * - `low` — >= requiredConfirmations distinct endpoints agree it is
61
+ * below the floor, and they are not outnumbered. Pages.
62
+ * - `unconfirmed` — at least one low read, but not corroborated. Never pages;
63
+ * the caller should log `detail` for forensics.
64
+ * - `healthy` — no endpoint reported below the floor.
65
+ * - `no-data` — zero valid reads; caller reports the RPC-exhausted error.
66
+ */
67
+ function evaluateGasQuorum(reads, opts = {}) {
68
+ const minEth = opts.minEth ?? exports.GAS_WALLET_MIN_ETH;
69
+ const required = opts.requiredConfirmations ?? exports.GAS_LOW_CONFIRMATIONS;
70
+ // Two reads from the SAME endpoint are one node's opinion, not independent
71
+ // corroboration — dedupe (first wins) before counting votes.
72
+ const seen = new Set();
73
+ const valid = [];
74
+ for (const r of reads) {
75
+ if (!r.ok || seen.has(r.endpoint))
76
+ continue;
77
+ seen.add(r.endpoint);
78
+ valid.push({ endpoint: r.endpoint, eth: r.eth });
79
+ }
80
+ if (valid.length === 0) {
81
+ return { verdict: 'no-data', error: null, balance: 0, detail: 'no valid RPC reads' };
82
+ }
83
+ const low = valid.filter(v => v.eth < minEth);
84
+ const healthy = valid.filter(v => v.eth >= minEth);
85
+ const maxEth = Math.max(...valid.map(v => v.eth));
86
+ const summary = valid.map(v => `${v.endpoint}=${v.eth.toFixed(6)}`).join(', ');
87
+ if (low.length >= required && low.length >= healthy.length) {
88
+ const worst = Math.min(...low.map(v => v.eth));
89
+ return {
90
+ verdict: 'low',
91
+ error: `Gas wallet low: ${worst.toFixed(6)} ETH (< ${minEth}) — ` +
92
+ `confirmed by ${low.length}/${valid.length} independent RPCs [${summary}]`,
93
+ balance: worst,
94
+ detail: summary,
95
+ };
96
+ }
97
+ if (low.length > 0) {
98
+ return {
99
+ verdict: 'unconfirmed',
100
+ error: null,
101
+ // Report the corroborated truth, not the suspect zero.
102
+ balance: maxEth,
103
+ detail: `uncorroborated low read (${low.length}/${valid.length} below ${minEth}; ` +
104
+ `need ${required} and not outnumbered) [${summary}]`,
105
+ };
106
+ }
107
+ return {
108
+ verdict: 'healthy',
109
+ error: null,
110
+ balance: maxEth,
111
+ detail: `${valid.length} RPC read(s) >= ${minEth} [${summary}]`,
112
+ };
113
+ }
114
+ //# sourceMappingURL=gas-wallet-quorum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas-wallet-quorum.js","sourceRoot":"","sources":["../../src/lib/gas-wallet-quorum.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAmCH,sDAoBC;AAYD,8CAwDC;AAzHD,+EAA+E;AAClE,QAAA,kBAAkB,GAAG,KAAK,CAAC;AAExC,mFAAmF;AACtE,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAqBvC;;;;GAIG;AACH,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAExC,+EAA+E;AAC/E,SAAgB,qBAAqB,CACnC,IAAa;IAEb,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QA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