@ledgerhq/coin-evm 16.5.4 → 16.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 (71) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/lib/api/index.d.ts +5 -2
  3. package/lib/api/index.d.ts.map +1 -1
  4. package/lib/api/index.js +2 -1
  5. package/lib/api/index.js.map +1 -1
  6. package/lib/errors.d.ts +17 -0
  7. package/lib/errors.d.ts.map +1 -1
  8. package/lib/errors.js +26 -1
  9. package/lib/errors.js.map +1 -1
  10. package/lib/logic/cip64Fees.d.ts +43 -0
  11. package/lib/logic/cip64Fees.d.ts.map +1 -0
  12. package/lib/logic/cip64Fees.js +139 -0
  13. package/lib/logic/cip64Fees.js.map +1 -0
  14. package/lib/logic/feeCollectorOperations.d.ts +2 -2
  15. package/lib/logic/feeCollectorOperations.js +2 -2
  16. package/lib/logic/getBlock.d.ts +2 -2
  17. package/lib/logic/getBlock.d.ts.map +1 -1
  18. package/lib/logic/getBlock.js +99 -19
  19. package/lib/logic/getBlock.js.map +1 -1
  20. package/lib/network/node/rpc.common.d.ts.map +1 -1
  21. package/lib/network/node/rpc.common.js +20 -0
  22. package/lib/network/node/rpc.common.js.map +1 -1
  23. package/lib/network/node/types.d.ts +6 -0
  24. package/lib/network/node/types.d.ts.map +1 -1
  25. package/lib/network/node/types.js.map +1 -1
  26. package/lib/network/node/withNodeSources.d.ts.map +1 -1
  27. package/lib/network/node/withNodeSources.js +2 -0
  28. package/lib/network/node/withNodeSources.js.map +1 -1
  29. package/lib-es/api/index.d.ts +5 -2
  30. package/lib-es/api/index.d.ts.map +1 -1
  31. package/lib-es/api/index.js +2 -1
  32. package/lib-es/api/index.js.map +1 -1
  33. package/lib-es/errors.d.ts +17 -0
  34. package/lib-es/errors.d.ts.map +1 -1
  35. package/lib-es/errors.js +21 -0
  36. package/lib-es/errors.js.map +1 -1
  37. package/lib-es/logic/cip64Fees.d.ts +43 -0
  38. package/lib-es/logic/cip64Fees.d.ts.map +1 -0
  39. package/lib-es/logic/cip64Fees.js +134 -0
  40. package/lib-es/logic/cip64Fees.js.map +1 -0
  41. package/lib-es/logic/feeCollectorOperations.d.ts +2 -2
  42. package/lib-es/logic/feeCollectorOperations.js +2 -2
  43. package/lib-es/logic/getBlock.d.ts +2 -2
  44. package/lib-es/logic/getBlock.d.ts.map +1 -1
  45. package/lib-es/logic/getBlock.js +99 -19
  46. package/lib-es/logic/getBlock.js.map +1 -1
  47. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  48. package/lib-es/network/node/rpc.common.js +20 -0
  49. package/lib-es/network/node/rpc.common.js.map +1 -1
  50. package/lib-es/network/node/types.d.ts +6 -0
  51. package/lib-es/network/node/types.d.ts.map +1 -1
  52. package/lib-es/network/node/types.js.map +1 -1
  53. package/lib-es/network/node/withNodeSources.d.ts.map +1 -1
  54. package/lib-es/network/node/withNodeSources.js +2 -0
  55. package/lib-es/network/node/withNodeSources.js.map +1 -1
  56. package/package.json +2 -2
  57. package/src/api/index.ts +4 -1
  58. package/src/api/tests/index.celo.integ.test.ts +93 -0
  59. package/src/api/tests/index.flare.integ.test.ts +2 -1
  60. package/src/api/tests/index.test.ts +9 -0
  61. package/src/errors.ts +24 -0
  62. package/src/logic/cip64Fees.ts +193 -0
  63. package/src/logic/feeCollectorOperations.ts +2 -2
  64. package/src/logic/getBlock.ts +170 -30
  65. package/src/logic/tests/cip64Fees.test.ts +277 -0
  66. package/src/logic/tests/getBlock.test.ts +249 -2
  67. package/src/network/node/rpc.common.ts +29 -0
  68. package/src/network/node/types.ts +6 -0
  69. package/src/network/node/withNodeSources.ts +3 -0
  70. package/src/network/tests/node/rpc.test.ts +39 -0
  71. package/src/network/tests/node/withNodeSources.test.ts +18 -0
