@opendatalabs/vana-sdk 2.2.2 → 2.2.3-canary.07f70f7

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