@ledgerhq/coin-evm 16.5.2 → 16.5.4

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 (71) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/config.d.ts +9 -0
  3. package/lib/config.d.ts.map +1 -1
  4. package/lib/config.js +4 -0
  5. package/lib/config.js.map +1 -1
  6. package/lib/errors.d.ts +15 -0
  7. package/lib/errors.d.ts.map +1 -1
  8. package/lib/errors.js +31 -1
  9. package/lib/errors.js.map +1 -1
  10. package/lib/logic/feeCollectorOperations.d.ts +61 -0
  11. package/lib/logic/feeCollectorOperations.d.ts.map +1 -0
  12. package/lib/logic/feeCollectorOperations.js +206 -0
  13. package/lib/logic/feeCollectorOperations.js.map +1 -0
  14. package/lib/logic/listOperations.d.ts.map +1 -1
  15. package/lib/logic/listOperations.js +4 -1
  16. package/lib/logic/listOperations.js.map +1 -1
  17. package/lib/network/node/rpc.common.d.ts.map +1 -1
  18. package/lib/network/node/rpc.common.js +122 -34
  19. package/lib/network/node/rpc.common.js.map +1 -1
  20. package/lib/network/node/types.d.ts +2 -1
  21. package/lib/network/node/types.d.ts.map +1 -1
  22. package/lib/network/node/types.js.map +1 -1
  23. package/lib-es/config.d.ts +9 -0
  24. package/lib-es/config.d.ts.map +1 -1
  25. package/lib-es/config.js +4 -0
  26. package/lib-es/config.js.map +1 -1
  27. package/lib-es/errors.d.ts +15 -0
  28. package/lib-es/errors.d.ts.map +1 -1
  29. package/lib-es/errors.js +27 -0
  30. package/lib-es/errors.js.map +1 -1
  31. package/lib-es/logic/feeCollectorOperations.d.ts +61 -0
  32. package/lib-es/logic/feeCollectorOperations.d.ts.map +1 -0
  33. package/lib-es/logic/feeCollectorOperations.js +201 -0
  34. package/lib-es/logic/feeCollectorOperations.js.map +1 -0
  35. package/lib-es/logic/listOperations.d.ts.map +1 -1
  36. package/lib-es/logic/listOperations.js +4 -1
  37. package/lib-es/logic/listOperations.js.map +1 -1
  38. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  39. package/lib-es/network/node/rpc.common.js +123 -35
  40. package/lib-es/network/node/rpc.common.js.map +1 -1
  41. package/lib-es/network/node/types.d.ts +2 -1
  42. package/lib-es/network/node/types.d.ts.map +1 -1
  43. package/lib-es/network/node/types.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/api/tests/getBlock.integ.test.ts +3 -32
  46. package/src/api/tests/index.alpen_testnet.integ.test.ts +2 -7
  47. package/src/api/tests/index.arbitrum.integ.test.ts +2 -12
  48. package/src/api/tests/index.arc.integ.test.ts +2 -13
  49. package/src/api/tests/index.avalanche_c_chain_fuji.integ.test.ts +2 -12
  50. package/src/api/tests/index.cronos.integ.test.ts +2 -12
  51. package/src/api/tests/index.flare.integ.test.ts +2 -8
  52. package/src/api/tests/index.integ.test.ts +5 -35
  53. package/src/api/tests/index.linea.integ.test.ts +2 -15
  54. package/src/api/tests/index.monad_testnet.integ.test.ts +5 -13
  55. package/src/api/tests/index.optimism.integ.test.ts +2 -12
  56. package/src/api/tests/index.rsk.integ.test.ts +2 -12
  57. package/src/api/tests/index.scroll.integ.test.ts +4 -7
  58. package/src/api/tests/index.shape.integ.test.ts +3 -27
  59. package/src/api/tests/index.somnia.integ.test.ts +2 -6
  60. package/src/api/tests/index.unichain.integ.test.ts +2 -12
  61. package/src/api/tests/index.zksync.integ.test.ts +5 -8
  62. package/src/config.ts +11 -0
  63. package/src/errors.ts +27 -0
  64. package/src/logic/feeCollectorOperations.ts +272 -0
  65. package/src/logic/listOperations.ts +20 -1
  66. package/src/logic/tests/broadcast.integ.test.ts +4 -15
  67. package/src/logic/tests/listOperations.test.ts +563 -0
  68. package/src/network/node/rpc.common.ts +171 -35
  69. package/src/network/node/types.ts +2 -1
  70. package/src/network/tests/node/rpc.test.ts +237 -7
  71. package/src/staking/validators.integ.test.ts +5 -22
@@ -23,7 +23,14 @@ import ERC20Abi from '../../abis/erc20.abi.json'
23
23
  import OptimismGasPriceOracleAbi from '../../abis/optimismGasPriceOracle.abi.json'
24
24
  import ScrollGasPriceOracleAbi from '../../abis/scrollGasPriceOracle.abi.json'
