@ledgerhq/coin-evm 17.0.0 → 17.1.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 (53) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/lib/logic/cip64Fees.d.ts +25 -3
  3. package/lib/logic/cip64Fees.d.ts.map +1 -1
  4. package/lib/logic/cip64Fees.js +78 -24
  5. package/lib/logic/cip64Fees.js.map +1 -1
  6. package/lib/logic/listOperations.d.ts.map +1 -1
  7. package/lib/logic/listOperations.js +21 -3
  8. package/lib/logic/listOperations.js.map +1 -1
  9. package/lib/logic/tokenFeeOperations.d.ts +61 -0
  10. package/lib/logic/tokenFeeOperations.d.ts.map +1 -0
  11. package/lib/logic/tokenFeeOperations.js +128 -0
  12. package/lib/logic/tokenFeeOperations.js.map +1 -0
  13. package/lib/network/node/rpc.common.d.ts.map +1 -1
  14. package/lib/network/node/rpc.common.js +18 -0
  15. package/lib/network/node/rpc.common.js.map +1 -1
  16. package/lib/network/node/types.d.ts +2 -0
  17. package/lib/network/node/types.d.ts.map +1 -1
  18. package/lib/network/node/types.js.map +1 -1
  19. package/lib/network/node/withNodeSources.d.ts.map +1 -1
  20. package/lib/network/node/withNodeSources.js +2 -0
  21. package/lib/network/node/withNodeSources.js.map +1 -1
  22. package/lib-es/logic/cip64Fees.d.ts +25 -3
  23. package/lib-es/logic/cip64Fees.d.ts.map +1 -1
  24. package/lib-es/logic/cip64Fees.js +77 -24
  25. package/lib-es/logic/cip64Fees.js.map +1 -1
  26. package/lib-es/logic/listOperations.d.ts.map +1 -1
  27. package/lib-es/logic/listOperations.js +21 -3
  28. package/lib-es/logic/listOperations.js.map +1 -1
  29. package/lib-es/logic/tokenFeeOperations.d.ts +61 -0
  30. package/lib-es/logic/tokenFeeOperations.d.ts.map +1 -0
  31. package/lib-es/logic/tokenFeeOperations.js +122 -0
  32. package/lib-es/logic/tokenFeeOperations.js.map +1 -0
  33. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  34. package/lib-es/network/node/rpc.common.js +18 -0
  35. package/lib-es/network/node/rpc.common.js.map +1 -1
  36. package/lib-es/network/node/types.d.ts +2 -0
  37. package/lib-es/network/node/types.d.ts.map +1 -1
  38. package/lib-es/network/node/types.js.map +1 -1
  39. package/lib-es/network/node/withNodeSources.d.ts.map +1 -1
  40. package/lib-es/network/node/withNodeSources.js +2 -0
  41. package/lib-es/network/node/withNodeSources.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/api/tests/index.celo.integ.test.ts +143 -0
  44. package/src/logic/cip64Fees.ts +99 -26
  45. package/src/logic/listOperations.ts +32 -2
  46. package/src/logic/tests/cip64Fees.test.ts +128 -4
  47. package/src/logic/tests/listOperations.test.ts +469 -1
  48. package/src/logic/tokenFeeOperations.ts +169 -0
  49. package/src/network/node/rpc.common.ts +19 -0
  50. package/src/network/node/types.ts +2 -0
  51. package/src/network/node/withNodeSources.ts +3 -0
  52. package/src/network/tests/node/rpc.test.ts +36 -0
  53. package/src/network/tests/node/withNodeSources.test.ts +17 -0
@@ -11,7 +11,19 @@ const USDT = '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e'
11
11
  const USDC = '0xcebA9300f2b948710d2653dD7B07f33A8B32118C'
12
12
  const CUSD = '0x765DE816845861e75A25fCA122bb6898B8B1282a'
13
13
  const CEUR = '0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73'
14
+ const USAT = '0xD2ab3C9A02DBBAB236BfEC45D1d755DF4267F771'
15
+ const KESM = '0x456a3D042C0DbD3db53D5489e98dFb038553B0d0'
14
16
  const USDT_SENDER = '0xfb4863FC2FE52A8131696e4a3a86676cff40A806'
17
+ const USAT_FEE_ONLY = {
18
+ height: 83106787,
19
+ hash: '0x437cfcbf162770f8586be4e263383653e0ccac33949d4fe1fc04e628b208ef80',
20
+ payer: '0xF30C0240a65a21b89B32F1bd0CaDfA6924cADA4E',
21
+ }
22
+ const KESM_FEE_ONLY = {
23
+ height: 83055835,
24
+ hash: '0x0cc6b0258288a498b7836808f107af9591b27c8b05f28ded56c2960a1e254074',
25
+ payer: '0xf0B48e98d0d8089cAa7D03478178482cAb75E0a3',
26
+ }
15
27
 
