@ledgerhq/coin-evm 5.3.6 → 5.4.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 (94) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/lib/adapters/etherscan.d.ts.map +1 -1
  3. package/lib/adapters/etherscan.js +2 -1
  4. package/lib/adapters/etherscan.js.map +1 -1
  5. package/lib/logic/getBlock.js +2 -2
  6. package/lib/logic/getBlock.js.map +1 -1
  7. package/lib/logic/getStakes.d.ts.map +1 -1
  8. package/lib/logic/getStakes.js +6 -2
  9. package/lib/logic/getStakes.js.map +1 -1
  10. package/lib/network/explorer/etherscan.d.ts.map +1 -1
  11. package/lib/network/explorer/etherscan.js +23 -5
  12. package/lib/network/explorer/etherscan.js.map +1 -1
  13. package/lib/network/node/rpc.common.d.ts.map +1 -1
  14. package/lib/network/node/rpc.common.js +30 -6
  15. package/lib/network/node/rpc.common.js.map +1 -1
  16. package/lib/network/node/types.d.ts +3 -1
  17. package/lib/network/node/types.d.ts.map +1 -1
  18. package/lib/network/node/types.js.map +1 -1
  19. package/lib/staking/contracts.d.ts.map +1 -1
  20. package/lib/staking/contracts.js +4 -0
  21. package/lib/staking/contracts.js.map +1 -1
  22. package/lib/staking/index.d.ts +1 -0
  23. package/lib/staking/index.d.ts.map +1 -1
  24. package/lib/staking/index.js +3 -1
  25. package/lib/staking/index.js.map +1 -1
  26. package/lib/staking/unbondings.d.ts +8 -0
  27. package/lib/staking/unbondings.d.ts.map +1 -0
  28. package/lib/staking/unbondings.js +114 -0
  29. package/lib/staking/unbondings.js.map +1 -0
  30. package/lib/types/etherscan.d.ts +2 -0
  31. package/lib/types/etherscan.d.ts.map +1 -1
  32. package/lib/types/staking.d.ts +17 -0
  33. package/lib/types/staking.d.ts.map +1 -1
  34. package/lib-es/adapters/etherscan.d.ts.map +1 -1
  35. package/lib-es/adapters/etherscan.js +2 -1
  36. package/lib-es/adapters/etherscan.js.map +1 -1
  37. package/lib-es/logic/getBlock.js +2 -2
  38. package/lib-es/logic/getBlock.js.map +1 -1
  39. package/lib-es/logic/getStakes.d.ts.map +1 -1
  40. package/lib-es/logic/getStakes.js +6 -2
  41. package/lib-es/logic/getStakes.js.map +1 -1
  42. package/lib-es/network/explorer/etherscan.d.ts.map +1 -1
  43. package/lib-es/network/explorer/etherscan.js +23 -5
  44. package/lib-es/network/explorer/etherscan.js.map +1 -1
  45. package/lib-es/network/node/rpc.common.d.ts.map +1 -1
  46. package/lib-es/network/node/rpc.common.js +30 -6
  47. package/lib-es/network/node/rpc.common.js.map +1 -1
  48. package/lib-es/network/node/types.d.ts +3 -1
  49. package/lib-es/network/node/types.d.ts.map +1 -1
  50. package/lib-es/network/node/types.js.map +1 -1
  51. package/lib-es/staking/contracts.d.ts.map +1 -1
  52. package/lib-es/staking/contracts.js +4 -0
  53. package/lib-es/staking/contracts.js.map +1 -1
  54. package/lib-es/staking/index.d.ts +1 -0
  55. package/lib-es/staking/index.d.ts.map +1 -1
  56. package/lib-es/staking/index.js +1 -0
  57. package/lib-es/staking/index.js.map +1 -1
  58. package/lib-es/staking/unbondings.d.ts +8 -0
  59. package/lib-es/staking/unbondings.d.ts.map +1 -0
  60. package/lib-es/staking/unbondings.js +108 -0
  61. package/lib-es/staking/unbondings.js.map +1 -0
  62. package/lib-es/types/etherscan.d.ts +2 -0
  63. package/lib-es/types/etherscan.d.ts.map +1 -1
  64. package/lib-es/types/staking.d.ts +17 -0
  65. package/lib-es/types/staking.d.ts.map +1 -1
  66. package/package.json +1 -1
  67. package/src/adapters/etherscan.test.ts +67 -0
  68. package/src/adapters/etherscan.ts +3 -1
  69. package/src/api/getBlock.integ.test.ts +1 -1
  70. package/src/api/index.avalanche_c_chain_fuji.integ.test.ts +1 -1
  71. package/src/api/index.integ.test.ts +7 -4
  72. package/src/api/index.linea.integ.test.ts +1 -1
  73. package/src/api/index.monad_testnet.integ.test.ts +1 -1
  74. package/src/api/index.optimism.integ.test.ts +30 -1
  75. package/src/api/index.rsk.integ.test.ts +1 -1
  76. package/src/api/index.shape.integ.test.ts +1 -1
  77. package/src/api/index.somnia.integ.test.ts +40 -0
  78. package/src/api/index.zksync.integ.test.ts +6 -2
  79. package/src/logic/getBlock.test.ts +49 -0
  80. package/src/logic/getBlock.ts +3 -2
  81. package/src/logic/getStakes.test.ts +84 -0
  82. package/src/logic/getStakes.ts +12 -8
  83. package/src/network/explorer/etherscan.test.ts +339 -90
  84. package/src/network/explorer/etherscan.ts +32 -6
  85. package/src/network/node/rpc.common.ts +35 -6
  86. package/src/network/node/rpc.test.ts +73 -0
  87. package/src/network/node/types.ts +10 -1
  88. package/src/staking/contracts.ts +4 -0
  89. package/src/staking/index.ts +1 -0
  90. package/src/staking/unbondings.test.ts +245 -0
  91. package/src/staking/unbondings.ts +137 -0
  92. package/src/staking/validators.integ.test.ts +1 -1
  93. package/src/types/etherscan.ts +2 -0
  94. package/src/types/staking.ts +18 -0
