@blockrun/franklin 3.44.0 → 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 +24 -14
- package/dist/commands/balance.js +37 -5
- package/dist/payments/auth-mode.d.ts +34 -0
- package/dist/payments/auth-mode.js +39 -0
- package/dist/payments/price-catalog.d.ts +61 -0
- package/dist/payments/price-catalog.js +141 -6
- package/dist/tools/defillama.d.ts +5 -5
- package/dist/tools/defillama.js +12 -12
- package/dist/tools/exa.d.ts +1 -1
- package/dist/tools/exa.js +27 -18
- package/dist/tools/prediction.js +2 -1
- package/dist/tools/realface.js +2 -2
- package/dist/tools/rpc.d.ts +1 -1
- package/dist/tools/rpc.js +4 -4
- package/dist/tools/surf.js +32 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -167,7 +167,7 @@ interchangeable. Everything else about the agent is identical.
|
|
|
167
167
|
| Settlement | On-chain, per call, via [x402](https://x402.org) | Against a prepaid balance |
|
|
168
168
|
| Gateway | `sol.blockrun.ai` / `blockrun.ai` | `api.blockrun.ai` |
|
|
169
169
|
| Where the money lives | A wallet only you hold the key to | Your BlockRun account |
|
|
170
|
-
| Spend visibility | `franklin stats` — exact settled amounts | [
|
|
170
|
+
| Spend visibility | `franklin stats` — exact settled amounts | `franklin balance` + [dashboard](https://user.blockrun.ai/dashboard); exact except chat |
|
|
171
171
|
|
|
172
172
|
**The wallet is still Franklin's identity.** Memory, the trading journal and goals are
|
|
173
173
|
keyed to it, and the wallet route is the one that needs nothing from us — no signup, no
|
|
@@ -208,23 +208,33 @@ If the key is rejected, or a tool needs an endpoint the key gateway does not ser
|
|
|
208
208
|
Franklin falls back to the wallet for that call and tells you. It never falls back on a
|
|
209
209
|
malformed request — a bad call is never retried with your USDC.
|
|
210
210
|
|
|
211
|
-
###
|
|
211
|
+
### Spend tracking, and the one thing that stays an estimate
|
|
212
212
|
|
|
213
213
|
In wallet mode every charge is exact: the gateway states the price in the x402 handshake
|
|
214
214
|
and Franklin records the amount that actually settled.
|
|
215
215
|
|
|
216
|
-
In API-key mode
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
216
|
+
In API-key mode most calls now report what they cost. The gateway returns an
|
|
217
|
+
`x-blockrun-cost-usd` header on the pre-priced service families — search, images, RPC,
|
|
218
|
+
market data, phone, sandboxes — and Franklin records that figure exactly.
|
|
219
|
+
|
|
220
|
+
**Chat is the exception, permanently.** Chat settles *after* the answer is on the wire, so
|
|
221
|
+
a slow settlement never becomes a slow answer, which means the amount does not exist yet
|
|
222
|
+
when the headers are written. Franklin reconstructs chat spend from token counts and the
|
|
223
|
+
published rate, so chat rows are estimates. `franklin stats` marks estimated totals with
|
|
224
|
+
`~` and reports the estimated portion separately, so you can always see which is which.
|
|
225
|
+
|
|
226
|
+
`franklin balance` reads your real credit standing from the gateway:
|
|
227
|
+
|
|
228
|
+
```
|
|
229
|
+
Account: acme (gated)
|
|
230
|
+
Remaining: $41.9980 of $50.00 granted
|
|
231
|
+
Spent: $8.0020 (BlockRun, authoritative)
|
|
232
|
+
Local: ~$8.0431 (Franklin's own tally, all time, both pay modes — expected to differ)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
The two numbers differ on purpose: Franklin's tally covers both pay modes and estimates
|
|
236
|
+
chat, while BlockRun's is what you were actually billed. For the full per-call history,
|
|
237
|
+
use the [dashboard](https://user.blockrun.ai/dashboard).
|
|
228
238
|
|
|
229
239
|
---
|
|
230
240
|
|
package/dist/commands/balance.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
|
|
3
3
|
import { loadChain, DASHBOARD_URL } from '../config.js';
|
|
4
|
-
import { isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
|
|
4
|
+
import { fetchCreditBalance, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
|
|
5
5
|
import { loadStats } from '../stats/tracker.js';
|
|
6
6
|
export async function balanceCommand() {
|
|
7
7
|
const chain = loadChain();
|
|
@@ -14,16 +14,48 @@ export async function balanceCommand() {
|
|
|
14
14
|
const key = loadApiKey();
|
|
15
15
|
console.log(`Pay mode: ${chalk.green('api-key')}`);
|
|
16
16
|
console.log(`Key: ${chalk.cyan(key ? maskApiKey(key) : 'unknown')}`);
|
|
17
|
+
const credit = await fetchCreditBalance();
|
|
18
|
+
if (credit) {
|
|
19
|
+
console.log(`Account: ${chalk.dim(credit.accountId)} (${chalk.dim(credit.billingMode)})`);
|
|
20
|
+
// `ungated` means no ceiling, and remaining_usd is legitimately null.
|
|
21
|
+
// Coalescing that to 0 would tell a paying customer they are broke, so
|
|
22
|
+
// branch on the mode rather than on the number.
|
|
23
|
+
if (credit.remainingUsd !== null) {
|
|
24
|
+
const low = credit.remainingUsd < 1;
|
|
25
|
+
console.log(`Remaining: ${(low ? chalk.yellow : chalk.green)('$' + credit.remainingUsd.toFixed(4))}` +
|
|
26
|
+
chalk.dim(` of $${credit.grantedUsd.toFixed(2)} granted`));
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
console.log(`Remaining: ${chalk.dim('no prepaid limit on this account')}`);
|
|
30
|
+
}
|
|
31
|
+
console.log(`Spent: ${chalk.cyan('$' + credit.spentUsd.toFixed(4))}` + chalk.dim(' (BlockRun, authoritative)'));
|
|
32
|
+
if (credit.blocked) {
|
|
33
|
+
// An append-only code set — show the raw code when it is one we do not
|
|
34
|
+
// know rather than swallowing it.
|
|
35
|
+
const explain = {
|
|
36
|
+
ACCOUNT_SUSPENDED: 'this account is suspended',
|
|
37
|
+
CREDIT_LIMIT_REACHED: 'the credit limit has been reached',
|
|
38
|
+
BALANCE_EXHAUSTED: 'the prepaid balance is exhausted',
|
|
39
|
+
};
|
|
40
|
+
const reason = credit.blockedReason
|
|
41
|
+
? explain[credit.blockedReason] ?? `blocked (${credit.blockedReason})`
|
|
42
|
+
: 'blocked';
|
|
43
|
+
console.log(chalk.red(`\nYour next paid call will be refused — ${reason}.`));
|
|
44
|
+
console.log(chalk.dim(`Top up at ${DASHBOARD_URL}/dashboard.`));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
17
47
|
try {
|
|
18
48
|
const stats = loadStats();
|
|
19
49
|
const spent = stats.totalCostUsd ?? 0;
|
|
20
50
|
const est = stats.totalEstimatedCostUsd ?? 0;
|
|
21
|
-
console.log(`
|
|
22
|
-
chalk.dim(
|
|
51
|
+
console.log(`Local: ${chalk.dim((est > 0 ? '~$' : '$') + spent.toFixed(4))}` +
|
|
52
|
+
chalk.dim(" (Franklin's own tally, all time, both pay modes — expected to differ)"));
|
|
23
53
|
}
|
|
24
54
|
catch { /* stats are best-effort */ }
|
|
25
|
-
|
|
26
|
-
|
|
55
|
+
if (!credit) {
|
|
56
|
+
console.log(chalk.dim(`\nCould not read the credit balance from the gateway.`));
|
|
57
|
+
}
|
|
58
|
+
console.log(chalk.dim(`\nFull activity: ${DASHBOARD_URL}/dashboard`));
|
|
27
59
|
console.log(chalk.dim('To spend from a USDC wallet instead: franklin --wallet, or franklin logout.'));
|
|
28
60
|
return;
|
|
29
61
|
}
|
|
@@ -79,6 +79,40 @@ export declare function walletBase(chain?: Chain): string;
|
|
|
79
79
|
* where payment rides on the PAYMENT-SIGNATURE header instead.
|
|
80
80
|
*/
|
|
81
81
|
export declare function gatewayHeaders(mode?: PayMode): Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* A key's credit standing, from GET /v1/credits. The authoritative figure for
|
|
84
|
+
* display — the per-response `x-blockrun-credit-remaining-usd` header can
|
|
85
|
+
* understate under concurrency and is for warnings, not for showing a user.
|
|
86
|
+
*/
|
|
87
|
+
export interface CreditBalance {
|
|
88
|
+
accountId: string;
|
|
89
|
+
/**
|
|
90
|
+
* `ungated` accounts have NO ceiling, so `remainingUsd` is legitimately null.
|
|
91
|
+
* Never coalesce that to 0 — it would tell a paying customer they are broke.
|
|
92
|
+
* Branch on this field instead.
|
|
93
|
+
*/
|
|
94
|
+
billingMode: string;
|
|
95
|
+
currency: string;
|
|
96
|
+
grantedUsd: number;
|
|
97
|
+
spentUsd: number;
|
|
98
|
+
remainingUsd: number | null;
|
|
99
|
+
blocked: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* A stable CODE to map, not a string to show: ACCOUNT_SUSPENDED,
|
|
102
|
+
* CREDIT_LIMIT_REACHED, BALANCE_EXHAUSTED. Treated as append-only, so an
|
|
103
|
+
* unrecognised value must degrade gracefully rather than throw.
|
|
104
|
+
*/
|
|
105
|
+
blockedReason: string | null;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Fetch the key's credit standing. Null when there is no key, the gateway is
|
|
109
|
+
* unreachable, or it answers with something unexpected — callers show what they
|
|
110
|
+
* do know rather than inventing a number.
|
|
111
|
+
*
|
|
112
|
+
* `blocked` describes what the gateway would do with the NEXT call, so it is
|
|
113
|
+
* safe to gate an autonomous run on.
|
|
114
|
+
*/
|
|
115
|
+
export declare function fetchCreditBalance(timeoutMs?: number): Promise<CreditBalance | null>;
|
|
82
116
|
/**
|
|
83
117
|
* Merge this mode's auth into a header bag that may already carry a client's
|
|
84
118
|
* own credential, in place.
|
|
@@ -142,6 +142,45 @@ export function gatewayHeaders(mode = resolvePayMode()) {
|
|
|
142
142
|
headers['Authorization'] = `Bearer ${mode.key}`;
|
|
143
143
|
return headers;
|
|
144
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Fetch the key's credit standing. Null when there is no key, the gateway is
|
|
147
|
+
* unreachable, or it answers with something unexpected — callers show what they
|
|
148
|
+
* do know rather than inventing a number.
|
|
149
|
+
*
|
|
150
|
+
* `blocked` describes what the gateway would do with the NEXT call, so it is
|
|
151
|
+
* safe to gate an autonomous run on.
|
|
152
|
+
*/
|
|
153
|
+
export async function fetchCreditBalance(timeoutMs = 15_000) {
|
|
154
|
+
const key = loadApiKey();
|
|
155
|
+
if (!key)
|
|
156
|
+
return null;
|
|
157
|
+
try {
|
|
158
|
+
const res = await fetch(`${KEY_API_URL}/v1/credits`, {
|
|
159
|
+
headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
|
|
160
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
161
|
+
});
|
|
162
|
+
if (!res.ok)
|
|
163
|
+
return null;
|
|
164
|
+
const b = (await res.json());
|
|
165
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
166
|
+
return {
|
|
167
|
+
accountId: typeof b.account_id === 'string' ? b.account_id : 'unknown',
|
|
168
|
+
billingMode: typeof b.billing_mode === 'string' ? b.billing_mode : 'unknown',
|
|
169
|
+
currency: typeof b.currency === 'string' ? b.currency : 'USD',
|
|
170
|
+
grantedUsd: num(b.granted_usd),
|
|
171
|
+
spentUsd: num(b.spent_usd),
|
|
172
|
+
// Explicitly preserve null — the whole point of this field.
|
|
173
|
+
remainingUsd: typeof b.remaining_usd === 'number' && Number.isFinite(b.remaining_usd)
|
|
174
|
+
? b.remaining_usd
|
|
175
|
+
: null,
|
|
176
|
+
blocked: b.blocked === true,
|
|
177
|
+
blockedReason: typeof b.blocked_reason === 'string' ? b.blocked_reason : null,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
145
184
|
/**
|
|
146
185
|
* Merge this mode's auth into a header bag that may already carry a client's
|
|
147
186
|
* own credential, in place.
|
|
@@ -50,6 +50,65 @@ export declare function __primePriceCatalog(entries: CatalogEntry[]): void;
|
|
|
50
50
|
* catalog refreshes in the background via `warmPriceCatalog()`.
|
|
51
51
|
*/
|
|
52
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
|
+
}
|
|
53
112
|
/**
|
|
54
113
|
* The amount to record for a completed paid call.
|
|
55
114
|
*
|
|
@@ -64,6 +123,8 @@ export interface ResolvedCharge {
|
|
|
64
123
|
}
|
|
65
124
|
export declare function resolveCharge(opts: {
|
|
66
125
|
apiPath: string;
|
|
126
|
+
/** From `x-blockrun-cost-usd` — what BlockRun actually charged. Wins outright. */
|
|
127
|
+
chargedUsd?: number | null;
|
|
67
128
|
settledUsd?: number;
|
|
68
129
|
reportedUsd?: number;
|
|
69
130
|
fallbackUsd?: number;
|
|
@@ -24,10 +24,43 @@
|
|
|
24
24
|
import fs from 'node:fs';
|
|
25
25
|
import path from 'node:path';
|
|
26
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';
|
|
27
29
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
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.
|
|
31
64
|
*/
|
|
32
65
|
const CATALOG_URL = 'https://blockrun.ai/.well-known/x402';
|
|
33
66
|
const CACHE_FILE = path.join(BLOCKRUN_DIR, 'price-catalog.json');
|
|
@@ -208,8 +241,16 @@ async function fetchCatalog() {
|
|
|
208
241
|
if (!res.ok)
|
|
209
242
|
return;
|
|
210
243
|
const body = (await res.json());
|
|
211
|
-
if (!Array.isArray(body.services))
|
|
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');
|
|
212
252
|
return;
|
|
253
|
+
}
|
|
213
254
|
const entries = [];
|
|
214
255
|
for (const svc of body.services) {
|
|
215
256
|
if (!svc || typeof svc !== 'object')
|
|
@@ -304,13 +345,107 @@ export function priceForPath(apiPath) {
|
|
|
304
345
|
}
|
|
305
346
|
return best ? best.usd : null;
|
|
306
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
|
+
}
|
|
307
431
|
export function resolveCharge(opts) {
|
|
308
|
-
const { apiPath, settledUsd, reportedUsd, fallbackUsd } = 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
|
+
}
|
|
309
438
|
if (typeof settledUsd === 'number' && settledUsd > 0) {
|
|
310
439
|
return { usd: settledUsd, estimated: false };
|
|
311
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.
|
|
312
446
|
if (typeof reportedUsd === 'number' && reportedUsd > 0) {
|
|
313
|
-
|
|
447
|
+
const listed = priceForPath(apiPath);
|
|
448
|
+
return { usd: listed !== null && listed > 0 ? listed : reportedUsd, estimated: true };
|
|
314
449
|
}
|
|
315
450
|
const listed = priceForPath(apiPath);
|
|
316
451
|
if (listed !== null)
|
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Five tools, each filtered + formatted on the way back so we don't dump
|
|
7
7
|
* 5–10 MB of raw DefiLlama JSON into agent context:
|
|
8
|
-
* - DeFiLlamaProtocols $0.
|
|
9
|
-
* - DeFiLlamaProtocol $0.
|
|
10
|
-
* - DeFiLlamaChains $0.
|
|
11
|
-
* - DeFiLlamaYields $0.
|
|
12
|
-
* - DeFiLlamaPrice $0.
|
|
8
|
+
* - DeFiLlamaProtocols $0.0050/call base (plus a $0.001 settlement fee on a wallet) — top-N protocols by TVL
|
|
9
|
+
* - DeFiLlamaProtocol $0.0050/call base (plus a $0.001 settlement fee on a wallet) — single protocol detail
|
|
10
|
+
* - DeFiLlamaChains $0.0050/call base (plus a $0.001 settlement fee on a wallet) — TVL ranked by chain
|
|
11
|
+
* - DeFiLlamaYields $0.0050/call base (plus a $0.001 settlement fee on a wallet) — yield pools, filtered + ranked
|
|
12
|
+
* - DeFiLlamaPrice $0.0050/call base (plus a $0.001 settlement fee on a wallet) — token price lookup
|
|
13
13
|
*
|
|
14
14
|
* DefiLlama is Apache 2.0 / "free for public and commercial use" — the
|
|
15
15
|
* BlockRun gateway adds metering + (future) caching/reliability layers,
|
package/dist/tools/defillama.js
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Five tools, each filtered + formatted on the way back so we don't dump
|
|
7
7
|
* 5–10 MB of raw DefiLlama JSON into agent context:
|
|
8
|
-
* - DeFiLlamaProtocols $0.
|
|
9
|
-
* - DeFiLlamaProtocol $0.
|
|
10
|
-
* - DeFiLlamaChains $0.
|
|
11
|
-
* - DeFiLlamaYields $0.
|
|
12
|
-
* - DeFiLlamaPrice $0.
|
|
8
|
+
* - DeFiLlamaProtocols $0.0050/call base (plus a $0.001 settlement fee on a wallet) — top-N protocols by TVL
|
|
9
|
+
* - DeFiLlamaProtocol $0.0050/call base (plus a $0.001 settlement fee on a wallet) — single protocol detail
|
|
10
|
+
* - DeFiLlamaChains $0.0050/call base (plus a $0.001 settlement fee on a wallet) — TVL ranked by chain
|
|
11
|
+
* - DeFiLlamaYields $0.0050/call base (plus a $0.001 settlement fee on a wallet) — yield pools, filtered + ranked
|
|
12
|
+
* - DeFiLlamaPrice $0.0050/call base (plus a $0.001 settlement fee on a wallet) — token price lookup
|
|
13
13
|
*
|
|
14
14
|
* DefiLlama is Apache 2.0 / "free for public and commercial use" — the
|
|
15
15
|
* BlockRun gateway adds metering + (future) caching/reliability layers,
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
19
19
|
import { loadChain, VERSION } from '../config.js';
|
|
20
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
20
|
+
import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
21
21
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
22
22
|
import { logger } from '../logger.js';
|
|
23
23
|
import { recordUsage } from '../stats/tracker.js';
|
|
@@ -65,7 +65,7 @@ async function getWithPayment(path, ctx) {
|
|
|
65
65
|
// stats / audit AND count against the --max-spend ceiling (parity with surf.ts).
|
|
66
66
|
// See rpc.ts — `paidUsd` is 0 whenever no 402 happened, which is every
|
|
67
67
|
// call in API-key mode.
|
|
68
|
-
const charge = resolveCharge({ apiPath: endpoint, settledUsd: paidUsd });
|
|
68
|
+
const charge = resolveCharge({ apiPath: endpoint, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd });
|
|
69
69
|
try {
|
|
70
70
|
recordUsage(`DeFiLlama:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
|
|
71
71
|
}
|
|
@@ -149,7 +149,7 @@ export const defiLlamaProtocolsCapability = {
|
|
|
149
149
|
name: 'DeFiLlamaProtocols',
|
|
150
150
|
description: 'Rank DeFi protocols by total value locked (TVL) across all chains, optionally filtered by category, chain, or minimum TVL. ' +
|
|
151
151
|
'Returns the top-N protocols (default 20), each with TVL, 24h/7d change, chain breakdown, and slug. ' +
|
|
152
|
-
'Uses BlockRun gateway → DefiLlama. $0.
|
|
152
|
+
'Uses BlockRun gateway → DefiLlama. $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
|
|
153
153
|
'Categories include: Lending, Liquid Staking, Bridge, Dexes, CDP, Yield, Yield Aggregator, Derivatives, Stablecoins, Insurance, etc.',
|
|
154
154
|
input_schema: {
|
|
155
155
|
type: 'object',
|
|
@@ -208,7 +208,7 @@ export const defiLlamaProtocolCapability = {
|
|
|
208
208
|
description: 'Detailed TVL + chain breakdown for a single DeFi protocol identified by DefiLlama slug ' +
|
|
209
209
|
'(e.g. "aave", "uniswap", "lido", "jito", "marinade-finance"). ' +
|
|
210
210
|
'Returns TVL across each chain it operates on, recent change, audits, social. ' +
|
|
211
|
-
'$0.
|
|
211
|
+
'$0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. To find a slug, run DeFiLlamaProtocols first.',
|
|
212
212
|
input_schema: {
|
|
213
213
|
type: 'object',
|
|
214
214
|
properties: {
|
|
@@ -266,7 +266,7 @@ export const defiLlamaProtocolCapability = {
|
|
|
266
266
|
export const defiLlamaChainsCapability = {
|
|
267
267
|
spec: {
|
|
268
268
|
name: 'DeFiLlamaChains',
|
|
269
|
-
description: 'TVL ranking across every chain DefiLlama tracks. Default returns top 20 by TVL. $0.
|
|
269
|
+
description: 'TVL ranking across every chain DefiLlama tracks. Default returns top 20 by TVL. $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet.',
|
|
270
270
|
input_schema: {
|
|
271
271
|
type: 'object',
|
|
272
272
|
properties: {
|
|
@@ -299,7 +299,7 @@ export const defiLlamaYieldsCapability = {
|
|
|
299
299
|
spec: {
|
|
300
300
|
name: 'DeFiLlamaYields',
|
|
301
301
|
description: 'Search DeFi yield pools (lending, LPs, vaults, staking) by symbol/chain/project, ranked by APY. ' +
|
|
302
|
-
'Returns top-N pools (default 10). $0.
|
|
302
|
+
'Returns top-N pools (default 10). $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
|
|
303
303
|
'Default filters: TVL > $1M (avoid microcaps), APY > 0. Override via params. ' +
|
|
304
304
|
'Use stablecoin_only=true for "where can my USDC earn?" queries.',
|
|
305
305
|
input_schema: {
|
|
@@ -372,7 +372,7 @@ export const defiLlamaYieldsCapability = {
|
|
|
372
372
|
export const defiLlamaPriceCapability = {
|
|
373
373
|
spec: {
|
|
374
374
|
name: 'DeFiLlamaPrice',
|
|
375
|
-
description: 'Token price lookup via DefiLlama (covers thousands of tokens — anything DEX-listed). $0.
|
|
375
|
+
description: 'Token price lookup via DefiLlama (covers thousands of tokens — anything DEX-listed). $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
|
|
376
376
|
'Coin identifier syntax: "{platform}:{address}" or "coingecko:{slug}". ' +
|
|
377
377
|
'Examples: "coingecko:bitcoin" (BTC USD), "ethereum:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" (WETH), ' +
|
|
378
378
|
'"solana:So11111111111111111111111111111111111111112" (SOL/wSOL), ' +
|
package/dist/tools/exa.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Three tools:
|
|
6
6
|
* - ExaSearch — semantic search for URLs ($0.01/call)
|
|
7
7
|
* - ExaAnswer — synthesized answer with citations ($0.01/call)
|
|
8
|
-
* - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.
|
|
8
|
+
* - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.0030/URL)
|
|
9
9
|
*
|
|
10
10
|
* Why these matter for an economic agent: ExaAnswer is Perplexity-in-a-
|
|
11
11
|
* tool — the agent gets a grounded reply with sources, avoiding the
|
package/dist/tools/exa.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Three tools:
|
|
6
6
|
* - ExaSearch — semantic search for URLs ($0.01/call)
|
|
7
7
|
* - ExaAnswer — synthesized answer with citations ($0.01/call)
|
|
8
|
-
* - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.
|
|
8
|
+
* - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.0030/URL)
|
|
9
9
|
*
|
|
10
10
|
* Why these matter for an economic agent: ExaAnswer is Perplexity-in-a-
|
|
11
11
|
* tool — the agent gets a grounded reply with sources, avoiding the
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
21
21
|
import { loadChain, VERSION } from '../config.js';
|
|
22
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
22
|
+
import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
23
23
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
24
24
|
import { frameUntrusted } from './untrusted.js';
|
|
25
25
|
import { recordUsage } from '../stats/tracker.js';
|
|
@@ -66,7 +66,12 @@ async function postWithPayment(path, body, ctx) {
|
|
|
66
66
|
const errText = await response.text().catch(() => '');
|
|
67
67
|
throw new Error(`Exa ${path} failed (${response.status}): ${errText.slice(0, 200)}`);
|
|
68
68
|
}
|
|
69
|
-
return {
|
|
69
|
+
return {
|
|
70
|
+
data: (await response.json()),
|
|
71
|
+
settled,
|
|
72
|
+
chargedUsd: chargeFromResponse(response),
|
|
73
|
+
latencyMs: Date.now() - start,
|
|
74
|
+
};
|
|
70
75
|
}
|
|
71
76
|
finally {
|
|
72
77
|
clearTimeout(timeout);
|
|
@@ -83,12 +88,16 @@ async function postWithPayment(path, body, ctx) {
|
|
|
83
88
|
// `costDollars`, so prefer that; otherwise price from the catalog. Returning
|
|
84
89
|
// early on !settled — as this did before key mode — would record $0 for real
|
|
85
90
|
// spend.
|
|
86
|
-
function recordExaSpend(path, settled, reportedUsd, fallbackUsd, latencyMs) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
function recordExaSpend(path, settled, chargedUsd, reportedUsd, fallbackUsd, latencyMs) {
|
|
92
|
+
// `reportedUsd` is Exa's own costDollars — its upstream cost, NOT what
|
|
93
|
+
// BlockRun charged. Measured 2026-09-05: Exa said $0.007 on a call the
|
|
94
|
+
// gateway charged $0.010 for. It is no longer treated as exact anywhere;
|
|
95
|
+
// x-blockrun-cost-usd is the authority when present.
|
|
96
|
+
const charge = chargedUsd !== null
|
|
97
|
+
? { usd: chargedUsd, estimated: false }
|
|
98
|
+
: settled
|
|
99
|
+
? { usd: fallbackUsd, estimated: false }
|
|
100
|
+
: resolveCharge({ apiPath: path, reportedUsd, fallbackUsd });
|
|
92
101
|
if (charge.usd <= 0)
|
|
93
102
|
return;
|
|
94
103
|
try {
|
|
@@ -146,7 +155,7 @@ async function extractPaymentReq(response) {
|
|
|
146
155
|
export const exaSearchCapability = {
|
|
147
156
|
spec: {
|
|
148
157
|
name: 'ExaSearch',
|
|
149
|
-
description: 'Neural web search via Exa ($0.
|
|
158
|
+
description: 'Neural web search via Exa ($0.0100/call base, plus a $0.001 settlement fee on a wallet). Returns a ranked list of ' +
|
|
150
159
|
'URLs + titles for a natural-language query. Understands meaning, ' +
|
|
151
160
|
'not just keywords. Optional `category` narrows to github / news / ' +
|
|
152
161
|
'`research paper` / tweet / pdf / company / etc. Prefer this over ' +
|
|
@@ -175,10 +184,10 @@ export const exaSearchCapability = {
|
|
|
175
184
|
if (!params.query)
|
|
176
185
|
return { output: 'Error: query is required', isError: true };
|
|
177
186
|
try {
|
|
178
|
-
const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/search', params, ctx);
|
|
187
|
+
const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/search', params, ctx);
|
|
179
188
|
const body = res.data ?? res;
|
|
180
189
|
const cost = body.costDollars?.total;
|
|
181
|
-
recordExaSpend('/v1/exa/search', settled, cost, 0.01, latencyMs);
|
|
190
|
+
recordExaSpend('/v1/exa/search', settled, chargedUsd, cost, 0.01, latencyMs);
|
|
182
191
|
const hits = body.results ?? [];
|
|
183
192
|
if (hits.length === 0) {
|
|
184
193
|
return { output: `No Exa results for "${params.query}".` };
|
|
@@ -203,7 +212,7 @@ export const exaAnswerCapability = {
|
|
|
203
212
|
spec: {
|
|
204
213
|
name: 'ExaAnswer',
|
|
205
214
|
description: "Ask a factual question, get a synthesized answer with real source " +
|
|
206
|
-
"citations ($0.
|
|
215
|
+
"citations ($0.0100/call base, plus a $0.001 settlement fee on a wallet). Like Perplexity in a tool — grounded in " +
|
|
207
216
|
"live web content, not LLM memory. Best for 'what is X?', 'how does " +
|
|
208
217
|
"Y work?', 'what's the current state of Z?'. Prefer this over " +
|
|
209
218
|
"chaining ExaSearch + ExaReadUrls + LLM synthesis when the user " +
|
|
@@ -221,10 +230,10 @@ export const exaAnswerCapability = {
|
|
|
221
230
|
if (!params.query)
|
|
222
231
|
return { output: 'Error: query is required', isError: true };
|
|
223
232
|
try {
|
|
224
|
-
const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/answer', params, ctx);
|
|
233
|
+
const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/answer', params, ctx);
|
|
225
234
|
const body = res.data ?? res;
|
|
226
235
|
const cost = body.costDollars?.total;
|
|
227
|
-
recordExaSpend('/v1/exa/answer', settled, cost, 0.01, latencyMs);
|
|
236
|
+
recordExaSpend('/v1/exa/answer', settled, chargedUsd, cost, 0.01, latencyMs);
|
|
228
237
|
const ans = body.answer ?? '';
|
|
229
238
|
const cites = body.citations ?? [];
|
|
230
239
|
const lines = [ans];
|
|
@@ -246,7 +255,7 @@ export const exaAnswerCapability = {
|
|
|
246
255
|
export const exaReadUrlsCapability = {
|
|
247
256
|
spec: {
|
|
248
257
|
name: 'ExaReadUrls',
|
|
249
|
-
description: "Batch-fetch clean Markdown content from a list of URLs ($0.
|
|
258
|
+
description: "Batch-fetch clean Markdown content from a list of URLs ($0.0020/URL base, plus a $0.001 settlement fee on a wallet). " +
|
|
250
259
|
"Up to 100 URLs per call. Much cheaper than chaining 100× WebFetch, " +
|
|
251
260
|
"and returns text already stripped of HTML/boilerplate — ready to " +
|
|
252
261
|
"feed into an LLM context window. Prefer over WebFetch when reading " +
|
|
@@ -272,11 +281,11 @@ export const exaReadUrlsCapability = {
|
|
|
272
281
|
return { output: `Error: max 100 URLs per call (got ${params.urls.length})`, isError: true };
|
|
273
282
|
}
|
|
274
283
|
try {
|
|
275
|
-
const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/contents', params, ctx);
|
|
284
|
+
const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/contents', params, ctx);
|
|
276
285
|
const body = res.data ?? res;
|
|
277
286
|
const cost = body.costDollars?.total;
|
|
278
287
|
// $0.002/URL list price as the floor when the gateway omits costDollars.
|
|
279
|
-
recordExaSpend('/v1/exa/contents', settled, cost, 0.002 * params.urls.length, latencyMs);
|
|
288
|
+
recordExaSpend('/v1/exa/contents', settled, chargedUsd, cost, 0.002 * params.urls.length, latencyMs);
|
|
280
289
|
const results = body.results ?? [];
|
|
281
290
|
if (results.length === 0) {
|
|
282
291
|
return { output: `No readable content returned for the ${params.urls.length} URL(s).` };
|
package/dist/tools/prediction.js
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
*/
|
|
38
38
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
39
39
|
import { loadChain, VERSION } from '../config.js';
|
|
40
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
40
|
+
import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
41
41
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
42
42
|
import { logger } from '../logger.js';
|
|
43
43
|
import { recordFetch } from '../trading/providers/telemetry.js';
|
|
@@ -116,6 +116,7 @@ async function getWithPayment(path, query, ctx) {
|
|
|
116
116
|
// to this module's own price table, then to the published catalog.
|
|
117
117
|
const charge = resolveCharge({
|
|
118
118
|
apiPath: endpoint,
|
|
119
|
+
chargedUsd: chargeFromResponse(response),
|
|
119
120
|
settledUsd: costRecorded,
|
|
120
121
|
fallbackUsd: priceForPath(path),
|
|
121
122
|
});
|
package/dist/tools/realface.js
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
*/
|
|
28
28
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
29
29
|
import { loadChain, USER_AGENT } from '../config.js';
|
|
30
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
30
|
+
import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
31
31
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
32
32
|
import { recordUsage } from '../stats/tracker.js';
|
|
33
33
|
import { logger } from '../logger.js';
|
|
@@ -191,7 +191,7 @@ async function actionEnroll(base, chain, input, ctx) {
|
|
|
191
191
|
paidUsd = 0;
|
|
192
192
|
// 0 whenever no 402 was settled, which is every call in API-key mode.
|
|
193
193
|
const charge = res.ok
|
|
194
|
-
? resolveCharge({ apiPath: url, settledUsd: paidUsd })
|
|
194
|
+
? resolveCharge({ apiPath: url, chargedUsd: chargeFromResponse(res), settledUsd: paidUsd })
|
|
195
195
|
: { usd: 0, estimated: false };
|
|
196
196
|
try {
|
|
197
197
|
recordUsage('RealFace:enroll', 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
|
package/dist/tools/rpc.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Multi-chain RPC — read-only JSON-RPC across 40+ chains via the BlockRun
|
|
3
3
|
* `/v1/rpc/{network}` endpoint (Tatum gateway). x402-paid against the user's
|
|
4
|
-
* USDC wallet, flat $0.
|
|
4
|
+
* USDC wallet, flat $0.0020 base + $0.001 settlement fee (measured 2026-09-05).
|
|
5
5
|
*
|
|
6
6
|
* For a trading agent this covers the on-chain reads the dedicated tools don't:
|
|
7
7
|
* native + ERC-20 balances on any chain, contract reads (eth_call), gas price,
|
package/dist/tools/rpc.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Multi-chain RPC — read-only JSON-RPC across 40+ chains via the BlockRun
|
|
3
3
|
* `/v1/rpc/{network}` endpoint (Tatum gateway). x402-paid against the user's
|
|
4
|
-
* USDC wallet, flat $0.
|
|
4
|
+
* USDC wallet, flat $0.0020 base + $0.001 settlement fee (measured 2026-09-05).
|
|
5
5
|
*
|
|
6
6
|
* For a trading agent this covers the on-chain reads the dedicated tools don't:
|
|
7
7
|
* native + ERC-20 balances on any chain, contract reads (eth_call), gas price,
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
20
20
|
import { loadChain, VERSION } from '../config.js';
|
|
21
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
21
|
+
import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
22
22
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
23
23
|
import { logger } from '../logger.js';
|
|
24
24
|
import { recordUsage } from '../stats/tracker.js';
|
|
@@ -92,7 +92,7 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
|
|
|
92
92
|
// `paidUsd` is only ever set by the 402 branch, so in API-key mode — where
|
|
93
93
|
// the gateway settles silently and never sends a 402 — it stays 0. Price the
|
|
94
94
|
// call from the published catalog instead of recording a free call.
|
|
95
|
-
const charge = resolveCharge({ apiPath: endpoint, settledUsd: paidUsd });
|
|
95
|
+
const charge = resolveCharge({ apiPath: endpoint, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd });
|
|
96
96
|
try {
|
|
97
97
|
recordUsage(`MultiChainRPC:${network}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
|
|
98
98
|
}
|
|
@@ -162,7 +162,7 @@ export const multiChainRpcCapability = {
|
|
|
162
162
|
spec: {
|
|
163
163
|
name: 'MultiChainRPC',
|
|
164
164
|
description: 'Read-only JSON-RPC against 40+ chains through the BlockRun gateway (one endpoint, no per-chain key). ' +
|
|
165
|
-
'$0.
|
|
165
|
+
'$0.0020 per call, plus a $0.001 settlement fee when paying from a wallet. Use for on-chain reads the other tools do not cover: native/token balances on any ' +
|
|
166
166
|
'chain, contract reads (eth_call), gas price, nonce, block height, and tx receipt checks ("did my swap land?"). ' +
|
|
167
167
|
'EVM chains speak eth_* (eth_blockNumber, eth_getBalance, eth_call, eth_gasPrice, eth_getTransactionReceipt, ...); ' +
|
|
168
168
|
'Solana speaks getSlot/getBalance/getAccountInfo/getTransaction; Bitcoin-family speaks getblockcount etc. ' +
|
package/dist/tools/surf.js
CHANGED
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
19
19
|
import { loadChain, USER_AGENT } from '../config.js';
|
|
20
|
-
import { resolveCharge } from '../payments/price-catalog.js';
|
|
20
|
+
import { basePriceForPath, chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
|
|
21
|
+
import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js';
|
|
21
22
|
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
22
23
|
import { frameUntrusted } from './untrusted.js';
|
|
23
24
|
import { recordUsage } from '../stats/tracker.js';
|
|
@@ -59,7 +60,7 @@ const CHAIN_ENDPOINTS = [
|
|
|
59
60
|
{ path: 'onchain/tx', method: 'GET', required: ['hash', 'chain'], desc: 'Transaction details by hash.' },
|
|
60
61
|
{ path: 'onchain/schema', method: 'GET', required: [], desc: 'Schema introspection for the SQL tables.' },
|
|
61
62
|
{ path: 'onchain/query', method: 'POST', required: [], desc: 'Structured chain query (POST body).' },
|
|
62
|
-
{ path: 'onchain/sql', method: 'POST', required: [], desc: 'Raw SQL against 80+ indexed chain tables (POST body
|
|
63
|
+
{ path: 'onchain/sql', method: 'POST', required: [], desc: 'Raw SQL against 80+ indexed chain tables (POST body).' },
|
|
63
64
|
{ path: 'token/tokenomics', method: 'GET', required: [], desc: 'Token supply / unlock / distribution.' },
|
|
64
65
|
{ path: 'token/dex-trades', method: 'GET', required: ['address'], desc: 'Recent DEX trades for a token.' },
|
|
65
66
|
{ path: 'token/holders', method: 'GET', required: ['address', 'chain'], desc: 'Top holders / concentration.' },
|
|
@@ -214,7 +215,7 @@ async function callSurf(toolName, table, input, ctx) {
|
|
|
214
215
|
// Fall back to the catalog price so Surf spend still counts against
|
|
215
216
|
// --max-spend and shows in stats.
|
|
216
217
|
const charge = response.ok
|
|
217
|
-
? resolveCharge({ apiPath: url, settledUsd: paidUsd })
|
|
218
|
+
? resolveCharge({ apiPath: url, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd })
|
|
218
219
|
: { usd: 0, estimated: false };
|
|
219
220
|
try {
|
|
220
221
|
recordUsage(`${toolName}:${entry.path}`, 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
|
|
@@ -238,13 +239,40 @@ async function callSurf(toolName, table, input, ctx) {
|
|
|
238
239
|
}
|
|
239
240
|
}
|
|
240
241
|
// ── Tool specs ───────────────────────────────────────────────────────────────
|
|
242
|
+
/**
|
|
243
|
+
* Price sentence for the tool description, read from the catalog rather than
|
|
244
|
+
* typed in.
|
|
245
|
+
*
|
|
246
|
+
* This used to read "Tier-1 $0.001, Tier-2 $0.005, Tier-3 $0.02", which the
|
|
247
|
+
* payment layer had long since replaced with one flat rate. Measured against
|
|
248
|
+
* the authoritative 402 on 2026-09-05: every Surf endpoint quotes $0.0085, so
|
|
249
|
+
* the description understated tier-1 by 8.5x and overstated tier-3 by 2.4x.
|
|
250
|
+
*
|
|
251
|
+
* That matters more than an inaccurate comment, because the agent reads this
|
|
252
|
+
* string to decide whether a call is worth making — it was being told the
|
|
253
|
+
* cheapest Surf call costs about a tenth of what it does. A hand-typed price
|
|
254
|
+
* is a published number with no owner; sourcing it from the catalog gives it
|
|
255
|
+
* one, and the guard test keeps literals from creeping back in.
|
|
256
|
+
*
|
|
257
|
+
* It states the BASE price and names the fee separately because there are two
|
|
258
|
+
* real prices per endpoint: the key rail charges the base, the wallet rail adds
|
|
259
|
+
* a settlement fee. One number cannot be right for both, and this phrasing is
|
|
260
|
+
* true on either.
|
|
261
|
+
*/
|
|
262
|
+
function surfPriceBlurb() {
|
|
263
|
+
const base = basePriceForPath('/v1/surf/market/ranking');
|
|
264
|
+
return base === null || base <= 0
|
|
265
|
+
? 'Each call is charged per request; the 402 quote states the exact price.'
|
|
266
|
+
: `Flat $${base.toFixed(4)} per call, plus a $${GATEWAY_TRANSACTION_FEE_USD.toFixed(3)} `
|
|
267
|
+
+ 'settlement fee when paying from a wallet.';
|
|
268
|
+
}
|
|
241
269
|
function makeSurfTool(name, blurb, table, extraParams) {
|
|
242
270
|
const endpointList = table.map((e) => `\`${e.path}\`${e.required.length ? ` (needs ${e.required.join('+')})` : ''} — ${e.desc}`).join('\n');
|
|
243
271
|
return {
|
|
244
272
|
spec: {
|
|
245
273
|
name,
|
|
246
274
|
description: `${blurb} Picks an endpoint from a fixed list and signs the x402 USDC payment from the wallet automatically — ` +
|
|
247
|
-
`you do not build paths or handle payment.
|
|
275
|
+
`you do not build paths or handle payment. ${surfPriceBlurb()}\n\nEndpoints:\n${endpointList}`,
|
|
248
276
|
input_schema: {
|
|
249
277
|
type: 'object',
|
|
250
278
|
properties: {
|
package/package.json
CHANGED