@ledgerhq/coin-evm 16.5.2 → 16.5.3

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 (64) hide show
  1. package/CHANGELOG.md +6 -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 +84 -29
  19. package/lib/network/node/rpc.common.js.map +1 -1
  20. package/lib-es/config.d.ts +9 -0
  21. package/lib-es/config.d.ts.map +1 -1
  22. package/lib-es/config.js +4 -0
  23. package/lib-es/config.js.map +1 -1
  24. package/lib-es/errors.d.ts +15 -0
  25. package/lib-es/errors.d.ts.map +1 -1
  26. package/lib-es/errors.js +27 -0
  27. package/lib-es/errors.js.map +1 -1
  28. package/lib-es/logic/feeCollectorOperations.d.ts +61 -0
  29. package/lib-es/logic/feeCollectorOperations.d.ts.map +1 -0
  30. package/lib-es/logic/feeCollectorOperations.js +201 -0
  31. package/lib-es/logic/feeCollectorOperations.js.map +1 -0
  32. package/lib-es/logic/listOperations.d.ts.map +1 -1
  33. package/lib-es/logic/listOperations.js +4 -1
  34. package/lib-es/logic/listOperations.js.map +1 -1
  35. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  36. package/lib-es/network/node/rpc.common.js +85 -30
  37. package/lib-es/network/node/rpc.common.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/api/tests/getBlock.integ.test.ts +3 -32
  40. package/src/api/tests/index.alpen_testnet.integ.test.ts +2 -7
  41. package/src/api/tests/index.arbitrum.integ.test.ts +2 -12
  42. package/src/api/tests/index.arc.integ.test.ts +2 -13
  43. package/src/api/tests/index.avalanche_c_chain_fuji.integ.test.ts +2 -12
  44. package/src/api/tests/index.cronos.integ.test.ts +2 -12
  45. package/src/api/tests/index.flare.integ.test.ts +2 -8
  46. package/src/api/tests/index.integ.test.ts +5 -35
  47. package/src/api/tests/index.linea.integ.test.ts +2 -15
  48. package/src/api/tests/index.monad_testnet.integ.test.ts +5 -13
  49. package/src/api/tests/index.optimism.integ.test.ts +2 -12
  50. package/src/api/tests/index.rsk.integ.test.ts +2 -12
  51. package/src/api/tests/index.scroll.integ.test.ts +4 -7
  52. package/src/api/tests/index.shape.integ.test.ts +3 -27
  53. package/src/api/tests/index.somnia.integ.test.ts +2 -6
  54. package/src/api/tests/index.unichain.integ.test.ts +2 -12
  55. package/src/api/tests/index.zksync.integ.test.ts +5 -8
  56. package/src/config.ts +11 -0
  57. package/src/errors.ts +27 -0
  58. package/src/logic/feeCollectorOperations.ts +272 -0
  59. package/src/logic/listOperations.ts +20 -1
  60. package/src/logic/tests/broadcast.integ.test.ts +4 -15
  61. package/src/logic/tests/listOperations.test.ts +563 -0
  62. package/src/network/node/rpc.common.ts +128 -30
  63. package/src/network/tests/node/rpc.test.ts +79 -7
  64. package/src/staking/validators.integ.test.ts +5 -22