@@ -776,9 +776,20 @@ export const getOperations = makeLRUCache<
776
776
  endpoint: FetchOperations,
777
777
  boundBlock: number | undefined,
778
778
  isDone: boolean | undefined
779
- ): Promise<{ result: EndpointResult; effectiveBoundBlock: number | undefined }> {
779
+ ): Promise<{
780
+ result: EndpointResult
781
+ effectiveBoundBlock: number | undefined
782
+ // True when the endpoint's block range was narrowed by a prior endpoint's bound.
783
+ // An isDone=true result in this case means "no more data in the constrained window",
784
+ // NOT "globally done" — more data may exist beyond the window.
785
+ wasConstrainedByBoundBlock: boolean
786
+ }> {
780
787
  if (isDone) {
781
- return { result: EMPTY_RESULT, effectiveBoundBlock: boundBlock }
788
+ return {
789
+ result: EMPTY_RESULT,
790
+ effectiveBoundBlock: boundBlock,
791
+ wasConstrainedByBoundBlock: false,
792
+ }
782
793
  }
783
794
  // in asc mode, the cursor is the toBlock
784
795
  // in desc mode the cursor is the fromBlock
@@ -799,7 +810,19 @@ export const getOperations = makeLRUCache<
799
810
  result,
800
811
  cmp
801
812
  )
802
- return { result: result, effectiveBoundBlock: effectiveBoundBlock }
813
+ // The endpoint was "additionally constrained" only when boundBlock tightens the range
814
+ // beyond what the user already specified:
815
+ // asc: boundBlock sets effectiveToBlock — tighter when boundBlock < user's toBlock (or toBlock=∞)
816
+ // desc: boundBlock sets effectiveFromBlock — tighter when boundBlock > user's fromBlock
817
+ const wasConstrainedByBoundBlock =
818
+ order === 'asc'
819
+ ? boundBlock !== undefined && (toBlock === undefined || boundBlock < toBlock)
820
+ : boundBlock !== undefined && boundBlock > fromBlock
821
+ return {
822
+ result: result,
823
+ effectiveBoundBlock: effectiveBoundBlock,
824
+ wasConstrainedByBoundBlock,
825
+ }
803
826
  }
804
827
 
805
828
  // endpoint calls are sorted by likelihood of having more operations than the next
@@ -855,9 +878,12 @@ export const getOperations = makeLRUCache<
855
878
  lastInternalOperations: internalsResult.operations,
856
879
  nextPagingToken: serializePagingToken(nextBoundBlock, {
857
880
  coinIsDone: coinsResult.isDone,
858
- internalIsDone: internalsResult.isDone,
859
- tokenIsDone: tokensResult.isDone,
860
- nftIsDone: nftsResult.isDone,
881
+ // An endpoint constrained by a prior endpoint's bound block is only locally done
882
+ // (no more data in the constrained window). It must be re-queried on the next page
883
+ // because more data may exist beyond that window.
884
+ internalIsDone: internalsResult.isDone && !internals.wasConstrainedByBoundBlock,
885
+ tokenIsDone: tokensResult.isDone && !tokens.wasConstrainedByBoundBlock,
886
+ nftIsDone: nftsResult.isDone && !nfts.wasConstrainedByBoundBlock,
861
887
  }),
