@ledgerhq/coin-evm 17.0.0 → 17.1.1

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 (61) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/logic/cip64Fees.d.ts +40 -9
  3. package/lib/logic/cip64Fees.d.ts.map +1 -1
  4. package/lib/logic/cip64Fees.js +86 -34
  5. package/lib/logic/cip64Fees.js.map +1 -1
  6. package/lib/logic/getBlock.d.ts.map +1 -1
  7. package/lib/logic/getBlock.js +48 -22
  8. package/lib/logic/getBlock.js.map +1 -1
  9. package/lib/logic/listOperations.d.ts.map +1 -1
  10. package/lib/logic/listOperations.js +21 -3
  11. package/lib/logic/listOperations.js.map +1 -1
  12. package/lib/logic/tokenFeeOperations.d.ts +61 -0
  13. package/lib/logic/tokenFeeOperations.d.ts.map +1 -0
  14. package/lib/logic/tokenFeeOperations.js +128 -0
  15. package/lib/logic/tokenFeeOperations.js.map +1 -0
  16. package/lib/network/node/rpc.common.d.ts.map +1 -1
  17. package/lib/network/node/rpc.common.js +18 -0
  18. package/lib/network/node/rpc.common.js.map +1 -1
  19. package/lib/network/node/types.d.ts +2 -0
  20. package/lib/network/node/types.d.ts.map +1 -1
  21. package/lib/network/node/types.js.map +1 -1
  22. package/lib/network/node/withNodeSources.d.ts.map +1 -1
  23. package/lib/network/node/withNodeSources.js +2 -0
  24. package/lib/network/node/withNodeSources.js.map +1 -1
  25. package/lib-es/logic/cip64Fees.d.ts +40 -9
  26. package/lib-es/logic/cip64Fees.d.ts.map +1 -1
  27. package/lib-es/logic/cip64Fees.js +85 -34
  28. package/lib-es/logic/cip64Fees.js.map +1 -1
  29. package/lib-es/logic/getBlock.d.ts.map +1 -1
  30. package/lib-es/logic/getBlock.js +48 -22
  31. package/lib-es/logic/getBlock.js.map +1 -1
  32. package/lib-es/logic/listOperations.d.ts.map +1 -1
  33. package/lib-es/logic/listOperations.js +21 -3
  34. package/lib-es/logic/listOperations.js.map +1 -1
  35. package/lib-es/logic/tokenFeeOperations.d.ts +61 -0
  36. package/lib-es/logic/tokenFeeOperations.d.ts.map +1 -0
  37. package/lib-es/logic/tokenFeeOperations.js +122 -0
  38. package/lib-es/logic/tokenFeeOperations.js.map +1 -0
  39. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  40. package/lib-es/network/node/rpc.common.js +18 -0
  41. package/lib-es/network/node/rpc.common.js.map +1 -1
  42. package/lib-es/network/node/types.d.ts +2 -0
  43. package/lib-es/network/node/types.d.ts.map +1 -1
  44. package/lib-es/network/node/types.js.map +1 -1
  45. package/lib-es/network/node/withNodeSources.d.ts.map +1 -1
  46. package/lib-es/network/node/withNodeSources.js +2 -0
  47. package/lib-es/network/node/withNodeSources.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/api/tests/index.celo.integ.test.ts +143 -0
  50. package/src/logic/cip64Fees.ts +123 -38
  51. package/src/logic/getBlock.ts +74 -34
  52. package/src/logic/listOperations.ts +32 -2
  53. package/src/logic/tests/cip64Fees.test.ts +149 -14
  54. package/src/logic/tests/getBlock.test.ts +45 -5
  55. package/src/logic/tests/listOperations.test.ts +469 -1
  56. package/src/logic/tokenFeeOperations.ts +169 -0
  57. package/src/network/node/rpc.common.ts +19 -0
  58. package/src/network/node/types.ts +2 -0
  59. package/src/network/node/withNodeSources.ts +3 -0
  60. package/src/network/tests/node/rpc.test.ts +36 -0
  61. package/src/network/tests/node/withNodeSources.test.ts +17 -0
@@ -3,12 +3,15 @@
3
3
 
4
4
  import type { EvmConfig, EvmContext } from '../../config'
