@ledgerhq/coin-evm 16.5.4 → 16.8.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.
- package/CHANGELOG.md +22 -0
- package/lib/api/index.d.ts +5 -2
- package/lib/api/index.d.ts.map +1 -1
- package/lib/api/index.js +2 -1
- package/lib/api/index.js.map +1 -1
- package/lib/errors.d.ts +17 -0
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +26 -1
- package/lib/errors.js.map +1 -1
- package/lib/logic/cip64Fees.d.ts +43 -0
- package/lib/logic/cip64Fees.d.ts.map +1 -0
- package/lib/logic/cip64Fees.js +139 -0
- package/lib/logic/cip64Fees.js.map +1 -0
- package/lib/logic/feeCollectorOperations.d.ts +2 -2
- package/lib/logic/feeCollectorOperations.js +2 -2
- package/lib/logic/getBlock.d.ts +2 -2
- package/lib/logic/getBlock.d.ts.map +1 -1
- package/lib/logic/getBlock.js +99 -19
- package/lib/logic/getBlock.js.map +1 -1
- package/lib/network/node/rpc.common.d.ts.map +1 -1
- package/lib/network/node/rpc.common.js +20 -0
- package/lib/network/node/rpc.common.js.map +1 -1
- package/lib/network/node/types.d.ts +6 -0
- package/lib/network/node/types.d.ts.map +1 -1
- package/lib/network/node/types.js.map +1 -1
- package/lib/network/node/withNodeSources.d.ts.map +1 -1
- package/lib/network/node/withNodeSources.js +2 -0
- package/lib/network/node/withNodeSources.js.map +1 -1
- package/lib/staking/contracts.d.ts.map +1 -1
- package/lib/staking/contracts.js +7 -0
- package/lib/staking/contracts.js.map +1 -1
- package/lib/staking/validators/index.d.ts.map +1 -1
- package/lib/staking/validators/index.js +36 -1
- package/lib/staking/validators/index.js.map +1 -1
- package/lib/staking/validators/monad.d.ts +1 -0
- package/lib/staking/validators/monad.d.ts.map +1 -1
- package/lib/staking/validators/monad.js +103 -6
- package/lib/staking/validators/monad.js.map +1 -1
- package/lib/staking/validators/sei.d.ts.map +1 -1
- package/lib/staking/validators/sei.js +46 -14
- package/lib/staking/validators/sei.js.map +1 -1
- package/lib/staking/validators/somnia.d.ts.map +1 -1
- package/lib/staking/validators/somnia.js +31 -2
- package/lib/staking/validators/somnia.js.map +1 -1
- package/lib/staking/validators/zero_gravity.d.ts.map +1 -1
- package/lib/staking/validators/zero_gravity.js +14 -2
- package/lib/staking/validators/zero_gravity.js.map +1 -1
- package/lib/types/staking.d.ts +10 -0
- package/lib/types/staking.d.ts.map +1 -1
- package/lib-es/api/index.d.ts +5 -2
- package/lib-es/api/index.d.ts.map +1 -1
- package/lib-es/api/index.js +2 -1
- package/lib-es/api/index.js.map +1 -1
- package/lib-es/errors.d.ts +17 -0
- package/lib-es/errors.d.ts.map +1 -1
- package/lib-es/errors.js +21 -0
- package/lib-es/errors.js.map +1 -1
- package/lib-es/logic/cip64Fees.d.ts +43 -0
- package/lib-es/logic/cip64Fees.d.ts.map +1 -0
- package/lib-es/logic/cip64Fees.js +134 -0
- package/lib-es/logic/cip64Fees.js.map +1 -0
- package/lib-es/logic/feeCollectorOperations.d.ts +2 -2
- package/lib-es/logic/feeCollectorOperations.js +2 -2
- package/lib-es/logic/getBlock.d.ts +2 -2
- package/lib-es/logic/getBlock.d.ts.map +1 -1
- package/lib-es/logic/getBlock.js +99 -19
- package/lib-es/logic/getBlock.js.map +1 -1
- package/lib-es/network/node/rpc.common.d.ts.map +1 -1
- package/lib-es/network/node/rpc.common.js +20 -0
- package/lib-es/network/node/rpc.common.js.map +1 -1
- package/lib-es/network/node/types.d.ts +6 -0
- package/lib-es/network/node/types.d.ts.map +1 -1
- package/lib-es/network/node/types.js.map +1 -1
- package/lib-es/network/node/withNodeSources.d.ts.map +1 -1
- package/lib-es/network/node/withNodeSources.js +2 -0
- package/lib-es/network/node/withNodeSources.js.map +1 -1
- package/lib-es/staking/contracts.d.ts.map +1 -1
- package/lib-es/staking/contracts.js +7 -0
- package/lib-es/staking/contracts.js.map +1 -1
- package/lib-es/staking/validators/index.d.ts.map +1 -1
- package/lib-es/staking/validators/index.js +3 -1
- package/lib-es/staking/validators/index.js.map +1 -1
- package/lib-es/staking/validators/monad.d.ts +1 -0
- package/lib-es/staking/validators/monad.d.ts.map +1 -1
- package/lib-es/staking/validators/monad.js +101 -5
- package/lib-es/staking/validators/monad.js.map +1 -1
- package/lib-es/staking/validators/sei.d.ts.map +1 -1
- package/lib-es/staking/validators/sei.js +46 -14
- package/lib-es/staking/validators/sei.js.map +1 -1
- package/lib-es/staking/validators/somnia.d.ts.map +1 -1
- package/lib-es/staking/validators/somnia.js +31 -2
- package/lib-es/staking/validators/somnia.js.map +1 -1
- package/lib-es/staking/validators/zero_gravity.d.ts.map +1 -1
- package/lib-es/staking/validators/zero_gravity.js +14 -2
- package/lib-es/staking/validators/zero_gravity.js.map +1 -1
- package/lib-es/types/staking.d.ts +10 -0
- package/lib-es/types/staking.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/api/index.ts +4 -1
- package/src/api/tests/index.celo.integ.test.ts +93 -0
- package/src/api/tests/index.flare.integ.test.ts +2 -1
- package/src/api/tests/index.test.ts +9 -0
- package/src/errors.ts +24 -0
- package/src/logic/cip64Fees.ts +193 -0
- package/src/logic/feeCollectorOperations.ts +2 -2
- package/src/logic/getBlock.ts +170 -30
- package/src/logic/tests/cip64Fees.test.ts +277 -0
- package/src/logic/tests/getBlock.test.ts +249 -2
- package/src/network/node/rpc.common.ts +29 -0
- package/src/network/node/types.ts +6 -0
- package/src/network/node/withNodeSources.ts +3 -0
- package/src/network/tests/node/rpc.test.ts +39 -0
- package/src/network/tests/node/withNodeSources.test.ts +18 -0
- package/src/staking/contracts.ts +7 -0
- package/src/staking/validators/index.ts +4 -1
- package/src/staking/validators/monad.test.ts +175 -44
- package/src/staking/validators/monad.ts +156 -4
- package/src/staking/validators/sei.test.ts +93 -0
- package/src/staking/validators/sei.ts +56 -14
- package/src/staking/validators/somnia.test.ts +44 -2
- package/src/staking/validators/somnia.ts +32 -2
- package/src/staking/validators/zero_gravity.test.ts +25 -0
- package/src/staking/validators/zero_gravity.ts +17 -2
- package/src/staking/validators.integ.test.ts +35 -4
- package/src/staking/validators.test.ts +34 -22
- package/src/types/staking.ts +10 -0
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { EvmConfigInfo } from '../../config'
|
|
5
5
|
import type { StakingContractConfig } from '../../types/staking'
|
|
6
|
-
import type { AddressLike } from 'ethers'
|
|
6
|
+
import type { AddressLike, JsonRpcProvider } from 'ethers'
|
|
7
7
|
import network from '@ledgerhq/live-network'
|
|
8
8
|
import { ethers } from 'ethers'
|
|
9
9
|
import monadAbi from '../../abis/monad.abi.json'
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
mkLedgerNode,
|
|
15
15
|
testLogger,
|
|
16
16
|
} from '../../fixtures/context.fixtures'
|
|
17
|
-
import { mkJsonRpcProvider } from '../../fixtures/ethers.fixtures'
|
|
17
|
+
import { mkBlock, mkJsonRpcProvider } from '../../fixtures/ethers.fixtures'
|
|
18
18
|
import { withApi } from '../../network/node/rpc.common'
|
|
19
19
|
import { fetchMonadStakes, extractMonadKnownValIds } from './monad'
|
|
20
20
|
import { getValidatorAddressById } from './monadResolver'
|
|
@@ -77,11 +77,33 @@ type CallHandler = (request: {
|
|
|
77
77
|
const parseCalldata = (data: string | Uint8Array) =>
|
|
78
78
|
monadIface.parseTransaction({ data: ethers.hexlify(data) })
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
type GetBlock = JsonRpcProvider['getBlock']
|
|
81
|
+
|
|
82
|
+
const getBlockWith =
|
|
83
|
+
({ latest, previous }: { latest: number; previous: number }): GetBlock =>
|
|
84
|
+
async (blockHashOrTag) =>
|
|
85
|
+
blockHashOrTag === 'latest'
|
|
86
|
+
? mkBlock({ number: 20_000, timestamp: latest })
|
|
87
|
+
: mkBlock({ number: 10_000, timestamp: previous })
|
|
88
|
+
|
|
89
|
+
// 10,000 blocks in 5,000s: a block time of 0.5s, i.e. 63,072,000 blocks per year.
|
|
90
|
+
const defaultGetBlock = getBlockWith({ latest: 5_000, previous: 0 })
|
|
91
|
+
|
|
92
|
+
// With that block time, a total stake of 1,135,296,000 MON gives a gross rate of exactly 1
|
|
93
|
+
// (18 MON per block, 63,072,000 blocks per year).
|
|
94
|
+
const MON = 10n ** 18n
|
|
95
|
+
|
|
96
|
+
const countCalls = (
|
|
97
|
+
callMock: jest.Mock<ReturnType<CallHandler>, Parameters<CallHandler>>,
|
|
98
|
+
name: string
|
|
99
|
+
) => callMock.mock.calls.filter(([{ data }]) => data && parseCalldata(data)?.name === name).length
|
|
100
|
+
|
|
101
|
+
const setupRpc = (handler: CallHandler, getBlock: GetBlock = defaultGetBlock) => {
|
|
81
102
|
const callMock = jest.fn(handler)
|
|
82
103
|
mockedWithApi.mockImplementation(async (_config, fn) => {
|
|
83
104
|
const api = mkJsonRpcProvider()
|
|
84
105
|
jest.spyOn(api, 'call').mockImplementation(callMock)
|
|
106
|
+
jest.spyOn(api, 'getBlock').mockImplementation(getBlock)
|
|
85
107
|
return fn(api)
|
|
86
108
|
})
|
|
87
109
|
return callMock
|
|
@@ -161,20 +183,25 @@ describe('staking/validators/monad', () => {
|
|
|
161
183
|
it('fetches and maps a single page of validators from the precompile', async () => {
|
|
162
184
|
const valDetails: Record<string, { stake: bigint; commission: bigint; secpPubkey: string }> = {
|
|
163
185
|
'1': {
|
|
164
|
-
stake:
|
|
186
|
+
stake: 756_864_000n * MON,
|
|
165
187
|
commission: 10n ** 17n,
|
|
166
188
|
secpPubkey: '0x036e44a092493800e427b2b08d3427d804348b1368ecd0a6af6510ae40ce507187',
|
|
167
189
|
}, // 10%
|
|
168
190
|
'2': {
|
|
169
|
-
stake:
|
|
191
|
+
stake: 378_432_000n * MON,
|
|
170
192
|
commission: 5n * 10n ** 16n,
|
|
171
193
|
secpPubkey: '0x0316e0861acf92dc4c0e357f73fe07263a87b65513a4b73750ab9194f9a39a6a54',
|
|
172
194
|
}, // 5%
|
|
195
|
+
'3': {
|
|
196
|
+
stake: 0n,
|
|
197
|
+
commission: 10n ** 18n,
|
|
198
|
+
secpPubkey: '0x036e44a092493800e427b2b08d3427d804348b1368ecd0a6af6510ae40ce507187',
|
|
199
|
+
}, // 100%: the validator keeps the whole reward
|
|
173
200
|
}
|
|
174
201
|
|
|
175
202
|
const callMock = setupRpc(
|
|
176
203
|
routeByName({
|
|
177
|
-
getExecutionValidatorSet: () => encodeExecValSet(true, 0, [1n, 2n]),
|
|
204
|
+
getExecutionValidatorSet: () => encodeExecValSet(true, 0, [1n, 2n, 3n]),
|
|
178
205
|
getValidator: (valId) => encodeGetValidator(valDetails[valId.toString()]),
|
|
179
206
|
})
|
|
180
207
|
)
|
|
@@ -188,8 +215,8 @@ describe('staking/validators/monad', () => {
|
|
|
188
215
|
),
|
|
189
216
|
name: 'Validator 1',
|
|
190
217
|
commissionRate: '0.1',
|
|
191
|
-
balance:
|
|
192
|
-
apy: 0,
|
|
218
|
+
balance: 756_864_000n * MON,
|
|
219
|
+
apy: 0.9,
|
|
193
220
|
},
|
|
194
221
|
{
|
|
195
222
|
id: '2',
|
|
@@ -198,13 +225,25 @@ describe('staking/validators/monad', () => {
|
|
|
198
225
|
),
|
|
199
226
|
name: 'Validator 2',
|
|
200
227
|
commissionRate: '0.05',
|
|
201
|
-
balance:
|
|
228
|
+
balance: 378_432_000n * MON,
|
|
229
|
+
apy: 0.95,
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
id: '3',
|
|
233
|
+
address: ethers.computeAddress(
|
|
234
|
+
'0x036e44a092493800e427b2b08d3427d804348b1368ecd0a6af6510ae40ce507187'
|
|
235
|
+
),
|
|
236
|
+
name: 'Validator 3',
|
|
237
|
+
commissionRate: '1.0',
|
|
238
|
+
balance: 0n,
|
|
202
239
|
apy: 0,
|
|
203
240
|
},
|
|
204
241
|
],
|
|
205
242
|
next: undefined,
|
|
206
243
|
})
|
|
207
244
|
expect(callMock.mock.calls.every(([req]) => req.to === PRECOMPILE)).toBe(true)
|
|
245
|
+
// the validators fetched for the total stake are reused by the page
|
|
246
|
+
expect(countCalls(callMock, 'getValidator')).toBe(3)
|
|
208
247
|
|
|
209
248
|
// a non-empty page is cached: the second read makes no further RPC calls
|
|
210
249
|
const callsAfterFirst = callMock.mock.calls.length
|
|
@@ -212,6 +251,69 @@ describe('staking/validators/monad', () => {
|
|
|
212
251
|
expect(callMock.mock.calls.length).toBe(callsAfterFirst)
|
|
213
252
|
})
|
|
214
253
|
|
|
254
|
+
// `validatorCalls` is the number of getValidator calls for a single validator: when the block
|
|
255
|
+
// time fails, the validators are not scanned for nothing, they are only fetched by the page.
|
|
256
|
+
it.each([
|
|
257
|
+
['the latest block is missing', async () => null, 1],
|
|
258
|
+
[
|
|
259
|
+
'the previous block is missing',
|
|
260
|
+
async (tag: Parameters<GetBlock>[0]) =>
|
|
261
|
+
tag === 'latest' ? mkBlock({ number: 20_000, timestamp: 5_000 }) : null,
|
|
262
|
+
1,
|
|
263
|
+
],
|
|
264
|
+
[
|
|
265
|
+
'the block request fails',
|
|
266
|
+
async () => {
|
|
267
|
+
throw new Error('rpc timeout')
|
|
268
|
+
},
|
|
269
|
+
1,
|
|
270
|
+
],
|
|
271
|
+
// scanned for the total stake, then fetched again by the page as the rate is not usable
|
|
272
|
+
['the block time is zero', getBlockWith({ latest: 0, previous: 0 }), 2],
|
|
273
|
+
// 18 MON per block shared between 1,000 MON would be an apy way above 1
|
|
274
|
+
['the apy would be above 1', defaultGetBlock, 1],
|
|
275
|
+
])(
|
|
276
|
+
'keeps the validators with an undefined apy when %s',
|
|
277
|
+
async (_label, getBlock, validatorCalls) => {
|
|
278
|
+
const callMock = setupRpc(
|
|
279
|
+
routeByName({
|
|
280
|
+
getExecutionValidatorSet: () => encodeExecValSet(true, 0, [1n]),
|
|
281
|
+
getValidator: () => encodeGetValidator({ stake: 1_000n * MON, commission: 0n }),
|
|
282
|
+
}),
|
|
283
|
+
getBlock
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
const page = await getValidators(mockConfig, testLogger)
|
|
287
|
+
|
|
288
|
+
expect(page.items).toHaveLength(1)
|
|
289
|
+
expect(page.items[0].apy).toBeUndefined()
|
|
290
|
+
expect(countCalls(callMock, 'getValidator')).toBe(validatorCalls)
|
|
291
|
+
}
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
it('gives up on the apy after a deadline and still returns the validators', async () => {
|
|
295
|
+
jest.useFakeTimers()
|
|
296
|
+
try {
|
|
297
|
+
setupRpc(
|
|
298
|
+
routeByName({
|
|
299
|
+
getExecutionValidatorSet: () => encodeExecValSet(true, 0, [1n]),
|
|
300
|
+
getValidator: () => encodeGetValidator({ stake: 1_000n * MON, commission: 0n }),
|
|
301
|
+
}),
|
|
302
|
+
// a node that never answers the block lookups
|
|
303
|
+
() => new Promise(() => undefined)
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
const pending = getValidators(mockConfig, testLogger)
|
|
307
|
+
await jest.advanceTimersByTimeAsync(10_000)
|
|
308
|
+
const page = await pending
|
|
309
|
+
|
|
310
|
+
expect(page.items).toHaveLength(1)
|
|
311
|
+
expect(page.items[0].apy).toBeUndefined()
|
|
312
|
+
} finally {
|
|
313
|
+
jest.useRealTimers()
|
|
314
|
+
}
|
|
315
|
+
})
|
|
316
|
+
|
|
215
317
|
it('enriches the validator name from the validator-info overlay (keyed by secp pubkey)', async () => {
|
|
216
318
|
setupRpc(
|
|
217
319
|
routeByName({
|
|
@@ -248,22 +350,39 @@ describe('staking/validators/monad', () => {
|
|
|
248
350
|
})
|
|
249
351
|
|
|
250
352
|
it('returns the surviving validators when one getValidator call fails', async () => {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
353
|
+
const handler = routeByName({
|
|
354
|
+
getExecutionValidatorSet: () => encodeExecValSet(true, 0, [1n, 2n]),
|
|
355
|
+
getValidator: (valId) =>
|
|
356
|
+
valId === 1n
|
|
357
|
+
? new Error('rpc timeout')
|
|
358
|
+
: encodeGetValidator({
|
|
359
|
+
stake: 42n,
|
|
360
|
+
commission: 0n,
|
|
361
|
+
secpPubkey: '0x0316e0861acf92dc4c0e357f73fe07263a87b65513a4b73750ab9194f9a39a6a54',
|
|
362
|
+
}),
|
|
363
|
+
})
|
|
364
|
+
// Validator 2 answers after validator 1 failed: the page must not start its own getValidator
|
|
365
|
+
// calls while the ones of the total stake are still running.
|
|
366
|
+
let inFlight = 0
|
|
367
|
+
let maxInFlight = 0
|
|
368
|
+
setupRpc(async (request) => {
|
|
369
|
+
const call = request.data ? parseCalldata(request.data) : null
|
|
370
|
+
inFlight++
|
|
371
|
+
maxInFlight = Math.max(maxInFlight, inFlight)
|
|
372
|
+
try {
|
|
373
|
+
if (call?.name === 'getValidator' && call.args[0] === 2n) {
|
|
374
|
+
await new Promise((resolve) => setTimeout(resolve, 20))
|
|
375
|
+
}
|
|
376
|
+
return await handler(request)
|
|
377
|
+
} finally {
|
|
378
|
+
inFlight--
|
|
379
|
+
}
|
|
380
|
+
})
|
|
264
381
|
|
|
265
382
|
const page = await getValidators(mockConfig, testLogger)
|
|
266
383
|
|
|
384
|
+
expect(maxInFlight).toBeLessThanOrEqual(2)
|
|
385
|
+
|
|
267
386
|
expect(page.items).toHaveLength(1)
|
|
268
387
|
expect(page.items[0]).toMatchObject({
|
|
269
388
|
address: ethers.computeAddress(
|
|
@@ -271,6 +390,8 @@ describe('staking/validators/monad', () => {
|
|
|
271
390
|
),
|
|
272
391
|
name: 'Validator 2',
|
|
273
392
|
balance: 42n,
|
|
393
|
+
// the total stake is unknown without validator 1, hence so is the APY
|
|
394
|
+
apy: undefined,
|
|
274
395
|
})
|
|
275
396
|
})
|
|
276
397
|
|
|
@@ -376,7 +497,8 @@ describe('staking/validators/monad', () => {
|
|
|
376
497
|
startIndex === 0n
|
|
377
498
|
? encodeExecValSet(false, 100, [1n])
|
|
378
499
|
: encodeExecValSet(true, 0, [2n]),
|
|
379
|
-
|
|
500
|
+
// the total stake of both pages gives a gross reward rate of exactly 1
|
|
501
|
+
getValidator: () => encodeGetValidator({ stake: 567_648_000n * MON, commission: 0n }),
|
|
380
502
|
})
|
|
381
503
|
)
|
|
382
504
|
|
|
@@ -393,8 +515,8 @@ describe('staking/validators/monad', () => {
|
|
|
393
515
|
),
|
|
394
516
|
name: 'Validator 1',
|
|
395
517
|
commissionRate: '0.0',
|
|
396
|
-
balance:
|
|
397
|
-
apy:
|
|
518
|
+
balance: 567_648_000n * MON,
|
|
519
|
+
apy: 1,
|
|
398
520
|
},
|
|
399
521
|
],
|
|
400
522
|
next: '100',
|
|
@@ -407,28 +529,37 @@ describe('staking/validators/monad', () => {
|
|
|
407
529
|
expect(callMock.mock.calls.length).toBe(callsAfterBoth)
|
|
408
530
|
})
|
|
409
531
|
|
|
410
|
-
it(
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
532
|
+
it.each([
|
|
533
|
+
['clearValidatorsCache(chainId)', () => clearValidatorsCache(CHAIN_ID.MONAD)],
|
|
534
|
+
['clearValidatorsCache()', () => clearValidatorsCache()],
|
|
535
|
+
])(
|
|
536
|
+
'%s drops every cached cursor and the validators they were built from',
|
|
537
|
+
async (_label, clear) => {
|
|
538
|
+
let stake = 1n
|
|
539
|
+
const callMock = setupRpc(
|
|
540
|
+
routeByName({
|
|
541
|
+
getExecutionValidatorSet: (startIndex) =>
|
|
542
|
+
startIndex === 0n
|
|
543
|
+
? encodeExecValSet(false, 100, [1n])
|
|
544
|
+
: encodeExecValSet(true, 0, [2n]),
|
|
545
|
+
getValidator: () => encodeGetValidator({ stake, commission: 0n }),
|
|
546
|
+
})
|
|
547
|
+
)
|
|
420
548
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
549
|
+
await getValidators(mockConfig, testLogger)
|
|
550
|
+
await getValidators(mockConfig, testLogger, '100')
|
|
551
|
+
const callsBeforeClear = callMock.mock.calls.length
|
|
424
552
|
|
|
425
|
-
|
|
553
|
+
stake = 2n
|
|
554
|
+
clear()
|
|
426
555
|
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
556
|
+
// every cursor was evicted, so both reads hit the precompile again, for fresh details
|
|
557
|
+
const first = await getValidators(mockConfig, testLogger)
|
|
558
|
+
const second = await getValidators(mockConfig, testLogger, '100')
|
|
559
|
+
expect(callMock.mock.calls.length).toBeGreaterThan(callsBeforeClear)
|
|
560
|
+
expect([first.items[0].balance, second.items[0].balance]).toStrictEqual([2n, 2n])
|
|
561
|
+
}
|
|
562
|
+
)
|
|
432
563
|
})
|
|
433
564
|
|
|
434
565
|
describe('getValidatorAddressById', () => {
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { ChainId, EvmConfigInfo } from '../../config'
|
|
5
5
|
import type { StakingContractConfig } from '../../types/staking'
|
|
6
|
+
import type { ValidatorRaw } from './monadResolver'
|
|
6
7
|
import type { ValidatorApi } from './types'
|
|
7
8
|
import type { Cursor, Page } from '@ledgerhq/coin-module-framework/api/index'
|
|
8
9
|
import type {
|
|
@@ -158,12 +159,141 @@ const resolveContext = (evmConfig: EvmConfigInfo): ResolvedContext | undefined =
|
|
|
158
159
|
}
|
|
159
160
|
}
|
|
160
161
|
|
|
162
|
+
// Fixed inflationary reward minted per block (MON), since MIP-12. Priority fees go only to the
|
|
163
|
+
// validator, so they are not part of the delegators' APY.
|
|
164
|
+
// Source: https://docs.monad.xyz/monad-arch/consensus/staking
|
|
165
|
+
const BLOCK_REWARD_MON = 18
|
|
166
|
+
const SECONDS_PER_YEAR = 365 * 24 * 60 * 60
|
|
167
|
+
// The block time is averaged over the last blocks: far more than the 1s timestamp resolution.
|
|
168
|
+
const BLOCK_TIME_SAMPLE_SIZE = 10_000
|
|
169
|
+
// Same lifetime as the on-chain page cache in ./index.ts.
|
|
170
|
+
const REWARD_RATE_CACHE_MAX_AGE_MS = 30 * 1000
|
|
171
|
+
// The APY is optional: a stalled node must not keep the page past the 30s timeout of the
|
|
172
|
+
// coin service. The computation goes on in the cache, for the next reads.
|
|
173
|
+
const REWARD_RATE_DEADLINE_MS = 10 * 1000
|
|
174
|
+
|
|
175
|
+
const withDeadline = <T>(promise: Promise<T>, ms: number): Promise<T> =>
|
|
176
|
+
new Promise<T>((resolve, reject) => {
|
|
177
|
+
const timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms)
|
|
178
|
+
promise.then(resolve, reject).finally(() => clearTimeout(timer))
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
const fetchBlockTimeSeconds = async (provider: JsonRpcProvider): Promise<number> => {
|
|
182
|
+
const latest = await provider.getBlock('latest')
|
|
183
|
+
if (!latest) throw new Error('latest block not found')
|
|
184
|
+
const previous = await provider.getBlock(latest.number - BLOCK_TIME_SAMPLE_SIZE)
|
|
185
|
+
if (!previous) throw new Error('previous block not found')
|
|
186
|
+
return (latest.timestamp - previous.timestamp) / BLOCK_TIME_SAMPLE_SIZE
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Pages are read one after the other: each one gives the start of the next.
|
|
190
|
+
const fetchExecutionValidatorIds = async (
|
|
191
|
+
provider: JsonRpcProvider,
|
|
192
|
+
iface: ethers.Interface,
|
|
193
|
+
contractAddress: string,
|
|
194
|
+
startIndex = 0n
|
|
195
|
+
): Promise<bigint[]> => {
|
|
196
|
+
const raw = await provider.call({
|
|
197
|
+
to: contractAddress,
|
|
198
|
+
data: iface.encodeFunctionData('getExecutionValidatorSet', [startIndex]),
|
|
199
|
+
})
|
|
200
|
+
const decoded = iface.decodeFunctionResult('getExecutionValidatorSet', raw)
|
|
201
|
+
if (!isValidatorSetRaw(decoded)) throw new Error('getExecutionValidatorSet: unexpected format')
|
|
202
|
+
const [isDone, nextIndex, pageIds] = decoded
|
|
203
|
+
if (isDone || pageIds.length === 0 || nextIndex <= startIndex) return pageIds
|
|
204
|
+
return [
|
|
205
|
+
...pageIds,
|
|
206
|
+
...(await fetchExecutionValidatorIds(provider, iface, contractAddress, nextIndex)),
|
|
207
|
+
]
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Batches are read one after the other, to cap the concurrency (see DETAILS_BATCH_SIZE).
|
|
211
|
+
const fetchValidatorsRaw = async (
|
|
212
|
+
provider: JsonRpcProvider,
|
|
213
|
+
iface: ethers.Interface,
|
|
214
|
+
contractAddress: string,
|
|
215
|
+
valIds: bigint[],
|
|
216
|
+
fetched = new Map<bigint, ValidatorRaw>()
|
|
217
|
+
): Promise<Map<bigint, ValidatorRaw>> => {
|
|
218
|
+
if (valIds.length === 0) return fetched
|
|
219
|
+
const batch = valIds.slice(0, DETAILS_BATCH_SIZE)
|
|
220
|
+
// Every call of the batch is over before a failure is propagated: the calls that follow, such as
|
|
221
|
+
// the page's own, do not add up to the ones still running.
|
|
222
|
+
const settled = await Promise.allSettled(
|
|
223
|
+
batch.map((valId) => callGetValidator(provider, iface, contractAddress, valId))
|
|
224
|
+
)
|
|
225
|
+
batch.forEach((valId, idx) => {
|
|
226
|
+
const result = settled[idx]
|
|
227
|
+
if (result.status === 'rejected') throw result.reason
|
|
228
|
+
if (!result.value) throw new Error('getValidator: unexpected format')
|
|
229
|
+
fetched.set(valId, result.value)
|
|
230
|
+
})
|
|
231
|
+
return fetchValidatorsRaw(
|
|
232
|
+
provider,
|
|
233
|
+
iface,
|
|
234
|
+
contractAddress,
|
|
235
|
+
valIds.slice(DETAILS_BATCH_SIZE),
|
|
236
|
+
fetched
|
|
237
|
+
)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
type RewardRate = {
|
|
241
|
+
// Reward rate of the whole network, before commission.
|
|
242
|
+
grossRate: number
|
|
243
|
+
// Every validator of the execution set, so that the pages do not fetch them again.
|
|
244
|
+
validators: Map<bigint, ValidatorRaw>
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Yearly rewards over the total stake of the execution validator set.
|
|
248
|
+
// Source: https://docs.stakingrewards.com/staking-data/methodologies/monad-srb
|
|
249
|
+
// Throws when it cannot be computed, so that a failure is not cached.
|
|
250
|
+
const fetchRewardRate = async (
|
|
251
|
+
provider: JsonRpcProvider,
|
|
252
|
+
iface: ethers.Interface,
|
|
253
|
+
contractAddress: string
|
|
254
|
+
): Promise<RewardRate> => {
|
|
255
|
+
// The block time comes first: when it fails, no validator is fetched for nothing.
|
|
256
|
+
const blockTime = await fetchBlockTimeSeconds(provider)
|
|
257
|
+
const valIds = await fetchExecutionValidatorIds(provider, iface, contractAddress)
|
|
258
|
+
const validators = await fetchValidatorsRaw(provider, iface, contractAddress, valIds)
|
|
259
|
+
|
|
260
|
+
const totalStake = [...validators.values()].reduce((total, validator) => total + validator[2], 0n)
|
|
261
|
+
const grossRate =
|
|
262
|
+
(BLOCK_REWARD_MON * (SECONDS_PER_YEAR / blockTime)) / Number(ethers.formatUnits(totalStake, 18))
|
|
263
|
+
if (!Number.isFinite(grossRate)) throw new Error(`invalid reward rate ${grossRate}`)
|
|
264
|
+
return { grossRate, validators }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const rewardRateCache = makeLRUCache(
|
|
268
|
+
(
|
|
269
|
+
_chainId: ChainId,
|
|
270
|
+
provider: JsonRpcProvider,
|
|
271
|
+
iface: ethers.Interface,
|
|
272
|
+
contractAddress: string
|
|
273
|
+
) => fetchRewardRate(provider, iface, contractAddress),
|
|
274
|
+
String,
|
|
275
|
+
{ max: 10, ttl: REWARD_RATE_CACHE_MAX_AGE_MS }
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
// Drop the cached reward rate, and the validators it holds, of a chain or of every chain.
|
|
279
|
+
export const clearRewardRateCache = (chainId?: ChainId): void => {
|
|
280
|
+
if (chainId === undefined) rewardRateCache.reset()
|
|
281
|
+
else rewardRateCache.clear(String(chainId))
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// The apy is a fraction between 0 and 1: anything else means the rate cannot be trusted.
|
|
285
|
+
const toApy = (grossRate: number | undefined, commissionRate: string): number | undefined => {
|
|
286
|
+
const apy = grossRate === undefined ? Number.NaN : grossRate * (1 - Number(commissionRate))
|
|
287
|
+
return apy >= 0 && apy <= 1 ? apy : undefined
|
|
288
|
+
}
|
|
289
|
+
|
|
161
290
|
const fetchValidatorDetails = async (
|
|
162
291
|
chainId: ChainId,
|
|
163
292
|
provider: JsonRpcProvider,
|
|
164
293
|
iface: ethers.Interface,
|
|
165
294
|
contractAddress: string,
|
|
166
295
|
valIds: bigint[],
|
|
296
|
+
rewardRate: RewardRate | undefined,
|
|
167
297
|
logger: Logger
|
|
168
298
|
): Promise<Validator[]> => {
|
|
169
299
|
const items: Validator[] = []
|
|
@@ -172,7 +302,9 @@ const fetchValidatorDetails = async (
|
|
|
172
302
|
const chunk = valIds.slice(i, i + DETAILS_BATCH_SIZE)
|
|
173
303
|
const settled = await Promise.allSettled(
|
|
174
304
|
chunk.map(async (valId) => {
|
|
175
|
-
const decoded =
|
|
305
|
+
const decoded =
|
|
306
|
+
rewardRate?.validators.get(valId) ??
|
|
307
|
+
(await callGetValidator(provider, iface, contractAddress, valId))
|
|
176
308
|
if (!decoded) return undefined
|
|
177
309
|
|
|
178
310
|
const [, , stake, , commission, , , , , , secpPubkey] = decoded
|
|
@@ -180,13 +312,14 @@ const fetchValidatorDetails = async (
|
|
|
180
312
|
const name =
|
|
181
313
|
secp.length > 0 ? await validatorNameCache(chainId, secp, logger).catch(() => null) : null
|
|
182
314
|
|
|
315
|
+
const commissionRate = ethers.formatUnits(commission, COMMISSION_DECIMALS)
|
|
183
316
|
return {
|
|
184
317
|
id: valId.toString(),
|
|
185
318
|
address: ethers.computeAddress(secpPubkey),
|
|
186
319
|
name: name ?? `Validator ${valId.toString()}`,
|
|
187
|
-
commissionRate
|
|
320
|
+
commissionRate,
|
|
188
321
|
balance: stake,
|
|
189
|
-
apy:
|
|
322
|
+
apy: toApy(rewardRate?.grossRate, commissionRate),
|
|
190
323
|
}
|
|
191
324
|
})
|
|
192
325
|
)
|
|
@@ -217,6 +350,17 @@ const fetchPage = async (
|
|
|
217
350
|
startIndex: bigint,
|
|
218
351
|
logger: Logger
|
|
219
352
|
): Promise<Page<Validator>> => {
|
|
353
|
+
// An APY failure must not hide the validators: they are then reported without an APY.
|
|
354
|
+
const rewardRate = await withDeadline(
|
|
355
|
+
rewardRateCache(chainId, provider, iface, contractAddress),
|
|
356
|
+
REWARD_RATE_DEADLINE_MS
|
|
357
|
+
).catch((error) => {
|
|
358
|
+
logger('coin-evm/staking', 'fetchPage: Monad APY computation failed', {
|
|
359
|
+
error: error instanceof Error ? error.message : String(error),
|
|
360
|
+
})
|
|
361
|
+
return undefined
|
|
362
|
+
})
|
|
363
|
+
|
|
220
364
|
const data = iface.encodeFunctionData('getExecutionValidatorSet', [startIndex])
|
|
221
365
|
const raw = await provider.call({ to: contractAddress, data })
|
|
222
366
|
const decoded = iface.decodeFunctionResult('getExecutionValidatorSet', raw)
|
|
@@ -227,7 +371,15 @@ const fetchPage = async (
|
|
|
227
371
|
const items =
|
|
228
372
|
pageIds.length === 0
|
|
229
373
|
? []
|
|
230
|
-
: await fetchValidatorDetails(
|
|
374
|
+
: await fetchValidatorDetails(
|
|
375
|
+
chainId,
|
|
376
|
+
provider,
|
|
377
|
+
iface,
|
|
378
|
+
contractAddress,
|
|
379
|
+
pageIds,
|
|
380
|
+
rewardRate,
|
|
381
|
+
logger
|
|
382
|
+
)
|
|
231
383
|
|
|
232
384
|
const exhausted = isDone || pageIds.length === 0 || nextIndex <= startIndex
|
|
233
385
|
return { items, next: exhausted ? undefined : nextIndex.toString() }
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: © 2026 LEDGER SAS
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import type { DeepPartialReturn } from '@ledgerhq/coin-module-framework/test/utils'
|
|
5
|
+
import network from '@ledgerhq/live-network'
|
|
6
|
+
import { CHAIN_ID } from '../../config'
|
|
7
|
+
import {
|
|
8
|
+
createMockEvmConfigInfo,
|
|
9
|
+
mkExternalNode,
|
|
10
|
+
testLogger,
|
|
11
|
+
} from '../../fixtures/context.fixtures'
|
|
12
|
+
import seiValidatorApi from './sei'
|
|
13
|
+
|
|
14
|
+
jest.mock('@ledgerhq/live-network', () => ({ __esModule: true, default: jest.fn() }))
|
|
15
|
+
|
|
16
|
+
const mockedNetwork = jest.mocked<DeepPartialReturn<typeof network>>(network)
|
|
17
|
+
|
|
18
|
+
const mockConfig = createMockEvmConfigInfo({
|
|
19
|
+
chainId: CHAIN_ID.SEI_EVM,
|
|
20
|
+
node: mkExternalNode({ uri: 'https://sei-evm.coin.ledger.com' }),
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const validator = (address: string, commissionRate: string) => ({
|
|
24
|
+
operator_address: address,
|
|
25
|
+
description: { moniker: address },
|
|
26
|
+
commission: { commission_rates: { rate: commissionRate } },
|
|
27
|
+
tokens: '100',
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
type Responses = { minter?: unknown; pool?: unknown; validators?: unknown }
|
|
31
|
+
|
|
32
|
+
const mockRest = ({ minter, pool, validators }: Responses) => {
|
|
33
|
+
mockedNetwork.mockImplementation(async ({ url }) => {
|
|
34
|
+
if (url?.includes('/minter')) {
|
|
35
|
+
if (minter instanceof Error) throw minter
|
|
36
|
+
return { status: 200, data: minter }
|
|
37
|
+
}
|
|
38
|
+
if (url?.includes('/pool')) {
|
|
39
|
+
if (pool instanceof Error) throw pool
|
|
40
|
+
return { status: 200, data: pool }
|
|
41
|
+
}
|
|
42
|
+
return { status: 200, data: validators }
|
|
43
|
+
})
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const minter = (totalMintAmount: unknown) => ({ total_mint_amount: totalMintAmount })
|
|
47
|
+
const pool = (bondedTokens: unknown) => ({ pool: { bonded_tokens: bondedTokens } })
|
|
48
|
+
const validators = (...commissionRates: string[]) => ({
|
|
49
|
+
validators: commissionRates.map((rate, i) => validator(`seivaloper${i}`, rate)),
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
const fetchApys = async () => {
|
|
53
|
+
const { items } = await seiValidatorApi.fetchValidators(mockConfig, testLogger)
|
|
54
|
+
return items.map((item) => item.apy)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('seiValidatorApi.fetchValidators APY', () => {
|
|
58
|
+
beforeEach(() => {
|
|
59
|
+
jest.clearAllMocks()
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('shares the yearly mint amount between the bonded tokens, net of each commission', async () => {
|
|
63
|
+
mockRest({
|
|
64
|
+
minter: minter('1000'),
|
|
65
|
+
pool: pool('2000'),
|
|
66
|
+
validators: validators('0', '0.25', '1'),
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
expect(await fetchApys()).toEqual([0.5, 0.375, 0])
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it.each([
|
|
73
|
+
['the minter request fails', { minter: new Error('boom'), pool: pool('2000') }],
|
|
74
|
+
['the pool request fails', { minter: minter('1000'), pool: new Error('boom') }],
|
|
75
|
+
['the minted amount is not an integer string', { minter: minter(1000), pool: pool('2000') }],
|
|
76
|
+
['the minted amount is missing', { minter: {}, pool: pool('2000') }],
|
|
77
|
+
['the bonded tokens are not an integer string', { minter: minter('1000'), pool: pool('x') }],
|
|
78
|
+
['no token is bonded', { minter: minter('1000'), pool: pool('0') }],
|
|
79
|
+
])('keeps the validators without APY when %s', async (_name, responses) => {
|
|
80
|
+
mockRest({ ...responses, validators: validators('0') })
|
|
81
|
+
|
|
82
|
+
const { items } = await seiValidatorApi.fetchValidators(mockConfig, testLogger)
|
|
83
|
+
|
|
84
|
+
expect(items).toHaveLength(1)
|
|
85
|
+
expect(items[0].apy).toBeUndefined()
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('leaves the APY of a validator without a valid commission undefined', async () => {
|
|
89
|
+
mockRest({ minter: minter('1000'), pool: pool('2000'), validators: validators('abc', '0') })
|
|
90
|
+
|
|
91
|
+
expect(await fetchApys()).toEqual([undefined, 0.5])
|
|
92
|
+
})
|
|
93
|
+
})
|