@chorus-one/polygon 1.0.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 (43) hide show
  1. package/.mocharc.json +6 -0
  2. package/LICENSE +13 -0
  3. package/README.md +233 -0
  4. package/dist/cjs/constants.d.ts +187 -0
  5. package/dist/cjs/constants.js +141 -0
  6. package/dist/cjs/index.d.ts +4 -0
  7. package/dist/cjs/index.js +12 -0
  8. package/dist/cjs/package.json +3 -0
  9. package/dist/cjs/referrer.d.ts +2 -0
  10. package/dist/cjs/referrer.js +15 -0
  11. package/dist/cjs/staker.d.ts +335 -0
  12. package/dist/cjs/staker.js +716 -0
  13. package/dist/cjs/types.d.ts +40 -0
  14. package/dist/cjs/types.js +2 -0
  15. package/dist/mjs/constants.d.ts +187 -0
  16. package/dist/mjs/constants.js +138 -0
  17. package/dist/mjs/index.d.ts +4 -0
  18. package/dist/mjs/index.js +2 -0
  19. package/dist/mjs/package.json +3 -0
  20. package/dist/mjs/referrer.d.ts +2 -0
  21. package/dist/mjs/referrer.js +11 -0
  22. package/dist/mjs/staker.d.ts +335 -0
  23. package/dist/mjs/staker.js +712 -0
  24. package/dist/mjs/types.d.ts +40 -0
  25. package/dist/mjs/types.js +1 -0
  26. package/hardhat.config.ts +27 -0
  27. package/package.json +50 -0
  28. package/src/constants.ts +151 -0
  29. package/src/index.ts +14 -0
  30. package/src/referrer.ts +15 -0
  31. package/src/staker.ts +878 -0
  32. package/src/types.ts +45 -0
  33. package/test/fixtures/expected-data.ts +17 -0
  34. package/test/integration/localSigner.spec.ts +128 -0
  35. package/test/integration/setup.ts +41 -0
  36. package/test/integration/staker.spec.ts +587 -0
  37. package/test/integration/testStaker.ts +130 -0
  38. package/test/integration/utils.ts +263 -0
  39. package/test/lib/networks.json +14 -0
  40. package/test/staker.spec.ts +154 -0
  41. package/tsconfig.cjs.json +9 -0
  42. package/tsconfig.json +13 -0
  43. package/tsconfig.mjs.json +9 -0