5
5
  import type { ExplorerApi } from '../../network/explorer/types'
6
+ import type { ERC20Transfer } from '../../network/node/types'
6
7
  import type { LedgerExplorerOperation } from '../../types'
7
8
  import type { MemoNotSupported, Operation } from '@ledgerhq/coin-module-framework/api/types'
8
9
  import type { AxiosRequestConfig } from 'axios'
9
10
  import { InvalidParameterError } from '@ledgerhq/coin-module-framework/errors'
10
11
  import axios from 'axios'
11
12
  import BigNumber from 'bignumber.js'
13
+ import { CHAIN_ID } from '../../config'
14
+ import { UnexpectedFeeLogsError, UnsupportedFeeCurrencyError } from '../../errors'
12
15
  import {
13
16
  createMockEvmContext,
14
17
  mkEtherscanExplorer,
@@ -20,6 +23,7 @@ import { getNodeApi } from '../../network/node'
20
23
  import { mockNodeApi } from '../../network/tests/node/node.fixtures'
21
24
  import { readReceiptTransfers } from '../feeCollectorOperations'
22
25
  import { listOperations } from '../listOperations'
26
+ import { fetchCeloTransactionFee } from '../tokenFeeOperations'
23
27
 
24
28
  jest.mock('../../network/node')
25
29
 
@@ -1588,6 +1592,13 @@ describe('listOperations', () => {
1588
1592
  id?: string
1589
1593
  hash?: string
1590
1594
  }>
1595
+ lastNftOperations?: Array<{
1596
+ type: string
1597
+ senders: string[]
1598
+ recipients: string[]
1599
+ contract: string
1600
+ fee: number | string
1601
+ }>
1591
1602
  },
1592
1603
  sharedHash?: string
1593
1604
  ) {
@@ -1680,10 +1691,29 @@ describe('listOperations', () => {
1680
1691
  },
1681
1692
  details: { internal: true, sequence: BigNumber(1) },
1682
1693
  }))
1694
+ const nftOps: Array<Operation<MemoNotSupported>> = (response.lastNftOperations ?? []).map(
1695
+ (op, i) => ({
1696
+ id: `nft-op-${i}`,
1697
+ type: op.type,
1698
+ senders: op.senders,
1699
+ recipients: op.recipients,
1700
+ value: 1n,
1701
+ asset: { type: 'erc721', assetReference: op.contract, assetOwner: queriedAddress },
1702
+ tx: {
1703
+ hash: operationTxHash,
1704
+ block: { height: blockHeight, hash: blockHash, time: date },
1705
+ fees: toBigInt(op.fee),
1706
+ feesAsset: { type: 'native' },
1707
+ date,
1708
+ failed: false,
1709
+ },
1710
+ details: { sequence: BigNumber(1) },
1711
+ })
1712
+ )
1683
1713
  return {
1684
1714
  lastCoinOperations: coinOps,
1685
1715
  lastTokenOperations: tokenOps,
1686
- lastNftOperations: [],
1716
+ lastNftOperations: nftOps,
1687
1717
  lastInternalOperations: internalOps,
1688
1718
  nextPagingToken: '',
1689
1719
  }
@@ -3189,5 +3219,443 @@ describe('listOperations', () => {
3189
3219
  expect(items.every((op) => op.tx.feesPayer === undefined)).toBe(true)
3190
3220
  })
3191
3221
  })