16
28
  function usdtTransfer(from: string, to: string, amount: bigint): BlockOperation[] {
17
29
  const asset = { type: 'erc20' as const, assetReference: USDT }
@@ -71,6 +83,33 @@ describe('EVM Celo Network', () => {
71
83
  feesAsset: CEUR,
72
84
  operations: [],
73
85
  },
86
+ {
87
+ fee: 'cUSD (before cUSD minted its credits, fee-only transaction)',
88
+ height: 32000002,
89
+ hash: '0x870ee46734ffd61acb692f6b2c338c791178aa3ea82e0334136840ec4696e49d',
90
+ payer: '0xe17ad09b4f3ee94c9616c548cbba5a8c1fc89ceb',
91
+ fees: 604833996674040n,
92
+ feesAsset: CUSD,
93
+ operations: [],
94
+ },
95
+ {
96
+ fee: 'USAT (adapter, fee-only transaction)',
97
+ height: USAT_FEE_ONLY.height,
98
+ hash: USAT_FEE_ONLY.hash,
99
+ payer: USAT_FEE_ONLY.payer,
100
+ fees: 1601n,
101
+ feesAsset: USAT,
102
+ operations: [],
103
+ },
104
+ {
105
+ fee: 'KESm (fee-only transaction)',
106
+ height: KESM_FEE_ONLY.height,
107
+ hash: KESM_FEE_ONLY.hash,
108
+ payer: KESM_FEE_ONLY.payer,
109
+ fees: 148586650352216144n,
110
+ feesAsset: KESM,
111
+ operations: [],
112
+ },
74
113
  ])(
75
114
  'reports a fee paid in $fee in token units, without its fee logs',
76
115
  async ({ height, hash, payer, fees, feesAsset, operations }) => {
@@ -88,4 +127,108 @@ describe('EVM Celo Network', () => {
88
127
  }
89
128
  )
90
129
  })
130
+
131
+ describe('listOperations with the fee asset', () => {
132
+ const historyContext = createMockEvmContext({
133
+ ...config,
134
+ // forno load-balances backends whose receipt index differs, so a receipt can be missing
135
+ node: { type: 'external', uri: 'https://celo.coin.ledger.com/archive' },
136
+ explorer: {
137
+ type: 'etherscan',
138
+ uri: 'https://proxyetherscan.api.live.ledger.com/v2/api/42220',
139
+ },
140
+ })
141
+ const feeCarrier = (payer: string, contract: string) => ({
142
+ type: 'OUT',
143
+ value: 0n,
144
+ asset: { type: 'native' },
145
+ senders: [payer],
146
+ recipients: [contract],
147
+ })
148
+ const usdtIn = (from: string, to: string, value: bigint) => ({
149
+ type: 'IN',
150
+ value,
151
+ asset: { type: 'erc20', assetReference: USDT },
152
+ senders: [from],
153
+ recipients: [to],
154
+ })
155
+
156
+ it.each([
157
+ {
158
+ fee: 'USD₮ (adapter)',
159
+ address: '0x5362C723476b46a1e65D54E667C00e46b46F6f12',
160
+ height: 80494727,
161
+ hash: '0x45e41cf20fca9b079f8b23510bb9637d14df647cb6d25d85157924cd27df09d7',
162
+ fees: 3176n,
163
+ feesAsset: USDT,
164
+ operations: [usdtIn(USDT_SENDER, '0x5362C723476b46a1e65D54E667C00e46b46F6f12', 7000n)],
165
+ },
166
+ {
167
+ fee: 'USDC (adapter)',
168
+ address: '0x3EE17b4D2eC4E33339eE34f6F2a16429c4C67738',
169
+ height: 80502070,
170
+ hash: '0xf43732d1ca9d43dd6515708669e6083010672aed8a61de4c8d07164c7e3d400d',
171
+ fees: 4072n,
172
+ feesAsset: USDC,
173
+ operations: [usdtIn(USDT_SENDER, '0x3EE17b4D2eC4E33339eE34f6F2a16429c4C67738', 9000n)],
174
+ },
175
+ {
176
+ fee: 'cUSD',
177
+ address: '0xfb6f89fd218A62E39c9bb4D3bb0bc029ec0C6F73',
178
+ height: 82654841,
179
+ hash: '0xa92de9a2b85e285d2bf1c1317386e012034ddfbbd84739e5b5f46fe6c252e748',
180
+ fees: 2255358224402010n,
181
+ feesAsset: CUSD,
182
+ operations: [usdtIn(USDT_SENDER, '0xfb6f89fd218A62E39c9bb4D3bb0bc029ec0C6F73', 5800n)],
183
+ },
184
+ {
185
+ fee: 'USD₮ (fee-only transaction)',
186
+ address: '0x540d7DCfF6dE998Ec5e14AE5e6CDb063eA2eC88B',
187
+ height: 83099643,
188
+ hash: '0x670feaaac5150943eb5090b82f9bc51c06ada222e7c00fad86ad44a37f55ea6f',
189
+ fees: 1601n,
190
+ feesAsset: USDT,
191
+ operations: [feeCarrier('0x540d7DCfF6dE998Ec5e14AE5e6CDb063eA2eC88B', USDT)],
192
+ },
193
+ {
194
+ fee: 'USAT (fee-only transaction)',
195
+ address: USAT_FEE_ONLY.payer,
196
+ height: USAT_FEE_ONLY.height,
197
+ hash: USAT_FEE_ONLY.hash,
198
+ fees: 1601n,
199
+ feesAsset: USAT,
200
+ operations: [feeCarrier(USAT_FEE_ONLY.payer, USAT)],
201
+ },
202
+ {
203
+ fee: 'KESm (fee-only transaction)',
204
+ address: KESM_FEE_ONLY.payer,
205
+ height: KESM_FEE_ONLY.height,
206
+ hash: KESM_FEE_ONLY.hash,
207
+ fees: 148586650352216144n,
208
+ feesAsset: KESM,
209
+ operations: [feeCarrier(KESM_FEE_ONLY.payer, KESM)],
210
+ },
211
+ ])(
212
+ 'reports a fee paid in $fee on every operation, without its fee transfers',
213
+ async ({ address, height, hash, fees, feesAsset, operations }) => {
214
+ const { items } = await module.listOperations(historyContext, address, {
215
+ minHeight: height,
216
+ order: 'asc',
217
+ limit: 10,
218
+ })
219
+
220
+ const txOperations = items.filter((op) => op.tx.hash === hash)
221
+ expect(txOperations).toMatchObject(
222
+ operations.map((operation) => ({
223
+ ...operation,
224
+ tx: {
225
+ fees,
226
+ feesAsset: { type: 'erc20', assetReference: feesAsset },
227
+ feesPayer: address,
228
+ },
229
+ }))
230
+ )
231
+ }
232
+ )
233
+ })
91
234
  })
