@ckb-ccc/core 1.4.0 → 1.6.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 (109) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/ckb/transaction.d.ts +57 -4
  3. package/dist/ckb/transaction.d.ts.map +1 -1
  4. package/dist/ckb/transaction.js +83 -26
  5. package/dist/client/cache/cache.d.ts +67 -11
  6. package/dist/client/cache/cache.d.ts.map +1 -1
  7. package/dist/client/cache/cache.js +94 -9
  8. package/dist/client/cache/memory.advanced.d.ts +2 -2
  9. package/dist/client/cache/memory.advanced.d.ts.map +1 -1
  10. package/dist/client/cache/memory.advanced.js +19 -7
  11. package/dist/client/cache/memory.d.ts +24 -7
  12. package/dist/client/cache/memory.d.ts.map +1 -1
  13. package/dist/client/cache/memory.js +76 -18
  14. package/dist/client/client.d.ts +27 -6
  15. package/dist/client/client.d.ts.map +1 -1
  16. package/dist/client/client.js +113 -22
  17. package/dist/client/clientPublicMainnet.d.ts.map +1 -1
  18. package/dist/client/clientPublicMainnet.js +13 -2
  19. package/dist/client/clientPublicTestnet.d.ts.map +1 -1
  20. package/dist/client/clientPublicTestnet.js +13 -2
  21. package/dist/client/clientTypes.advanced.d.ts +3 -0
  22. package/dist/client/clientTypes.advanced.d.ts.map +1 -1
  23. package/dist/client/clientTypes.advanced.js +3 -0
  24. package/dist/client/clientTypes.d.ts +110 -13
  25. package/dist/client/clientTypes.d.ts.map +1 -1
  26. package/dist/client/clientTypes.js +118 -4
  27. package/dist/client/jsonRpc/client.d.ts +4 -4
  28. package/dist/client/jsonRpc/client.d.ts.map +1 -1
  29. package/dist/client/jsonRpc/client.js +4 -4
  30. package/dist/client/jsonRpc/transformers.js +3 -3
  31. package/dist/jsonRpc/requestor.d.ts +1 -0
  32. package/dist/jsonRpc/requestor.d.ts.map +1 -1
  33. package/dist/jsonRpc/requestor.js +4 -2
  34. package/dist/jsonRpc/transports/advanced.d.ts +1 -0
  35. package/dist/jsonRpc/transports/advanced.d.ts.map +1 -1
  36. package/dist/jsonRpc/transports/advanced.js +1 -0
  37. package/dist/jsonRpc/transports/fallback.d.ts +8 -0
  38. package/dist/jsonRpc/transports/fallback.d.ts.map +1 -0
  39. package/dist/jsonRpc/transports/fallback.js +22 -0
  40. package/dist/jsonRpc/transports/webSocket.d.ts.map +1 -1
  41. package/dist/jsonRpc/transports/webSocket.js +7 -3
  42. package/dist/molecule/predefined.d.ts +10 -10
  43. package/dist/molecule/predefined.d.ts.map +1 -1
  44. package/dist/utils/index.d.ts +4 -0
  45. package/dist/utils/index.d.ts.map +1 -1
  46. package/dist/utils/index.js +13 -1
  47. package/dist.commonjs/advanced.js +17 -7
  48. package/dist.commonjs/ckb/transaction.d.ts +57 -4
  49. package/dist.commonjs/ckb/transaction.d.ts.map +1 -1
  50. package/dist.commonjs/ckb/transaction.js +83 -26
  51. package/dist.commonjs/client/cache/cache.d.ts +67 -11
  52. package/dist.commonjs/client/cache/cache.d.ts.map +1 -1
  53. package/dist.commonjs/client/cache/cache.js +94 -9
  54. package/dist.commonjs/client/cache/memory.advanced.d.ts +2 -2
  55. package/dist.commonjs/client/cache/memory.advanced.d.ts.map +1 -1
  56. package/dist.commonjs/client/cache/memory.advanced.js +19 -7
  57. package/dist.commonjs/client/cache/memory.d.ts +24 -7
  58. package/dist.commonjs/client/cache/memory.d.ts.map +1 -1
  59. package/dist.commonjs/client/cache/memory.js +75 -17
  60. package/dist.commonjs/client/client.d.ts +27 -6
  61. package/dist.commonjs/client/client.d.ts.map +1 -1
  62. package/dist.commonjs/client/client.js +111 -20
  63. package/dist.commonjs/client/clientPublicMainnet.d.ts.map +1 -1
  64. package/dist.commonjs/client/clientPublicMainnet.js +13 -2
  65. package/dist.commonjs/client/clientPublicTestnet.d.ts.map +1 -1
  66. package/dist.commonjs/client/clientPublicTestnet.js +13 -2
  67. package/dist.commonjs/client/clientTypes.advanced.d.ts +3 -0
  68. package/dist.commonjs/client/clientTypes.advanced.d.ts.map +1 -1
  69. package/dist.commonjs/client/clientTypes.advanced.js +4 -0
  70. package/dist.commonjs/client/clientTypes.d.ts +110 -13
  71. package/dist.commonjs/client/clientTypes.d.ts.map +1 -1
  72. package/dist.commonjs/client/clientTypes.js +123 -4
  73. package/dist.commonjs/client/jsonRpc/client.d.ts +4 -4
  74. package/dist.commonjs/client/jsonRpc/client.d.ts.map +1 -1
  75. package/dist.commonjs/client/jsonRpc/client.js +4 -4
  76. package/dist.commonjs/client/jsonRpc/transformers.js +2 -2
  77. package/dist.commonjs/index.js +17 -7
  78. package/dist.commonjs/jsonRpc/requestor.d.ts +1 -0
  79. package/dist.commonjs/jsonRpc/requestor.d.ts.map +1 -1
  80. package/dist.commonjs/jsonRpc/requestor.js +3 -1
  81. package/dist.commonjs/jsonRpc/transports/advanced.d.ts +1 -0
  82. package/dist.commonjs/jsonRpc/transports/advanced.d.ts.map +1 -1
  83. package/dist.commonjs/jsonRpc/transports/advanced.js +1 -0
  84. package/dist.commonjs/jsonRpc/transports/fallback.d.ts +8 -0
  85. package/dist.commonjs/jsonRpc/transports/fallback.d.ts.map +1 -0
  86. package/dist.commonjs/jsonRpc/transports/fallback.js +26 -0
  87. package/dist.commonjs/jsonRpc/transports/webSocket.d.ts.map +1 -1
  88. package/dist.commonjs/jsonRpc/transports/webSocket.js +7 -3
  89. package/dist.commonjs/molecule/index.js +17 -7
  90. package/dist.commonjs/utils/index.d.ts +4 -0
  91. package/dist.commonjs/utils/index.d.ts.map +1 -1
  92. package/dist.commonjs/utils/index.js +13 -0
  93. package/package.json +1 -1
  94. package/src/ckb/transaction.ts +112 -41
  95. package/src/client/cache/cache.ts +126 -13
  96. package/src/client/cache/memory.advanced.ts +24 -7
  97. package/src/client/cache/memory.ts +130 -30
  98. package/src/client/client.ts +170 -27
  99. package/src/client/clientPublicMainnet.ts +14 -2
  100. package/src/client/clientPublicTestnet.ts +14 -2
  101. package/src/client/clientTypes.advanced.ts +4 -0
  102. package/src/client/clientTypes.ts +224 -33
  103. package/src/client/jsonRpc/client.ts +11 -9
  104. package/src/client/jsonRpc/transformers.ts +2 -2
  105. package/src/jsonRpc/requestor.ts +10 -1
  106. package/src/jsonRpc/transports/advanced.ts +1 -0
  107. package/src/jsonRpc/transports/fallback.ts +27 -0
  108. package/src/jsonRpc/transports/webSocket.ts +17 -13
  109. package/src/utils/index.ts +14 -1