25
25
  import { CHAIN_ID, OP_STACK_L1_FEE_CHAIN_IDS } from '../../config'
26
- import { GasEstimationError, InsufficientFunds, UnsupportedRpcMethodError } from '../../errors'
26
+ import {
27
+ GasEstimationError,
28
+ InsufficientFunds,
29
+ MalformedNodeResponse,
30
+ NodeBlockNotFound,
31
+ NodeTransactionNotFound,
32
+ UnsupportedRpcMethodError,
33
+ } from '../../errors'
27
34
  import { isSmartContractInput, safeEncodeEIP55, normalizeAddress } from '../../logic-public'
28
35
  import {
29
36
  isOptionalQuantity,
@@ -306,6 +313,92 @@ function parseReceiptL1Fee(raw: Record<string, unknown>): string | undefined {
306
313
  return typeof l1Fee === 'string' ? BigInt(l1Fee).toString() : undefined
307
314
  }
308
315
 
316
+ /** The fields of a transaction {@link getTransaction} reads, as ethers or the raw RPC gives them. */
317
+ type TransactionFields = {
318
+ hash: string
319
+ blockNumber: number | null
320
+ blockHash: string | null
321
+ /** Absent when the node omits it, as some Celo nodes do for older deposit transactions */
322
+ nonce?: number
323
+ gasLimit: bigint
324
+ value: bigint
325
+ from: string
326
+ to: string | null
327
+ type: number
328
+ data: string
329
+ }
330
+
331
+ function rawQuantity(value: unknown, fieldName: string): bigint {
332
+ if (typeof value === 'string' || typeof value === 'number') return BigInt(value)
333
+ throw new MalformedNodeResponse(`Malformed ${fieldName} in eth_getTransactionByHash response`)
334
+ }
335
+
336
+ function rawString(value: unknown, fieldName: string): string {
337
+ if (typeof value === 'string') return value
338
+ throw new MalformedNodeResponse(`Malformed ${fieldName} in eth_getTransactionByHash response`)
339
+ }
340
+
341
+ /**
342
+ * Reads a transaction with the raw `eth_getTransactionByHash`, for a transaction ethers cannot
343
+ * format: zkSync L1→L2 deposits (type `0xff`) have no signature fields.
344
+ */
345
+ async function getTransactionFromRawRpc(
346
+ api: JsonRpcProvider,
347
+ txHash: string
348
+ ): Promise<TransactionFields | null> {
349
+ const raw: unknown = await api.send('eth_getTransactionByHash', [txHash])
350
+ if (raw === null || raw === undefined) return null
351
+ if (!isRecord(raw)) throw new MalformedNodeResponse('Invalid eth_getTransactionByHash response')
352
+
353
+ const blockNumber = raw.blockNumber
354
+ return {
355
+ hash: rawString(raw.hash, 'hash'),
356
+ blockNumber:
357
+ blockNumber === null || blockNumber === undefined
358
+ ? null
359
+ : Number(rawQuantity(blockNumber, 'blockNumber')),
360
+ blockHash: typeof raw.blockHash === 'string' ? raw.blockHash : null,
361
+ ...(raw.nonce === undefined || raw.nonce === null
362
+ ? {}
363
+ : { nonce: Number(rawQuantity(raw.nonce, 'nonce')) }),
364
+ gasLimit: rawQuantity(raw.gas, 'gas'),
365
+ value: rawQuantity(raw.value, 'value'),
366
+ // Checksummed, as ethers gives them
367
+ from: ethers.getAddress(rawString(raw.from, 'from')),
368
+ to: typeof raw.to === 'string' ? ethers.getAddress(raw.to) : null,
369
+ type: Number(rawQuantity(raw.type ?? 0, 'type')),
370
+ data: typeof raw.input === 'string' ? raw.input : '0x',
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Reads a transaction with ethers, or with the raw RPC when ethers cannot format it for missing
376
+ * signature fields, as {@link getBlockByHeight} does for a block.
377
+ */
378
+ async function readTransaction(
379
+ api: JsonRpcProvider,
380
+ txHash: string,
381
+ logger: Logger
382
+ ): Promise<TransactionFields | null> {
383
+ try {
384
+ return await api.getTransaction(txHash)
385
+ } catch (error) {
386
+ if (isMissingNonceError(error)) {
387
+ logger('warn', 'EVM getTransaction fallback: the transaction has no nonce', {
388
+ txHash,
389
+ error: error.shortMessage,
390
+ })
391
+ return getTransactionFromRawRpc(api, txHash)
392
+ }
393
+ if (!isSignatureError(error)) throw error
394
+ logger('warn', 'EVM getTransaction fallback: using raw eth_getTransactionByHash response', {
395
+ txHash,
396
+ error: String(error),
397
+ })
398
+ return getTransactionFromRawRpc(api, txHash)
399
+ }
400
+ }
401
+
309
402
  async function getTransaction(
310
403
  api: JsonRpcProvider,
311
404
  txHash: string,
@@ -315,12 +408,12 @@ async function getTransaction(
315
408
  // extra fields that contain L1 fees.
316
409
  // A pull request for ethers is open to avoid this: https://github.com/ethers-io/ethers.js/pull/5189
317
410
  const [tx, rawReceipt] = await Promise.all([
318
- api.getTransaction(txHash),
411
+ readTransaction(api, txHash, logger),
319
412
  api.send('eth_getTransactionReceipt', [txHash]),
320
413
  ])
321
414
 
322
415
  if (!tx || !isTransactionReceipt(rawReceipt)) {
323
- throw new Error('Transaction or receipt not found')
416
+ throw new NodeTransactionNotFound('Transaction or receipt not found', { txHash })
324
417
  }
325
418
 
326
419
  const receipt = rawReceipt
@@ -338,7 +431,7 @@ async function getTransaction(
338
431
  hash: tx.hash,
339
432
  blockHeight: tx.blockNumber ?? undefined,
340
433
  blockHash: tx.blockHash ?? undefined,
341
- nonce: tx.nonce,
434
+ ...(tx.nonce !== undefined ? { nonce: tx.nonce } : {}),
342
435
  gasUsed: quantityToDecimal(receipt.gasUsed),
343
436
  gasPrice: receiptGasPrice(receipt),
344
437
  gasLimit: tx.gasLimit.toString(),
@@ -575,7 +668,10 @@ function assertNotStubBlock(
575
668
  timestampInSeconds: number
576
669
  ): void {
577
670
  if (height > 0 && timestampInSeconds === 0) {
578
- throw new Error(`Block ${blockHeight} not found (the node returned an empty stub block)`)
671
+ throw new NodeBlockNotFound(
672
+ `Block ${blockHeight} not found (the node returned an empty stub block)`,
673
+ { blockHeight }
674
+ )
579
675
  }
580
676
  }
581
677
 
@@ -598,16 +694,23 @@ async function getBlockByHeight(
598
694
  })
599
695
  return getBlockByHeightFromRawRpc(api, blockHeight, true)
600
696
  }
697
+ if (prefetchTxs && isMissingNonceError(error)) {
698
+ logger('warn', 'EVM getBlock fallback: a transaction has no nonce', {
699
+ blockHeight,
700
+ error: error.shortMessage,
701
+ })
702
+ return getBlockByHeightFromRawRpc(api, blockHeight, true)
703
+ }
601
704
  throw error
602
705
  }
603
706
 
604
707
  if (!block) {
605
- throw new Error(`Block ${blockHeight} not found`)
708
+ throw new NodeBlockNotFound(`Block ${blockHeight} not found`, { blockHeight })
606
709
  }
607
710
  assertNotStubBlock(blockHeight, block.number, block.timestamp)
608
711
 
609
712
  if (!block.hash) {
610
- throw new Error(`Block ${blockHeight} is missing hash`)
713
+ throw new MalformedNodeResponse(`Block ${blockHeight} is missing hash`)
611
714
  }
612
715
 
613
716
  const transactionHashes =
@@ -625,7 +728,7 @@ async function getBlockByHeight(
625
728
  const prefetchedTransactions = prefetchTxs ? getPrefetchedBlockTransactions(block) : undefined
626
729
  const transactions = prefetchedTransactions?.map((tx, index) => {
627
730
  if (!isPrefetchedBlockTransaction(tx))
628
- throw new Error(
731
+ throw new MalformedNodeResponse(
629
732
  `Block ${blockHeight} contains malformed prefetched transaction at index ${index}`
630
733
  )
631
734
 
@@ -656,13 +759,29 @@ async function getBlockByHeight(
656
759
  }
657
760
  }
658
761
 
659
- /** Specific error thrown by ethers when handling zksync blocks with missing signature fields in prefetched transactions */
762
+ /** Specific error thrown by ethers when formatting zkSync transactions with missing signature fields */
660
763
  function isSignatureError(error: unknown): boolean {
661
764
  if (!hasErrorCode(error, 'INVALID_ARGUMENT')) return false
662
765
  if (!isRecord(error)) return false
663
766
  return error.argument === 'signature'
664
767
  }
665
768
 
769
+ /**
770
+ * Error thrown by ethers when it formats a transaction without `nonce`, which it requires. Some
771
+ * Celo nodes omit the nonce of the deposit transaction of older blocks. Only this field is
772
+ * matched: the raw parsers would not reject every other field ethers does.
773
+ */
774
+ function isMissingNonceError(error: unknown): error is { shortMessage: string } {
775
+ if (!hasErrorCode(error, 'BAD_DATA') || !isRecord(error)) return false
776
+ const { shortMessage, value } = error
777
+ return (
778
+ typeof shortMessage === 'string' &&
779
+ shortMessage.startsWith('invalid value for value.nonce ') &&
780
+ isRecord(value) &&
781
+ (value.nonce === undefined || value.nonce === null)
782
+ )
783
+ }
784
+
666
785
  /**
667
786
  * Parse a quantity (eg: amount or block height) return from an RPC.
668
787
  *
@@ -672,7 +791,7 @@ function isSignatureError(error: unknown): boolean {
672
791
  function parseRpcHexQuantity(value: unknown, fieldName: string): number {
673
792
  if (typeof value === 'number') return value
674
793
  if (typeof value === 'string') return Number(BigInt(value))
675
- throw new Error(`Malformed ${fieldName} in eth_getBlockByNumber response`)
794
+ throw new MalformedNodeResponse(`Malformed ${fieldName} in eth_getBlockByNumber response`)
676
795
  }
677
796
 
678
797
  /**
@@ -687,26 +806,26 @@ async function getBlockByHeightFromRawRpc(
687
806
  ): Promise<BlockByHeightResult> {
688
807
  const blockTag = typeof blockHeight === 'number' ? ethers.toQuantity(blockHeight) : blockHeight
689
808
  const rawBlock = await api.send('eth_getBlockByNumber', [blockTag, prefetchTxs])
690
- if (!isRecord(rawBlock)) throw new Error('Invalid eth_getBlockByNumber response')
809
+ if (!isRecord(rawBlock)) throw new MalformedNodeResponse('Invalid eth_getBlockByNumber response')
691
810
 
692
811
  const block = rawBlock
693
812
  if (typeof block.hash !== 'string')
694
- throw new Error('Malformed block hash in eth_getBlockByNumber')
813
+ throw new MalformedNodeResponse('Malformed block hash in eth_getBlockByNumber')
695
814
  if (typeof block.parentHash !== 'string')
696
- throw new Error('Malformed block parentHash in eth_getBlockByNumber')
815
+ throw new MalformedNodeResponse('Malformed block parentHash in eth_getBlockByNumber')
697
816
 
698
817
  const height = parseRpcHexQuantity(block.number, 'block.number')
699
818
  const timestampInSeconds = parseRpcHexQuantity(block.timestamp, 'block.timestamp')
700
819
  assertNotStubBlock(blockHeight, height, timestampInSeconds)
701
820
  const rawTransactions = block.transactions
702
821
  if (rawTransactions !== undefined && !Array.isArray(rawTransactions))
703
- throw new Error('Malformed block.transactions in eth_getBlockByNumber response')
822
+ throw new MalformedNodeResponse('Malformed block.transactions in eth_getBlockByNumber response')
704
823
 
705
824
  const transactionHashes = rawTransactions?.map((tx, index) => {
706
825
  if (typeof tx === 'string') return tx
707
826
  if (typeof tx === 'object' && tx !== null && 'hash' in tx && typeof tx.hash === 'string')
708
827
  return tx.hash
709
- throw new Error(
828
+ throw new MalformedNodeResponse(
710
829
  `Malformed block transaction at index ${index} in eth_getBlockByNumber response`
711
830
  )
712
831
  })
@@ -715,31 +834,44 @@ async function getBlockByHeightFromRawRpc(
715
834
  prefetchTxs && rawTransactions
716
835
  ? rawTransactions.map((tx) => {
717
836
  if (typeof tx === 'string')
718
- throw new Error('Expected prefetched transaction object, got hash string')
837
+ throw new MalformedNodeResponse(
838
+ 'Expected prefetched transaction object, got hash string'
839
+ )
719
840
  if (typeof tx !== 'object' || tx === null)
720
- throw new Error('Malformed prefetched transaction in eth_getBlockByNumber response')
841
+ throw new MalformedNodeResponse(
842
+ 'Malformed prefetched transaction in eth_getBlockByNumber response'
843
+ )
721
844
  if (!('hash' in tx) || typeof tx.hash !== 'string')
722
- throw new Error(
845
+ throw new MalformedNodeResponse(
723
846
  'Malformed prefetched transaction hash in eth_getBlockByNumber response'
724
847
  )
725
- if (!('from' in tx) || typeof tx.from !== 'string')
726
- throw new Error(
848
+ if (!('from' in tx) || typeof tx.from !== 'string' || !ethers.isAddress(tx.from))
849
+ throw new MalformedNodeResponse(
727
850
  'Malformed prefetched transaction from in eth_getBlockByNumber response'
728
851
  )
729
852
  if ('to' in tx && tx.to !== null && tx.to !== undefined && typeof tx.to !== 'string')
730
- throw new Error('Malformed prefetched transaction to in eth_getBlockByNumber response')
731
- if ('value' in tx && tx.value !== undefined && typeof tx.value !== 'string')
732
- throw new Error(
853
+ throw new MalformedNodeResponse(
854
+ 'Malformed prefetched transaction to in eth_getBlockByNumber response'
855
+ )
856
+ if (!('value' in tx) || typeof tx.value !== 'string')
857
+ throw new MalformedNodeResponse(
733
858
  'Malformed prefetched transaction value in eth_getBlockByNumber response'
734
859
  )
735
860
  if ('gasPrice' in tx && tx.gasPrice !== undefined && typeof tx.gasPrice !== 'string')
736
- throw new Error(
861
+ throw new MalformedNodeResponse(
737
862
  'Malformed prefetched transaction gasPrice in eth_getBlockByNumber response'
738
863
  )
739
864
  if ('gas' in tx && tx.gas !== undefined && typeof tx.gas !== 'string')
740
- throw new Error('Malformed prefetched transaction gas in eth_getBlockByNumber response')
741
- if ('nonce' in tx && tx.nonce !== undefined && typeof tx.nonce !== 'string')
742
- throw new Error(
865
+ throw new MalformedNodeResponse(
866
+ 'Malformed prefetched transaction gas in eth_getBlockByNumber response'
867
+ )
868
+ if (
869
+ 'nonce' in tx &&
870
+ tx.nonce !== undefined &&
871
+ tx.nonce !== null &&
872
+ typeof tx.nonce !== 'string'
873
+ )
874
+ throw new MalformedNodeResponse(
743
875
  'Malformed prefetched transaction nonce in eth_getBlockByNumber response'
744
876
  )
745
877
  if (
@@ -748,13 +880,13 @@ async function getBlockByHeightFromRawRpc(
748
880
  tx.input !== null &&
749
881
  typeof tx.input !== 'string'
750
882
  )
751
- throw new Error(
883
+ throw new MalformedNodeResponse(
752
884
  'Malformed prefetched transaction input in eth_getBlockByNumber response'
753
885
  )
754
886
 
755
887
  return {
756
888
  hash: tx.hash,
757
- value: BigInt(tx.value ?? '0x0').toString(),
889
+ value: BigInt(tx.value).toString(),
758
890
  from: tx.from,
759
891
  to: tx.to ?? undefined,
760
892
  ...('input' in tx && typeof tx.input === 'string' && isSmartContractInput(tx.input)
@@ -803,11 +935,12 @@ async function getBlockReceipts(
803
935
  throw error
804
936
  }
805
937
 
806
- if (!Array.isArray(receipts)) throw new Error('Invalid eth_getBlockReceipts response')
938
+ if (!Array.isArray(receipts))
939
+ throw new MalformedNodeResponse('Invalid eth_getBlockReceipts response')
807
940
 
808
941
  return receipts.map((receipt, index) => {
809
942
  if (!isTransactionReceipt(receipt))
810
- throw new Error(`Malformed eth_getBlockReceipts response at index ${index}`)
943
+ throw new MalformedNodeResponse(`Malformed eth_getBlockReceipts response at index ${index}`)
811
944
 
812
945
  const raw = recordOf(receipt)
813
946
  const contractAddressRaw = raw.contractAddress
@@ -855,7 +988,8 @@ async function traceBlockGeth(
855
988
  }
856
989
  throw error
857
990
  })
858
- if (!Array.isArray(debugResults)) throw new Error('Invalid debug_traceBlockByNumber response')
991
+ if (!Array.isArray(debugResults))
992
+ throw new MalformedNodeResponse('Invalid debug_traceBlockByNumber response')
859
993
  return normalizeTraceBlockItems(gethCallTracerToTraceBlockItems(blockHeight, debugResults))
860
994
  }
861
995
 
@@ -877,11 +1011,13 @@ async function traceBlockErigon(
877
1011
  }
878
1012
 
879
1013
  function normalizeTraceBlockItems(traces: TraceBlockItem[]): TraceBlockItem[] {
880
- if (!Array.isArray(traces)) throw new Error('Invalid trace block response')
1014
+ if (!Array.isArray(traces)) throw new MalformedNodeResponse('Invalid trace block response')
881
1015
 
882
1016
  return traces.map((trace, index) => {
883
1017
  if (!isTraceBlockItem(trace)) {
884
- throw new Error(`Malformed trace block response at index ${index} ${JSON.stringify(trace)}`)
1018
+ throw new MalformedNodeResponse(
1019
+ `Malformed trace block response at index ${index} ${JSON.stringify(trace)}`
1020
+ )
885
1021
  }
886
1022
  return trace
887
1023
  })
@@ -901,7 +1037,7 @@ type EthersPrefetchedTransaction = {
901
1037
 
902
1038
  function recordOf(value: object): Record<string, unknown> {
903
1039
  if (isRecord(value)) return value
904
- throw new Error('expected object')
1040
+ throw new MalformedNodeResponse('expected object')
905
1041
  }
906
1042
 
907
1043
  function isPrefetchedBlockTransaction(value: unknown): value is EthersPrefetchedTransaction {
@@ -102,7 +102,8 @@ export type TransactionInfo = {
102
102
  hash: string
103
103
  blockHeight: number | undefined
104
104
  blockHash: string | undefined
105
- nonce: number
105
+ /** Absent when the node omits it, as some Celo nodes do for older deposit transactions */
106
+ nonce?: number
106
107
  gasUsed: string
107
108
  gasPrice: string
108
109
  /** Gas limit set by the sender (decimal), when the source reports it */
@@ -56,6 +56,82 @@ jest.mocked(delay).mockImplementation(
56
56
  () => new Promise((resolve) => setTimeout(resolve, 1)) // mocking the delay supposed to happen after each try
57
57
  )
58
58
 
59
+ // Celo block 80494727 as some nodes serve it: its deposit transaction has no `nonce`
60
+ const CELO_DEPOSIT_HASH = '0xe7a0b5d03b530cafc01fec8ed44cc9b6e821d5e0224dae43ecf5af01dd5bd814'
61
+ const celoDepositWithoutNonce = {
62
+ blockHash: '0x832b94266e345c9f788ba3bcf7fd52ecff13801ee9b1b1c2d036f1c06fd4597e',
63
+ blockNumber: '0x4cc4087',
64
+ from: '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0001',
65
+ gas: '0xf4240',
66
+ gasPrice: '0x0',
67
+ hash: CELO_DEPOSIT_HASH,
68
+ input: '0x3db6be2b',
69
+ mint: '0x0',
70
+ r: '0x0',
71
+ s: '0x0',
72
+ sourceHash: '0xf5893f7db6a4f3effe82397b9eae2a68778c65f9d0c522bba6dbdf6afbd711e5',
73
+ to: '0x4200000000000000000000000000000000000015',
74
+ transactionIndex: '0x0',
75
+ type: '0x7e',
76
+ v: '0x0',
77
+ value: '0x0',
78
+ yParity: '0x0',
79
+ }
80
+ const celoTransfer = {
81
+ blockHash: '0x832b94266e345c9f788ba3bcf7fd52ecff13801ee9b1b1c2d036f1c06fd4597e',
82
+ blockNumber: '0x4cc4087',
83
+ chainId: '0xa4ec',
84
+ from: '0x37e6d7c66d2dc9a37c326e15c9df2b5347421f93',
85
+ gas: '0xe049',
86
+ gasPrice: '0x3893edbe00',
87
+ hash: '0xa2099d34015c257aaca25b69ff9ec209dcb04fb83841186972dd8598fa88ec83',
88
+ input:
89
+ '0xa9059cbb0000000000000000000000004cb8c4f8b374201ae1be5b385896178c72422ec400000000000000000000000000000000000000000000000000000000000093ee',
90
+ nonce: '0xe269a',
91
+ r: '0x88a542dce02e7fed7517b3bfe2335a18f8ba6878c9c79a2fcebc8361172edb3c',
92
+ s: '0x644f48a3ccdf2d23ff59a8420b89c6e4cb8f321886ca076e4ee23561f39392a3',
93
+ to: '0x48065fbbe25f71c9282ddf5e1cd6d6a887483d5e',
94
+ transactionIndex: '0x1',
95
+ type: '0x0',
96
+ v: '0x149fb',
97
+ value: '0x0',
98
+ }
99
+
100
+ function celoBlock(transactions: unknown[]): Record<string, unknown> {
101
+ return {
102
+ baseFeePerGas: '0x2ecb7ec00e',
103
+ difficulty: '0x0',
104
+ extraData: '0x0100000190000000050000002e90edd000',
105
+ gasLimit: '0x1c9c380',
106
+ gasUsed: '0x1f6b3b',
107
+ hash: '0x832b94266e345c9f788ba3bcf7fd52ecff13801ee9b1b1c2d036f1c06fd4597e',
108
+ miner: '0x4200000000000000000000000000000000000011',
109
+ nonce: '0x0000000000000000',
110
+ number: '0x4cc4087',
111
+ parentHash: '0x04003c8eca609659919ee03e214e378b808161e787c469d7fce3ee18ea828cbf',
112
+ timestamp: '0x6ad5c8dd',
113
+ transactions,
114
+ }
115
+ }
116
+
117
+ // The ethers implementations, before the tests mock them
118
+ const {
119
+ getBlock: ethersGetBlock,
120
+ getTransaction: ethersGetTransaction,
121
+ _perform: ethersPerform,
122
+ } = JsonRpcProvider.prototype
123
+
124
+ /** Serves the raw RPC responses, so that ethers formats them as it would a node's. */
125
+ function mockRawRpc(responses: Record<string, unknown>): jest.SpyInstance {
126
+ jest.spyOn(JsonRpcProvider.prototype, 'getBlock').mockImplementation(ethersGetBlock)
127
+ jest.spyOn(JsonRpcProvider.prototype, 'getTransaction').mockImplementation(ethersGetTransaction)
128
+ jest.spyOn(JsonRpcProvider.prototype, '_perform').mockImplementation(ethersPerform)
129
+ return jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
130
+ if (method in responses) return responses[method]
131
+ throw new Error(`Method not mocked: ${method}`)
132
+ })
133
+ }
134
+
59
135
  describe('EVM Family', () => {
60
136
  let config: EvmConfigInfo
61
137
 
@@ -306,6 +382,98 @@ describe('EVM Family', () => {
306
382
  expect(tx.type).toBe(0)
307
383
  })
308
384
 
385
+ it('should read a zkSync deposit, which ethers cannot format for its missing signature, from the raw RPC', async () => {
386
+ // tx 0xe63e66c9…1ee4 on zkSync Era: an L1→L2 deposit (type 0xff), with no r, s, v
387
+ const hash = '0xe63e66c987d3b8e8b8621e0fde174055687289594d5955e9b97615cc7feb1ee4'
388
+ const account = '0xbeb30f27e61efff46aa27dce18e23ee8d5a7c6a4'
389
+ jest.spyOn(JsonRpcProvider.prototype, 'getTransaction').mockImplementationOnce(async () => {
390
+ throw Object.assign(new TypeError('missing r'), {
391
+ code: 'INVALID_ARGUMENT',
392
+ argument: 'signature',
393
+ })
394
+ })
395
+ jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
396
+ if (method === 'eth_getTransactionByHash') {
397
+ return {
398
+ hash,
399
+ blockNumber: '0x436128',
400
+ blockHash: '0xb8f0774c03f5f8a4a998fcc30037286d93277efd904e6c096a7124d998dc01a0',
401
+ nonce: '0x0',
402
+ gas: '0xb54a3',
403
+ value: '0x3bf3b91c95b0000',
404
+ from: account,
405
+ to: account,
406
+ type: '0xff',
407
+ input: '0x',
408
+ }
409
+ }
410
+ if (method === 'eth_getTransactionReceipt') {
411
+ return {
412
+ transactionHash: hash,
413
+ gasUsed: '0x7a',
414
+ gasPrice: '0x211f3840',
415
+ status: '0x1',
416
+ logs: [],
417
+ type: '0xff',
418
+ contractAddress: null,
419
+ }
420
+ }
421
+ return null
422
+ })
423
+
424
+ const tx = await nodeApi.getTransaction(hash)
425
+
426
+ expect(tx).toMatchObject({
427
+ hash,
428
+ blockHeight: 4415784,
429
+ nonce: 0,
430
+ gasLimit: '742563',
431
+ value: '270000000000000000',
432
+ from: '0xbEB30f27e61eFFF46Aa27dcE18E23ee8D5A7c6a4',
433
+ to: '0xbEB30f27e61eFFF46Aa27dcE18E23ee8D5A7c6a4',
434
+ type: 255,
435
+ })
436
+ })
437
+
438
+ it('should read a deposit transaction without nonce from the raw RPC', async () => {
439
+ mockRawRpc({
440
+ eth_getTransactionByHash: celoDepositWithoutNonce,
441
+ eth_getTransactionReceipt: {
442
+ transactionHash: CELO_DEPOSIT_HASH,
443
+ gasUsed: '0xb5e5',
444
+ effectiveGasPrice: '0x0',
445
+ status: '0x1',
446
+ logs: [],
447
+ type: '0x7e',
448
+ contractAddress: null,
449
+ },
450
+ })
451
+
452
+ const tx = await nodeApi.getTransaction(CELO_DEPOSIT_HASH)
453
+
454
+ expect(tx).toMatchObject({
455
+ hash: CELO_DEPOSIT_HASH,
456
+ blockHeight: 80494727,
457
+ from: '0xDeaDDEaDDeAdDeAdDEAdDEaddeAddEAdDEAd0001',
458
+ type: 126,
459
+ })
460
+ expect(tx).not.toHaveProperty('nonce')
461
+ })
462
+
463
+ it('should not fall back to the raw RPC for another ethers error', async () => {
464
+ jest
465
+ .spyOn(JsonRpcProvider.prototype, 'getTransaction')
466
+ .mockRejectedValueOnce(new Error('connection reset'))
467
+ const send = jest.spyOn(JsonRpcProvider.prototype, 'send')
468
+
469
+ // withRetries reads it again, from ethers
470
+ await nodeApi.getTransaction(
471
+ '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
472
+ )
473
+
474
+ expect(send).not.toHaveBeenCalledWith('eth_getTransactionByHash', expect.anything())
475
+ })
476
+
309
477
  it.each([
310
478
  ['status', { status: 'success' }],
311
479
  ['gasUsed', { gasUsed: 'lots' }],
@@ -332,7 +500,10 @@ describe('EVM Family', () => {
332
500
  nodeApi.getTransaction(
333
501
  '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
334
502
  )
335
- ).rejects.toThrow('Transaction or receipt not found')
503
+ ).rejects.toMatchObject({
504
+ name: 'NodeTransactionNotFound',
505
+ message: 'Transaction or receipt not found',
506
+ })
336
507
  })
337
508
 
338
509
  it('should return the expected payload', async () => {
@@ -1333,9 +1504,10 @@ describe('EVM Family', () => {
1333
1504
  })
1334
1505
  )
1335
1506
 
1336
- await expect(nodeApi.getBlockByHeight(956855)).rejects.toThrow(
1337
- 'Block 956855 not found (the node returned an empty stub block)'
1338
- )
1507
+ await expect(nodeApi.getBlockByHeight(956855)).rejects.toMatchObject({
1508
+ name: 'NodeBlockNotFound',
1509
+ message: 'Block 956855 not found (the node returned an empty stub block)',
1510
+ })
1339
1511
  })
1340
1512
 
1341
1513
  it('should accept a zero timestamp on the genesis block', async () => {
@@ -1475,6 +1647,63 @@ describe('EVM Family', () => {
1475
1647
  ],
1476
1648
  })
1477
1649
  })
1650
+
1651
+ it.each([
1652
+ ['no nonce', celoDepositWithoutNonce],
1653
+ ['a null nonce', { ...celoDepositWithoutNonce, nonce: null }],
1654
+ ])('should fallback to raw RPC block when a deposit transaction has %s', async (_, deposit) => {
1655
+ mockRawRpc({ eth_getBlockByNumber: celoBlock([deposit, celoTransfer]) })
1656
+
1657
+ const block = await nodeApi.getBlockByHeight(80494727, true)
1658
+
1659
+ expect(block.transactions).toEqual([
1660
+ {
1661
+ hash: CELO_DEPOSIT_HASH,
1662
+ value: '0',
1663
+ from: '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0001',
1664
+ to: '0x4200000000000000000000000000000000000015',
1665
+ input: '0x3db6be2b',
1666
+ gasPrice: '0',
1667
+ gasLimit: '1000000',
1668
+ },
1669
+ expect.objectContaining({ hash: celoTransfer.hash, nonce: 927386 }),
1670
+ ])
1671
+ })
1672
+
1673
+ it('should not fallback when ethers rejects another field than the nonce', async () => {
1674
+ const { value: _, ...withoutValue } = celoDepositWithoutNonce
1675
+ mockRawRpc({ eth_getBlockByNumber: celoBlock([withoutValue, celoTransfer]) })
1676
+
1677
+ // The raw parser would reject it as MalformedNodeResponse
1678
+ await expect(nodeApi.getBlockByHeight(80494727, true)).rejects.toMatchObject({
1679
+ code: 'BAD_DATA',
1680
+ shortMessage: expect.stringMatching(/^invalid value for value\.value /),
1681
+ })
1682
+ })
1683
+
1684
+ it('should reject a transaction without value in the raw RPC block', async () => {
1685
+ const { value: _, ...withoutValue } = celoTransfer
1686
+ mockRawRpc({ eth_getBlockByNumber: celoBlock([celoDepositWithoutNonce, withoutValue]) })
1687
+
1688
+ await expect(nodeApi.getBlockByHeight(80494727, true)).rejects.toMatchObject({
1689
+ name: 'MalformedNodeResponse',
1690
+ message: 'Malformed prefetched transaction value in eth_getBlockByNumber response',
1691
+ })
1692
+ })
1693
+
1694
+ it('should reject a malformed sender in the raw RPC block', async () => {
1695
+ mockRawRpc({
1696
+ eth_getBlockByNumber: celoBlock([
1697
+ celoDepositWithoutNonce,
1698
+ { ...celoTransfer, from: '0xnot-an-address' },
1699
+ ]),
1700
+ })
1701
+
1702
+ await expect(nodeApi.getBlockByHeight(80494727, true)).rejects.toMatchObject({
1703
+ name: 'MalformedNodeResponse',
1704
+ message: 'Malformed prefetched transaction from in eth_getBlockByNumber response',
1705
+ })
1706
+ })
1478
1707
  })
1479
1708
 
1480
1709
  describe('getBlockReceipts', () => {
@@ -1632,9 +1861,10 @@ describe('EVM Family', () => {
1632
1861
  throw new Error(`Method not mocked: ${method}`)
1633
1862
  })
1634
1863
 
1635
- await expect(nodeApi.getBlockReceipts!(1)).rejects.toThrow(
1636
- 'Malformed eth_getBlockReceipts response at index 0'
1637
- )
1864
+ await expect(nodeApi.getBlockReceipts!(1)).rejects.toMatchObject({
1865
+ name: 'MalformedNodeResponse',
1866
+ message: 'Malformed eth_getBlockReceipts response at index 0',
1867
+ })
1638
1868
  })
1639
1869
 
1640
1870
  it('should throw UnsupportedRpcMethodError for RPC -32601', async () => {