@@ -0,0 +1,716 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PolygonStaker = void 0;
4
+ const viem_1 = require("viem");
5
+ const chains_1 = require("viem/chains");
6
+ const secp256k1_js_1 = require("@noble/curves/secp256k1.js");
7
+ const referrer_1 = require("./referrer");
8
+ const constants_1 = require("./constants");
9
+ /**
10
+ * PolygonStaker - TypeScript SDK for Polygon PoS staking operations
11
+ *
12
+ * This class provides the functionality to stake (delegate), unstake, withdraw,
13
+ * claim rewards, and compound rewards on Polygon PoS via ValidatorShare contracts
14
+ * deployed on Ethereum L1.
15
+ *
16
+ * Built with viem for type-safety and modern patterns.
17
+ *
18
+ * ---
19
+ *
20
+ * **Referrer Tracking**
21
+ *
22
+ * Transaction builders that support referrer tracking (stake, unstake, claim rewards, compound)
23
+ * append a tracking marker to the transaction calldata. The marker format is `c1c1` followed by
24
+ * the first 3 bytes of the keccak256 hash of the referrer string. By default, `sdk-chorusone-staking`
25
+ * is used as the referrer.
26
+ *
27
+ * To extract the referrer from on-chain transactions, look for the `c1c1` prefix in the trailing
28
+ * bytes after the function calldata.
29
+ */
30
+ const NETWORK_CHAINS = {
31
+ mainnet: chains_1.mainnet,
32
+ testnet: chains_1.sepolia
33
+ };
34
+ class PolygonStaker {
35
+ rpcUrl;
36
+ contracts;
37
+ publicClient;
38
+ chain;
39
+ withdrawalDelayCache = null;
40
+ validatorPrecisionCache = new Map();
41
+ /**
42
+ * This **static** method is used to derive an address from a public key.
43
+ *
44
+ * It can be used for signer initialization, e.g. `FireblocksSigner` or `LocalSigner`.
45
+ *
46
+ * @returns Returns an array containing the derived address.
47
+ */
48
+ static getAddressDerivationFn = () => async (publicKey) => {
49
+ const pkUncompressed = secp256k1_js_1.secp256k1.Point.fromBytes(publicKey).toBytes(false);
50
+ const hash = (0, viem_1.keccak256)(pkUncompressed.subarray(1));
51
+ const ethAddress = hash.slice(-40);
52
+ return [ethAddress];
53
+ };
54
+ /**
55
+ * Creates a PolygonStaker instance
56
+ *
57
+ * @param params - Initialization configuration
58
+ * @param params.network - Network to use: 'mainnet' (Ethereum L1) or 'testnet' (Sepolia L1)
59
+ * @param params.rpcUrl - Optional RPC endpoint URL override. If not provided, uses viem's default for the network.
60
+ *
61
+ * @returns An instance of PolygonStaker
62
+ */
63
+ constructor(params) {
64
+ this.rpcUrl = params.rpcUrl;
65
+ this.contracts = constants_1.NETWORK_CONTRACTS[params.network];
66
+ this.chain = NETWORK_CHAINS[params.network];
67
+ this.publicClient = (0, viem_1.createPublicClient)({
68
+ chain: this.chain,
69
+ transport: (0, viem_1.http)(this.rpcUrl)
70
+ });
71
+ }
72
+ /** @deprecated No longer required. Kept for backward compatibility. */
73
+ async init() { }
74
+ /**
75
+ * Builds a token approval transaction
76
+ *
77
+ * Approves the StakeManager contract to spend POL tokens on behalf of the delegator.
78
+ * This must be called before staking if the current allowance is insufficient.
79
+ *
80
+ * @param params - Parameters for building the transaction
81
+ * @param params.amount - The amount to approve in POL (will be converted to wei internally). Pass "max" for unlimited approval.
82
+ *
83
+ * @returns Returns a promise that resolves to an approval transaction
84
+ */
85
+ async buildApproveTx(params) {
86
+ const { amount } = params;
87
+ const amountWei = amount === 'max' ? viem_1.maxUint256 : this.parseAmount(amount);
88
+ const data = (0, viem_1.encodeFunctionData)({
89
+ abi: viem_1.erc20Abi,
90
+ functionName: 'approve',
91
+ args: [this.contracts.stakeManagerAddress, amountWei]
92
+ });
93
+ return {
94
+ tx: {
95
+ to: this.contracts.stakingTokenAddress,
96
+ data,
97
+ value: 0n
98
+ }
99
+ };
100
+ }
101
+ /**
102
+ * Builds a staking (delegation) transaction
103
+ *
104
+ * Delegates POL tokens to a validator via their ValidatorShare contract.
105
+ * Requires prior token approval to the StakeManager contract.
106
+ *
107
+ * @param params - Parameters for building the transaction
108
+ * @param params.delegatorAddress - The delegator's Ethereum address
109
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
110
+ * @param params.amount - The amount to stake in POL
111
+ * @param params.slippageBps - (Optional) Slippage tolerance in basis points (e.g., 50 = 0.5%). Used to calculate minSharesToMint.
112
+ * @param params.minSharesToMint - (Optional) Minimum validator shares to receive. Use this OR slippageBps, not both.
113
+ * @param params.referrer - (Optional) Custom referrer string for tracking. If not provided, uses 'sdk-chorusone-staking'.
114
+ *
115
+ * @returns Returns a promise that resolves to a Polygon staking transaction
116
+ */
117
+ async buildStakeTx(params) {
118
+ const { delegatorAddress, validatorShareAddress, amount, slippageBps, referrer } = params;
119
+ let { minSharesToMint } = params;
120
+ if (!(0, viem_1.isAddress)(delegatorAddress)) {
121
+ throw new Error(`Invalid delegator address: ${delegatorAddress}`);
122
+ }
123
+ if (!(0, viem_1.isAddress)(validatorShareAddress)) {
124
+ throw new Error(`Invalid validator share address: ${validatorShareAddress}`);
125
+ }
126
+ if (slippageBps !== undefined && minSharesToMint !== undefined) {
127
+ throw new Error('Cannot specify both slippageBps and minSharesToMint. Use one or the other.');
128
+ }
129
+ const amountWei = this.parseAmount(amount);
130
+ const allowance = await this.getAllowance(delegatorAddress);
131
+ if ((0, viem_1.parseEther)(allowance) < amountWei) {
132
+ throw new Error(`Insufficient POL allowance. Current: ${allowance}, Required: ${amount}. Call buildApproveTx() first.`);
133
+ }
134
+ if (slippageBps !== undefined) {
135
+ const [exchangeRate, precision] = await Promise.all([
136
+ this.getExchangeRate(validatorShareAddress),
137
+ this.getExchangeRatePrecision(validatorShareAddress)
138
+ ]);
139
+ const expectedShares = (amountWei * precision) / exchangeRate;
140
+ minSharesToMint = expectedShares - (expectedShares * BigInt(slippageBps)) / 10000n;
141
+ }
142
+ if (minSharesToMint === undefined) {
143
+ throw new Error('Either slippageBps or minSharesToMint must be provided');
144
+ }
145
+ const calldata = (0, viem_1.encodeFunctionData)({
146
+ abi: constants_1.VALIDATOR_SHARE_ABI,
147
+ functionName: 'buyVoucherPOL',
148
+ args: [amountWei, minSharesToMint]
149
+ });
150
+ return {
151
+ tx: {
152
+ to: validatorShareAddress,
153
+ data: (0, referrer_1.appendReferrerTracking)(calldata, referrer),
154
+ value: 0n
155
+ }
156
+ };
157
+ }
158
+ /**
159
+ * Builds an unstaking transaction
160
+ *
161
+ * Creates an unbond request to unstake POL tokens from a validator.
162
+ * After the unbonding period (~80 checkpoints, approximately 3-4 days), call buildWithdrawTx() to claim funds.
163
+ *
164
+ * @param params - Parameters for building the transaction
165
+ * @param params.delegatorAddress - The delegator's address
166
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
167
+ * @param params.amount - The amount to unstake in POL (will be converted to wei internally)
168
+ * @param params.slippageBps - (Optional) Slippage tolerance in basis points (e.g., 50 = 0.5%). Used to calculate maximumSharesToBurn.
169
+ * @param params.maximumSharesToBurn - (Optional) Maximum validator shares willing to burn. Use this OR slippageBps, not both.
170
+ * @param params.referrer - (Optional) Custom referrer string for tracking. If not provided, uses 'sdk-chorusone-staking'.
171
+ *
172
+ * @returns Returns a promise that resolves to a Polygon unstaking transaction
173
+ */
174
+ async buildUnstakeTx(params) {
175
+ const { delegatorAddress, validatorShareAddress, amount, slippageBps, referrer } = params;
176
+ let { maximumSharesToBurn } = params;
177
+ if (!(0, viem_1.isAddress)(delegatorAddress)) {
178
+ throw new Error(`Invalid delegator address: ${delegatorAddress}`);
179
+ }
180
+ if (!(0, viem_1.isAddress)(validatorShareAddress)) {
181
+ throw new Error(`Invalid validator share address: ${validatorShareAddress}`);
182
+ }
183
+ if (slippageBps !== undefined && maximumSharesToBurn !== undefined) {
184
+ throw new Error('Cannot specify both slippageBps and maximumSharesToBurn. Use one or the other.');
185
+ }
186
+ const amountWei = this.parseAmount(amount);
187
+ const stake = await this.getStake({ delegatorAddress, validatorShareAddress });
188
+ if ((0, viem_1.parseEther)(stake.balance) < amountWei) {
189
+ throw new Error(`Insufficient stake. Current: ${stake.balance} POL, Requested: ${amount} POL`);
190
+ }
191
+ if (slippageBps !== undefined) {
192
+ const precision = await this.getExchangeRatePrecision(validatorShareAddress);
193
+ const expectedShares = (amountWei * precision) / stake.exchangeRate;
194
+ maximumSharesToBurn = expectedShares + (expectedShares * BigInt(slippageBps)) / 10000n;
195
+ }
196
+ if (maximumSharesToBurn === undefined) {
197
+ throw new Error('Either slippageBps or maximumSharesToBurn must be provided');
198
+ }
199
+ const calldata = (0, viem_1.encodeFunctionData)({
200
+ abi: constants_1.VALIDATOR_SHARE_ABI,
201
+ functionName: 'sellVoucher_newPOL',
202
+ args: [amountWei, maximumSharesToBurn]
203
+ });
204
+ return {
205
+ tx: {
206
+ to: validatorShareAddress,
207
+ data: (0, referrer_1.appendReferrerTracking)(calldata, referrer),
208
+ value: 0n
209
+ }
210
+ };
211
+ }
212
+ /**
213
+ * Builds a withdraw transaction
214
+ *
215
+ * Claims unstaked POL tokens after the unbonding period has elapsed.
216
+ * Use getUnbond() to check if the unbonding period is complete.
217
+ *
218
+ * Note: Each unstake creates a separate unbond with its own nonce (1, 2, 3, etc.).
219
+ * Withdrawals must be done per-nonce. To withdraw all pending unbonds, iterate
220
+ * through nonces from 1 to getUnbondNonce() and withdraw each eligible one.
221
+ *
222
+ * @param params - Parameters for building the transaction
223
+ * @param params.delegatorAddress - The delegator's address that will receive the funds
224
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
225
+ * @param params.unbondNonce - The specific unbond nonce to withdraw
226
+ *
227
+ * @returns Returns a promise that resolves to a Polygon withdrawal transaction
228
+ */
229
+ async buildWithdrawTx(params) {
230
+ const { delegatorAddress, validatorShareAddress, unbondNonce } = params;
231
+ if (!(0, viem_1.isAddress)(delegatorAddress)) {
232
+ throw new Error(`Invalid delegator address: ${delegatorAddress}`);
233
+ }
234
+ if (!(0, viem_1.isAddress)(validatorShareAddress)) {
235
+ throw new Error(`Invalid validator share address: ${validatorShareAddress}`);
236
+ }
237
+ const unbond = await this.getUnbond({ delegatorAddress, validatorShareAddress, unbondNonce });
238
+ if (unbond.shares === 0n) {
239
+ throw new Error(`No unbond request found for nonce ${unbondNonce}`);
240
+ }
241
+ const [currentEpoch, withdrawalDelay] = await Promise.all([this.getEpoch(), this.getWithdrawalDelay()]);
242
+ const requiredEpoch = unbond.withdrawEpoch + withdrawalDelay;
243
+ if (currentEpoch < requiredEpoch) {
244
+ throw new Error(`Unbonding not complete. Current epoch: ${currentEpoch}, Required epoch: ${requiredEpoch}`);
245
+ }
246
+ const data = (0, viem_1.encodeFunctionData)({
247
+ abi: constants_1.VALIDATOR_SHARE_ABI,
248
+ functionName: 'unstakeClaimTokens_newPOL',
249
+ args: [unbondNonce]
250
+ });
251
+ return {
252
+ tx: {
253
+ to: validatorShareAddress,
254
+ data,
255
+ value: 0n
256
+ }
257
+ };
258
+ }
259
+ /**
260
+ * Builds a claim rewards transaction
261
+ *
262
+ * Claims accumulated delegation rewards and sends them to the delegator's wallet.
263
+ *
264
+ * @param params - Parameters for building the transaction
265
+ * @param params.delegatorAddress - The delegator's address that will receive the rewards
266
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
267
+ * @param params.referrer - (Optional) Custom referrer string for tracking. If not provided, uses 'sdk-chorusone-staking'.
268
+ *
269
+ * @returns Returns a promise that resolves to a Polygon claim rewards transaction
270
+ */
271
+ async buildClaimRewardsTx(params) {
272
+ const { delegatorAddress, validatorShareAddress, referrer } = params;
273
+ if (!(0, viem_1.isAddress)(delegatorAddress)) {
274
+ throw new Error(`Invalid delegator address: ${delegatorAddress}`);
275
+ }
276
+ if (!(0, viem_1.isAddress)(validatorShareAddress)) {
277
+ throw new Error(`Invalid validator share address: ${validatorShareAddress}`);
278
+ }
279
+ const rewards = await this.getLiquidRewards({ delegatorAddress, validatorShareAddress });
280
+ if ((0, viem_1.parseEther)(rewards) === 0n) {
281
+ throw new Error('No rewards available to claim');
282
+ }
283
+ const calldata = (0, viem_1.encodeFunctionData)({
284
+ abi: constants_1.VALIDATOR_SHARE_ABI,
285
+ functionName: 'withdrawRewardsPOL'
286
+ });
287
+ return {
288
+ tx: {
289
+ to: validatorShareAddress,
290
+ data: (0, referrer_1.appendReferrerTracking)(calldata, referrer),
291
+ value: 0n
292
+ }
293
+ };
294
+ }
295
+ /**
296
+ * Builds a compound (restake) rewards transaction
297
+ *
298
+ * Restakes accumulated rewards back into the validator, increasing delegation without new tokens.
299
+ *
300
+ * @param params - Parameters for building the transaction
301
+ * @param params.delegatorAddress - The delegator's address
302
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
303
+ * @param params.referrer - (Optional) Custom referrer string for tracking. If not provided, uses 'sdk-chorusone-staking'.
304
+ *
305
+ * @returns Returns a promise that resolves to a Polygon compound transaction
306
+ */
307
+ async buildCompoundTx(params) {
308
+ const { delegatorAddress, validatorShareAddress, referrer } = params;
309
+ if (!(0, viem_1.isAddress)(delegatorAddress)) {
310
+ throw new Error(`Invalid delegator address: ${delegatorAddress}`);
311
+ }
312
+ if (!(0, viem_1.isAddress)(validatorShareAddress)) {
313
+ throw new Error(`Invalid validator share address: ${validatorShareAddress}`);
314
+ }
315
+ const rewards = await this.getLiquidRewards({ delegatorAddress, validatorShareAddress });
316
+ if ((0, viem_1.parseEther)(rewards) === 0n) {
317
+ throw new Error('No rewards available to compound');
318
+ }
319
+ const calldata = (0, viem_1.encodeFunctionData)({
320
+ abi: constants_1.VALIDATOR_SHARE_ABI,
321
+ functionName: 'restakePOL'
322
+ });
323
+ return {
324
+ tx: {
325
+ to: validatorShareAddress,
326
+ data: (0, referrer_1.appendReferrerTracking)(calldata, referrer),
327
+ value: 0n
328
+ }
329
+ };
330
+ }
331
+ // ========== QUERY METHODS ==========
332
+ /**
333
+ * Retrieves the delegator's staking information for a specific validator
334
+ *
335
+ * @param params - Parameters for the query
336
+ * @param params.delegatorAddress - Ethereum address of the delegator
337
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
338
+ *
339
+ * @returns Promise resolving to stake information:
340
+ * - balance: Total staked amount formatted in POL
341
+ * - shares: Total shares held by the delegator
342
+ * - exchangeRate: Current exchange rate between shares and POL
343
+ */
344
+ async getStake(params) {
345
+ const { delegatorAddress, validatorShareAddress } = params;
346
+ const [balance, exchangeRate] = await this.publicClient.readContract({
347
+ address: validatorShareAddress,
348
+ abi: constants_1.VALIDATOR_SHARE_ABI,
349
+ functionName: 'getTotalStake',
350
+ args: [delegatorAddress]
351
+ });
352
+ const shares = await this.publicClient.readContract({
353
+ address: validatorShareAddress,
354
+ abi: viem_1.erc20Abi,
355
+ functionName: 'balanceOf',
356
+ args: [delegatorAddress]
357
+ });
358
+ return { balance: (0, viem_1.formatEther)(balance), shares, exchangeRate };
359
+ }
360
+ /**
361
+ * Retrieves the latest unbond nonce for a delegator
362
+ *
363
+ * Each unstake operation creates a new unbond request with an incrementing nonce.
364
+ * Nonces start at 1 and increment with each unstake.
365
+ * Note: a nonce having existed does not mean it is still pending —
366
+ * claimed unbonds are deleted, but the counter is never decremented.
367
+ *
368
+ * @param params - Parameters for the query
369
+ * @param params.delegatorAddress - Ethereum address of the delegator
370
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
371
+ *
372
+ * @returns Promise resolving to the latest unbond nonce (0n if no unstakes performed)
373
+ */
374
+ async getUnbondNonce(params) {
375
+ return this.publicClient.readContract({
376
+ address: params.validatorShareAddress,
377
+ abi: constants_1.VALIDATOR_SHARE_ABI,
378
+ functionName: 'unbondNonces',
379
+ args: [params.delegatorAddress]
380
+ });
381
+ }
382
+ /**
383
+ * Retrieves unbond request information for a specific nonce
384
+ *
385
+ * Use this to check the status of individual unbond requests.
386
+ * For fetching multiple unbonds efficiently, use getUnbonds() instead.
387
+ *
388
+ * @param params - Parameters for the query
389
+ * @param params.delegatorAddress - Ethereum address of the delegator
390
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
391
+ * @param params.unbondNonce - The specific unbond nonce to query (1, 2, 3, etc.)
392
+ *
393
+ * @returns Promise resolving to unbond information:
394
+ * - amount: Amount pending unbonding in POL
395
+ * - isWithdrawable: Whether the unbond can be withdrawn now
396
+ * - shares: Shares amount pending unbonding (0n if already withdrawn or doesn't exist)
397
+ * - withdrawEpoch: Epoch number when the unbond started
398
+ */
399
+ async getUnbond(params) {
400
+ const { delegatorAddress, validatorShareAddress, unbondNonce } = params;
401
+ const [multicallResults, withdrawalDelay, precision] = await Promise.all([
402
+ this.publicClient.multicall({
403
+ contracts: [
404
+ {
405
+ address: validatorShareAddress,
406
+ abi: constants_1.VALIDATOR_SHARE_ABI,
407
+ functionName: 'unbonds_new',
408
+ args: [delegatorAddress, unbondNonce]
409
+ },
410
+ {
411
+ address: this.contracts.stakeManagerAddress,
412
+ abi: constants_1.STAKE_MANAGER_ABI,
413
+ functionName: 'epoch'
414
+ },
415
+ {
416
+ address: validatorShareAddress,
417
+ abi: constants_1.VALIDATOR_SHARE_ABI,
418
+ functionName: 'withdrawExchangeRate'
419
+ }
420
+ ]
421
+ }),
422
+ this.getWithdrawalDelay(),
423
+ this.getExchangeRatePrecision(validatorShareAddress)
424
+ ]);
425
+ const [unbondResult, epochResult, withdrawRateResult] = multicallResults;
426
+ if (unbondResult.status === 'failure' ||
427
+ epochResult.status === 'failure' ||
428
+ withdrawRateResult.status === 'failure') {
429
+ throw new Error('Failed to fetch unbond information');
430
+ }
431
+ const [shares, withdrawEpoch] = unbondResult.result;
432
+ const currentEpoch = epochResult.result;
433
+ const withdrawExchangeRate = withdrawRateResult.result;
434
+ const amountWei = (shares * withdrawExchangeRate) / precision;
435
+ const amount = (0, viem_1.formatEther)(amountWei);
436
+ const isWithdrawable = shares > 0n && currentEpoch >= withdrawEpoch + withdrawalDelay;
437
+ return { amount, isWithdrawable, shares, withdrawEpoch };
438
+ }
439
+ /**
440
+ * Retrieves unbond request information for multiple nonces efficiently
441
+ *
442
+ * This method batches all contract reads into a single RPC call, making it
443
+ * much more efficient than calling getUnbond() multiple times.
444
+ *
445
+ * @param params - Parameters for the query
446
+ * @param params.delegatorAddress - Ethereum address of the delegator
447
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
448
+ * @param params.unbondNonces - Array of unbond nonces to query (1, 2, 3, etc.)
449
+ *
450
+ * @returns Promise resolving to array of unbond information (same order as input nonces)
451
+ */
452
+ async getUnbonds(params) {
453
+ const { delegatorAddress, validatorShareAddress, unbondNonces } = params;
454
+ if (unbondNonces.length === 0) {
455
+ return [];
456
+ }
457
+ const unbondContracts = unbondNonces.map((nonce) => ({
458
+ address: validatorShareAddress,
459
+ abi: constants_1.VALIDATOR_SHARE_ABI,
460
+ functionName: 'unbonds_new',
461
+ args: [delegatorAddress, nonce]
462
+ }));
463
+ const [multicallResults, withdrawalDelay, precision] = await Promise.all([
464
+ this.publicClient.multicall({
465
+ contracts: [
466
+ ...unbondContracts,
467
+ {
468
+ address: this.contracts.stakeManagerAddress,
469
+ abi: constants_1.STAKE_MANAGER_ABI,
470
+ functionName: 'epoch'
471
+ },
472
+ {
473
+ address: validatorShareAddress,
474
+ abi: constants_1.VALIDATOR_SHARE_ABI,
475
+ functionName: 'withdrawExchangeRate'
476
+ }
477
+ ]
478
+ }),
479
+ this.getWithdrawalDelay(),
480
+ this.getExchangeRatePrecision(validatorShareAddress)
481
+ ]);
482
+ const epochResult = multicallResults[unbondNonces.length];
483
+ const withdrawRateResult = multicallResults[unbondNonces.length + 1];
484
+ if (epochResult.status === 'failure' || withdrawRateResult.status === 'failure') {
485
+ throw new Error('Failed to fetch epoch or exchange rate');
486
+ }
487
+ const currentEpoch = epochResult.result;
488
+ const withdrawExchangeRate = withdrawRateResult.result;
489
+ return unbondNonces.map((nonce, index) => {
490
+ const unbondResult = multicallResults[index];
491
+ if (unbondResult.status === 'failure') {
492
+ throw new Error(`Failed to fetch unbond for nonce ${nonce}`);
493
+ }
494
+ const [shares, withdrawEpoch] = unbondResult.result;
495
+ const amountWei = (shares * withdrawExchangeRate) / precision;
496
+ const amount = (0, viem_1.formatEther)(amountWei);
497
+ const isWithdrawable = shares > 0n && currentEpoch >= withdrawEpoch + withdrawalDelay;
498
+ return { amount, isWithdrawable, shares, withdrawEpoch };
499
+ });
500
+ }
501
+ /**
502
+ * Retrieves pending liquid rewards for a delegator
503
+ *
504
+ * @param params - Parameters for the query
505
+ * @param params.delegatorAddress - Ethereum address of the delegator
506
+ * @param params.validatorShareAddress - The validator's ValidatorShare contract address
507
+ *
508
+ * @returns Promise resolving to the pending rewards in POL
509
+ */
510
+ async getLiquidRewards(params) {
511
+ const rewards = await this.publicClient.readContract({
512
+ address: params.validatorShareAddress,
513
+ abi: constants_1.VALIDATOR_SHARE_ABI,
514
+ functionName: 'getLiquidRewards',
515
+ args: [params.delegatorAddress]
516
+ });
517
+ return (0, viem_1.formatEther)(rewards);
518
+ }
519
+ /**
520
+ * Retrieves the current POL allowance for the StakeManager contract
521
+ *
522
+ * @param ownerAddress - The token owner's address
523
+ *
524
+ * @returns Promise resolving to the current allowance in POL
525
+ */
526
+ async getAllowance(ownerAddress) {
527
+ const allowance = await this.publicClient.readContract({
528
+ address: this.contracts.stakingTokenAddress,
529
+ abi: viem_1.erc20Abi,
530
+ functionName: 'allowance',
531
+ args: [ownerAddress, this.contracts.stakeManagerAddress]
532
+ });
533
+ return (0, viem_1.formatEther)(allowance);
534
+ }
535
+ /**
536
+ * Retrieves the current checkpoint epoch from the StakeManager
537
+ *
538
+ * @returns Promise resolving to the current epoch number
539
+ */
540
+ async getEpoch() {
541
+ return this.publicClient.readContract({
542
+ address: this.contracts.stakeManagerAddress,
543
+ abi: constants_1.STAKE_MANAGER_ABI,
544
+ functionName: 'epoch'
545
+ });
546
+ }
547
+ /**
548
+ * Retrieves the withdrawal delay from the StakeManager
549
+ *
550
+ * The withdrawal delay is the number of epochs that must pass after an unbond
551
+ * request before the funds can be withdrawn (~80 checkpoints, approximately 3-4 days).
552
+ *
553
+ * @returns Promise resolving to the withdrawal delay in epochs
554
+ */
555
+ async getWithdrawalDelay() {
556
+ if (this.withdrawalDelayCache !== null) {
557
+ return this.withdrawalDelayCache;
558
+ }
559
+ const delay = await this.publicClient.readContract({
560
+ address: this.contracts.stakeManagerAddress,
561
+ abi: constants_1.STAKE_MANAGER_ABI,
562
+ functionName: 'withdrawalDelay'
563
+ });
564
+ this.withdrawalDelayCache = delay;
565
+ return delay;
566
+ }
567
+ /**
568
+ * Retrieves the exchange rate precision for a validator
569
+ *
570
+ * Foundation validators (ID < 8) use precision of 100, others use 10^29.
571
+ *
572
+ * @param validatorShareAddress - The validator's ValidatorShare contract address
573
+ *
574
+ * @returns Promise resolving to the precision constant
575
+ */
576
+ async getExchangeRatePrecision(validatorShareAddress) {
577
+ const cached = this.validatorPrecisionCache.get(validatorShareAddress);
578
+ if (cached !== undefined) {
579
+ return cached;
580
+ }
581
+ const validatorId = await this.publicClient.readContract({
582
+ address: validatorShareAddress,
583
+ abi: constants_1.VALIDATOR_SHARE_ABI,
584
+ functionName: 'validatorId'
585
+ });
586
+ const precision = validatorId < 8n ? constants_1.EXCHANGE_RATE_PRECISION : constants_1.EXCHANGE_RATE_HIGH_PRECISION;
587
+ this.validatorPrecisionCache.set(validatorShareAddress, precision);
588
+ return precision;
589
+ }
590
+ /**
591
+ * Retrieves the current exchange rate for a validator
592
+ *
593
+ * @param validatorShareAddress - The validator's ValidatorShare contract address
594
+ *
595
+ * @returns Promise resolving to the exchange rate
596
+ */
597
+ async getExchangeRate(validatorShareAddress) {
598
+ const [, exchangeRate] = await this.publicClient.readContract({
599
+ address: validatorShareAddress,
600
+ abi: constants_1.VALIDATOR_SHARE_ABI,
601
+ functionName: 'getTotalStake',
602
+ args: [validatorShareAddress]
603
+ });
604
+ return exchangeRate;
605
+ }
606
+ /**
607
+ * Signs a transaction using the provided signer.
608
+ *
609
+ * @param params - Parameters for the signing process
610
+ * @param params.signer - A signer instance
611
+ * @param params.signerAddress - The address of the signer
612
+ * @param params.tx - The transaction to sign
613
+ * @param params.baseFeeMultiplier - (Optional) The multiplier for fees, which is used to manage fee fluctuations, is applied to the base fee per gas from the latest block to determine the final `maxFeePerGas`. The default value is 1.2
614
+ * @param params.defaultPriorityFee - (Optional) This overrides the `maxPriorityFeePerGas` estimated by the RPC
615
+ *
616
+ * @returns A promise that resolves to an object containing the signed transaction
617
+ */
618
+ async sign(params) {
619
+ const { signer, signerAddress, tx, baseFeeMultiplier, defaultPriorityFee } = params;
620
+ const baseChain = this.chain;
621
+ const baseFees = baseChain.fees ?? {};
622
+ const fees = {
623
+ ...baseFees,
624
+ baseFeeMultiplier: baseFeeMultiplier ?? baseFees.baseFeeMultiplier,
625
+ defaultPriorityFee: defaultPriorityFee === undefined ? baseFees.maxPriorityFeePerGas : (0, viem_1.parseEther)(defaultPriorityFee)
626
+ };
627
+ const chain = {
628
+ ...baseChain,
629
+ fees
630
+ };
631
+ const client = (0, viem_1.createWalletClient)({
632
+ chain,
633
+ transport: (0, viem_1.http)(this.rpcUrl),
634
+ account: signerAddress
635
+ });
636
+ const request = await client.prepareTransactionRequest({
637
+ chain: undefined,
638
+ account: signerAddress,
639
+ to: tx.to,
640
+ value: tx.value,
641
+ data: tx.data,
642
+ type: 'eip1559'
643
+ });
644
+ const message = (0, viem_1.keccak256)((0, viem_1.serializeTransaction)(request)).slice(2);
645
+ const data = { tx };
646
+ const { sig } = await signer.sign(signerAddress.toLowerCase().slice(2), { message, data }, {});
647
+ const signature = {
648
+ r: `0x${sig.r}`,
649
+ s: `0x${sig.s}`,
650
+ v: sig.v ? 28n : 27n,
651
+ yParity: sig.v
652
+ };
653
+ const signedTx = (0, viem_1.serializeTransaction)(request, signature);
654
+ return { signedTx };
655
+ }
656
+ /**
657
+ * Broadcasts a signed transaction to the network.
658
+ *
659
+ * @param params - Parameters for the broadcast process
660
+ * @param params.signedTx - The signed transaction to broadcast
661
+ *
662
+ * @returns A promise that resolves to the transaction hash
663
+ */
664
+ async broadcast(params) {
665
+ const { signedTx } = params;
666
+ const hash = await this.publicClient.sendRawTransaction({ serializedTransaction: signedTx });
667
+ return { txHash: hash };
668
+ }
669
+ /**
670
+ * Retrieves the status of a transaction using the transaction hash.
671
+ *
672
+ * @param params - Parameters for the transaction status request
673
+ * @param params.txHash - The transaction hash to query
674
+ *
675
+ * @returns A promise that resolves to an object containing the transaction status
676
+ */
677
+ async getTxStatus(params) {
678
+ const { txHash } = params;
679
+ try {
680
+ const tx = await this.publicClient.getTransactionReceipt({
681
+ hash: txHash
682
+ });
683
+ if (tx.status === 'reverted') {
684
+ return { status: 'failure', receipt: tx };
685
+ }
686
+ return { status: 'success', receipt: tx };
687
+ }
688
+ catch (e) {
689
+ return {
690
+ status: 'unknown',
691
+ receipt: null
692
+ };
693
+ }
694
+ }
695
+ parseAmount(amount) {
696
+ if (typeof amount === 'bigint') {
697
+ throw new Error('Amount must be a string, denominated in POL. e.g. "1.5" - 1.5 POL. You can use `formatEther` to convert a `bigint` to a string');
698
+ }
699
+ if (typeof amount !== 'string') {
700
+ throw new Error('Amount must be a string, denominated in POL. e.g. "1.5" - 1.5 POL.');
701
+ }
702
+ if (amount === '')
703
+ throw new Error('Amount cannot be empty');
704
+ let result;
705
+ try {
706
+ result = (0, viem_1.parseEther)(amount);
707
+ }
708
+ catch (e) {
709
+ throw new Error('Amount must be a valid number denominated in POL. e.g. "1.5" - 1.5 POL');
710
+ }
711
+ if (result <= 0n)
712
+ throw new Error('Amount must be greater than 0');
713
+ return result;
714
+ }
715
+ }
716
+ exports.PolygonStaker = PolygonStaker;