@@ -3,6 +3,7 @@ import {
3
3
  CellDep,
4
4
  CellDepLike,
5
5
  Epoch,
6
+ EpochLike,
6
7
  HashType,
7
8
  HashTypeLike,
8
9
  OutPoint,
@@ -10,6 +11,8 @@ import {
10
11
  Script,
11
12
  ScriptLike,
12
13
  Transaction,
14
+ TransactionLike,
15
+ epochFrom,
13
16
  hashTypeFrom,
14
17
  } from "../ckb/index.js";
15
18
  import { Hex, HexLike, hexFrom } from "../hex/index.js";
@@ -67,6 +70,10 @@ export class CellDepInfo {
67
70
  ) {}
68
71
 
69
72
  static from(cellDepInfoLike: CellDepInfoLike): CellDepInfo {
73
+ if (cellDepInfoLike instanceof CellDepInfo) {
74
+ return cellDepInfoLike;
75
+ }
76
+
70
77
  return new CellDepInfo(
71
78
  CellDep.from(cellDepInfoLike.cellDep),
72
79
  apply(Script.from, cellDepInfoLike.type),
@@ -94,6 +101,10 @@ export class ScriptInfo {
94
101
  ) {}
95
102
 
96
103
  static from(scriptInfoLike: ScriptInfoLike): ScriptInfo {
104
+ if (scriptInfoLike instanceof ScriptInfo) {
105
+ return scriptInfoLike;
106
+ }
107
+
97
108
  return new ScriptInfo(
98
109
  hexFrom(scriptInfoLike.codeHash),
99
110
  hashTypeFrom(scriptInfoLike.hashType),
@@ -120,15 +131,59 @@ export type TransactionStatus =
120
131
  /**
121
132
  * @public
122
133
  */
123
- export type ClientTransactionResponse = {
124
- transaction: Transaction;
134
+ export type ClientTransactionResponseLike = {
135
+ transaction: TransactionLike;
125
136
  status: TransactionStatus;
126
- cycles?: Num;
127
- blockHash?: Hex;
128
- blockNumber?: Num;
129
- txIndex?: Num;
137
+ cycles?: NumLike;
138
+ blockHash?: HexLike;
139
+ blockNumber?: NumLike;
140
+ txIndex?: NumLike;
130
141
  reason?: string;
131
142
  };
143
+ /**
144
+ * @public
145
+ */
146
+ export class ClientTransactionResponse {
147
+ constructor(
148
+ public transaction: Transaction,
149
+ public status: TransactionStatus,
150
+ public cycles?: Num,
151
+ public blockHash?: Hex,
152
+ public blockNumber?: Num,
153
+ public txIndex?: Num,
154
+ public reason?: string,
155
+ ) {}
156
+
157
+ static from(
158
+ responseLike: ClientTransactionResponseLike,
159
+ ): ClientTransactionResponse {
160
+ if (responseLike instanceof ClientTransactionResponse) {
161
+ return responseLike;
162
+ }
163
+
164
+ return new ClientTransactionResponse(
165
+ Transaction.from(responseLike.transaction),
166
+ responseLike.status,
167
+ apply(numFrom, responseLike.cycles),
168
+ apply(hexFrom, responseLike.blockHash),
169
+ apply(numFrom, responseLike.blockNumber),
170
+ apply(numFrom, responseLike.txIndex),
171
+ responseLike.reason,
172
+ );
173
+ }
174
+
175
+ clone() {
176
+ return new ClientTransactionResponse(
177
+ this.transaction.clone(),
178
+ this.status,
179
+ this.cycles,
180
+ this.blockHash,
181
+ this.blockNumber,
182
+ this.txIndex,
183
+ this.reason,
184
+ );
185
+ }
186
+ }
132
187
 
133
188
  /**
134
189
  * @public
@@ -154,6 +209,10 @@ export class ClientIndexerSearchKeyFilter {
154
209
  static from(
155
210
  filterLike: ClientIndexerSearchKeyFilterLike,
156
211
  ): ClientIndexerSearchKeyFilter {
212
+ if (filterLike instanceof ClientIndexerSearchKeyFilter) {
213
+ return filterLike;
214
+ }
215
+
157
216
  return new ClientIndexerSearchKeyFilter(
158
217
  apply(Script.from, filterLike.script),
159
218
  apply(clientSearchKeyRangeFrom, filterLike.scriptLenRange),
@@ -186,6 +245,10 @@ export class ClientIndexerSearchKey {
186
245
  ) {}
187
246
 
188
247
  static from(keyLike: ClientIndexerSearchKeyLike): ClientIndexerSearchKey {
248
+ if (keyLike instanceof ClientIndexerSearchKey) {
249
+ return keyLike;
250
+ }
251
+
189
252
  return new ClientIndexerSearchKey(
190
253
  Script.from(keyLike.script),
191
254
  keyLike.scriptType,
@@ -230,6 +293,10 @@ export class ClientIndexerSearchKeyTransaction {
230
293
  static from(
231
294
  keyLike: ClientIndexerSearchKeyTransactionLike,
232
295
  ): ClientIndexerSearchKeyTransaction {
296
+ if (keyLike instanceof ClientIndexerSearchKeyTransaction) {
297
+ return keyLike;
298
+ }
299
+
233
300
  return new ClientIndexerSearchKeyTransaction(
234
301
  Script.from(keyLike.script),
235
302
  keyLike.scriptType,
@@ -273,58 +340,167 @@ export type ClientFindTransactionsGroupedResponse = {
273
340
  /**
274
341
  * @public
275
342
  */
276
- export type ClientBlockHeader = {
277
- compactTarget: Num;
343
+ export type ClientBlockHeaderLike = {
344
+ compactTarget: NumLike;
278
345
  dao: {
279
346
  /**
280
347
  * C_i: the total issuance up to and including block i.
281
348
  */
282
- c: Num;
349
+ c: NumLike;
283
350
  /**
284
351
  * AR_i: the current accumulated rate at block i.
285
352
  * AR_j / AR_i reflects the CKByte amount if one deposit 1 CKB to Nervos DAO at block i, and withdraw at block j.
286
353
  */
287
- ar: Num;
354
+ ar: NumLike;
288
355
  /**
289
356
  * S_i: the total unissued secondary issuance up to and including block i,
290
357
  * including unclaimed Nervos DAO compensation and treasury funds.
291
358
  */
292
- s: Num;
359
+ s: NumLike;
293
360
  /**
294
361
  * U_i: the total occupied capacities currently in the blockchain up to and including block i.
295
362
  * Occupied capacity is the sum of capacities used to store all cells.
296
363
  */
297
- u: Num;
364
+ u: NumLike;
298
365
  };
299
- epoch: Epoch;
300
- extraHash: Hex;
301
- hash: Hex;
302
- nonce: Num;
303
- number: Num;
304
- parentHash: Hex;
305
- proposalsHash: Hex;
306
- timestamp: Num;
307
- transactionsRoot: Hex;
308
- version: Num;
366
+ epoch: EpochLike;
367
+ extraHash: HexLike;
368
+ hash: HexLike;
369
+ nonce: NumLike;
370
+ number: NumLike;
371
+ parentHash: HexLike;
372
+ proposalsHash: HexLike;
373
+ timestamp: NumLike;
374
+ transactionsRoot: HexLike;
375
+ version: NumLike;
309
376
  };
377
+ /**
378
+ * @public
379
+ */
380
+ export class ClientBlockHeader {
381
+ constructor(
382
+ public compactTarget: Num,
383
+ public dao: {
384
+ /**
385
+ * C_i: the total issuance up to and including block i.
386
+ */
387
+ c: Num;
388
+ /**
389
+ * AR_i: the current accumulated rate at block i.
390
+ * AR_j / AR_i reflects the CKByte amount if one deposit 1 CKB to Nervos DAO at block i, and withdraw at block j.
391
+ */
392
+ ar: Num;
393
+ /**
394
+ * S_i: the total unissued secondary issuance up to and including block i,
395
+ * including unclaimed Nervos DAO compensation and treasury funds.
396
+ */
397
+ s: Num;
398
+ /**
399
+ * U_i: the total occupied capacities currently in the blockchain up to and including block i.
400
+ * Occupied capacity is the sum of capacities used to store all cells.
401
+ */
402
+ u: Num;
403
+ },
404
+ public epoch: Epoch,
405
+ public extraHash: Hex,
406
+ public hash: Hex,
407
+ public nonce: Num,
408
+ public number: Num,
409
+ public parentHash: Hex,
410
+ public proposalsHash: Hex,
411
+ public timestamp: Num,
412
+ public transactionsRoot: Hex,
413
+ public version: Num,
414
+ ) {}
415
+
416
+ static from(headerLike: ClientBlockHeaderLike): ClientBlockHeader {
417
+ if (headerLike instanceof ClientBlockHeader) {
418
+ return headerLike;
419
+ }
420
+
421
+ return new ClientBlockHeader(
422
+ numFrom(headerLike.compactTarget),
423
+ {
424
+ c: numFrom(headerLike.dao.c),
425
+ ar: numFrom(headerLike.dao.ar),
426
+ s: numFrom(headerLike.dao.s),
427
+ u: numFrom(headerLike.dao.u),
428
+ },
429
+ epochFrom(headerLike.epoch),
430
+ hexFrom(headerLike.extraHash),
431
+ hexFrom(headerLike.hash),
432
+ numFrom(headerLike.nonce),
433
+ numFrom(headerLike.number),
434
+ hexFrom(headerLike.parentHash),
435
+ hexFrom(headerLike.proposalsHash),
436
+ numFrom(headerLike.timestamp),
437
+ hexFrom(headerLike.transactionsRoot),
438
+ numFrom(headerLike.version),
439
+ );
440
+ }
441
+ }
310
442
 
311
443
  /**
312
444
  * @public
313
445
  */
314
- export type ClientBlockUncle = {
315
- header: ClientBlockHeader;
316
- proposals: Hex[];
446
+ export type ClientBlockUncleLike = {
447
+ header: ClientBlockHeaderLike;
448
+ proposals: HexLike[];
317
449
  };
450
+ /**
451
+ * @public
452
+ */
453
+ export class ClientBlockUncle {
454
+ constructor(
455
+ public header: ClientBlockHeader,
456
+ public proposals: Hex[],
457
+ ) {}
458
+
459
+ static from(uncleLike: ClientBlockUncleLike): ClientBlockUncle {
460
+ if (uncleLike instanceof ClientBlockUncle) {
461
+ return uncleLike;
462
+ }
463
+
464
+ return new ClientBlockUncle(
465
+ ClientBlockHeader.from(uncleLike.header),
466
+ uncleLike.proposals.map(hexFrom),
467
+ );
468
+ }
469
+ }
318
470
 
319
471
  /**
320
472
  * @public
321
473
  */
322
- export type ClientBlock = {
323
- header: ClientBlockHeader;
324
- proposals: Hex[];
325
- transactions: Transaction[];
326
- uncles: ClientBlockUncle[];
474
+ export type ClientBlockLike = {
475
+ header: ClientBlockHeaderLike;
476
+ proposals: HexLike[];
477
+ transactions: TransactionLike[];
478
+ uncles: ClientBlockUncleLike[];
327
479
  };
480
+ /**
481
+ * @public
482
+ */
483
+ export class ClientBlock {
484
+ constructor(
485
+ public header: ClientBlockHeader,
486
+ public proposals: Hex[],
487
+ public transactions: Transaction[],
488
+ public uncles: ClientBlockUncle[],
489
+ ) {}
490
+
491
+ static from(blockLike: ClientBlockLike): ClientBlock {
492
+ if (blockLike instanceof ClientBlock) {
493
+ return blockLike;
494
+ }
495
+
496
+ return new ClientBlock(
497
+ ClientBlockHeader.from(blockLike.header),
498
+ blockLike.proposals.map(hexFrom),
499
+ blockLike.transactions.map(Transaction.from),
500
+ blockLike.uncles.map(ClientBlockUncle.from),
501
+ );
502
+ }
503
+ }
328
504
 
329
505
  export interface ErrorClientBaseLike {
330
506
  message?: string;
@@ -392,8 +568,23 @@ export class ErrorClientRBFRejected extends ErrorClientBase {
392
568
  }
393
569
  }
394
570
 
395
- export class ErrorClientWaitTransactionTimeout extends Error {
396
- constructor() {
397
- super("Wait transaction timeout");
571
+ export class ErrorClientWaitTransactionTimeout extends ErrorClientBase {
572
+ constructor(timeoutLike: NumLike) {
573
+ const timeout = numFrom(timeoutLike).toString();
574
+ super({
575
+ message: `Wait transaction timeout ${timeout}ms`,
576
+ data: JSON.stringify({ timeout }),
577
+ });
578
+ }
579
+ }
580
+
581
+ export class ErrorClientMaxFeeRateExceeded extends ErrorClientBase {
582
+ constructor(limitLike: NumLike, actualLike: NumLike) {
583
+ const limit = numFrom(limitLike).toString();
584
+ const actual = numFrom(actualLike).toString();
585
+ super({
586
+ message: `Max fee rate exceeded limit ${limit}, actual ${actual}. Developer might forgot to complete transaction fee before sending. See https://docs.ckbccc.com/classes/_ckb_ccc_core.index.ccc.Transaction.html#completeFeeBy.`,
587
+ data: JSON.stringify({ limit, actual }),
588
+ });
398
589
  }
399
590
  }
@@ -169,11 +169,11 @@ export abstract class ClientJsonRpc extends Client {
169
169
  * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)
170
170
  * @returns Block
171
171
  */
172
- getBlockByNumber = this.buildSender(
172
+ getBlockByNumberNoCache = this.buildSender(
173
173
  "get_block_by_number",
174
174
  [(v: NumLike) => numToHex(numFrom(v))],
175
175
  (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),
176
- ) as Client["getBlockByNumber"];
176
+ ) as Client["getBlockByNumberNoCache"];
177
177
 
178
178
  /**
179
179
  * Get block by block hash
@@ -183,9 +183,11 @@ export abstract class ClientJsonRpc extends Client {
183
183
  * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)
184
184
  * @returns Block
185
185
  */
186
- getBlockByHash = this.buildSender("get_block", [hexFrom], (b: JsonRpcBlock) =>
187
- apply(JsonRpcTransformers.blockTo, b),
188
- ) as Client["getBlockByHash"];
186
+ getBlockByHashNoCache = this.buildSender(
187
+ "get_block",
188
+ [hexFrom],
189
+ (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),
190
+ ) as Client["getBlockByHashNoCache"];
189
191
 
190
192
  /**
191
193
  * Get header by block number
@@ -194,11 +196,11 @@ export abstract class ClientJsonRpc extends Client {
194
196
  * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)
195
197
  * @returns BlockHeader
196
198
  */
197
- getHeaderByNumber = this.buildSender(
199
+ getHeaderByNumberNoCache = this.buildSender(
198
200
  "get_header_by_number",
199
201
  [(v: NumLike) => numToHex(numFrom(v))],
200
202
  (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),
201
- ) as Client["getHeaderByNumber"];
203
+ ) as Client["getHeaderByNumberNoCache"];
202
204
 
203
205
  /**
204
206
  * Get header by block hash
@@ -207,11 +209,11 @@ export abstract class ClientJsonRpc extends Client {
207
209
  * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)
208
210
  * @returns BlockHeader
209
211
  */
210
- getHeaderByHash = this.buildSender(
212
+ getHeaderByHashNoCache = this.buildSender(
211
213
  "get_header",
212
214
  [hexFrom],
213
215
  (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),
214
- ) as Client["getHeaderByHash"];
216
+ ) as Client["getHeaderByHashNoCache"];
215
217
 
216
218
  /**
217
219
  * Estimate cycles of a transaction.
@@ -192,7 +192,7 @@ export class JsonRpcTransformers {
192
192
  return;
193
193
  }
194
194
 
195
- return {
195
+ return ClientTransactionResponse.from({
196
196
  transaction: JsonRpcTransformers.transactionTo(transaction),
197
197
  status,
198
198
  cycles: apply(numFrom, cycles),
@@ -200,7 +200,7 @@ export class JsonRpcTransformers {
200
200
  blockNumber: apply(numFrom, block_number),
201
201
  txIndex: apply(numFrom, tx_index),
202
202
  reason,
203
- };
203
+ });
204
204
  }
205
205
  static blockHeaderTo(header: JsonRpcBlockHeader): ClientBlockHeader {
206
206
  const dao = bytesFrom(header.dao);
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  JsonRpcPayload,
3
3
  Transport,
4
+ TransportFallback,
4
5
  transportFromUri,
5
6
  } from "./transports/advanced.js";
6
7
 
@@ -25,6 +26,7 @@ function transform(value: unknown, transformer?: (i: unknown) => unknown) {
25
26
  }
26
27
 
27
28
  export type RequestorJsonRpcConfig = {
29
+ fallbacks?: string[];
28
30
  timeout?: number;
29
31
  maxConcurrent?: number;
30
32
  transport?: Transport;
@@ -51,7 +53,14 @@ export class RequestorJsonRpc {
51
53
  private readonly onError?: (err: unknown) => Promise<void> | void,
52
54
  ) {
53
55
  this.maxConcurrent = config?.maxConcurrent;
54
- this.transport = config?.transport ?? transportFromUri(url_, config);
56
+ this.transport =
57
+ config?.transport ??
58
+ new TransportFallback(
59
+ Array.from(
60
+ new Set([url_, ...(config?.fallbacks ?? [])]).values(),
61
+ (url) => transportFromUri(url, config),
62
+ ),
63
+ );
55
64
  }
56
65
 
57
66
  /**
@@ -1,4 +1,5 @@
1
1
  export * from "./factory.js";
2
+ export * from "./fallback.js";
2
3
  export * from "./http.js";
3
4
  export * from "./transport.js";
4
5
  export * from "./webSocket.js";
@@ -0,0 +1,27 @@
1
+ import { JsonRpcPayload, Transport } from "./transport.js";
2
+
3
+ export class TransportFallback implements Transport {
4
+ // Current transport index
5
+ private i = 0;
6
+
7
+ constructor(private readonly transports: Transport[]) {}
8
+
9
+ async request(data: JsonRpcPayload): Promise<unknown> {
10
+ let triedCount = 0;
11
+
12
+ while (true) {
13
+ try {
14
+ return await this.transports[this.i % this.transports.length].request(
15
+ data,
16
+ );
17
+ } catch (err) {
18
+ triedCount += 1;
19
+ this.i += 1;
20
+
21
+ if (triedCount >= this.transports.length) {
22
+ throw err;
23
+ }
24
+ }
25
+ }
26
+ }
27
+ }
@@ -87,24 +87,28 @@ export class TransportWebSocket implements Transport {
87
87
  reject,
88
88
  setTimeout(() => {
89
89
  this.ongoing.delete(data.id);
90
- void socket.then((socket) => socket.close());
90
+ void socket
91
+ .then((socket) => socket.close())
92
+ .catch((err) => reject(err));
91
93
  reject(new Error("Request timeout"));
92
94
  }, this.timeout),
93
95
  ];
94
96
  this.ongoing.set(data.id, req);
95
97
 
96
- void socket.then((socket) => {
97
- if (
98
- socket.readyState === socket.CLOSED ||
99
- socket.readyState === socket.CLOSING
100
- ) {
101
- clearTimeout(req[2]);
102
- this.ongoing.delete(data.id);
103
- reject(new Error("Connection closed"));
104
- } else {
105
- socket.send(JSON.stringify(data));
106
- }
107
- });
98
+ void socket
99
+ .then((socket) => {
100
+ if (
101
+ socket.readyState === socket.CLOSED ||
102
+ socket.readyState === socket.CLOSING
103
+ ) {
104
+ clearTimeout(req[2]);
105
+ this.ongoing.delete(data.id);
106
+ reject(new Error("Connection closed"));
107
+ } else {
108
+ socket.send(JSON.stringify(data));
109
+ }
110
+ })
111
+ .catch((err) => reject(err));
108
112
  });
109
113
  }
110
114
  }
@@ -1,4 +1,4 @@
1
- import { NumLike, numFrom } from "../num/index.js";
1
+ import { NumLike, numFrom, numToHex } from "../num/index.js";
2
2
 
3
3
  /**
4
4
  * A type safe way to apply a transformer on a value if it's not empty.
@@ -183,3 +183,16 @@ export type Constructor<T> = {
183
183
  export function isWebview(userAgent: string): boolean {
184
184
  return /webview|wv|ip((?!.*Safari)|(?=.*like Safari))/i.test(userAgent);
185
185
  }
186
+
187
+ /**
188
+ * @public
189
+ */
190
+ export function stringify(val: unknown) {
191
+ return JSON.stringify(val, (_, value) => {
192
+ if (typeof value === "bigint") {
193
+ return numToHex(value);
194
+ }
195
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
196
+ return value;
197
+ });
198
+ }