@redditech/x402-solana 0.0.0-stage → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +301 -2
  4. package/dist/budget-policy.d.ts +68 -0
  5. package/dist/budget-policy.js +234 -0
  6. package/dist/buyer.d.ts +54 -0
  7. package/dist/buyer.js +147 -0
  8. package/dist/client.d.ts +80 -0
  9. package/dist/client.js +225 -0
  10. package/dist/direct-auth.d.ts +94 -0
  11. package/dist/direct-auth.js +120 -0
  12. package/dist/direct-payment.d.ts +33 -0
  13. package/dist/direct-payment.js +65 -0
  14. package/dist/ed25519.d.ts +6 -0
  15. package/dist/ed25519.js +42 -0
  16. package/dist/escrow-http.d.ts +125 -0
  17. package/dist/escrow-http.js +192 -0
  18. package/dist/escrow-readiness.d.ts +132 -0
  19. package/dist/escrow-readiness.js +171 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +42 -0
  22. package/dist/jupiter.d.ts +36 -0
  23. package/dist/jupiter.js +120 -0
  24. package/dist/metered.d.ts +58 -0
  25. package/dist/metered.js +82 -0
  26. package/dist/middleware.d.ts +9 -0
  27. package/dist/middleware.js +71 -0
  28. package/dist/nonce.d.ts +57 -0
  29. package/dist/nonce.js +123 -0
  30. package/dist/payment.d.ts +202 -0
  31. package/dist/payment.js +967 -0
  32. package/dist/provider.d.ts +371 -0
  33. package/dist/provider.js +492 -0
  34. package/dist/rating.d.ts +552 -0
  35. package/dist/rating.js +829 -0
  36. package/dist/session-auth.d.ts +168 -0
  37. package/dist/session-auth.js +341 -0
  38. package/dist/session.d.ts +220 -0
  39. package/dist/session.js +297 -0
  40. package/dist/spl-token-observer.d.ts +70 -0
  41. package/dist/spl-token-observer.js +319 -0
  42. package/dist/token-escrow.d.ts +125 -0
  43. package/dist/token-escrow.js +163 -0
  44. package/dist/types.d.ts +148 -0
  45. package/dist/types.js +2 -0
  46. package/package.json +109 -4
