@t402/core 2.0.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 (66) hide show
  1. package/README.md +293 -0
  2. package/dist/cjs/client/index.d.ts +103 -0
  3. package/dist/cjs/client/index.js +510 -0
  4. package/dist/cjs/client/index.js.map +1 -0
  5. package/dist/cjs/facilitator/index.d.ts +192 -0
  6. package/dist/cjs/facilitator/index.js +398 -0
  7. package/dist/cjs/facilitator/index.js.map +1 -0
  8. package/dist/cjs/http/index.d.ts +52 -0
  9. package/dist/cjs/http/index.js +763 -0
  10. package/dist/cjs/http/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +3 -0
  12. package/dist/cjs/index.js +31 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/mechanisms-CmrqNl1M.d.ts +238 -0
  15. package/dist/cjs/mechanisms-DsJn3ZiM.d.ts +238 -0
  16. package/dist/cjs/server/index.d.ts +2 -0
  17. package/dist/cjs/server/index.js +1241 -0
  18. package/dist/cjs/server/index.js.map +1 -0
  19. package/dist/cjs/t402HTTPClient-m6cjzTek.d.ts +243 -0
  20. package/dist/cjs/t402HTTPResourceServer-B-xmYMwj.d.ts +719 -0
  21. package/dist/cjs/t402HTTPResourceServer-Bcfxp2UO.d.ts +719 -0
  22. package/dist/cjs/types/index.d.ts +1 -0
  23. package/dist/cjs/types/index.js +19 -0
  24. package/dist/cjs/types/index.js.map +1 -0
  25. package/dist/cjs/types/v1/index.d.ts +1 -0
  26. package/dist/cjs/types/v1/index.js +19 -0
  27. package/dist/cjs/types/v1/index.js.map +1 -0
  28. package/dist/cjs/utils/index.d.ts +48 -0
  29. package/dist/cjs/utils/index.js +108 -0
  30. package/dist/cjs/utils/index.js.map +1 -0
  31. package/dist/esm/chunk-3IUBYRYG.mjs +78 -0
  32. package/dist/esm/chunk-3IUBYRYG.mjs.map +1 -0
  33. package/dist/esm/chunk-3VTYR43U.mjs +7 -0
  34. package/dist/esm/chunk-3VTYR43U.mjs.map +1 -0
  35. package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
  36. package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
  37. package/dist/esm/chunk-D5DYKKCZ.mjs +722 -0
  38. package/dist/esm/chunk-D5DYKKCZ.mjs.map +1 -0
  39. package/dist/esm/client/index.d.mts +103 -0
  40. package/dist/esm/client/index.mjs +356 -0
  41. package/dist/esm/client/index.mjs.map +1 -0
  42. package/dist/esm/facilitator/index.d.mts +192 -0
  43. package/dist/esm/facilitator/index.mjs +373 -0
  44. package/dist/esm/facilitator/index.mjs.map +1 -0
  45. package/dist/esm/http/index.d.mts +52 -0
  46. package/dist/esm/http/index.mjs +28 -0
  47. package/dist/esm/http/index.mjs.map +1 -0
  48. package/dist/esm/index.d.mts +3 -0
  49. package/dist/esm/index.mjs +8 -0
  50. package/dist/esm/index.mjs.map +1 -0
  51. package/dist/esm/mechanisms-CmrqNl1M.d.mts +238 -0
  52. package/dist/esm/server/index.d.mts +2 -0
  53. package/dist/esm/server/index.mjs +562 -0
  54. package/dist/esm/server/index.mjs.map +1 -0
  55. package/dist/esm/t402HTTPClient-C285YGCp.d.mts +243 -0
  56. package/dist/esm/t402HTTPResourceServer-k_l3d8ua.d.mts +719 -0
  57. package/dist/esm/types/index.d.mts +1 -0
  58. package/dist/esm/types/index.mjs +1 -0
  59. package/dist/esm/types/index.mjs.map +1 -0
  60. package/dist/esm/types/v1/index.d.mts +1 -0
  61. package/dist/esm/types/v1/index.mjs +1 -0
  62. package/dist/esm/types/v1/index.mjs.map +1 -0
  63. package/dist/esm/utils/index.d.mts +48 -0
  64. package/dist/esm/utils/index.mjs +20 -0
  65. package/dist/esm/utils/index.mjs.map +1 -0
  66. package/package.json +129 -0
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # @t402/core
2
+
3
+ Core implementation of the t402 payment protocol for TypeScript/JavaScript applications. Provides transport-agnostic client, server and facilitator components.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm install @t402/core
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### Client Usage
14
+
15
+ ```typescript
16
+ import { t402Client } from '@t402/core/client';
17
+ import { t402HTTPClient } from '@t402/core/http';
18
+ import { ExactEvmScheme } from '@t402/evm/exact/client';
19
+
20
+ // Create core client and register payment schemes
21
+ const coreClient = new t402Client()
22
+ .register('eip155:*', new ExactEvmScheme(evmSigner));
23
+
24
+ // Wrap with HTTP client for header encoding/decoding
25
+ const client = new t402HTTPClient(coreClient);
26
+
27
+ // Make a request
28
+ const response = await fetch('https://api.example.com/protected');
29
+
30
+ if (response.status === 402) {
31
+ // Extract payment requirements from response
32
+ const paymentRequired = client.getPaymentRequiredResponse(
33
+ (name) => response.headers.get(name),
34
+ await response.json()
35
+ );
36
+
37
+ // Create and send payment
38
+ const paymentPayload = await client.createPaymentPayload(paymentRequired);
39
+
40
+ const paidResponse = await fetch('https://api.example.com/protected', {
41
+ headers: client.encodePaymentSignatureHeader(paymentPayload),
42
+ });
43
+
44
+ // Get settlement confirmation
45
+ const settlement = client.getPaymentSettleResponse(
46
+ (name) => paidResponse.headers.get(name)
47
+ );
48
+ console.log('Transaction:', settlement.transaction);
49
+ }
50
+ ```
51
+
52
+ ### Server Usage
53
+
54
+ ```typescript
55
+ import { t402ResourceServer, HTTPFacilitatorClient } from '@t402/core/server';
56
+ import { t402HTTPResourceServer } from '@t402/core/http';
57
+ import { ExactEvmScheme } from '@t402/evm/exact/server';
58
+
59
+ // Connect to facilitator
60
+ const facilitatorClient = new HTTPFacilitatorClient({
61
+ url: 'https://t402.org/facilitator',
62
+ });
63
+
64
+ // Create resource server with payment schemes
65
+ const resourceServer = new t402ResourceServer(facilitatorClient)
66
+ .register('eip155:*', new ExactEvmScheme());
67
+
68
+ // Initialize (fetches supported kinds from facilitator)
69
+ await resourceServer.initialize();
70
+
71
+ // Configure routes with payment requirements
72
+ const routes = {
73
+ 'GET /api/data': {
74
+ accepts: {
75
+ scheme: 'exact',
76
+ network: 'eip155:8453',
77
+ payTo: '0xYourAddress',
78
+ price: '$0.01',
79
+ },
80
+ description: 'Premium data access',
81
+ mimeType: 'application/json',
82
+ },
83
+ };
84
+
85
+ // Create HTTP server wrapper
86
+ const httpServer = new t402HTTPResourceServer(resourceServer, routes);
87
+ ```
88
+
89
+ ### Facilitator Usage
90
+
91
+ ```typescript
92
+ import { t402Facilitator } from '@t402/core/facilitator';
93
+ import { registerExactEvmScheme } from '@t402/evm/exact/facilitator';
94
+
95
+ const facilitator = new t402Facilitator();
96
+
97
+ // Register scheme implementations using helper
98
+ registerExactEvmScheme(facilitator, {
99
+ signer: evmSigner,
100
+ networks: 'eip155:84532',
101
+ });
102
+
103
+ // Verify payment
104
+ const verifyResult = await facilitator.verify(paymentPayload, paymentRequirements);
105
+
106
+ if (verifyResult.isValid) {
107
+ // Settle payment
108
+ const settleResult = await facilitator.settle(paymentPayload, paymentRequirements);
109
+ console.log('Transaction:', settleResult.transaction);
110
+ }
111
+ ```
112
+
113
+ ## Route Configuration
114
+
115
+ Routes use the `accepts` field to define payment options:
116
+
117
+ ```typescript
118
+ const routes = {
119
+ // Single payment option
120
+ 'GET /api/data': {
121
+ accepts: {
122
+ scheme: 'exact',
123
+ network: 'eip155:8453',
124
+ payTo: '0xAddress',
125
+ price: '$0.01',
126
+ },
127
+ description: 'Data endpoint',
128
+ mimeType: 'application/json',
129
+ },
130
+
131
+ // Multiple payment options (EVM + SVM)
132
+ 'POST /api/*': {
133
+ accepts: [
134
+ {
135
+ scheme: 'exact',
136
+ network: 'eip155:8453',
137
+ payTo: evmAddress,
138
+ price: '$0.05',
139
+ },
140
+ {
141
+ scheme: 'exact',
142
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
143
+ payTo: svmAddress,
144
+ price: '$0.05',
145
+ },
146
+ ],
147
+ },
148
+ };
149
+ ```
150
+
151
+ ## Client Configuration
152
+
153
+ Use `fromConfig()` for declarative setup:
154
+
155
+ ```typescript
156
+ const client = t402Client.fromConfig({
157
+ schemes: [
158
+ { network: 'eip155:8453', client: new ExactEvmScheme(evmSigner) },
159
+ { network: 'solana:mainnet', client: new ExactSvmScheme(svmSigner) },
160
+ ],
161
+ policies: [
162
+ // Filter by max price
163
+ (version, reqs) => reqs.filter(r => BigInt(r.amount) < BigInt('1000000')),
164
+ ],
165
+ });
166
+ ```
167
+
168
+ ## Lifecycle Hooks
169
+
170
+ ### Client Hooks
171
+
172
+ ```typescript
173
+ client
174
+ .onBeforePaymentCreation(async (ctx) => {
175
+ console.log('Creating payment for:', ctx.selectedRequirements.network);
176
+ // Return { abort: true, reason: '...' } to cancel
177
+ })
178
+ .onAfterPaymentCreation(async (ctx) => {
179
+ console.log('Payment created:', ctx.paymentPayload);
180
+ })
181
+ .onPaymentCreationFailure(async (ctx) => {
182
+ console.error('Payment failed:', ctx.error);
183
+ // Return { recovered: true, payload: ... } to recover
184
+ });
185
+ ```
186
+
187
+ ### Server Hooks
188
+
189
+ ```typescript
190
+ resourceServer
191
+ .onBeforeVerify(async (ctx) => { /* ... */ })
192
+ .onAfterVerify(async (ctx) => { /* ... */ })
193
+ .onBeforeSettle(async (ctx) => { /* ... */ })
194
+ .onAfterSettle(async (ctx) => { /* ... */ });
195
+ ```
196
+
197
+ ### Facilitator Hooks
198
+
199
+ ```typescript
200
+ facilitator
201
+ .onBeforeVerify(async (ctx) => { console.log('Before verify', ctx); })
202
+ .onAfterVerify(async (ctx) => { console.log('After verify', ctx); })
203
+ .onVerifyFailure(async (ctx) => { console.log('Verify failure', ctx); })
204
+ .onBeforeSettle(async (ctx) => { console.log('Before settle', ctx); })
205
+ .onAfterSettle(async (ctx) => { console.log('After settle', ctx); })
206
+ .onSettleFailure(async (ctx) => { console.log('Settle failure', ctx); });
207
+ ```
208
+
209
+ ## HTTP Headers
210
+
211
+ ### v2 Protocol (Current)
212
+
213
+ | Header | Description |
214
+ |--------|-------------|
215
+ | `PAYMENT-SIGNATURE` | Base64-encoded payment payload |
216
+ | `PAYMENT-REQUIRED` | Base64-encoded payment requirements |
217
+ | `PAYMENT-RESPONSE` | Base64-encoded settlement response |
218
+
219
+ ### v1 Protocol (Legacy)
220
+
221
+ | Header | Description |
222
+ |--------|-------------|
223
+ | `X-PAYMENT` | Base64-encoded payment payload |
224
+ | `X-PAYMENT-RESPONSE` | Base64-encoded settlement response |
225
+
226
+ ## Network Pattern Matching
227
+
228
+ Register handlers for network families using wildcards:
229
+
230
+ ```typescript
231
+ // All EVM networks
232
+ server.register('eip155:*', new ExactEvmScheme());
233
+
234
+ // Specific network takes precedence
235
+ server.register('eip155:8453', new ExactEvmScheme());
236
+ ```
237
+
238
+ ## Types
239
+
240
+ ```typescript
241
+ type Network = `${string}:${string}`; // e.g., "eip155:8453"
242
+
243
+ type PaymentRequirements = {
244
+ scheme: string;
245
+ network: Network;
246
+ asset: string;
247
+ amount: string;
248
+ payTo: string;
249
+ maxTimeoutSeconds: number;
250
+ extra: Record<string, unknown>;
251
+ };
252
+
253
+ type PaymentPayload = {
254
+ t402Version: number;
255
+ resource: ResourceInfo;
256
+ accepted: PaymentRequirements;
257
+ payload: Record<string, unknown>;
258
+ extensions?: Record<string, unknown>;
259
+ };
260
+
261
+ type PaymentRequired = {
262
+ t402Version: number;
263
+ error?: string;
264
+ resource: ResourceInfo;
265
+ accepts: PaymentRequirements[];
266
+ extensions?: Record<string, unknown>;
267
+ };
268
+ ```
269
+
270
+ ## Framework Integration
271
+
272
+ For framework-specific middleware, use:
273
+
274
+ - `@t402/express` - Express.js middleware
275
+ - `@t402/hono` - Hono middleware
276
+ - `@t402/next` - Next.js integration
277
+ - `@t402/axios` - Axios interceptor
278
+ - `@t402/fetch` - Fetch wrapper
279
+
280
+ ## Implementation Packages
281
+
282
+ For blockchain-specific implementations:
283
+
284
+ - `@t402/evm` - Ethereum and EVM-compatible chains
285
+ - `@t402/svm` - Solana blockchain
286
+
287
+ ## Examples
288
+
289
+ See the [examples directory](https://github.com/t402-io/t402/tree/main/examples/typescript) for complete examples.
290
+
291
+ ## Contributing
292
+
293
+ Contributions welcome! See [Contributing Guide](https://github.com/t402-io/t402/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,103 @@
1
+ export { A as AfterPaymentCreationHook, B as BeforePaymentCreationHook, O as OnPaymentCreationFailureHook, a as PaymentCreatedContext, P as PaymentCreationContext, b as PaymentCreationFailureContext, c as PaymentPolicy, d as SchemeRegistration, S as SelectPaymentRequirements, e as t402Client, t as t402ClientConfig, f as t402HTTPClient } from '../t402HTTPClient-m6cjzTek.js';
2
+ import { P as PaymentRequirements } from '../mechanisms-CmrqNl1M.js';
3
+
4
+ /**
5
+ * Token Selector Utility for T402 Clients
6
+ *
7
+ * Helps clients select the best payment method from available payment requirements.
8
+ * Prioritizes tokens based on:
9
+ * 1. User token balances
10
+ * 2. Token priority (USDT0 > USDC > legacy tokens)
11
+ * 3. Network gas costs
12
+ */
13
+
14
+ /**
15
+ * User token balance information
16
+ */
17
+ interface UserTokenBalance {
18
+ /** Token contract address */
19
+ asset: string;
20
+ /** Network in CAIP-2 format (e.g., "eip155:42161") */
21
+ network: string;
22
+ /** Token balance in smallest units */
23
+ amount: string;
24
+ /** Token symbol (optional, for display) */
25
+ symbol?: string;
26
+ }
27
+ /**
28
+ * Token priority configuration
29
+ * Lower number = higher priority
30
+ */
31
+ declare const DEFAULT_TOKEN_PRIORITY: Record<string, number>;
32
+ /**
33
+ * Options for token selection
34
+ */
35
+ interface TokenSelectionOptions {
36
+ /** Custom token priorities (overrides defaults) */
37
+ tokenPriority?: Record<string, number>;
38
+ /** Preferred networks (will be prioritized) */
39
+ preferredNetworks?: string[];
40
+ /** Only consider tokens the user has sufficient balance for */
41
+ requireSufficientBalance?: boolean;
42
+ }
43
+ /**
44
+ * Result of token selection
45
+ */
46
+ interface TokenSelectionResult {
47
+ /** The selected payment requirements */
48
+ selected: PaymentRequirements | null;
49
+ /** All valid payment options sorted by priority */
50
+ alternatives: PaymentRequirements[];
51
+ /** Reason if no payment method was selected */
52
+ reason?: string;
53
+ }
54
+ /**
55
+ * Select the best payment method from available requirements
56
+ *
57
+ * @param requirements - Array of payment requirements from the server
58
+ * @param userBalances - Array of user's token balances
59
+ * @param options - Selection options
60
+ * @returns The best payment requirement and alternatives
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const result = selectBestPaymentMethod(
65
+ * paymentRequirements,
66
+ * [
67
+ * { asset: "0x...", network: "eip155:42161", amount: "1000000000" },
68
+ * ],
69
+ * { requireSufficientBalance: true }
70
+ * );
71
+ *
72
+ * if (result.selected) {
73
+ * // Use result.selected for payment
74
+ * }
75
+ * ```
76
+ */
77
+ declare function selectBestPaymentMethod(requirements: PaymentRequirements[], userBalances: UserTokenBalance[], options?: TokenSelectionOptions): TokenSelectionResult;
78
+ /**
79
+ * Check if a payment requirement uses a gasless token (EIP-3009)
80
+ */
81
+ declare function isGaslessPayment(requirement: PaymentRequirements): boolean;
82
+ /**
83
+ * Check if a payment requirement is for USDT0
84
+ */
85
+ declare function isUsdt0Payment(requirement: PaymentRequirements): boolean;
86
+ /**
87
+ * Get payment requirements for a specific token
88
+ */
89
+ declare function filterByToken(requirements: PaymentRequirements[], symbol: string): PaymentRequirements[];
90
+ /**
91
+ * Get payment requirements for a specific network
92
+ */
93
+ declare function filterByNetwork(requirements: PaymentRequirements[], network: string): PaymentRequirements[];
94
+ /**
95
+ * Get all unique networks from payment requirements
96
+ */
97
+ declare function getAvailableNetworks(requirements: PaymentRequirements[]): string[];
98
+ /**
99
+ * Get all unique tokens from payment requirements
100
+ */
101
+ declare function getAvailableTokens(requirements: PaymentRequirements[]): string[];
102
+
103
+ export { DEFAULT_TOKEN_PRIORITY, type TokenSelectionOptions, type TokenSelectionResult, type UserTokenBalance, filterByNetwork, filterByToken, getAvailableNetworks, getAvailableTokens, isGaslessPayment, isUsdt0Payment, selectBestPaymentMethod };