uvd-describe-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +612 -0
- package/dist/client-s3KrgrCt.d.mts +1537 -0
- package/dist/client-s3KrgrCt.d.ts +1537 -0
- package/dist/config-Y2VK_neB.d.mts +169 -0
- package/dist/config-Y2VK_neB.d.ts +169 -0
- package/dist/index.d.mts +488 -0
- package/dist/index.d.ts +488 -0
- package/dist/index.js +1082 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1038 -0
- package/dist/index.mjs.map +1 -0
- package/dist/partner/index.d.mts +194 -0
- package/dist/partner/index.d.ts +194 -0
- package/dist/partner/index.js +77 -0
- package/dist/partner/index.js.map +1 -0
- package/dist/partner/index.mjs +71 -0
- package/dist/partner/index.mjs.map +1 -0
- package/dist/x402/index.d.mts +91 -0
- package/dist/x402/index.d.ts +91 -0
- package/dist/x402/index.js +29 -0
- package/dist/x402/index.js.map +1 -0
- package/dist/x402/index.mjs +26 -0
- package/dist/x402/index.mjs.map +1 -0
- package/package.json +97 -0
- package/src/caveats.ts +124 -0
- package/src/client.ts +953 -0
- package/src/config.ts +181 -0
- package/src/errors.ts +596 -0
- package/src/format.ts +67 -0
- package/src/hashes.ts +229 -0
- package/src/index.ts +192 -0
- package/src/jitter.ts +112 -0
- package/src/parse.ts +388 -0
- package/src/partner/index.ts +295 -0
- package/src/raters.ts +118 -0
- package/src/recovery.ts +254 -0
- package/src/types.ts +457 -0
- package/src/x402/index.ts +123 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `DescribeClient` — six methods, four of which touch the network.
|
|
3
|
+
*
|
|
4
|
+
* ## The one thing to read before changing anything here
|
|
5
|
+
*
|
|
6
|
+
* There are THREE different absences in this file and collapsing any two of
|
|
7
|
+
* them is the failure this package exists to prevent:
|
|
8
|
+
*
|
|
9
|
+
* 1. **`globalScore: null` inside a returned object** — "the index looked and
|
|
10
|
+
* there is no eligible rating". Verified live on 2026-08-30 against
|
|
11
|
+
* `0xdEaD…BEEF`: HTTP 200, `chains: []`, `global_score: null`. Data.
|
|
12
|
+
* 2. **The method returning `null`** — "we could not ask" (`failOpen`).
|
|
13
|
+
* describe.net is down, or slow, or answered something unreadable.
|
|
14
|
+
* 3. **A thrown `DescribeError`** — the caller's request was wrong, or a 402
|
|
15
|
+
* arrived with no payer, or a challenge named the wrong treasury.
|
|
16
|
+
*
|
|
17
|
+
* A fail-open that is silent turns (2) into (1) — "describe is down" becomes
|
|
18
|
+
* "this wallet has no reputation" — which is precisely the confusion R1 exists
|
|
19
|
+
* to forbid, arriving through the back door. That is why `onFailure` is not
|
|
20
|
+
* optional decoration: it is the half of `failOpen` that keeps it honest, and
|
|
21
|
+
* `client.test.ts` asserts a failure is always announced before `null` is
|
|
22
|
+
* returned.
|
|
23
|
+
*
|
|
24
|
+
* ## 🔴 The paid routes never fail open — added 2026-08-30, and it is a money rule
|
|
25
|
+
*
|
|
26
|
+
* `wallet()`, `leaderboard()` and `health()` are free, so absence (2) costs
|
|
27
|
+
* nothing and a `null` is the kindest answer: without it every consumer writes
|
|
28
|
+
* the same try/catch around a lookup, which is the duplication this package
|
|
29
|
+
* exists to delete.
|
|
30
|
+
*
|
|
31
|
+
* `walletBreakdown()` and `agent()` are NOT free, and there they return no
|
|
32
|
+
* absence value at all — they throw, always, **including with `failOpen: true`
|
|
33
|
+
* set explicitly**. The line is not "how many methods", it is *was there money
|
|
34
|
+
* in flight*.
|
|
35
|
+
*
|
|
36
|
+
* ⚠️ **This is a correction of what shipped, left written because it is the
|
|
37
|
+
* whole reason this rule exists.** Until 2026-08-30 these two returned
|
|
38
|
+
* `| null` and ran their failures through `failOpenCovers()`, which is `true`
|
|
39
|
+
* for every `serviceFault`. Measured against a dead port that same day: a
|
|
40
|
+
* timeout on a metered route returned `null`. The paywall settles **before**
|
|
41
|
+
* running the query (`describe-net/describenet/paywall.py:1031-1047`), so that
|
|
42
|
+
* `null` could be handed back with the USDC already moved — and nothing in it
|
|
43
|
+
* distinguished "I paid and it fell over" from "there was nothing to fetch".
|
|
44
|
+
* That is not degrading gracefully, it is a spent credential with no receipt.
|
|
45
|
+
*
|
|
46
|
+
* A loud failure after paying is recoverable: the caller can retry, log or
|
|
47
|
+
* claim. A silent `null` is not, and no flag the caller sets can buy the right
|
|
48
|
+
* to swallow a receipt — availability is a preference, a settled payment is a
|
|
49
|
+
* fact. What the exception carries instead is `error.payment` (see
|
|
50
|
+
* `errors.ts::PaymentAttempt`) and `failedAfterPaying()` reads it.
|
|
51
|
+
*
|
|
52
|
+
* ## 🔴 The partner rail has a THIRD money rule — added 2026-08-30
|
|
53
|
+
*
|
|
54
|
+
* With `partner` configured (see `PartnerSigner` below and
|
|
55
|
+
* `uvd-describe-sdk/partner`), every request is signed and the metered routes
|
|
56
|
+
* are supposed to be free. Two failures are therefore CALLER-fault and neither
|
|
57
|
+
* one degrades:
|
|
58
|
+
*
|
|
59
|
+
* 1. the signature could not be produced → `DescribePartnerUnsigned`, thrown
|
|
60
|
+
* on every route including the free ones, `failOpen` or not;
|
|
61
|
+
* 2. the signature was produced and the route charged anyway →
|
|
62
|
+
* `DescribePartnerRejected`, thrown BEFORE the payer is ever called.
|
|
63
|
+
*
|
|
64
|
+
* Both are `serviceFault: false`, so `failOpenCovers()` refuses them. The
|
|
65
|
+
* symmetry with the paid-route rule is exact and deliberate: there, money that
|
|
66
|
+
* already moved may not be swallowed; here, money that is ABOUT to move may not
|
|
67
|
+
* be spent by accident. A partner rail that quietly falls back to paying is
|
|
68
|
+
* indistinguishable from a working one until the invoice arrives.
|
|
69
|
+
*
|
|
70
|
+
* ## What this client deliberately does NOT do
|
|
71
|
+
*
|
|
72
|
+
* **No cache.** MeshRelay has one (a `Map`, 12-minute TTL) and needs it: it
|
|
73
|
+
* recomputes channel scores on a route reachable from the internet, so an
|
|
74
|
+
* uncached lookup would let a stranger burn our share of a rate limit that has
|
|
75
|
+
* no per-partner bucket (the live figure is 50 rps sustained / burst 40, and
|
|
76
|
+
* the `RateLimit-Policy` response header is the authority — see the correction
|
|
77
|
+
* in `config.ts`). EM and KarmaKadabra have none. One of three is not a
|
|
78
|
+
* mandate, and a cache in a library is a policy
|
|
79
|
+
* decision about staleness that belongs to the app: MeshRelay's split of
|
|
80
|
+
* `refreshWallets` (async, network) from `getCached` (sync, NEVER network)
|
|
81
|
+
* exists because ITS threat model needed it, and baking a TTL in here would
|
|
82
|
+
* hand every consumer a staleness they did not choose. Documented in the README
|
|
83
|
+
* with MeshRelay's shape as the recipe.
|
|
84
|
+
*
|
|
85
|
+
* ⚠️ **Ratified 2026-08-30 by the only consumer that has a cache.** MeshRelay
|
|
86
|
+
* reviewed this decision in `#agents` and agreed the cache must not move into
|
|
87
|
+
* the library: *"una librería que decide cuánto tiempo miente por vos es peor
|
|
88
|
+
* que una que no cachea"*. The paragraph above now has two signatures, not one —
|
|
89
|
+
* which is the difference between a preference and a decision.
|
|
90
|
+
*
|
|
91
|
+
* **No retry.** Same reason, plus a measured one: MeshRelay retries a transient
|
|
92
|
+
* failure at most ONCE, "hammering a permanent failure is how EM turned one
|
|
93
|
+
* error into a four-hour storm" (`describenet.js:150-151`). A retry policy
|
|
94
|
+
* inside a library multiplies against whatever the caller already has.
|
|
95
|
+
* `DescribeError.transient` is exported so a caller can build the policy they
|
|
96
|
+
* want on a fact instead of on a string match.
|
|
97
|
+
*
|
|
98
|
+
* ## What it DOES do without being asked, and there is exactly one — added 2026-08-30
|
|
99
|
+
*
|
|
100
|
+
* **It sleeps `[0, 400) ms` before the first request of every call.** That is
|
|
101
|
+
* the one thing in this list that goes the other way, so it carries the burden
|
|
102
|
+
* of proof: the number and the measurement are KarmaKadabra's (27 agents on one
|
|
103
|
+
* EventBridge schedule, against a rate limit shared with no per-partner bucket —
|
|
104
|
+
* *"sin jitter, un enjambre es un DDoS educado"*), and the argument for shipping
|
|
105
|
+
* it ON is in `config.ts::DEFAULT_JITTER_MS`. `jitterMs: 0` turns it off.
|
|
106
|
+
*
|
|
107
|
+
* It is NOT the retry policy above wearing a different hat, and `jitter.ts`
|
|
108
|
+
* spells out why: jitter disperses a herd that has not asked for anything yet,
|
|
109
|
+
* backoff yields to a service that has already said no. The first goes before
|
|
110
|
+
* the first request; the second would go before a retry this package does not
|
|
111
|
+
* have.
|
|
112
|
+
*
|
|
113
|
+
* ## The second thing `onFailure` announces — added 2026-08-30
|
|
114
|
+
*
|
|
115
|
+
* A hash field that arrives as something other than a hash is dropped to `null`
|
|
116
|
+
* and announced as `kind: 'malformed_hash'` (KarmaKadabra's *"el 200 sin tx"*;
|
|
117
|
+
* see `hashes.ts` and `announceMalformed` below). It does not throw — one bad
|
|
118
|
+
* accessory field must not destroy a decomposition that was paid for — and it
|
|
119
|
+
* does not pass through, which is what bit them.
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
import {
|
|
123
|
+
DEFAULT_BASE_URL,
|
|
124
|
+
DEFAULT_JITTER_MS,
|
|
125
|
+
DEFAULT_SITE_URL,
|
|
126
|
+
DEFAULT_TIMEOUT_MS,
|
|
127
|
+
TREASURY_EVM,
|
|
128
|
+
userAgent,
|
|
129
|
+
} from './config';
|
|
130
|
+
import {
|
|
131
|
+
attachPayment,
|
|
132
|
+
DescribeError,
|
|
133
|
+
DescribeHTTPError,
|
|
134
|
+
DescribeMalformedHash,
|
|
135
|
+
DescribeNotFound,
|
|
136
|
+
DescribePartnerRejected,
|
|
137
|
+
DescribePartnerUnsigned,
|
|
138
|
+
DescribePaymentRefused,
|
|
139
|
+
DescribePaymentRequired,
|
|
140
|
+
DescribeTimeout,
|
|
141
|
+
DescribeUnparseable,
|
|
142
|
+
DescribeUnreachable,
|
|
143
|
+
failOpenCovers,
|
|
144
|
+
type PaymentAttempt,
|
|
145
|
+
type X402Challenge,
|
|
146
|
+
} from './errors';
|
|
147
|
+
import { looksLikeSettlementReceipt, malformedHashReport } from './hashes';
|
|
148
|
+
import { jitterDelayMs, sleep } from './jitter';
|
|
149
|
+
import {
|
|
150
|
+
parseAgentReputation,
|
|
151
|
+
parseHealth,
|
|
152
|
+
parseLeaderboard,
|
|
153
|
+
parseWalletBreakdown,
|
|
154
|
+
parseWalletReputation,
|
|
155
|
+
} from './parse';
|
|
156
|
+
import type {
|
|
157
|
+
AgentReputation,
|
|
158
|
+
IndexHealth,
|
|
159
|
+
LeaderboardRow,
|
|
160
|
+
PaymentEvidence,
|
|
161
|
+
WalletBreakdown,
|
|
162
|
+
WalletReputation,
|
|
163
|
+
} from './types';
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* How a metered call gets paid.
|
|
167
|
+
*
|
|
168
|
+
* 🔴 This SDK NEVER signs, never touches a private key and never builds an
|
|
169
|
+
* EIP-3009 authorization. That is `uvd-x402-sdk`'s job and reimplementing it
|
|
170
|
+
* here would be the house's cardinal sin (upstream-first: if the payment SDK
|
|
171
|
+
* lacks something, it is added THERE and consumed from here). This interface is
|
|
172
|
+
* the seam, and it is one method wide on purpose — anything wider would start
|
|
173
|
+
* to encode payment knowledge we have no business having.
|
|
174
|
+
*
|
|
175
|
+
* The canonical implementation ships at `uvd-describe-sdk/x402` and wraps the
|
|
176
|
+
* payment SDK's `X402Client`. It lives behind a subpath so this module never
|
|
177
|
+
* imports it: a consumer who only reads free routes installs nothing.
|
|
178
|
+
*/
|
|
179
|
+
export interface X402Payer {
|
|
180
|
+
/**
|
|
181
|
+
* Given the parsed 402 challenge, return the value for the `X-PAYMENT`
|
|
182
|
+
* header. Throwing aborts the call — nothing is replayed.
|
|
183
|
+
*/
|
|
184
|
+
pay(challenge: X402Challenge): Promise<string>;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* How a request proves it comes from a partner of the house.
|
|
189
|
+
*
|
|
190
|
+
* ## The seam, and why it is exactly one method wide
|
|
191
|
+
*
|
|
192
|
+
* Same shape and same reason as {@link X402Payer}: this package holds no key,
|
|
193
|
+
* builds no signature and knows no cryptography. It hands a request over and
|
|
194
|
+
* gets headers back. Anything wider would start encoding signing knowledge that
|
|
195
|
+
* belongs to `uvd-x402-sdk`, and the canonical implementation — which does
|
|
196
|
+
* nothing but call that SDK's ERC-8128 signer — ships at
|
|
197
|
+
* `uvd-describe-sdk/partner`, behind a subpath, so the main entry keeps its zero
|
|
198
|
+
* runtime imports.
|
|
199
|
+
*
|
|
200
|
+
* ## What the other side does with it
|
|
201
|
+
*
|
|
202
|
+
* describe.net has no accounts and no API keys — *"el pago es la
|
|
203
|
+
* autenticación"* — so the free rail for our own products could not be a token.
|
|
204
|
+
* It is an allowlist of PUBLIC ADDRESSES plus a per-request ERC-8128 signature
|
|
205
|
+
* (`describe-net/describenet/partner.py`, read 2026-08-30). The service
|
|
206
|
+
* therefore custodies no secret of ours: a breach of describe.net leaks a list
|
|
207
|
+
* of addresses, which are already public. That property is the reason this is a
|
|
208
|
+
* signature and not the `X-API-Key` everybody expects, and it is worth
|
|
209
|
+
* protecting when extending this interface.
|
|
210
|
+
*
|
|
211
|
+
* The gate verifies with a policy pinned to `api.describe.net`, chain 8453 and a
|
|
212
|
+
* 300 s window, and then — the line that makes it a gate — looks the recovered
|
|
213
|
+
* address up in the allowlist (`partner.py:242`). A valid signature from an
|
|
214
|
+
* unlisted wallet pays like everybody else.
|
|
215
|
+
*
|
|
216
|
+
* ## Throwing is the contract
|
|
217
|
+
*
|
|
218
|
+
* `sign()` MUST throw rather than return partial or unsigned headers. The client
|
|
219
|
+
* turns that throw into `DescribePartnerUnsigned` and raises it — it never
|
|
220
|
+
* proceeds unsigned, because an unsigned request from a partner client is an
|
|
221
|
+
* anonymous request, and an anonymous request pays.
|
|
222
|
+
*/
|
|
223
|
+
export interface PartnerSigner {
|
|
224
|
+
/**
|
|
225
|
+
* Sign one request; return the headers to add to it.
|
|
226
|
+
*
|
|
227
|
+
* For describe.net's GET-only surface that is `Signature` and
|
|
228
|
+
* `Signature-Input` (RFC 9421). `Content-Digest` appears only for a request
|
|
229
|
+
* with a body, and this client never sends one.
|
|
230
|
+
*/
|
|
231
|
+
sign(request: { method: string; url: string }): Promise<Record<string, string>>;
|
|
232
|
+
/**
|
|
233
|
+
* The signing address, if the implementation cares to publish it. Used ONLY
|
|
234
|
+
* to write a useful error message. It is never sent as a header and never
|
|
235
|
+
* trusted: the server decides from the address it RECOVERS, not one we claim.
|
|
236
|
+
*/
|
|
237
|
+
readonly address?: string;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** What `onFailure` is handed. Enough to log, alert or fall back on. */
|
|
241
|
+
export interface DescribeFailure {
|
|
242
|
+
/** The route that failed, e.g. `/wallets/0x…/chains`. */
|
|
243
|
+
path: string;
|
|
244
|
+
error: DescribeError;
|
|
245
|
+
/** Shorthand for `error.kind`, so a logger never has to reach in. */
|
|
246
|
+
kind: DescribeError['kind'];
|
|
247
|
+
/** Would retrying help? */
|
|
248
|
+
transient: boolean;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export interface DescribeClientConfig {
|
|
252
|
+
/** Default `https://api.describe.net`. */
|
|
253
|
+
baseUrl?: string;
|
|
254
|
+
/** Default 30 000 ms. See `config.ts` for why that number and not another. */
|
|
255
|
+
timeoutMs?: number;
|
|
256
|
+
/**
|
|
257
|
+
* Your product's name, appended to the `User-Agent` as `(+name)`.
|
|
258
|
+
*
|
|
259
|
+
* Strongly recommended and free: the rate limit is shared across the
|
|
260
|
+
* ecosystem with no per-partner bucket, and the UA is the only thing that
|
|
261
|
+
* makes your share of it attributable when something gets loud. The ceiling
|
|
262
|
+
* itself is not typed here — the `RateLimit-Policy` response header is the
|
|
263
|
+
* authority (see the correction in `config.ts`).
|
|
264
|
+
*/
|
|
265
|
+
product?: string;
|
|
266
|
+
/**
|
|
267
|
+
* Default **true**, and it is what Saul asked for in those words: *"pon un
|
|
268
|
+
* fallback si es que describe está caído"* (2026-08-28).
|
|
269
|
+
*
|
|
270
|
+
* `true` — a describe.net-side failure returns `null` and calls `onFailure`.
|
|
271
|
+
* `false` — the same failure throws a typed `DescribeError`.
|
|
272
|
+
*
|
|
273
|
+
* **Scope: the free routes only** — `wallet()`, `leaderboard()`, `health()`.
|
|
274
|
+
* `walletBreakdown()` and `agent()` ignore this flag in both positions and
|
|
275
|
+
* always throw; see the header of this file for why money removes the choice.
|
|
276
|
+
*
|
|
277
|
+
* Either way a 4xx that is the CALLER's fault still throws: `failOpen`
|
|
278
|
+
* protects you from their outage, not from your own bug.
|
|
279
|
+
*/
|
|
280
|
+
failOpen?: boolean;
|
|
281
|
+
/**
|
|
282
|
+
* Where a swallowed fact goes. **`onFailure` announces everything this client
|
|
283
|
+
* swallowed, and nothing it handed you.** Two things qualify:
|
|
284
|
+
*
|
|
285
|
+
* 1. a `null` returned instead of an answer (the fail-open, free routes
|
|
286
|
+
* only) — announced BEFORE the `null`, always;
|
|
287
|
+
* 2. a hash field dropped because it was not a hash
|
|
288
|
+
* (`kind: 'malformed_hash'`, metered routes, added 2026-08-30).
|
|
289
|
+
*
|
|
290
|
+
* A failure that reaches you as a throw is never announced here: you are
|
|
291
|
+
* already holding it.
|
|
292
|
+
*
|
|
293
|
+
* ⚠️ **This is a restatement, and the old wording is left because someone will
|
|
294
|
+
* look for it.** It read: *"fires if and only if a method hands back `null`…
|
|
295
|
+
* the paid routes therefore never call this at all"*. That was a description
|
|
296
|
+
* of the only case that existed, not of the rule — and the rule it protected
|
|
297
|
+
* is that nothing disappears quietly. A field that vanished out of a 200 is
|
|
298
|
+
* exactly as invisible as a silent fail-open, so it belongs on the same
|
|
299
|
+
* channel. Filter it in one line if you only page on outages:
|
|
300
|
+
* `if (f.kind === 'malformed_hash') return;` — it is `transient: false` and
|
|
301
|
+
* `serviceFault: false`, and the paid routes still never fail open.
|
|
302
|
+
*
|
|
303
|
+
* Leaving this unset with `failOpen: true` is the one configuration this
|
|
304
|
+
* package will not defend: it converts "describe is down" into "this wallet
|
|
305
|
+
* has no reputation" with nothing written down anywhere. It is allowed
|
|
306
|
+
* because a hard requirement would be a `throw` in the constructor of a
|
|
307
|
+
* read-only client, but the README says it plainly and so does this comment.
|
|
308
|
+
*/
|
|
309
|
+
onFailure?: (failure: DescribeFailure) => void;
|
|
310
|
+
/**
|
|
311
|
+
* Sleep a random `[0, jitterMs)` before **every** request, so a fleet waking
|
|
312
|
+
* on one schedule does not arrive as one spike. **Default 400**, and `0` turns
|
|
313
|
+
* it off.
|
|
314
|
+
*
|
|
315
|
+
* ⚠️ *Every* request, the replay of a paid one included: a method that fires
|
|
316
|
+
* two requests sleeps twice. The intuitive rule — once per public call — was
|
|
317
|
+
* written here first and is wrong, because it disperses the first request and
|
|
318
|
+
* lets the rest out in a pack. `jitter()` below carries the correction and the
|
|
319
|
+
* call site in KarmaKadabra's own code that settles it.
|
|
320
|
+
*
|
|
321
|
+
* The number and the reason are KarmaKadabra's, measured on a fleet of 27
|
|
322
|
+
* (2026-08-30) — see `config.ts::DEFAULT_JITTER_MS` for why it ships ON, and
|
|
323
|
+
* `jitter.ts` for why this is not backoff and why it is not a CSPRNG.
|
|
324
|
+
*
|
|
325
|
+
* Set it to `0` in your own unit tests: a suite that sleeps 200 ms per mocked
|
|
326
|
+
* call is paying for a behaviour it is not testing. This package's own suite
|
|
327
|
+
* does exactly that.
|
|
328
|
+
*
|
|
329
|
+
* A value that is not a finite number ≥ 0 falls back to the **default**, not
|
|
330
|
+
* to off: a typo must not silently remove a protection the rest of the
|
|
331
|
+
* ecosystem is relying on. Only a real `0` disables it.
|
|
332
|
+
*/
|
|
333
|
+
jitterMs?: number;
|
|
334
|
+
/** Pay metered routes. Without it, a 402 throws `DescribePaymentRequired`. */
|
|
335
|
+
payer?: X402Payer;
|
|
336
|
+
/**
|
|
337
|
+
* Enter through the partner rail: sign every request as a wallet the house
|
|
338
|
+
* has allowlisted, and read the metered routes for free.
|
|
339
|
+
*
|
|
340
|
+
* Build one with `partnerFromEnv()` or `partnerFromSigner()` from
|
|
341
|
+
* `uvd-describe-sdk/partner`. Both are the same rail — one reads a key the
|
|
342
|
+
* environment holds, the other takes a signer you already have.
|
|
343
|
+
*
|
|
344
|
+
* 🔴 EVERY request is signed, free routes included, and that is a decision
|
|
345
|
+
* with a reason: the alternative is a table in this package saying which
|
|
346
|
+
* routes are metered, which would be a second copy of the service's
|
|
347
|
+
* `pricing.TIERS` and would silently start paying the day a free route
|
|
348
|
+
* becomes metered. The server already knows which is which; we do not need
|
|
349
|
+
* to. What it costs, measured on this machine 2026-08-30 (Node v23.11.0, 200
|
|
350
|
+
* signatures with an in-process ethers wallet, after 20 warm-up rounds):
|
|
351
|
+
* **0,67 ms** per signature, against a 30 000 ms request timeout. Four ten-
|
|
352
|
+
* thousandths of the budget for the request it rides on.
|
|
353
|
+
*/
|
|
354
|
+
partner?: PartnerSigner;
|
|
355
|
+
/**
|
|
356
|
+
* 🔴 Default **false**, and the default is the point.
|
|
357
|
+
*
|
|
358
|
+
* With partner mode on, a metered route that answers 402 means the free rail
|
|
359
|
+
* did not work. By default that throws `DescribePartnerRejected` and NOTHING
|
|
360
|
+
* IS PAID. Set this to `true` to fall through to the `payer` instead — an
|
|
361
|
+
* explicit decision to spend USDC when the rail is down, which is a
|
|
362
|
+
* reasonable thing to want and an unreasonable thing to get by accident.
|
|
363
|
+
*
|
|
364
|
+
* With no `partner` configured this flag does nothing at all.
|
|
365
|
+
*/
|
|
366
|
+
partnerFallsBackToPaying?: boolean;
|
|
367
|
+
/**
|
|
368
|
+
* The only address this client will pay. Defaults to the pinned treasury.
|
|
369
|
+
* Override only if you have verified a rotation out of band — see
|
|
370
|
+
* `config.ts::TREASURY_EVM` for the failure mode of pinning.
|
|
371
|
+
*/
|
|
372
|
+
expectedPayTo?: string;
|
|
373
|
+
/** Injectable for tests. Defaults to the global `fetch`. */
|
|
374
|
+
fetchImpl?: typeof fetch;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Read reputation from describe.net. */
|
|
378
|
+
export class DescribeClient {
|
|
379
|
+
private readonly baseUrl: string;
|
|
380
|
+
private readonly timeoutMs: number;
|
|
381
|
+
private readonly ua: string;
|
|
382
|
+
private readonly failOpen: boolean;
|
|
383
|
+
private readonly onFailure?: (failure: DescribeFailure) => void;
|
|
384
|
+
private readonly jitterMs: number;
|
|
385
|
+
private readonly payer?: X402Payer;
|
|
386
|
+
private readonly partner?: PartnerSigner;
|
|
387
|
+
private readonly partnerFallsBackToPaying: boolean;
|
|
388
|
+
private readonly expectedPayTo: string;
|
|
389
|
+
private readonly fetchImpl: typeof fetch;
|
|
390
|
+
|
|
391
|
+
constructor(config: DescribeClientConfig = {}) {
|
|
392
|
+
this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
393
|
+
this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
394
|
+
this.ua = userAgent(config.product);
|
|
395
|
+
this.failOpen = config.failOpen ?? true;
|
|
396
|
+
this.onFailure = config.onFailure;
|
|
397
|
+
// Garbage falls back to the DEFAULT, never to off, and never throws here: a
|
|
398
|
+
// mistyped option must not silently drop a protection the rest of the
|
|
399
|
+
// ecosystem relies on, and a library that dies in its constructor over one
|
|
400
|
+
// is worse than one that ignores it. Only a real 0 disables the jitter.
|
|
401
|
+
this.jitterMs =
|
|
402
|
+
typeof config.jitterMs === 'number' && Number.isFinite(config.jitterMs) && config.jitterMs >= 0
|
|
403
|
+
? config.jitterMs
|
|
404
|
+
: DEFAULT_JITTER_MS;
|
|
405
|
+
this.payer = config.payer;
|
|
406
|
+
this.partner = config.partner;
|
|
407
|
+
this.partnerFallsBackToPaying = config.partnerFallsBackToPaying ?? false;
|
|
408
|
+
this.expectedPayTo = config.expectedPayTo ?? TREASURY_EVM;
|
|
409
|
+
const impl = config.fetchImpl ?? globalThis.fetch;
|
|
410
|
+
if (typeof impl !== 'function') {
|
|
411
|
+
throw new TypeError(
|
|
412
|
+
'No fetch available. Node >= 18 has one; otherwise pass `fetchImpl` in the config.',
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
this.fetchImpl = impl;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// -------------------------------------------------------------------------
|
|
419
|
+
// Free — no dependency, no signature, no credential
|
|
420
|
+
// -------------------------------------------------------------------------
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* `GET /wallets/{wallet}/chains` — **free**. The happy path starts here.
|
|
424
|
+
*
|
|
425
|
+
* Gratis-primero is not politeness, it is the shape of the product: the 402
|
|
426
|
+
* challenge of the metered route says it itself — *"si ahí no hay nada, no
|
|
427
|
+
* hay nada que comprar"*. Ask for free whether there is anything, and only
|
|
428
|
+
* then buy the decomposition.
|
|
429
|
+
*
|
|
430
|
+
* `wallet` goes through VERBATIM. EVM is normalised server-side, but Solana
|
|
431
|
+
* base58 is case-SENSITIVE and lower-casing it here would silently ask about
|
|
432
|
+
* a different wallet.
|
|
433
|
+
*
|
|
434
|
+
* @returns the reputation (whose `globalScore` may be `null` — that is an
|
|
435
|
+
* answer), or `null` when describe.net could not be reached and `failOpen`
|
|
436
|
+
* is on.
|
|
437
|
+
*/
|
|
438
|
+
async wallet(address: string): Promise<WalletReputation | null> {
|
|
439
|
+
const path = `/wallets/${encodeURIComponent(address)}/chains`;
|
|
440
|
+
return this.guard(path, async () => parseWalletReputation(await this.getJson(path)));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* `GET /leaderboard` — **free**, first page.
|
|
445
|
+
*
|
|
446
|
+
* Takes NO parameters: `?limit=2` answers 422 `leaderboard_takes_no_params`
|
|
447
|
+
* (verified live 2026-08-30). Paging is the metered `/leaderboard/page`.
|
|
448
|
+
*
|
|
449
|
+
* ⚠️ Ordered by `shrunkScore`, not by `finalScore`. Re-sorting client-side by
|
|
450
|
+
* `finalScore` undoes the shrinkage and puts a single 100-point rating above
|
|
451
|
+
* two hundred real ones.
|
|
452
|
+
*/
|
|
453
|
+
async leaderboard(): Promise<LeaderboardRow[] | null> {
|
|
454
|
+
const path = '/leaderboard';
|
|
455
|
+
return this.guard(path, async () => parseLeaderboard(await this.getJson(path)));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* `GET /health` — **free**, and the authority on this index's totals.
|
|
460
|
+
*
|
|
461
|
+
* Also the live source for `readingPolicy` and `confidenceThresholds`: the
|
|
462
|
+
* server publishes its own calibrable values so that no consumer re-types
|
|
463
|
+
* them. Read them here rather than hardcoding a threshold that will drift.
|
|
464
|
+
*/
|
|
465
|
+
async health(): Promise<IndexHealth | null> {
|
|
466
|
+
const path = '/health';
|
|
467
|
+
return this.guard(path, async () => parseHealth(await this.getJson(path)));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The badge URL. **Builds a string, opens no socket, cannot fail.**
|
|
472
|
+
*
|
|
473
|
+
* `GET /badge/{wallet}.svg` is free and returns `image/svg+xml` (604 bytes,
|
|
474
|
+
* verified 2026-08-30). Drop it in an `<img>` and a page shows a live score
|
|
475
|
+
* with its distinct raters and the date of the data, with no JavaScript and
|
|
476
|
+
* no dependency on this package at all.
|
|
477
|
+
*/
|
|
478
|
+
badgeUrl(address: string): string {
|
|
479
|
+
return `${this.baseUrl}/badge/${encodeURIComponent(address)}.svg`;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Where a human reads the same wallet. On surfaces without hover, THIS is the attribution. */
|
|
483
|
+
profileUrl(address: string, siteUrl: string = DEFAULT_SITE_URL): string {
|
|
484
|
+
return `${siteUrl.replace(/\/+$/, '')}/agent.html?wallet=${encodeURIComponent(address)}`;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// -------------------------------------------------------------------------
|
|
488
|
+
// Metered — a 402 is paid through uvd-x402-sdk, never by us
|
|
489
|
+
// -------------------------------------------------------------------------
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* `GET /reputation/wallet/{wallet}` — **metered, $0.01** ($0.05 with a
|
|
493
|
+
* citable snapshot). Who rated, how many times, how concentrated.
|
|
494
|
+
*
|
|
495
|
+
* The price above is documentation with a date on it, not a value this SDK
|
|
496
|
+
* uses: what gets paid is what the live challenge says. We never type a
|
|
497
|
+
* price into a code path.
|
|
498
|
+
*
|
|
499
|
+
* 🔴 **Not nullable, and never fail-open** — not even with `failOpen: true`.
|
|
500
|
+
* There is money in flight here, and a swallowed failure is a spent
|
|
501
|
+
* credential with no receipt. Every failure arrives as a typed throw, and one
|
|
502
|
+
* that happened after the envelope left carries `error.payment`
|
|
503
|
+
* (`failedAfterPaying()`). Note this includes a 404: it is still absence and
|
|
504
|
+
* still costs nothing (it is checked before the challenge is read), but with
|
|
505
|
+
* no `| null` left there is nowhere to degrade it to.
|
|
506
|
+
*
|
|
507
|
+
* Without a `payer`, throws `DescribePaymentRequired` with the challenge
|
|
508
|
+
* attached — asking is free and is the intended first move, so you can read
|
|
509
|
+
* the price without paying.
|
|
510
|
+
*/
|
|
511
|
+
async walletBreakdown(address: string): Promise<WalletBreakdown> {
|
|
512
|
+
const path = `/reputation/wallet/${encodeURIComponent(address)}`;
|
|
513
|
+
const { body, payment, servedReceipt } = await this.getPaidJson(path);
|
|
514
|
+
const result = parseWalletBreakdown(body, payment);
|
|
515
|
+
this.announceMalformed(path, result, servedReceipt);
|
|
516
|
+
return result;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* `GET /reputation/agent/{network}/{agentId}` — **metered, $0.02**. One
|
|
521
|
+
* ERC-8004 identity, down to the individual ratings.
|
|
522
|
+
*
|
|
523
|
+
* 🔴 Same money rule as `walletBreakdown()`: not nullable, never fail-open,
|
|
524
|
+
* throws on everything including a 404 for an agent id that does not exist.
|
|
525
|
+
*/
|
|
526
|
+
async agent(network: string, agentId: string | number): Promise<AgentReputation> {
|
|
527
|
+
const path = `/reputation/agent/${encodeURIComponent(network)}/${encodeURIComponent(String(agentId))}`;
|
|
528
|
+
const { body, payment, servedReceipt } = await this.getPaidJson(path);
|
|
529
|
+
const result = parseAgentReputation(body, payment);
|
|
530
|
+
this.announceMalformed(path, result, servedReceipt);
|
|
531
|
+
return result;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// -------------------------------------------------------------------------
|
|
535
|
+
// Internals
|
|
536
|
+
// -------------------------------------------------------------------------
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* The fail-open gate — **for the free routes, and only for them**.
|
|
540
|
+
*
|
|
541
|
+
* ⚠️ Corrected 2026-08-30. The old comment here read *"every network method
|
|
542
|
+
* goes through exactly one of these so the rule cannot drift between
|
|
543
|
+
* methods"*, and the intent was right while the scope was wrong: routing the
|
|
544
|
+
* paid methods through it is what let a post-settlement timeout come back as
|
|
545
|
+
* `null`. The rule that must not drift is R5, and R5 has a term this function
|
|
546
|
+
* cannot see. So the paid methods do not call it — deliberately, and a test
|
|
547
|
+
* named `MOUNTS THE BAD STATE` goes red if anyone puts them back.
|
|
548
|
+
*
|
|
549
|
+
* Whoever adds the sixth method: free ⇒ wrap it here; metered ⇒ do not.
|
|
550
|
+
*/
|
|
551
|
+
private async guard<T>(path: string, run: () => Promise<T>): Promise<T | null> {
|
|
552
|
+
try {
|
|
553
|
+
return await run();
|
|
554
|
+
} catch (error) {
|
|
555
|
+
// A 404 is DATA — "there is nothing here" — so it never leaves as an
|
|
556
|
+
// exception, `failOpen` or not (R4). It is still announced: a mistyped
|
|
557
|
+
// `baseUrl` 404s every route, and a silent null forever would read as
|
|
558
|
+
// "nobody in this index has any reputation".
|
|
559
|
+
if (error instanceof DescribeNotFound) {
|
|
560
|
+
this.onFailure?.({ path, error, kind: error.kind, transient: false });
|
|
561
|
+
return null;
|
|
562
|
+
}
|
|
563
|
+
if (this.failOpen && failOpenCovers(error)) {
|
|
564
|
+
// Announced BEFORE the null. If this ever moves below the return, a
|
|
565
|
+
// failure becomes indistinguishable from an unrated wallet.
|
|
566
|
+
this.onFailure?.({
|
|
567
|
+
path,
|
|
568
|
+
error,
|
|
569
|
+
kind: error.kind,
|
|
570
|
+
transient: error.transient,
|
|
571
|
+
});
|
|
572
|
+
return null;
|
|
573
|
+
}
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* The pause that disperses a fleet. **Before EVERY request** — called from the
|
|
580
|
+
* top of `request()` and from nowhere else, so a method that makes two
|
|
581
|
+
* requests sleeps twice.
|
|
582
|
+
*
|
|
583
|
+
* ⚠️ **Corrected 2026-08-30, and the wrong version is left written because it
|
|
584
|
+
* is the intuitive one and someone will want it back.** This first sat in
|
|
585
|
+
* `getJson()` / `getPaidJson()`, i.e. *once per public call, before the FIRST
|
|
586
|
+
* request*, on the theory that the metered flow should not sleep twice. That
|
|
587
|
+
* is a hole: a call that fires N requests would disperse one of them and let
|
|
588
|
+
* the other N−1 out in a pack, which is the exact problem this contribution
|
|
589
|
+
* came to fix. KarmaKadabra's own call site settles it — their sleep lives
|
|
590
|
+
* inside the function that performs the GET (`reputation_scan.py:123`), and
|
|
591
|
+
* that function runs twice on their real path (`:242` for the EVM address,
|
|
592
|
+
* `:245` for the Solana one). Their jitter is per REQUEST, and the reason they
|
|
593
|
+
* wrote beside it (`:121-122`) is per-PROCESS: agents that wake together
|
|
594
|
+
* against a shared ceiling.
|
|
595
|
+
*
|
|
596
|
+
* The paid replay sleeps too, and that was the hardest half of the correction
|
|
597
|
+
* to accept. The argument for exempting it was that delaying a signed envelope
|
|
598
|
+
* widens the window in which a crash loses a receipt — but the challenge this
|
|
599
|
+
* client answers carries `maxTimeoutSeconds: 120`, so 400 ms is a third of a
|
|
600
|
+
* percent of the envelope's own validity, while the herd argument applies to
|
|
601
|
+
* the replay in full: 27 agents that get their 402 in the same second replay
|
|
602
|
+
* in the same second.
|
|
603
|
+
*
|
|
604
|
+
* **Before the signature, and before the clock.** `request()` calls this
|
|
605
|
+
* first, so an ERC-8128 signature is never left ageing against its 300 s
|
|
606
|
+
* window while we sleep, and the sleep is not charged to `timeoutMs`.
|
|
607
|
+
*/
|
|
608
|
+
private async jitter(): Promise<void> {
|
|
609
|
+
const ms = jitterDelayMs(this.jitterMs);
|
|
610
|
+
if (ms > 0) await sleep(ms);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Announce a malformed hash field, if there is one — KarmaKadabra's *"el 200
|
|
615
|
+
* sin tx"*, reaching the caller.
|
|
616
|
+
*
|
|
617
|
+
* ⚠️ **This is the second thing `onFailure` announces, and invariant 4 is
|
|
618
|
+
* restated rather than broken.** It used to read *"`onFailure` fires if and
|
|
619
|
+
* only if a method hands back `null`"*, and that wording was a description of
|
|
620
|
+
* the only case that existed on 2026-08-30 at noon. The rule it was protecting
|
|
621
|
+
* is bigger and now reads: **`onFailure` announces everything that was
|
|
622
|
+
* silently swallowed — a `null` handed back instead of an answer, and a field
|
|
623
|
+
* dropped because it was not what it claimed to be — and nothing that reaches
|
|
624
|
+
* you as a throw.** A failure you are holding does not need announcing; a
|
|
625
|
+
* field that vanished out of a 200 does, and it is exactly as invisible as a
|
|
626
|
+
* silent fail-open.
|
|
627
|
+
*
|
|
628
|
+
* That is why it is not a second callback: the channel a consumer is already
|
|
629
|
+
* watching is where KarmaKadabra asked for this to land, and a new one would
|
|
630
|
+
* be a channel nobody wired. The notice is filterable in one line
|
|
631
|
+
* (`f.kind === 'malformed_hash'`), carries `transient: false` and
|
|
632
|
+
* `serviceFault: false`, and the error it carries is never thrown.
|
|
633
|
+
*
|
|
634
|
+
* 🔴 The callback is wrapped, and this call site is the reason: it fires after
|
|
635
|
+
* a metered read that already SETTLED. An observer that throws would destroy a
|
|
636
|
+
* response the caller paid for, which is the same class of bug as swallowing a
|
|
637
|
+
* receipt — with the sign flipped. (The `guard()` call site is deliberately
|
|
638
|
+
* left unwrapped: there the answer is already `null`, so a throwing observer
|
|
639
|
+
* costs nothing that was bought.)
|
|
640
|
+
*/
|
|
641
|
+
private announceMalformed(
|
|
642
|
+
path: string,
|
|
643
|
+
result: Parameters<typeof malformedHashReport>[0],
|
|
644
|
+
servedReceipt: string | null,
|
|
645
|
+
): void {
|
|
646
|
+
const fields = malformedHashReport(result);
|
|
647
|
+
if (fields.length === 0) return;
|
|
648
|
+
// The receipt is the ONE malformed value `raw` cannot preserve — `raw` is
|
|
649
|
+
// the body and that arrived as a header — so it is quoted here or it is
|
|
650
|
+
// lost. Truncated because a field that is not a hash can be anything: the
|
|
651
|
+
// longest `tag1` in this index is 471 characters of prose.
|
|
652
|
+
const quoted =
|
|
653
|
+
fields.includes('payment.receipt') && servedReceipt !== null
|
|
654
|
+
? ` The receipt as served was ${JSON.stringify(servedReceipt.slice(0, 120))}.`
|
|
655
|
+
: '';
|
|
656
|
+
const error = new DescribeMalformedHash(
|
|
657
|
+
`GET ${path} served ${fields.length} field(s) that are not hashes: ${fields.join(', ')}. ` +
|
|
658
|
+
'Each one was dropped to null; every other value as served is still in `raw`. ' +
|
|
659
|
+
`Nothing was retried and nothing else in the answer was touched.${quoted}`,
|
|
660
|
+
fields,
|
|
661
|
+
);
|
|
662
|
+
try {
|
|
663
|
+
this.onFailure?.({ path, error, kind: error.kind, transient: false });
|
|
664
|
+
} catch {
|
|
665
|
+
// An observer that throws must not destroy a response that was paid for.
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The partner headers for one request, or `{}` when there is no partner.
|
|
671
|
+
*
|
|
672
|
+
* 🔴 THIS RUNS OUTSIDE `request()`'s try/catch AND THAT IS THE WHOLE POINT.
|
|
673
|
+
* Inside it, a signer that threw would be caught by the transport handler and
|
|
674
|
+
* re-thrown as `DescribeUnreachable` — which is `serviceFault: true`, which
|
|
675
|
+
* `failOpen` swallows, which turns "my partner key is missing" into a `null`
|
|
676
|
+
* that reads as "this wallet has no reputation". The most expensive bug in
|
|
677
|
+
* this file, one indentation level away.
|
|
678
|
+
*/
|
|
679
|
+
private async partnerHeaders(path: string): Promise<Record<string, string>> {
|
|
680
|
+
if (!this.partner) return {};
|
|
681
|
+
try {
|
|
682
|
+
return await this.partner.sign({ method: 'GET', url: `${this.baseUrl}${path}` });
|
|
683
|
+
} catch (error) {
|
|
684
|
+
throw new DescribePartnerUnsigned(path, this.partner.address, error);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
private async request(path: string, headers: Record<string, string> = {}): Promise<Response> {
|
|
689
|
+
// Every request, not every call: see `jitter()` for the correction and for
|
|
690
|
+
// the KarmaKadabra call site that settles it. It runs before the signature
|
|
691
|
+
// (which would otherwise age against its 300 s window) and before the timer
|
|
692
|
+
// (so the sleep is not charged to `timeoutMs`).
|
|
693
|
+
await this.jitter();
|
|
694
|
+
|
|
695
|
+
// Signed BEFORE the timer starts and before the try: see `partnerHeaders`.
|
|
696
|
+
const signed = await this.partnerHeaders(path);
|
|
697
|
+
|
|
698
|
+
const controller = new AbortController();
|
|
699
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
700
|
+
try {
|
|
701
|
+
return await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
702
|
+
method: 'GET', // never HEAD: every route but /openapi.json answers 405 to it
|
|
703
|
+
headers: { Accept: 'application/json', 'User-Agent': this.ua, ...signed, ...headers },
|
|
704
|
+
signal: controller.signal,
|
|
705
|
+
});
|
|
706
|
+
} catch (error) {
|
|
707
|
+
// An AbortError here is ours (the timer), not the caller's: this
|
|
708
|
+
// controller is created in this function and handed to nobody.
|
|
709
|
+
const name = (error as { name?: string } | null)?.name;
|
|
710
|
+
if (name === 'AbortError' || name === 'TimeoutError') {
|
|
711
|
+
throw new DescribeTimeout(`GET ${path} timed out after ${this.timeoutMs} ms`, error);
|
|
712
|
+
}
|
|
713
|
+
throw new DescribeUnreachable(`GET ${path} unreachable: ${String(error)}`, error);
|
|
714
|
+
} finally {
|
|
715
|
+
clearTimeout(timer);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
private async readJson(response: Response, path: string): Promise<unknown> {
|
|
720
|
+
try {
|
|
721
|
+
return await response.json();
|
|
722
|
+
} catch (error) {
|
|
723
|
+
throw new DescribeUnparseable(`GET ${path} body is not JSON`, error);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** A free route: any non-2xx is a typed HTTP error. */
|
|
728
|
+
private async getJson(path: string): Promise<unknown> {
|
|
729
|
+
const response = await this.request(path);
|
|
730
|
+
if (response.status === 404) {
|
|
731
|
+
throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
|
|
732
|
+
}
|
|
733
|
+
if (!response.ok) {
|
|
734
|
+
throw new DescribeHTTPError(response.status, `GET ${path} -> HTTP ${response.status}`);
|
|
735
|
+
}
|
|
736
|
+
return this.readJson(response, path);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* A metered route: ask free, read the challenge, verify WHO we are about to
|
|
741
|
+
* pay, pay through the injected payer, replay the identical request.
|
|
742
|
+
*
|
|
743
|
+
* The order matters and the third step is the one people skip. The published
|
|
744
|
+
* guide says it in the imperative — *"verify who you are about to pay — do
|
|
745
|
+
* this every time"* — because the challenge arrives over the same network
|
|
746
|
+
* that could be lying to you, and it names its own recipient.
|
|
747
|
+
*
|
|
748
|
+
* There is one line in this function that changes what a failure MEANS, and
|
|
749
|
+
* it is marked: everything above `payer.pay()` returning is a failure that
|
|
750
|
+
* cost nothing, everything below it may have cost real USDC. Failures below
|
|
751
|
+
* it are stamped with a `PaymentAttempt` so the caller does not have to infer
|
|
752
|
+
* which side of that line they landed on. Nothing above it is stamped, and
|
|
753
|
+
* that asymmetry IS the signal — see `errors.ts::PaymentAttempt`.
|
|
754
|
+
*/
|
|
755
|
+
private async getPaidJson(
|
|
756
|
+
path: string,
|
|
757
|
+
): Promise<{ body: unknown; payment: PaymentEvidence | null; servedReceipt: string | null }> {
|
|
758
|
+
const first = await this.request(path);
|
|
759
|
+
|
|
760
|
+
if (first.ok) {
|
|
761
|
+
// Free-tier or already-settled. No charge, so no evidence to report.
|
|
762
|
+
return { body: await this.readJson(first, path), payment: null, servedReceipt: null };
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (first.status === 404) {
|
|
766
|
+
// Absence, and free: nothing was paid to learn it. The metered route is
|
|
767
|
+
// the one where a 404 is most likely (an agent id that does not exist),
|
|
768
|
+
// and charging for it would be charging for "there is nothing here".
|
|
769
|
+
throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
if (first.status !== 402) {
|
|
773
|
+
throw new DescribeHTTPError(first.status, `GET ${path} -> HTTP ${first.status}`);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const challenge = await this.readChallenge(first, path);
|
|
777
|
+
|
|
778
|
+
// ── THE PARTNER RAIL FAILED, AND FAILING LOUDLY IS THE FEATURE ──────────
|
|
779
|
+
// We signed this request (every request is signed in partner mode) and the
|
|
780
|
+
// route charged anyway, so the gate did not exempt us. Falling through to
|
|
781
|
+
// `payer.pay()` from here is the silent downgrade this whole rail exists to
|
|
782
|
+
// prevent: identical answers, identical latency, USDC leaving a wallet that
|
|
783
|
+
// budgeted none. Checked BEFORE the missing-payer branch because "your free
|
|
784
|
+
// rail is down" is the more useful of the two messages when both are true.
|
|
785
|
+
if (this.partner && !this.partnerFallsBackToPaying) {
|
|
786
|
+
throw new DescribePartnerRejected(path, this.partner.address, challenge);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
if (!this.payer) {
|
|
790
|
+
throw new DescribePaymentRequired(
|
|
791
|
+
`GET ${path} is metered (${challenge.amount ?? '?'} ${challenge.token ?? 'USDC'}) ` +
|
|
792
|
+
'and no `payer` is configured. Read `error.challenge` for the terms, or use the ' +
|
|
793
|
+
'free route: GET /wallets/{wallet}/chains.',
|
|
794
|
+
challenge,
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
this.assertPayableTo(challenge);
|
|
799
|
+
|
|
800
|
+
// Nothing above this line has spent anything: the payer may still refuse,
|
|
801
|
+
// and a signature that never leaves the payer moves no money — the seller
|
|
802
|
+
// is what settles it. A throw from `pay()` is the caller's own payer
|
|
803
|
+
// talking, so it is not annotated and not translated.
|
|
804
|
+
const header = await this.payer.pay(challenge);
|
|
805
|
+
|
|
806
|
+
// ─────────── BELOW THIS LINE A SIGNED ENVELOPE IS IN FLIGHT ───────────
|
|
807
|
+
const terms = {
|
|
808
|
+
amount: typeof challenge.amount === 'string' ? challenge.amount : undefined,
|
|
809
|
+
token: typeof challenge.token === 'string' ? challenge.token : undefined,
|
|
810
|
+
payTo: typeof challenge.recipient === 'string' ? challenge.recipient : undefined,
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
let second: Response;
|
|
814
|
+
try {
|
|
815
|
+
second = await this.request(path, { 'X-PAYMENT': header });
|
|
816
|
+
} catch (error) {
|
|
817
|
+
// No answer at all — timeout or dead socket. `fetch` rejects identically
|
|
818
|
+
// whether the request bytes were written or not, so this is exactly the
|
|
819
|
+
// case that CANNOT be narrowed: `unknown`, said out loud.
|
|
820
|
+
throw attachPayment(error, { settlement: 'unknown', receipt: null, reused: null, ...terms });
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
const receipt = second.headers.get('X-Payment-Receipt');
|
|
824
|
+
const reused = second.headers.get('X-Payment-Reused');
|
|
825
|
+
const attempt: PaymentAttempt = {
|
|
826
|
+
// A receipt is the settlement transaction hash, put there by the seller:
|
|
827
|
+
// proof, not inference. Its absence proves nothing — an unhandled 500 is
|
|
828
|
+
// rendered above the paywall middleware and never gets the header.
|
|
829
|
+
//
|
|
830
|
+
// ⚠️ Since 2026-08-30 the header must also LOOK like a settlement id (a
|
|
831
|
+
// hash, or the `pending` the OpenAPI declares) before it may be called
|
|
832
|
+
// proof. `'settled'` means *we hold the hash*, and a string that is not
|
|
833
|
+
// one is not one. The value is still carried in `receipt` — on this path
|
|
834
|
+
// it is forensic evidence, not a typed field — and `'unknown'` is the
|
|
835
|
+
// honest verdict: ask the chain.
|
|
836
|
+
settlement: receipt !== null && looksLikeSettlementReceipt(receipt) ? 'settled' : 'unknown',
|
|
837
|
+
receipt,
|
|
838
|
+
reused: reused === null ? null : reused.toLowerCase() === 'true',
|
|
839
|
+
status: second.status,
|
|
840
|
+
...terms,
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
if (!second.ok) {
|
|
844
|
+
// 🔴 Money may already be gone here: the authorization was signed and the
|
|
845
|
+
// paywall settles BEFORE running the query. The status is preserved so a
|
|
846
|
+
// caller can tell "they refused the payment" (4xx) from "we paid and
|
|
847
|
+
// their query blew up" (5xx) — different conversations to have with them.
|
|
848
|
+
throw attachPayment(
|
|
849
|
+
new DescribeHTTPError(
|
|
850
|
+
second.status,
|
|
851
|
+
`GET ${path} -> HTTP ${second.status} AFTER paying (settlement: ${attempt.settlement}` +
|
|
852
|
+
`${receipt ? `, receipt ${receipt}` : ''}). Read \`error.payment\` before retrying: ` +
|
|
853
|
+
'the same receipt unlocks only this byte-identical resource.',
|
|
854
|
+
),
|
|
855
|
+
attempt,
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
let body: unknown;
|
|
860
|
+
try {
|
|
861
|
+
body = await this.readJson(second, path);
|
|
862
|
+
} catch (error) {
|
|
863
|
+
// The worst of the set and the easiest to forget: a 200 whose body is
|
|
864
|
+
// garbage. It settled — the receipt is right there — and the caller got
|
|
865
|
+
// nothing for it. Swallowing THIS was the old behaviour.
|
|
866
|
+
throw attachPayment(error, attempt);
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// The receipt is a hash too, and it is the one hash the caller is most
|
|
870
|
+
// likely to carry somewhere — to an explorer, to a support ticket, to a
|
|
871
|
+
// reconciliation. So it gets the same shape check as every other hash field
|
|
872
|
+
// (KarmaKadabra, 2026-08-30), with its own predicate: `pending` is a value
|
|
873
|
+
// the seller's OpenAPI declares legitimate, and calling it garbage would
|
|
874
|
+
// fire an alarm on the happy path of every freshly settled payment.
|
|
875
|
+
//
|
|
876
|
+
// 🔴 Only the SUCCESS path nulls a malformed receipt. On the failure path
|
|
877
|
+
// (`attempt`, above) the served string is kept verbatim, because there it is
|
|
878
|
+
// forensic evidence rather than a typed field — what changes there is that
|
|
879
|
+
// `settlement` may not claim `'settled'` on the strength of a string that is
|
|
880
|
+
// not a hash. `'settled'` means *we hold the hash*, and we do not.
|
|
881
|
+
const receiptOk = receipt !== null && looksLikeSettlementReceipt(receipt);
|
|
882
|
+
return {
|
|
883
|
+
body,
|
|
884
|
+
payment: {
|
|
885
|
+
receipt: receiptOk ? receipt : null,
|
|
886
|
+
reused: (reused ?? '').toLowerCase() === 'true',
|
|
887
|
+
malformedHashes: receipt !== null && !receiptOk ? ['receipt'] : [],
|
|
888
|
+
},
|
|
889
|
+
servedReceipt: receipt,
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Read the 402 challenge from wherever it is.
|
|
895
|
+
*
|
|
896
|
+
* The header FIRST, then the body — and that order is measured, not
|
|
897
|
+
* defensive: of 40 live x402 resources probed on 2026-08-20, 36 of 36 that
|
|
898
|
+
* answered 402 carried the challenge in the header and none in the body
|
|
899
|
+
* (`uvd-x402-sdk-typescript/src/utils/x402.ts`). describe.net serves BOTH
|
|
900
|
+
* (verified 2026-08-30: `Payment-Required` base64 header AND a JSON body), so
|
|
901
|
+
* either path works here — the order is for the ecosystem, not for us.
|
|
902
|
+
*/
|
|
903
|
+
private async readChallenge(response: Response, path: string): Promise<X402Challenge> {
|
|
904
|
+
const raw = response.headers.get('Payment-Required') ?? response.headers.get('X-Payment-Required');
|
|
905
|
+
if (raw) {
|
|
906
|
+
const trimmed = raw.trim();
|
|
907
|
+
for (const decode of [() => atob(trimmed), () => trimmed]) {
|
|
908
|
+
try {
|
|
909
|
+
const parsed = JSON.parse(decode());
|
|
910
|
+
if (parsed && typeof parsed === 'object') return parsed as X402Challenge;
|
|
911
|
+
} catch {
|
|
912
|
+
// not this encoding; try the next
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const body = await this.readJson(response, path);
|
|
917
|
+
if (body && typeof body === 'object') return body as X402Challenge;
|
|
918
|
+
throw new DescribeUnparseable(`GET ${path} answered 402 with no readable challenge`);
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* `DO_NOT_PAY` unless every recipient in the challenge is the pinned
|
|
923
|
+
* treasury.
|
|
924
|
+
*
|
|
925
|
+
* Checks the top-level `recipient` AND every `accepts[].payTo`, because a
|
|
926
|
+
* challenge that names the right treasury up top and a stranger in one of six
|
|
927
|
+
* `accepts` entries is exactly the shape an attack would take: the caller's
|
|
928
|
+
* chain selection decides which one gets paid. Case-insensitive, since EVM
|
|
929
|
+
* addresses travel in mixed checksum case (the live challenge serves
|
|
930
|
+
* `0xe4dc963c56979E0260fc146b87eE24F18220e545` while the path parameter is
|
|
931
|
+
* lowercase).
|
|
932
|
+
*/
|
|
933
|
+
private assertPayableTo(challenge: X402Challenge): void {
|
|
934
|
+
const expected = this.expectedPayTo.toLowerCase();
|
|
935
|
+
const offered: Array<string | undefined> = [
|
|
936
|
+
typeof challenge.recipient === 'string' ? challenge.recipient : undefined,
|
|
937
|
+
...Object.values(challenge.recipients ?? {}),
|
|
938
|
+
...(challenge.accepts ?? []).map((a) =>
|
|
939
|
+
typeof a?.payTo === 'string' ? (a.payTo as string) : undefined,
|
|
940
|
+
),
|
|
941
|
+
];
|
|
942
|
+
|
|
943
|
+
const seen = offered.filter((a): a is string => typeof a === 'string' && a.length > 0);
|
|
944
|
+
if (seen.length === 0) {
|
|
945
|
+
throw new DescribePaymentRefused(this.expectedPayTo, undefined, challenge);
|
|
946
|
+
}
|
|
947
|
+
for (const address of seen) {
|
|
948
|
+
if (address.toLowerCase() !== expected) {
|
|
949
|
+
throw new DescribePaymentRefused(this.expectedPayTo, address, challenge);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|