@@ -30,38 +30,74 @@ type FeePattern = 'holder' | 'burnRemint' | 'burnMint'
30
30
  /** Credits of every supported fee currency: refund, tip and base fee, each emitted also when 0. */
31
31
  const CREDIT_COUNT = 3
32
32
 
33
+ type FeeCurrency = { token: string; patterns: readonly FeePattern[] }
34
+
35
+ /**
36
+ * Mento stable tokens have moved fees both ways: cUSD used `burnRemint` until an upgrade between
37
+ * blocks 50M and 75M, and `burnMint` since. The two shapes cannot be mistaken for each other, and
38
+ * the fee is the payer's net movement in either, so every Mento token accepts both.
39
+ */
40
+ const MENTO_PATTERNS: readonly FeePattern[] = ['burnMint', 'burnRemint']
41
+
42
+ const mentoToken = (token: string): [string, FeeCurrency] => [
43
+ token,
44
+ { token, patterns: MENTO_PATTERNS },
45
+ ]
46
+
33
47
  /**
34
- * Fee currencies whose fee logs were checked on mainnet receipts, by lower-case fee currency
35
- * address, with the lower-case token they move. Any other fee currency is rejected rather than
36
- * guessed.
48
+ * Fee currencies whose fee logs are known, by lower-case fee currency address, with the
49
+ * lower-case token they move. The patterns were checked on mainnet receipts, the oldest on Celo
50
+ * L1. A Mento token without receipts shares the proxy implementation of one with receipts, and
51
+ * WETH's verified source burns the debit and mints each credit. Any other fee currency is
52
+ * reported as unsupported rather than guessed.
37
53
  */