@@ -0,0 +1,277 @@
1
+ // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { ERC20Transfer, NodeApi } from '../../network/node/types'
5
+ import {
6
+ FeeCurrencyUnavailableError,
7
+ UnexpectedFeeLogsError,
8
+ UnsupportedFeeCurrencyError,
9
+ } from '../../errors'
10
+ import { mockNodeApi } from '../../network/tests/node/node.fixtures'
11
+ import { createCeloTokenFeeReader, splitTokenFee } from '../cip64Fees'
12
+
13
+ const USDT = '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e'
14
+ const USDT_ADAPTER = '0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72'
15
+ const USDT_HOLDER = '0x000000000000000000000000000000000Ce106A5'
16
+ const USDC = '0xcebA9300f2b948710d2653dD7B07f33A8B32118C'
17
+ const USDC_ADAPTER = '0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B'
18
+ const CUSD = '0x765DE816845861e75A25fCA122bb6898B8B1282a'
19
+ const CEUR = '0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73'
20
+ const ZERO = '0x0000000000000000000000000000000000000000'
21
+ const SEQUENCER_VAULT = '0x4200000000000000000000000000000000000011'
22
+ const FEE_HANDLER = '0xcD437749E43A154C07F3553504c68fBfD56B8778'
23
+ const PAYER = '0x5362C723476b46a1e65D54E667C00e46b46F6f12'
24
+ const OTHER = '0xfb4863FC2FE52A8131696e4a3a86676cff40A806'
25
+
26
+ function transfer(token: string, from: string, to: string, value: bigint): ERC20Transfer {
27
+ return { asset: { type: 'erc20', assetReference: token }, from, to, value: value.toString() }
28
+ }
29
+
30
+ // Fee logs of tx 0x45e41cf20fca9b079f8b23510bb9637d14df647cb6d25d85157924cd27df09d7 (block 80494727)
31
+ const usdtDebit = transfer(USDT, PAYER, USDT_HOLDER, 4252n)
32
+ const usdtCredits = [
33
+ transfer(USDT, USDT_HOLDER, SEQUENCER_VAULT, 0n),
34
+ transfer(USDT, USDT_HOLDER, FEE_HANDLER, 3176n),
35
+ transfer(USDT, USDT_HOLDER, PAYER, 1076n),
36
+ ]
37
+
38
+ // Fee logs of tx 0xf43732d1ca9d43dd6515708669e6083010672aed8a61de4c8d07164c7e3d400d
39
+ const usdcDebit = transfer(USDC, PAYER, ZERO, 5020n)
40
+ const usdcCredits = [
41
+ transfer(USDC, ZERO, PAYER, 5020n),
42
+ transfer(USDC, PAYER, SEQUENCER_VAULT, 0n),
43
+ transfer(USDC, PAYER, FEE_HANDLER, 4072n),
44
+ ]
45
+
46
+ // Fee logs of tx 0xa92de9a2b85e285d2bf1c1317386e012034ddfbbd84739e5b5f46fe6c252e748
47
+ const cusdDebit = transfer(CUSD, PAYER, ZERO, 2831373668469528n)
48
+ const cusdCredits = [
49
+ transfer(CUSD, ZERO, PAYER, 576015444067518n),
50
+ transfer(CUSD, ZERO, SEQUENCER_VAULT, 12404402010n),
51
+ transfer(CUSD, ZERO, FEE_HANDLER, 2255345820000000n),
52
+ ]
53
+
54
+ const userTransfer = transfer(USDT, OTHER, PAYER, 5800n)
55
+
56
+ describe('splitTokenFee', () => {
57
+ it('reads the net USD₮ debit and keeps the transfers of the transaction', () => {
58
+ expect(splitTokenFee(USDT_ADAPTER, PAYER, [usdtDebit, userTransfer, ...usdtCredits])).toEqual({
59
+ fees: 3176n,
60
+ feesAsset: { type: 'erc20', assetReference: USDT },
61
+ transfers: [userTransfer],
62
+ })
63
+ })
64
+
65
+ it('reads the USDC fee from the burn, the re-mint and the payments', () => {
66
+ expect(splitTokenFee(USDC_ADAPTER, PAYER, [usdcDebit, userTransfer, ...usdcCredits])).toEqual({
67
+ fees: 4072n,
68
+ feesAsset: { type: 'erc20', assetReference: USDC },
69
+ transfers: [userTransfer],
70
+ })
71
+ })
72
+
73
+ it('reads a Mento fee from the burn and the mints', () => {
74
+ expect(splitTokenFee(CUSD, PAYER, [cusdDebit, ...cusdCredits])).toEqual({
75
+ fees: 12404402010n + 2255345820000000n,
76
+ feesAsset: { type: 'erc20', assetReference: CUSD },
77
+ transfers: [],
78
+ })
79
+ })
80
+
81
+ it('reads a cEUR fee from a transaction whose only effect is its fee', () => {
82
+ // Fee logs of tx 0x6b455f0193606be12273669e67edebf8765de56e4472d7aef86b51157a889797
83
+ const transfers = [
84
+ transfer(CEUR, PAYER, ZERO, 4330420086600000n),
85
+ transfer(CEUR, ZERO, PAYER, 1706618556129060n),
86
+ transfer(CEUR, ZERO, SEQUENCER_VAULT, 454425000000000n),
87
+ transfer(CEUR, ZERO, FEE_HANDLER, 2169376530470940n),
88
+ ]
89
+
90
+ expect(splitTokenFee(CEUR, PAYER, transfers)).toEqual({
91
+ fees: 2623801530470940n,
92
+ feesAsset: { type: 'erc20', assetReference: CEUR },
93
+ transfers: [],
94
+ })
95
+ })
96
+
97
+ it('reads the fee of a failed transaction, which keeps its fee logs', () => {
98
+ // Values of tx 0x799747034724d0099d7e692b0f9ca0809184a6379dc0c5bf63dbc96e866ea9b9 (status 0)
99
+ const transfers = [
100
+ transfer(USDT, PAYER, USDT_HOLDER, 4230n),
101
+ transfer(USDT, USDT_HOLDER, SEQUENCER_VAULT, 0n),
102
+ transfer(USDT, USDT_HOLDER, FEE_HANDLER, 2816n),
103
+ transfer(USDT, USDT_HOLDER, PAYER, 1414n),
104
+ ]
105
+
106
+ expect(splitTokenFee(USDT_ADAPTER, PAYER, transfers)).toEqual({
107
+ fees: 2816n,
108
+ feesAsset: { type: 'erc20', assetReference: USDT },
109
+ transfers: [],
110
+ })
111
+ })
112
+
113
+ it('keeps a transfer of the transaction to the fee handler, in the fee token', () => {
114
+ const toFeeHandler = transfer(USDT, PAYER, FEE_HANDLER, 1000n)
115
+
116
+ const { fees, transfers } = splitTokenFee(USDT_ADAPTER, PAYER, [
117
+ usdtDebit,
118
+ toFeeHandler,
119
+ ...usdtCredits,
120
+ ])
121
+
122
+ expect(fees).toBe(3176n)
123
+ expect(transfers).toEqual([toFeeHandler])
124
+ })
125
+
126
+ it('keeps a USDC mint and payment of the transaction just before the credits', () => {
127
+ const mint = transfer(USDC, ZERO, PAYER, 100n)
128
+ const payment = transfer(USDC, PAYER, OTHER, 50n)
129
+
130
+ const { fees, transfers } = splitTokenFee(USDC_ADAPTER, PAYER, [
131
+ usdcDebit,
132
+ mint,
133
+ payment,
134
+ ...usdcCredits,
135
+ ])
136
+
137
+ expect(fees).toBe(4072n)
138
+ expect(transfers).toEqual([mint, payment])
139
+ })
140
+
141
+ it('keeps a Mento mint of the transaction just before the credits', () => {
142
+ const mint = transfer(CUSD, ZERO, PAYER, 100n)
143
+
144
+ const { fees, transfers } = splitTokenFee(CUSD, PAYER, [cusdDebit, mint, ...cusdCredits])
145
+
146
+ expect(fees).toBe(12404402010n + 2255345820000000n)
147
+ expect(transfers).toEqual([mint])
148
+ })
149
+
150
+ it('matches addresses whatever their case', () => {
151
+ expect(
152
+ splitTokenFee(USDT_ADAPTER.toLowerCase(), PAYER.toLowerCase(), [usdtDebit, ...usdtCredits])
153
+ .fees
154
+ ).toBe(3176n)
155
+ })
156
+
157
+ it('rejects an unsupported fee currency', () => {
158
+ expect(() => splitTokenFee(OTHER, PAYER, [usdtDebit, ...usdtCredits])).toThrow(
159
+ UnsupportedFeeCurrencyError
160
+ )
161
+ })
162
+
163
+ it.each([
164
+ ['a receipt without fee logs', USDT_ADAPTER, [userTransfer]],
165
+ ['a receipt with fewer than four token transfers', USDT_ADAPTER, usdtCredits],
166
+ [
167
+ 'a debit sent by another account',
168
+ USDT_ADAPTER,
169
+ [{ ...usdtDebit, from: OTHER }, ...usdtCredits],
170
+ ],
171
+ ['fee logs of another token', USDT_ADAPTER, [usdcDebit, ...usdcCredits]],
172
+ [
173
+ 'a credit not sent by the holder',
174
+ USDT_ADAPTER,
175
+ [usdtDebit, ...usdtCredits.slice(0, 2), transfer(USDT, OTHER, PAYER, 1076n)],
176
+ ],
177
+ [
178
+ 'a USDC re-mint of another amount',
179
+ USDC_ADAPTER,
180
+ [usdcDebit, transfer(USDC, ZERO, PAYER, 5019n), ...usdcCredits.slice(1)],
181
+ ],
182
+ [
183
+ 'a USDC payment not sent by the payer',
184
+ USDC_ADAPTER,
185
+ [usdcDebit, ...usdcCredits.slice(0, 2), transfer(USDC, OTHER, FEE_HANDLER, 4072n)],
186
+ ],
187
+ [
188
+ 'a Mento debit that is not a burn',
189
+ CUSD,
190
+ [transfer(CUSD, PAYER, OTHER, 2831373668469528n), ...cusdCredits],
191
+ ],
192
+ [
193
+ 'a Mento credit that is not a mint',
194
+ CEUR,
195
+ [
196
+ transfer(CEUR, PAYER, ZERO, 10n),
197
+ transfer(CEUR, ZERO, PAYER, 1n),
198
+ transfer(CEUR, ZERO, SEQUENCER_VAULT, 1n),
199
+ transfer(CEUR, PAYER, FEE_HANDLER, 8n),
200
+ ],
201
+ ],
202
+ [
203
+ 'credits larger than the debit',
204
+ USDT_ADAPTER,
205
+ [transfer(USDT, PAYER, USDT_HOLDER, 1n), ...usdtCredits],
206
+ ],
207
+ ])('rejects %s', (_, feeCurrency, transfers) => {
208
+ expect(() => splitTokenFee(feeCurrency, PAYER, transfers)).toThrow(UnexpectedFeeLogsError)
209
+ })
210
+ })
211
+
212
+ function nodeWithFeeCurrencies(feeCurrencies: Map<string, string | null>): NodeApi {
213
+ return mockNodeApi({ getFeeCurrencies: jest.fn().mockResolvedValue(feeCurrencies) })
214
+ }
215
+
216
+ describe('createCeloTokenFeeReader', () => {
217
+ const cip64Tx = {
218
+ hash: '0xABC',
219
+ from: PAYER,
220
+ type: 0x7b,
221
+ erc20Transfers: [usdtDebit, ...usdtCredits],
222
+ }
223
+
224
+ it('reads nothing for a transaction that is not CIP-64', async () => {
225
+ const nodeApi = nodeWithFeeCurrencies(new Map())
226
+
227
+ await expect(
228
+ createCeloTokenFeeReader(nodeApi, 1)({ ...cip64Tx, type: 2 })
229
+ ).resolves.toBeUndefined()
230
+ expect(nodeApi.getFeeCurrencies).not.toHaveBeenCalled()
231
+ })
232
+
233
+ it('reads nothing for a CIP-64 transaction that pays in the native coin', async () => {
234
+ const read = createCeloTokenFeeReader(nodeWithFeeCurrencies(new Map([['0xabc', null]])), 1)
235
+
236
+ await expect(read(cip64Tx)).resolves.toBeUndefined()
237
+ })
238
+
239
+ it('reads the fee currency of a transaction whose receipt has no type', async () => {
240
+ const read = createCeloTokenFeeReader(
241
+ nodeWithFeeCurrencies(
242
+ new Map([
243
+ ['0xabc', USDT_ADAPTER],
244
+ ['0xdef', null],
245
+ ])
246
+ ),
247
+ 1
248
+ )
249
+
250
+ await expect(read({ ...cip64Tx, type: undefined })).resolves.toMatchObject({ fees: 3176n })
251
+ await expect(read({ ...cip64Tx, hash: '0xDEF', type: undefined })).resolves.toBeUndefined()
252
+ })
253
+
254
+ it('reads the token fee, fetching the fee currencies of the block once', async () => {
255
+ const nodeApi = nodeWithFeeCurrencies(new Map([['0xabc', USDT_ADAPTER]]))
256
+ const read = createCeloTokenFeeReader(nodeApi, 80494727)
257
+
258
+ const [first, second] = await Promise.all([read(cip64Tx), read(cip64Tx)])
259
+
260
+ expect(first?.fees).toBe(3176n)
261
+ expect(second?.fees).toBe(3176n)
262
+ expect(nodeApi.getFeeCurrencies).toHaveBeenCalledTimes(1)
263
+ expect(nodeApi.getFeeCurrencies).toHaveBeenCalledWith(80494727)
264
+ })
265
+
266
+ it('rejects a CIP-64 transaction whose fee currency the node does not report', async () => {
267
+ const read = createCeloTokenFeeReader(nodeWithFeeCurrencies(new Map()), 1)
268
+
269
+ await expect(read(cip64Tx)).rejects.toThrow(FeeCurrencyUnavailableError)
270
+ })
271
+
272
+ it('rejects a CIP-64 transaction when the node cannot report fee currencies', async () => {
273
+ await expect(createCeloTokenFeeReader(mockNodeApi(), 1)(cip64Tx)).rejects.toThrow(
274
+ FeeCurrencyUnavailableError
275
+ )
276
+ })
277
+ })
@@ -15,7 +15,7 @@ import type { EtherscanInternalTransaction } from '../../types'
15
15
  import type { BlockOperation } from '@ledgerhq/coin-module-framework/api/index'