862
888
  }
863
889
  } catch (err) {
@@ -223,37 +223,63 @@ export async function withApi<T>(
223
223
  )
224
224
  }
225
225
 
226
+ /**
227
+ * Read the L1 data/security fee from a raw RPC receipt, normalized to a decimal string.
228
+ *
229
+ * Only OP-stack chains (Optimism, Base, Blast, …) report it; it is a non-standard field, so it is read off the raw
230
+ * record rather than the typed receipt.
231
+ *
232
+ * @param raw raw RPC receipt
233
+ */
234
+ function parseReceiptL1Fee(raw: Record<string, unknown>): string | undefined {
235
+ const l1Fee = raw.l1Fee
236
+ return typeof l1Fee === 'string' ? BigInt(l1Fee).toString() : undefined
237
+ }
238
+
226
239
  async function getTransaction(
227
240
  api: JsonRpcProvider,
228
241
  _currencyId: string,
229
242
  txHash: string
230
243
  ): Promise<TransactionInfo> {
244
+ // Note: raw RPC call is used to get transaction receipt, as ethers method drops extra fields. We need optimism's
245
+ // extra fields that contain L1 fees.
246
+ // A pull request for ethers is open to avoid this: https://github.com/ethers-io/ethers.js/pull/5189
231
247
  const [tx, receipt] = await Promise.all([
232
248
  api.getTransaction(txHash),
233
- api.getTransactionReceipt(txHash),
249
+ api.send('eth_getTransactionReceipt', [txHash]) as Promise<TransactionReceipt | null>,
234
250
  ])
235
251
 
236
252
  if (!tx || !receipt) {
237
253
  throw new Error('Transaction or receipt not found')
238
254
  }
239
255
 
256
+ const raw = receipt as TransactionReceipt & Record<string, unknown>
257
+ const contractAddressRaw = raw.contractAddress
258
+ const contractAddress =
259
+ typeof contractAddressRaw === 'string' && contractAddressRaw.startsWith('0x')
260
+ ? contractAddressRaw
261
+ : undefined
262
+
263
+ const l1Fee = parseReceiptL1Fee(raw)
264
+
240
265
  return {
241
266
  hash: tx.hash,
242
267
  blockHeight: tx.blockNumber ?? undefined,
243
268
  blockHash: tx.blockHash ?? undefined,
244
269
  nonce: tx.nonce,
245
- gasUsed: receipt.gasUsed.toString(),
246
- gasPrice: receipt.gasPrice.toString(),
247
- status: receipt.status,
270
+ gasUsed: BigInt(receipt.gasUsed).toString(),
271
+ gasPrice: BigInt(receipt.effectiveGasPrice ?? receipt.gasPrice ?? '0x0').toString(),
272
+ status: receipt.status === null ? null : Number(receipt.status),
248
273
  value: tx.value.toString(),
249
274
  from: tx.from,
250
275
  to: tx.to ?? undefined,
251
- type: receipt.type ?? tx.type ?? undefined,
276
+ type: receipt.type !== undefined ? Number(receipt.type) : (tx.type ?? undefined),
252
277
  ...(tx.data !== null && tx.data !== undefined && isSmartContractInput(tx.data)
253
278
  ? { input: tx.data }
254
279
  : {}),
255
- ...(receipt.contractAddress ? { contractAddress: receipt.contractAddress } : {}),
280
+ ...(contractAddress ? { contractAddress } : {}),
256
281
  erc20Transfers: parseERC20TransfersFromLogs(receipt.logs),
282
+ ...(l1Fee !== undefined ? { l1Fee } : {}),
257
283
  }
258
284
  }
259
285
 
@@ -710,6 +736,8 @@ async function getBlockReceipts(
710
736
  ? contractAddressRaw
711
737
  : undefined
712
738
 
739
+ const l1Fee = parseReceiptL1Fee(raw)
740
+
713
741
  return {
714
742
  hash: receipt.transactionHash,
715
743
  gasUsed: BigInt(receipt.gasUsed).toString(),
@@ -718,6 +746,7 @@ async function getBlockReceipts(
718
746
  erc20Transfers: parseERC20TransfersFromLogs(receipt.logs),
719
747
  ...(contractAddress ? { contractAddress } : {}),
720
748
  ...(receipt.type !== undefined ? { type: Number(receipt.type) } : {}),
749
+ ...(l1Fee !== undefined ? { l1Fee } : {}),
721
750
  }
722
751
  })
723
752
  }
@@ -281,6 +281,50 @@ describe('EVM Family', () => {
281
281
  })