38
- const CELO_FEE_CURRENCIES: ReadonlyMap<string, { token: string; pattern: FeePattern }> = new Map([
54
+ const CELO_FEE_CURRENCIES: ReadonlyMap<string, FeeCurrency> = new Map([
39
55
  // USD₮ through its adapter
40
56
  [
41
57
  '0x0e2a3e05bc9a16f5292a6170456a710cb89c6f72',
42
- { token: '0x48065fbbe25f71c9282ddf5e1cd6d6a887483d5e', pattern: 'holder' },
58
+ { token: '0x48065fbbe25f71c9282ddf5e1cd6d6a887483d5e', patterns: ['holder'] },
43
59
  ],
44
60
  // USDC through its adapter
45
61
  [
46
62
  '0x2f25deb3848c207fc8e0c34035b3ba7fc157602b',
47
- { token: '0xceba9300f2b948710d2653dd7b07f33a8b32118c', pattern: 'burnRemint' },
63
+ { token: '0xceba9300f2b948710d2653dd7b07f33a8b32118c', patterns: ['burnRemint'] },
48
64
  ],
49
- // cUSD
65
+ // USAT through its adapter
50
66
  [
51
- '0x765de816845861e75a25fca122bb6898b8b1282a',
52
- { token: '0x765de816845861e75a25fca122bb6898b8b1282a', pattern: 'burnMint' },
67
+ '0x0357ee22278c922e1d36cfe6b899269b161880c4',
68
+ { token: '0xd2ab3c9a02dbbab236bfec45d1d755df4267f771', patterns: ['holder'] },
53
69
  ],
54
- // cEUR
70
+ // WETH, not upgradeable
55
71
  [
56
- '0xd8763cba276a3738e6de85b4b3bf5fded6d6ca73',
57
- { token: '0xd8763cba276a3738e6de85b4b3bf5fded6d6ca73', pattern: 'burnMint' },
72
+ '0xd221812de1bd094f35587ee8e174b07b6167d9af',
73
+ { token: '0xd221812de1bd094f35587ee8e174b07b6167d9af', patterns: ['burnMint'] },
58
74
  ],
75
+ // Mento USDm (cUSD), EURm (cEUR), GBPm, CHFm, JPYm, KESm, COPm, NGNm, GHSm, PHPm, ZARm, AUDm,
76
+ // XOFm, BRLm, CADm
77
+ ...[
78
+ '0x765de816845861e75a25fca122bb6898b8b1282a',
79
+ '0xd8763cba276a3738e6de85b4b3bf5fded6d6ca73',
80
+ '0xccf663b1ff11028f0b19058d0f7b674004a40746',
81
+ '0xb55a79f398e759e43c95b979163f30ec87ee131d',
82
+ '0xc45ecf20f3cd864b32d9794d6f76814ae8892e20',
83
+ '0x456a3d042c0dbd3db53d5489e98dfb038553b0d0',
84
+ '0x8a567e2ae79ca692bd748ab832081c45de4041ea',
85
+ '0xe2702bd97ee33c88c8f6f92da3b733608aa76f71',
86
+ '0xfaea5f3404bba20d3cc2f8c4b0a888f55a3c7313',
87
+ '0x105d4a9306d2e55a71d2eb95b81553ae1dc20d7b',
88
+ '0x4c35853a3b4e647fd266f4de678dcc8fec410bf6',
89
+ '0x7175504c455076f15c04a2f90a8e352281f492f9',
90
+ '0x73f93dcc49cb8a239e2032663e9475dd5ef29a08',
91
+ '0xe8537a3d056da446677b9e9d6c5db704eaab4787',
92
+ '0xff4ab19391af240c311c54200a492233052b6325',
93
+ ].map(mentoToken),
59
94
  ])
60
95
 
61
- /** The fee of a token-paid transaction, and the transfers of the transaction itself. */
96
+ /** The fee of a token-paid transaction, the transfers that move it, and the other transfers. */
62
97
  export type TokenFee = {
63
98
  fees: bigint
64
99
  feesAsset: AssetInfo
100
+ feeTransfers: ERC20Transfer[]
65
101
  transfers: ERC20Transfer[]
66
102
  }
67
103
 
@@ -99,7 +135,7 @@ function matchesPattern(
99
135
  * Splits the token transfers of a CIP-64 transaction into its fee and its own transfers.
100
136
  *
101
137
  * The fee logs are found by position: the first transfer is the debit and the last
102
- * {@link CREDIT_COUNT} are the credits, each checked against the pattern of the fee currency.
138
+ * {@link CREDIT_COUNT} are the credits, checked against the patterns of the fee currency.
103
139
  * Matching on position, not on recipients, keeps a transfer of the transaction to the fee
104
140
  * recipients. The fee is what the payer sent minus what it got back, in the token's own units:
105
141
  * a value converted from the adapter's 18 decimals would not be the amount debited.
@@ -107,19 +143,20 @@ function matchesPattern(
107
143
  * @param feeCurrency `feeCurrency` of the transaction
108
144
  * @param payer sender of the transaction
109
145
  * @param transfers the token transfers of the receipt, in log order
146
+ * @param hash hash of the transaction, for the error context
110
147
  * @throws UnsupportedFeeCurrencyError when the fee currency is not supported
111
148
  * @throws UnexpectedFeeLogsError when the fee logs do not match the fee currency
112
149
  */
113
150
  export function splitTokenFee(
114
151
  feeCurrency: string,
115
152
  payer: string,
116
- transfers: readonly ERC20Transfer[]
153
+ transfers: readonly ERC20Transfer[],
154
+ hash?: string
117
155
  ): TokenFee {
156
+ const context = { feeCurrency, payer, ...(hash !== undefined && { hash }) }
118
157
  const currency = CELO_FEE_CURRENCIES.get(feeCurrency.toLowerCase())
119
158
  if (currency === undefined) {
120
- throw new UnsupportedFeeCurrencyError(`Unsupported Celo fee currency ${feeCurrency}`, {
121
- feeCurrency,
122
- })
159
+ throw new UnsupportedFeeCurrencyError(`Unsupported Celo fee currency ${feeCurrency}`, context)
123
160
  }
124
161
 
125
162
  const creditStart = transfers.length - CREDIT_COUNT
@@ -129,11 +166,12 @@ export function splitTokenFee(
129
166
  debit === undefined ||
130
167
  creditStart < 1 ||
131
168
  ![debit, ...credits].every((transfer) => same(transfer.asset.assetReference, currency.token)) ||
132
- !matchesPattern(currency.pattern, payer, debit, credits)
169
+ !currency.patterns.some((pattern) => matchesPattern(pattern, payer, debit, credits))
133
170
  ) {
134
- throw new UnexpectedFeeLogsError(`Unexpected fee logs for Celo fee currency ${feeCurrency}`, {
135
- feeCurrency,
136
- })
171
+ throw new UnexpectedFeeLogsError(
172
+ `Unexpected fee logs for Celo fee currency ${feeCurrency}`,
173
+ context
174
+ )
137
175
  }
138
176
 
139
177
  let fees = 0n
@@ -143,14 +181,13 @@ export function splitTokenFee(
143
181
  if (same(transfer.to, payer)) fees -= value
144
182
  }
145
183
  if (fees < 0n) {
146
- throw new UnexpectedFeeLogsError(`Negative fee for Celo fee currency ${feeCurrency}`, {
147
- feeCurrency,
148
- })
184
+ throw new UnexpectedFeeLogsError(`Negative fee for Celo fee currency ${feeCurrency}`, context)
149
185
  }
150
186
 
151
187
  return {
152
188
  fees,
153
189
  feesAsset: { type: 'erc20', assetReference: debit.asset.assetReference },
190
+ feeTransfers: [debit, ...credits],
154
191
  transfers: transfers.slice(1, creditStart),
155
192
  }
156
193
  }
@@ -188,6 +225,42 @@ export function createCeloTokenFeeReader(nodeApi: NodeApi, blockHeight: number):
188
225
  hash,
189
226
  })
190
227
  }
191
- return feeCurrency === null ? undefined : splitTokenFee(feeCurrency, from, erc20Transfers)
228
+ return feeCurrency === null ? undefined : splitTokenFee(feeCurrency, from, erc20Transfers, hash)
229
+ }
230
+ }
231
+
232
+ /** How a Celo transaction paid its fee. */
233
+ export type CeloTransactionFee =
234
+ | { kind: 'native' }
235
+ | { kind: 'token'; tokenFee: TokenFee }
236
+ | { kind: 'unsupported'; feeCurrency: string }
237
+
238
+ /**
239
+ * Reads how a Celo transaction paid its fee, fetching its fee currency alone, for transactions
240
+ * that are not read block by block. A fee currency whose fee logs are not known is reported, not
241
+ * rejected, so that the caller decides whether the fee matters to it.
242
+ *
243
+ * @param nodeApi node of the network
244
+ * @param tx the transaction, with the token transfers of its receipt
245
+ * @throws UnexpectedFeeLogsError when the fee logs do not match a supported fee currency
246
+ */
247
+ export async function readCeloTransactionFee(
248
+ nodeApi: NodeApi,
249
+ tx: Parameters<ReadTokenFee>[0]
250
+ ): Promise<CeloTransactionFee> {
251
+ if (tx.type !== undefined && tx.type !== CIP64_TX_TYPE) return { kind: 'native' }
252
+ if (nodeApi.getFeeCurrency === undefined) {
253
+ throw new FeeCurrencyUnavailableError(
254
+ 'The node cannot report the fee currency of a transaction',
255
+ { hash: tx.hash }
256
+ )
257
+ }
258
+ const feeCurrency = await nodeApi.getFeeCurrency(tx.hash)
259
+ if (feeCurrency === null) return { kind: 'native' }
260
+ if (!CELO_FEE_CURRENCIES.has(feeCurrency.toLowerCase()))
261
+ return { kind: 'unsupported', feeCurrency }
262
+ return {
263
+ kind: 'token',
264
+ tokenFee: splitTokenFee(feeCurrency, tx.from, tx.erc20Transfers, tx.hash),
192
265
  }
193
266
  }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import type { EvmContext } from '../config'