16
16
  import { ethers } from 'ethers'
17
17
  import { CHAIN_ID, evmDefaults, internalTxSourcesFromList } from '../../config'
18
- import { UnsupportedRpcMethodError } from '../../errors'
18
+ import { UnsupportedFeeCurrencyError, UnsupportedRpcMethodError } from '../../errors'
19
19
  import {
20
20
  createMockEvmConfigInfo,
21
21
  createMockEvmContext,
@@ -1096,7 +1096,8 @@ describe('getBlock', () => {
1096
1096
  }
1097
1097
 
1098
1098
  function mockBulkBlock(
1099
- network: Pick<EvmConfigInfo, 'chainId' | 'feeCollectorContracts'>
1099
+ network: Pick<EvmConfigInfo, 'chainId' | 'feeCollectorContracts' | 'feeCollectorTokens'>,
1100
+ otherTransfers: ERC20Transfer[] = []
1100
1101
  ): EvmContext {
1101
1102
  const context = createMockEvmContext(
1102
1103
  createMockEvmConfigInfo({
@@ -1131,6 +1132,7 @@ describe('getBlock', () => {
1131
1132
  to: USER,
1132
1133
  value: REFUND.toString(),
1133
1134
  }),
1135
+ ...otherTransfers,
1134
1136
  ],
1135
1137
  }),
1136
1138
  ]),
@@ -1333,6 +1335,109 @@ describe('getBlock', () => {
1333
1335
  expect(bootloaderNativeOps(tx.operations)).toHaveLength(2)
1334
1336
  expect(userNativeDelta(tx.operations)).toBe(-PREPAYMENT)
1335
1337
  })
1338
+
1339
+ it('drops the base-token fee legs too when the caller asks for the fee asset', async () => {
1340
+ const otherTransfer = makeNodeErc20Transfer({
1341
+ asset: { type: 'erc20', assetReference: L2_BASE_TOKEN },
1342
+ from: USER,
1343
+ to: address2,
1344
+ value: '1000',
1345
+ })
1346
+ const context = mockBulkBlock(
1347
+ {
1348
+ chainId: CHAIN_ID.ZKSYNC,
1349
+ feeCollectorContracts: [BOOTLOADER],
1350
+ feeCollectorTokens: [L2_BASE_TOKEN],
1351
+ },
1352
+ [otherTransfer]
1353
+ )
1354
+ jest.mocked(getInternalTransactionsByBlock).mockResolvedValueOnce([
1355
+ makeExplorerInternalTransaction({
1356
+ from: USER,
1357
+ to: BOOTLOADER,
1358
+ value: PREPAYMENT.toString(),
1359
+ }),
1360
+ ])
1361
+
1362
+ const [tx] = (await getBlock(context, 12345, { feesAsset: true })).transactions
1363
+
1364
+ expect(tx.operations).toEqual([
1365
+ {
1366
+ type: 'transfer',
1367
+ address: USER,
1368
+ peer: address2,
1369
+ asset: { type: 'erc20', assetReference: L2_BASE_TOKEN },
1370
+ amount: -1000n,
1371
+ },
1372
+ {
1373
+ type: 'transfer',
1374
+ address: address2,
1375
+ peer: USER,
1376
+ asset: { type: 'erc20', assetReference: L2_BASE_TOKEN },
1377
+ amount: 1000n,
1378
+ },
1379
+ ])
1380
+ expect(tx.fees).toBe(FEE)
1381
+ expect(tx.feesPayer).toBe(USER)
1382
+ expect(tx).not.toHaveProperty('feesAsset')
1383
+ })
1384
+
1385
+ it.each([
1386
+ ['no internal transfer', false],
1387
+ ['only its internal refund', true],
1388
+ ])('reads a paymaster from its base-token prepayment, with %s', async (_, withRefund) => {
1389
+ const PAYMASTER = '0xA2Aac7bC9725c36ad9B12D2407dF8de6B2B68359'
1390
+ if (withRefund) {
1391
+ jest.mocked(getInternalTransactionsByBlock).mockResolvedValueOnce([
1392
+ makeExplorerInternalTransaction({
1393
+ from: BOOTLOADER,
1394
+ to: PAYMASTER,
1395
+ value: '42357348500000',
1396
+ }),
1397
+ ])
1398
+ }
1399
+ const context = createMockEvmContext(
1400
+ createMockEvmConfigInfo({
1401
+ chainId: CHAIN_ID.ZKSYNC,
1402
+ feeCollectorContracts: [BOOTLOADER],
1403
+ feeCollectorTokens: [L2_BASE_TOKEN],
1404
+ node: mkExternalNode(),
1405
+ explorer: mkEtherscanExplorer(),
1406
+ })
1407
+ )
1408
+ mockGetBlockNodeApi(
1409
+ mockNodeApi({
1410
+ getBlockByHeight: jest.fn().mockResolvedValueOnce(
1411
+ makeNodeBlock({
1412
+ transactions: [makeNodeBlockTx({ from: USER, to: address2, value: '0' })],
1413
+ })
1414
+ ),
1415
+ getBlockReceipts: jest.fn().mockResolvedValueOnce([
1416
+ makeNodeBlockReceipt({
1417
+ erc20Transfers: [
1418
+ makeNodeErc20Transfer({
1419
+ asset: { type: 'erc20', assetReference: L2_BASE_TOKEN },
1420
+ from: PAYMASTER,
1421
+ to: BOOTLOADER,
1422
+ value: '49775000000000',
1423
+ }),
1424
+ makeNodeErc20Transfer({
1425
+ asset: { type: 'erc20', assetReference: L2_BASE_TOKEN },
1426
+ from: BOOTLOADER,
1427
+ to: PAYMASTER,
1428
+ value: '42357348500000',
1429
+ }),
1430
+ ],
1431
+ }),
1432
+ ]),
1433
+ })
1434
+ )
1435
+
1436
+ const [tx] = (await getBlock(context, 12345, { feesAsset: true })).transactions
1437
+
1438
+ expect(tx.feesPayer).toBe(PAYMASTER)
1439
+ expect(tx.operations).toEqual([])
1440
+ })
1336
1441
  })