@@ -0,0 +1,371 @@
1
+ /**
2
+ * The seller side of a per-token (metered) call.
3
+ *
4
+ * A buyer locks the most it will pay in a metered token escrow payable to the
5
+ * provider. The provider reads the lock back from the chain, serves the call,
6
+ * counts the tokens the model reports and settles the actual cost. The escrow
7
+ * program pays the protocol fee (2.5% until 1 April 2027, then 5%) of that to the protocol treasury, the rest to the
8
+ * provider, and returns the unused maximum to the buyer.
9
+ *
10
+ * Nothing here reads a key or sends a transaction. `meteredSettlement` returns
11
+ * instructions; the operator signs and sends them.
12
+ */
13
+ import { PublicKey, type TransactionInstruction } from '@solana/web3.js';
14
+ import { type MeteredSettlement, type PerTokenPrice, type TokenCounts } from './metered';
15
+ import { type TokenEscrowTerms } from './token-escrow';
16
+ import type { NonceReplayStore, SolanaPaymentNetwork } from './types';
17
+ /** Output tokens assumed when the request sets no limit and the operator sets none. */
18
+ export declare const DEFAULT_MAX_OUTPUT_TOKENS = 1000;
19
+ /** The buyer's default maximum, as a multiple of the estimate. The buyer may raise it, never below the estimate. */
20
+ export declare const DEFAULT_MAX_CHARGE_MULTIPLE = 2;
21
+ /**
22
+ * What a reader of chain accounts returns. A `Connection` adapts to it. Read
23
+ * at `confirmed` commitment or better: a buyer can opt an escrow in to rating
24
+ * only in the slot of the lock, so a read that sees that whole slot tells for
25
+ * good whether the job is rated, and a `processed` read may not.
26
+ */
27
+ export type AccountReader = (address: PublicKey) => Promise<{
28
+ owner: PublicKey;
29
+ data: Uint8Array;
30
+ } | null>;
31
+ /** The chain's current slot. */
32
+ export type SlotReader = () => Promise<number | bigint>;
33
+ /**
34
+ * Signs the settle transaction with the provider wallet's key, sends it and
35
+ * waits for confirmation. Returns the signature. The instructions go into one
36
+ * transaction, in order, with the provider wallet as fee payer: the settle,
37
+ * preceded by a create of the buyer's token account only when the operator
38
+ * has chosen to pay for one.
39
+ */
40
+ export type MeteredSettleSigner = (instructions: TransactionInstruction[]) => Promise<string>;
41
+ export interface MeteredTerms {
42
+ price: PerTokenPrice;
43
+ programId: PublicKey;
44
+ mint: PublicKey;
45
+ tokenProgram: PublicKey;
46
+ payee: PublicKey;
47
+ maxOutputTokens: number;
48
+ /**
49
+ * Another token account of the mint that the provider wallet owns. Payouts
50
+ * go here when the provider's associated token account, which locks name,
51
+ * is closed or frozen. A recovery setting; leave it unset otherwise.
52
+ */
53
+ payoutAccount?: PublicKey;
54
+ }
55
+ export interface MeteredTermsInput {
56
+ /** A token currency the escrow program accepts: USDC, AUDD, PYUSD or USDG. */
57
+ currency: string;
58
+ /** Decimal price per million input and output tokens, in `currency`. */
59
+ inputPerMillion: string;
60
+ outputPerMillion: string;
61
+ /** The most output tokens one call may use. Defaults to `DEFAULT_MAX_OUTPUT_TOKENS`. */
62
+ maxOutputTokens?: number;
63
+ /** The escrow program buyers lock in. */
64
+ programId: string | PublicKey;
65
+ /** The mint accepted for `currency` on the provider's network. */
66
+ mint: string | PublicKey;
67
+ /** The provider's wallet. Payouts go to its associated token account for the mint. */
68
+ payee: string | PublicKey;
69
+ /** Recovery only: another token account of the mint the provider wallet owns, used when its associated token account cannot receive. */
70
+ payoutAccount?: string | PublicKey;
71
+ }
72
+ /**
73
+ * A provider's metered terms. Throws when the currency is not a token
74
+ * currency, a price does not parse, or an address is malformed.
75
+ */
76
+ export declare function providerMeteredTerms(input: MeteredTermsInput): MeteredTerms;
77
+ /** About four characters a token, over every message. */
78
+ export declare function estimateInputTokens(messages: readonly {
79
+ content: string;
80
+ }[]): number;
81
+ /** Output limit for this call: the request's own, held to the provider's. */
82
+ export declare function outputLimit(terms: MeteredTerms, requested?: number): number;
83
+ /** The estimate a call is quoted on: the input estimate plus the full output limit. */
84
+ export declare function meteredEstimate(terms: MeteredTerms, messages: readonly {
85
+ content: string;
86
+ }[], requestedMaxTokens?: number): TokenCounts;
87
+ export interface MeteredOffer {
88
+ settlement: 'metered-escrow';
89
+ /** Present when the provider states its network. */
90
+ network?: SolanaPaymentNetwork;
91
+ currency: string;
92
+ inputPerMillion: string;
93
+ outputPerMillion: string;
94
+ maxOutputTokens: number;
95
+ estimate: TokenCounts;
96
+ /** Cost of the estimate, as a decimal amount of `currency`. */
97
+ estimatedCost: string;
98
+ /** The maximum a buyer locks by default: twice the estimate. A buyer may lock more, never less than the estimate. */
99
+ suggestedMaxCharge: string;
100
+ suggestedMaxChargeBaseUnits: string;
101
+ /** Protocol fee if the estimate holds, at the scheduled rate (2.5% until 1 April 2027, then 5%), taken out of the provider's share. */
102
+ estimatedFee: string;
103
+ /** The least a lock may hold, in base units: the cost of the estimate. */
104
+ minimumLockBaseUnits: string;
105
+ escrowProgramId: string;
106
+ mint: string;
107
+ payTo: string;
108
+ nonce: string;
109
+ [key: string]: unknown;
110
+ }
111
+ /** What a 402 tells a buyer about metered payment. The buyer's lock must cover `minimumLockBaseUnits`. */
112
+ export declare function meteredOffer(terms: MeteredTerms, messages: readonly {
113
+ content: string;
114
+ }[], requestedMaxTokens?: number, network?: SolanaPaymentNetwork): MeteredOffer;
115
+ export interface MeteredPaymentHeader {
116
+ escrow: PublicKey;
117
+ payer: PublicKey;
118
+ nonce: Uint8Array;
119
+ }
120
+ /** A request's headers: a fetch `Headers`, or anything with the same `get`. */
121
+ export interface HeaderReader {
122
+ get(name: string): string | null;
123
+ }
124
+ /** The metered receipt a buyer presents, or undefined when the header is not one. */
125
+ export declare function readMeteredPaymentHeader(headers: HeaderReader): MeteredPaymentHeader | {
126
+ error: string;
127
+ } | undefined;
128
+ /** The value a buyer sends in `x402-payment` once its metered lock is confirmed. */
129
+ export declare function meteredPaymentHeaderValue(input: {
130
+ payer: PublicKey;
131
+ nonce: Uint8Array;
132
+ programId: PublicKey;
133
+ }): string;
134
+ export type ClusterCheck = {
135
+ ok: true;
136
+ } | {
137
+ ok: false;
138
+ reason: 'wrong_cluster' | 'payment_check_unavailable';
139
+ message: string;
140
+ };
141
+ /**
142
+ * Confirms the RPC endpoint serves the network the provider is configured
143
+ * for, so a lock on another cluster is never taken as payment. Run it before
144
+ * trusting any account the endpoint returns.
145
+ */
146
+ export declare function checkProviderCluster(readGenesisHash: () => Promise<string>, network: SolanaPaymentNetwork, expectedGenesisHash?: string): Promise<ClusterCheck>;
147
+ /** The accounts a settle pays into, as checked on chain. */
148
+ export interface PayoutAccounts {
149
+ /** Set when the provider is paid at its recovery account instead of the recipient the lock names. */
150
+ payTo?: PublicKey;
151
+ treasuryToken: PublicKey;
152
+ /** Where the unused part returns: a token account of the mint the payer owns. */
153
+ refundTo: PublicKey;
154
+ /** Pass the mint writable, so fees withheld on a Token-2022 vault are moved out and the vault can close. */
155
+ harvestWithheldFees: boolean;
156
+ /** The settle first creates `refundTo`, the payer's associated token account, at the provider's cost. */
157
+ createRefundAccount?: boolean;
158
+ }
159
+ export type PayoutCheck = {
160
+ ok: true;
161
+ payout: PayoutAccounts;
162
+ } | {
163
+ ok: false;
164
+ reason: 'refund_account_unusable' | 'provider_not_ready' | 'payment_check_unavailable';
165
+ message: string;
166
+ };
167
+ /**
168
+ * Reads every account a settle of this escrow would pay into and says whether
169
+ * the payout can land: the provider's token account (or its recovery
170
+ * account), the treasury's, and the buyer's account for the unused part. Each
171
+ * must exist under the mint's token program, be initialised, not frozen, hold
172
+ * the mint, have the right owner and not require a memo.
173
+ *
174
+ * Nothing is created by default. `allowPayerAssociatedAccount` lets the
175
+ * unused part go to the payer's associated token account when the recorded
176
+ * source no longer works; `createRefundAccount` lets the provider pay to
177
+ * create that account when it does not exist at all.
178
+ */
179
+ export declare function checkMeteredPayout(input: {
180
+ terms: MeteredTerms;
181
+ escrow: Pick<TokenEscrowTerms, 'payer' | 'source' | 'recipient'>;
182
+ readAccount: AccountReader;
183
+ treasury?: PublicKey;
184
+ allowPayerAssociatedAccount?: boolean;
185
+ createRefundAccount?: boolean;
186
+ }): Promise<PayoutCheck>;
187
+ export type VerifiedLock = {
188
+ ok: true;
189
+ terms: TokenEscrowTerms;
190
+ maxBaseUnits: bigint;
191
+ payer: PublicKey;
192
+ payout: PayoutAccounts;
193
+ /**
194
+ * The buyer opted this job in to rating (bit 0x02 of the escrow's flag
195
+ * byte). Only ever true when the lock was verified with
196
+ * `acceptRatedEscrows`. The settle and the decline then carry the rating
197
+ * account, and by settling the provider agrees to be rated: it has to
198
+ * commit and reveal its own rating within the windows or lose reputation.
199
+ */
200
+ rated: boolean;
201
+ /**
202
+ * For a rated lock, the rating account's `opened_slot` as read with the
203
+ * lock: the job this provider verified. The settle and the decline name
204
+ * it, so they are refused (6051) if another job has taken the address by
205
+ * then. Undefined for a lock that is not rated.
206
+ */
207
+ openedSlot?: bigint;
208
+ /** The slot the lock was made in. The buyer may refund from `createdSlot + terms.cancelWindowSlots`. */
209
+ createdSlot: bigint;
210
+ } | {
211
+ ok: false;
212
+ reason: string;
213
+ message: string;
214
+ };
215
+ /**
216
+ * Checks the lock on chain against this provider's terms: the escrow program,
217
+ * the address the payer and nonce give, still locked, metered, payable to this
218
+ * provider's token account in the accepted mint, and at least `minimum`. Then
219
+ * checks that the payout can land (`checkMeteredPayout`), using the source
220
+ * account the lock recorded for the unused part, so a call is refused before
221
+ * any work is done rather than left unpaid after it.
222
+ * The escrow is then remembered, so one lock pays for one call.
223
+ *
224
+ * An escrow the buyer opted in to rating is refused (`rated_escrow_declined`)
225
+ * before anything is served or remembered, unless `acceptRatedEscrows` is
226
+ * true. `readAccount` must read at `confirmed` commitment or better for that
227
+ * answer to be final (see `AccountReader`).
228
+ */
229
+ export declare function verifyMeteredLock(input: {
230
+ header: MeteredPaymentHeader;
231
+ terms: MeteredTerms;
232
+ minimum: bigint;
233
+ readAccount: AccountReader;
234
+ readSlot: SlotReader;
235
+ /** Unused for `session-call` and `session-settle`. */
236
+ replayStore: NonceReplayStore;
237
+ /** The protocol treasury. Only a local test deployment has another. */
238
+ treasury?: PublicKey;
239
+ /**
240
+ * Serve jobs the buyer opted in to rating. Default false: a rated escrow is
241
+ * refused before serving. Settling a rated job is the provider's agreement
242
+ * to be rated, after which it must commit and reveal a rating of its own
243
+ * within the program's windows or lose reputation, so turn this on only
244
+ * for a provider that does that.
245
+ */
246
+ acceptRatedEscrows?: boolean;
247
+ /**
248
+ * What the lock is checked for. `call` (the default): one call, and the
249
+ * escrow is remembered so it pays for no other. `session-call`: a call of a
250
+ * session (`MeteredSessionLedger`), which itself claims the escrow and orders
251
+ * the calls, so nothing is remembered here; a refund window too short for
252
+ * another call is reported as `session_window_closing`. `session-settle`:
253
+ * reading the lock back to settle a session's calls already served, so
254
+ * neither the refund window left nor the replay store is consulted; every
255
+ * other check still applies.
256
+ */
257
+ purpose?: 'call' | 'session-call' | 'session-settle';
258
+ /**
259
+ * `session-settle` only: when neither the account that funded the lock nor
260
+ * the payer's associated token account can take the unused part, let the
261
+ * settle create the associated account at the provider's cost. Default
262
+ * false, so the provider decides, and can bound, what it pays for.
263
+ */
264
+ createRefundAccount?: boolean;
265
+ }): Promise<VerifiedLock>;
266
+ /** The replay-store key that marks an escrow as taken, by a single call or by a session's first call. */
267
+ export declare function meteredEscrowReplayKey(escrow: PublicKey): string;
268
+ /** Token counts from an OpenAI-style usage report, or the estimate from the text when it reports none. */
269
+ export declare function usageFrom(upstream: Record<string, unknown>, inputEstimate: number): TokenCounts;
270
+ /**
271
+ * The settle for the tokens used, never above the locked maximum. It pays
272
+ * into the accounts checked with the lock (`lock.payout`), or into `payout`
273
+ * when the caller has checked them again. Nothing is created unless that
274
+ * check chose to create the buyer's token account. The settle names the
275
+ * escrow by its lock slot (`lock.createdSlot`) after its data, and a rated
276
+ * lock's settle carries the escrow's rating account after the usual accounts.
277
+ */
278
+ export declare function meteredSettlement(terms: MeteredTerms, lock: Extract<VerifiedLock, {
279
+ ok: true;
280
+ }>, usage: TokenCounts, payout?: PayoutAccounts): {
281
+ settlement: MeteredSettlement;
282
+ instruction: TransactionInstruction;
283
+ instructions: TransactionInstruction[];
284
+ };
285
+ /** One token account's balance before and after a transaction, in base units. */
286
+ export interface TokenBalanceChange {
287
+ account: string;
288
+ mint: string;
289
+ before: bigint;
290
+ after: bigint;
291
+ }
292
+ /** A top-level instruction as read back from the chain: its program, its accounts in order, and its data in base64. */
293
+ export interface RecordedInstruction {
294
+ programId: string;
295
+ accounts: string[];
296
+ data: string;
297
+ }
298
+ /** What a confirmed transaction did, as read back from the chain. */
299
+ export interface SettlementRecord {
300
+ failed: boolean;
301
+ /** Programs its instructions called. */
302
+ programIds: string[];
303
+ /** Every account it named. */
304
+ accounts: string[];
305
+ tokenBalances: TokenBalanceChange[];
306
+ /** Its top-level instructions. Needed when the settle instruction itself is checked (`expected.instruction`). */
307
+ instructions?: RecordedInstruction[];
308
+ }
309
+ /** The form a settle instruction is recorded and compared in. */
310
+ export declare function recordedInstruction(instruction: TransactionInstruction): RecordedInstruction;
311
+ /**
312
+ * True when the transaction calls the escrow program exactly once, with
313
+ * exactly `expected`: the same accounts in the same order and the same data.
314
+ * So the credits read from its balances are this settle's, not another
315
+ * instruction's.
316
+ */
317
+ export declare function transactionHasOnlyInstruction(record: SettlementRecord, expected: RecordedInstruction): boolean;
318
+ export type ConfirmedSettlement = {
319
+ ok: true;
320
+ /** What left the lock for the provider and the treasury together: the amount billed. */
321
+ paidBaseUnits: bigint;
322
+ feeBaseUnits: bigint;
323
+ providerBaseUnits: bigint;
324
+ /** The buyer's own unused part: the maximum less the amount billed. */
325
+ refundedBaseUnits: bigint;
326
+ /** Anything returned to the buyer above that, for example tokens someone else sent to the vault. */
327
+ surplusBaseUnits: bigint;
328
+ } | {
329
+ ok: false;
330
+ reason: 'not_found' | 'failed' | 'wrong_transaction' | 'amounts_do_not_add_up';
331
+ };
332
+ /**
333
+ * The amounts a settle actually moved, from the confirmed transaction: it
334
+ * must have succeeded, called the escrow program and named this escrow (and,
335
+ * when `expected.rating` is given, that rating account: pass
336
+ * `meteredRatingAccount(lock)` for a rated lock). Accounts the transaction
337
+ * names beyond those are not held against it. The
338
+ * provider's credit and the treasury's fee are read from the balance changes,
339
+ * not from what the provider intended. Refused when the buyer got back less
340
+ * than the maximum less the amount billed, or more was billed than was
341
+ * locked: a receipt cannot state that honestly. A mint that charges a
342
+ * non-zero transfer fee would land here on every settle, since each transfer
343
+ * arrives short; the accepted Token-2022 mints are watched to stay at zero.
344
+ */
345
+ export declare function confirmMeteredSettlement(record: SettlementRecord | null, expected: {
346
+ programId: PublicKey;
347
+ escrow: PublicKey;
348
+ mint: PublicKey;
349
+ destination: PublicKey;
350
+ treasuryToken: PublicKey;
351
+ refundTo: PublicKey;
352
+ maxBaseUnits: bigint;
353
+ rating?: PublicKey;
354
+ instruction?: RecordedInstruction;
355
+ }): ConfirmedSettlement;
356
+ /**
357
+ * Declines a verified lock the provider will not serve, for example when the
358
+ * model failed before any work was done: the payee may refund the whole
359
+ * amount to the payer at any time. The program sends a decline to the source
360
+ * account the lock recorded, which the lock check found usable. Returns the
361
+ * instruction for the operator to sign with the provider wallet. The decline
362
+ * of a rated lock carries the rating account, which the program closes: a
363
+ * job that was not paid is not rated.
364
+ */
365
+ export declare function meteredDecline(terms: MeteredTerms, lock: Extract<VerifiedLock, {
366
+ ok: true;
367
+ }>): TransactionInstruction;
368
+ /** The rating account a rated lock's settle and decline carry, or undefined for a lock that is not rated. */
369
+ export declare function meteredRatingAccount(lock: Extract<VerifiedLock, {
370
+ ok: true;
371
+ }>): PublicKey | undefined;