@opendatalabs/vana-sdk 2.2.3 → 2.3.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 (37) hide show
  1. package/dist/controllers/staking.cjs +626 -0
  2. package/dist/controllers/staking.cjs.map +1 -0
  3. package/dist/controllers/staking.d.ts +457 -0
  4. package/dist/controllers/staking.js +602 -0
  5. package/dist/controllers/staking.js.map +1 -0
  6. package/dist/core.cjs +4 -0
  7. package/dist/core.cjs.map +1 -1
  8. package/dist/core.d.ts +3 -0
  9. package/dist/core.js +4 -0
  10. package/dist/core.js.map +1 -1
  11. package/dist/generated/abi/VanaPoolEntityImplementation.cjs +65 -0
  12. package/dist/generated/abi/VanaPoolEntityImplementation.cjs.map +1 -1
  13. package/dist/generated/abi/VanaPoolEntityImplementation.d.ts +51 -0
  14. package/dist/generated/abi/VanaPoolEntityImplementation.js +65 -0
  15. package/dist/generated/abi/VanaPoolEntityImplementation.js.map +1 -1
  16. package/dist/generated/abi/VanaPoolStakingImplementation.cjs +187 -19
  17. package/dist/generated/abi/VanaPoolStakingImplementation.cjs.map +1 -1
  18. package/dist/generated/abi/VanaPoolStakingImplementation.d.ts +144 -14
  19. package/dist/generated/abi/VanaPoolStakingImplementation.js +187 -19
  20. package/dist/generated/abi/VanaPoolStakingImplementation.js.map +1 -1
  21. package/dist/generated/abi/index.d.ts +195 -14
  22. package/dist/generated/event-types.cjs.map +1 -1
  23. package/dist/generated/event-types.d.ts +7 -0
  24. package/dist/generated/eventRegistry.cjs +42 -0
  25. package/dist/generated/eventRegistry.cjs.map +1 -1
  26. package/dist/generated/eventRegistry.js +42 -0
  27. package/dist/generated/eventRegistry.js.map +1 -1
  28. package/dist/index.browser.d.ts +2 -0
  29. package/dist/index.browser.js +2 -0
  30. package/dist/index.browser.js.map +1 -1
  31. package/dist/index.node.cjs +3 -0
  32. package/dist/index.node.cjs.map +1 -1
  33. package/dist/index.node.d.ts +2 -0
  34. package/dist/index.node.js +2 -0
  35. package/dist/index.node.js.map +1 -1
  36. package/dist/tests/staking.test.d.ts +1 -0
  37. package/package.json +1 -1