1337
1442
 
1338
1443
  it('when explorer is not etherscan like, falls back to node.traceBlockErigon', async () => {
@@ -2195,6 +2300,148 @@ describe('getBlock', () => {
2195
2300
  ])
2196
2301
  })
2197
2302
  })
2303
+
2304
+ describe('Celo CIP-64 fee currencies', () => {
2305
+ // Fee logs of tx 0x45e41cf20fca9b079f8b23510bb9637d14df647cb6d25d85157924cd27df09d7 (block
2306
+ // 80494727), which pays its fee in USD₮ through the USD₮ adapter
2307
+ const PAYER = '0x5362C723476b46a1e65D54E667C00e46b46F6f12'
2308
+ const USDT = '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e'
2309
+ const USDT_ADAPTER = '0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72'
2310
+ const HOLDER = '0x000000000000000000000000000000000Ce106A5'
2311
+ const FEE_HANDLER = '0xcD437749E43A154C07F3553504c68fBfD56B8778'
2312
+ const SEQUENCER_VAULT = '0x4200000000000000000000000000000000000011'
2313
+ const GAS_USED = '100000'
2314
+ const GAS_PRICE = '31763731729'
2315
+ const NATIVE_FEES = 3176373172900000n
2316
+
2317
+ const usdt = (from: string, to: string, value: string): ERC20Transfer =>
2318
+ makeNodeErc20Transfer({ asset: { type: 'erc20', assetReference: USDT }, from, to, value })
2319
+ const userTransfer = usdt(address2, PAYER, '5800')
2320
+ const transfers = [
2321
+ usdt(PAYER, HOLDER, '4252'),
2322
+ userTransfer,
2323
+ usdt(HOLDER, SEQUENCER_VAULT, '0'),
2324
+ usdt(HOLDER, FEE_HANDLER, '3176'),
2325
+ usdt(HOLDER, PAYER, '1076'),
2326
+ ]
2327
+ const userOperations: BlockOperation[] = [
2328
+ {
2329
+ type: 'transfer',
2330
+ address: address2,
2331
+ peer: PAYER,
2332
+ asset: { type: 'erc20', assetReference: USDT },
2333
+ amount: -5800n,
2334
+ },
2335
+ {
2336
+ type: 'transfer',
2337
+ address: PAYER,
2338
+ peer: address2,
2339
+ asset: { type: 'erc20', assetReference: USDT },
2340
+ amount: 5800n,
2341
+ },
2342
+ ]
2343
+
2344
+ function mockCeloBlock({
2345
+ chainId = CHAIN_ID.CELO,
2346
+ feeCurrency = USDT_ADAPTER,
2347
+ prefetched = true,
2348
+ receiptType = 0x7b,
2349
+ }: {
2350
+ chainId?: ChainId
2351
+ feeCurrency?: string | null
2352
+ prefetched?: boolean
2353
+ receiptType?: number | null
2354
+ } = {}): { context: EvmContext; nodeApi: ReturnType<typeof mockNodeApi> } {
2355
+ const context = createMockEvmContext(
2356
+ createMockEvmConfigInfo({
2357
+ chainId,
2358
+ node: mkExternalNode(),
2359
+ explorer: mkEtherscanExplorer(),
2360
+ })
2361
+ )
2362
+ const receipt = {
2363
+ hash: '0xtx1',
2364
+ gasUsed: GAS_USED,
2365
+ gasPrice: GAS_PRICE,
2366
+ ...(receiptType !== null ? { type: receiptType } : {}),
2367
+ erc20Transfers: transfers,
2368
+ }
2369
+ const nodeApi = mockNodeApi({
2370
+ getBlockByHeight: jest.fn().mockResolvedValueOnce(
2371
+ prefetched
2372
+ ? makeNodeBlock({
2373
+ transactions: [makeNodeBlockTx({ from: PAYER, value: '0', gasPrice: GAS_PRICE })],
2374
+ })
2375
+ : makeNodeBlock({ transactionHashes: ['0xtx1'] })
2376
+ ),
2377
+ getBlockReceipts: jest.fn().mockResolvedValueOnce([makeNodeBlockReceipt(receipt)]),
2378
+ getTransaction: jest
2379
+ .fn()
2380
+ .mockResolvedValueOnce(makeNodeTxInfo({ ...receipt, from: PAYER, value: '0' })),
2381
+ getFeeCurrencies: jest.fn().mockResolvedValue(new Map([['0xtx1', feeCurrency]])),
2382
+ })
2383
+ mockGetBlockNodeApi(nodeApi)
2384
+ return { context, nodeApi }
2385
+ }
2386
+
2387
+ it.each([
2388
+ ['prefetched with block receipts', true, 0x7b],
2389
+ ['fetched one by one', false, 0x7b],
2390
+ ['whose block receipt has no type', true, null],
2391
+ ])(
2392
+ 'reports the token fee and drops the fee logs, on a transaction %s',
2393
+ async (_, prefetched, receiptType) => {
2394
+ const { context, nodeApi } = mockCeloBlock({ prefetched, receiptType })
2395
+
2396
+ const [tx] = (await getBlock(context, 12345, { feesAsset: true })).transactions
2397
+
2398
+ expect(tx.fees).toBe(3176n)
2399
+ expect(tx.feesAsset).toEqual({ type: 'erc20', assetReference: USDT })
2400
+ expect(tx.feesPayer).toBe(PAYER)
2401
+ expect(tx.operations).toEqual(userOperations)
2402
+ expect(nodeApi.getFeeCurrencies).toHaveBeenCalledWith(12345)
2403
+ }
2404
+ )
2405
+
2406
+ it('keeps the native fee and the fee logs when the caller does not ask for the fee asset', async () => {
2407
+ const { context, nodeApi } = mockCeloBlock()
2408
+
2409
+ const [tx] = (await getBlock(context, 12345)).transactions
2410
+
2411
+ expect(tx.fees).toBe(NATIVE_FEES)
2412
+ expect(tx).not.toHaveProperty('feesAsset')
2413
+ expect(tx.operations).toHaveLength(transfers.length * 2)
2414
+ expect(nodeApi.getFeeCurrencies).not.toHaveBeenCalled()
2415
+ })
2416
+
2417
+ it('keeps the native fee of a CIP-64 transaction that pays in the native coin', async () => {
2418
+ const { context } = mockCeloBlock({ feeCurrency: null })
2419
+
2420
+ const [tx] = (await getBlock(context, 12345, { feesAsset: true })).transactions
2421
+
2422
+ expect(tx.fees).toBe(NATIVE_FEES)
2423
+ expect(tx).not.toHaveProperty('feesAsset')
2424
+ expect(tx.operations).toHaveLength(transfers.length * 2)
2425
+ })
2426
+
2427
+ it('does not read fee currencies on another chain', async () => {
2428
+ const { context, nodeApi } = mockCeloBlock({ chainId: CHAIN_ID.ETHEREUM })
2429
+
2430
+ const [tx] = (await getBlock(context, 12345, { feesAsset: true })).transactions
2431
+
2432
+ expect(tx.fees).toBe(NATIVE_FEES)
2433
+ expect(tx).not.toHaveProperty('feesAsset')
2434
+ expect(nodeApi.getFeeCurrencies).not.toHaveBeenCalled()
2435
+ })
2436
+
2437
+ it('rejects a block with a transaction paid in an unsupported fee currency', async () => {
2438
+ const { context } = mockCeloBlock({ feeCurrency: address2 })
2439
+
2440
+ await expect(getBlock(context, 12345, { feesAsset: true })).rejects.toThrow(
2441
+ UnsupportedFeeCurrencyError
2442
+ )
2443
+ })
2444
+ })
2198
2445
  })
