@ledgerhq/coin-evm 16.5.1 → 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 (73) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/chains.d.ts +0 -1
  3. package/lib/chains.d.ts.map +1 -1
  4. package/lib/chains.js +0 -1
  5. package/lib/chains.js.map +1 -1
  6. package/lib/config.d.ts +9 -0
  7. package/lib/config.d.ts.map +1 -1
  8. package/lib/config.js +4 -0
  9. package/lib/config.js.map +1 -1
  10. package/lib/errors.d.ts +15 -0
  11. package/lib/errors.d.ts.map +1 -1
  12. package/lib/errors.js +31 -1
  13. package/lib/errors.js.map +1 -1
  14. package/lib/logic/feeCollectorOperations.d.ts +61 -0
  15. package/lib/logic/feeCollectorOperations.d.ts.map +1 -0
  16. package/lib/logic/feeCollectorOperations.js +206 -0
  17. package/lib/logic/feeCollectorOperations.js.map +1 -0
  18. package/lib/logic/listOperations.d.ts.map +1 -1
  19. package/lib/logic/listOperations.js +4 -1
  20. package/lib/logic/listOperations.js.map +1 -1
  21. package/lib/network/node/rpc.common.d.ts.map +1 -1
  22. package/lib/network/node/rpc.common.js +84 -29
  23. package/lib/network/node/rpc.common.js.map +1 -1
  24. package/lib-es/chains.d.ts +0 -1
  25. package/lib-es/chains.d.ts.map +1 -1
  26. package/lib-es/chains.js +0 -1
  27. package/lib-es/chains.js.map +1 -1
  28. package/lib-es/config.d.ts +9 -0
  29. package/lib-es/config.d.ts.map +1 -1
  30. package/lib-es/config.js +4 -0
  31. package/lib-es/config.js.map +1 -1
  32. package/lib-es/errors.d.ts +15 -0
  33. package/lib-es/errors.d.ts.map +1 -1
  34. package/lib-es/errors.js +27 -0
  35. package/lib-es/errors.js.map +1 -1
  36. package/lib-es/logic/feeCollectorOperations.d.ts +61 -0
  37. package/lib-es/logic/feeCollectorOperations.d.ts.map +1 -0
  38. package/lib-es/logic/feeCollectorOperations.js +201 -0
  39. package/lib-es/logic/feeCollectorOperations.js.map +1 -0
  40. package/lib-es/logic/listOperations.d.ts.map +1 -1
  41. package/lib-es/logic/listOperations.js +4 -1
  42. package/lib-es/logic/listOperations.js.map +1 -1
  43. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  44. package/lib-es/network/node/rpc.common.js +85 -30
  45. package/lib-es/network/node/rpc.common.js.map +1 -1
  46. package/package.json +2 -2
  47. package/src/api/tests/getBlock.integ.test.ts +5 -102
  48. package/src/api/tests/index.alpen_testnet.integ.test.ts +2 -7
  49. package/src/api/tests/index.arbitrum.integ.test.ts +2 -12
  50. package/src/api/tests/index.arc.integ.test.ts +2 -13
  51. package/src/api/tests/index.avalanche_c_chain_fuji.integ.test.ts +2 -12
  52. package/src/api/tests/index.cronos.integ.test.ts +2 -12
  53. package/src/api/tests/index.flare.integ.test.ts +2 -8
  54. package/src/api/tests/index.integ.test.ts +5 -35
  55. package/src/api/tests/index.linea.integ.test.ts +2 -15
  56. package/src/api/tests/index.monad_testnet.integ.test.ts +5 -13
  57. package/src/api/tests/index.optimism.integ.test.ts +2 -12
  58. package/src/api/tests/index.rsk.integ.test.ts +2 -12
  59. package/src/api/tests/index.scroll.integ.test.ts +4 -7
  60. package/src/api/tests/index.shape.integ.test.ts +3 -27
  61. package/src/api/tests/index.somnia.integ.test.ts +2 -6
  62. package/src/api/tests/index.unichain.integ.test.ts +2 -12
  63. package/src/api/tests/index.zksync.integ.test.ts +5 -8
  64. package/src/chains.ts +0 -1
  65. package/src/config.ts +11 -0
  66. package/src/errors.ts +27 -0
  67. package/src/logic/feeCollectorOperations.ts +272 -0
  68. package/src/logic/listOperations.ts +20 -1
  69. package/src/logic/tests/broadcast.integ.test.ts +4 -15
  70. package/src/logic/tests/listOperations.test.ts +563 -0
  71. package/src/network/node/rpc.common.ts +128 -30
  72. package/src/network/tests/node/rpc.test.ts +81 -9
  73. package/src/staking/validators.integ.test.ts +5 -22