3222
+
3223
+ describe('Celo fee paid in a token', () => {
3224
+ const USDT = '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e'
3225
+ const USDT_ADAPTER = '0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72'
3226
+ const HOLDER = '0x000000000000000000000000000000000Ce106A5'
3227
+ const SEQUENCER_VAULT = '0x4200000000000000000000000000000000000011'
3228
+ const FEE_HANDLER = '0xcD437749E43A154C07F3553504c68fBfD56B8778'
3229
+ const PAYER = '0x5362C723476b46a1e65D54E667C00e46b46F6f12'
3230
+ const OTHER = '0xfb4863FC2FE52A8131696e4a3a86676cff40A806'
3231
+ const HASH = '0xce1o'
3232
+ const UNSUPPORTED_FEE_CURRENCY = '0x857BF24e29da0773687E804a743c2E421a394C16'
3233
+ const NATIVE_FEE = 999
3234
+
3235
+ const celoContext: EvmContext = createMockEvmContext({
3236
+ chainId: CHAIN_ID.CELO,
3237
+ explorer: mkLedgerExplorer(),
3238
+ })
3239
+
3240
+ const transfer = (from: string, to: string, value: bigint): ERC20Transfer => ({
3241
+ asset: { type: 'erc20', assetReference: USDT },
3242
+ from,
3243
+ to,
3244
+ value: value.toString(),
3245
+ })
3246
+ const debit = transfer(PAYER, HOLDER, 4252n)
3247
+ const credits = [
3248
+ transfer(HOLDER, SEQUENCER_VAULT, 0n),
3249
+ transfer(HOLDER, FEE_HANDLER, 3176n),
3250
+ transfer(HOLDER, PAYER, 1076n),
3251
+ ]
3252
+ // The explorer rows of the fee logs that reach the payer: the debit and the refund
3253
+ const payerFeeRows = [
3254
+ {
3255
+ type: 'OUT',
3256
+ senders: [PAYER],
3257
+ recipients: [HOLDER],
3258
+ value: 4252,
3259
+ contract: USDT,
3260
+ fee: NATIVE_FEE,
3261
+ },
3262
+ {
3263
+ type: 'IN',
3264
+ senders: [HOLDER],
3265
+ recipients: [PAYER],
3266
+ value: 1076,
3267
+ contract: USDT,
3268
+ fee: NATIVE_FEE,
3269
+ },
3270
+ ]
3271
+ const tokenFee = {
3272
+ fees: 3176n,
3273
+ feesAsset: { type: 'erc20', assetReference: USDT },
3274
+ feesPayer: PAYER,
3275
+ }
3276
+
3277
+ const mockCeloNode = (
3278
+ userTransfers: ERC20Transfer[],
3279
+ feeCurrency: string | null = USDT_ADAPTER
3280
+ ): jest.Mocked<ReturnType<typeof getNodeApi>> => {
3281
+ const nodeApi = mockNodeApi({
3282
+ getTransaction: jest.fn().mockResolvedValue({
3283
+ hash: HASH,
3284
+ from: PAYER,
3285
+ type: 0x7b,
3286
+ erc20Transfers: [debit, ...userTransfers, ...credits],
3287
+ }),
3288
+ getFeeCurrency: jest.fn().mockResolvedValue(feeCurrency),
3289
+ })
3290
+ jest.mocked(getNodeApi).mockReturnValue(nodeApi)
3291
+ return nodeApi
3292
+ }
3293
+
3294
+ beforeEach(() => {
3295
+ fetchCeloTransactionFee.reset()
3296
+ })
3297
+
3298
+ it('reports the token fee of a token transfer and removes its fee rows', async () => {
3299
+ mockCeloNode([transfer(PAYER, OTHER, 5000n)])
3300
+ mockGetOperations(
3301
+ {
3302
+ lastCoinOperations: [
3303
+ { type: 'FEES', senders: [PAYER], recipients: [USDT], value: 0, fee: NATIVE_FEE },
3304
+ ],
3305
+ lastTokenOperations: [
3306
+ ...payerFeeRows,
3307
+ {
3308
+ type: 'OUT',
3309
+ senders: [PAYER],
3310
+ recipients: [OTHER],
3311
+ value: 5000,
3312
+ contract: USDT,
3313
+ fee: NATIVE_FEE,
3314
+ },
3315
+ ],
3316
+ },
3317
+ HASH
3318
+ )
3319
+
3320
+ const { items } = await listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3321
+
3322
+ expect(items).toEqual([
3323
+ expect.objectContaining({
3324
+ type: 'OUT',
3325
+ recipients: [OTHER],
3326
+ value: 5000n,
3327
+ asset: expect.objectContaining({ type: 'erc20', assetReference: USDT }),
3328
+ tx: expect.objectContaining(tokenFee),
3329
+ }),
3330
+ ])
3331
+ })
3332
+
3333
+ it('keeps the native operation as the carrier of a fee-only transaction', async () => {
3334
+ mockCeloNode([])
3335
+ mockGetOperations(
3336
+ {
3337
+ lastCoinOperations: [
3338
+ { type: 'FEES', senders: [PAYER], recipients: [USDT], value: 0, fee: NATIVE_FEE },
3339
+ ],
3340
+ lastTokenOperations: payerFeeRows,
3341
+ },
3342
+ HASH
3343
+ )
3344
+
3345
+ const { items } = await listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3346
+
3347
+ // listOperations reports a sender-only FEES row as OUT, whatever pays the fee
3348
+ expect(items).toEqual([
3349
+ expect.objectContaining({
3350
+ type: 'OUT',
3351
+ value: 0n,
3352
+ asset: { type: 'native' },
3353
+ tx: expect.objectContaining(tokenFee),
3354
+ }),
3355
+ ])
3356
+ })
3357
+
3358
+ it('keeps both native rows of a value-0 self-send, as for a native fee', async () => {
3359
+ mockCeloNode([])
3360
+ mockGetOperations(
3361
+ {
3362
+ lastCoinOperations: [
3363
+ {
3364
+ id: 'self-in',
3365
+ type: 'IN',
3366
+ senders: [PAYER],
3367
+ recipients: [PAYER],
3368
+ value: 0,
3369
+ fee: NATIVE_FEE,
3370
+ },
3371
+ {
3372
+ id: 'self-out',
3373
+ type: 'OUT',
3374
+ senders: [PAYER],
3375
+ recipients: [PAYER],
3376
+ value: 0,
3377
+ fee: NATIVE_FEE,
3378
+ },
3379
+ ],
3380
+ lastTokenOperations: payerFeeRows,
3381
+ },
3382
+ HASH
3383
+ )
3384
+
3385
+ const { items } = await listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3386
+
3387
+ expect(items).toEqual([
3388
+ expect.objectContaining({ type: 'IN', value: 0n, tx: expect.objectContaining(tokenFee) }),
3389
+ expect.objectContaining({
3390
+ type: 'OUT',
3391
+ value: 0n,
3392
+ tx: expect.objectContaining(tokenFee),
3393
+ }),
3394
+ ])
3395
+ })
3396
+
3397
+ it('removes as many identical rows as the receipt has fee transfers, whatever their casing', async () => {
3398
+ // The transaction itself sends the holder the same amount as the fee debit
3399
+ mockCeloNode([transfer(PAYER, HOLDER, 4252n)])
3400
+ const lowerCaseRow = {
3401
+ type: 'OUT',
3402
+ senders: [PAYER.toLowerCase()],
3403
+ recipients: [HOLDER.toLowerCase()],
3404
+ value: 4252,
3405
+ contract: USDT.toLowerCase(),
3406
+ fee: NATIVE_FEE,
3407
+ }
3408
+ mockGetOperations(
3409
+ {
3410
+ lastCoinOperations: [
3411
+ { type: 'FEES', senders: [PAYER], recipients: [USDT], value: 0, fee: NATIVE_FEE },
3412
+ ],
3413
+ lastTokenOperations: [lowerCaseRow, lowerCaseRow, payerFeeRows[1]],
3414
+ },
3415
+ HASH.toUpperCase()
3416
+ )
3417
+
3418
+ const { items } = await listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3419
+
3420
+ expect(items).toEqual([
3421
+ expect.objectContaining({
3422
+ value: 4252n,
3423
+ recipients: [HOLDER.toLowerCase()],
3424
+ tx: expect.objectContaining(tokenFee),
3425
+ }),
3426
+ ])
3427
+ })
3428
+
3429
+ it('gives the token fee to the NFT and internal operations of the transaction', async () => {
3430
+ mockCeloNode([])
3431
+ mockGetOperations(
3432
+ {
3433
+ lastTokenOperations: payerFeeRows,
3434
+ lastNftOperations: [
3435
+ {
3436
+ type: 'NFT_IN',
3437
+ senders: [PAYER],
3438
+ recipients: [OTHER],
3439
+ contract: '0xNft',
3440
+ fee: NATIVE_FEE,
3441
+ },
3442
+ ],
3443
+ lastInternalOperations: [
3444
+ { type: 'IN', senders: ['0xContract'], recipients: [OTHER], value: 3, fee: 0 },
3445
+ ],
3446
+ },
3447
+ HASH
3448
+ )
3449
+
3450
+ const { items } = await listOperations(celoContext, OTHER, { minHeight: 0, order: 'asc' })
3451
+
3452
+ expect(items).toHaveLength(2)
3453
+ expect(items).toEqual(
3454
+ expect.arrayContaining([
3455
+ expect.objectContaining({ type: 'NFT_IN', tx: expect.objectContaining(tokenFee) }),
3456
+ expect.objectContaining({
3457
+ type: 'IN',
3458
+ value: 3n,
3459
+ asset: { type: 'native' },
3460
+ tx: expect.objectContaining(tokenFee),
3461
+ }),
3462
+ ])
3463
+ )
3464
+ })
3465
+
3466
+ it('gives the token fee and its payer to a transfer the account received', async () => {
3467
+ mockCeloNode([transfer(PAYER, OTHER, 5000n)])
3468
+ mockGetOperations(
3469
+ {
3470
+ lastTokenOperations: [
3471
+ {
3472
+ type: 'OUT',
3473
+ senders: [PAYER],
3474
+ recipients: [OTHER],
3475
+ value: 5000,
3476
+ contract: USDT,
3477
+ fee: NATIVE_FEE,
3478
+ },
3479
+ ],
3480
+ },
3481
+ HASH
3482
+ )
3483
+
3484
+ const { items } = await listOperations(celoContext, OTHER, { minHeight: 0, order: 'asc' })
3485
+
3486
+ expect(items).toEqual([
3487
+ expect.objectContaining({
3488
+ type: 'IN',
3489
+ value: 5000n,
3490
+ tx: expect.objectContaining(tokenFee),
3491
+ }),
3492
+ ])
3493
+ })
3494
+
3495
+ it('keeps the native fee of a CIP-64 transaction that pays in the native coin', async () => {
3496
+ const nodeApi = mockNodeApi({
3497
+ getTransaction: jest
3498
+ .fn()
3499
+ .mockResolvedValue({ hash: HASH, from: PAYER, type: 0x7b, erc20Transfers: [] }),
3500
+ getFeeCurrency: jest.fn().mockResolvedValue(null),
3501
+ })
3502
+ jest.mocked(getNodeApi).mockReturnValue(nodeApi)
3503
+ mockGetOperations(
3504
+ {
3505
+ lastCoinOperations: [
3506
+ { type: 'OUT', senders: [PAYER], recipients: [OTHER], value: 7, fee: NATIVE_FEE },
3507
+ ],
3508
+ },
3509
+ HASH
3510
+ )
3511
+
3512
+ const { items } = await listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3513
+
3514
+ expect(items).toEqual([
3515
+ expect.objectContaining({
3516
+ value: 7n,
3517
+ tx: expect.objectContaining({ fees: 999n, feesAsset: { type: 'native' } }),
3518
+ }),
3519
+ ])
3520
+ expect(nodeApi.getFeeCurrency).toHaveBeenCalledWith(HASH)
3521
+ })
3522
+
3523
+ it('rejects a page where the account paid a fee in an unsupported currency', async () => {
3524
+ mockCeloNode([], UNSUPPORTED_FEE_CURRENCY)
3525
+ mockGetOperations(
3526
+ {
3527
+ lastCoinOperations: [
3528
+ { type: 'FEES', senders: [PAYER], recipients: [USDT], value: 0, fee: NATIVE_FEE },
3529
+ ],
3530
+ },
3531
+ HASH
3532
+ )
3533
+
3534
+ await expect(
3535
+ listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3536
+ ).rejects.toThrow(
3537
+ expect.objectContaining({
3538
+ name: UnsupportedFeeCurrencyError.name,
3539
+ hash: HASH,
3540
+ feeCurrency: UNSUPPORTED_FEE_CURRENCY,
3541
+ payer: PAYER,
3542
+ })
3543
+ )
3544
+ })
3545
+
3546
+ it('rejects an unsupported fee the node shows the account paid, without its native row', async () => {
3547
+ mockCeloNode([], UNSUPPORTED_FEE_CURRENCY)
3548
+ mockGetOperations(
3549
+ {
3550
+ lastTokenOperations: [
3551
+ {
3552
+ type: 'OUT',
3553
+ senders: [PAYER],
3554
+ recipients: [OTHER],
3555
+ value: 5000,
3556
+ contract: USDT,
3557
+ fee: NATIVE_FEE,
3558
+ },
3559
+ ],
3560
+ },
3561
+ HASH
3562
+ )
3563
+
3564
+ await expect(
3565
+ listOperations(celoContext, PAYER.toLowerCase(), { minHeight: 0, order: 'asc' })
3566
+ ).rejects.toThrow(UnsupportedFeeCurrencyError)
3567
+ })
3568
+
3569
+ it('keeps the explorer rows of a transaction another account paid in an unsupported currency', async () => {
3570
+ mockCeloNode([], UNSUPPORTED_FEE_CURRENCY)
3571
+ mockGetOperations(
3572
+ {
3573
+ lastCoinOperations: [
3574
+ { type: 'OUT', senders: [PAYER], recipients: [OTHER], value: 1, fee: NATIVE_FEE },
3575
+ ],
3576
+ },
3577
+ HASH
3578
+ )
3579
+
3580
+ const { items } = await listOperations(celoContext, OTHER, { minHeight: 0, order: 'asc' })
3581
+
3582
+ expect(items).toEqual([
3583
+ expect.objectContaining({
3584
+ type: 'IN',
3585
+ value: 1n,
3586
+ tx: expect.objectContaining({ fees: 999n, feesAsset: { type: 'native' } }),
3587
+ }),
3588
+ ])
3589
+ expect(celoContext.logger).toHaveBeenCalledWith(
3590
+ 'warn',
3591
+ expect.any(String),
3592
+ expect.objectContaining({ hash: HASH, feeCurrency: UNSUPPORTED_FEE_CURRENCY })
3593
+ )
3594
+ })
3595
+
3596
+ it('applies the payer rule per account to a cached unsupported fee', async () => {
3597
+ const nodeApi = mockCeloNode([], UNSUPPORTED_FEE_CURRENCY)
3598
+ mockGetOperations(
3599
+ {
3600
+ lastCoinOperations: [
3601
+ { type: 'OUT', senders: [PAYER], recipients: [OTHER], value: 1, fee: NATIVE_FEE },
3602
+ ],
3603
+ },
3604
+ HASH
3605
+ )
3606
+
3607
+ await expect(
3608
+ listOperations(celoContext, OTHER, { minHeight: 0, order: 'asc' })
3609
+ ).resolves.toBeDefined()
3610
+ await expect(
3611
+ listOperations(celoContext, PAYER, { minHeight: 0, order: 'asc' })
3612
+ ).rejects.toThrow(UnsupportedFeeCurrencyError)
3613
+ expect(nodeApi.getTransaction).toHaveBeenCalledTimes(1)
3614
+ })
3615
+
3616
+ it('rejects a page with fee logs that do not match a supported currency, whoever paid', async () => {
3617
+ jest.mocked(getNodeApi).mockReturnValue(
3618
+ mockNodeApi({
3619
+ getTransaction: jest
3620
+ .fn()
3621
+ .mockResolvedValue({ hash: HASH, from: PAYER, type: 0x7b, erc20Transfers: credits }),
3622
+ getFeeCurrency: jest.fn().mockResolvedValue(USDT_ADAPTER),
3623
+ })
3624
+ )
3625
+ mockGetOperations(
3626
+ {
3627
+ lastCoinOperations: [
3628
+ { type: 'OUT', senders: [PAYER], recipients: [OTHER], value: 1, fee: NATIVE_FEE },
3629
+ ],
3630
+ },
3631
+ HASH
3632
+ )
3633
+
3634
+ await expect(
3635
+ listOperations(celoContext, OTHER, { minHeight: 0, order: 'asc' })
3636
+ ).rejects.toThrow(UnexpectedFeeLogsError)
3637
+ })
3638
+
3639
+ it('reads no transaction on another network', async () => {
3640
+ const nodeApi = mockCeloNode([])
3641
+ mockGetOperations(
3642
+ {
3643
+ lastCoinOperations: [
3644
+ { type: 'FEES', senders: [PAYER], recipients: [USDT], value: 0, fee: NATIVE_FEE },
3645
+ ],
3646
+ lastTokenOperations: payerFeeRows,
3647
+ },
3648
+ HASH
3649
+ )
3650
+
3651
+ const { items } = await listOperations(ctxWithExplorer(mkLedgerExplorer()), PAYER, {
3652
+ minHeight: 0,
3653
+ order: 'asc',
3654
+ })
3655
+
3656
+ expect(nodeApi.getTransaction).not.toHaveBeenCalled()
3657
+ expect(items.every((op) => op.tx.feesAsset?.type === 'native')).toBe(true)
3658
+ })
3659
+ })
3192
3660
  })
