@blockrun/franklin 3.43.1 → 3.45.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/README.md +105 -11
- package/dist/agent/intent-prefetch.js +4 -3
- package/dist/agent/llm.js +5 -0
- package/dist/agent/loop.js +7 -4
- package/dist/agent/secret-redact.js +11 -0
- package/dist/commands/balance.js +57 -1
- package/dist/commands/doctor.js +48 -2
- package/dist/commands/login.d.ts +14 -0
- package/dist/commands/login.js +97 -0
- package/dist/commands/models.js +3 -2
- package/dist/commands/plugin.js +3 -2
- package/dist/commands/predict.js +3 -2
- package/dist/commands/proxy.js +3 -2
- package/dist/commands/setup.js +15 -1
- package/dist/commands/slack.js +3 -2
- package/dist/commands/social.js +3 -2
- package/dist/commands/start.js +3 -2
- package/dist/commands/stats.js +18 -1
- package/dist/commands/telegram.js +3 -2
- package/dist/config.d.ts +5 -0
- package/dist/config.js +17 -0
- package/dist/gateway-models.js +9 -4
- package/dist/index.js +26 -3
- package/dist/onramp/client.js +3 -2
- package/dist/payments/auth-mode.d.ts +148 -0
- package/dist/payments/auth-mode.js +225 -0
- package/dist/payments/post-with-payment.d.ts +6 -0
- package/dist/payments/post-with-payment.js +40 -6
- package/dist/payments/price-catalog.d.ts +132 -0
- package/dist/payments/price-catalog.js +457 -0
- package/dist/phone/client.js +6 -2
- package/dist/pricing.js +3 -3
- package/dist/proxy/server.js +11 -0
- package/dist/router/index.js +2 -1
- package/dist/serve/cloud-sync.d.ts +1 -0
- package/dist/serve/server.js +10 -3
- package/dist/stats/tracker.d.ts +15 -1
- package/dist/stats/tracker.js +14 -2
- package/dist/tools/blockrun.js +10 -3
- package/dist/tools/defillama.d.ts +5 -5
- package/dist/tools/defillama.js +19 -13
- package/dist/tools/exa.d.ts +1 -1
- package/dist/tools/exa.js +43 -21
- package/dist/tools/imagegen.js +4 -2
- package/dist/tools/modal.js +4 -2
- package/dist/tools/musicgen.js +4 -2
- package/dist/tools/phone.js +4 -2
- package/dist/tools/prediction.js +16 -4
- package/dist/tools/realface.js +14 -8
- package/dist/tools/rpc.d.ts +1 -1
- package/dist/tools/rpc.js +12 -5
- package/dist/tools/surf.js +42 -6
- package/dist/tools/videogen.js +4 -2
- package/dist/tools/voice.js +6 -4
- package/dist/tools/zerox-base.js +4 -2
- package/dist/tools/zerox-gasless.js +6 -4
- package/dist/trading/providers/blockrun/client.js +20 -7
- package/dist/ui/model-picker.js +1 -1
- package/package.json +8 -4
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
15
15
|
import { loadChain, USER_AGENT } from '../config.js';
|
|
16
|
+
import { classifyKeyFailure, gatewayHeaders, invalidateKey, resolvePayMode, toWalletUrl, } from './auth-mode.js';
|
|
16
17
|
async function extractPaymentReq(response) {
|
|
17
18
|
let header = response.headers.get('payment-required');
|
|
18
19
|
if (!header) {
|
|
@@ -63,24 +64,56 @@ async function signPayment(response, chain, endpoint, resourceDescription) {
|
|
|
63
64
|
*/
|
|
64
65
|
export async function postWithPayment(endpoint, body, resourceDescription, timeoutMs = 30_000) {
|
|
65
66
|
const chain = loadChain();
|
|
66
|
-
const headers = {
|
|
67
|
-
'Content-Type': 'application/json',
|
|
68
|
-
'User-Agent': USER_AGENT,
|
|
69
|
-
};
|
|
70
67
|
const ctrl = new AbortController();
|
|
71
68
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
72
69
|
try {
|
|
73
70
|
const payload = JSON.stringify(body);
|
|
71
|
+
const mode = resolvePayMode();
|
|
72
|
+
// Key mode: one authenticated POST, no 402 dance. The gateway settles
|
|
73
|
+
// against the prepaid balance and answers 200 directly.
|
|
74
|
+
if (mode.kind === 'key') {
|
|
75
|
+
const keyHeaders = {
|
|
76
|
+
'Content-Type': 'application/json',
|
|
77
|
+
...gatewayHeaders(mode),
|
|
78
|
+
};
|
|
79
|
+
const keyResponse = await fetch(endpoint, {
|
|
80
|
+
method: 'POST',
|
|
81
|
+
signal: ctrl.signal,
|
|
82
|
+
headers: keyHeaders,
|
|
83
|
+
body: payload,
|
|
84
|
+
});
|
|
85
|
+
const keyRaw = await keyResponse.text().catch(() => '');
|
|
86
|
+
const failure = classifyKeyFailure(keyResponse.status, keyRaw);
|
|
87
|
+
// Only a bad key or a path the key host does not serve is worth retrying
|
|
88
|
+
// on the wallet. Anything else (400, 402, 5xx) is returned as-is so a
|
|
89
|
+
// malformed request never silently spends wallet USDC on a second try.
|
|
90
|
+
if (!failure) {
|
|
91
|
+
let parsedKey = {};
|
|
92
|
+
try {
|
|
93
|
+
parsedKey = keyRaw ? JSON.parse(keyRaw) : {};
|
|
94
|
+
}
|
|
95
|
+
catch { /* leave as {} */ }
|
|
96
|
+
return { ok: keyResponse.ok, status: keyResponse.status, body: parsedKey, raw: keyRaw, settled: false };
|
|
97
|
+
}
|
|
98
|
+
if (failure === 'invalid-key')
|
|
99
|
+
invalidateKey();
|
|
100
|
+
endpoint = toWalletUrl(endpoint, chain);
|
|
101
|
+
}
|
|
102
|
+
const headers = {
|
|
103
|
+
'Content-Type': 'application/json',
|
|
104
|
+
'User-Agent': USER_AGENT,
|
|
105
|
+
};
|
|
74
106
|
let response = await fetch(endpoint, {
|
|
75
107
|
method: 'POST',
|
|
76
108
|
signal: ctrl.signal,
|
|
77
109
|
headers,
|
|
78
110
|
body: payload,
|
|
79
111
|
});
|
|
112
|
+
let settled = false;
|
|
80
113
|
if (response.status === 402) {
|
|
81
114
|
const paymentHeaders = await signPayment(response, chain, endpoint, resourceDescription);
|
|
82
115
|
if (!paymentHeaders) {
|
|
83
|
-
return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '' };
|
|
116
|
+
return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '', settled: false };
|
|
84
117
|
}
|
|
85
118
|
response = await fetch(endpoint, {
|
|
86
119
|
method: 'POST',
|
|
@@ -88,6 +121,7 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
|
|
|
88
121
|
headers: { ...headers, ...paymentHeaders },
|
|
89
122
|
body: payload,
|
|
90
123
|
});
|
|
124
|
+
settled = response.ok;
|
|
91
125
|
}
|
|
92
126
|
const raw = await response.text().catch(() => '');
|
|
93
127
|
let parsed = {};
|
|
@@ -95,7 +129,7 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
|
|
|
95
129
|
parsed = raw ? JSON.parse(raw) : {};
|
|
96
130
|
}
|
|
97
131
|
catch { /* leave as {} */ }
|
|
98
|
-
return { ok: response.ok, status: response.status, body: parsed, raw };
|
|
132
|
+
return { ok: response.ok, status: response.status, body: parsed, raw, settled };
|
|
99
133
|
}
|
|
100
134
|
finally {
|
|
101
135
|
clearTimeout(timer);
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* List prices for the gateway's flat-rate service endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Wallet mode learns what a call costs from the 402 handshake — the amount is
|
|
5
|
+
* in the payment requirements, so the recorded spend is exact. API-key mode
|
|
6
|
+
* has no handshake: the gateway settles against a prepaid balance and answers
|
|
7
|
+
* 200 with no charge amount anywhere in the response. Without a price source,
|
|
8
|
+
* every paid call in key mode would record $0, which silently disables the
|
|
9
|
+
* --max-spend ceiling, the PreSpend hooks and every budget in the product.
|
|
10
|
+
*
|
|
11
|
+
* BlockRun publishes machine-readable prices at `/.well-known/x402`, so that
|
|
12
|
+
* is the source of truth here rather than constants scattered across tools
|
|
13
|
+
* (which had already drifted — surf.ts documented tiered $0.001/$0.005/$0.02
|
|
14
|
+
* against a catalog that says a flat $0.0085).
|
|
15
|
+
*
|
|
16
|
+
* Scope is deliberately narrow: **flat-rate service endpoints only**.
|
|
17
|
+
* Model-priced endpoints — chat, images, video, speech — are already costed by
|
|
18
|
+
* `gateway-models.ts` from the live model catalog, and that path works
|
|
19
|
+
* identically in both modes.
|
|
20
|
+
*
|
|
21
|
+
* Prices from this module are estimates. Callers must tag what they record so
|
|
22
|
+
* the audit trail never claims more precision than it has.
|
|
23
|
+
*/
|
|
24
|
+
interface CatalogEntry {
|
|
25
|
+
/** Endpoint pattern as published, e.g. `/api/v1/surf/*`. */
|
|
26
|
+
endpoint: string;
|
|
27
|
+
/** USD per request, or 0 for a free endpoint. */
|
|
28
|
+
usd: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Refresh the catalog in the background. Safe to call repeatedly; only one
|
|
32
|
+
* fetch is ever in flight and it is skipped while the cache is fresh.
|
|
33
|
+
*/
|
|
34
|
+
export declare function warmPriceCatalog(): void;
|
|
35
|
+
/** Test seam — drop the loaded catalog and fall back to the static floor. */
|
|
36
|
+
export declare function __resetPriceCatalog(): void;
|
|
37
|
+
/** Test seam — install a catalog without touching the network or disk. */
|
|
38
|
+
export declare function __primePriceCatalog(entries: CatalogEntry[]): void;
|
|
39
|
+
/**
|
|
40
|
+
* List price in USD for one gateway path, or null when the path is not a
|
|
41
|
+
* flat-rate service endpoint (chat and the other model-priced endpoints land
|
|
42
|
+
* here, and are costed from the model catalog instead).
|
|
43
|
+
*
|
|
44
|
+
* `apiPath` may be a bare path or a full URL, with or without the `/api`
|
|
45
|
+
* prefix and with or without a query string — the two payment hosts differ on
|
|
46
|
+
* the prefix and callers should not have to care.
|
|
47
|
+
*
|
|
48
|
+
* Synchronous by design: it is called on the response path of every paid tool,
|
|
49
|
+
* where an await would serialise the accounting behind a network fetch. The
|
|
50
|
+
* catalog refreshes in the background via `warmPriceCatalog()`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function priceForPath(apiPath: string): number | null;
|
|
53
|
+
/**
|
|
54
|
+
* The base price for an endpoint — what the API-key rail charges — or null
|
|
55
|
+
* when the endpoint is not catalogued.
|
|
56
|
+
*
|
|
57
|
+
* There are two real prices per endpoint and one literal cannot serve both.
|
|
58
|
+
* The catalog and the 402 challenge both state the WALLET price, which is the
|
|
59
|
+
* base plus a settlement fee. The key rail charges the base and no fee, which
|
|
60
|
+
* is why it issues no 402 at all.
|
|
61
|
+
*
|
|
62
|
+
* Measured 2026-09-05 via x-blockrun-cost-usd against the unsigned 402:
|
|
63
|
+
*
|
|
64
|
+
* endpoint 402 / catalog key rail charges
|
|
65
|
+
* surf $0.0085 $0.0075
|
|
66
|
+
* rpc $0.0030 $0.0020
|
|
67
|
+
* exa search $0.0110 $0.0100
|
|
68
|
+
* defillama $0.0060 $0.0050
|
|
69
|
+
*
|
|
70
|
+
* Exactly one fee apart, every time. Quoting the 402 figure to a key-mode user
|
|
71
|
+
* overstates every call by $0.001 — small in absolute terms and 50% on a
|
|
72
|
+
* $0.002 RPC call.
|
|
73
|
+
*/
|
|
74
|
+
export declare function basePriceForPath(apiPath: string): number | null;
|
|
75
|
+
/**
|
|
76
|
+
* The exact amount BlockRun charged for this call, from
|
|
77
|
+
* `x-blockrun-cost-usd`, or null when the response does not state one.
|
|
78
|
+
*
|
|
79
|
+
* Live on the pre-priced service families (exa, surf, pm, phone, modal,
|
|
80
|
+
* speech, images, rpc, defillama). Deliberately and permanently ABSENT on
|
|
81
|
+
* chat, which settles after the answer is on the wire (`x-settlement-async`)
|
|
82
|
+
* — at header-writing time the amount does not exist yet, and waiting for it
|
|
83
|
+
* would mean holding the customer's response until the money lands. Chat is
|
|
84
|
+
* reconstructed from tokens x published rate instead.
|
|
85
|
+
*
|
|
86
|
+
* Absent means "no charge settled at response time", NOT "free" — reading it
|
|
87
|
+
* as $0 would zero out chat, the largest spend category. A charge that really
|
|
88
|
+
* did settle at zero is written explicitly as `0.000000`, so 0 is a value and
|
|
89
|
+
* missing is not.
|
|
90
|
+
*
|
|
91
|
+
* Empty, malformed and negative are all treated as absent. `Number('')` is 0
|
|
92
|
+
* in JS, which would book $0 against a billed call.
|
|
93
|
+
*/
|
|
94
|
+
export declare function chargeFromResponse(res: HeaderBag): number | null;
|
|
95
|
+
/**
|
|
96
|
+
* Credit left on the account after this call, from
|
|
97
|
+
* `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
|
|
98
|
+
* ceiling and so nothing to report — that is correct, not a failure.
|
|
99
|
+
*
|
|
100
|
+
* It can understate and never overstates: the figure is read inside the
|
|
101
|
+
* reservation transaction, already net of concurrent in-flight holds. That is
|
|
102
|
+
* the right error direction for a pre-run low-balance warning (warn early
|
|
103
|
+
* rather than fail to warn), and the wrong one for display — GET /v1/credits
|
|
104
|
+
* is the authority for a number shown to a user.
|
|
105
|
+
*/
|
|
106
|
+
export declare function remainingCreditFromResponse(res: HeaderBag): number | null;
|
|
107
|
+
interface HeaderBag {
|
|
108
|
+
headers: {
|
|
109
|
+
get(name: string): string | null;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The amount to record for a completed paid call.
|
|
114
|
+
*
|
|
115
|
+
* `settledUsd` is the exact figure from an x402 settlement and always wins.
|
|
116
|
+
* `reportedUsd` is a charge the endpoint itself returned (Exa's `costDollars`).
|
|
117
|
+
* Otherwise the call is priced from the catalog — an estimate, flagged as such
|
|
118
|
+
* so `franklin stats` can render it honestly.
|
|
119
|
+
*/
|
|
120
|
+
export interface ResolvedCharge {
|
|
121
|
+
usd: number;
|
|
122
|
+
estimated: boolean;
|
|
123
|
+
}
|
|
124
|
+
export declare function resolveCharge(opts: {
|
|
125
|
+
apiPath: string;
|
|
126
|
+
/** From `x-blockrun-cost-usd` — what BlockRun actually charged. Wins outright. */
|
|
127
|
+
chargedUsd?: number | null;
|
|
128
|
+
settledUsd?: number;
|
|
129
|
+
reportedUsd?: number;
|
|
130
|
+
fallbackUsd?: number;
|
|
131
|
+
}): ResolvedCharge;
|
|
132
|
+
export {};
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* List prices for the gateway's flat-rate service endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Wallet mode learns what a call costs from the 402 handshake — the amount is
|
|
5
|
+
* in the payment requirements, so the recorded spend is exact. API-key mode
|
|
6
|
+
* has no handshake: the gateway settles against a prepaid balance and answers
|
|
7
|
+
* 200 with no charge amount anywhere in the response. Without a price source,
|
|
8
|
+
* every paid call in key mode would record $0, which silently disables the
|
|
9
|
+
* --max-spend ceiling, the PreSpend hooks and every budget in the product.
|
|
10
|
+
*
|
|
11
|
+
* BlockRun publishes machine-readable prices at `/.well-known/x402`, so that
|
|
12
|
+
* is the source of truth here rather than constants scattered across tools
|
|
13
|
+
* (which had already drifted — surf.ts documented tiered $0.001/$0.005/$0.02
|
|
14
|
+
* against a catalog that says a flat $0.0085).
|
|
15
|
+
*
|
|
16
|
+
* Scope is deliberately narrow: **flat-rate service endpoints only**.
|
|
17
|
+
* Model-priced endpoints — chat, images, video, speech — are already costed by
|
|
18
|
+
* `gateway-models.ts` from the live model catalog, and that path works
|
|
19
|
+
* identically in both modes.
|
|
20
|
+
*
|
|
21
|
+
* Prices from this module are estimates. Callers must tag what they record so
|
|
22
|
+
* the audit trail never claims more precision than it has.
|
|
23
|
+
*/
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { BLOCKRUN_DIR, USER_AGENT } from '../config.js';
|
|
27
|
+
import { logger } from '../logger.js';
|
|
28
|
+
import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js';
|
|
29
|
+
/**
|
|
30
|
+
* Always the Base origin — because it is the only host serving the SHAPE this
|
|
31
|
+
* module parses, not because it is the only one that publishes prices.
|
|
32
|
+
*
|
|
33
|
+
* Measured 2026-09-05:
|
|
34
|
+
* blockrun.ai/.well-known/x402 68KB, `services[]` with per-endpoint prices
|
|
35
|
+
* sol.blockrun.ai/.well-known/x402 4KB, x402scan v1 fallback shape:
|
|
36
|
+
* {version: 1, resources: [114 strings]},
|
|
37
|
+
* no `services`, no prices
|
|
38
|
+
* sol.blockrun.ai/openapi.json 34 paths priced under `x-payment-info`
|
|
39
|
+
* api.blockrun.ai/.well-known/x402 404
|
|
40
|
+
*
|
|
41
|
+
* So sol does publish prices, just in a different document and schema that
|
|
42
|
+
* parsePricing does not read. Do not "fix" this to fetch /.well-known per host:
|
|
43
|
+
* fetchCatalog bails on a missing `services[]`, so the sol origin would freeze
|
|
44
|
+
* every price at the static floor below with nothing reporting it.
|
|
45
|
+
*
|
|
46
|
+
* Do not switch to sol's openapi prices either, which is the tempting move once
|
|
47
|
+
* you know they exist. They currently disagree with what sol itself quotes and
|
|
48
|
+
* settles. For /v1/surf/market/fear-greed on 2026-09-05:
|
|
49
|
+
*
|
|
50
|
+
* sol openapi.json publishes $0.001
|
|
51
|
+
* sol 402 quotes and settles $0.0075 (measured against a funded wallet)
|
|
52
|
+
* this Base card publishes $0.0085
|
|
53
|
+
*
|
|
54
|
+
* The payment layer charges one flat rate across Surf while sol's sheet still
|
|
55
|
+
* lists three tiers, so nine Surf endpoints publish 7.5x under what they
|
|
56
|
+
* charge. Until that is reconciled the Base card is the closer predictor of a
|
|
57
|
+
* real sol Surf charge, which is the opposite of what you would assume.
|
|
58
|
+
*
|
|
59
|
+
* The remaining Base-vs-Solana gap is the service fee: Solana charges none
|
|
60
|
+
* (SERVICE_FEE_USD = 0 in the sol gateway), so a settled Solana call runs
|
|
61
|
+
* $0.001 under this card. None of this touches the amount recorded for a
|
|
62
|
+
* settled wallet call, which uses the exact 402 figure and never reaches this
|
|
63
|
+
* module — it only bounds how precise a catalog-priced estimate can be.
|
|
64
|
+
*/
|
|
65
|
+
const CATALOG_URL = 'https://blockrun.ai/.well-known/x402';
|
|
66
|
+
const CACHE_FILE = path.join(BLOCKRUN_DIR, 'price-catalog.json');
|
|
67
|
+
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // prices move rarely; a stale read is cheap
|
|
68
|
+
const FETCH_TIMEOUT_MS = 8_000;
|
|
69
|
+
/**
|
|
70
|
+
* Offline floor, current as of 2026-09-05. Used before the first successful
|
|
71
|
+
* fetch and whenever the network is unavailable, so key mode never falls back
|
|
72
|
+
* to recording zero. Refreshed automatically from the live catalog.
|
|
73
|
+
*/
|
|
74
|
+
const STATIC_CATALOG = [
|
|
75
|
+
{ endpoint: '/api/v1/surf/*', usd: 0.0085 },
|
|
76
|
+
{ endpoint: '/api/v1/exa/contents', usd: 0.003 },
|
|
77
|
+
{ endpoint: '/api/v1/exa/*', usd: 0.011 },
|
|
78
|
+
{ endpoint: '/api/v1/rpc/{network}', usd: 0.003 },
|
|
79
|
+
{ endpoint: '/api/v1/pm/*', usd: 0.0085 },
|
|
80
|
+
{ endpoint: '/api/v1/defillama/*', usd: 0.006 },
|
|
81
|
+
{ endpoint: '/api/v1/phone/*', usd: 0.011 },
|
|
82
|
+
{ endpoint: '/api/v1/voice/call', usd: 0.541 },
|
|
83
|
+
{ endpoint: '/api/v1/modal/sandbox/create', usd: 0.011 },
|
|
84
|
+
{ endpoint: '/api/v1/modal/*', usd: 0.002 },
|
|
85
|
+
{ endpoint: '/api/v1/realface/*', usd: 0.011 },
|
|
86
|
+
{ endpoint: '/api/v1/portrait/*', usd: 0.011 },
|
|
87
|
+
{ endpoint: '/api/v1/polymarket/fund', usd: 0.011 },
|
|
88
|
+
{ endpoint: '/api/v1/usstock/price/{ticker}', usd: 0.002 },
|
|
89
|
+
{ endpoint: '/api/v1/search', usd: 0.025 },
|
|
90
|
+
// Explicitly free — listed so a lookup returns 0 rather than "unknown",
|
|
91
|
+
// which would make callers fall back to a non-zero guess.
|
|
92
|
+
{ endpoint: '/api/v1/zerox/*', usd: 0 },
|
|
93
|
+
{ endpoint: '/api/v1/crypto/price/{pair}', usd: 0 },
|
|
94
|
+
{ endpoint: '/api/v1/fx/price/{pair}', usd: 0 },
|
|
95
|
+
{ endpoint: '/api/v1/commodity/price/{symbol}', usd: 0 },
|
|
96
|
+
{ endpoint: '/api/v1/onramp/token', usd: 0 },
|
|
97
|
+
{ endpoint: '/api/v1/models', usd: 0 },
|
|
98
|
+
];
|
|
99
|
+
let catalog = STATIC_CATALOG;
|
|
100
|
+
let loadedAt = 0;
|
|
101
|
+
let inFlight = null;
|
|
102
|
+
// ─── Price parsing ──────────────────────────────────────────────────────
|
|
103
|
+
/** `"$0.0085"` / `"0.006"` / `0.003` → 0.0085 / 0.006 / 0.003. Null if unparseable. */
|
|
104
|
+
function toUsd(value) {
|
|
105
|
+
if (typeof value === 'number')
|
|
106
|
+
return Number.isFinite(value) ? value : null;
|
|
107
|
+
if (typeof value !== 'string')
|
|
108
|
+
return null;
|
|
109
|
+
const n = Number(value.replace(/^\$/, '').trim());
|
|
110
|
+
return Number.isFinite(n) ? n : null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Reduce one service's `pricing` object to a single per-request USD figure,
|
|
114
|
+
* plus any nested endpoint-specific overrides it declares.
|
|
115
|
+
*
|
|
116
|
+
* The catalog uses several shapes for the same idea — `perRequest`, `perCall`,
|
|
117
|
+
* `flat`, `tierN.perRequest`, and grouped `{ endpoints: [...] }` lists. Only
|
|
118
|
+
* flat-rate shapes are handled; per-model maps (chat, images, video, speech)
|
|
119
|
+
* return null because `gateway-models.ts` prices those from the model catalog.
|
|
120
|
+
*/
|
|
121
|
+
function parsePricing(endpoint, pricing) {
|
|
122
|
+
if (!pricing || typeof pricing !== 'object')
|
|
123
|
+
return [];
|
|
124
|
+
const p = pricing;
|
|
125
|
+
const out = [];
|
|
126
|
+
if (p.free === true)
|
|
127
|
+
return [{ endpoint, usd: 0 }];
|
|
128
|
+
const direct = toUsd(p.perRequest) ?? toUsd(p.perCall) ?? toUsd(p.flat) ?? toUsd(p.perUrl);
|
|
129
|
+
if (direct !== null)
|
|
130
|
+
out.push({ endpoint, usd: direct });
|
|
131
|
+
// Live search is billed per source queried. Franklin's Search tool sends one
|
|
132
|
+
// source unless the caller widens it, so the single-source price is the
|
|
133
|
+
// floor. A multi-source call is under-counted rather than guessed at — the
|
|
134
|
+
// dashboard remains the authority on the exact figure.
|
|
135
|
+
const perSource = toUsd(p.pricePerSource);
|
|
136
|
+
if (perSource !== null)
|
|
137
|
+
out.push({ endpoint, usd: perSource });
|
|
138
|
+
// Nested groups: { tier1: {...}, tier2: {...} } and
|
|
139
|
+
// { create: { perRequest, endpoint }, operations: { perRequest, endpoints: [] } }.
|
|
140
|
+
for (const [key, value] of Object.entries(p)) {
|
|
141
|
+
if (!value || typeof value !== 'object' || key === 'payment')
|
|
142
|
+
continue;
|
|
143
|
+
const group = value;
|
|
144
|
+
const usd = toUsd(group.perRequest) ?? toUsd(group.perCall) ?? toUsd(group.perUrl);
|
|
145
|
+
if (usd === null)
|
|
146
|
+
continue;
|
|
147
|
+
const own = typeof group.endpoint === 'string' ? [group.endpoint] : [];
|
|
148
|
+
const many = Array.isArray(group.endpoints)
|
|
149
|
+
? group.endpoints.filter((e) => typeof e === 'string')
|
|
150
|
+
: [];
|
|
151
|
+
const targets = [...own, ...many];
|
|
152
|
+
if (targets.length > 0)
|
|
153
|
+
for (const t of targets)
|
|
154
|
+
out.push({ endpoint: t, usd });
|
|
155
|
+
// A bare tier with no endpoint list prices the whole service. Take the
|
|
156
|
+
// dearest tier so an estimate errs toward over-counting, which is the safe
|
|
157
|
+
// direction for a spend ceiling.
|
|
158
|
+
else if (!out.some((e) => e.endpoint === endpoint && e.usd >= usd)) {
|
|
159
|
+
out.push({ endpoint, usd });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// A service listing per-endpoint prices as a flat array.
|
|
163
|
+
if (Array.isArray(p.endpoints)) {
|
|
164
|
+
for (const item of p.endpoints) {
|
|
165
|
+
if (!item || typeof item !== 'object')
|
|
166
|
+
continue;
|
|
167
|
+
const row = item;
|
|
168
|
+
const usd = toUsd(row.perRequest) ?? toUsd(row.perCall);
|
|
169
|
+
if (typeof row.endpoint === 'string' && usd !== null) {
|
|
170
|
+
out.push({ endpoint: row.endpoint, usd });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
// ─── Pattern matching ───────────────────────────────────────────────────
|
|
177
|
+
/**
|
|
178
|
+
* Turn a published endpoint pattern into a matcher.
|
|
179
|
+
*
|
|
180
|
+
* `/api/v1/surf/*` → any path under /surf/
|
|
181
|
+
* `/api/v1/rpc/{network}` → one path segment
|
|
182
|
+
* `/api/v1/pm/{limitless,opinion}/*` → one of the listed segments
|
|
183
|
+
*/
|
|
184
|
+
function patternToRegExp(pattern) {
|
|
185
|
+
let src = '';
|
|
186
|
+
for (const part of pattern.split('/')) {
|
|
187
|
+
if (part === '')
|
|
188
|
+
continue;
|
|
189
|
+
src += '/';
|
|
190
|
+
if (part === '*') {
|
|
191
|
+
src += '.*';
|
|
192
|
+
}
|
|
193
|
+
else if (part.startsWith('{') && part.endsWith('}')) {
|
|
194
|
+
const inner = part.slice(1, -1);
|
|
195
|
+
// A brace group may itself contain slashes and nested braces, e.g.
|
|
196
|
+
// `{identity/{wallet},identities}` — too irregular to model exactly, so
|
|
197
|
+
// treat any such group as "one or more segments".
|
|
198
|
+
src += inner.includes(',') || inner.includes('/') ? '[^?]+' : '[^/?]+';
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
src += part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return new RegExp(`^${src}/?$`);
|
|
205
|
+
}
|
|
206
|
+
/** Specificity: more literal segments and no wildcard wins. */
|
|
207
|
+
function specificity(pattern) {
|
|
208
|
+
const segments = pattern.split('/').filter(Boolean);
|
|
209
|
+
const literal = segments.filter((s) => s !== '*' && !s.startsWith('{')).length;
|
|
210
|
+
return literal * 10 - (pattern.includes('*') ? 1 : 0);
|
|
211
|
+
}
|
|
212
|
+
// ─── Cache ──────────────────────────────────────────────────────────────
|
|
213
|
+
function readDiskCache() {
|
|
214
|
+
try {
|
|
215
|
+
const stat = fs.statSync(CACHE_FILE);
|
|
216
|
+
if (Date.now() - stat.mtimeMs > CACHE_TTL_MS)
|
|
217
|
+
return;
|
|
218
|
+
const parsed = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
|
|
219
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
220
|
+
catalog = parsed;
|
|
221
|
+
loadedAt = stat.mtimeMs;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch { /* no cache, or unreadable — the static floor covers it */ }
|
|
225
|
+
}
|
|
226
|
+
function writeDiskCache(entries) {
|
|
227
|
+
try {
|
|
228
|
+
fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
|
|
229
|
+
fs.writeFileSync(CACHE_FILE, JSON.stringify(entries), { mode: 0o600 });
|
|
230
|
+
}
|
|
231
|
+
catch { /* best-effort — an in-memory catalog still works */ }
|
|
232
|
+
}
|
|
233
|
+
async function fetchCatalog() {
|
|
234
|
+
const ctrl = new AbortController();
|
|
235
|
+
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
|
|
236
|
+
try {
|
|
237
|
+
const res = await fetch(CATALOG_URL, {
|
|
238
|
+
signal: ctrl.signal,
|
|
239
|
+
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
|
|
240
|
+
});
|
|
241
|
+
if (!res.ok)
|
|
242
|
+
return;
|
|
243
|
+
const body = (await res.json());
|
|
244
|
+
if (!Array.isArray(body.services)) {
|
|
245
|
+
// The one failure that would otherwise be invisible: a 200 with no
|
|
246
|
+
// priced catalog leaves every estimate pinned to the static floor
|
|
247
|
+
// forever, and nothing else in the product would ever say so. The sol
|
|
248
|
+
// origin's discovery doc has exactly this shape, so this fires the
|
|
249
|
+
// moment someone repoints CATALOG_URL at it.
|
|
250
|
+
logger.warn(`[franklin] price catalog at ${CATALOG_URL} returned no services[] — ` +
|
|
251
|
+
'estimates will stay on the built-in floor');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const entries = [];
|
|
255
|
+
for (const svc of body.services) {
|
|
256
|
+
if (!svc || typeof svc !== 'object')
|
|
257
|
+
continue;
|
|
258
|
+
const s = svc;
|
|
259
|
+
if (typeof s.endpoint !== 'string')
|
|
260
|
+
continue;
|
|
261
|
+
entries.push(...parsePricing(s.endpoint, s.pricing));
|
|
262
|
+
}
|
|
263
|
+
if (entries.length === 0)
|
|
264
|
+
return;
|
|
265
|
+
// Keep the static floor underneath so an endpoint the catalog stops
|
|
266
|
+
// listing does not silently become free.
|
|
267
|
+
const merged = new Map();
|
|
268
|
+
for (const e of STATIC_CATALOG)
|
|
269
|
+
merged.set(e.endpoint, e.usd);
|
|
270
|
+
for (const e of entries)
|
|
271
|
+
merged.set(e.endpoint, e.usd);
|
|
272
|
+
catalog = [...merged].map(([endpoint, usd]) => ({ endpoint, usd }));
|
|
273
|
+
loadedAt = Date.now();
|
|
274
|
+
writeDiskCache(catalog);
|
|
275
|
+
}
|
|
276
|
+
catch { /* offline — the static floor covers it */ }
|
|
277
|
+
finally {
|
|
278
|
+
clearTimeout(timer);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Refresh the catalog in the background. Safe to call repeatedly; only one
|
|
283
|
+
* fetch is ever in flight and it is skipped while the cache is fresh.
|
|
284
|
+
*/
|
|
285
|
+
export function warmPriceCatalog() {
|
|
286
|
+
if (loadedAt === 0)
|
|
287
|
+
readDiskCache();
|
|
288
|
+
if (Date.now() - loadedAt < CACHE_TTL_MS)
|
|
289
|
+
return;
|
|
290
|
+
if (inFlight)
|
|
291
|
+
return;
|
|
292
|
+
inFlight = fetchCatalog().finally(() => { inFlight = null; });
|
|
293
|
+
}
|
|
294
|
+
/** Test seam — drop the loaded catalog and fall back to the static floor. */
|
|
295
|
+
export function __resetPriceCatalog() {
|
|
296
|
+
catalog = STATIC_CATALOG;
|
|
297
|
+
loadedAt = 0;
|
|
298
|
+
inFlight = null;
|
|
299
|
+
}
|
|
300
|
+
/** Test seam — install a catalog without touching the network or disk. */
|
|
301
|
+
export function __primePriceCatalog(entries) {
|
|
302
|
+
catalog = entries;
|
|
303
|
+
loadedAt = Date.now();
|
|
304
|
+
}
|
|
305
|
+
// ─── Lookup ─────────────────────────────────────────────────────────────
|
|
306
|
+
/**
|
|
307
|
+
* List price in USD for one gateway path, or null when the path is not a
|
|
308
|
+
* flat-rate service endpoint (chat and the other model-priced endpoints land
|
|
309
|
+
* here, and are costed from the model catalog instead).
|
|
310
|
+
*
|
|
311
|
+
* `apiPath` may be a bare path or a full URL, with or without the `/api`
|
|
312
|
+
* prefix and with or without a query string — the two payment hosts differ on
|
|
313
|
+
* the prefix and callers should not have to care.
|
|
314
|
+
*
|
|
315
|
+
* Synchronous by design: it is called on the response path of every paid tool,
|
|
316
|
+
* where an await would serialise the accounting behind a network fetch. The
|
|
317
|
+
* catalog refreshes in the background via `warmPriceCatalog()`.
|
|
318
|
+
*/
|
|
319
|
+
export function priceForPath(apiPath) {
|
|
320
|
+
warmPriceCatalog();
|
|
321
|
+
// Accept a bare path or a full gateway URL — call sites already hold the
|
|
322
|
+
// absolute endpoint they fetched, and making them slice it would just
|
|
323
|
+
// duplicate this logic 8 times.
|
|
324
|
+
let normalized = apiPath;
|
|
325
|
+
if (/^https?:\/\//.test(normalized)) {
|
|
326
|
+
try {
|
|
327
|
+
normalized = new URL(normalized).pathname;
|
|
328
|
+
}
|
|
329
|
+
catch { /* fall through */ }
|
|
330
|
+
}
|
|
331
|
+
normalized = normalized.split('?')[0];
|
|
332
|
+
if (!normalized.startsWith('/'))
|
|
333
|
+
normalized = '/' + normalized;
|
|
334
|
+
// The x402 hosts serve these routes under /api, the key host at the root.
|
|
335
|
+
// Catalog patterns use the /api form, so normalise onto that.
|
|
336
|
+
if (!normalized.startsWith('/api/'))
|
|
337
|
+
normalized = '/api' + normalized;
|
|
338
|
+
let best = null;
|
|
339
|
+
for (const entry of catalog) {
|
|
340
|
+
if (!patternToRegExp(entry.endpoint).test(normalized))
|
|
341
|
+
continue;
|
|
342
|
+
const score = specificity(entry.endpoint);
|
|
343
|
+
if (!best || score > best.score)
|
|
344
|
+
best = { usd: entry.usd, score };
|
|
345
|
+
}
|
|
346
|
+
return best ? best.usd : null;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* The base price for an endpoint — what the API-key rail charges — or null
|
|
350
|
+
* when the endpoint is not catalogued.
|
|
351
|
+
*
|
|
352
|
+
* There are two real prices per endpoint and one literal cannot serve both.
|
|
353
|
+
* The catalog and the 402 challenge both state the WALLET price, which is the
|
|
354
|
+
* base plus a settlement fee. The key rail charges the base and no fee, which
|
|
355
|
+
* is why it issues no 402 at all.
|
|
356
|
+
*
|
|
357
|
+
* Measured 2026-09-05 via x-blockrun-cost-usd against the unsigned 402:
|
|
358
|
+
*
|
|
359
|
+
* endpoint 402 / catalog key rail charges
|
|
360
|
+
* surf $0.0085 $0.0075
|
|
361
|
+
* rpc $0.0030 $0.0020
|
|
362
|
+
* exa search $0.0110 $0.0100
|
|
363
|
+
* defillama $0.0060 $0.0050
|
|
364
|
+
*
|
|
365
|
+
* Exactly one fee apart, every time. Quoting the 402 figure to a key-mode user
|
|
366
|
+
* overstates every call by $0.001 — small in absolute terms and 50% on a
|
|
367
|
+
* $0.002 RPC call.
|
|
368
|
+
*/
|
|
369
|
+
export function basePriceForPath(apiPath) {
|
|
370
|
+
const wallet = priceForPath(apiPath);
|
|
371
|
+
if (wallet === null)
|
|
372
|
+
return null;
|
|
373
|
+
if (wallet <= 0)
|
|
374
|
+
return wallet; // free stays free on both rails
|
|
375
|
+
const base = wallet - GATEWAY_TRANSACTION_FEE_USD;
|
|
376
|
+
return base > 0 ? +base.toFixed(6) : wallet;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* The exact amount BlockRun charged for this call, from
|
|
380
|
+
* `x-blockrun-cost-usd`, or null when the response does not state one.
|
|
381
|
+
*
|
|
382
|
+
* Live on the pre-priced service families (exa, surf, pm, phone, modal,
|
|
383
|
+
* speech, images, rpc, defillama). Deliberately and permanently ABSENT on
|
|
384
|
+
* chat, which settles after the answer is on the wire (`x-settlement-async`)
|
|
385
|
+
* — at header-writing time the amount does not exist yet, and waiting for it
|
|
386
|
+
* would mean holding the customer's response until the money lands. Chat is
|
|
387
|
+
* reconstructed from tokens x published rate instead.
|
|
388
|
+
*
|
|
389
|
+
* Absent means "no charge settled at response time", NOT "free" — reading it
|
|
390
|
+
* as $0 would zero out chat, the largest spend category. A charge that really
|
|
391
|
+
* did settle at zero is written explicitly as `0.000000`, so 0 is a value and
|
|
392
|
+
* missing is not.
|
|
393
|
+
*
|
|
394
|
+
* Empty, malformed and negative are all treated as absent. `Number('')` is 0
|
|
395
|
+
* in JS, which would book $0 against a billed call.
|
|
396
|
+
*/
|
|
397
|
+
export function chargeFromResponse(res) {
|
|
398
|
+
return usdHeader(res, 'x-blockrun-cost-usd');
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Credit left on the account after this call, from
|
|
402
|
+
* `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
|
|
403
|
+
* ceiling and so nothing to report — that is correct, not a failure.
|
|
404
|
+
*
|
|
405
|
+
* It can understate and never overstates: the figure is read inside the
|
|
406
|
+
* reservation transaction, already net of concurrent in-flight holds. That is
|
|
407
|
+
* the right error direction for a pre-run low-balance warning (warn early
|
|
408
|
+
* rather than fail to warn), and the wrong one for display — GET /v1/credits
|
|
409
|
+
* is the authority for a number shown to a user.
|
|
410
|
+
*/
|
|
411
|
+
export function remainingCreditFromResponse(res) {
|
|
412
|
+
return usdHeader(res, 'x-blockrun-credit-remaining-usd');
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Shared parse for both money headers. 0 is a value; empty, malformed and
|
|
416
|
+
* negative are all absence. `Number('')` is 0 in JS, which would book $0
|
|
417
|
+
* against a billed call.
|
|
418
|
+
*/
|
|
419
|
+
function usdHeader(res, name) {
|
|
420
|
+
const raw = res.headers.get(name);
|
|
421
|
+
if (raw === null)
|
|
422
|
+
return null;
|
|
423
|
+
const trimmed = raw.trim();
|
|
424
|
+
if (trimmed === '')
|
|
425
|
+
return null;
|
|
426
|
+
const n = Number(trimmed);
|
|
427
|
+
if (!Number.isFinite(n) || n < 0)
|
|
428
|
+
return null;
|
|
429
|
+
return n;
|
|
430
|
+
}
|
|
431
|
+
export function resolveCharge(opts) {
|
|
432
|
+
const { apiPath, chargedUsd, settledUsd, reportedUsd, fallbackUsd } = opts;
|
|
433
|
+
// The gateway stating its own charge beats every other source, including a
|
|
434
|
+
// settled x402 amount. 0 is a real answer here, so test for null, not truth.
|
|
435
|
+
if (typeof chargedUsd === 'number') {
|
|
436
|
+
return { usd: chargedUsd, estimated: false };
|
|
437
|
+
}
|
|
438
|
+
if (typeof settledUsd === 'number' && settledUsd > 0) {
|
|
439
|
+
return { usd: settledUsd, estimated: false };
|
|
440
|
+
}
|
|
441
|
+
// An upstream provider's self-reported cost is NOT what BlockRun charged.
|
|
442
|
+
// Measured 2026-09-05: Exa reported costDollars $0.007 on a call BlockRun
|
|
443
|
+
// charged $0.010 for. Treating it as exact booked a wrong number with false
|
|
444
|
+
// confidence, which is worse than a hedged one — so it now ranks below the
|
|
445
|
+
// catalog price and is tagged estimated like any other guess.
|
|
446
|
+
if (typeof reportedUsd === 'number' && reportedUsd > 0) {
|
|
447
|
+
const listed = priceForPath(apiPath);
|
|
448
|
+
return { usd: listed !== null && listed > 0 ? listed : reportedUsd, estimated: true };
|
|
449
|
+
}
|
|
450
|
+
const listed = priceForPath(apiPath);
|
|
451
|
+
if (listed !== null)
|
|
452
|
+
return { usd: listed, estimated: true };
|
|
453
|
+
if (typeof fallbackUsd === 'number' && fallbackUsd > 0) {
|
|
454
|
+
return { usd: fallbackUsd, estimated: true };
|
|
455
|
+
}
|
|
456
|
+
return { usd: 0, estimated: true };
|
|
457
|
+
}
|