@@ -1,24 +1,14 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import type { EvmConfigInfo } from '../../config'
4
+ import { evmDefaults } from '../../config'
5
5
  import { createMockEvmContext } from '../../fixtures/context.fixtures'
6
6
  import { createApi } from '../index'
7
7
 
8
8
  describe('EVM RSK Network', () => {
9
9
  let module: ReturnType<typeof createApi>
10
10
 
11
- const config: Partial<EvmConfigInfo> = {
12
- chainId: 30,
13
- node: {
14
- type: 'external',
15
- uri: 'https://rsk.coin.ledger.com',
16
- },
17
- explorer: {
18
- type: 'blockscout',
19
- uri: 'https://proxyblockscout.api.live.ledger.com/30/api',
20
- },
21
- }
11
+ const config = evmDefaults.rsk
22
12
  beforeAll(() => {
23
13
  module = createApi()
24
14
  })
@@ -3,17 +3,14 @@
3
3
 
4
4
  import type { EvmConfigInfo } from '../../config'
5
5
  import type { MemoNotSupported, Operation } from '@ledgerhq/coin-module-framework/api/types'
6
- import { internalTxSourcesFromList } from '../../config'
6
+ import { evmDefaults, internalTxSourcesFromList } from '../../config'
7
7
  import { createMockEvmContext } from '../../fixtures/context.fixtures'
8
8
  import { createApi } from '../index'
9
9
 
10
10
  describe('EVM Scroll Network (blockscout-v2 explorer)', () => {
11
- const config: Partial<EvmConfigInfo> = {
12
- chainId: 534352,
13
- node: {
14
- type: 'external',
15
- uri: 'https://scroll.alpaca.api.ledger.com',
16
- },
11
+ const config: EvmConfigInfo = {
12
+ ...evmDefaults.scroll,
13
+ // These tests target the blockscout-v2 API and NFT transfers, unlike the default config.
17
14
  explorer: {
18
15
  type: 'blockscout-v2',
19
16
  uri: 'https://proxyblockscout.api.live.ledger.com/534352/api/v2',
@@ -1,28 +1,14 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import type { EvmConfigInfo } from '../../config'
5
4
  import { fail } from 'assert'
5
+ import { evmDefaults } from '../../config'
6
6
  import { createMockEvmContext } from '../../fixtures/context.fixtures'
7
7
  import { createApi } from '../index'
8
8
 
9
9
  describe('Shape (external node)', () => {
10
10
  describe('getBlock', () => {
11
- const shapeConfig: EvmConfigInfo = {
12
- status: { type: 'active' },
13
- chainId: 360,
14
- name: 'Shape',
15
- unit: { name: 'ETH', code: 'ETH', magnitude: 18 },
16
- node: {
17
- type: 'external',
18
- uri: 'https://mainnet.shape.network',
19
- },
20
- explorer: {
21
- type: 'blockscout',
22
- uri: 'https://proxyblockscout.api.live.ledger.com/360/api',
23
- },
24
- supportedTokens: ['erc721', 'erc1155'],
25
- }
11
+ const shapeConfig = evmDefaults.shape
26
12
  const module = createApi()
27
13
 
28
14
  it('should return WETH mint from Deposit log in block 26327282 (tx 0x08761e…) see BACK-10995', async () => {
@@ -50,17 +36,7 @@ describe('Shape (external node)', () => {
50
36
 
51
37
  // Shape's Blockscout reports the L1 data fee in `txlist` (`L1FeesPaid`), so the v1 API is enough
52
38
  describe('fees include the L1 data fee', () => {
53
- const config: Partial<EvmConfigInfo> = {
54
- chainId: 360,
55
- node: {
56
- type: 'external',
57
- uri: 'https://mainnet.shape.network',
58
- },
59
- explorer: {
60
- type: 'blockscout',
61
- uri: 'https://proxyblockscout.api.live.ledger.com/360/api',
62
- },
63
- }
39
+ const config = evmDefaults.shape
64
40
  const module = createApi()
65
41
 
66
42
  const txHash = '0x68d2739afa41ec0523e03eb672002152195af1cf928ba6afa4b48944462d6754'
@@ -1,18 +1,14 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import type { EvmConfigInfo } from '../../config'
4
+ import { evmDefaults } from '../../config'
5
5
  import { createMockEvmContext } from '../../fixtures/context.fixtures'
6
6
  import { createApi } from '../index'
7
7
 
8
8
  describe('EVM Api (Somnia)', () => {
9
9
  let module: ReturnType<typeof createApi>
10
10
 
11
- const config: Partial<EvmConfigInfo> = {
12
- chainId: 5031,
13
- node: { type: 'external', uri: 'https://api.infra.mainnet.somnia.network' },
14
- explorer: { type: 'blockscout', uri: 'https://explorer.somnia.network/api/' },
15
- }
11
+ const config = evmDefaults.somnia
16
12
 
17
13
  beforeAll(() => {
18
14
  module = createApi()
@@ -1,24 +1,14 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import type { EvmConfigInfo } from '../../config'
4
+ import { evmDefaults } from '../../config'
5
5
  import { createMockEvmContext } from '../../fixtures/context.fixtures'
6
6
  import { createApi } from '../index'
7
7
 
8
8
  describe('EVM Unichain Network', () => {
9
9
  const module = createApi()
10
10
 
11
- const config: Partial<EvmConfigInfo> = {
12
- chainId: 130,
13
- node: {
14
- type: 'external',
15
- uri: 'https://unichain-rpc.publicnode.com',
16
- },
17
- explorer: {
18
- type: 'etherscan',
19
- uri: 'https://proxyetherscan.api.live.ledger.com/v2/api/130',
20
- },
21
- }
11
+ const config = evmDefaults.unichain
22
12
 
23
13
  const txHash = '0x39051f6ca394bb88cc17b3a38f00fd64444152056ab3c3bc9c2840da1f7c6f45'
24
14
  // gasUsed × gasPrice (467932 × 100890 = 47_209_659_480) + l1Fee (13_500_719_807), see LIVE-38797
@@ -1,7 +1,8 @@
1
1
  // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { createMockEvmContext, mkExternalNode } from '../../fixtures/context.fixtures'
4
+ import { evmDefaults } from '../../config'
5
+ import { createMockEvmContext } from '../../fixtures/context.fixtures'
5
6
  import { createApi } from '../index'
6
7
 
7
8
  /**
@@ -24,13 +25,9 @@ describe('ZkSync (blockscout explorer)', () => {
24
25
  it('listOperations completes without timing out', async () => {
25
26
  const { items } = await module.listOperations(
26
27
  createMockEvmContext({
27
- chainId: 324,
28
- node: mkExternalNode({ uri: 'https://zksync.coin.ledger.com', retries: 0 }),
29
- explorer: {
30
- type: 'blockscout',
31
- uri: 'https://proxyblockscout.api.live.ledger.com/324/api',
32
- retries: 0,
33
- },
28
+ ...evmDefaults.zksync,
29
+ node: { ...evmDefaults.zksync.node, retries: 0 },
30
+ explorer: { ...evmDefaults.zksync.explorer, retries: 0 },
34
31
  }),
35
32
  ADDRESS,
36
33
  { minHeight: 0, order: 'asc', limit: 1 }
package/src/chains.ts CHANGED
@@ -23,7 +23,6 @@ export const CHAIN_ID = {
23
23
  MIX: 76,
24
24
  TOMO: 88,
25
25
  POA: 99,
26
- VELAS_EVM: 106,
27
26
  THUNDERCORE: 108,
28
27
  UNICHAIN: 130,
29
28
  POLYGON: 137,
package/src/config.ts CHANGED
@@ -132,6 +132,13 @@ export type EvmConfig = {
132
132
  * Addresses are matched case-insensitively.
133
133
  */
134
134
  feeCollectorContracts?: string[]
135
+ /**
136
+ * Token contracts that carry the native coin to and from the `feeCollectorContracts` (e.g. the
137
+ * zkSync base token, the native coin as an ERC-20). A transfer of one of them to a fee collector
138
+ * pays the fee, like a native transfer; another token sent to it does not.
139
+ * Addresses are matched case-insensitively.
140
+ */
141
+ feeCollectorTokens?: string[]
135
142
  /**
136
143
  * Minimum effective price per gas (in wei, decimal string) accepted by this chain's
137
144
  * mempool. Applied as a floor to both the legacy `gasPrice` and the EIP-1559
@@ -964,6 +971,8 @@ export const evmDefaults = {
964
971
  explorer: { type: 'blockscout', uri: 'https://proxyblockscout.api.live.ledger.com/324/api' },
965
972
  // bootloader
966
973
  feeCollectorContracts: ['0x0000000000000000000000000000000000008001'],
974
+ // base token (L2BaseToken)
975
+ feeCollectorTokens: ['0x000000000000000000000000000000000000800A'],
967
976
  },
968
977
  zksync_sepolia: {
969
978
  status: {
@@ -977,6 +986,8 @@ export const evmDefaults = {
977
986
  explorer: { type: 'blockscout', uri: 'https://zksync-sepolia.blockscout.com/api' },
978
987
  // bootloader
979
988
  feeCollectorContracts: ['0x0000000000000000000000000000000000008001'],
989
+ // base token (L2BaseToken)
990
+ feeCollectorTokens: ['0x000000000000000000000000000000000000800A'],
980
991
  },
981
992
  monad: {
982
993
  status: {
package/src/errors.ts CHANGED
@@ -94,6 +94,33 @@ export class UnsupportedRpcMethodError extends Error {
94
94
  }
95
95
  }
96
96
 
97
+ /** The node has no such transaction, or no receipt for it yet. */
98
+ export class NodeTransactionNotFound extends Error {
99
+ override name = 'NodeTransactionNotFound'
100
+ constructor(message?: string, fields?: Record<string, unknown>) {
101
+ super(message || 'NodeTransactionNotFound')
102
+ if (fields) Object.assign(this, fields)
103
+ }
104
+ }
105
+
106
+ /** The node has no such block, or answered with an empty stub block. */
107
+ export class NodeBlockNotFound extends Error {
108
+ override name = 'NodeBlockNotFound'
109
+ constructor(message?: string, fields?: Record<string, unknown>) {
110
+ super(message || 'NodeBlockNotFound')
111
+ if (fields) Object.assign(this, fields)
112
+ }
113
+ }
114
+
115
+ /** The node answered with a response that does not have the expected shape. */
116
+ export class MalformedNodeResponse extends Error {
117
+ override name = 'MalformedNodeResponse'
118
+ constructor(message?: string, fields?: Record<string, unknown>) {
119
+ super(message || 'MalformedNodeResponse')
120
+ if (fields) Object.assign(this, fields)
121
+ }
122
+ }
123
+
97
124
  /**
98
125
  * Internal-tx source should be skipped (not propagated): not configured, structurally
99
126
  * unsupported, best-effort runtime failure (e.g. explorer), or all sources exhausted
@@ -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
  }