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/dist/index.js ADDED
@@ -0,0 +1,1082 @@
1
+ 'use strict';
2
+
3
+ // src/config.ts
4
+ var DEFAULT_BASE_URL = "https://api.describe.net";
5
+ var DEFAULT_SITE_URL = "https://describe.net";
6
+ var DEFAULT_TIMEOUT_MS = 3e4;
7
+ var DEFAULT_JITTER_MS = 400;
8
+ var TREASURY_EVM = "0xe4dc963c56979E0260fc146b87eE24F18220e545";
9
+ var PARTNER_CHAIN_ID = 8453;
10
+ var PARTNER_KEY_ENV = "DESCRIBE_PARTNER_PRIVATE_KEY";
11
+ var SDK_VERSION = "0.1.0";
12
+ var SDK_NAME = "uvd-describe-sdk-ts";
13
+ function userAgent(product) {
14
+ const base = `${SDK_NAME}/${SDK_VERSION}`;
15
+ const trimmed = (product ?? "").trim();
16
+ return trimmed ? `${base} (+${trimmed})` : base;
17
+ }
18
+
19
+ // src/recovery.ts
20
+ var RECOVERY = Object.freeze({
21
+ /**
22
+ * 🔴 **The honest empty, and it is a measured decision — do not fill it in.**
23
+ *
24
+ * A timeout has exactly two levers. The first is retrying, which `transient:
25
+ * true` already announces and which a recovery may not repeat. The second is
26
+ * the client timeout, and the numbers in `config.ts::DEFAULT_TIMEOUT_MS` say
27
+ * raising it past the default buys nothing that can ever arrive: the
28
+ * provider's API Gateway integration ceiling is **29 s** and the default here
29
+ * is 30 000 ms. Telling a caller to raise it would be advice that provably
30
+ * does not work — the exact failure this file's own rule forbids.
31
+ *
32
+ * (The opposite mistake — a timeout set BELOW the 15,2 s cold start, which
33
+ * turned a cold index into a fake outage for Execution Market once — is a
34
+ * configuration fact and already lives, once, in `config.ts`. It is not
35
+ * re-typed here.)
36
+ *
37
+ * What separates this from its neighbour `http_5xx`, which DOES have a
38
+ * recovery: a 5xx is evidence that the service is alive and one query is not,
39
+ * so another route is worth trying. A timeout is no evidence at all.
40
+ */
41
+ timeout: null,
42
+ http_5xx: "They answered, so the process is alive and one query is not \u2014 which makes a different door worth more than the same one again. `GET /wallets/{wallet}/chains` is free and serves the coarse version of the same question (which ERC-8004 identities the wallet has, and the score, review count and distinct raters of each) through another query path. It costs nothing to find out; if the whole index is down it fails too, and on the free routes that arrives as a null rather than as this.",
43
+ http_4xx: "Fix the request before repeating it: a 4xx is your input, not their outage. A 422 is never absence \u2014 an unregistered wallet answers 200 with nulls, so `not_an_address` means the string is not an address at all (a Solana base58 wallet is case-sensitive and this client sends it verbatim), and `GET /leaderboard` answers 422 to ANY query parameter because paging moved to the metered `/leaderboard/page`. To turn a loose id into a question that exists, ask the free `GET /search/{query}` first.",
44
+ rate_limited: "Not your request: describe.net rate-limits the whole ecosystem out of one bucket with no per-partner share, so a 429 is usually somebody else spiking. Retrying tighter makes it worse \u2014 spread the fleet instead (this client already sleeps a random jitter before every request; widening it is the lever) and read the `RateLimit-Policy` response header for the live budget rather than any number written in a document. The cached free routes (`GET /health`, `/pricing`, `/leaderboard`, `/stats/*`) are served from CloudFront and a hit does not spend the budget at all.",
45
+ not_found: "Nothing failed and nothing was charged: the index is saying there is nothing there. The one case worth acting on is an agent id, because an id alone does not name a row \u2014 resolve the pair for free with `GET /search/{query}` (measured by the service on 2026-08-23: 26.736 of 62.814 ids live on two or more chains, and in 100 % of those the owning wallet is a different one on each). If EVERY route 404s, the base URL is pointing somewhere else.",
46
+ unreachable: "The request never reached describe.net: nothing was asked, nothing was signed, nothing was charged. This one is on your side of the socket \u2014 DNS, egress or proxy, TLS interception, a browser CORS block, or a base URL whose host does not exist \u2014 and it is the thing to check before blaming the index, which never saw the request.",
47
+ unparseable: "Ask WHAT answered rather than asking again: an HTML error page from a proxy, a captive portal or a gateway arrives exactly like this and is not the index talking. Retrying is measured to buy nothing (MeshRelay excludes this from its retry set on purpose). If the body really did come from describe.net, the door that changes the answer is another one: `GET /wallets/{wallet}/chains` is free and serves the coarse version of the same question.",
48
+ partial_index: "Read the coverage before reading the absence as a verdict: a chain the index does not scan produces no rows, and that looks identical to an agent nobody rated. `GET /chains` (free) lists what is indexed and `GET /health` (free) carries the per-chain totals and how current each one is. If the chain you write to is missing there, no re-reading of this answer will fix it \u2014 that is a question for whoever runs the index.",
49
+ payment_required: "Nothing was charged: asking the price is free, and asking first is the intended move. Three doors out. (1) Wire a payer \u2014 this SDK ships the x402 adapter behind its own subpath, so a free-only consumer installs nothing. (2) Enter the partner rail with a wallet on describe.net's allowlist and the metered routes stop charging. (3) Answer the cheaper question for free \u2014 the challenge names it itself: `free_preview.endpoint` is the free route about THIS subject (a wallet lands on `GET /wallets/{wallet}/chains`) and `see_also` lists every other free door. If there is nothing there, there is nothing to buy.",
50
+ payment_refused: "Do NOT retry, and do NOT widen the expected payee to make this pass: the challenge that named a stranger arrived over the same network that could be lying to you, so it cannot be the evidence that clears itself. Verify out of band \u2014 describe.net publishes the treasury in its OpenAPI (`GET /openapi.json`, free, where `payTo` must equal that address) and on its own site. If a rotation is real, upgrade this SDK or set the expected payee yourself once you have confirmed the new address through a channel that is not this response.",
51
+ malformed_hash: "Nothing to retry: the same request serves the same bad field, and nothing else in the answer was touched. Read the mark rather than the `null` \u2014 the object that lost the field carries a malformed-hash list naming it, the notice carries the field's wire path, and the value as served is still in `raw`, which is what belongs in the ticket to whoever runs the index. A `null` with an EMPTY list is the other thing entirely: the field has not been written yet, which is documented and normal.",
52
+ partner_unsigned: "Fix the signer, not the request \u2014 and do not \"fix\" it by dropping partner mode, because an anonymous client is a client that PAYS. The measured common cause is a trailing newline: `KEY=$(cat file)` keeps it, which is why the key is shape-checked before it can reach the signer. The environment variable is `DESCRIBE_PARTNER_PRIVATE_KEY`. The signer's own error travels as this exception's cause and is never copied into any message here \u2014 read it there.",
53
+ partner_rejected: "Fix the rail; do not reach for the payer by reflex. In the order these actually happen: the wallet is not on describe.net's allowlist yet (send them the signing address this error carries \u2014 it is public, which is the point of an allowlist of addresses instead of a token); the base URL is not `https://api.describe.net`, so the signed authority cannot match (a raw execute-api host does this); the keyid chain is not 8453; or the clock drifted (more than 30 s ahead, or a signature older than 300 s). The attached challenge says what it would have cost, and paying anyway is an explicit opt-in, never a fallback."
54
+ });
55
+ function recoveryFor(kind, status) {
56
+ if (kind === "http_4xx" && status === 429) return RECOVERY.rate_limited;
57
+ return RECOVERY[kind];
58
+ }
59
+
60
+ // src/errors.ts
61
+ var DescribeError = class extends Error {
62
+ kind;
63
+ /** Would retrying help? Drives backoff, never `failOpen`. */
64
+ transient;
65
+ /** Is this describe.net's fault? Drives `failOpen`, never retry. */
66
+ serviceFault;
67
+ /** Present when a status was actually received. */
68
+ status;
69
+ /**
70
+ * What to do INSTEAD, in one sentence — or `null` when there honestly is
71
+ * nothing beyond the retry `transient` already announces (`timeout` is the
72
+ * one, and `recovery.ts` says why at the entry).
73
+ *
74
+ * 🔴 **Branch on `kind`, read this.** It is prose meant for a human or an
75
+ * agent, it is free to be re-worded, and matching on it is the mistake the
76
+ * caveat codes exist to prevent one level up.
77
+ *
78
+ * 🔴 It is always one of the frozen literals in `recovery.ts` — never built
79
+ * from a message, a URL or a `cause`. That is the redaction guard: a
80
+ * transport exception can carry an endpoint with an API key in it, and this
81
+ * is the string most likely to end up pasted into a ticket.
82
+ */
83
+ recovery;
84
+ /**
85
+ * Set **only** when a signed envelope was already in flight. Not readonly for
86
+ * one reason: the failure is built deep in the transport, which knows nothing
87
+ * about payment, and `attachPayment()` stamps it on the way out. Treat it as
88
+ * readonly — nothing in this package writes it twice.
89
+ */
90
+ payment;
91
+ constructor(kind, message, opts = {
92
+ transient: false,
93
+ serviceFault: false
94
+ }) {
95
+ super(message, { cause: opts.cause });
96
+ this.name = "DescribeError";
97
+ this.kind = kind;
98
+ this.transient = opts.transient;
99
+ this.serviceFault = opts.serviceFault;
100
+ this.status = opts.status;
101
+ this.recovery = recoveryFor(kind, opts.status);
102
+ }
103
+ };
104
+ var DescribeTimeout = class extends DescribeError {
105
+ constructor(message, cause) {
106
+ super("timeout", message, { transient: true, serviceFault: true, cause });
107
+ this.name = "DescribeTimeout";
108
+ }
109
+ };
110
+ var DescribeUnreachable = class extends DescribeError {
111
+ constructor(message, cause) {
112
+ super("unreachable", message, { transient: true, serviceFault: true, cause });
113
+ this.name = "DescribeUnreachable";
114
+ }
115
+ };
116
+ var DescribeUnparseable = class extends DescribeError {
117
+ constructor(message, cause) {
118
+ super("unparseable", message, { transient: false, serviceFault: true, cause });
119
+ this.name = "DescribeUnparseable";
120
+ }
121
+ };
122
+ var DescribeMalformedHash = class extends DescribeError {
123
+ /** Qualified paths of the fields that arrived malformed, in order. */
124
+ fields;
125
+ constructor(message, fields) {
126
+ super("malformed_hash", message, { transient: false, serviceFault: false });
127
+ this.name = "DescribeMalformedHash";
128
+ this.fields = [...fields];
129
+ }
130
+ };
131
+ var DescribeNotFound = class extends DescribeError {
132
+ constructor(message) {
133
+ super("not_found", message, { transient: false, serviceFault: false, status: 404 });
134
+ this.name = "DescribeNotFound";
135
+ }
136
+ };
137
+ var DescribeHTTPError = class extends DescribeError {
138
+ constructor(status, message) {
139
+ const server = status >= 500;
140
+ super(server ? "http_5xx" : "http_4xx", message, {
141
+ // 429 is the one 4xx worth retrying: the 20 rps ceiling is shared with
142
+ // every other UVD consumer, so it says "someone else is loud right now",
143
+ // not "your request is wrong".
144
+ transient: server || status === 429,
145
+ // A 4xx is the caller's fault and must NOT vanish into failOpen — except
146
+ // 429, which is the shared limit and reads exactly like a brief outage.
147
+ serviceFault: server || status === 429,
148
+ status
149
+ });
150
+ this.name = "DescribeHTTPError";
151
+ }
152
+ };
153
+ var DescribePaymentRequired = class extends DescribeError {
154
+ challenge;
155
+ constructor(message, challenge) {
156
+ super("payment_required", message, { transient: false, serviceFault: false, status: 402 });
157
+ this.name = "DescribePaymentRequired";
158
+ this.challenge = challenge;
159
+ }
160
+ };
161
+ var DescribePaymentRefused = class extends DescribeError {
162
+ challenge;
163
+ expected;
164
+ offered;
165
+ constructor(expected, offered, challenge) {
166
+ super(
167
+ "payment_refused",
168
+ `DO_NOT_PAY: the 402 challenge asks to pay ${offered ?? "(no recipient)"}, not the pinned treasury ${expected}. Nothing was signed.`,
169
+ { transient: false, serviceFault: false, status: 402 }
170
+ );
171
+ this.name = "DescribePaymentRefused";
172
+ this.challenge = challenge;
173
+ this.expected = expected;
174
+ this.offered = offered;
175
+ }
176
+ };
177
+ var DescribePartnerUnsigned = class extends DescribeError {
178
+ /** The signing address, when the signer published one. Public by design. */
179
+ address;
180
+ constructor(path, address, cause) {
181
+ super(
182
+ "partner_unsigned",
183
+ `Partner mode is configured but signing GET ${path} failed${address ? ` for ${address}` : ""}. This is a CALLER configuration failure, and it is raised rather than downgraded on purpose: without a signature this client is an anonymous client, and an anonymous client PAYS. Read \`error.cause\` for the signer's own error.`,
184
+ { transient: false, serviceFault: false, cause }
185
+ );
186
+ this.name = "DescribePartnerUnsigned";
187
+ this.address = address;
188
+ }
189
+ };
190
+ var DescribePartnerRejected = class extends DescribeError {
191
+ challenge;
192
+ /** The address we signed with. Public by design — the allowlist is public. */
193
+ address;
194
+ constructor(path, address, challenge) {
195
+ super(
196
+ "partner_rejected",
197
+ `GET ${path} answered 402 even though this client signed it as a partner${address ? ` with ${address}` : ""}. The free rail is NOT active: the address may not be in describe.net's allowlist, the signed @authority may not be api.describe.net (a custom baseUrl does that), the keyid chain may not be 8453, or the clock may be off. NOTHING WAS PAID \u2014 this throw is what stops a partner from silently spending USDC. Read \`error.challenge\` for the price, or set \`partnerFallsBackToPaying: true\` to pay on purpose.`,
198
+ { transient: false, serviceFault: false, status: 402 }
199
+ );
200
+ this.name = "DescribePartnerRejected";
201
+ this.challenge = challenge;
202
+ this.address = address;
203
+ }
204
+ };
205
+ function failOpenCovers(error) {
206
+ return error instanceof DescribeError && error.serviceFault;
207
+ }
208
+ function failedAfterPaying(error) {
209
+ return error instanceof DescribeError && error.payment !== void 0;
210
+ }
211
+ function attachPayment(error, attempt) {
212
+ if (error instanceof DescribeError) error.payment = attempt;
213
+ return error;
214
+ }
215
+
216
+ // src/hashes.ts
217
+ var EVM_HASH = /^0x[0-9a-fA-F]{64}$/;
218
+ var BARE_DIGEST = /^[0-9a-fA-F]{64}$/;
219
+ var BASE58_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{86,88}$/;
220
+ var SETTLEMENT_PENDING = "pending";
221
+ function looksLikeOnchainId(value) {
222
+ return EVM_HASH.test(value) || BASE58_SIGNATURE.test(value) || BARE_DIGEST.test(value);
223
+ }
224
+ function looksLikeSettlementReceipt(value) {
225
+ return value === SETTLEMENT_PENDING || looksLikeOnchainId(value);
226
+ }
227
+ function hashField(row, key, malformed, ok = looksLikeOnchainId) {
228
+ const value = row[key];
229
+ if (value === null || value === void 0) return null;
230
+ if (typeof value === "string" && ok(value)) return value;
231
+ malformed.push(key);
232
+ return null;
233
+ }
234
+ function malformedHashReport(result) {
235
+ if (!result) return [];
236
+ const fields = [];
237
+ (result.ratings ?? []).forEach((rating, i) => {
238
+ for (const name of rating.malformedHashes ?? []) fields.push(`ratings[${i}].${name}`);
239
+ });
240
+ for (const attr of ["snapshot", "payment"]) {
241
+ const part = result[attr];
242
+ if (part) for (const name of part.malformedHashes ?? []) fields.push(`${attr}.${name}`);
243
+ }
244
+ return fields;
245
+ }
246
+
247
+ // src/jitter.ts
248
+ function jitterDelayMs(maxMs, random = Math.random) {
249
+ if (!Number.isFinite(maxMs) || maxMs <= 0) return 0;
250
+ const draw = random();
251
+ if (!Number.isFinite(draw) || draw < 0) return 0;
252
+ return Math.min(draw, 1) * maxMs;
253
+ }
254
+ function sleep(ms) {
255
+ return new Promise((resolve) => setTimeout(resolve, ms));
256
+ }
257
+
258
+ // src/caveats.ts
259
+ var CAVEAT_CODES = [
260
+ /** No score to qualify: there is no eligible rating at all. */
261
+ "no-score",
262
+ /** The concentration signal itself is degraded and should not be leaned on. */
263
+ "concentration-degraded",
264
+ /** Exactly one distinct counterparty is behind this score. */
265
+ "single-rater",
266
+ /** Below the evidence bar (`reading_policy.min_raters`, 3 as of 2026-08-30). */
267
+ "few-raters",
268
+ /** One client wrote more than `reading_policy.top_share` of the ratings. */
269
+ "top-client-share",
270
+ /** Ratings-per-rater above `reading_policy.campaign_per_rater` — looks like a campaign. */
271
+ "campaign-per-rater",
272
+ /** The subject rated itself. */
273
+ "self-rated",
274
+ /**
275
+ * The subject is a burn address: nobody controls it, anyone may rate it, and
276
+ * nobody can answer for its reputation. The ratings are real on-chain facts
277
+ * — which is why they are still served — but the subject is not an identity.
278
+ */
279
+ "burn-address"
280
+ ];
281
+ var CAVEAT_SCOPE_FREE = "public-data-subset";
282
+ var CAVEAT_SCOPE_METERED = "full";
283
+ function isKnownCaveatCode(code) {
284
+ return CAVEAT_CODES.includes(code);
285
+ }
286
+ function hasCaveat(subject, code) {
287
+ return (subject?.caveats ?? []).some((c) => c.code === code);
288
+ }
289
+
290
+ // src/parse.ts
291
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
292
+ function optNumber(v) {
293
+ if (v === null || v === void 0) return null;
294
+ const n = Number(v);
295
+ return Number.isFinite(n) ? n : null;
296
+ }
297
+ function num(v, fallback = 0) {
298
+ const n = Number(v);
299
+ return Number.isFinite(n) ? n : fallback;
300
+ }
301
+ function optString(v) {
302
+ return typeof v === "string" ? v : null;
303
+ }
304
+ function strArray(v) {
305
+ return Array.isArray(v) ? v.map(String) : null;
306
+ }
307
+ function parseCaveats(v) {
308
+ if (!Array.isArray(v)) return [];
309
+ const out = [];
310
+ for (const entry of v) {
311
+ if (isObj(entry) && typeof entry.code === "string") {
312
+ out.push({ code: entry.code, text: typeof entry.text === "string" ? entry.text : "" });
313
+ }
314
+ }
315
+ return out;
316
+ }
317
+ function parseFacets(v) {
318
+ if (!isObj(v)) return {};
319
+ const out = {};
320
+ for (const [key, raw] of Object.entries(v)) {
321
+ if (!isObj(raw)) continue;
322
+ out[key] = {
323
+ score: optNumber(raw.score),
324
+ count: num(raw.count),
325
+ distinctRaters: num(raw.distinct_raters),
326
+ revokedCount: num(raw.revoked_count),
327
+ outOfDomainCount: num(raw.out_of_domain_count),
328
+ selfRatedCount: num(raw.self_rated_count),
329
+ direction: optString(raw.direction),
330
+ directionCategory: optString(raw.direction_category),
331
+ directionMeaning: optString(raw.direction_meaning)
332
+ };
333
+ }
334
+ return out;
335
+ }
336
+ function parseSelfRated(v) {
337
+ if (!isObj(v)) return null;
338
+ return { count: num(v.count), score: optNumber(v.score), gap: optNumber(v.gap) };
339
+ }
340
+ function parseConcentration(v) {
341
+ if (!isObj(v)) return null;
342
+ return {
343
+ distinctRaters: num(v.distinct_raters),
344
+ topClientShare: optNumber(v.top_client_share),
345
+ topClient: optString(v.top_client)
346
+ };
347
+ }
348
+ function parseConfidence(v) {
349
+ if (!isObj(v)) return null;
350
+ const iv = v.interval;
351
+ return {
352
+ band: String(v.band ?? ""),
353
+ distinctRaters: num(v.distinct_raters),
354
+ interval: isObj(iv) ? { lower: num(iv.lower), upper: num(iv.upper) } : null,
355
+ thresholds: isObj(v.thresholds) ? v.thresholds : {},
356
+ advice: String(v.advice ?? ""),
357
+ confidencePolicy: String(v.confidence_policy ?? "")
358
+ };
359
+ }
360
+ function parseActivity(v) {
361
+ if (!isObj(v)) return null;
362
+ return { firstRatingAt: optString(v.first_rating_at), lastRatingAt: optString(v.last_rating_at) };
363
+ }
364
+ function parseSnapshot(v) {
365
+ if (!isObj(v)) return null;
366
+ const malformed = [];
367
+ return {
368
+ id: num(v.id),
369
+ // A bare sha256 hexdigest, no `0x` (`aggregate.py:1920`). This one is worth
370
+ // validating precisely because it is the citable field: two snapshots with
371
+ // the same digest are supposed to say the same thing, and a comparison
372
+ // between two garbage strings can agree by accident.
373
+ inputsDigest: hashField(v, "inputs_digest", malformed),
374
+ policyVersion: String(v.policy_version ?? ""),
375
+ computedAt: String(v.computed_at ?? ""),
376
+ malformedHashes: malformed
377
+ };
378
+ }
379
+ function parseOwnership(v) {
380
+ if (!isObj(v)) return null;
381
+ return {
382
+ ownerUpdatedBlock: num(v.owner_updated_block),
383
+ identityTransferred: typeof v.identity_transferred === "boolean" ? v.identity_transferred : null,
384
+ inheritedReviewCount: num(v.inherited_review_count),
385
+ inheritedScore: optNumber(v.inherited_score),
386
+ currentEraReviewCount: num(v.current_era_review_count),
387
+ currentEraScore: optNumber(v.current_era_score),
388
+ undeterminedReviewCount: num(v.undetermined_review_count),
389
+ inheritedShare: optNumber(v.inherited_share)
390
+ };
391
+ }
392
+ function parseRatings(v) {
393
+ if (!Array.isArray(v)) return [];
394
+ return v.filter(isObj).map((r) => {
395
+ const malformed = [];
396
+ return {
397
+ client: String(r.client ?? ""),
398
+ feedbackIndex: num(r.feedback_index),
399
+ value: num(r.value),
400
+ valueDecimals: num(r.value_decimals),
401
+ normalizedValue: optNumber(r.normalized_value),
402
+ tag1: optString(r.tag1),
403
+ tag2: optString(r.tag2),
404
+ isRevoked: r.is_revoked === true,
405
+ isSelf: r.is_self === true,
406
+ txHash: hashField(r, "tx_hash", malformed),
407
+ blockNumber: optNumber(r.block_number),
408
+ logIndex: optNumber(r.log_index),
409
+ feedbackUri: optString(r.feedback_uri),
410
+ issuerHost: optString(r.issuer_host),
411
+ issuer: optString(r.issuer),
412
+ issuerOrg: optString(r.issuer_org),
413
+ feedbackHash: hashField(r, "feedback_hash", malformed),
414
+ revokedTx: hashField(r, "revoked_tx", malformed),
415
+ malformedHashes: malformed
416
+ };
417
+ });
418
+ }
419
+ function parseWalletReputation(payload) {
420
+ if (!isObj(payload) || typeof payload.wallet !== "string") {
421
+ throw new DescribeUnparseable("wallet-chains response is missing its essential shape (wallet)");
422
+ }
423
+ const rows = Array.isArray(payload.chains) ? payload.chains : [];
424
+ const chains = rows.filter(isObj).map((row) => ({
425
+ network: String(row.network ?? ""),
426
+ agentCount: num(row.agent_count),
427
+ agentIds: strArray(row.agent_ids),
428
+ finalScore: optNumber(row.final_score),
429
+ totalReviews: num(row.total_reviews),
430
+ distinctRaters: num(row.distinct_raters)
431
+ }));
432
+ return {
433
+ wallet: payload.wallet,
434
+ chains,
435
+ globalScore: optNumber(payload.global_score),
436
+ distinctRaters: optNumber(payload.distinct_raters),
437
+ identityCount: num(payload.identity_count),
438
+ chainsWithIdentity: num(payload.chains_with_identity),
439
+ chainsWithReputation: num(payload.chains_with_reputation),
440
+ totalReviews: num(payload.total_reviews),
441
+ policyVersion: optString(payload.policy_version),
442
+ caveats: parseCaveats(payload.caveats),
443
+ caveatScope: CAVEAT_SCOPE_FREE,
444
+ source: optString(payload.source),
445
+ refreshedAt: optString(payload.refreshed_at),
446
+ raw: payload
447
+ };
448
+ }
449
+ function parseWalletBreakdown(payload, payment) {
450
+ if (!isObj(payload) || typeof payload.wallet !== "string") {
451
+ throw new DescribeUnparseable("wallet-breakdown response is missing its essential shape (wallet)");
452
+ }
453
+ return {
454
+ wallet: payload.wallet,
455
+ finalScore: optNumber(payload.final_score),
456
+ weightedScore: optNumber(payload.weighted_score),
457
+ raterWeightPolicy: String(payload.rater_weight_policy ?? ""),
458
+ chainCount: num(payload.chain_count),
459
+ totalReviews: num(payload.total_reviews),
460
+ perChain: isObj(payload.per_chain) ? payload.per_chain : {},
461
+ facets: parseFacets(payload.facets),
462
+ selfRated: parseSelfRated(payload.self_rated),
463
+ concentration: parseConcentration(payload.concentration),
464
+ confidence: parseConfidence(payload.confidence),
465
+ activity: parseActivity(payload.activity),
466
+ snapshot: parseSnapshot(payload.snapshot),
467
+ payment,
468
+ policyVersion: optString(payload.policy_version),
469
+ caveats: parseCaveats(payload.caveats),
470
+ caveatScope: CAVEAT_SCOPE_METERED,
471
+ source: optString(payload.source),
472
+ refreshedAt: optString(payload.refreshed_at),
473
+ raw: payload
474
+ };
475
+ }
476
+ function parseAgentReputation(payload, payment) {
477
+ if (!isObj(payload) || payload.agent_id === void 0) {
478
+ throw new DescribeUnparseable("agent response is missing its essential shape (agent_id)");
479
+ }
480
+ return {
481
+ network: String(payload.network ?? ""),
482
+ agentId: String(payload.agent_id),
483
+ currentOwner: optString(payload.current_owner),
484
+ declaredType: optString(payload.declared_type),
485
+ agentUri: optString(payload.agent_uri),
486
+ indexedIdentity: payload.indexed_identity === true,
487
+ score: optNumber(payload.score),
488
+ reviewCount: num(payload.review_count),
489
+ revokedCount: num(payload.revoked_count),
490
+ outOfDomainCount: num(payload.out_of_domain_count),
491
+ selfRated: parseSelfRated(payload.self_rated),
492
+ facets: parseFacets(payload.facets),
493
+ concentration: parseConcentration(payload.concentration),
494
+ ownership: parseOwnership(payload.ownership),
495
+ confidence: parseConfidence(payload.confidence),
496
+ ratings: parseRatings(payload.ratings),
497
+ payment,
498
+ policyVersion: optString(payload.policy_version),
499
+ caveats: parseCaveats(payload.caveats),
500
+ caveatScope: CAVEAT_SCOPE_METERED,
501
+ source: optString(payload.source),
502
+ refreshedAt: optString(payload.refreshed_at),
503
+ raw: payload
504
+ };
505
+ }
506
+ function parseLeaderboard(payload) {
507
+ if (!Array.isArray(payload)) {
508
+ throw new DescribeUnparseable("leaderboard response is not an array");
509
+ }
510
+ return payload.filter(isObj).map((row) => ({
511
+ rank: num(row.rank),
512
+ wallet: String(row.wallet ?? ""),
513
+ finalScore: optNumber(row.final_score),
514
+ shrunkScore: optNumber(row.shrunk_score),
515
+ distinctRaters: num(row.distinct_raters),
516
+ chainCount: num(row.chain_count),
517
+ totalReviews: num(row.total_reviews),
518
+ networks: Array.isArray(row.networks) ? row.networks.map(String) : [],
519
+ declaredTypes: Array.isArray(row.declared_types) ? row.declared_types.map((t) => typeof t === "string" ? t : null) : [],
520
+ raw: row
521
+ }));
522
+ }
523
+ function parseHealth(payload) {
524
+ if (!isObj(payload) || typeof payload.status !== "string") {
525
+ throw new DescribeUnparseable("health response is missing its essential shape (status)");
526
+ }
527
+ const chains = (Array.isArray(payload.chains) ? payload.chains : []).filter(isObj).map((row) => ({
528
+ network: String(row.network ?? ""),
529
+ lastScannedBlock: optNumber(row.last_scanned_block),
530
+ updatedAt: optString(row.updated_at),
531
+ nextSyncAt: optString(row.next_sync_at),
532
+ lastError: optString(row.last_error),
533
+ raw: row
534
+ }));
535
+ return {
536
+ status: payload.status,
537
+ policyVersion: String(payload.policy_version ?? ""),
538
+ orderingPolicy: String(payload.ordering_policy ?? ""),
539
+ raterWeightPolicy: String(payload.rater_weight_policy ?? ""),
540
+ confidencePolicy: String(payload.confidence_policy ?? ""),
541
+ confidenceThresholds: isObj(payload.confidence_thresholds) ? payload.confidence_thresholds : {},
542
+ readingPolicy: isObj(payload.reading_policy) ? payload.reading_policy : {},
543
+ buildSha: optString(payload.build_sha),
544
+ agents: num(payload.agents),
545
+ feedbackEntries: num(payload.feedback_entries),
546
+ indexerPeriodSeconds: optNumber(payload.indexer_period_seconds),
547
+ chains,
548
+ raw: payload
549
+ };
550
+ }
551
+
552
+ // src/client.ts
553
+ var DescribeClient = class {
554
+ baseUrl;
555
+ timeoutMs;
556
+ ua;
557
+ failOpen;
558
+ onFailure;
559
+ jitterMs;
560
+ payer;
561
+ partner;
562
+ partnerFallsBackToPaying;
563
+ expectedPayTo;
564
+ fetchImpl;
565
+ constructor(config = {}) {
566
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
567
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
568
+ this.ua = userAgent(config.product);
569
+ this.failOpen = config.failOpen ?? true;
570
+ this.onFailure = config.onFailure;
571
+ this.jitterMs = typeof config.jitterMs === "number" && Number.isFinite(config.jitterMs) && config.jitterMs >= 0 ? config.jitterMs : DEFAULT_JITTER_MS;
572
+ this.payer = config.payer;
573
+ this.partner = config.partner;
574
+ this.partnerFallsBackToPaying = config.partnerFallsBackToPaying ?? false;
575
+ this.expectedPayTo = config.expectedPayTo ?? TREASURY_EVM;
576
+ const impl = config.fetchImpl ?? globalThis.fetch;
577
+ if (typeof impl !== "function") {
578
+ throw new TypeError(
579
+ "No fetch available. Node >= 18 has one; otherwise pass `fetchImpl` in the config."
580
+ );
581
+ }
582
+ this.fetchImpl = impl;
583
+ }
584
+ // -------------------------------------------------------------------------
585
+ // Free — no dependency, no signature, no credential
586
+ // -------------------------------------------------------------------------
587
+ /**
588
+ * `GET /wallets/{wallet}/chains` — **free**. The happy path starts here.
589
+ *
590
+ * Gratis-primero is not politeness, it is the shape of the product: the 402
591
+ * challenge of the metered route says it itself — *"si ahí no hay nada, no
592
+ * hay nada que comprar"*. Ask for free whether there is anything, and only
593
+ * then buy the decomposition.
594
+ *
595
+ * `wallet` goes through VERBATIM. EVM is normalised server-side, but Solana
596
+ * base58 is case-SENSITIVE and lower-casing it here would silently ask about
597
+ * a different wallet.
598
+ *
599
+ * @returns the reputation (whose `globalScore` may be `null` — that is an
600
+ * answer), or `null` when describe.net could not be reached and `failOpen`
601
+ * is on.
602
+ */
603
+ async wallet(address) {
604
+ const path = `/wallets/${encodeURIComponent(address)}/chains`;
605
+ return this.guard(path, async () => parseWalletReputation(await this.getJson(path)));
606
+ }
607
+ /**
608
+ * `GET /leaderboard` — **free**, first page.
609
+ *
610
+ * Takes NO parameters: `?limit=2` answers 422 `leaderboard_takes_no_params`
611
+ * (verified live 2026-08-30). Paging is the metered `/leaderboard/page`.
612
+ *
613
+ * ⚠️ Ordered by `shrunkScore`, not by `finalScore`. Re-sorting client-side by
614
+ * `finalScore` undoes the shrinkage and puts a single 100-point rating above
615
+ * two hundred real ones.
616
+ */
617
+ async leaderboard() {
618
+ const path = "/leaderboard";
619
+ return this.guard(path, async () => parseLeaderboard(await this.getJson(path)));
620
+ }
621
+ /**
622
+ * `GET /health` — **free**, and the authority on this index's totals.
623
+ *
624
+ * Also the live source for `readingPolicy` and `confidenceThresholds`: the
625
+ * server publishes its own calibrable values so that no consumer re-types
626
+ * them. Read them here rather than hardcoding a threshold that will drift.
627
+ */
628
+ async health() {
629
+ const path = "/health";
630
+ return this.guard(path, async () => parseHealth(await this.getJson(path)));
631
+ }
632
+ /**
633
+ * The badge URL. **Builds a string, opens no socket, cannot fail.**
634
+ *
635
+ * `GET /badge/{wallet}.svg` is free and returns `image/svg+xml` (604 bytes,
636
+ * verified 2026-08-30). Drop it in an `<img>` and a page shows a live score
637
+ * with its distinct raters and the date of the data, with no JavaScript and
638
+ * no dependency on this package at all.
639
+ */
640
+ badgeUrl(address) {
641
+ return `${this.baseUrl}/badge/${encodeURIComponent(address)}.svg`;
642
+ }
643
+ /** Where a human reads the same wallet. On surfaces without hover, THIS is the attribution. */
644
+ profileUrl(address, siteUrl = DEFAULT_SITE_URL) {
645
+ return `${siteUrl.replace(/\/+$/, "")}/agent.html?wallet=${encodeURIComponent(address)}`;
646
+ }
647
+ // -------------------------------------------------------------------------
648
+ // Metered — a 402 is paid through uvd-x402-sdk, never by us
649
+ // -------------------------------------------------------------------------
650
+ /**
651
+ * `GET /reputation/wallet/{wallet}` — **metered, $0.01** ($0.05 with a
652
+ * citable snapshot). Who rated, how many times, how concentrated.
653
+ *
654
+ * The price above is documentation with a date on it, not a value this SDK
655
+ * uses: what gets paid is what the live challenge says. We never type a
656
+ * price into a code path.
657
+ *
658
+ * 🔴 **Not nullable, and never fail-open** — not even with `failOpen: true`.
659
+ * There is money in flight here, and a swallowed failure is a spent
660
+ * credential with no receipt. Every failure arrives as a typed throw, and one
661
+ * that happened after the envelope left carries `error.payment`
662
+ * (`failedAfterPaying()`). Note this includes a 404: it is still absence and
663
+ * still costs nothing (it is checked before the challenge is read), but with
664
+ * no `| null` left there is nowhere to degrade it to.
665
+ *
666
+ * Without a `payer`, throws `DescribePaymentRequired` with the challenge
667
+ * attached — asking is free and is the intended first move, so you can read
668
+ * the price without paying.
669
+ */
670
+ async walletBreakdown(address) {
671
+ const path = `/reputation/wallet/${encodeURIComponent(address)}`;
672
+ const { body, payment, servedReceipt } = await this.getPaidJson(path);
673
+ const result = parseWalletBreakdown(body, payment);
674
+ this.announceMalformed(path, result, servedReceipt);
675
+ return result;
676
+ }
677
+ /**
678
+ * `GET /reputation/agent/{network}/{agentId}` — **metered, $0.02**. One
679
+ * ERC-8004 identity, down to the individual ratings.
680
+ *
681
+ * 🔴 Same money rule as `walletBreakdown()`: not nullable, never fail-open,
682
+ * throws on everything including a 404 for an agent id that does not exist.
683
+ */
684
+ async agent(network, agentId) {
685
+ const path = `/reputation/agent/${encodeURIComponent(network)}/${encodeURIComponent(String(agentId))}`;
686
+ const { body, payment, servedReceipt } = await this.getPaidJson(path);
687
+ const result = parseAgentReputation(body, payment);
688
+ this.announceMalformed(path, result, servedReceipt);
689
+ return result;
690
+ }
691
+ // -------------------------------------------------------------------------
692
+ // Internals
693
+ // -------------------------------------------------------------------------
694
+ /**
695
+ * The fail-open gate — **for the free routes, and only for them**.
696
+ *
697
+ * ⚠️ Corrected 2026-08-30. The old comment here read *"every network method
698
+ * goes through exactly one of these so the rule cannot drift between
699
+ * methods"*, and the intent was right while the scope was wrong: routing the
700
+ * paid methods through it is what let a post-settlement timeout come back as
701
+ * `null`. The rule that must not drift is R5, and R5 has a term this function
702
+ * cannot see. So the paid methods do not call it — deliberately, and a test
703
+ * named `MOUNTS THE BAD STATE` goes red if anyone puts them back.
704
+ *
705
+ * Whoever adds the sixth method: free ⇒ wrap it here; metered ⇒ do not.
706
+ */
707
+ async guard(path, run) {
708
+ try {
709
+ return await run();
710
+ } catch (error) {
711
+ if (error instanceof DescribeNotFound) {
712
+ this.onFailure?.({ path, error, kind: error.kind, transient: false });
713
+ return null;
714
+ }
715
+ if (this.failOpen && failOpenCovers(error)) {
716
+ this.onFailure?.({
717
+ path,
718
+ error,
719
+ kind: error.kind,
720
+ transient: error.transient
721
+ });
722
+ return null;
723
+ }
724
+ throw error;
725
+ }
726
+ }
727
+ /**
728
+ * The pause that disperses a fleet. **Before EVERY request** — called from the
729
+ * top of `request()` and from nowhere else, so a method that makes two
730
+ * requests sleeps twice.
731
+ *
732
+ * ⚠️ **Corrected 2026-08-30, and the wrong version is left written because it
733
+ * is the intuitive one and someone will want it back.** This first sat in
734
+ * `getJson()` / `getPaidJson()`, i.e. *once per public call, before the FIRST
735
+ * request*, on the theory that the metered flow should not sleep twice. That
736
+ * is a hole: a call that fires N requests would disperse one of them and let
737
+ * the other N−1 out in a pack, which is the exact problem this contribution
738
+ * came to fix. KarmaKadabra's own call site settles it — their sleep lives
739
+ * inside the function that performs the GET (`reputation_scan.py:123`), and
740
+ * that function runs twice on their real path (`:242` for the EVM address,
741
+ * `:245` for the Solana one). Their jitter is per REQUEST, and the reason they
742
+ * wrote beside it (`:121-122`) is per-PROCESS: agents that wake together
743
+ * against a shared ceiling.
744
+ *
745
+ * The paid replay sleeps too, and that was the hardest half of the correction
746
+ * to accept. The argument for exempting it was that delaying a signed envelope
747
+ * widens the window in which a crash loses a receipt — but the challenge this
748
+ * client answers carries `maxTimeoutSeconds: 120`, so 400 ms is a third of a
749
+ * percent of the envelope's own validity, while the herd argument applies to
750
+ * the replay in full: 27 agents that get their 402 in the same second replay
751
+ * in the same second.
752
+ *
753
+ * **Before the signature, and before the clock.** `request()` calls this
754
+ * first, so an ERC-8128 signature is never left ageing against its 300 s
755
+ * window while we sleep, and the sleep is not charged to `timeoutMs`.
756
+ */
757
+ async jitter() {
758
+ const ms = jitterDelayMs(this.jitterMs);
759
+ if (ms > 0) await sleep(ms);
760
+ }
761
+ /**
762
+ * Announce a malformed hash field, if there is one — KarmaKadabra's *"el 200
763
+ * sin tx"*, reaching the caller.
764
+ *
765
+ * ⚠️ **This is the second thing `onFailure` announces, and invariant 4 is
766
+ * restated rather than broken.** It used to read *"`onFailure` fires if and
767
+ * only if a method hands back `null`"*, and that wording was a description of
768
+ * the only case that existed on 2026-08-30 at noon. The rule it was protecting
769
+ * is bigger and now reads: **`onFailure` announces everything that was
770
+ * silently swallowed — a `null` handed back instead of an answer, and a field
771
+ * dropped because it was not what it claimed to be — and nothing that reaches
772
+ * you as a throw.** A failure you are holding does not need announcing; a
773
+ * field that vanished out of a 200 does, and it is exactly as invisible as a
774
+ * silent fail-open.
775
+ *
776
+ * That is why it is not a second callback: the channel a consumer is already
777
+ * watching is where KarmaKadabra asked for this to land, and a new one would
778
+ * be a channel nobody wired. The notice is filterable in one line
779
+ * (`f.kind === 'malformed_hash'`), carries `transient: false` and
780
+ * `serviceFault: false`, and the error it carries is never thrown.
781
+ *
782
+ * 🔴 The callback is wrapped, and this call site is the reason: it fires after
783
+ * a metered read that already SETTLED. An observer that throws would destroy a
784
+ * response the caller paid for, which is the same class of bug as swallowing a
785
+ * receipt — with the sign flipped. (The `guard()` call site is deliberately
786
+ * left unwrapped: there the answer is already `null`, so a throwing observer
787
+ * costs nothing that was bought.)
788
+ */
789
+ announceMalformed(path, result, servedReceipt) {
790
+ const fields = malformedHashReport(result);
791
+ if (fields.length === 0) return;
792
+ const quoted = fields.includes("payment.receipt") && servedReceipt !== null ? ` The receipt as served was ${JSON.stringify(servedReceipt.slice(0, 120))}.` : "";
793
+ const error = new DescribeMalformedHash(
794
+ `GET ${path} served ${fields.length} field(s) that are not hashes: ${fields.join(", ")}. Each one was dropped to null; every other value as served is still in \`raw\`. Nothing was retried and nothing else in the answer was touched.${quoted}`,
795
+ fields
796
+ );
797
+ try {
798
+ this.onFailure?.({ path, error, kind: error.kind, transient: false });
799
+ } catch {
800
+ }
801
+ }
802
+ /**
803
+ * The partner headers for one request, or `{}` when there is no partner.
804
+ *
805
+ * 🔴 THIS RUNS OUTSIDE `request()`'s try/catch AND THAT IS THE WHOLE POINT.
806
+ * Inside it, a signer that threw would be caught by the transport handler and
807
+ * re-thrown as `DescribeUnreachable` — which is `serviceFault: true`, which
808
+ * `failOpen` swallows, which turns "my partner key is missing" into a `null`
809
+ * that reads as "this wallet has no reputation". The most expensive bug in
810
+ * this file, one indentation level away.
811
+ */
812
+ async partnerHeaders(path) {
813
+ if (!this.partner) return {};
814
+ try {
815
+ return await this.partner.sign({ method: "GET", url: `${this.baseUrl}${path}` });
816
+ } catch (error) {
817
+ throw new DescribePartnerUnsigned(path, this.partner.address, error);
818
+ }
819
+ }
820
+ async request(path, headers = {}) {
821
+ await this.jitter();
822
+ const signed = await this.partnerHeaders(path);
823
+ const controller = new AbortController();
824
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
825
+ try {
826
+ return await this.fetchImpl(`${this.baseUrl}${path}`, {
827
+ method: "GET",
828
+ // never HEAD: every route but /openapi.json answers 405 to it
829
+ headers: { Accept: "application/json", "User-Agent": this.ua, ...signed, ...headers },
830
+ signal: controller.signal
831
+ });
832
+ } catch (error) {
833
+ const name = error?.name;
834
+ if (name === "AbortError" || name === "TimeoutError") {
835
+ throw new DescribeTimeout(`GET ${path} timed out after ${this.timeoutMs} ms`, error);
836
+ }
837
+ throw new DescribeUnreachable(`GET ${path} unreachable: ${String(error)}`, error);
838
+ } finally {
839
+ clearTimeout(timer);
840
+ }
841
+ }
842
+ async readJson(response, path) {
843
+ try {
844
+ return await response.json();
845
+ } catch (error) {
846
+ throw new DescribeUnparseable(`GET ${path} body is not JSON`, error);
847
+ }
848
+ }
849
+ /** A free route: any non-2xx is a typed HTTP error. */
850
+ async getJson(path) {
851
+ const response = await this.request(path);
852
+ if (response.status === 404) {
853
+ throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
854
+ }
855
+ if (!response.ok) {
856
+ throw new DescribeHTTPError(response.status, `GET ${path} -> HTTP ${response.status}`);
857
+ }
858
+ return this.readJson(response, path);
859
+ }
860
+ /**
861
+ * A metered route: ask free, read the challenge, verify WHO we are about to
862
+ * pay, pay through the injected payer, replay the identical request.
863
+ *
864
+ * The order matters and the third step is the one people skip. The published
865
+ * guide says it in the imperative — *"verify who you are about to pay — do
866
+ * this every time"* — because the challenge arrives over the same network
867
+ * that could be lying to you, and it names its own recipient.
868
+ *
869
+ * There is one line in this function that changes what a failure MEANS, and
870
+ * it is marked: everything above `payer.pay()` returning is a failure that
871
+ * cost nothing, everything below it may have cost real USDC. Failures below
872
+ * it are stamped with a `PaymentAttempt` so the caller does not have to infer
873
+ * which side of that line they landed on. Nothing above it is stamped, and
874
+ * that asymmetry IS the signal — see `errors.ts::PaymentAttempt`.
875
+ */
876
+ async getPaidJson(path) {
877
+ const first = await this.request(path);
878
+ if (first.ok) {
879
+ return { body: await this.readJson(first, path), payment: null, servedReceipt: null };
880
+ }
881
+ if (first.status === 404) {
882
+ throw new DescribeNotFound(`GET ${path} -> HTTP 404`);
883
+ }
884
+ if (first.status !== 402) {
885
+ throw new DescribeHTTPError(first.status, `GET ${path} -> HTTP ${first.status}`);
886
+ }
887
+ const challenge = await this.readChallenge(first, path);
888
+ if (this.partner && !this.partnerFallsBackToPaying) {
889
+ throw new DescribePartnerRejected(path, this.partner.address, challenge);
890
+ }
891
+ if (!this.payer) {
892
+ throw new DescribePaymentRequired(
893
+ `GET ${path} is metered (${challenge.amount ?? "?"} ${challenge.token ?? "USDC"}) and no \`payer\` is configured. Read \`error.challenge\` for the terms, or use the free route: GET /wallets/{wallet}/chains.`,
894
+ challenge
895
+ );
896
+ }
897
+ this.assertPayableTo(challenge);
898
+ const header = await this.payer.pay(challenge);
899
+ const terms = {
900
+ amount: typeof challenge.amount === "string" ? challenge.amount : void 0,
901
+ token: typeof challenge.token === "string" ? challenge.token : void 0,
902
+ payTo: typeof challenge.recipient === "string" ? challenge.recipient : void 0
903
+ };
904
+ let second;
905
+ try {
906
+ second = await this.request(path, { "X-PAYMENT": header });
907
+ } catch (error) {
908
+ throw attachPayment(error, { settlement: "unknown", receipt: null, reused: null, ...terms });
909
+ }
910
+ const receipt = second.headers.get("X-Payment-Receipt");
911
+ const reused = second.headers.get("X-Payment-Reused");
912
+ const attempt = {
913
+ // A receipt is the settlement transaction hash, put there by the seller:
914
+ // proof, not inference. Its absence proves nothing — an unhandled 500 is
915
+ // rendered above the paywall middleware and never gets the header.
916
+ //
917
+ // ⚠️ Since 2026-08-30 the header must also LOOK like a settlement id (a
918
+ // hash, or the `pending` the OpenAPI declares) before it may be called
919
+ // proof. `'settled'` means *we hold the hash*, and a string that is not
920
+ // one is not one. The value is still carried in `receipt` — on this path
921
+ // it is forensic evidence, not a typed field — and `'unknown'` is the
922
+ // honest verdict: ask the chain.
923
+ settlement: receipt !== null && looksLikeSettlementReceipt(receipt) ? "settled" : "unknown",
924
+ receipt,
925
+ reused: reused === null ? null : reused.toLowerCase() === "true",
926
+ status: second.status,
927
+ ...terms
928
+ };
929
+ if (!second.ok) {
930
+ throw attachPayment(
931
+ new DescribeHTTPError(
932
+ second.status,
933
+ `GET ${path} -> HTTP ${second.status} AFTER paying (settlement: ${attempt.settlement}${receipt ? `, receipt ${receipt}` : ""}). Read \`error.payment\` before retrying: the same receipt unlocks only this byte-identical resource.`
934
+ ),
935
+ attempt
936
+ );
937
+ }
938
+ let body;
939
+ try {
940
+ body = await this.readJson(second, path);
941
+ } catch (error) {
942
+ throw attachPayment(error, attempt);
943
+ }
944
+ const receiptOk = receipt !== null && looksLikeSettlementReceipt(receipt);
945
+ return {
946
+ body,
947
+ payment: {
948
+ receipt: receiptOk ? receipt : null,
949
+ reused: (reused ?? "").toLowerCase() === "true",
950
+ malformedHashes: receipt !== null && !receiptOk ? ["receipt"] : []
951
+ },
952
+ servedReceipt: receipt
953
+ };
954
+ }
955
+ /**
956
+ * Read the 402 challenge from wherever it is.
957
+ *
958
+ * The header FIRST, then the body — and that order is measured, not
959
+ * defensive: of 40 live x402 resources probed on 2026-08-20, 36 of 36 that
960
+ * answered 402 carried the challenge in the header and none in the body
961
+ * (`uvd-x402-sdk-typescript/src/utils/x402.ts`). describe.net serves BOTH
962
+ * (verified 2026-08-30: `Payment-Required` base64 header AND a JSON body), so
963
+ * either path works here — the order is for the ecosystem, not for us.
964
+ */
965
+ async readChallenge(response, path) {
966
+ const raw = response.headers.get("Payment-Required") ?? response.headers.get("X-Payment-Required");
967
+ if (raw) {
968
+ const trimmed = raw.trim();
969
+ for (const decode of [() => atob(trimmed), () => trimmed]) {
970
+ try {
971
+ const parsed = JSON.parse(decode());
972
+ if (parsed && typeof parsed === "object") return parsed;
973
+ } catch {
974
+ }
975
+ }
976
+ }
977
+ const body = await this.readJson(response, path);
978
+ if (body && typeof body === "object") return body;
979
+ throw new DescribeUnparseable(`GET ${path} answered 402 with no readable challenge`);
980
+ }
981
+ /**
982
+ * `DO_NOT_PAY` unless every recipient in the challenge is the pinned
983
+ * treasury.
984
+ *
985
+ * Checks the top-level `recipient` AND every `accepts[].payTo`, because a
986
+ * challenge that names the right treasury up top and a stranger in one of six
987
+ * `accepts` entries is exactly the shape an attack would take: the caller's
988
+ * chain selection decides which one gets paid. Case-insensitive, since EVM
989
+ * addresses travel in mixed checksum case (the live challenge serves
990
+ * `0xe4dc963c56979E0260fc146b87eE24F18220e545` while the path parameter is
991
+ * lowercase).
992
+ */
993
+ assertPayableTo(challenge) {
994
+ const expected = this.expectedPayTo.toLowerCase();
995
+ const offered = [
996
+ typeof challenge.recipient === "string" ? challenge.recipient : void 0,
997
+ ...Object.values(challenge.recipients ?? {}),
998
+ ...(challenge.accepts ?? []).map(
999
+ (a) => typeof a?.payTo === "string" ? a.payTo : void 0
1000
+ )
1001
+ ];
1002
+ const seen = offered.filter((a) => typeof a === "string" && a.length > 0);
1003
+ if (seen.length === 0) {
1004
+ throw new DescribePaymentRefused(this.expectedPayTo, void 0, challenge);
1005
+ }
1006
+ for (const address of seen) {
1007
+ if (address.toLowerCase() !== expected) {
1008
+ throw new DescribePaymentRefused(this.expectedPayTo, address, challenge);
1009
+ }
1010
+ }
1011
+ }
1012
+ };
1013
+
1014
+ // src/format.ts
1015
+ function formatScore(value) {
1016
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
1017
+ return String(parseFloat(value.toFixed(2)));
1018
+ }
1019
+ function roundScore(value) {
1020
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
1021
+ return parseFloat(value.toFixed(2));
1022
+ }
1023
+
1024
+ // src/raters.ts
1025
+ function resolveDistinctRaters(wallet) {
1026
+ if (!wallet) return null;
1027
+ if (wallet.distinctRaters !== null && wallet.distinctRaters !== void 0) {
1028
+ return wallet.distinctRaters;
1029
+ }
1030
+ let best = null;
1031
+ for (const chain of wallet.chains ?? []) {
1032
+ const n = chain?.distinctRaters;
1033
+ if (typeof n === "number" && Number.isFinite(n) && (best === null || n > best)) best = n;
1034
+ }
1035
+ return best;
1036
+ }
1037
+
1038
+ exports.CAVEAT_CODES = CAVEAT_CODES;
1039
+ exports.CAVEAT_SCOPE_FREE = CAVEAT_SCOPE_FREE;
1040
+ exports.CAVEAT_SCOPE_METERED = CAVEAT_SCOPE_METERED;
1041
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1042
+ exports.DEFAULT_JITTER_MS = DEFAULT_JITTER_MS;
1043
+ exports.DEFAULT_SITE_URL = DEFAULT_SITE_URL;
1044
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1045
+ exports.DescribeClient = DescribeClient;
1046
+ exports.DescribeError = DescribeError;
1047
+ exports.DescribeHTTPError = DescribeHTTPError;
1048
+ exports.DescribeMalformedHash = DescribeMalformedHash;
1049
+ exports.DescribeNotFound = DescribeNotFound;
1050
+ exports.DescribePartnerRejected = DescribePartnerRejected;
1051
+ exports.DescribePartnerUnsigned = DescribePartnerUnsigned;
1052
+ exports.DescribePaymentRefused = DescribePaymentRefused;
1053
+ exports.DescribePaymentRequired = DescribePaymentRequired;
1054
+ exports.DescribeTimeout = DescribeTimeout;
1055
+ exports.DescribeUnparseable = DescribeUnparseable;
1056
+ exports.DescribeUnreachable = DescribeUnreachable;
1057
+ exports.PARTNER_CHAIN_ID = PARTNER_CHAIN_ID;
1058
+ exports.PARTNER_KEY_ENV = PARTNER_KEY_ENV;
1059
+ exports.RECOVERY = RECOVERY;
1060
+ exports.SDK_NAME = SDK_NAME;
1061
+ exports.SDK_VERSION = SDK_VERSION;
1062
+ exports.SETTLEMENT_PENDING = SETTLEMENT_PENDING;
1063
+ exports.TREASURY_EVM = TREASURY_EVM;
1064
+ exports.failOpenCovers = failOpenCovers;
1065
+ exports.failedAfterPaying = failedAfterPaying;
1066
+ exports.formatScore = formatScore;
1067
+ exports.hasCaveat = hasCaveat;
1068
+ exports.isKnownCaveatCode = isKnownCaveatCode;
1069
+ exports.looksLikeOnchainId = looksLikeOnchainId;
1070
+ exports.looksLikeSettlementReceipt = looksLikeSettlementReceipt;
1071
+ exports.malformedHashReport = malformedHashReport;
1072
+ exports.parseAgentReputation = parseAgentReputation;
1073
+ exports.parseHealth = parseHealth;
1074
+ exports.parseLeaderboard = parseLeaderboard;
1075
+ exports.parseWalletBreakdown = parseWalletBreakdown;
1076
+ exports.parseWalletReputation = parseWalletReputation;
1077
+ exports.recoveryFor = recoveryFor;
1078
+ exports.resolveDistinctRaters = resolveDistinctRaters;
1079
+ exports.roundScore = roundScore;
1080
+ exports.userAgent = userAgent;
1081
+ //# sourceMappingURL=index.js.map
1082
+ //# sourceMappingURL=index.js.map