@@ -0,0 +1,602 @@
1
+ import { BaseController } from "./base";
2
+ import { getContract, parseEther } from "viem";
3
+ import { getContractAddress } from "../generated/addresses";
4
+ import { getAbi } from "../generated/abi";
5
+ import { BlockchainError } from "../errors";
6
+ class StakingController extends BaseController {
7
+ constructor(context) {
8
+ super(context);
9
+ }
10
+ /**
11
+ * Gets the chain ID from context.
12
+ */
13
+ getChainId() {
14
+ const chainId = this.context.walletClient?.chain?.id ?? this.context.publicClient.chain?.id;
15
+ if (!chainId) {
16
+ throw new Error("Chain ID not available");
17
+ }
18
+ return chainId;
19
+ }
20
+ /**
21
+ * Gets the VanaPoolEntity contract instance.
22
+ */
23
+ getEntityContract() {
24
+ const chainId = this.getChainId();
25
+ return getContract({
26
+ address: getContractAddress(chainId, "VanaPoolEntity"),
27
+ abi: getAbi("VanaPoolEntity"),
28
+ client: this.context.publicClient
29
+ });
30
+ }
31
+ /**
32
+ * Gets the VanaPoolStaking contract instance.
33
+ */
34
+ getStakingContract() {
35
+ const chainId = this.getChainId();
36
+ return getContract({
37
+ address: getContractAddress(chainId, "VanaPoolStaking"),
38
+ abi: getAbi("VanaPoolStaking"),
39
+ client: this.context.publicClient
40
+ });
41
+ }
42
+ /**
43
+ * Gets the total amount of VANA staked in the VanaPool protocol or a specific entity.
44
+ *
45
+ * @remarks
46
+ * When called without an entityId, this retrieves the sum of activeRewardPool
47
+ * across all active entities in the VanaPool protocol.
48
+ * When called with an entityId, this returns the activeRewardPool for that specific entity.
49
+ * The value is returned in wei (10^18 = 1 VANA).
50
+ *
51
+ * @param entityId - Optional entity ID to get staked amount for a specific entity
52
+ * @returns The total amount of VANA staked in wei
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * // Get total staked across all entities
57
+ * const totalStaked = await vana.staking.getTotalVanaStaked();
58
+ * console.log(`Total staked: ${Number(totalStaked) / 1e18} VANA`);
59
+ *
60
+ * // Get staked amount for a specific entity
61
+ * const entityStaked = await vana.staking.getTotalVanaStaked(1n);
62
+ * console.log(`Entity 1 staked: ${Number(entityStaked) / 1e18} VANA`);
63
+ * ```
64
+ */
65
+ async getTotalVanaStaked(entityId) {
66
+ const entityContract = this.getEntityContract();
67
+ if (entityId !== void 0) {
68
+ const entity = await entityContract.read.entities([entityId]);
69
+ return entity.activeRewardPool;
70
+ }
71
+ const activeEntityIds = await entityContract.read.activeEntitiesValues();
72
+ let totalStaked = 0n;
73
+ for (const id of activeEntityIds) {
74
+ const entity = await entityContract.read.entities([id]);
75
+ totalStaked += entity.activeRewardPool;
76
+ }
77
+ return totalStaked;
78
+ }
79
+ /**
80
+ * Gets information about a specific staking entity.
81
+ *
82
+ * @param entityId - The ID of the entity to query
83
+ * @returns The entity information including name, APY, shares, and reward pools
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * const entity = await vana.staking.getEntity(1n);
88
+ * console.log(`Entity: ${entity.name}`);
89
+ * console.log(`Total shares: ${entity.totalShares}`);
90
+ * console.log(`Max APY: ${Number(entity.maxAPY) / 100}%`);
91
+ * ```
92
+ */
93
+ async getEntity(entityId) {
94
+ const entityContract = this.getEntityContract();
95
+ const result = await entityContract.read.entities([entityId]);
96
+ return {
97
+ entityId: result.entityId,
98
+ ownerAddress: result.ownerAddress,
99
+ status: result.status,
100
+ name: result.name,
101
+ maxAPY: result.maxAPY,
102
+ lockedRewardPool: result.lockedRewardPool,
103
+ activeRewardPool: result.activeRewardPool,
104
+ totalShares: result.totalShares,
105
+ lastUpdateTimestamp: result.lastUpdateTimestamp,
106
+ totalDistributedRewards: result.totalDistributedRewards
107
+ };
108
+ }
109
+ /**
110
+ * Gets the total number of staking entities in the protocol.
111
+ *
112
+ * @returns The count of entities
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * const count = await vana.staking.getEntitiesCount();
117
+ * console.log(`Total entities: ${count}`);
118
+ * ```
119
+ */
120
+ async getEntitiesCount() {
121
+ const entityContract = this.getEntityContract();
122
+ return entityContract.read.entitiesCount();
123
+ }
124
+ /**
125
+ * Gets the IDs of all active staking entities.
126
+ *
127
+ * @returns Array of active entity IDs
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const activeIds = await vana.staking.getActiveEntities();
132
+ * console.log(`Active entities: ${activeIds.join(', ')}`);
133
+ * ```
134
+ */
135
+ async getActiveEntities() {
136
+ const entityContract = this.getEntityContract();
137
+ return entityContract.read.activeEntitiesValues();
138
+ }
139
+ /**
140
+ * Gets a staker's position in a specific entity.
141
+ *
142
+ * @param staker - The address of the staker
143
+ * @param entityId - The ID of the entity
144
+ * @returns The staker's position information
145
+ *
146
+ * @example
147
+ * ```typescript
148
+ * const position = await vana.staking.getStakerPosition(
149
+ * '0x742d35...',
150
+ * 1n
151
+ * );
152
+ * console.log(`Shares: ${position.shares}`);
153
+ * console.log(`Rewards: ${position.realizedRewards}`);
154
+ * ```
155
+ */
156
+ async getStakerPosition(staker, entityId) {
157
+ const stakingContract = this.getStakingContract();
158
+ const result = await stakingContract.read.stakerEntities([
159
+ staker,
160
+ entityId
161
+ ]);
162
+ return {
163
+ shares: result.shares,
164
+ costBasis: result.costBasis,
165
+ rewardEligibilityTimestamp: result.rewardEligibilityTimestamp,
166
+ realizedRewards: result.realizedRewards,
167
+ vestedRewards: result.vestedRewards
168
+ };
169
+ }
170
+ /**
171
+ * Gets the earned rewards for a staker in an entity.
172
+ *
173
+ * @param staker - The address of the staker
174
+ * @param entityId - The ID of the entity
175
+ * @returns The earned rewards amount in wei
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * const rewards = await vana.staking.getEarnedRewards(
180
+ * '0x742d35...',
181
+ * 1n
182
+ * );
183
+ * console.log(`Earned: ${Number(rewards) / 1e18} VANA`);
184
+ * ```
185
+ */
186
+ async getEarnedRewards(staker, entityId) {
187
+ const stakingContract = this.getStakingContract();
188
+ return stakingContract.read.getEarnedRewards([staker, entityId]);
189
+ }
190
+ /**
191
+ * Gets the minimum stake amount required to stake.
192
+ *
193
+ * @returns The minimum stake amount in wei
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * const minStake = await vana.staking.getMinStakeAmount();
198
+ * console.log(`Minimum stake: ${Number(minStake) / 1e18} VANA`);
199
+ * ```
200
+ */
201
+ async getMinStakeAmount() {
202
+ const stakingContract = this.getStakingContract();
203
+ return stakingContract.read.minStakeAmount();
204
+ }
205
+ /**
206
+ * Gets the count of active stakers in the protocol.
207
+ *
208
+ * @returns The number of active stakers
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * const count = await vana.staking.getActiveStakersCount();
213
+ * console.log(`Active stakers: ${count}`);
214
+ * ```
215
+ */
216
+ async getActiveStakersCount() {
217
+ const stakingContract = this.getStakingContract();
218
+ return stakingContract.read.activeStakersListCount();
219
+ }
220
+ /**
221
+ * Gets the bonding period for staking.
222
+ *
223
+ * @returns The bonding period in seconds
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * const bondingPeriod = await vana.staking.getBondingPeriod();
228
+ * console.log(`Bonding period: ${bondingPeriod / 86400n} days`);
229
+ * ```
230
+ */
231
+ async getBondingPeriod() {
232
+ const stakingContract = this.getStakingContract();
233
+ return stakingContract.read.bondingPeriod();
234
+ }
235
+ /**
236
+ * Gets the total distributed rewards for a specific entity from the contract.
237
+ *
238
+ * @remarks
239
+ * This reads the `totalDistributedRewards` field from the entity's on-chain state.
240
+ * This value represents the sum of all rewards that have been processed
241
+ * (moved from lockedRewardPool to activeRewardPool) minus any forfeited
242
+ * rewards that were returned.
243
+ *
244
+ * @param entityId - The ID of the entity to query
245
+ * @returns The total distributed rewards in wei
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * const totalRewards = await vana.staking.getTotalDistributedRewards(1n);
250
+ * const totalRewardsVana = Number(totalRewards) / 1e18;
251
+ * console.log(`Total distributed rewards: ${totalRewardsVana.toLocaleString()} VANA`);
252
+ * ```
253
+ */
254
+ async getTotalDistributedRewards(entityId) {
255
+ const entityContract = this.getEntityContract();
256
+ const result = await entityContract.read.entities([entityId]);
257
+ return result.totalDistributedRewards;
258
+ }
259
+ /**
260
+ * Gets a comprehensive staking summary for a staker in an entity.
261
+ *
262
+ * @remarks
263
+ * This method aggregates all relevant staking information for a staker in a single call,
264
+ * including staked amount, current value, bonding status, and all reward types.
265
+ *
266
+ * Reward breakdown:
267
+ * - `earnedRewards` = pendingInterest + vestedRewards + realizedRewards
268
+ * - `pendingInterest` = currentValue - costBasis (unvested appreciation)
269
+ * - `vestedRewards` = rewards that have vested but not yet withdrawn
270
+ * - `realizedRewards` = rewards already withdrawn during unstakes
271
+ *
272
+ * @param staker - The address of the staker
273
+ * @param entityId - The ID of the entity
274
+ * @returns A comprehensive summary of the staker's position
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * const summary = await vana.staking.getStakerSummary('0x742d35...', 1n);
279
+ * console.log(`Total staked: ${Number(summary.totalStaked) / 1e18} VANA`);
280
+ * console.log(`Current value: ${Number(summary.currentValue) / 1e18} VANA`);
281
+ * console.log(`In bonding period: ${summary.isInBondingPeriod}`);
282
+ * console.log(`Remaining bonding time: ${Number(summary.remainingBondingTime) / 86400} days`);
283
+ * console.log(`Vested rewards: ${Number(summary.vestedRewards) / 1e18} VANA`);
284
+ * console.log(`Unvested rewards: ${Number(summary.unvestedRewards) / 1e18} VANA`);
285
+ * console.log(`Realized rewards: ${Number(summary.realizedRewards) / 1e18} VANA`);
286
+ * console.log(`Total earned: ${Number(summary.earnedRewards) / 1e18} VANA`);
287
+ * ```
288
+ */
289
+ async getStakerSummary(staker, entityId) {
290
+ const chainId = this.getChainId();
291
+ const stakingAddress = getContractAddress(chainId, "VanaPoolStaking");
292
+ const entityAddress = getContractAddress(chainId, "VanaPoolEntity");
293
+ const stakingAbi = getAbi("VanaPoolStaking");
294
+ const entityAbi = getAbi("VanaPoolEntity");
295
+ const block = await this.context.publicClient.getBlock();
296
+ const blockNumber = block.number;
297
+ const multicallResults = await this.context.publicClient.multicall({
298
+ contracts: [
299
+ {
300
+ address: stakingAddress,
301
+ abi: stakingAbi,
302
+ functionName: "stakerEntities",
303
+ args: [staker, entityId]
304
+ },
305
+ {
306
+ address: stakingAddress,
307
+ abi: stakingAbi,
308
+ functionName: "getEarnedRewards",
309
+ args: [staker, entityId]
310
+ },
311
+ {
312
+ address: entityAddress,
313
+ abi: entityAbi,
314
+ functionName: "entityShareToVana",
315
+ args: [entityId]
316
+ }
317
+ ],
318
+ blockNumber
319
+ });
320
+ const [positionResult, earnedRewardsResult, shareToVanaResult] = multicallResults;
321
+ if (positionResult.status === "failure" || earnedRewardsResult.status === "failure" || shareToVanaResult.status === "failure") {
322
+ throw new BlockchainError(
323
+ "Failed to fetch staker summary: one or more contract calls failed"
324
+ );
325
+ }
326
+ const position = positionResult.result;
327
+ const earnedRewards = earnedRewardsResult.result;
328
+ const shareToVana = shareToVanaResult.result;
329
+ const currentTimestamp = block.timestamp;
330
+ const eligibilityTimestamp = position.rewardEligibilityTimestamp;
331
+ const remainingBondingTime = eligibilityTimestamp > currentTimestamp ? eligibilityTimestamp - currentTimestamp : 0n;
332
+ const isInBondingPeriod = remainingBondingTime > 0n;
333
+ const currentValue = position.shares * shareToVana / 10n ** 18n;
334
+ const unvestedRewards = currentValue > position.costBasis ? currentValue - position.costBasis : 0n;
335
+ return {
336
+ shares: position.shares,
337
+ costBasis: position.costBasis,
338
+ currentValue,
339
+ rewardEligibilityTimestamp: eligibilityTimestamp,
340
+ remainingBondingTime,
341
+ isInBondingPeriod,
342
+ vestedRewards: position.vestedRewards,
343
+ unvestedRewards,
344
+ realizedRewards: position.realizedRewards,
345
+ earnedRewards
346
+ };
347
+ }
348
+ /**
349
+ * Stakes VANA to an entity in the VanaPool protocol.
350
+ *
351
+ * @remarks
352
+ * This method stakes native VANA tokens to a specified entity. The staker will receive
353
+ * shares in proportion to their stake amount. A bonding period applies during which
354
+ * rewards cannot be fully claimed without penalty.
355
+ *
356
+ * Requires a wallet client to be configured in the Vana constructor.
357
+ *
358
+ * @param params - The staking parameters
359
+ * @param params.entityId - The ID of the entity to stake to
360
+ * @param params.amount - The amount of VANA to stake (in wei, or as a string like "1.5" for 1.5 VANA)
361
+ * @param params.recipient - Optional recipient address for the shares (defaults to the sender)
362
+ * @param params.minShares - Optional minimum shares to receive (slippage protection, defaults to 0)
363
+ * @returns The transaction hash
364
+ * @throws {BlockchainError} When wallet client is not configured
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * // Stake 100 VANA to entity 1
369
+ * const txHash = await vana.staking.stake({
370
+ * entityId: 1n,
371
+ * amount: "100", // 100 VANA
372
+ * });
373
+ * console.log(`Staked! Transaction: ${txHash}`);
374
+ *
375
+ * // Stake with slippage protection
376
+ * const txHash2 = await vana.staking.stake({
377
+ * entityId: 1n,
378
+ * amount: parseEther("50"), // 50 VANA in wei
379
+ * minShares: parseEther("49"), // Expect at least 49 shares
380
+ * });
381
+ * ```
382
+ */
383
+ async stake(params, options) {
384
+ this.assertWallet();
385
+ const chainId = this.getChainId();
386
+ const stakingAddress = getContractAddress(chainId, "VanaPoolStaking");
387
+ const stakingAbi = getAbi("VanaPoolStaking");
388
+ const amountWei = typeof params.amount === "string" ? parseEther(params.amount) : params.amount;
389
+ const account = this.context.walletClient.account ?? this.context.userAddress;
390
+ const accountAddress = typeof account === "string" ? account : account.address;
391
+ const recipient = params.recipient ?? accountAddress;
392
+ const minShares = params.minShares ?? 0n;
393
+ const txHash = await this.context.walletClient.writeContract({
394
+ address: stakingAddress,
395
+ abi: stakingAbi,
396
+ functionName: "stake",
397
+ args: [params.entityId, recipient, minShares],
398
+ value: amountWei,
399
+ account,
400
+ chain: this.context.walletClient.chain,
401
+ ...this.spreadTransactionOptions(options)
402
+ });
403
+ return txHash;
404
+ }
405
+ /**
406
+ * Gets the maximum amount of VANA that can be unstaked in a single transaction.
407
+ *
408
+ * @remarks
409
+ * This calls the contract's getMaxUnstakeAmount which returns the minimum of:
410
+ * 1. The withdrawable VANA (costBasis if in bonding period, shareValue if eligible)
411
+ * 2. The entity's activeRewardPool (what the entity has available)
412
+ * 3. The treasury balance (what can be paid out)
413
+ *
414
+ * The limiting factor indicates what's constraining the unstake:
415
+ * - 0 = user shares/costBasis
416
+ * - 1 = activeRewardPool
417
+ * - 2 = treasury
418
+ *
419
+ * @param staker - The address of the staker
420
+ * @param entityId - The ID of the entity
421
+ * @returns Object containing maxVana, maxShares, limitingFactor, and isInBondingPeriod
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * const result = await vana.staking.getMaxUnstakeAmount('0x742d35...', 1n);
426
+ * console.log(`Max unstake: ${Number(result.maxVana) / 1e18} VANA`);
427
+ * console.log(`Max shares: ${result.maxShares}`);
428
+ * console.log(`In bonding period: ${result.isInBondingPeriod}`);
429
+ * ```
430
+ */
431
+ async getMaxUnstakeAmount(staker, entityId) {
432
+ const stakingContract = this.getStakingContract();
433
+ const result = await stakingContract.read.getMaxUnstakeAmount([
434
+ staker,
435
+ entityId
436
+ ]);
437
+ return {
438
+ maxVana: result[0],
439
+ maxShares: result[1],
440
+ limitingFactor: Number(result[2]),
441
+ isInBondingPeriod: result[3]
442
+ };
443
+ }
444
+ /**
445
+ * Computes the new bonding period end timestamp after adding stake.
446
+ *
447
+ * @remarks
448
+ * When a staker adds more stake to an existing position, the reward eligibility timestamp
449
+ * is recalculated as a weighted average of the existing and new positions. This function
450
+ * allows you to preview what the new eligibility timestamp would be without executing
451
+ * the stake transaction.
452
+ *
453
+ * The formula used (matching the contract):
454
+ * ```
455
+ * newEligibility = (existingShares * existingEligibility + newShares * newEligibility) / totalShares
456
+ * ```
457
+ *
458
+ * Where `newEligibility` for the incoming stake is `currentTimestamp + bondingPeriod`.
459
+ *
460
+ * @param params - The parameters for computing the new bonding period
461
+ * @param params.staker - The address of the staker
462
+ * @param params.entityId - The ID of the entity
463
+ * @param params.stakeAmount - The amount of VANA to stake (in wei)
464
+ * @returns Object containing the new eligibility timestamp and related info
465
+ *
466
+ * @example
467
+ * ```typescript
468
+ * // Preview bonding period after staking 100 VANA
469
+ * const preview = await vana.staking.computeNewBondingPeriod({
470
+ * staker: '0x742d35...',
471
+ * entityId: 1n,
472
+ * stakeAmount: parseEther("100"),
473
+ * });
474
+ * console.log(`New eligibility: ${new Date(Number(preview.newEligibilityTimestamp) * 1000)}`);
475
+ * console.log(`Remaining bonding time: ${Number(preview.newRemainingBondingTime) / 86400} days`);
476
+ * ```
477
+ */
478
+ async computeNewBondingPeriod(params) {
479
+ const chainId = this.getChainId();
480
+ const stakingAddress = getContractAddress(chainId, "VanaPoolStaking");
481
+ const entityAddress = getContractAddress(chainId, "VanaPoolEntity");
482
+ const stakingAbi = getAbi("VanaPoolStaking");
483
+ const entityAbi = getAbi("VanaPoolEntity");
484
+ const block = await this.context.publicClient.getBlock();
485
+ const blockNumber = block.number;
486
+ const currentTimestamp = block.timestamp;
487
+ const multicallResults = await this.context.publicClient.multicall({
488
+ contracts: [
489
+ {
490
+ address: stakingAddress,
491
+ abi: stakingAbi,
492
+ functionName: "stakerEntities",
493
+ args: [params.staker, params.entityId]
494
+ },
495
+ {
496
+ address: stakingAddress,
497
+ abi: stakingAbi,
498
+ functionName: "bondingPeriod",
499
+ args: []
500
+ },
501
+ {
502
+ address: entityAddress,
503
+ abi: entityAbi,
504
+ functionName: "vanaToEntityShare",
505
+ args: [params.entityId]
506
+ }
507
+ ],
508
+ blockNumber
509
+ });
510
+ const [positionResult, bondingPeriodResult, vanaToShareResult] = multicallResults;
511
+ if (positionResult.status === "failure" || bondingPeriodResult.status === "failure" || vanaToShareResult.status === "failure") {
512
+ throw new BlockchainError(
513
+ "Failed to compute new bonding period: one or more contract calls failed"
514
+ );
515
+ }
516
+ const position = positionResult.result;
517
+ const bondingPeriodDuration = bondingPeriodResult.result;
518
+ const vanaToShare = vanaToShareResult.result;
519
+ const currentShares = position.shares;
520
+ const currentEligibilityTimestamp = position.rewardEligibilityTimestamp;
521
+ const currentRemainingBondingTime = currentEligibilityTimestamp > currentTimestamp ? currentEligibilityTimestamp - currentTimestamp : 0n;
522
+ const estimatedNewShares = params.stakeAmount * vanaToShare / 10n ** 18n;
523
+ const totalSharesAfter = currentShares + estimatedNewShares;
524
+ const newStakeEligibility = currentTimestamp + bondingPeriodDuration;
525
+ let newEligibilityTimestamp;
526
+ if (currentShares === 0n) {
527
+ newEligibilityTimestamp = newStakeEligibility;
528
+ } else {
529
+ newEligibilityTimestamp = (currentShares * currentEligibilityTimestamp + estimatedNewShares * newStakeEligibility) / totalSharesAfter;
530
+ }
531
+ const newRemainingBondingTime = newEligibilityTimestamp > currentTimestamp ? newEligibilityTimestamp - currentTimestamp : 0n;
532
+ return {
533
+ newEligibilityTimestamp,
534
+ newRemainingBondingTime,
535
+ currentEligibilityTimestamp,
536
+ currentRemainingBondingTime,
537
+ currentShares,
538
+ estimatedNewShares,
539
+ totalSharesAfter,
540
+ bondingPeriodDuration,
541
+ currentTimestamp
542
+ };
543
+ }
544
+ /**
545
+ * Unstakes VANA from an entity in the VanaPool protocol.
546
+ *
547
+ * @remarks
548
+ * This method unstakes native VANA tokens from a specified entity. The amount
549
+ * that can be unstaked depends on whether the staker is in the bonding period:
550
+ *
551
+ * - **During bonding period**: Only cost basis can be withdrawn; rewards are forfeited
552
+ * - **After bonding period**: Full current value (cost basis + rewards) can be withdrawn
553
+ *
554
+ * Use `getMaxUnstakeAmount` to determine the maximum amount that can be unstaked.
555
+ *
556
+ * Requires a wallet client to be configured in the Vana constructor.
557
+ *
558
+ * @param params - The unstaking parameters
559
+ * @param params.entityId - The ID of the entity to unstake from
560
+ * @param params.amount - The amount of VANA to unstake (in wei, or as a string like "1.5" for 1.5 VANA)
561
+ * @param params.maxShares - Maximum shares to burn for slippage protection (defaults to 0, no protection)
562
+ * @returns The transaction hash
563
+ * @throws {BlockchainError} When wallet client is not configured
564
+ *
565
+ * @example
566
+ * ```typescript
567
+ * // Get max unstake amount first
568
+ * const maxUnstake = await vana.staking.getMaxUnstakeAmount(address, 1n);
569
+ *
570
+ * // Unstake the maximum amount with slippage protection
571
+ * const txHash = await vana.staking.unstake({
572
+ * entityId: 1n,
573
+ * amount: maxUnstake.maxVana,
574
+ * maxShares: maxUnstake.maxShares,
575
+ * });
576
+ * console.log(`Unstaked! Transaction: ${txHash}`);
577
+ * ```
578
+ */
579
+ async unstake(params, options) {
580
+ this.assertWallet();
581
+ const chainId = this.getChainId();
582
+ const stakingAddress = getContractAddress(chainId, "VanaPoolStaking");
583
+ const stakingAbi = getAbi("VanaPoolStaking");
584
+ const amountWei = typeof params.amount === "string" ? parseEther(params.amount) : params.amount;
585
+ const maxShares = params.maxShares ?? 0n;
586
+ const account = this.context.walletClient.account ?? this.context.userAddress;
587
+ const txHash = await this.context.walletClient.writeContract({
588
+ address: stakingAddress,
589
+ abi: stakingAbi,
590
+ functionName: "unstakeVana",
591
+ args: [params.entityId, amountWei, maxShares],
592
+ account,
593
+ chain: this.context.walletClient.chain,
594
+ ...this.spreadTransactionOptions(options)
595
+ });
596
+ return txHash;
597
+ }
598
+ }
599
+ export {
600
+ StakingController
601
+ };
602
+ //# sourceMappingURL=staking.js.map