282
282
 
283
283
  describe('getTransaction', () => {
284
+ // Mocks the raw eth_getTransactionReceipt response, as ethers' getTransactionReceipt would
285
+ // drop the non-standard fields (l1Fee) this path reads.
286
+ function mockRawReceipt(overrides: Record<string, unknown> = {}): void {
287
+ jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
288
+ if (method === 'eth_getTransactionReceipt') {
289
+ return {
290
+ transactionHash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
291
+ gasUsed: '0x7a',
292
+ gasPrice: '0x315',
293
+ status: '0x1',
294
+ logs: [],
295
+ type: '0x0',
296
+ contractAddress: null,
297
+ ...overrides,
298
+ }
299
+ }
300
+ return null
301
+ })
302
+ }
303
+
304
+ beforeEach(() => {
305
+ mockRawReceipt()
306
+ })
307
+
308
+ it('should normalize the hex l1Fee of an OP-stack receipt to a decimal string', async () => {
309
+ mockRawReceipt({ l1Fee: '0x56c2d5eea374' }) // 95394812830580
310
+
311
+ const tx = await nodeApi.getTransaction(
312
+ currencyId,
313
+ '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
314
+ )
315
+
316
+ expect(tx.l1Fee).toBe('95394812830580')
317
+ })
318
+
319
+ it('should leave l1Fee undefined when the receipt has none (non OP-stack chains)', async () => {
320
+ const tx = await nodeApi.getTransaction(
321
+ currencyId,
322
+ '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59'
323
+ )
324
+
325
+ expect(tx.l1Fee).toBeUndefined()
326
+ })
327
+
284
328
  it('should return the expected payload', async () => {
285
329
  expect(
286
330
  await nodeApi.getTransaction(
@@ -1368,6 +1412,35 @@ describe('EVM Family', () => {
1368
1412
  ])
1369
1413
  })
1370
1414
 
1415
+ it('should normalize the hex l1Fee of an OP-stack receipt to a decimal string', async () => {
1416
+ jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementationOnce(async (method) => {
1417
+ if (method === 'eth_getBlockReceipts') {
1418
+ return [
1419
+ {
1420
+ transactionHash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
1421
+ gasUsed: '0x5208', // 21000
1422
+ effectiveGasPrice: '0x3b9aca00', // 1000000000
1423
+ status: '0x1',
1424
+ logs: [],
1425
+ l1Fee: '0x56c2d5eea374', // 95394812830580
1426
+ },
1427
+ ]
1428
+ }
1429
+ throw new Error(`Method not mocked: ${method}`)
1430
+ })
1431
+
1432
+ expect(await nodeApi.getBlockReceipts!(currencyId, 1)).toEqual([
1433
+ {
1434
+ hash: '0x435b00d28a10febbcfefbdea080134d08ef843df122d5bc9174b09de7fce6a59',
1435
+ gasUsed: '21000',
1436
+ gasPrice: '1000000000',
1437
+ status: 1,
1438
+ erc20Transfers: [],
1439
+ l1Fee: '95394812830580',
1440
+ },
1441
+ ])
1442
+ })
1443
+
1371
1444
  it('should throw UnsupportedRpcMethodError for RPC -32601', async () => {
1372
1445
  jest.spyOn(JsonRpcProvider.prototype, 'send').mockImplementation(async (method) => {
1373
1446
  if (method === 'eth_chainId') {
@@ -146,6 +146,8 @@ export type TransactionInfo = {
146
146
  erc20Transfers: ERC20Transfer[]
147
147
  /** Tx envelope type per EIP-2718 (decimal), e.g. 2 for EIP-1559. */
148
148
  type?: number
149
+ /** L1 data/security fee in wei (OP-stack chains: Optimism, Base, Blast, …). Present only when the receipt includes the field. */
150
+ l1Fee?: string
149
151
  }
150
152
 
151
153
  export type PrefetchedBlockTransaction = Pick<
@@ -155,7 +157,14 @@ export type PrefetchedBlockTransaction = Pick<
155
157
 
156
158
  export type BlockReceiptInfo = Pick<
157
159
  TransactionInfo,
158
- 'hash' | 'gasUsed' | 'gasPrice' | 'status' | 'erc20Transfers' | 'contractAddress' | 'type'
160
+ | 'hash'
161
+ | 'gasUsed'
162
+ | 'gasPrice'
163
+ | 'status'
164
+ | 'erc20Transfers'
165
+ | 'contractAddress'
166
+ | 'type'
167
+ | 'l1Fee'
159
168
  >
160
169
 
161
170
  export type BlockByHeightResult = {
@@ -58,6 +58,10 @@ export const STAKING_CONTRACTS: Record<string, StakingContractConfig> = {
58
58
  hrp: 'sei',
59
59
  endpoint: '/cosmos/staking/v1beta1/delegators/{address}/redelegations',
60
60
  },
61
+ unbondingStrategy: {
62
+ type: 'cosmos-rest',
63
+ endpoint: '/cosmos/staking/v1beta1/delegators/{address}/unbonding_delegations',
64
+ },
61
65
  rewardsStrategy: {
62
66
  type: 'cosmos-rest',
63
67
  endpoint: '/cosmos/distribution/v1beta1/delegators/{address}/rewards',
@@ -39,3 +39,4 @@ export {
39
39
  resolveRedelegationValidators,
40
40
  resolveStakingValidator,
41
41
  } from './redelegations'
42
+ export { fetchUnbondings } from './unbondings'
@@ -0,0 +1,245 @@
1
+ // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { EvmConfigInfo } from '../config'
5
+ import type { DeepPartialCtor } from '@ledgerhq/coin-module-framework/test/utils'
6
+ import { ethers } from 'ethers'
7
+ import { USEI_TO_EVM_SCALE } from '../utils'
8
+ import { STAKING_CONTRACTS } from './contracts'
9
+ import { fetchUnbondings } from './unbondings'
10
+
11
+ jest.mock('ethers', () => {
12
+ const actual = jest.requireActual('ethers')
13
+ const JsonRpcProvider = jest.fn()
14
+ const Contract = jest.fn()
15
+ return {
16
+ ...actual,
17
+ ethers: { ...actual.ethers, JsonRpcProvider, Contract },
18
+ JsonRpcProvider,
19
+ Contract,
20
+ }
21
+ })
22
+ jest.mock('@ledgerhq/live-network', () => jest.fn())
23
+ jest.mock('../network/node/types')
24
+
25
+ const mockNetwork = jest.mocked(require('@ledgerhq/live-network'))
26
+ const mockIsExternalNodeConfig = jest.mocked(require('../network/node/types').isExternalNodeConfig)
27
+
28
+ const mockNode: EvmConfigInfo['node'] = { type: 'external', uri: 'https://sei-evm.coin.ledger.com' }
29
+ const mockConfig: EvmConfigInfo = {
30
+ status: { type: 'active' },
31
+ chainId: 1329,
32
+ name: 'Sei',
33
+ node: mockNode,
34
+ explorer: { type: 'none' },
35
+ }
36
+
37
+ const SEI_CURRENCY = 'sei_evm'
38
+ const EVM_ADDRESS = '0x1111111111111111111111111111111111111111'
39
+ const VALIDATOR = 'seivaloper1qe8uuf5x69c526h4nzxwv4ltftr73v7qnkypla'
40
+ const OTHER_VALIDATOR = 'seivaloper1y82m5y3wevjneamzg0pmx87dzanyxzht0kepvn'
41
+
42
+ /** Far enough ahead that the entry is always still unbonding when the test runs. */
43
+ const futureDate = (daysFromNow: number): string =>
44
+ new Date(Date.now() + daysFromNow * 24 * 60 * 60 * 1000).toISOString()
45
+
46
+ const pastDate = (): string => new Date(Date.now() - 60 * 1000).toISOString()
47
+
48
+ function unbondingResponse(
49
+ validatorAddress: string,
50
+ entries: Array<{ balance: string; completion_time: string; creation_height?: string }>
51
+ ) {
52
+ return {
53
+ delegator_address: 'sei1delegator',
54
+ validator_address: validatorAddress,
55
+ entries: entries.map((e) => ({
56
+ creation_height: e.creation_height ?? '231825631',
57
+ completion_time: e.completion_time,
58
+ initial_balance: e.balance,
59
+ balance: e.balance,
60
+ })),
61
+ }
62
+ }
63
+
64
+ describe('staking/unbondings', () => {
65
+ describe('fetchUnbondings', () => {
66
+ let mockGetSeiAddr: jest.Mock
67
+
68
+ beforeEach(() => {
69
+ jest.clearAllMocks()
70
+ mockGetSeiAddr = jest.fn().mockResolvedValue('sei1defaultcosmosaddressfortest')
71
+ jest
72
+ .mocked<DeepPartialCtor<typeof ethers.JsonRpcProvider>>(ethers.JsonRpcProvider)
73
+ .mockImplementation(() => ({}))
74
+ jest
75
+ .mocked<DeepPartialCtor<typeof ethers.Contract>>(ethers.Contract)
76
+ .mockImplementation(() => ({ getSeiAddr: mockGetSeiAddr }))
77
+ mockIsExternalNodeConfig.mockImplementation((node: unknown) => node === mockNode)
78
+ })
79
+
80
+ it('should return [] for an unknown currencyId', async () => {
81
+ expect(await fetchUnbondings(mockConfig, 'unknown_chain', EVM_ADDRESS)).toEqual([])
82
+ expect(mockNetwork).not.toHaveBeenCalled()
83
+ })
84
+
85
+ it('should return [] for a currency without an unbonding strategy', async () => {
86
+ expect(await fetchUnbondings(mockConfig, 'celo', EVM_ADDRESS)).toEqual([])
87
+ expect(mockNetwork).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it('should return [] when the address is not associated on-chain yet', async () => {
91
+ mockGetSeiAddr.mockResolvedValue(null)
92
+ expect(await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)).toEqual([])
93
+ expect(mockNetwork).not.toHaveBeenCalled()
94
+ })
95
+
96
+ it('should return [] when the REST call fails', async () => {
97
+ mockNetwork.mockRejectedValue(new Error('network error'))
98
+ expect(await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)).toEqual([])
99
+ })
100
+
101
+ it('should return [] when the response has no unbonding_responses array', async () => {
102
+ mockNetwork.mockResolvedValue({ data: {} })
103
+ expect(await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)).toEqual([])
104
+ })
105
+
106
+ it('should query the delegator endpoint with the resolved Cosmos address', async () => {
107
+ mockNetwork.mockResolvedValue({ data: { unbonding_responses: [] } })
108
+
109
+ await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
110
+
111
+ expect(mockNetwork).toHaveBeenCalledWith({
112
+ url: 'https://rest.sei-apis.com/cosmos/staking/v1beta1/delegators/sei1defaultcosmosaddressfortest/unbonding_delegations',
113
+ method: 'GET',
114
+ })
115
+ })
116
+
117
+ it('should map a pending entry to a deactivating stake scaled to wei', async () => {
118
+ const completionTime = futureDate(21)
119
+ mockNetwork.mockResolvedValue({
120
+ data: {
121
+ unbonding_responses: [
122
+ unbondingResponse(VALIDATOR, [
123
+ { balance: '101000000', completion_time: completionTime },
124
+ ]),
125
+ ],
126
+ },
127
+ })
128
+
129
+ const stakes = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
130
+
131
+ expect(stakes).toHaveLength(1)
132
+ expect(stakes[0]).toMatchObject({
133
+ address: EVM_ADDRESS,
134
+ delegate: VALIDATOR,
135
+ state: 'deactivating',
136
+ stateUpdatedAt: new Date(completionTime),
137
+ amount: 101000000n * USEI_TO_EVM_SCALE,
138
+ actions: [],
139
+ })
140
+ expect(stakes[0].asset).toMatchObject({ type: 'native', name: 'Sei' })
141
+ })
142
+
143
+ it('should not expose a withdraw action nor a withdrawId', async () => {
144
+ mockNetwork.mockResolvedValue({
145
+ data: {
146
+ unbonding_responses: [
147
+ unbondingResponse(VALIDATOR, [{ balance: '1000000', completion_time: futureDate(21) }]),
148
+ ],
149
+ },
150
+ })
151
+
152
+ const [stake] = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
153
+
154
+ // Sei credits the funds back automatically: no withdraw transaction exists.
155
+ expect(stake.actions).toEqual([])
156
+ expect(stake.details).not.toHaveProperty('withdrawId')
157
+ })
158
+
159
+ it('should keep concurrent entries of the same validator distinct', async () => {
160
+ mockNetwork.mockResolvedValue({
161
+ data: {
162
+ unbonding_responses: [
163
+ unbondingResponse(VALIDATOR, [
164
+ { balance: '1000000', completion_time: futureDate(10), creation_height: '1' },
165
+ { balance: '2000000', completion_time: futureDate(20), creation_height: '2' },
166
+ ]),
167
+ ],
168
+ },
169
+ })
170
+
171
+ const stakes = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
172
+
173
+ expect(stakes).toHaveLength(2)
174
+ expect(new Set(stakes.map((s) => s.uid)).size).toBe(2)
175
+ expect(stakes.map((s) => s.amount)).toEqual([
176
+ 1000000n * USEI_TO_EVM_SCALE,
177
+ 2000000n * USEI_TO_EVM_SCALE,
178
+ ])
179
+ })
180
+
181
+ it('should map entries across several validators', async () => {
182
+ mockNetwork.mockResolvedValue({
183
+ data: {
184
+ unbonding_responses: [
185
+ unbondingResponse(VALIDATOR, [{ balance: '1000000', completion_time: futureDate(21) }]),
186
+ unbondingResponse(OTHER_VALIDATOR, [
187
+ { balance: '20000000', completion_time: futureDate(21) },
188
+ ]),
189
+ ],
190
+ },
191
+ })
192
+
193
+ const stakes = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
194
+
195
+ expect(stakes.map((s) => s.delegate)).toEqual([VALIDATOR, OTHER_VALIDATOR])
196
+ })
197
+
198
+ it('should skip entries whose unbonding period already completed', async () => {
199
+ mockNetwork.mockResolvedValue({
200
+ data: {
201
+ unbonding_responses: [
202
+ unbondingResponse(VALIDATOR, [
203
+ { balance: '1000000', completion_time: pastDate(), creation_height: '1' },
204
+ { balance: '2000000', completion_time: futureDate(5), creation_height: '2' },
205
+ ]),
206
+ ],
207
+ },
208
+ })
209
+
210
+ const stakes = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
211
+
212
+ expect(stakes).toHaveLength(1)
213
+ expect(stakes[0].amount).toBe(2000000n * USEI_TO_EVM_SCALE)
214
+ })
215
+
216
+ it('should skip malformed entries without failing the whole fetch', async () => {
217
+ mockNetwork.mockResolvedValue({
218
+ data: {
219
+ unbonding_responses: [
220
+ unbondingResponse(VALIDATOR, [
221
+ { balance: 'not-a-number', completion_time: futureDate(21), creation_height: '1' },
222
+ { balance: '1000000', completion_time: 'not-a-date', creation_height: '2' },
223
+ { balance: '0', completion_time: futureDate(21), creation_height: '3' },
224
+ { balance: '3000000', completion_time: futureDate(21), creation_height: '4' },
225
+ ]),
226
+ ],
227
+ },
228
+ })
229
+
230
+ const stakes = await fetchUnbondings(mockConfig, SEI_CURRENCY, EVM_ADDRESS)
231
+
232
+ expect(stakes).toHaveLength(1)
233
+ expect(stakes[0].amount).toBe(3000000n * USEI_TO_EVM_SCALE)
234
+ })
235
+ })
236
+
237
+ describe('sei_evm unbonding strategy config', () => {
238
+ it('should be configured to read the Cosmos unbonding_delegations endpoint', () => {
239
+ expect(STAKING_CONTRACTS[SEI_CURRENCY]?.unbondingStrategy).toEqual({
240
+ type: 'cosmos-rest',
241
+ endpoint: '/cosmos/staking/v1beta1/delegators/{address}/unbonding_delegations',
242
+ })
243
+ })
244
+ })
245
+ })
@@ -0,0 +1,137 @@
1
+ // SPDX-FileCopyrightText: © 2026 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { EvmConfigInfo } from '../config'
5
+ import type { StakingContractConfig, UnbondingStrategy } from '../types/staking'
6
+ import type { Stake } from '@ledgerhq/coin-module-framework/api/types'
7
+ import network from '@ledgerhq/live-network'
8
+ import { log } from '@ledgerhq/logs'
9
+ import { evmUnit } from '../logic/evmUnit'
10
+ import { isExternalNodeConfig } from '../network/node/types'
11
+ import { STAKING_CONTRACTS } from './contracts'
12
+ import { getCosmosAddr } from './redelegations'
13
+
14
+ type UnbondingEntry = {
15
+ creation_height: string
16
+ completion_time: string
17
+ balance: string
18
+ }
19
+
20
+ type ValidatorUnbonding = {
21
+ validator_address: string
22
+ entries: UnbondingEntry[]
23
+ }
24
+
25
+ type UnbondingsApiResponse = { unbonding_responses: ValidatorUnbonding[] }
26
+
27
+ /**
28
+ * The staking precompile only reports active delegations, so an undelegation
29
+ * would otherwise be invisible for the whole unbonding period.
30
+ *
31
+ * Returns `[]` on any failure so a sync is never blocked by this call.
32
+ */
33
+ async function fetchCosmosRestUnbondings(
34
+ evmConfig: EvmConfigInfo,
35
+ config: StakingContractConfig,
36
+ strategy: Extract<UnbondingStrategy, { type: 'cosmos-rest' }>,
37
+ currencyId: string,
38
+ evmAddress: string
39
+ ): Promise<Stake[]> {
40
+ const baseUrl = config.apiConfig?.baseUrl
41
+ const precompileAddress = config.apiConfig?.precompileAddress
42
+ if (!baseUrl || !precompileAddress) return []
43
+
44
+ const node = evmConfig.node
45
+ const evmRpcUrl = isExternalNodeConfig(node) ? node.uri : undefined
46
+ if (!evmRpcUrl) return []
47
+
48
+ const cosmosAddress = await getCosmosAddr(evmRpcUrl, precompileAddress, evmAddress)
49
+ if (!cosmosAddress) return []
50
+
51
+ const url = `${baseUrl.replace(/\/$/, '')}${strategy.endpoint.replace('{address}', cosmosAddress)}`
52
+
53
+ let data: UnbondingsApiResponse | undefined
54
+ try {
55
+ const res = await network<UnbondingsApiResponse>({ url, method: 'GET' })
56
+ data = res.data
57
+ } catch (e) {
58
+ log('coin-evm/staking', 'fetchCosmosRestUnbondings: REST request failed', {
59
+ url,
60
+ error: e instanceof Error ? e.message : String(e),
61
+ })
62
+ return []
63
+ }
64
+
65
+ if (!Array.isArray(data?.unbonding_responses)) return []
66
+
67
+ // The REST balance is in the same base unit as the staking calldata (usei).
68
+ const scale = config.calldataAmountScale ?? 1n
69
+ const contractAddress = config.contractAddress({ mode: 'undelegate' })
70
+ const now = new Date()
71
+ const stakes: Stake[] = []
72
+
73
+ for (const response of data.unbonding_responses) {
74
+ const validatorAddress = response.validator_address
75
+ if (typeof validatorAddress !== 'string' || !validatorAddress) continue
76
+
77
+ for (const entry of response.entries ?? []) {
78
+ const completionDate = new Date(entry.completion_time)
79
+ if (Number.isNaN(completionDate.valueOf())) continue
80
+ // A matured entry is already back in the available balance.
81
+ if (completionDate <= now) continue
82
+
83
+ let amount: bigint
84
+ try {
85
+ amount = BigInt(entry.balance) * scale
86
+ } catch {
87
+ continue
88
+ }
89
+ if (amount === 0n) continue
90
+
91
+ stakes.push({
92
+ // Cosmos keeps concurrent unbondings from one validator as separate entries.
93
+ uid: `${contractAddress}-${validatorAddress}-${evmAddress}-unbonding-${entry.creation_height}`,
94
+ address: evmAddress,
95
+ delegate: validatorAddress,
96
+ // Never `withdrawable`: Sei credits the funds back automatically, and the
97
+ // empty `actions` keeps `canWithdraw` false, so no withdraw action shows up.
98
+ state: 'deactivating',
99
+ stateUpdatedAt: completionDate,
100
+ asset: {
101
+ type: 'native',
102
+ name: evmConfig.name,
103
+ unit: evmUnit[currencyId],
104
+ },
105
+ amount,
106
+ actions: [],
107
+ details: {
108
+ contractAddress,
109
+ validator: validatorAddress,
110
+ },
111
+ })
112
+ }
113
+ }
114
+
115
+ return stakes
116
+ }
117
+
118
+ /**
119
+ * To support a new chain, add a `case` for its `UnbondingStrategy.type` and the
120
+ * matching entry in `STAKING_CONTRACTS`.
121
+ */
122
+ export async function fetchUnbondings(
123
+ evmConfig: EvmConfigInfo,
124
+ currencyId: string,
125
+ evmAddress: string
126
+ ): Promise<Stake[]> {
127
+ const config = STAKING_CONTRACTS[currencyId]
128
+ const strategy = config?.unbondingStrategy
129
+ if (!config || !strategy || strategy.type === 'none') return []
130
+
131
+ switch (strategy.type) {
132
+ case 'cosmos-rest':
133
+ return fetchCosmosRestUnbondings(evmConfig, config, strategy, currencyId, evmAddress)
134
+ default:
135
+ return []
136
+ }
137
+ }
@@ -24,7 +24,7 @@ describe('getValidators', () => {
24
24
  'somnia',
25
25
  createMockEvmCoinConfig({
26
26
  chainId: 5031,
27
- node: mkExternalNode({ uri: 'https://somnia-rpc.publicnode.com' }),
27
+ node: mkExternalNode({ uri: 'https://api.infra.mainnet.somnia.network' }),
28
28
  }),
29
29
  ],
30
30
  ])("fetches validators on '%s'", async (currencyId, config) => {
@@ -28,6 +28,8 @@ export type EtherscanOperation = {
28
28
  confirmations: string
29
29
  methodId: string
30
30
  functionName: string
31
+ /** L1 data/security fee in wei, as reported by OP-stack explorers (Optimism, Base, Blast, …). */
32
+ L1FeesPaid?: string
31
33
  }
32
34
 
33
35
  export type EtherscanERC20Event = {