2199
2446
 
2200
2447
  describe('dropRootTraceDuplicates', () => {
@@ -965,6 +965,34 @@ async function getBlockReceipts(
965
965
  })
966
966
  }
967
967
 
968
+ async function getFeeCurrencies(
969
+ api: JsonRpcProvider,
970
+ blockHeight: number
971
+ ): Promise<Map<string, string | null>> {
972
+ const rawBlock: unknown = await api.send('eth_getBlockByNumber', [
973
+ ethers.toQuantity(blockHeight),
974
+ true,
975
+ ])
976
+ if (!isRecord(rawBlock) || !Array.isArray(rawBlock.transactions))
977
+ throw new MalformedNodeResponse('Invalid eth_getBlockByNumber response')
978
+
979
+ const feeCurrencies = new Map<string, string | null>()
980
+ for (const [index, tx] of rawBlock.transactions.entries()) {
981
+ if (!isRecord(tx) || typeof tx.hash !== 'string')
982
+ throw new MalformedNodeResponse(
983
+ `Malformed block transaction at index ${index} in eth_getBlockByNumber response`
984
+ )
985
+ // op-geth omits `feeCurrency` when the fee is paid in the native coin
986
+ const feeCurrency = tx.feeCurrency ?? null
987
+ if (feeCurrency !== null && typeof feeCurrency !== 'string')
988
+ throw new MalformedNodeResponse(
989
+ `Malformed feeCurrency at index ${index} in eth_getBlockByNumber response`
990
+ )
991
+ feeCurrencies.set(tx.hash.toLowerCase(), feeCurrency)
992
+ }
993
+ return feeCurrencies
994
+ }
995
+
968
996
  async function traceBlockGeth(
969
997
  api: JsonRpcProvider,
970
998
  blockHeight: number
@@ -1181,6 +1209,7 @@ export function createNodeApi(
1181
1209
  withApi(evmConfig, (api) => getTransaction(api, txHash, logger), nodeConfig),
1182
1210
  getBlockReceipts: (blockHeight) =>
1183
1211
  withApi(evmConfig, (api) => getBlockReceipts(api, blockHeight, logger), nodeConfig),
1212
+ getFeeCurrencies: make(getFeeCurrencies, evmConfig, nodeConfig),
1184
1213
  traceBlockErigon: make(traceBlockErigon, evmConfig, nodeConfig),
1185
1214
  traceBlockGeth: make(traceBlockGeth, evmConfig, nodeConfig),
1186
1215
  getGasEstimation: makeGetGasEstimation(evmConfig, nodeConfig, logger),
@@ -183,6 +183,12 @@ export type NodeApi = {
183
183
  // timestamp is in milliseconds
184
184
  ) => Promise<BlockByHeightResult>
185
185
  getBlockReceipts?: (blockHeight: number | 'latest') => Promise<BlockReceiptInfo[]>
186
+ /**
187
+ * The Celo CIP-64 `feeCurrency` of each transaction of a block, by lower-case hash: `null` when
188
+ * the transaction pays its fee in the native coin, which the node shows by omitting the field.
189
+ * Ethers drops the field, so this reads the raw block.
190
+ */
191
+ getFeeCurrencies?: (blockHeight: number) => Promise<Map<string, string | null>>
186
192
  traceBlockErigon?: (blockHeight: number | 'latest') => Promise<TraceBlockItem[]>
187
193
  traceBlockGeth?: (blockHeight: number) => Promise<TraceBlockItem[]>
188
194
  getOptimismAdditionalFees: (transaction: string) => Promise<BigNumber>
@@ -56,6 +56,9 @@ export function createFailoverNodeApi(sources: NodeApi[], logger: Logger): NodeA
56
56
  if (sources.some((api) => api.getBlockReceipts))
57
57
  base.getBlockReceipts = (h): Promise<BlockReceiptInfo[]> =>
58
58
  tryInOrder('getBlockReceipts', (api) => api.getBlockReceipts?.(h))
59
+ if (sources.some((api) => api.getFeeCurrencies))
60
+ base.getFeeCurrencies = (h): Promise<Map<string, string | null>> =>
61
+ tryInOrder('getFeeCurrencies', (api) => api.getFeeCurrencies?.(h))
59
62
  if (sources.some((api) => api.traceBlockErigon))
60
63
  base.traceBlockErigon = (h): Promise<TraceBlockItem[]> =>
61
64
  tryInOrder('traceBlockErigon', (api) => api.traceBlockErigon?.(h))
@@ -1902,6 +1902,45 @@ describe('EVM Family', () => {
1902
1902
  })
1903
1903
  })