@@ -0,0 +1,272 @@
1
+ // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { EvmConfigInfo } from '../config'
5
+ import type { ERC20Transfer } from '../network/node/types'
6
+ import type { MemoNotSupported, Operation } from '@ledgerhq/coin-module-framework/api/types'
7
+ import type { Logger } from '@ledgerhq/coin-module-framework/config'
8
+ import { promiseAllBatched } from '@ledgerhq/coin-module-framework/promises'
9
+ import { makeLRUCache } from '@ledgerhq/live-network/cache'
10
+ import { getNodeApi } from '../network/node'
11
+
12
+ type Op = Operation<MemoNotSupported>
13
+
14
+ // Receipts read in parallel, as getBlock does for transactions it fetches one by one
15
+ const MAX_RECEIPT_CONCURRENCY = 2
16
+
17
+ /**
18
+ * True when a transfer moves the fee: a positive amount of the native coin, as a native transfer
19
+ * or as one of the network's `feeCollectorTokens` (the zkSync base token). Another token sent to a
20
+ * fee collector does not pay the fee.
21
+ *
22
+ * @param feeCollectorTokens lower-cased `feeCollectorTokens` of the network
23
+ */
24
+ function isFeePayment(
25
+ asset: { type: string; assetReference?: string },
26
+ amount: bigint,
27
+ feeCollectorTokens: ReadonlySet<string>
28
+ ): boolean {
29
+ if (amount <= 0n) return false
30
+ if (asset.type === 'native') return true
31
+ return (
32
+ asset.assetReference !== undefined && feeCollectorTokens.has(asset.assetReference.toLowerCase())
33
+ )
34
+ }
35
+
36
+ function lowerCased(addresses: readonly string[] | undefined): Set<string> {
37
+ return new Set((addresses ?? []).map((address) => address.toLowerCase()))
38
+ }
39
+
40
+ /**
41
+ * The ERC-20 transfers of a transaction, from its receipt. A mined transaction keeps them, so each
42
+ * receipt is read once: a sync of the whole history does not read the receipts of the transactions
43
+ * paid by others again. Kept per chain and transaction, before any network setting applies. A
44
+ * failed read is not kept.
45
+ */
46
+ export const readReceiptTransfers = makeLRUCache(
47
+ async (config: EvmConfigInfo, logger: Logger, hash: string): Promise<ERC20Transfer[]> => {
48
+ const { erc20Transfers } = await getNodeApi(config, logger).getTransaction(hash)
49
+ return erc20Transfers
50
+ },
51
+ (config, _logger, hash) => `${config.chainId}:${hash}`,
52
+ { max: 10_000, ttl: 24 * 60 * 60 * 1000 }
53
+ )
54
+
55
+ /**
56
+ * The accounts that sent the network's fee collectors a fee payment in a transaction (see
57
+ * {@link isFeePayment}), lowercase, from its receipt.
58
+ */
59
+ async function findFeeCollectorPrepayers(
60
+ config: EvmConfigInfo,
61
+ logger: Logger,
62
+ hash: string
63
+ ): Promise<string[]> {
64
+ const collectors = lowerCased(config.feeCollectorContracts)
65
+ const tokens = lowerCased(config.feeCollectorTokens)
66
+ const transfers = await readReceiptTransfers(config, logger, hash)
67
+ return transfers
68
+ .filter(
69
+ (transfer) =>
70
+ collectors.has(transfer.to.toLowerCase()) &&
71
+ isFeePayment(transfer.asset, BigInt(transfer.value), tokens)
72
+ )
73
+ .map((transfer) => transfer.from.toLowerCase())
74
+ }
75
+
76
+ type AddressMatchers = {
77
+ isAccount: (other: string) => boolean
78
+ isCollector: (other: string) => boolean
79
+ }
80
+
81
+ function addressMatchers(
82
+ address: string,
83
+ feeCollectorContracts: readonly string[]
84
+ ): AddressMatchers {
85
+ const account = address.toLowerCase()
86
+ const collectors = new Set(feeCollectorContracts.map((contract) => contract.toLowerCase()))
87
+ return {
88
+ isAccount: (other: string): boolean => other.toLowerCase() === account,
89
+ isCollector: (other: string): boolean => collectors.has(other.toLowerCase()),
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The account, as the explorer spells it (EIP-55), by hash of the transactions its history shows
95
+ * it paid: a fee payment from the account to a fee collector (see {@link isFeePayment}), on zkSync
96
+ * the base-token (`0x800A`, a `feeCollectorTokens` entry) prepayment to the bootloader.
97
+ */
98
+ function findPrepayments(
99
+ address: string,
100
+ feeCollectorContracts: readonly string[],
101
+ feeCollectorTokens: readonly string[],
102
+ evidence: readonly Op[]
103
+ ): Map<string, string> {
104
+ const { isAccount, isCollector } = addressMatchers(address, feeCollectorContracts)
105
+ const tokens = lowerCased(feeCollectorTokens)
106
+ const payers = new Map<string, string>()
107
+ for (const op of evidence) {
108
+ const sender = op.senders.find(isAccount)
109
+ if (sender === undefined || !op.recipients.some(isCollector)) continue
110
+ if (isFeePayment(op.asset, op.value, tokens)) payers.set(op.tx.hash, sender)
111
+ }
112
+ return payers
113
+ }
114
+
115
+ /**
116
+ * Finds the transactions whose fee the explorer charges to the account but that another account
117
+ * paid, on a network that collects the fee in a contract (see `feeCollectorContracts`).
118
+ *
119
+ * The explorer names the sender as the fee payer. When the account history has no prepayment of
120
+ * the account to a fee collector for such a transaction, its receipt tells who paid: a zkSync
121
+ * paymaster prepays the fee to the bootloader, and an L1→L2 deposit pays it on L1. A transaction
122
+ * whose receipt cannot be read keeps the explorer's fee payer.
123
+ *
124
+ * @param operations operations of the account, as listOperations returns them
125
+ * @param evidence the token, NFT and internal operations of the account from the explorer
126
+ * @returns hashes of the transactions the account did not pay
127
+ */
128
+ export async function findTransactionsPaidByOthers(
129
+ config: EvmConfigInfo,
130
+ logger: Logger,
131
+ address: string,
132
+ operations: readonly Op[],
133
+ evidence: readonly Op[]
134
+ ): Promise<Set<string>> {
135
+ const feeCollectorContracts = config.feeCollectorContracts ?? []
136
+ if (feeCollectorContracts.length === 0) return new Set()
137
+
138
+ const { isAccount } = addressMatchers(address, feeCollectorContracts)
139
+ const prepayments = findPrepayments(
140
+ address,
141
+ feeCollectorContracts,
142
+ config.feeCollectorTokens ?? [],
143
+ evidence
144
+ )
145
+ const unconfirmed = [
146
+ ...new Set(
147
+ operations
148
+ .filter((op) => op.tx.feesPayer !== undefined && isAccount(op.tx.feesPayer))
149
+ .map((op) => op.tx.hash)
150
+ .filter((hash) => !prepayments.has(hash))
151
+ ),
152
+ ]
153
+ if (unconfirmed.length === 0) return new Set()
154
+
155
+ const paidByOthers = await promiseAllBatched(
156
+ MAX_RECEIPT_CONCURRENCY,
157
+ unconfirmed,
158
+ async (hash) => {
159
+ try {
160
+ const prepayers = await findFeeCollectorPrepayers(config, logger, hash)
161
+ return prepayers.some(isAccount) ? undefined : hash
162
+ } catch (error) {
163
+ logger('warn', 'EVM listOperations: cannot read the receipt to find the fee payer', {
164
+ currency: config.name,
165
+ hash,
166
+ error,
167
+ })
168
+ return undefined
169
+ }
170
+ }
171
+ )
172
+ return new Set(paidByOthers.filter((hash): hash is string => hash !== undefined))
173
+ }
174
+
175
+ /**
176
+ * Gives the operations of an account the fee payer seen from the account's own history, on a
177
+ * network that collects the fee in a contract (see `feeCollectorContracts`, e.g. the zkSync
178
+ * bootloader).
179
+ *
180
+ * The account paid the fee of a transaction when its history has a transfer from the account to a
181
+ * fee collector in that transaction (see {@link findPrepayments}):
182
+ * - a paying account is the `feesPayer` of all its operations of the transaction, which carry
183
+ * the fee of the transaction, from whichever of its operations knows it;
184
+ * - an account that another account paid for (see {@link findTransactionsPaidByOthers}) is never
185
+ * the `feesPayer`: ADR-016 leaves the payer unset when it is unknown, rather than defaulting
186
+ * to the sender.
187
+ *
188
+ * The internal native transfers between a paying account and a fee collector move the fee, which
189
+ * `fees` holds: keeping them would debit the account twice, so they are dropped when another
190
+ * operation of the transaction gives the fee. Internal operations carry none, so without one the
191
+ * native transfers stay, as the only trace of what the account paid. When one was the only
192
+ * operation of the transaction for the account, a value-0 `FEES` operation carries the fee
193
+ * instead, as ADR-016 allows.
194
+ *
195
+ * The fee also moves as base-token transfers (zkSync `0x800A`), which stay as token operations,
196
+ * as `getBlock` keeps them (BACK-11036). ADR-068 (proposed) would remove fee movements in every
197
+ * asset, behind an opt-in option; this function does not follow it.
198
+ *
199
+ * @param operations operations of the account, as listOperations returns them
200
+ * @param address the account
201
+ * @param feeCollectorContracts fee collector contracts of the network
202
+ * @param feeCollectorTokens tokens that carry the native coin to those contracts
203
+ * @param evidence the token, NFT and internal operations of the account from the explorer, before
204
+ * listOperations drops any of them
205
+ * @param paidByOthers hashes of the transactions the account did not pay
206
+ */
207
+ export function attributeFeeCollectorPayments(
208
+ operations: Op[],
209
+ address: string,
210
+ feeCollectorContracts: readonly string[],
211
+ feeCollectorTokens: readonly string[],
212
+ evidence: readonly Op[],
213
+ paidByOthers: ReadonlySet<string>
214
+ ): Op[] {
215
+ if (feeCollectorContracts.length === 0) return operations
216
+
217
+ const { isAccount, isCollector } = addressMatchers(address, feeCollectorContracts)
218
+ const payers = findPrepayments(address, feeCollectorContracts, feeCollectorTokens, evidence)
219
+
220
+ const feesByHash = new Map<string, bigint>()
221
+ for (const op of [...operations, ...evidence]) {
222
+ if (op.tx.fees > (feesByHash.get(op.tx.hash) ?? 0n)) feesByHash.set(op.tx.hash, op.tx.fees)
223
+ }
224
+
225
+ // Only the payer's transfers move the fee: a refund to an account that did not pay, such as the
226
+ // refund recipient of an L1→L2 deposit, is a real credit
227
+ const isFeeLeg = (op: Op): boolean =>
228
+ payers.has(op.tx.hash) &&
229
+ feesByHash.has(op.tx.hash) &&
230
+ op.asset.type === 'native' &&
231
+ ((op.senders.some(isAccount) && op.recipients.some(isCollector)) ||
232
+ (op.senders.some(isCollector) && op.recipients.some(isAccount)))
233
+
234
+ const feeLegs = operations.filter(isFeeLeg)
235
+ const kept = operations.filter((op) => !isFeeLeg(op))
236
+
237
+ const attributed = kept.map((op) => {
238
+ const payer = payers.get(op.tx.hash)
239
+ if (payer !== undefined) {
240
+ const fees = feesByHash.get(op.tx.hash) ?? op.tx.fees
241
+ return { ...op, tx: { ...op.tx, fees, feesPayer: payer } }
242
+ }
243
+ if (
244
+ !paidByOthers.has(op.tx.hash) ||
245
+ op.tx.feesPayer === undefined ||
246
+ !isAccount(op.tx.feesPayer)
247
+ ) {
248
+ return op
249
+ }
250
+ const { feesPayer: _notThePayer, ...tx } = op.tx
251
+ return { ...op, tx }
252
+ })
253
+
254
+ const keptHashes = new Set(kept.map((op) => op.tx.hash))
255
+ const carriers = new Map<string, Op>()
256
+ for (const leg of feeLegs) {
257
+ if (keptHashes.has(leg.tx.hash) || carriers.has(leg.tx.hash)) continue
258
+ carriers.set(leg.tx.hash, {
259
+ ...leg,
260
+ id: `${leg.id}-FEES`,
261
+ type: 'FEES',
262
+ value: 0n,
263
+ tx: {
264
+ ...leg.tx,
265
+ fees: feesByHash.get(leg.tx.hash) ?? 0n,
266
+ feesPayer: payers.get(leg.tx.hash) ?? leg.senders[0],
267
+ },
268
+ })
269
+ }
270
+
271
+ return [...attributed, ...carriers.values()]
272
+ }
@@ -10,6 +10,10 @@ import type {
10
10
  } from '@ledgerhq/coin-module-framework/api/types'
11
11
  import { InvalidParameterError } from '@ledgerhq/coin-module-framework/errors'
12
12
  import { getExplorerApi } from '../network/explorer'
13
+ import {
14
+ attributeFeeCollectorPayments,
15
+ findTransactionsPaidByOthers,
16
+ } from './feeCollectorOperations'
13
17
 
14
18
  // the sort parameter has a double meaning:
15
19
  // - legacy (for the bridge): it's used to sort the operations in the result list. Explorer always queried in "desc" order.
@@ -277,11 +281,26 @@ export async function listOperations(
277
281
  const nativeExpanded = expandSelfSendToTwoOps(nativeWithPerspective, address)
278
282
  const tokenExpanded = expandSelfSendToTwoOps(tokenOperations, address)
279
283
 
280
- const operations = nativeExpanded
284
+ const accountOperations = nativeExpanded
281
285
  .concat(tokenExpanded)
282
286
  .concat(internalOperations)
283
287
  .filter(hasValidType)
284
288
  .filter(isAddressInvolved)
289
+ const feeEvidence = [...lastTokenOperations, ...lastNftOperations, ...lastInternalOperations]
290
+ const operations = attributeFeeCollectorPayments(
291
+ accountOperations,
292
+ address,
293
+ config.feeCollectorContracts ?? [],
294
+ config.feeCollectorTokens ?? [],
295
+ feeEvidence,
296
+ await findTransactionsPaidByOthers(
297
+ config,
298
+ context.logger,
299
+ address,
300
+ accountOperations,
301
+ feeEvidence
302
+ )
303
+ )
285
304
 
286
305
  operations.sort((a, b) =>
287
306
  options.order === 'asc'
@@ -3,27 +3,16 @@
3
3
 
4
4
  import type { EvmContext } from '../../config'
5
5
  import { Wallet } from 'ethers'
6
- import {
7
- createMockEvmConfigInfo,
8
- createMockEvmContext,
9
- mkExternalNode,
10
- mkLedgerNode,
11
- } from '../../fixtures/context.fixtures'
6
+ import { evmDefaults } from '../../config'
7
+ import { createMockEvmContext } from '../../fixtures/context.fixtures'
12
8
  import broadcast from '../broadcast'
13
9
 
14
10
  const contextForNetwork = (network: string): EvmContext => {
15
11
  switch (network) {
16
12
  case 'ethereum':
17
- return createMockEvmContext(
18
- createMockEvmConfigInfo({ chainId: 1, node: mkLedgerNode({ explorerId: 'eth' }) })
19
- )
13
+ return createMockEvmContext(evmDefaults.ethereum)
20
14
  case 'sonic':
21
- return createMockEvmContext(
22
- createMockEvmConfigInfo({
23
- chainId: 146,
24
- node: mkExternalNode({ uri: 'https://sonic.coin.ledger.com' }),
25
- })
26
- )
15
+ return createMockEvmContext(evmDefaults.sonic)
27
16
  default:
28
17
  throw new Error('Unhandled currency')
29
18
  }