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/src/types.ts ADDED
@@ -0,0 +1,457 @@
1
+ /**
2
+ * The wire shapes — hand-written, and here is the argument for that.
3
+ *
4
+ * ## Why not generated from the OpenAPI
5
+ *
6
+ * The schema is live, complete (20 paths, `securitySchemes.x402`, every field
7
+ * typed) and generating from it would tie these types to it for free. It was
8
+ * measured and rejected for three reasons, in increasing order of weight:
9
+ *
10
+ * 1. **Surface.** This SDK wraps 4 of the 20 paths. `openapi.snapshot.json`
11
+ * carries 41 component schemas; generating produces every one of them, so a
12
+ * package whose whole public surface is six methods would ship ~40
13
+ * interfaces nobody reviewed. Unreviewed code in a package other people
14
+ * install is a liability, not a saving.
15
+ *
16
+ * 2. **A build dependency for a package that has none.** The whole dependency
17
+ * argument of this SDK is that a free-only consumer installs nothing. Adding
18
+ * a generator plus its runtime to make that true is a strange trade.
19
+ *
20
+ * 3. **And the real one: the schema cannot say what matters here.** It says
21
+ * `global_score: number | null`. It does NOT say that the `null` means "no
22
+ * evidence" and must never be coerced to `0` — which is the single most
23
+ * important fact about this API, the invariant the index is built around,
24
+ * and the thing every consumer gets wrong first. Generated types carry no
25
+ * docstring, so the schema's shape would be pinned and the product's thesis
26
+ * would be nowhere. In this package the comment IS the deliverable.
27
+ *
28
+ * ## What replaces generation
29
+ *
30
+ * The third way: hand-written types PLUS a test that compares them against the
31
+ * schema, at two speeds.
32
+ *
33
+ * * `types.schema.test.ts` runs in the normal loop, offline, against
34
+ * `schema/openapi.snapshot.json` — a pinned copy of the live schema fetched
35
+ * 2026-08-30. It fails when a hand-written type drifts from the schema.
36
+ * * `npm run schema:check` re-fetches the live schema and diffs it against
37
+ * the snapshot. It fails when the SERVER moves. Deliberate, networked, and
38
+ * never in the test loop (tests do not touch the network).
39
+ *
40
+ * Two gates because there are two different failures: we drifted, and they
41
+ * moved. Generation conflates them into "the build broke" and tells you
42
+ * nothing about which happened.
43
+ */
44
+
45
+ import type { Caveat } from './caveats';
46
+
47
+ /** The eleven indexed chains are strings on the wire. Never an enum here: the index adds chains. */
48
+ export type Network = string;
49
+
50
+ /** ISO-8601 as served. `null` means "not recorded" — never "just now". */
51
+ export type Timestamp = string | null;
52
+
53
+ /**
54
+ * The receipt headers describe.net's paywall has been emitting since
55
+ * 2026-08-25 and that, as of 2026-08-30, NO client reads.
56
+ *
57
+ * `X-Payment-Receipt` is the settlement id; `X-Payment-Reused` says the call
58
+ * was served against a receipt already settled rather than a fresh payment.
59
+ * Surfacing them is the point: without them a caller who paid has no local
60
+ * record of having paid, and cannot tell a re-served response from a second
61
+ * charge. Present only on metered responses that actually went through payment.
62
+ */
63
+ export interface PaymentEvidence {
64
+ /**
65
+ * The settlement id, or `null` when none was served **or when what was served
66
+ * was not one** — `malformedHashes` tells the two apart.
67
+ *
68
+ * Validated with its own rule (`hashes.looksLikeSettlementReceipt`) because
69
+ * this is the one field where `"pending"` is a legitimate value: the live
70
+ * OpenAPI declares the header as the settlement transaction hash *"or
71
+ * `pending` if settlement has not reported one"*. Treating that as garbage
72
+ * would fire an alarm on the happy path of every fresh payment.
73
+ */
74
+ receipt: string | null;
75
+ reused: boolean;
76
+ /**
77
+ * `['receipt']` when the header carried something that is neither a hash nor
78
+ * `pending`. Empty in the normal case, and empty when no header came at all.
79
+ *
80
+ * ⚠️ This is the one malformed value that does NOT survive in a result's
81
+ * `raw`, and the reason is structural: `raw` is the response BODY and this
82
+ * arrived as a header. So the offending string is put in the `onFailure`
83
+ * message instead — it is the only place it can be kept.
84
+ */
85
+ malformedHashes: string[];
86
+ }
87
+
88
+ /**
89
+ * Every result of this SDK carries its composition seal.
90
+ *
91
+ * R2 and it is the product's thesis, not a convention: *"un score sin sus
92
+ * calificadores es un rumor"*. There is deliberately NO method here that
93
+ * returns a bare `number`, and adding one would erase the reason the index
94
+ * exists. If you want the number alone you take it off the object by hand, and
95
+ * that friction is the feature.
96
+ *
97
+ * `policyVersion` travels because a score is only comparable to another score
98
+ * under the SAME policy: KarmaKadabra measured its flagship wallet going
99
+ * 86.33 → 81.41 with MORE reviews, purely because the policy revised. Two
100
+ * numbers from different `policy_version`s are not two measurements of one
101
+ * thing.
102
+ */
103
+ export interface Sealed {
104
+ /** e.g. `equal-weight-per-chain@2`. Compare scores only within one value of this. */
105
+ policyVersion: string | null;
106
+ /** Advisory. Branch on `code`, render `text`. Never moves a score. */
107
+ caveats: Caveat[];
108
+ /** `public-data-subset` on free routes, `full` on metered ones. */
109
+ caveatScope: string;
110
+ /** Which route produced this — `chain_rankings_mv`, a matview name, etc. */
111
+ source: string | null;
112
+ /** When the index last recomputed the value. `null` = not recorded. */
113
+ refreshedAt: Timestamp;
114
+ /** The exact JSON as served, unmodified. See `raw` below. */
115
+ raw: Record<string, unknown>;
116
+ }
117
+
118
+ /**
119
+ * `raw` on every result is the passthrough rule made concrete.
120
+ *
121
+ * Tipar lo conocido, CONSERVAR lo que no. The measured lesson is
122
+ * `Facet.direction`: a field the server was serving got dropped by a layer that
123
+ * had not declared it, and the response came back 200, correctly shaped, with
124
+ * the data gone. A typed field that this SDK version has not heard of yet is
125
+ * still in `raw`, so a consumer is never blocked on our release cycle to read
126
+ * something describe.net already publishes.
127
+ */
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // GET /wallets/{wallet}/chains — free, and the one every surface calls
131
+ // ---------------------------------------------------------------------------
132
+
133
+ /** One chain's row of a wallet's reputation. */
134
+ export interface WalletChainRow {
135
+ network: Network;
136
+ agentCount: number;
137
+ agentIds: string[] | null;
138
+ /**
139
+ * 🔴 `null`, NEVER `0`. "No eligible ratings here" and "rated badly" are
140
+ * different facts and the index refuses to collapse them. A `0` asserts the
141
+ * second where the API asserted the first.
142
+ */
143
+ finalScore: number | null;
144
+ totalReviews: number;
145
+ distinctRaters: number;
146
+ }
147
+
148
+ /**
149
+ * `GET /wallets/{wallet}/chains` — the free per-wallet answer.
150
+ *
151
+ * Verified live 2026-08-30 against an address with no identity
152
+ * (`0xdEaD…BEEF`): **HTTP 200**, `chains: []`, `global_score: null`,
153
+ * `distinct_raters: null`. That is a RESPONSE, not an error — the A2A gate of
154
+ * the same service says it in its own voice: *"That is an answer, not an
155
+ * error."* This SDK never throws for it (R1, R4).
156
+ */
157
+ export interface WalletReputation extends Sealed {
158
+ /** As served. EVM is normalised server-side; Solana base58 is case-SENSITIVE. */
159
+ wallet: string;
160
+ chains: WalletChainRow[];
161
+ /**
162
+ * Mean of the per-chain means — one chain, one vote. `null` when there is no
163
+ * eligible rating anywhere. Full precision: format with `formatScore`.
164
+ */
165
+ globalScore: number | null;
166
+ /**
167
+ * `COUNT(DISTINCT client)` across every chain AND every identity, so a rater
168
+ * who reviewed on two chains counts once.
169
+ *
170
+ * `null` when the index has nothing to count — and the difference from `0`
171
+ * matters: MeshRelay measured that taking the per-chain MAXIMUM instead
172
+ * reports 4 for a wallet with 3 raters on base and 4 different ones on
173
+ * avalanche (7 distinct counterparties), and that SUMMING double-counts
174
+ * whoever rated on more than one chain (karma-hello reads 9 globally while
175
+ * the per-chain figures add to 11). Neither reconstruction is correct; this
176
+ * field is.
177
+ */
178
+ distinctRaters: number | null;
179
+ identityCount: number;
180
+ chainsWithIdentity: number;
181
+ chainsWithReputation: number;
182
+ totalReviews: number;
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // GET /reputation/wallet/{wallet} — metered, $0.01
187
+ // ---------------------------------------------------------------------------
188
+
189
+ /** How lopsided the evidence is. `null` when there is not enough to say. */
190
+ export interface Concentration {
191
+ distinctRaters: number;
192
+ /** Share of ratings written by the single loudest client, 0..1. */
193
+ topClientShare: number | null;
194
+ topClient: string | null;
195
+ }
196
+
197
+ /** Wilson interval over distinct raters. Read `interval` before acting on `band`. */
198
+ export interface Confidence {
199
+ /** `no_ratings` | `low` | `medium` | `high` — the server's own bands. */
200
+ band: string;
201
+ distinctRaters: number;
202
+ interval: { lower: number; upper: number } | null;
203
+ /** The cut points, published live so nobody re-types them. */
204
+ thresholds: Record<string, number>;
205
+ advice: string;
206
+ confidencePolicy: string;
207
+ }
208
+
209
+ export interface SelfRated {
210
+ count: number;
211
+ score: number | null;
212
+ /** Distance between the self-rating and everyone else's. */
213
+ gap: number | null;
214
+ }
215
+
216
+ export interface Activity {
217
+ firstRatingAt: Timestamp;
218
+ lastRatingAt: Timestamp;
219
+ }
220
+
221
+ /** One facet (`tag1`), as declared on-chain. */
222
+ export interface Facet {
223
+ score: number | null;
224
+ count: number;
225
+ distinctRaters: number;
226
+ revokedCount: number;
227
+ outOfDomainCount: number;
228
+ selfRatedCount: number;
229
+ /**
230
+ * ⚠️ `tag1` is FREE TEXT on-chain. The longest facet in this index is 471
231
+ * characters — a paragraph about gardening used as a label. Escape
232
+ * everything that comes from the chain before it reaches a DOM.
233
+ */
234
+ direction: string | null;
235
+ directionCategory: string | null;
236
+ directionMeaning: string | null;
237
+ }
238
+
239
+ /** A citable computation: same `inputsDigest`, same numbers. */
240
+ export interface Snapshot {
241
+ id: number;
242
+ /**
243
+ * A bare `sha256` hexdigest — 64 hex, **no `0x`** (`aggregate.py:1920`).
244
+ *
245
+ * `null` when it did not come **or** when what came was not a digest;
246
+ * `malformedHashes` is what tells those apart. It is nullable rather than `''`
247
+ * on purpose: this is the field that makes an answer citable, and an empty
248
+ * string here would be a citation to nothing wearing the clothes of a
249
+ * citation.
250
+ */
251
+ inputsDigest: string | null;
252
+ policyVersion: string;
253
+ computedAt: string;
254
+ /**
255
+ * `['inputs_digest']` when the digest arrived malformed. Empty means "nothing
256
+ * arrived malformed" — it says nothing about what arrived.
257
+ */
258
+ malformedHashes: string[];
259
+ }
260
+
261
+ /**
262
+ * `GET /reputation/wallet/{wallet}` — metered ($0.01; $0.05 with a citable
263
+ * snapshot). The decomposition: who rated, how many times, how concentrated.
264
+ */
265
+ export interface WalletBreakdown extends Sealed {
266
+ wallet: string;
267
+ finalScore: number | null;
268
+ weightedScore: number | null;
269
+ raterWeightPolicy: string;
270
+ chainCount: number;
271
+ totalReviews: number;
272
+ /** Keyed by network. Values keep the server's shape. */
273
+ perChain: Record<string, unknown>;
274
+ facets: Record<string, Facet>;
275
+ selfRated: SelfRated | null;
276
+ concentration: Concentration | null;
277
+ confidence: Confidence | null;
278
+ activity: Activity | null;
279
+ snapshot: Snapshot | null;
280
+ /** What was actually paid, if anything was. */
281
+ payment: PaymentEvidence | null;
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // GET /reputation/agent/{network}/{agent_id} — metered, $0.02
286
+ // ---------------------------------------------------------------------------
287
+
288
+ /**
289
+ * One rating, at the grain. `tag1`/`tag2` are on-chain free text: escape them.
290
+ *
291
+ * 🔴 **Its three hash fields arrive shape-validated** (`txHash`, `feedbackHash`,
292
+ * `revokedTx`) — KarmaKadabra's contribution of 2026-08-30, from *"el 200 sin
293
+ * tx"*. Anything that is not a hash is dropped to `null` and its wire name goes
294
+ * into `malformedHashes`. **Absent and malformed are not the same thing**: read
295
+ * the list, not the `null`. See `hashes.ts`.
296
+ */
297
+ export interface Rating {
298
+ client: string;
299
+ feedbackIndex: number;
300
+ value: number;
301
+ valueDecimals: number;
302
+ normalizedValue: number | null;
303
+ tag1: string | null;
304
+ tag2: string | null;
305
+ isRevoked: boolean;
306
+ isSelf: boolean;
307
+ /**
308
+ * The transaction that wrote this rating — `0x` + 64 hex on the EVM chains, a
309
+ * base58 signature on Solana. `null` means it did not come **or** it came
310
+ * malformed; `malformedHashes` separates them. The schema's own note: *"null
311
+ * until the log scan reaches this entry, not null forever"*, so a hole here is
312
+ * normal and is not reported.
313
+ */
314
+ txHash: string | null;
315
+ blockNumber: number | null;
316
+ logIndex: number | null;
317
+ feedbackUri: string | null;
318
+ /** Host of `feedbackURI`. What the ISSUER declared — advisory, never a score. */
319
+ issuerHost: string | null;
320
+ issuer: string | null;
321
+ issuerOrg: string | null;
322
+ /**
323
+ * The content hash the rater committed to. `bytes32`, so `0x` + 64 hex — and
324
+ * **NULL on purpose on Solana** (`solana_indexer.py`), so absence here is
325
+ * correct and is not reported.
326
+ *
327
+ * ⚠️ A well-shaped hash is not a meaningful one: an EVM rater that declared
328
+ * nothing writes 32 zero bytes, which passes the shape check as
329
+ * `0x0000…0000`. This SDK will not decide that for you — a shape check says
330
+ * "this could be a hash", never "this hash means something".
331
+ */
332
+ feedbackHash: string | null;
333
+ /** The transaction that killed this rating, if it was revoked. Same shapes. */
334
+ revokedTx: string | null;
335
+ /**
336
+ * Which of the three hash fields above arrived with something that is not a
337
+ * hash. Empty in the normal case.
338
+ *
339
+ * 🔴 Branch on this, not on `txHash === null`.
340
+ */
341
+ malformedHashes: string[];
342
+ }
343
+
344
+ /** Whether reputation was inherited across an identity transfer. */
345
+ export interface Ownership {
346
+ ownerUpdatedBlock: number;
347
+ identityTransferred: boolean | null;
348
+ inheritedReviewCount: number;
349
+ inheritedScore: number | null;
350
+ currentEraReviewCount: number;
351
+ currentEraScore: number | null;
352
+ undeterminedReviewCount: number;
353
+ inheritedShare: number | null;
354
+ }
355
+
356
+ /** `GET /reputation/agent/{network}/{agent_id}` — metered ($0.02). */
357
+ export interface AgentReputation extends Sealed {
358
+ network: Network;
359
+ agentId: string;
360
+ /**
361
+ * The wallet that owns this identity TODAY (`agents.current_owner`), never
362
+ * the minter of the `Registered` event — that is almost always the
363
+ * facilitator, and attributing by it would file the whole index under one
364
+ * address.
365
+ */
366
+ currentOwner: string | null;
367
+ /**
368
+ * ⚠️ NOT a type. 283 770 of 470 064 agents (60,4 %, measured 2026-08-30) are
369
+ * `unknown`, and the second largest "type" is the URL of the EIP schema —
370
+ * with its typo variant. ERC-8004 has no type field. Never treat it as
371
+ * verification. Read it live from `GET /stats/types`.
372
+ */
373
+ declaredType: string | null;
374
+ agentUri: string | null;
375
+ indexedIdentity: boolean;
376
+ score: number | null;
377
+ reviewCount: number;
378
+ revokedCount: number;
379
+ outOfDomainCount: number;
380
+ selfRated: SelfRated | null;
381
+ facets: Record<string, Facet>;
382
+ concentration: Concentration | null;
383
+ ownership: Ownership | null;
384
+ confidence: Confidence | null;
385
+ ratings: Rating[];
386
+ payment: PaymentEvidence | null;
387
+ }
388
+
389
+ // ---------------------------------------------------------------------------
390
+ // GET /leaderboard — free (first page only; `/leaderboard/page` is metered)
391
+ // ---------------------------------------------------------------------------
392
+
393
+ /**
394
+ * ⚠️ The leaderboard does NOT order by average. It orders by `shrunkScore`
395
+ * (Bayesian shrinkage over distinct raters), which is why row 1 can show a
396
+ * lower `finalScore` than row 2. Ordering by `finalScore` client-side
397
+ * reproduces the bug the shrinkage exists to prevent: a wallet with one
398
+ * 100-point rating outranking one with two hundred.
399
+ */
400
+ export interface LeaderboardRow {
401
+ rank: number;
402
+ wallet: string;
403
+ finalScore: number | null;
404
+ shrunkScore: number | null;
405
+ distinctRaters: number;
406
+ chainCount: number;
407
+ totalReviews: number;
408
+ networks: Network[];
409
+ declaredTypes: Array<string | null>;
410
+ /** The row exactly as served. */
411
+ raw: Record<string, unknown>;
412
+ }
413
+
414
+ // ---------------------------------------------------------------------------
415
+ // GET /health — the authority on index totals
416
+ // ---------------------------------------------------------------------------
417
+
418
+ export interface HealthChain {
419
+ network: Network;
420
+ lastScannedBlock: number | null;
421
+ updatedAt: Timestamp;
422
+ /** When this chain is next due. The freshness pointer worth polling against. */
423
+ nextSyncAt: Timestamp;
424
+ lastError: string | null;
425
+ raw: Record<string, unknown>;
426
+ }
427
+
428
+ /**
429
+ * `GET /health` — free, and the ONLY authority on the index's totals.
430
+ *
431
+ * "Toda cifra o se lee viva o lleva fecha": never type a total of this index
432
+ * into a UI, a README or a doc. Read it here. That is also why
433
+ * `readingPolicy` and `confidenceThresholds` come through as maps rather than
434
+ * as constants of this package — they are the server's calibrable values,
435
+ * published live precisely so no consumer re-types them (invariante 10).
436
+ *
437
+ * Slowest free endpoint (~1,6 s measured, 2,4 s on 2026-08-30) and deliberately
438
+ * uncached at the edge — never probe it with a sub-3 s timeout.
439
+ */
440
+ export interface IndexHealth {
441
+ status: string;
442
+ policyVersion: string;
443
+ orderingPolicy: string;
444
+ raterWeightPolicy: string;
445
+ confidencePolicy: string;
446
+ /** e.g. `{no_ratings: 0, low: 1, medium: 3, high: 6}` — live, never re-typed. */
447
+ confidenceThresholds: Record<string, number>;
448
+ /** e.g. `{min_raters: 3, campaign_per_rater: 20, top_share: 0.5, ...}`. */
449
+ readingPolicy: Record<string, unknown>;
450
+ /** Which commit is serving. Useful when a shape changes under you. */
451
+ buildSha: string | null;
452
+ agents: number;
453
+ feedbackEntries: number;
454
+ indexerPeriodSeconds: number | null;
455
+ chains: HealthChain[];
456
+ raw: Record<string, unknown>;
457
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The canonical payer — the ONLY file in this package that knows `uvd-x402-sdk`
3
+ * exists.
4
+ *
5
+ * ## Why it lives behind a subpath instead of in the main entry
6
+ *
7
+ * `uvd-x402-sdk` depends on `ethers` plus three `@noble/*` packages (measured
8
+ * 2026-08-30 with `npm view uvd-x402-sdk dependencies`). Measured on the same
9
+ * day, **all three live HTTP consumers of describe.net read only free routes**:
10
+ * EM's client says so in its docstring (*"Free routes only … Paid routes are a
11
+ * separate, deliberate decision and are NOT implemented here"*), MeshRelay
12
+ * fetches `/wallets/{w}/chains`, KarmaKadabra reads free and falls back to the
13
+ * facilitator. Three of three would install a signing stack for code they never
14
+ * call — and Saul's stated goal for this whole line of work is a widget so
15
+ * light that a stranger pastes it into a news page.
16
+ *
17
+ * So: `uvd-x402-sdk` is an OPTIONAL peer dependency, and the split is enforced
18
+ * by the build (`tsup.config.ts` has two entries; `index` never reaches here).
19
+ * This is the same shape the payment SDK itself uses for its thirteen optional
20
+ * peers — the house convention, not a new one.
21
+ *
22
+ * ## What it does NOT do, and this is the absolute part
23
+ *
24
+ * It does not sign. It does not build an EIP-3009 authorization. It does not
25
+ * touch a private key. Every one of those is `uvd-x402-sdk`'s and stays there:
26
+ * if the payment SDK lacks something, the fix goes UPSTREAM and is consumed
27
+ * from here — never patched in this package.
28
+ *
29
+ * ⚠️ **Measured gap, reported not patched (2026-08-30):** npm `uvd-x402-sdk`
30
+ * 2.75.0 has no `isTransientError` export, while PyPI `uvd-x402-sdk` 0.70.0
31
+ * made one public that day. This package therefore classifies transience
32
+ * itself, in `errors.ts`, over describe.net's HTTP surface only. That is a
33
+ * narrower job than the payment SDK's and it is not a reimplementation of it —
34
+ * but the moment npm ships the helper, the classification of PAYMENT failures
35
+ * should come from there. Filed as a report, deliberately not patched here.
36
+ */
37
+
38
+ // TYPE-ONLY, and that is load-bearing: with `import type` the compiler erases
39
+ // this line entirely, so the built `x402/index.js` has **zero** runtime imports
40
+ // and the optional peer stays optional even on the paid path. You get the
41
+ // checked signature of `uvd-x402-sdk` 2.75.0 without the artifact requiring it
42
+ // to be installed — which is what lets a browser bundle this subpath and pass
43
+ // in a wallet-backed client instead.
44
+ import type { PaymentInfo, X402Client } from 'uvd-x402-sdk';
45
+
46
+ import type { X402Payer } from '../client';
47
+ import type { X402Challenge } from '../errors';
48
+
49
+ /**
50
+ * Wrap a connected `X402Client` as a payer this SDK can use.
51
+ *
52
+ * The challenge maps onto `PaymentInfo` almost field for field, because
53
+ * describe.net serves the standard shape — verified live against the 402 of
54
+ * `GET /reputation/wallet/{w}` on 2026-08-30: `recipient`, `recipients.evm`,
55
+ * `amount: "0.01"`, `token: "USDC"`, `supportedChains: [8453, 43114, 42161, 10,
56
+ * 137, 42220]`. So this function forwards; it does not translate. A translator
57
+ * would be a second place where payment knowledge lives.
58
+ *
59
+ * The recipient has ALREADY been checked against the pinned treasury by the
60
+ * time this runs (`DescribeClient.assertPayableTo`), and that ordering is the
61
+ * contract: this function must never be the thing that decides who gets paid.
62
+ *
63
+ * ```ts
64
+ * import { DescribeClient } from 'uvd-describe-sdk';
65
+ * import { payerFromX402Client } from 'uvd-describe-sdk/x402';
66
+ * import { X402Client } from 'uvd-x402-sdk';
67
+ *
68
+ * const x402 = new X402Client();
69
+ * await x402.connectWithPrivateKey(process.env.PAYER_PRIVATE_KEY!, 'base');
70
+ *
71
+ * const describe = new DescribeClient({
72
+ * product: 'my-app',
73
+ * payer: payerFromX402Client(x402),
74
+ * });
75
+ * ```
76
+ *
77
+ * 🔴 The key comes from the environment. Never a literal, never "just for a
78
+ * test": bots scan public repos for `0x` + 64 hex and drain in minutes (two DAO
79
+ * wallets, INC-2026-03-30).
80
+ *
81
+ * ⚠️ **Verification status, stated plainly:** the mapping below is checked
82
+ * against the live 402 body and against `PaymentInfo` / `PaymentResult` in
83
+ * `uvd-x402-sdk` 2.75.0 (`src/types/index.ts:206,272`), and
84
+ * `x402/payer.test.ts` proves the forwarding with a stub client. It has NOT
85
+ * been run through a real settlement — that costs USDC and was out of scope for
86
+ * the session that wrote it. Treat the first live metered call as the test.
87
+ */
88
+ export function payerFromX402Client(client: X402Client): X402Payer {
89
+ return {
90
+ async pay(challenge: X402Challenge): Promise<string> {
91
+ const info: PaymentInfo = {
92
+ recipient: String(challenge.recipient ?? ''),
93
+ recipients: challenge.recipients as PaymentInfo['recipients'],
94
+ amount: String(challenge.amount ?? ''),
95
+ token: typeof challenge.token === 'string' ? challenge.token : 'USDC',
96
+ supportedChains: Array.isArray(challenge.supportedChains)
97
+ ? (challenge.supportedChains as number[])
98
+ : undefined,
99
+ };
100
+
101
+ const result = await client.createPayment(info);
102
+ if (!result.success || !result.paymentHeader) {
103
+ throw new Error(`x402 payment was not created: ${result.error ?? 'no header returned'}`);
104
+ }
105
+ return result.paymentHeader;
106
+ },
107
+ };
108
+ }
109
+
110
+ /**
111
+ * The same seam for a wallet this package knows nothing about.
112
+ *
113
+ * Anything that can turn a challenge into an `X-PAYMENT` value is a payer — a
114
+ * browser wallet, a custodial signer, a queue that asks a human. Exported so
115
+ * that "bring your own payment" does not require importing `uvd-x402-sdk` at
116
+ * all, which is the point of the subpath.
117
+ */
118
+ export function payerFrom(fn: (challenge: X402Challenge) => Promise<string>): X402Payer {
119
+ return { pay: fn };
120
+ }
121
+
122
+ export type { X402Payer } from '../client';
123
+ export type { X402Challenge } from '../errors';