@net-protocol/relay 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.
@@ -0,0 +1,458 @@
1
+ import { Address, LocalAccount } from 'viem/accounts';
2
+ import { Address as Address$1, Hash, PublicClient } from 'viem';
3
+ import { WriteTransactionConfig } from '@net-protocol/core';
4
+
5
+ /**
6
+ * Create a relay session token
7
+ *
8
+ * Signs an EIP-712 message proving ownership of operatorAddress
9
+ * and receives a sessionToken that can be reused for multiple batch requests.
10
+ *
11
+ * @param params - Session creation parameters
12
+ * @returns Session token and expiration timestamp
13
+ * @throws Error if session creation fails
14
+ */
15
+ declare function createRelaySession(params: {
16
+ apiUrl: string;
17
+ chainId: number;
18
+ operatorAddress: Address;
19
+ secretKey: string;
20
+ account: LocalAccount;
21
+ expiresIn?: number;
22
+ }): Promise<{
23
+ sessionToken: string;
24
+ expiresAt: number;
25
+ }>;
26
+
27
+ /**
28
+ * Error response from API endpoints
29
+ */
30
+ interface ErrorResponse {
31
+ success: false;
32
+ error: string;
33
+ }
34
+ /**
35
+ * Response from /api/relay/[chainId]/fund endpoint
36
+ */
37
+ interface FundResponse {
38
+ success: boolean;
39
+ message?: string;
40
+ payer?: Address$1;
41
+ amount?: string;
42
+ error?: string;
43
+ }
44
+ /**
45
+ * Response from /api/relay/fund/verify endpoint
46
+ */
47
+ interface VerifyFundResponse {
48
+ success: boolean;
49
+ paymentTxHash?: Hash;
50
+ backendWalletAddress?: Address$1;
51
+ fundedAmountEth?: string;
52
+ transactionHash?: Hash;
53
+ alreadyProcessed?: boolean;
54
+ message?: string;
55
+ error?: string;
56
+ }
57
+ /**
58
+ * Response from /api/relay/submit endpoint
59
+ */
60
+ interface SubmitResponse {
61
+ success: boolean;
62
+ transactionHashes: Hash[];
63
+ successfulIndexes: number[];
64
+ failedIndexes: number[];
65
+ errors: {
66
+ index: number;
67
+ error: string;
68
+ }[];
69
+ backendWalletAddress: Address$1;
70
+ appFeeTransactionHash: Hash;
71
+ error?: string;
72
+ }
73
+ /**
74
+ * Response from /api/relay/session endpoint
75
+ */
76
+ interface CreateSessionResponse {
77
+ success: boolean;
78
+ sessionToken?: string;
79
+ expiresAt?: number;
80
+ error?: string;
81
+ }
82
+ /**
83
+ * Response from /api/relay/balance endpoint
84
+ */
85
+ interface BalanceResponse {
86
+ success: boolean;
87
+ backendWalletAddress: Address$1;
88
+ balanceWei: string;
89
+ balanceEth: string;
90
+ sufficientBalance: boolean;
91
+ minRequiredWei: string;
92
+ minRequiredEth: string;
93
+ error?: string;
94
+ }
95
+ /**
96
+ * Result of funding backend wallet
97
+ */
98
+ interface RelayFundResult {
99
+ paymentTxHash: Hash;
100
+ backendWalletAddress: Address$1;
101
+ }
102
+ /**
103
+ * Result of submitting transactions via relay
104
+ */
105
+ interface RelaySubmitResult {
106
+ transactionHashes: Hash[];
107
+ successfulIndexes: number[];
108
+ failedIndexes: number[];
109
+ errors: {
110
+ index: number;
111
+ error: string;
112
+ }[];
113
+ backendWalletAddress: Address$1;
114
+ appFeeTransactionHash: Hash;
115
+ }
116
+ /**
117
+ * Configuration for retry logic
118
+ */
119
+ interface RetryConfig {
120
+ maxRetries?: number;
121
+ initialDelay?: number;
122
+ maxDelay?: number;
123
+ backoffMultiplier?: number;
124
+ }
125
+ /**
126
+ * Parameters for funding backend wallet
127
+ */
128
+ interface FundBackendWalletParams {
129
+ apiUrl: string;
130
+ chainId: number;
131
+ operatorAddress: Address$1;
132
+ secretKey: string;
133
+ fetchWithPayment: typeof fetch;
134
+ httpClient: {
135
+ getPaymentSettleResponse: (getHeader: (name: string) => string | null) => {
136
+ transaction?: string;
137
+ txHash?: string;
138
+ } | null;
139
+ };
140
+ }
141
+ /**
142
+ * Parameters for submitting transactions via relay
143
+ */
144
+ interface SubmitTransactionsViaRelayParams {
145
+ apiUrl: string;
146
+ chainId: number;
147
+ operatorAddress: Address$1;
148
+ secretKey: string;
149
+ transactions: WriteTransactionConfig[];
150
+ sessionToken: string;
151
+ }
152
+ /**
153
+ * Parameters for retrying failed transactions
154
+ */
155
+ interface RetryFailedTransactionsParams {
156
+ apiUrl: string;
157
+ chainId: number;
158
+ operatorAddress: Address$1;
159
+ secretKey: string;
160
+ failedIndexes: number[];
161
+ originalTransactions: WriteTransactionConfig[];
162
+ backendWalletAddress: Address$1;
163
+ config?: RetryConfig;
164
+ sessionToken: string;
165
+ recheckFunction?: (failedIndexes: number[], transactions: WriteTransactionConfig[], backendWalletAddress: Address$1) => Promise<number[]>;
166
+ }
167
+ /**
168
+ * Parameters for waiting for transaction confirmations
169
+ */
170
+ interface WaitForConfirmationsParams {
171
+ publicClient: PublicClient;
172
+ transactionHashes: Hash[];
173
+ confirmations?: number;
174
+ timeout?: number;
175
+ onProgress?: (confirmed: number, total: number) => void;
176
+ }
177
+ /**
178
+ * Result of waiting for transaction confirmations
179
+ */
180
+ interface ConfirmationResult {
181
+ hash: Hash;
182
+ receipt: any;
183
+ }
184
+ /**
185
+ * Parameters for checking backend wallet balance
186
+ */
187
+ interface CheckBackendWalletBalanceParams {
188
+ apiUrl: string;
189
+ chainId: number;
190
+ operatorAddress: Address$1;
191
+ secretKey: string;
192
+ }
193
+ /**
194
+ * Result of checking backend wallet balance
195
+ */
196
+ interface CheckBalanceResult {
197
+ backendWalletAddress: Address$1;
198
+ balanceWei: string;
199
+ balanceEth: string;
200
+ sufficientBalance: boolean;
201
+ minRequiredWei: string;
202
+ minRequiredEth: string;
203
+ }
204
+ /**
205
+ * Result of creating x402 client
206
+ */
207
+ interface X402ClientResult {
208
+ fetchWithPayment: typeof fetch;
209
+ httpClient: {
210
+ getPaymentSettleResponse: (getHeader: (name: string) => string | null) => {
211
+ transaction?: string;
212
+ txHash?: string;
213
+ } | null;
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Check backend wallet balance via relay service
219
+ *
220
+ * This function:
221
+ * 1. Calls /api/relay/balance with operatorAddress and secretKey
222
+ * 2. Returns balance information including sufficientBalance flag
223
+ *
224
+ * @param params - Balance check parameters
225
+ * @returns Result with balance information
226
+ * @throws Error if balance check fails
227
+ */
228
+ declare function checkBackendWalletBalance(params: CheckBackendWalletBalanceParams): Promise<CheckBalanceResult>;
229
+
230
+ /**
231
+ * Fund backend wallet via x402 relay service
232
+ *
233
+ * This function:
234
+ * 1. Calls /api/relay/[chainId]/fund with x402 payment (using fetchWithPayment)
235
+ * 2. Extracts paymentTxHash from X-PAYMENT-RESPONSE header
236
+ * 3. Waits for payment confirmation (2 seconds)
237
+ * 4. Calls /api/relay/fund/verify to get backendWalletAddress
238
+ * 5. Returns { paymentTxHash, backendWalletAddress }
239
+ *
240
+ * @param params - Funding parameters
241
+ * @returns Result with paymentTxHash and backendWalletAddress
242
+ * @throws Error if funding fails
243
+ */
244
+ declare function fundBackendWallet(params: FundBackendWalletParams): Promise<RelayFundResult>;
245
+
246
+ /**
247
+ * Submit transactions via relay service
248
+ *
249
+ * Calls /api/relay/submit with transactions and returns result
250
+ * with success/failure tracking by index.
251
+ *
252
+ * @param params - Submission parameters
253
+ * @returns Result with transaction hashes and success/failure tracking
254
+ * @throws Error if submission fails
255
+ */
256
+ declare function submitTransactionsViaRelay(params: SubmitTransactionsViaRelayParams): Promise<RelaySubmitResult>;
257
+
258
+ /**
259
+ * Retry failed transactions with exponential backoff
260
+ *
261
+ * This function:
262
+ * 1. Extracts failed transactions by index from RelaySubmitResult
263
+ * 2. Optionally re-checks on-chain before retry (via recheckFunction)
264
+ * 3. Retries with exponential backoff
265
+ * 4. Handles nested retries
266
+ *
267
+ * @param params - Retry parameters
268
+ * @returns Final success/failure status after retries
269
+ */
270
+ declare function retryFailedTransactions(params: RetryFailedTransactionsParams): Promise<RelaySubmitResult>;
271
+
272
+ /**
273
+ * Estimate the size of a serialized transaction config in bytes
274
+ *
275
+ * Storage transactions can be large due to:
276
+ * - Large args arrays (chunk data)
277
+ * - Hex-encoded data in args
278
+ * - ABI structure overhead
279
+ *
280
+ * We use a conservative estimate of 100KB per transaction to ensure we stay under the 1MB limit.
281
+ * With 100KB per transaction, we can fit ~9 transactions per batch (900KB / 100KB).
282
+ */
283
+ declare function estimateTransactionSize(tx: WriteTransactionConfig): number;
284
+ /**
285
+ * Estimate the total request size for a batch of transactions
286
+ */
287
+ declare function estimateRequestSize(transactions: WriteTransactionConfig[]): number;
288
+ /**
289
+ * Batch transactions into groups that respect count and size limits
290
+ *
291
+ * With 100KB per transaction estimate:
292
+ * - Size limit: ~9 transactions per batch (900KB / 100KB)
293
+ * - Count limit: 100 transactions per batch
294
+ * - Size limit is the constraining factor for large transactions
295
+ */
296
+ declare function batchTransactions(transactions: WriteTransactionConfig[]): WriteTransactionConfig[][];
297
+
298
+ /**
299
+ * Wait for transaction confirmations
300
+ *
301
+ * Uses waitForTransactionReceipt() from viem/actions to wait for
302
+ * multiple transactions in parallel. Handles timeouts and tracks progress.
303
+ *
304
+ * @param params - Confirmation parameters
305
+ * @returns Array of transaction receipts
306
+ * @throws Error if timeout occurs or transaction fails
307
+ */
308
+ declare function waitForConfirmations(params: WaitForConfirmationsParams): Promise<ConfirmationResult[]>;
309
+
310
+ /**
311
+ * Create x402 client for relay payments
312
+ *
313
+ * Sets up x402Client with user's account, registers EVM scheme,
314
+ * and returns wrapped fetch function and HTTP client for header extraction.
315
+ *
316
+ * @param account - User's local account (from privateKeyToAccount)
317
+ * @param chainId - Chain ID (optional, for logging purposes)
318
+ * @returns Object with fetchWithPayment and httpClient
319
+ */
320
+ declare function createRelayX402Client(account: LocalAccount, chainId?: number): X402ClientResult;
321
+
322
+ /**
323
+ * High-level client for Net Relay Service
324
+ *
325
+ * Provides a convenient class-based API that stores apiUrl and chainId,
326
+ * reducing boilerplate when making multiple relay calls.
327
+ */
328
+ declare class RelayClient {
329
+ private apiUrl;
330
+ private chainId;
331
+ constructor(options: {
332
+ apiUrl: string;
333
+ chainId: number;
334
+ });
335
+ /**
336
+ * Create a relay session token
337
+ *
338
+ * @param params - Session creation parameters (apiUrl and chainId are already set)
339
+ * @returns Session token and expiration timestamp
340
+ */
341
+ createSession(params: {
342
+ operatorAddress: Address;
343
+ secretKey: string;
344
+ account: LocalAccount;
345
+ expiresIn?: number;
346
+ }): Promise<{
347
+ sessionToken: string;
348
+ expiresAt: number;
349
+ }>;
350
+ /**
351
+ * Check backend wallet balance
352
+ *
353
+ * @param params - Balance check parameters (apiUrl and chainId are already set)
354
+ * @returns Result with balance information
355
+ */
356
+ checkBalance(params: {
357
+ operatorAddress: Address;
358
+ secretKey: string;
359
+ }): Promise<CheckBalanceResult>;
360
+ /**
361
+ * Fund backend wallet via x402 payment
362
+ *
363
+ * @param params - Funding parameters (apiUrl and chainId are already set)
364
+ * @returns Result with paymentTxHash and backendWalletAddress
365
+ */
366
+ fundBackendWallet(params: {
367
+ operatorAddress: Address;
368
+ secretKey: string;
369
+ fetchWithPayment: typeof fetch;
370
+ httpClient: FundBackendWalletParams["httpClient"];
371
+ }): Promise<RelayFundResult>;
372
+ /**
373
+ * Submit transactions via relay
374
+ *
375
+ * @param params - Submission parameters (apiUrl and chainId are already set)
376
+ * @returns Result with transaction hashes and success/failure tracking
377
+ */
378
+ submitTransactions(params: {
379
+ operatorAddress: Address;
380
+ secretKey: string;
381
+ transactions: WriteTransactionConfig[];
382
+ sessionToken: string;
383
+ }): Promise<RelaySubmitResult>;
384
+ /**
385
+ * Retry failed transactions with exponential backoff
386
+ *
387
+ * @param params - Retry parameters (apiUrl and chainId are already set)
388
+ * @returns Final success/failure status after retries
389
+ */
390
+ retryFailedTransactions(params: {
391
+ operatorAddress: Address;
392
+ secretKey: string;
393
+ failedIndexes: number[];
394
+ originalTransactions: WriteTransactionConfig[];
395
+ backendWalletAddress: Address;
396
+ config?: RetryConfig;
397
+ sessionToken: string;
398
+ recheckFunction?: RetryFailedTransactionsParams["recheckFunction"];
399
+ }): Promise<RelaySubmitResult>;
400
+ /**
401
+ * Create x402 client for relay payments
402
+ *
403
+ * @param account - User's local account
404
+ * @returns Object with fetchWithPayment and httpClient
405
+ */
406
+ createX402Client(account: LocalAccount): X402ClientResult;
407
+ }
408
+
409
+ /**
410
+ * EIP-712 domain name for relay session signing
411
+ */
412
+ declare const RELAY_DOMAIN_NAME = "Net Relay Service";
413
+ /**
414
+ * EIP-712 domain version for relay session signing
415
+ */
416
+ declare const RELAY_DOMAIN_VERSION = "1";
417
+ /**
418
+ * EIP-712 types for relay session signing
419
+ */
420
+ declare const RELAY_SESSION_TYPES: {
421
+ readonly RelaySession: readonly [{
422
+ readonly name: "operatorAddress";
423
+ readonly type: "address";
424
+ }, {
425
+ readonly name: "secretKeyHash";
426
+ readonly type: "bytes32";
427
+ }, {
428
+ readonly name: "expiresAt";
429
+ readonly type: "uint256";
430
+ }];
431
+ };
432
+ /**
433
+ * Default retry configuration
434
+ */
435
+ declare const DEFAULT_RETRY_CONFIG: Required<RetryConfig>;
436
+ /**
437
+ * Default number of confirmations to wait for
438
+ */
439
+ declare const DEFAULT_CONFIRMATIONS = 1;
440
+ /**
441
+ * Default timeout for waiting for transaction confirmations (milliseconds)
442
+ */
443
+ declare const DEFAULT_TIMEOUT = 60000;
444
+ /**
445
+ * Maximum transactions per batch (matches server limit)
446
+ */
447
+ declare const MAX_TRANSACTIONS_PER_BATCH = 100;
448
+ /**
449
+ * Maximum request size in bytes (slightly under 1MB for safety margin)
450
+ */
451
+ declare const MAX_BATCH_SIZE_BYTES: number;
452
+ /**
453
+ * Maximum size per transaction in bytes
454
+ * Storage transactions can include large data chunks, so we assume up to 100KB per transaction
455
+ */
456
+ declare const MAX_TRANSACTION_SIZE_BYTES: number;
457
+
458
+ export { type BalanceResponse, type CheckBackendWalletBalanceParams, type CheckBalanceResult, type ConfirmationResult, type CreateSessionResponse, DEFAULT_CONFIRMATIONS, DEFAULT_RETRY_CONFIG, DEFAULT_TIMEOUT, type ErrorResponse, type FundBackendWalletParams, type FundResponse, MAX_BATCH_SIZE_BYTES, MAX_TRANSACTIONS_PER_BATCH, MAX_TRANSACTION_SIZE_BYTES, RELAY_DOMAIN_NAME, RELAY_DOMAIN_VERSION, RELAY_SESSION_TYPES, RelayClient, type RelayFundResult, type RelaySubmitResult, type RetryConfig, type RetryFailedTransactionsParams, type SubmitResponse, type SubmitTransactionsViaRelayParams, type VerifyFundResponse, type WaitForConfirmationsParams, type X402ClientResult, batchTransactions, checkBackendWalletBalance, createRelaySession, createRelayX402Client, estimateRequestSize, estimateTransactionSize, fundBackendWallet, retryFailedTransactions, submitTransactionsViaRelay, waitForConfirmations };