3193
3661
  })
@@ -0,0 +1,169 @@
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 { TokenFee } from './cip64Fees'
7
+ import type { MemoNotSupported, Operation } from '@ledgerhq/coin-module-framework/api/types'
8
+ import type { Logger } from '@ledgerhq/coin-module-framework/config'
9
+ import { promiseAllBatched } from '@ledgerhq/coin-module-framework/promises'
10
+ import { makeLRUCache } from '@ledgerhq/live-network/cache'
11
+ import { UnsupportedFeeCurrencyError } from '../errors'
12
+ import { getNodeApi } from '../network/node'
13
+ import { readCeloTransactionFee } from './cip64Fees'
14
+
15
+ type Op = Operation<MemoNotSupported>
16
+
17
+ /** The token fee of a transaction, with the account that paid it. */
18
+ export type TransactionTokenFee = Pick<TokenFee, 'fees' | 'feesAsset' | 'feeTransfers'> & {
19
+ feesPayer: string
20
+ }
21
+
22
+ /** How a Celo transaction paid its fee, with the account that paid it when not natively. */
23
+ type CeloFeeRead =
24
+ | { kind: 'native' }
25
+ | { kind: 'token'; tokenFee: TransactionTokenFee }
26
+ | { kind: 'unsupported'; feeCurrency: string; feesPayer: string }
27
+
28
+ // Transactions read in parallel, as getBlock does for transactions it fetches one by one
29
+ const MAX_TRANSACTION_CONCURRENCY = 2
30
+
31
+ /**
32
+ * How a Celo transaction paid its fee. A mined transaction keeps its fee, so each one is read
33
+ * once per chain. A failed read is not kept.
34
+ */
35
+ export const fetchCeloTransactionFee = makeLRUCache(
36
+ async (config: EvmConfigInfo, logger: Logger, hash: string): Promise<CeloFeeRead> => {
37
+ const nodeApi = getNodeApi(config, logger)
38
+ const transaction = await nodeApi.getTransaction(hash)
39
+ const fee = await readCeloTransactionFee(nodeApi, transaction)
40
+ switch (fee.kind) {
41
+ case 'native':
42
+ return fee
43
+ case 'unsupported':
44
+ return { ...fee, feesPayer: transaction.from }
45
+ case 'token': {
46
+ const { fees, feesAsset, feeTransfers } = fee.tokenFee
47
+ return {
48
+ kind: 'token',
49
+ tokenFee: { fees, feesAsset, feeTransfers, feesPayer: transaction.from },
50
+ }
51
+ }
52
+ }
53
+ },
54
+ (config, _logger, hash) => `${config.chainId}:${hash.toLowerCase()}`,
55
+ { max: 10_000, ttl: 24 * 60 * 60 * 1000 }
56
+ )
57
+
58
+ /**
59
+ * The token fees of the transactions of a Celo history page, by lower-case hash. The explorer
60
+ * gives neither the transaction type nor the fee currency, so each transaction is read from the
61
+ * node. Transactions paid in the native coin are left out.
62
+ *
63
+ * A fee currency with unknown fee logs fails the page only when the account paid the fee. Anyone
64
+ * can send the account a transaction paid in such a currency, and its fee is not the account's,
65
+ * so that transaction keeps its explorer fee and fee rows.
66
+ *
67
+ * @param address the account of the page
68
+ * @param hashes hashes of the transactions of the page
69
+ * @param ownHashes lower-case hashes the explorer shows the account sent
70
+ * @throws UnsupportedFeeCurrencyError when the account paid a fee in a currency with unknown fee
71
+ * logs
72
+ * @throws any other failure to read a transaction or its fee, which a retry may recover: a fee
73
+ * reported in the wrong asset is worse than no page
74
+ */
75
+ export async function readCeloTokenFees(
76
+ config: EvmConfigInfo,
77
+ logger: Logger,
78
+ address: string,
79
+ hashes: Iterable<string>,
80
+ ownHashes: ReadonlySet<string>
81
+ ): Promise<Map<string, TransactionTokenFee>> {
82
+ const unique = [...new Set([...hashes].map((hash) => hash.toLowerCase()))]
83
+ const reads = await promiseAllBatched(MAX_TRANSACTION_CONCURRENCY, unique, (hash) =>
84
+ fetchCeloTransactionFee(config, logger, hash)
85
+ )
86
+ const byHash = new Map<string, TransactionTokenFee>()
87
+ unique.forEach((hash, index) => {
88
+ const read = reads[index]
89
+ if (read?.kind === 'token') byHash.set(hash, read.tokenFee)
90
+ if (read?.kind !== 'unsupported') return
91
+ const { feeCurrency, feesPayer } = read
92
+ if (ownHashes.has(hash) || feesPayer.toLowerCase() === address.toLowerCase()) {
93
+ throw new UnsupportedFeeCurrencyError(`Unsupported Celo fee currency ${feeCurrency}`, {
94
+ hash,
95
+ feeCurrency,
96
+ payer: feesPayer,
97
+ })
98
+ }
99
+ logger('warn', 'Celo fee currency not supported, keeping the explorer fee', {
100
+ hash,
101
+ feeCurrency,
102
+ })
103
+ })
104
+ return byHash
105
+ }
106
+
107
+ const transferKey = (
108
+ hash: string,
109
+ token: string,
110
+ from: string,
111
+ to: string,
112
+ value: bigint
113
+ ): string => [hash, token, from, to, value.toString()].join('\t').toLowerCase()
114
+
115
+ /**
116
+ * Removes the token operations that move a fee, one per fee transfer. The explorer gives no log
117
+ * index, so a fee transfer matches an operation by hash, token, sender, recipient and amount. A
118
+ * transfer of the transaction identical to a fee transfer may be removed in its place, which
119
+ * leaves the same operations.
120
+ *
121
+ * @param operations token operations of the account from the explorer
122
+ * @param tokenFees token fees by lower-case hash
123
+ */
124
+ export function removeFeeTransfers(
125
+ operations: readonly Op[],
126
+ tokenFees: ReadonlyMap<string, TransactionTokenFee>
127
+ ): Op[] {
128
+ const remaining = new Map<string, number>()
129
+ for (const [hash, { feeTransfers }] of tokenFees) {
130
+ for (const transfer of feeTransfers) {
131
+ const key = feeTransferKey(hash, transfer)
132
+ remaining.set(key, (remaining.get(key) ?? 0) + 1)
133
+ }
134
+ }
135
+
136
+ return operations.filter((op) => {
137
+ if (op.asset.type !== 'erc20' || !('assetReference' in op.asset)) return true
138
+ const [from] = op.senders
139
+ const [to] = op.recipients
140
+ if (from === undefined || to === undefined || op.asset.assetReference === undefined) return true
141
+ const key = transferKey(op.tx.hash, op.asset.assetReference, from, to, op.value)
142
+ const count = remaining.get(key) ?? 0
143
+ if (count === 0) return true
144
+ remaining.set(key, count - 1)
145
+ return false
146
+ })
147
+ }
148
+
149
+ function feeTransferKey(hash: string, transfer: ERC20Transfer): string {
150
+ return transferKey(
151
+ hash,
152
+ transfer.asset.assetReference,
153
+ transfer.from,
154
+ transfer.to,
155
+ BigInt(transfer.value)
156
+ )
157
+ }
158
+
159
+ /**
160
+ * Gives an operation the token fee of its transaction: amount, asset and payer.
161
+ *
162
+ * @param tokenFees token fees by lower-case hash
163
+ */
164
+ export function withTokenFee(op: Op, tokenFees: ReadonlyMap<string, TransactionTokenFee>): Op {
165
+ const tokenFee = tokenFees.get(op.tx.hash.toLowerCase())
166
+ if (tokenFee === undefined) return op
167
+ const { fees, feesAsset, feesPayer } = tokenFee
168
+ return { ...op, tx: { ...op.tx, fees, feesAsset, feesPayer } }
169
+ }