1904
1904
 
1905
+ describe('getFeeCurrencies', () => {
1906
+ it('reads the fee currency of each transaction from the raw block, an omitted one as native', async () => {
1907
+ const send = mockRawRpc({
1908
+ eth_getBlockByNumber: {
1909
+ transactions: [
1910
+ {
1911
+ hash: '0xAA',
1912
+ type: '0x7b',
1913
+ feeCurrency: '0x0e2a3e05bc9a16f5292a6170456a710cb89c6f72',
1914
+ },
1915
+ { hash: '0xbb', type: '0x7b', feeCurrency: null },
1916
+ { hash: '0xcc', type: '0x7b' },
1917
+ ],
1918
+ },
1919
+ })
1920
+
1921
+ expect(await nodeApi.getFeeCurrencies!(80494727)).toEqual(
1922
+ new Map([
1923
+ ['0xaa', '0x0e2a3e05bc9a16f5292a6170456a710cb89c6f72'],
1924
+ ['0xbb', null],
1925
+ ['0xcc', null],
1926
+ ])
1927
+ )
1928
+ expect(send).toHaveBeenCalledWith('eth_getBlockByNumber', ['0x4cc4087', true])
1929
+ })
1930
+
1931
+ it.each([
1932
+ ['a block without transactions', undefined],
1933
+ ['a transaction without hash', [{ feeCurrency: null }]],
1934
+ ['a malformed fee currency', [{ hash: '0xaa', feeCurrency: 1 }]],
1935
+ ])('rejects %s', async (_, transactions) => {
1936
+ mockRawRpc({ eth_getBlockByNumber: { transactions } })
1937
+
1938
+ await expect(nodeApi.getFeeCurrencies!(1)).rejects.toMatchObject({
1939
+ name: 'MalformedNodeResponse',
1940
+ })
1941
+ })
1942
+ })
1943
+
1905
1944
  describe('traceBlockErigon', () => {
1906
1945
  it('should return trace array when trace_block is supported', async () => {
1907
1946
  const traceItem = {