5
+ import type { TransactionTokenFee } from './tokenFeeOperations'
5
6
  import type {
6
7
  Page,
7
8
  MemoNotSupported,
@@ -9,11 +10,13 @@ import type {
9
10
  ListOperationsOptions,
10
11
  } from '@ledgerhq/coin-module-framework/api/types'
11
12
  import { InvalidParameterError } from '@ledgerhq/coin-module-framework/errors'
13
+ import { CHAIN_ID } from '../config'
12
14
  import { getExplorerApi } from '../network/explorer'
13
15
  import {
14
16
  attributeFeeCollectorPayments,
15
17
  findTransactionsPaidByOthers,
16
18
  } from './feeCollectorOperations'
19
+ import { readCeloTokenFees, removeFeeTransfers, withTokenFee } from './tokenFeeOperations'
17
20
 
18
21
  // the sort parameter has a double meaning:
19
22
  // - legacy (for the bridge): it's used to sort the operations in the result list. Explorer always queried in "desc" order.
@@ -67,7 +70,7 @@ export async function listOperations(
67
70
  const explorerOrder = options.limit === undefined ? 'desc' : (options.order ?? 'desc')
68
71
  const {
69
72
  lastCoinOperations,
70
- lastTokenOperations,
73
+ lastTokenOperations: explorerTokenOperations,
71
74
  lastNftOperations,
72
75
  lastInternalOperations,
73
76
  nextPagingToken,
@@ -82,6 +85,31 @@ export async function listOperations(
82
85
  explorerOrder
83
86
  )
84
87
 
88
+ const addressLower = address.toLowerCase()
89
+
90
+ // A Celo CIP-64 transaction can pay its fee in a token. The fee transfers are removed before the
91
+ // parent suppression below, so that the native operation stays as the fee carrier.
92
+ const tokenFees =
93
+ config.chainId === CHAIN_ID.CELO
94
+ ? await readCeloTokenFees(
95
+ config,
96
+ context.logger,
97
+ address,
98
+ [
99
+ ...lastCoinOperations,
100
+ ...explorerTokenOperations,
101
+ ...lastNftOperations,
102
+ ...lastInternalOperations,
103
+ ].map((op) => op.tx.hash),
104
+ new Set(
105
+ lastCoinOperations
106
+ .filter((op) => op.senders.some((sender) => sender.toLowerCase() === addressLower))
107
+ .map((op) => op.tx.hash.toLowerCase())
108
+ )
109
+ )
110
+ : new Map<string, TransactionTokenFee>()
111
+ const lastTokenOperations = removeFeeTransfers(explorerTokenOperations, tokenFees)
112
+
85
113
  const tokenOrNftHashes = new Set(
86
114
  [...lastTokenOperations, ...lastNftOperations].map((op) => op.tx.hash)
87
115
  )
@@ -91,7 +119,6 @@ export async function listOperations(
91
119
  )
92
120
  )
93
121
 
94
- const addressLower = address.toLowerCase()
95
122
  const isAddressInOp = (op: Operation<MemoNotSupported>): boolean =>
96
123
  op.senders.some((s) => s.toLowerCase() === addressLower) ||
97
124
  op.recipients.some((r) => r.toLowerCase() === addressLower)
@@ -143,6 +170,7 @@ export async function listOperations(
143
170
  ...op.tx,
144
171
  block: { ...op.tx.block, hash: op.tx.block.hash || parent.tx.block.hash },
145
172
  fees: parent.tx.fees,
173
+ ...(parent.tx.feesAsset ? { feesAsset: parent.tx.feesAsset } : {}),
146
174
  failed: parent.tx.failed,
147
175
  ...(parent.tx.feesPayer ? { feesPayer: parent.tx.feesPayer } : {}),
148
176
  },
@@ -192,6 +220,7 @@ export async function listOperations(
192
220
  ...op.tx,
193
221
  block: { ...op.tx.block, hash: parent.tx.block.hash },
194
222
  fees: parent.tx.fees,
223
+ ...(parent.tx.feesAsset ? { feesAsset: parent.tx.feesAsset } : {}),
195
224
  ...(parent.tx.feesPayer ? { feesPayer: parent.tx.feesPayer } : {}),
196
225
  },
197
226
  }
@@ -286,6 +315,7 @@ export async function listOperations(
286
315
  .concat(internalOperations)
287
316
  .filter(hasValidType)
288
317
  .filter(isAddressInvolved)
318
+ .map((op) => withTokenFee(op, tokenFees))
289
319
  const feeEvidence = [...lastTokenOperations, ...lastNftOperations, ...lastInternalOperations]
290
320
  const operations = attributeFeeCollectorPayments(
291
321
  accountOperations,
@@ -8,7 +8,7 @@ import {
8
8
  UnsupportedFeeCurrencyError,
9
9
  } from '../../errors'
10
10
  import { mockNodeApi } from '../../network/tests/node/node.fixtures'
11
- import { createCeloTokenFeeReader, splitTokenFee } from '../cip64Fees'
11
+ import { createCeloTokenFeeReader, readCeloTransactionFee, splitTokenFee } from '../cip64Fees'
12
12
 
13
13
  const USDT = '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e'
14
14
  const USDT_ADAPTER = '0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72'
@@ -17,6 +17,9 @@ const USDC = '0xcebA9300f2b948710d2653dD7B07f33A8B32118C'
17
17
  const USDC_ADAPTER = '0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B'
18
18
  const CUSD = '0x765DE816845861e75A25fCA122bb6898B8B1282a'
19
19
  const CEUR = '0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73'
20
+ const KESM = '0x456a3D042C0DbD3db53D5489e98dFb038553B0d0'
21
+ const USAT = '0xD2ab3C9A02DBBAB236BfEC45D1d755DF4267F771'
22
+ const USAT_ADAPTER = '0x0357EE22278c922e1D36cFe6b899269b161880C4'
20
23
  const ZERO = '0x0000000000000000000000000000000000000000'
21
24
  const SEQUENCER_VAULT = '0x4200000000000000000000000000000000000011'
22
25
  const FEE_HANDLER = '0xcD437749E43A154C07F3553504c68fBfD56B8778'
@@ -58,6 +61,7 @@ describe('splitTokenFee', () => {
58
61
  expect(splitTokenFee(USDT_ADAPTER, PAYER, [usdtDebit, userTransfer, ...usdtCredits])).toEqual({
59
62
  fees: 3176n,
60
63
  feesAsset: { type: 'erc20', assetReference: USDT },
64
+ feeTransfers: [usdtDebit, ...usdtCredits],
61
65
  transfers: [userTransfer],
62
66
  })
63
67
  })
@@ -66,6 +70,7 @@ describe('splitTokenFee', () => {
66
70
  expect(splitTokenFee(USDC_ADAPTER, PAYER, [usdcDebit, userTransfer, ...usdcCredits])).toEqual({
67
71
  fees: 4072n,
68
72
  feesAsset: { type: 'erc20', assetReference: USDC },
73
+ feeTransfers: [usdcDebit, ...usdcCredits],
69
74
  transfers: [userTransfer],
70
75
  })
71
76
  })
@@ -74,6 +79,7 @@ describe('splitTokenFee', () => {
74
79
  expect(splitTokenFee(CUSD, PAYER, [cusdDebit, ...cusdCredits])).toEqual({
75
80
  fees: 12404402010n + 2255345820000000n,
76
81
  feesAsset: { type: 'erc20', assetReference: CUSD },
82
+ feeTransfers: [cusdDebit, ...cusdCredits],
77
83
  transfers: [],
78
84
  })
79
85
  })
@@ -90,6 +96,7 @@ describe('splitTokenFee', () => {
90
96
  expect(splitTokenFee(CEUR, PAYER, transfers)).toEqual({
91
97
  fees: 2623801530470940n,
92
98
  feesAsset: { type: 'erc20', assetReference: CEUR },
99
+ feeTransfers: transfers,
93
100
  transfers: [],
94
101
  })
95
102
  })
@@ -106,6 +113,7 @@ describe('splitTokenFee', () => {
106
113
  expect(splitTokenFee(USDT_ADAPTER, PAYER, transfers)).toEqual({
107
114
  fees: 2816n,
108
115
  feesAsset: { type: 'erc20', assetReference: USDT },
116
+ feeTransfers: transfers,
109
117
  transfers: [],
110
118
  })
111
119
  })
@@ -154,9 +162,63 @@ describe('splitTokenFee', () => {
154
162
  ).toBe(3176n)
155
163
  })
156
164
 
157
- it('rejects an unsupported fee currency', () => {
158
- expect(() => splitTokenFee(OTHER, PAYER, [usdtDebit, ...usdtCredits])).toThrow(
159
- UnsupportedFeeCurrencyError
165
+ it.each([
166
+ {
167
+ // Fee logs of tx 0x437cfcbf162770f8586be4e263383653e0ccac33949d4fe1fc04e628b208ef80
168
+ name: 'USAT, through a holder',
169
+ feeCurrency: USAT_ADAPTER,
170
+ token: USAT,
171
+ transfers: [
172
+ transfer(USAT, PAYER, USDT_HOLDER, 2032n),
173
+ transfer(USAT, USDT_HOLDER, SEQUENCER_VAULT, 0n),
174
+ transfer(USAT, USDT_HOLDER, FEE_HANDLER, 1601n),
175
+ transfer(USAT, USDT_HOLDER, PAYER, 431n),
176
+ ],
177
+ fees: 1601n,
178
+ },
179
+ {
180
+ // Fee logs of tx 0x0cc6b0258288a498b7836808f107af9591b27c8b05f28ded56c2960a1e254074
181
+ name: 'KESm, from the burn, the re-mint and the payments',
182
+ feeCurrency: KESM,
183
+ token: KESM,
184
+ transfers: [
185
+ transfer(KESM, PAYER, ZERO, 157008136848681234n),
186
+ transfer(KESM, ZERO, PAYER, 157008136848681234n),
187
+ transfer(KESM, PAYER, SEQUENCER_VAULT, 742929512920n),
188
+ transfer(KESM, PAYER, FEE_HANDLER, 148585907422703224n),
189
+ ],
190
+ fees: 148586650352216144n,
191
+ },
192
+ {
193
+ // Fee logs of tx 0x870ee46734ffd61acb692f6b2c338c791178aa3ea82e0334136840ec4696e49d
194
+ name: 'cUSD, from before cUSD minted its credits',
195
+ feeCurrency: CUSD,
196
+ token: CUSD,
197
+ transfers: [
198
+ transfer(CUSD, PAYER, ZERO, 775085251046848n),
199
+ transfer(CUSD, ZERO, PAYER, 775085251046848n),
200
+ transfer(CUSD, PAYER, SEQUENCER_VAULT, 26611431540n),
201
+ transfer(CUSD, PAYER, FEE_HANDLER, 604807385242500n),
202
+ ],
203
+ fees: 604833996674040n,
204
+ },
205
+ ])('reads a $name fee', ({ feeCurrency, token, transfers, fees }) => {
206
+ expect(splitTokenFee(feeCurrency, PAYER, transfers)).toEqual({
207
+ fees,
208
+ feesAsset: { type: 'erc20', assetReference: token },
209
+ feeTransfers: transfers,
210
+ transfers: [],
211
+ })
212
+ })
213
+
214
+ it('rejects an unsupported fee currency, with the transaction in the error', () => {
215
+ expect(() => splitTokenFee(OTHER, PAYER, [usdtDebit, ...usdtCredits], '0xabc')).toThrow(
216
+ expect.objectContaining({
217
+ name: UnsupportedFeeCurrencyError.name,
218
+ feeCurrency: OTHER,
219
+ payer: PAYER,
220
+ hash: '0xabc',
221
+ })
160
222
  )
161
223
  })
162
224
 
@@ -275,3 +337,65 @@ describe('createCeloTokenFeeReader', () => {
275
337
  )
276
338
  })
277
339
  })
340
+
341
+ function nodeWithFeeCurrency(feeCurrency: string | null): NodeApi {
342
+ return mockNodeApi({ getFeeCurrency: jest.fn().mockResolvedValue(feeCurrency) })
343
+ }
344
+
345
+ describe('readCeloTransactionFee', () => {
346
+ const cip64Tx = {
347
+ hash: '0xabc',
348
+ from: PAYER,
349
+ type: 0x7b,
350
+ erc20Transfers: [usdtDebit, ...usdtCredits],
351
+ }
352
+
353
+ it('reads a native fee for a transaction that is not CIP-64', async () => {
354
+ const nodeApi = nodeWithFeeCurrency(USDT_ADAPTER)
355
+
356
+ await expect(readCeloTransactionFee(nodeApi, { ...cip64Tx, type: 2 })).resolves.toEqual({
357
+ kind: 'native',
358
+ })
359
+ expect(nodeApi.getFeeCurrency).not.toHaveBeenCalled()
360
+ })
361
+
362
+ it('reads a native fee for a CIP-64 transaction that pays in the native coin', async () => {
363
+ await expect(readCeloTransactionFee(nodeWithFeeCurrency(null), cip64Tx)).resolves.toEqual({
364
+ kind: 'native',
365
+ })
366
+ })
367
+
368
+ it('reads the token fee of a transaction, also when its receipt has no type', async () => {
369
+ const nodeApi = nodeWithFeeCurrency(USDT_ADAPTER)
370
+
371
+ await expect(
372
+ readCeloTransactionFee(nodeApi, { ...cip64Tx, type: undefined })
373
+ ).resolves.toMatchObject({
374
+ kind: 'token',
375
+ tokenFee: { fees: 3176n, feesAsset: { type: 'erc20', assetReference: USDT } },
376
+ })
377
+ expect(nodeApi.getFeeCurrency).toHaveBeenCalledWith('0xabc')
378
+ })
379
+
380
+ it('reports a fee currency whose fee logs are not known', async () => {
381
+ await expect(readCeloTransactionFee(nodeWithFeeCurrency(OTHER), cip64Tx)).resolves.toEqual({
382
+ kind: 'unsupported',
383
+ feeCurrency: OTHER,
384
+ })
385
+ })
386
+
387
+ it('rejects fee logs that do not match a supported fee currency', async () => {
388
+ await expect(
389
+ readCeloTransactionFee(nodeWithFeeCurrency(USDT_ADAPTER), {
390
+ ...cip64Tx,
391
+ erc20Transfers: usdtCredits,
392
+ })
393
+ ).rejects.toThrow(expect.objectContaining({ name: UnexpectedFeeLogsError.name, hash: '0xabc' }))
394
+ })
395
+
396
+ it('rejects a CIP-64 transaction when the node cannot report its fee currency', async () => {
397
+ await expect(readCeloTransactionFee(mockNodeApi(), cip64Tx)).rejects.toThrow(
398
+ FeeCurrencyUnavailableError
399
+ )
400
+ })
401
+ })