@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 @@
1
+ {"version":3,"sources":["../../src/controllers/staking.ts"],"sourcesContent":["/**\n * Provides staking functionality for the VanaPool protocol.\n *\n * @remarks\n * This controller handles interactions with VanaPool staking contracts,\n * allowing users to query staking information such as total VANA staked,\n * entity information, and staker positions.\n *\n * @category Controllers\n * @module StakingController\n */\n\nimport type { ControllerContext } from \"../types/controller-context\";\nimport type { TransactionOptions } from \"../types/operations\";\nimport { BaseController } from \"./base\";\nimport { getContract, parseEther } from \"viem\";\nimport type { Address, Hash } from \"viem\";\nimport { getContractAddress } from \"../generated/addresses\";\nimport { getAbi } from \"../generated/abi\";\nimport { BlockchainError } from \"../errors\";\n\n/**\n * Information about a staking entity in the VanaPool protocol.\n */\nexport interface EntityInfo {\n entityId: bigint;\n ownerAddress: Address;\n status: number;\n name: string;\n maxAPY: bigint;\n lockedRewardPool: bigint;\n activeRewardPool: bigint;\n totalShares: bigint;\n lastUpdateTimestamp: bigint;\n totalDistributedRewards: bigint;\n}\n\n/**\n * Information about a staker's position in an entity.\n */\nexport interface StakerEntityInfo {\n shares: bigint;\n costBasis: bigint;\n rewardEligibilityTimestamp: bigint;\n realizedRewards: bigint;\n vestedRewards: bigint;\n}\n\n/**\n * Comprehensive staking summary for a staker in an entity.\n */\nexport interface StakerEntitySummary {\n /** Number of shares owned by the staker */\n shares: bigint;\n /** Cost basis - the original VANA amount staked */\n costBasis: bigint;\n /** Current value of the staker's shares in VANA */\n currentValue: bigint;\n /** Timestamp when rewards become eligible */\n rewardEligibilityTimestamp: bigint;\n /** Remaining bonding time in seconds (0 if bonding period has passed) */\n remainingBondingTime: bigint;\n /** Whether the staker is still in the bonding period */\n isInBondingPeriod: boolean;\n /** Vested rewards that can be claimed without penalty */\n vestedRewards: bigint;\n /** Unvested rewards (pending interest = currentValue - costBasis) */\n unvestedRewards: bigint;\n /** Realized/withdrawn rewards (already claimed) */\n realizedRewards: bigint;\n /** Total earned rewards (includes vested, unvested, and realized) */\n earnedRewards: bigint;\n}\n\n/**\n * Controller for VanaPool staking operations.\n *\n * @remarks\n * Provides methods to query staking information from the VanaPool contracts.\n * This includes total VANA staked across the protocol, entity information,\n * and individual staker positions.\n *\n * @example\n * ```typescript\n * // Get total VANA staked in the protocol\n * const totalStaked = await vana.staking.getTotalVanaStaked();\n * console.log(`Total staked: ${totalStaked} wei`);\n *\n * // Get entity information\n * const entity = await vana.staking.getEntity(1n);\n * console.log(`Entity name: ${entity.name}`);\n * ```\n *\n * @category Controllers\n */\nexport class StakingController extends BaseController {\n constructor(context: ControllerContext) {\n super(context);\n }\n\n /**\n * Gets the chain ID from context.\n */\n private getChainId(): number {\n const chainId =\n this.context.walletClient?.chain?.id ??\n this.context.publicClient.chain?.id;\n if (!chainId) {\n throw new Error(\"Chain ID not available\");\n }\n return chainId;\n }\n\n /**\n * Gets the VanaPoolEntity contract instance.\n */\n private getEntityContract() {\n const chainId = this.getChainId();\n return getContract({\n address: getContractAddress(chainId, \"VanaPoolEntity\"),\n abi: getAbi(\"VanaPoolEntity\"),\n client: this.context.publicClient,\n });\n }\n\n /**\n * Gets the VanaPoolStaking contract instance.\n */\n private getStakingContract() {\n const chainId = this.getChainId();\n return getContract({\n address: getContractAddress(chainId, \"VanaPoolStaking\"),\n abi: getAbi(\"VanaPoolStaking\"),\n client: this.context.publicClient,\n });\n }\n\n /**\n * Gets the total amount of VANA staked in the VanaPool protocol or a specific entity.\n *\n * @remarks\n * When called without an entityId, this retrieves the sum of activeRewardPool\n * across all active entities in the VanaPool protocol.\n * When called with an entityId, this returns the activeRewardPool for that specific entity.\n * The value is returned in wei (10^18 = 1 VANA).\n *\n * @param entityId - Optional entity ID to get staked amount for a specific entity\n * @returns The total amount of VANA staked in wei\n *\n * @example\n * ```typescript\n * // Get total staked across all entities\n * const totalStaked = await vana.staking.getTotalVanaStaked();\n * console.log(`Total staked: ${Number(totalStaked) / 1e18} VANA`);\n *\n * // Get staked amount for a specific entity\n * const entityStaked = await vana.staking.getTotalVanaStaked(1n);\n * console.log(`Entity 1 staked: ${Number(entityStaked) / 1e18} VANA`);\n * ```\n */\n async getTotalVanaStaked(entityId?: bigint): Promise<bigint> {\n const entityContract = this.getEntityContract();\n\n // If entityId is provided, return the activeRewardPool for that specific entity\n if (entityId !== undefined) {\n const entity = await entityContract.read.entities([entityId]);\n return entity.activeRewardPool;\n }\n\n // Otherwise, sum up the activeRewardPool from all active entities\n const activeEntityIds = await entityContract.read.activeEntitiesValues();\n\n let totalStaked = 0n;\n for (const id of activeEntityIds) {\n const entity = await entityContract.read.entities([id]);\n totalStaked += entity.activeRewardPool;\n }\n\n return totalStaked;\n }\n\n /**\n * Gets information about a specific staking entity.\n *\n * @param entityId - The ID of the entity to query\n * @returns The entity information including name, APY, shares, and reward pools\n *\n * @example\n * ```typescript\n * const entity = await vana.staking.getEntity(1n);\n * console.log(`Entity: ${entity.name}`);\n * console.log(`Total shares: ${entity.totalShares}`);\n * console.log(`Max APY: ${Number(entity.maxAPY) / 100}%`);\n * ```\n */\n async getEntity(entityId: bigint): Promise<EntityInfo> {\n const entityContract = this.getEntityContract();\n\n const result = await entityContract.read.entities([entityId]);\n\n return {\n entityId: result.entityId,\n ownerAddress: result.ownerAddress as Address,\n status: result.status,\n name: result.name,\n maxAPY: result.maxAPY,\n lockedRewardPool: result.lockedRewardPool,\n activeRewardPool: result.activeRewardPool,\n totalShares: result.totalShares,\n lastUpdateTimestamp: result.lastUpdateTimestamp,\n totalDistributedRewards: result.totalDistributedRewards,\n };\n }\n\n /**\n * Gets the total number of staking entities in the protocol.\n *\n * @returns The count of entities\n *\n * @example\n * ```typescript\n * const count = await vana.staking.getEntitiesCount();\n * console.log(`Total entities: ${count}`);\n * ```\n */\n async getEntitiesCount(): Promise<bigint> {\n const entityContract = this.getEntityContract();\n return entityContract.read.entitiesCount();\n }\n\n /**\n * Gets the IDs of all active staking entities.\n *\n * @returns Array of active entity IDs\n *\n * @example\n * ```typescript\n * const activeIds = await vana.staking.getActiveEntities();\n * console.log(`Active entities: ${activeIds.join(', ')}`);\n * ```\n */\n async getActiveEntities(): Promise<readonly bigint[]> {\n const entityContract = this.getEntityContract();\n return entityContract.read.activeEntitiesValues();\n }\n\n /**\n * Gets a staker's position in a specific entity.\n *\n * @param staker - The address of the staker\n * @param entityId - The ID of the entity\n * @returns The staker's position information\n *\n * @example\n * ```typescript\n * const position = await vana.staking.getStakerPosition(\n * '0x742d35...',\n * 1n\n * );\n * console.log(`Shares: ${position.shares}`);\n * console.log(`Rewards: ${position.realizedRewards}`);\n * ```\n */\n async getStakerPosition(\n staker: Address,\n entityId: bigint,\n ): Promise<StakerEntityInfo> {\n const stakingContract = this.getStakingContract();\n\n const result = await stakingContract.read.stakerEntities([\n staker,\n entityId,\n ]);\n\n return {\n shares: result.shares,\n costBasis: result.costBasis,\n rewardEligibilityTimestamp: result.rewardEligibilityTimestamp,\n realizedRewards: result.realizedRewards,\n vestedRewards: result.vestedRewards,\n };\n }\n\n /**\n * Gets the earned rewards for a staker in an entity.\n *\n * @param staker - The address of the staker\n * @param entityId - The ID of the entity\n * @returns The earned rewards amount in wei\n *\n * @example\n * ```typescript\n * const rewards = await vana.staking.getEarnedRewards(\n * '0x742d35...',\n * 1n\n * );\n * console.log(`Earned: ${Number(rewards) / 1e18} VANA`);\n * ```\n */\n async getEarnedRewards(staker: Address, entityId: bigint): Promise<bigint> {\n const stakingContract = this.getStakingContract();\n return stakingContract.read.getEarnedRewards([staker, entityId]);\n }\n\n /**\n * Gets the minimum stake amount required to stake.\n *\n * @returns The minimum stake amount in wei\n *\n * @example\n * ```typescript\n * const minStake = await vana.staking.getMinStakeAmount();\n * console.log(`Minimum stake: ${Number(minStake) / 1e18} VANA`);\n * ```\n */\n async getMinStakeAmount(): Promise<bigint> {\n const stakingContract = this.getStakingContract();\n return stakingContract.read.minStakeAmount();\n }\n\n /**\n * Gets the count of active stakers in the protocol.\n *\n * @returns The number of active stakers\n *\n * @example\n * ```typescript\n * const count = await vana.staking.getActiveStakersCount();\n * console.log(`Active stakers: ${count}`);\n * ```\n */\n async getActiveStakersCount(): Promise<bigint> {\n const stakingContract = this.getStakingContract();\n return stakingContract.read.activeStakersListCount();\n }\n\n /**\n * Gets the bonding period for staking.\n *\n * @returns The bonding period in seconds\n *\n * @example\n * ```typescript\n * const bondingPeriod = await vana.staking.getBondingPeriod();\n * console.log(`Bonding period: ${bondingPeriod / 86400n} days`);\n * ```\n */\n async getBondingPeriod(): Promise<bigint> {\n const stakingContract = this.getStakingContract();\n return stakingContract.read.bondingPeriod();\n }\n\n /**\n * Gets the total distributed rewards for a specific entity from the contract.\n *\n * @remarks\n * This reads the `totalDistributedRewards` field from the entity's on-chain state.\n * This value represents the sum of all rewards that have been processed\n * (moved from lockedRewardPool to activeRewardPool) minus any forfeited\n * rewards that were returned.\n *\n * @param entityId - The ID of the entity to query\n * @returns The total distributed rewards in wei\n *\n * @example\n * ```typescript\n * const totalRewards = await vana.staking.getTotalDistributedRewards(1n);\n * const totalRewardsVana = Number(totalRewards) / 1e18;\n * console.log(`Total distributed rewards: ${totalRewardsVana.toLocaleString()} VANA`);\n * ```\n */\n async getTotalDistributedRewards(entityId: bigint): Promise<bigint> {\n const entityContract = this.getEntityContract();\n const result = await entityContract.read.entities([entityId]);\n return result.totalDistributedRewards;\n }\n\n /**\n * Gets a comprehensive staking summary for a staker in an entity.\n *\n * @remarks\n * This method aggregates all relevant staking information for a staker in a single call,\n * including staked amount, current value, bonding status, and all reward types.\n *\n * Reward breakdown:\n * - `earnedRewards` = pendingInterest + vestedRewards + realizedRewards\n * - `pendingInterest` = currentValue - costBasis (unvested appreciation)\n * - `vestedRewards` = rewards that have vested but not yet withdrawn\n * - `realizedRewards` = rewards already withdrawn during unstakes\n *\n * @param staker - The address of the staker\n * @param entityId - The ID of the entity\n * @returns A comprehensive summary of the staker's position\n *\n * @example\n * ```typescript\n * const summary = await vana.staking.getStakerSummary('0x742d35...', 1n);\n * console.log(`Total staked: ${Number(summary.totalStaked) / 1e18} VANA`);\n * console.log(`Current value: ${Number(summary.currentValue) / 1e18} VANA`);\n * console.log(`In bonding period: ${summary.isInBondingPeriod}`);\n * console.log(`Remaining bonding time: ${Number(summary.remainingBondingTime) / 86400} days`);\n * console.log(`Vested rewards: ${Number(summary.vestedRewards) / 1e18} VANA`);\n * console.log(`Unvested rewards: ${Number(summary.unvestedRewards) / 1e18} VANA`);\n * console.log(`Realized rewards: ${Number(summary.realizedRewards) / 1e18} VANA`);\n * console.log(`Total earned: ${Number(summary.earnedRewards) / 1e18} VANA`);\n * ```\n */\n async getStakerSummary(\n staker: Address,\n entityId: bigint,\n ): Promise<StakerEntitySummary> {\n const chainId = this.getChainId();\n const stakingAddress = getContractAddress(chainId, \"VanaPoolStaking\");\n const entityAddress = getContractAddress(chainId, \"VanaPoolEntity\");\n const stakingAbi = getAbi(\"VanaPoolStaking\");\n const entityAbi = getAbi(\"VanaPoolEntity\");\n\n // Get latest block first to ensure all reads are from the same block\n const block = await this.context.publicClient.getBlock();\n const blockNumber = block.number;\n\n // Batch all contract reads into a single multicall RPC request at the same block\n const multicallResults = await this.context.publicClient.multicall({\n contracts: [\n {\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"stakerEntities\",\n args: [staker, entityId],\n },\n {\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"getEarnedRewards\",\n args: [staker, entityId],\n },\n {\n address: entityAddress,\n abi: entityAbi,\n functionName: \"entityShareToVana\",\n args: [entityId],\n },\n ],\n blockNumber,\n });\n\n const [positionResult, earnedRewardsResult, shareToVanaResult] =\n multicallResults;\n\n if (\n positionResult.status === \"failure\" ||\n earnedRewardsResult.status === \"failure\" ||\n shareToVanaResult.status === \"failure\"\n ) {\n throw new BlockchainError(\n \"Failed to fetch staker summary: one or more contract calls failed\",\n );\n }\n\n const position = positionResult.result as {\n shares: bigint;\n costBasis: bigint;\n rewardEligibilityTimestamp: bigint;\n realizedRewards: bigint;\n vestedRewards: bigint;\n };\n const earnedRewards = earnedRewardsResult.result as bigint;\n const shareToVana = shareToVanaResult.result as bigint;\n const currentTimestamp = block.timestamp;\n\n // Calculate remaining bonding time\n const eligibilityTimestamp = position.rewardEligibilityTimestamp;\n const remainingBondingTime =\n eligibilityTimestamp > currentTimestamp\n ? eligibilityTimestamp - currentTimestamp\n : 0n;\n const isInBondingPeriod = remainingBondingTime > 0n;\n\n // Calculate current value of shares\n // entityShareToVana returns the VANA value of 1 share (scaled by 1e18)\n const currentValue = (position.shares * shareToVana) / 10n ** 18n;\n\n // Calculate pending interest (unvested rewards)\n // pendingInterest = currentValue - costBasis (if positive)\n const unvestedRewards =\n currentValue > position.costBasis\n ? currentValue - position.costBasis\n : 0n;\n\n return {\n shares: position.shares,\n costBasis: position.costBasis,\n currentValue,\n rewardEligibilityTimestamp: eligibilityTimestamp,\n remainingBondingTime,\n isInBondingPeriod,\n vestedRewards: position.vestedRewards,\n unvestedRewards,\n realizedRewards: position.realizedRewards,\n earnedRewards,\n };\n }\n\n /**\n * Stakes VANA to an entity in the VanaPool protocol.\n *\n * @remarks\n * This method stakes native VANA tokens to a specified entity. The staker will receive\n * shares in proportion to their stake amount. A bonding period applies during which\n * rewards cannot be fully claimed without penalty.\n *\n * Requires a wallet client to be configured in the Vana constructor.\n *\n * @param params - The staking parameters\n * @param params.entityId - The ID of the entity to stake to\n * @param params.amount - The amount of VANA to stake (in wei, or as a string like \"1.5\" for 1.5 VANA)\n * @param params.recipient - Optional recipient address for the shares (defaults to the sender)\n * @param params.minShares - Optional minimum shares to receive (slippage protection, defaults to 0)\n * @returns The transaction hash\n * @throws {BlockchainError} When wallet client is not configured\n *\n * @example\n * ```typescript\n * // Stake 100 VANA to entity 1\n * const txHash = await vana.staking.stake({\n * entityId: 1n,\n * amount: \"100\", // 100 VANA\n * });\n * console.log(`Staked! Transaction: ${txHash}`);\n *\n * // Stake with slippage protection\n * const txHash2 = await vana.staking.stake({\n * entityId: 1n,\n * amount: parseEther(\"50\"), // 50 VANA in wei\n * minShares: parseEther(\"49\"), // Expect at least 49 shares\n * });\n * ```\n */\n async stake(\n params: {\n entityId: bigint;\n amount: bigint | string;\n recipient?: Address;\n minShares?: bigint;\n },\n options?: TransactionOptions,\n ): Promise<Hash> {\n this.assertWallet();\n\n const chainId = this.getChainId();\n const stakingAddress = getContractAddress(chainId, \"VanaPoolStaking\");\n const stakingAbi = getAbi(\"VanaPoolStaking\");\n\n // Convert amount to bigint if it's a string (e.g., \"1.5\" -> 1.5 VANA in wei)\n const amountWei =\n typeof params.amount === \"string\"\n ? parseEther(params.amount)\n : params.amount;\n\n // Get account with fallback to userAddress\n const account =\n this.context.walletClient.account ?? this.context.userAddress;\n const accountAddress =\n typeof account === \"string\" ? account : account.address;\n\n // Default recipient to the sender's address\n const recipient = params.recipient ?? accountAddress;\n\n // Default minShares to 0 (no slippage protection)\n const minShares = params.minShares ?? 0n;\n\n const txHash = await this.context.walletClient.writeContract({\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"stake\",\n args: [params.entityId, recipient, minShares],\n value: amountWei,\n account,\n chain: this.context.walletClient.chain,\n ...this.spreadTransactionOptions(options),\n });\n\n return txHash;\n }\n\n /**\n * Gets the maximum amount of VANA that can be unstaked in a single transaction.\n *\n * @remarks\n * This calls the contract's getMaxUnstakeAmount which returns the minimum of:\n * 1. The withdrawable VANA (costBasis if in bonding period, shareValue if eligible)\n * 2. The entity's activeRewardPool (what the entity has available)\n * 3. The treasury balance (what can be paid out)\n *\n * The limiting factor indicates what's constraining the unstake:\n * - 0 = user shares/costBasis\n * - 1 = activeRewardPool\n * - 2 = treasury\n *\n * @param staker - The address of the staker\n * @param entityId - The ID of the entity\n * @returns Object containing maxVana, maxShares, limitingFactor, and isInBondingPeriod\n *\n * @example\n * ```typescript\n * const result = await vana.staking.getMaxUnstakeAmount('0x742d35...', 1n);\n * console.log(`Max unstake: ${Number(result.maxVana) / 1e18} VANA`);\n * console.log(`Max shares: ${result.maxShares}`);\n * console.log(`In bonding period: ${result.isInBondingPeriod}`);\n * ```\n */\n async getMaxUnstakeAmount(\n staker: Address,\n entityId: bigint,\n ): Promise<{\n maxVana: bigint;\n maxShares: bigint;\n limitingFactor: number;\n isInBondingPeriod: boolean;\n }> {\n const stakingContract = this.getStakingContract();\n\n const result = await stakingContract.read.getMaxUnstakeAmount([\n staker,\n entityId,\n ]);\n\n return {\n maxVana: result[0],\n maxShares: result[1],\n limitingFactor: Number(result[2]),\n isInBondingPeriod: result[3],\n };\n }\n\n /**\n * Computes the new bonding period end timestamp after adding stake.\n *\n * @remarks\n * When a staker adds more stake to an existing position, the reward eligibility timestamp\n * is recalculated as a weighted average of the existing and new positions. This function\n * allows you to preview what the new eligibility timestamp would be without executing\n * the stake transaction.\n *\n * The formula used (matching the contract):\n * ```\n * newEligibility = (existingShares * existingEligibility + newShares * newEligibility) / totalShares\n * ```\n *\n * Where `newEligibility` for the incoming stake is `currentTimestamp + bondingPeriod`.\n *\n * @param params - The parameters for computing the new bonding period\n * @param params.staker - The address of the staker\n * @param params.entityId - The ID of the entity\n * @param params.stakeAmount - The amount of VANA to stake (in wei)\n * @returns Object containing the new eligibility timestamp and related info\n *\n * @example\n * ```typescript\n * // Preview bonding period after staking 100 VANA\n * const preview = await vana.staking.computeNewBondingPeriod({\n * staker: '0x742d35...',\n * entityId: 1n,\n * stakeAmount: parseEther(\"100\"),\n * });\n * console.log(`New eligibility: ${new Date(Number(preview.newEligibilityTimestamp) * 1000)}`);\n * console.log(`Remaining bonding time: ${Number(preview.newRemainingBondingTime) / 86400} days`);\n * ```\n */\n async computeNewBondingPeriod(params: {\n staker: Address;\n entityId: bigint;\n stakeAmount: bigint;\n }): Promise<{\n /** The new reward eligibility timestamp after staking */\n newEligibilityTimestamp: bigint;\n /** Remaining bonding time in seconds after staking */\n newRemainingBondingTime: bigint;\n /** Current eligibility timestamp (before staking) */\n currentEligibilityTimestamp: bigint;\n /** Current remaining bonding time (before staking) */\n currentRemainingBondingTime: bigint;\n /** Current shares held by staker */\n currentShares: bigint;\n /** Estimated new shares to be received */\n estimatedNewShares: bigint;\n /** Total shares after staking */\n totalSharesAfter: bigint;\n /** The bonding period duration in seconds */\n bondingPeriodDuration: bigint;\n /** Current block timestamp used for calculation */\n currentTimestamp: bigint;\n }> {\n const chainId = this.getChainId();\n const stakingAddress = getContractAddress(chainId, \"VanaPoolStaking\");\n const entityAddress = getContractAddress(chainId, \"VanaPoolEntity\");\n const stakingAbi = getAbi(\"VanaPoolStaking\");\n const entityAbi = getAbi(\"VanaPoolEntity\");\n\n // Get latest block first to ensure all reads are from the same block\n const block = await this.context.publicClient.getBlock();\n const blockNumber = block.number;\n const currentTimestamp = block.timestamp;\n\n // Batch all contract reads into a single multicall RPC request at the same block\n const multicallResults = await this.context.publicClient.multicall({\n contracts: [\n {\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"stakerEntities\",\n args: [params.staker, params.entityId],\n },\n {\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"bondingPeriod\",\n args: [],\n },\n {\n address: entityAddress,\n abi: entityAbi,\n functionName: \"vanaToEntityShare\",\n args: [params.entityId],\n },\n ],\n blockNumber,\n });\n\n const [positionResult, bondingPeriodResult, vanaToShareResult] =\n multicallResults;\n\n if (\n positionResult.status === \"failure\" ||\n bondingPeriodResult.status === \"failure\" ||\n vanaToShareResult.status === \"failure\"\n ) {\n throw new BlockchainError(\n \"Failed to compute new bonding period: one or more contract calls failed\",\n );\n }\n\n const position = positionResult.result as {\n shares: bigint;\n costBasis: bigint;\n rewardEligibilityTimestamp: bigint;\n realizedRewards: bigint;\n vestedRewards: bigint;\n };\n const bondingPeriodDuration = bondingPeriodResult.result as bigint;\n const vanaToShare = vanaToShareResult.result as bigint;\n\n const currentShares = position.shares;\n const currentEligibilityTimestamp = position.rewardEligibilityTimestamp;\n\n // Calculate current remaining bonding time\n const currentRemainingBondingTime =\n currentEligibilityTimestamp > currentTimestamp\n ? currentEligibilityTimestamp - currentTimestamp\n : 0n;\n\n // Estimate new shares: newShares = (stakeAmount * vanaToShare) / 1e18\n const estimatedNewShares = (params.stakeAmount * vanaToShare) / 10n ** 18n;\n\n // Calculate new eligibility timestamp using weighted average formula\n // newEligibility = (existingShares * existingEligibility + newShares * (currentTime + bondingPeriod)) / totalShares\n const totalSharesAfter = currentShares + estimatedNewShares;\n const newStakeEligibility = currentTimestamp + bondingPeriodDuration;\n\n let newEligibilityTimestamp: bigint;\n if (currentShares === 0n) {\n // First stake: eligibility is simply current time + bonding period\n newEligibilityTimestamp = newStakeEligibility;\n } else {\n // Weighted average of existing and new positions\n newEligibilityTimestamp =\n (currentShares * currentEligibilityTimestamp +\n estimatedNewShares * newStakeEligibility) /\n totalSharesAfter;\n }\n\n // Calculate new remaining bonding time\n const newRemainingBondingTime =\n newEligibilityTimestamp > currentTimestamp\n ? newEligibilityTimestamp - currentTimestamp\n : 0n;\n\n return {\n newEligibilityTimestamp,\n newRemainingBondingTime,\n currentEligibilityTimestamp,\n currentRemainingBondingTime,\n currentShares,\n estimatedNewShares,\n totalSharesAfter,\n bondingPeriodDuration,\n currentTimestamp,\n };\n }\n\n /**\n * Unstakes VANA from an entity in the VanaPool protocol.\n *\n * @remarks\n * This method unstakes native VANA tokens from a specified entity. The amount\n * that can be unstaked depends on whether the staker is in the bonding period:\n *\n * - **During bonding period**: Only cost basis can be withdrawn; rewards are forfeited\n * - **After bonding period**: Full current value (cost basis + rewards) can be withdrawn\n *\n * Use `getMaxUnstakeAmount` to determine the maximum amount that can be unstaked.\n *\n * Requires a wallet client to be configured in the Vana constructor.\n *\n * @param params - The unstaking parameters\n * @param params.entityId - The ID of the entity to unstake from\n * @param params.amount - The amount of VANA to unstake (in wei, or as a string like \"1.5\" for 1.5 VANA)\n * @param params.maxShares - Maximum shares to burn for slippage protection (defaults to 0, no protection)\n * @returns The transaction hash\n * @throws {BlockchainError} When wallet client is not configured\n *\n * @example\n * ```typescript\n * // Get max unstake amount first\n * const maxUnstake = await vana.staking.getMaxUnstakeAmount(address, 1n);\n *\n * // Unstake the maximum amount with slippage protection\n * const txHash = await vana.staking.unstake({\n * entityId: 1n,\n * amount: maxUnstake.maxVana,\n * maxShares: maxUnstake.maxShares,\n * });\n * console.log(`Unstaked! Transaction: ${txHash}`);\n * ```\n */\n async unstake(\n params: {\n entityId: bigint;\n amount: bigint | string;\n maxShares?: bigint;\n },\n options?: TransactionOptions,\n ): Promise<Hash> {\n this.assertWallet();\n\n const chainId = this.getChainId();\n const stakingAddress = getContractAddress(chainId, \"VanaPoolStaking\");\n const stakingAbi = getAbi(\"VanaPoolStaking\");\n\n // Convert amount to bigint if it's a string (e.g., \"1.5\" -> 1.5 VANA in wei)\n const amountWei =\n typeof params.amount === \"string\"\n ? parseEther(params.amount)\n : params.amount;\n\n // Default maxShares to 0 (no slippage protection)\n const maxShares = params.maxShares ?? 0n;\n\n // Get account with fallback to userAddress\n const account =\n this.context.walletClient.account ?? this.context.userAddress;\n\n const txHash = await this.context.walletClient.writeContract({\n address: stakingAddress,\n abi: stakingAbi,\n functionName: \"unstakeVana\",\n args: [params.entityId, amountWei, maxShares],\n account,\n chain: this.context.walletClient.chain,\n ...this.spreadTransactionOptions(options),\n });\n\n return txHash;\n }\n}\n"],"mappings":"AAcA,SAAS,sBAAsB;AAC/B,SAAS,aAAa,kBAAkB;AAExC,SAAS,0BAA0B;AACnC,SAAS,cAAc;AACvB,SAAS,uBAAuB;AA4EzB,MAAM,0BAA0B,eAAe;AAAA,EACpD,YAAY,SAA4B;AACtC,UAAM,OAAO;AAAA,EACf;AAAA;AAAA;AAAA;AAAA,EAKQ,aAAqB;AAC3B,UAAM,UACJ,KAAK,QAAQ,cAAc,OAAO,MAClC,KAAK,QAAQ,aAAa,OAAO;AACnC,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKQ,oBAAoB;AAC1B,UA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c;AAAA,MACd,MAAM,CAAC,OAAO,UAAU,WAAW,SAAS;AAAA,MAC5C;AAAA,MACA,OAAO,KAAK,QAAQ,aAAa;AAAA,MACjC,GAAG,KAAK,yBAAyB,OAAO;AAAA,IAC1C,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/core.cjs CHANGED
@@ -40,6 +40,7 @@ var import_schemas = require("./controllers/schemas");
40
40
  var import_server = require("./controllers/server");
41
41
  var import_protocol = require("./controllers/protocol");
42
42
  var import_operations = require("./controllers/operations");
43
+ var import_staking = require("./controllers/staking");
43
44
  var import_storage = require("./storage");
44
45
  var import_viem = require("viem");
45
46
  var import_wallet = require("./utils/wallet");
@@ -100,6 +101,8 @@ class VanaCore {
100
101
  server;
101
102
  /** Offers low-level access to Vana protocol smart contracts. */
102
103
  protocol;
104
+ /** Provides VanaPool staking information and operations. */
105
+ staking;
103
106
  /** Handles environment-specific operations like encryption and file systems. */
104
107
  platform;
105
108
  relayerConfig;
@@ -269,6 +272,7 @@ class VanaCore {
269
272
  this.operations = new import_operations.OperationsController(sharedContext);
270
273
  this.server = new import_server.ServerController(sharedContext);
271
274
  this.protocol = new import_protocol.ProtocolController(sharedContext);
275
+ this.staking = new import_staking.StakingController(sharedContext);
272
276
  }
273
277
  /**
274
278
  * Validates that storage is available for storage-dependent operations.
package/dist/core.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts"],"sourcesContent":["import type {\n VanaConfig,\n VanaConfigWithStorage,\n RuntimeConfig,\n VanaChainId,\n StorageRequiredMarker,\n} from \"./types\";\nimport {\n isWalletConfig,\n isChainConfig,\n isReadOnlyConfig,\n isAddressOnlyConfig,\n isVanaChainId,\n hasStorageConfig,\n} from \"./types\";\nimport type { DownloadRelayerCallbacks } from \"./types/config\";\nimport type {\n RelayerConfig,\n UnifiedRelayerRequest,\n UnifiedRelayerResponse,\n} from \"./types/relayer\";\nimport { InvalidConfigurationError } from \"./errors\";\nimport type { ControllerContext } from \"./controllers/permissions\";\nimport { PermissionsController } from \"./controllers/permissions\";\nimport { DataController } from \"./controllers/data\";\nimport { SchemaController } from \"./controllers/schemas\";\nimport { ServerController } from \"./controllers/server\";\nimport { ProtocolController } from \"./controllers/protocol\";\nimport { OperationsController } from \"./controllers/operations\";\nimport { StorageManager } from \"./storage\";\nimport { createWalletClient, createPublicClient, http } from \"viem\";\nimport type {\n PublicClient,\n WalletClient,\n Address,\n Hash,\n TransactionReceipt,\n Chain,\n} from \"viem\";\nimport { extractAddress } from \"./utils/wallet\";\nimport type {\n Operation,\n PollingOptions,\n TransactionResult,\n TransactionWaitOptions,\n} from \"./types/operations\";\nimport type {\n IOperationStore,\n IRelayerStateStore,\n} from \"./types/operationStore\";\nimport type { IAtomicStore } from \"./types/atomicStore\";\nimport type {\n Contract,\n Fn,\n TypedTransactionResult,\n} from \"./generated/event-types\";\nimport { chains } from \"./config/chains\";\nimport { getChainConfig, vanaMainnet } from \"./chains\";\nimport type { VanaPlatformAdapter } from \"./platform/interface\";\nimport {\n encryptBlobWithSignedKey,\n decryptBlobWithSignedKey,\n} from \"./utils/encryption\";\n\n/**\n * Factory functions for creating VanaCore instances with proper type safety\n */\nexport class VanaCoreFactory {\n /**\n * Creates a VanaCore instance that enforces storage requirements at compile time.\n * Use this factory when you know you'll need storage-dependent operations.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - Configuration that includes required storage providers\n * @returns VanaCore instance with storage validation\n * @example\n * ```typescript\n * const vanaCore = VanaCoreFactory.createWithStorage(platformAdapter, {\n * walletClient: myWalletClient,\n * storage: {\n * providers: { ipfs: new IPFSStorage() },\n * defaultProvider: 'ipfs'\n * }\n * });\n * ```\n */\n static createWithStorage(\n platform: VanaPlatformAdapter,\n config: VanaConfigWithStorage,\n ): VanaCore & StorageRequiredMarker {\n const core = new VanaCore(platform, config);\n return core as VanaCore & StorageRequiredMarker;\n }\n\n /**\n * Creates a VanaCore instance without storage requirements.\n * Storage-dependent operations will fail at runtime if not configured.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - Basic configuration without required storage\n * @returns VanaCore instance\n * @example\n * ```typescript\n * const vanaCore = VanaCoreFactory.create(platformAdapter, {\n * walletClient: myWalletClient\n * });\n * ```\n */\n static create(platform: VanaPlatformAdapter, config: VanaConfig): VanaCore {\n return new VanaCore(platform, config);\n }\n}\n\n/**\n * Provides the core SDK functionality for interacting with the Vana network.\n *\n * @remarks\n * This environment-agnostic class contains all SDK logic and accepts a platform\n * adapter to handle environment-specific operations. It initializes all controllers\n * and manages shared context between them, providing a unified interface for\n * data management, permissions, smart contracts, and storage operations.\n *\n * The class uses TypeScript overloading to enforce storage requirements at compile time.\n * Methods that require storage will throw `InvalidConfigurationError` at runtime if\n * storage providers are not configured, implementing a fail-fast approach to prevent\n * errors during expensive operations.\n *\n * **Core Architecture:**\n * - **Controllers**: Specialized modules for different Vana features (data, permissions, etc.)\n * - **Platform Adapters**: Environment-specific implementations (browser vs Node.js)\n * - **Storage Managers**: Abstraction layer for multiple storage providers\n * - **Context Sharing**: Unified configuration and services across all controllers\n *\n * For public usage, use the platform-specific factory functions:\n * - Browser: `import { Vana } from '@opendatalabs/vana-sdk/browser'`\n * - Node.js: `import { Vana } from '@opendatalabs/vana-sdk/node'`\n *\n * @example\n * ```typescript\n * // Direct instantiation (advanced usage)\n * import { VanaCore, BrowserPlatformAdapter } from '@opendatalabs/vana-sdk/browser';\n *\n * const core = new VanaCore(new BrowserPlatformAdapter(), {\n * walletClient: myWalletClient,\n * storage: {\n * providers: { ipfs: new IPFSStorage() },\n * defaultProvider: 'ipfs'\n * }\n * });\n *\n * // Access all controllers\n * const files = await core.data.getUserFiles();\n * const permissions = await core.permissions.grant({\n * grantee: '0x742d35...',\n * operation: 'read'\n * });\n * ```\n * @category Core SDK\n */\nexport class VanaCore {\n /** Manages gasless data access permissions and trusted server registry. */\n public readonly permissions: PermissionsController;\n\n /** Handles user data file operations. */\n public readonly data: DataController;\n\n /** Manages data schemas and refiners. */\n public readonly schemas: SchemaController;\n\n /** Manages asynchronous operation recovery and status checking. */\n public readonly operations: OperationsController;\n\n /** Provides personal server setup and trusted server interactions. */\n public readonly server: ServerController;\n\n /** Offers low-level access to Vana protocol smart contracts. */\n public readonly protocol: ProtocolController;\n\n /** Handles environment-specific operations like encryption and file systems. */\n protected platform: VanaPlatformAdapter;\n\n private readonly relayerConfig?: RelayerConfig;\n private readonly relayerCallback?: (\n request: UnifiedRelayerRequest,\n ) => Promise<UnifiedRelayerResponse>;\n private readonly downloadRelayer?: DownloadRelayerCallbacks;\n private readonly storageManager?: StorageManager;\n private readonly hasRequiredStorage: boolean;\n private readonly ipfsGateways?: string[];\n public readonly publicClient: PublicClient;\n private readonly walletClient?: WalletClient;\n private readonly _staticUserAddress?: Address; // For read-only mode\n protected readonly operationStore?: IOperationStore | IRelayerStateStore;\n protected readonly atomicStore?: IAtomicStore;\n\n /**\n * Initializes a new VanaCore client instance with the provided configuration.\n *\n * @remarks\n * The constructor validates the configuration, initializes storage providers if configured,\n * creates wallet and public clients, and sets up all SDK controllers with shared context.\n *\n * IMPORTANT: This constructor will validate storage requirements at runtime to fail fast.\n * Methods that require storage will throw runtime errors if storage is not configured.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - The configuration object specifying wallet or chain settings\n * @throws {InvalidConfigurationError} When the configuration is invalid or incomplete\n * @example\n * ```typescript\n * // Direct instantiation (consider using factory methods instead)\n * const vanaCore = new VanaCore(platformAdapter, {\n * walletClient: myWalletClient,\n * });\n * ```\n */\n constructor(platform: VanaPlatformAdapter, config: VanaConfig) {\n // Store the platform adapter\n this.platform = platform;\n\n // Validate configuration\n this.validateConfig(config);\n\n // Store operation store if provided\n this.operationStore = config?.operationStore;\n\n // Store relayer config and set up callback\n this.relayerConfig = config.relayer;\n if (config.relayer) {\n // Validate relayer type\n if (\n typeof config.relayer !== \"string\" &&\n typeof config.relayer !== \"function\"\n ) {\n throw new InvalidConfigurationError(\n \"Relayer must be either a URL string or a callback function\",\n );\n }\n\n if (typeof config.relayer === \"string\") {\n // Convenience: URL string - create HTTP transport\n const url = config.relayer;\n this.relayerCallback = async (request: UnifiedRelayerRequest) => {\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n if (!response.ok) {\n throw new Error(`Relayer request failed: ${response.statusText}`);\n }\n return response.json();\n };\n } else {\n // Direct callback function\n this.relayerCallback = config.relayer;\n }\n }\n\n // Store download relayer if provided\n this.downloadRelayer = config.downloadRelayer;\n\n // Store IPFS gateways if provided\n this.ipfsGateways = config.ipfsGateways;\n\n // Check if storage is properly configured\n this.hasRequiredStorage = hasStorageConfig(config);\n\n // Initialize storage manager if storage providers are provided\n if (config.storage?.providers) {\n this.storageManager = new StorageManager();\n\n // Register all provided storage providers\n for (const [name, provider] of Object.entries(config.storage.providers)) {\n const isDefault = name === config.storage.defaultProvider;\n this.storageManager.register(name, provider, isDefault);\n }\n\n // If no default was explicitly set but providers exist, use the first one\n if (\n !config.storage.defaultProvider &&\n Object.keys(config.storage.providers).length > 0\n ) {\n const firstProviderName = Object.keys(config.storage.providers)[0];\n this.storageManager.setDefaultProvider(firstProviderName);\n }\n }\n\n // Initialize clients based on configuration type\n let walletClient: WalletClient | undefined;\n let publicClient: PublicClient;\n let staticUserAddress: Address | undefined; // Only for read-only mode\n let chainToUse: Chain;\n\n if (isWalletConfig(config)) {\n // Full mode with wallet client\n walletClient = config.walletClient;\n chainToUse = (walletClient.chain as Chain) ?? vanaMainnet;\n\n // In wallet mode, address is dynamic (not stored)\n staticUserAddress = undefined;\n\n // Use provided publicClient or create one\n if (\"publicClient\" in config && config.publicClient) {\n publicClient = config.publicClient;\n } else {\n publicClient = createPublicClient({\n chain: chainToUse,\n transport: http(),\n });\n }\n } else if (isReadOnlyConfig(config)) {\n // Read-only mode with public client and address\n walletClient = undefined;\n publicClient = config.publicClient;\n staticUserAddress = config.address;\n chainToUse = config.publicClient.chain ?? vanaMainnet;\n } else if (isAddressOnlyConfig(config)) {\n // Read-only mode with just address (create public client)\n walletClient = undefined;\n staticUserAddress = config.address;\n chainToUse = config.chain ?? vanaMainnet;\n\n publicClient = createPublicClient({\n chain: chainToUse,\n transport: http(),\n });\n } else if (isChainConfig(config)) {\n // Legacy chain configuration - create wallet client\n if (!config.account) {\n throw new InvalidConfigurationError(\n \"Account is required when using ChainConfig\",\n );\n }\n\n const chain = chains[config.chainId];\n if (!chain) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${config.chainId}`,\n );\n }\n\n chainToUse = chain;\n walletClient = createWalletClient({\n chain,\n transport: http(config.rpcUrl ?? chain.rpcUrls.default.http[0]),\n account: config.account,\n });\n // In wallet mode, address is dynamic (not stored)\n staticUserAddress = undefined;\n publicClient = createPublicClient({\n chain,\n transport: http(),\n });\n } else {\n throw new InvalidConfigurationError(\n \"Invalid configuration: must provide either walletClient, publicClient + address, or address alone\",\n );\n }\n\n // Store the clients and static address for later use\n this.publicClient = publicClient;\n this.walletClient = walletClient;\n this._staticUserAddress = staticUserAddress;\n\n // Get default service URLs from chain config if not provided\n const chainConfig = getChainConfig(chainToUse.id);\n const subgraphUrl = config.subgraphUrl ?? chainConfig?.subgraphUrl;\n const personalServerUrl =\n config.defaultPersonalServerUrl ?? chainConfig?.personalServerUrl;\n\n // Create shared context for all controllers with dynamic userAddress getter\n const self = this; // Capture VanaCore instance for getter delegation\n const sharedContext: ControllerContext = {\n walletClient,\n publicClient,\n get userAddress() {\n // Delegate to VanaCore's getter for dynamic resolution\n return self.userAddress;\n },\n applicationClient: walletClient, // Using same wallet for now\n relayer: this.relayerCallback,\n downloadRelayer: this.downloadRelayer,\n storageManager: this.storageManager,\n subgraphUrl,\n platform: this.platform, // Pass the platform adapter to controllers\n validateStorageRequired: this.validateStorageRequired.bind(this),\n hasStorage: this.hasStorage.bind(this),\n ipfsGateways: this.ipfsGateways,\n defaultPersonalServerUrl: personalServerUrl,\n waitForTransactionEvents: this.waitForTransactionEvents.bind(this),\n waitForOperation: this.waitForOperation.bind(this),\n operationStore: this.operationStore,\n };\n\n // Initialize controllers\n this.permissions = new PermissionsController(sharedContext);\n this.data = new DataController(sharedContext);\n this.schemas = new SchemaController(sharedContext);\n this.operations = new OperationsController(sharedContext);\n this.server = new ServerController(sharedContext);\n this.protocol = new ProtocolController(sharedContext);\n }\n\n /**\n * Validates that storage is available for storage-dependent operations.\n * This method enforces the fail-fast principle by checking storage availability\n * at method call time rather than during expensive operations.\n *\n * @throws {InvalidConfigurationError} When storage is required but not configured\n * @example\n * ```typescript\n * // This will throw if storage is not configured\n * vana.validateStorageRequired();\n * await vana.data.uploadFile(file); // Safe to proceed\n * ```\n */\n public validateStorageRequired(): void {\n if (!this.hasRequiredStorage) {\n throw new InvalidConfigurationError(\n \"Storage configuration is required for this operation. \" +\n \"Please configure storage providers in VanaConfig.storage, \" +\n \"provide a relayer configuration, \" +\n \"or pass pre-stored URLs to avoid this dependency. \" +\n \"\\n\\nFor better type safety, consider using VanaCoreFactory.createWithStorage() \" +\n \"with VanaConfigWithStorage to catch this error at compile time.\",\n );\n }\n }\n\n /**\n * Checks whether storage is configured without throwing an error.\n *\n * @returns True if storage is properly configured\n * @example\n * ```typescript\n * if (vana.hasStorage()) {\n * await vana.data.uploadFile(file);\n * } else {\n * console.warn('Storage not configured - using pre-stored URLs only');\n * }\n * ```\n */\n public hasStorage(): boolean {\n return this.hasRequiredStorage;\n }\n\n /**\n * Type guard to check if this instance has storage enabled at compile time.\n * Use this when you need TypeScript to understand that storage is available.\n *\n * @returns True if storage is configured, with type narrowing\n * @example\n * ```typescript\n * if (vana.isStorageEnabled()) {\n * // TypeScript knows storage is available here\n * await vana.data.uploadFile(file);\n * }\n * ```\n */\n public isStorageEnabled(): this is VanaCore & StorageRequiredMarker {\n return this.hasRequiredStorage;\n }\n\n /**\n * Validates the provided configuration object against all requirements.\n *\n * @remarks\n * This method performs comprehensive validation of wallet client configuration,\n * chain configuration, storage providers, and relayer callbacks.\n * @param config - The configuration object to validate\n * @throws {InvalidConfigurationError} When any configuration parameter is invalid\n */\n private validateConfig(config: VanaConfig): void {\n if (!config) {\n throw new InvalidConfigurationError(\"Configuration object is required\");\n }\n\n // Validate storage configuration if provided\n if (config.storage?.providers) {\n if (typeof config.storage.providers !== \"object\") {\n throw new InvalidConfigurationError(\n \"storage.providers must be an object\",\n );\n }\n\n // Validate that all providers have required methods\n for (const [name, provider] of Object.entries(config.storage.providers)) {\n if (!provider || typeof provider !== \"object\") {\n throw new InvalidConfigurationError(\n `Storage provider '${name}' must be a valid StorageProvider object`,\n );\n }\n }\n\n // Validate default provider if specified\n if (config.storage.defaultProvider) {\n if (!(config.storage.defaultProvider in config.storage.providers)) {\n throw new InvalidConfigurationError(\n `Default storage provider '${config.storage.defaultProvider}' not found in providers`,\n );\n }\n }\n }\n\n if (isWalletConfig(config)) {\n // Validate WalletConfig\n if (!config.walletClient) {\n throw new InvalidConfigurationError(\"walletClient is required\");\n }\n\n // Validate that walletClient is actually a WalletClient\n if (\n typeof config.walletClient !== \"object\" ||\n !config.walletClient.signTypedData\n ) {\n throw new InvalidConfigurationError(\n \"walletClient must be a valid viem WalletClient\",\n );\n }\n\n // Validate that wallet client has a chain\n if (!config.walletClient.chain) {\n throw new InvalidConfigurationError(\n \"walletClient must have a chain configured\",\n );\n }\n\n // Validate that the chain is supported\n if (!isVanaChainId(config.walletClient.chain.id)) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${String(config.walletClient.chain.id)}. Supported chains: 14800 (Moksha testnet), 1480 (Vana mainnet)`,\n );\n }\n } else if (isChainConfig(config)) {\n // Validate ChainConfig\n if (!isVanaChainId(config.chainId)) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${String(config.chainId)}. Supported chains: 14800 (Moksha testnet), 1480 (Vana mainnet)`,\n );\n }\n\n // Validate rpcUrl if provided\n if (config.rpcUrl) {\n if (typeof config.rpcUrl !== \"string\") {\n throw new InvalidConfigurationError(\"rpcUrl must be a string\");\n }\n\n if (config.rpcUrl.trim() === \"\") {\n throw new InvalidConfigurationError(\"rpcUrl cannot be empty\");\n }\n\n // Basic URL validation for RPC URL\n try {\n new URL(config.rpcUrl);\n } catch {\n throw new InvalidConfigurationError(\"rpcUrl must be a valid URL\");\n }\n }\n\n // Account is optional for ChainConfig, but if provided, validate it\n if (config.account) {\n if (typeof config.account !== \"object\" || !config.account.address) {\n throw new InvalidConfigurationError(\n \"account must be a valid viem Account object\",\n );\n }\n }\n } else if (isReadOnlyConfig(config)) {\n // Validate read-only config with publicClient and address\n if (!config.publicClient) {\n throw new InvalidConfigurationError(\n \"publicClient is required for read-only configuration\",\n );\n }\n if (!config.address) {\n throw new InvalidConfigurationError(\n \"address is required for read-only configuration\",\n );\n }\n } else if (isAddressOnlyConfig(config)) {\n // Validate address-only config\n if (!config.address) {\n throw new InvalidConfigurationError(\n \"address is required for address-only configuration\",\n );\n }\n // chain is optional, will use default\n } else {\n throw new InvalidConfigurationError(\n \"Invalid configuration: must provide either walletClient, publicClient + address, or address alone\",\n );\n }\n }\n\n /**\n * Gets the current chain ID from the wallet client.\n *\n * @returns The numeric chain ID of the connected network\n * @example\n * ```typescript\n * const chainId = vana.chainId;\n * console.log(`Connected to chain: ${chainId}`); // e.g., \"Connected to chain: 14800\"\n * ```\n */\n get chainId(): number {\n return this.protocol.getChainId();\n }\n\n /**\n * Gets the current chain name from the wallet client.\n *\n * @returns The human-readable name of the connected network\n * @example\n * ```typescript\n * const chainName = vana.chainName;\n * console.log(`Connected to: ${chainName}`); // e.g., \"Connected to: Moksha Testnet\"\n * ```\n */\n get chainName(): string {\n return this.protocol.getChainName();\n }\n\n /**\n * The user's wallet address.\n * In wallet mode, this always returns the current wallet account address.\n * In read-only mode, this returns the static address provided during initialization.\n *\n * @example\n * ```typescript\n * const address = vana.userAddress;\n * console.log(`User address: ${address}`); // e.g., \"User address: 0x742d35...\"\n * ```\n */\n get userAddress(): Address {\n // In wallet mode: dynamically read from wallet\n if (this.walletClient?.account) {\n return extractAddress(this.walletClient.account);\n }\n\n // In read-only mode: use static address\n if (this._staticUserAddress) {\n return this._staticUserAddress;\n }\n\n throw new Error(\"No user address available\");\n }\n\n /**\n * Retrieves comprehensive runtime configuration information.\n *\n * @returns The current runtime configuration including chain, storage, and relayer settings\n * @example\n * ```typescript\n * const config = vana.getConfig();\n * console.log(`Chain: ${config.chainName} (${config.chainId})`);\n * console.log(`Storage providers: ${config.storageProviders.join(\", \")}`);\n * ```\n */\n getConfig(): RuntimeConfig {\n return {\n chainId: this.chainId as VanaChainId,\n chainName: this.chainName,\n relayerConfig: this.relayerConfig,\n storageProviders: this.storageManager?.getStorageProviders() ?? [],\n defaultStorageProvider: this.storageManager?.getDefaultStorageProvider(),\n };\n }\n\n /**\n * Sets the platform adapter for environment-specific operations.\n * This is useful for testing and advanced use cases where you need\n * to override the default platform detection.\n *\n * @param adapter - The platform adapter to use\n * @example\n * ```typescript\n * // For testing with a mock adapter\n * const mockAdapter = new MockPlatformAdapter();\n * vana.setPlatformAdapter(mockAdapter);\n *\n * // For advanced use cases with custom adapters\n * const customAdapter = new CustomPlatformAdapter();\n * vana.setPlatformAdapter(customAdapter);\n * ```\n */\n setPlatformAdapter(adapter: VanaPlatformAdapter): void {\n this.platform = adapter;\n\n // Note: Controllers will use the new platform adapter on their next operation\n // since they access this.platform from the shared context\n }\n\n /**\n * Gets the current platform adapter.\n * This is useful for advanced use cases where you need to access\n * the platform adapter directly.\n *\n * @returns The current platform adapter\n * @example\n * ```typescript\n * const adapter = vana.getPlatformAdapter();\n * const encrypted = await adapter.encrypt(data, key);\n * ```\n */\n getPlatformAdapter(): VanaPlatformAdapter {\n return this.platform;\n }\n\n /**\n * Encrypts data using the Vana protocol standard encryption.\n *\n * @remarks\n * This method implements the Vana network's standard encryption protocol using\n * platform-appropriate cryptographic libraries. It automatically handles different\n * input types (string or Blob) and produces encrypted output suitable for secure\n * storage or transmission. The encryption is compatible with the network's\n * decryption protocols and can be decrypted by authorized parties.\n *\n * @param data - The data to encrypt (string or Blob)\n * @param key - The encryption key (typically generated via `generateEncryptionKey`)\n * @returns The encrypted data as a Blob\n * @throws {Error} When encryption fails due to invalid key or data format\n * @example\n * ```typescript\n * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';\n *\n * // Generate encryption key from wallet signature\n * const encryptionKey = await generateEncryptionKey(vana.walletClient);\n *\n * // Encrypt string data\n * const sensitiveData = \"User's private information\";\n * const encrypted = await vana.encryptBlob(sensitiveData, encryptionKey);\n *\n * // Encrypt file data\n * const fileBlob = new Blob([fileContent], { type: 'application/json' });\n * const encryptedFile = await vana.encryptBlob(fileBlob, encryptionKey);\n *\n * // Store encrypted data safely\n * await storageProvider.upload(encrypted, 'encrypted-data.bin');\n * ```\n */\n public async encryptBlob(data: string | Blob, key: string): Promise<Blob> {\n return encryptBlobWithSignedKey(data, key, this.platform);\n }\n\n /**\n * Decrypts data that was encrypted using the Vana protocol.\n *\n * @remarks\n * This method decrypts data that was previously encrypted using the Vana network's\n * standard encryption protocol. It requires the same wallet signature that was used\n * for encryption and automatically uses the appropriate platform adapter for\n * cryptographic operations. The decrypted output maintains the original data format.\n *\n * @param encryptedData - The encrypted data (string or Blob)\n * @param walletSignature - The wallet signature used as decryption key\n * @returns The decrypted data as a Blob\n * @throws {Error} When decryption fails due to invalid signature or corrupted data\n * @example\n * ```typescript\n * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';\n *\n * // Retrieve encrypted data from storage\n * const encryptedBlob = await storageProvider.download('encrypted-data.bin');\n *\n * // Generate the same key used for encryption\n * const decryptionKey = await generateEncryptionKey(vana.walletClient);\n *\n * // Decrypt the data\n * const decrypted = await vana.decryptBlob(encryptedBlob, decryptionKey);\n *\n * // Convert back to original format\n * const originalText = await decrypted.text();\n * const originalJson = JSON.parse(originalText);\n *\n * console.log('Decrypted data:', originalJson);\n * ```\n *\n * @example\n * ```typescript\n * // Decrypt file downloaded from Vana network\n * const userFiles = await vana.data.getUserFiles();\n * const file = userFiles[0];\n *\n * // Download encrypted content\n * const encrypted = await fetch(file.url).then(r => r.blob());\n *\n * // Decrypt with user's key\n * const decryptionKey = await generateEncryptionKey(vana.walletClient);\n * const decrypted = await vana.decryptBlob(encrypted, decryptionKey);\n *\n * // Process original data\n * const fileContent = await decrypted.arrayBuffer();\n * ```\n */\n public async decryptBlob(\n encryptedData: string | Blob,\n walletSignature: string,\n ): Promise<Blob> {\n return decryptBlobWithSignedKey(\n encryptedData,\n walletSignature,\n this.platform,\n );\n }\n\n /**\n * Waits for an operation to complete and returns the final result.\n *\n * @remarks\n * This method polls the operation status at regular intervals until it\n * reaches a terminal state (succeeded, failed, or canceled). Supports\n * ergonomic overloads to accept either an Operation object or just the ID.\n *\n * @param opOrId - Either an Operation object or operation ID string\n * @param options - Optional polling configuration\n * @returns The completed operation with result or error\n * @throws {PersonalServerError} When the operation fails or times out\n * @example\n * ```typescript\n * // Using operation object\n * const operation = await vana.server.createOperation({ permissionId: 123 });\n * const completed = await vana.waitForOperation(operation);\n *\n * // Using just the ID\n * const completed = await vana.waitForOperation(\"op_abc123\");\n *\n * // With custom timeout\n * const completed = await vana.waitForOperation(operation, {\n * timeout: 60000,\n * pollingInterval: 1000\n * });\n * ```\n */\n public async waitForOperation(\n opOrId: Operation | string,\n options?: PollingOptions,\n ): Promise<Operation> {\n return this.server.waitForOperation(opOrId, options);\n }\n\n /**\n * Waits for a transaction to be confirmed and returns the receipt.\n *\n * @remarks\n * This method polls for transaction confirmation on the blockchain.\n * Supports ergonomic overloads to accept either a transaction result\n * object or just the hash string.\n *\n * @param hashOrObj - Either a TransactionResult object or hash string\n * @param options - Optional wait configuration\n * @returns The transaction receipt with logs and status\n * @example\n * ```typescript\n * // Using transaction result object\n * const tx = await vana.permissions.grant(params);\n * const receipt = await vana.waitForTransactionReceipt(tx);\n *\n * // Using just the hash\n * const receipt = await vana.waitForTransactionReceipt(\"0x123...\");\n *\n * // With custom confirmations\n * const receipt = await vana.waitForTransactionReceipt(tx, {\n * confirmations: 3,\n * timeout: 60000\n * });\n * ```\n */\n public async waitForTransactionReceipt(\n hashOrObj: TransactionResult | { hash: Hash } | Hash,\n options?: TransactionWaitOptions,\n ): Promise<TransactionReceipt> {\n const hash = typeof hashOrObj === \"string\" ? hashOrObj : hashOrObj.hash;\n\n return this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: options?.confirmations,\n pollingInterval: options?.pollingInterval,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Waits for transaction confirmation and extracts blockchain event data.\n *\n * @remarks\n * This method leverages the context-carrying POJO architecture. When passed a\n * `TransactionResult` with an `operation` field, it automatically parses the\n * correct events from the transaction logs. For legacy compatibility, it accepts\n * raw hashes but will not parse events without operation context.\n *\n * @param transaction - Transaction result with operation context\n * @param options - Optional confirmation and timeout settings\n * @returns Parsed event data specific to the transaction's operation type\n * @throws {NetworkError} When transaction confirmation times out\n * @throws {BlockchainError} When expected events are not found in the transaction\n *\n * @example\n * ```typescript\n * // Recommended: Pass the transaction result for automatic event parsing\n * const tx = await vana.permissions.submitAddServerFilesAndPermissions(params);\n * const events = await vana.waitForTransactionEvents<{ permissionId: bigint }>(tx);\n * console.log(`Permission ID: ${events.permissionId}`);\n *\n * // Legacy: Raw hash without event parsing (returns receipt)\n * const receipt = await vana.waitForTransactionEvents(\"0x123...\");\n * ```\n *\n * @see For understanding transaction flows, visit https://docs.vana.org/docs/transactions\n */\n public async waitForTransactionEvents<C extends Contract, F extends Fn<C>>(\n transaction: TransactionResult<C, F>,\n options?: TransactionWaitOptions,\n ): Promise<TypedTransactionResult<C, F>> {\n // Import the POJO-based parser\n const { parseTransaction } = await import(\"./utils/parseTransactionPojo\");\n\n // Wait for the transaction to be mined\n const receipt = await this.waitForTransactionReceipt(\n transaction.hash,\n options,\n );\n\n // Parse events using our heuristic-free POJO system\n const result = parseTransaction(transaction, receipt);\n\n // Return the strongly-typed result\n // TypeScript knows exactly what events are possible!\n return result;\n }\n\n /**\n * Enhances a unified relayer response with client-side behavior.\n *\n * @remarks\n * This method wraps a relayer response in an enhanced object that provides\n * a fluent `.wait()` method for handling asynchronous operations. The enhanced\n * response intelligently handles both submitted transactions (via hash) and\n * pending operations (via operationId).\n *\n * @param response - The unified relayer response to enhance\n * @returns EnhancedTransactionResponse if the response can be enhanced, null otherwise\n *\n * @example\n * ```typescript\n * // Enhance a relayer response for fluent waiting\n * const response = await handleRelayerOperation(vana, request);\n * const enhanced = vana.enhanceRelayerResponse(response);\n * if (enhanced) {\n * const result = await enhanced.wait();\n * if (result.expectedEvents?.FileAdded) {\n * console.log('File ID:', result.expectedEvents.FileAdded.fileId);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With status updates for pending operations\n * const enhanced = vana.enhanceRelayerResponse(response);\n * if (enhanced) {\n * const result = await enhanced.wait({\n * onStatusUpdate: (status) => {\n * console.log('Operation status:', status.type);\n * },\n * timeout: 60000 // 1 minute timeout\n * });\n * }\n * ```\n *\n * @category Relayer\n * @since 0.2.0\n */\n public async enhanceRelayerResponse(\n response: UnifiedRelayerResponse,\n ): Promise<any> {\n const { enhanceResponse } = await import(\"./client/enhancedResponse\");\n return enhanceResponse(response, this);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAOO;AAOP,oBAA0C;AAE1C,yBAAsC;AACtC,kBAA+B;AAC/B,qBAAiC;AACjC,oBAAiC;AACjC,sBAAmC;AACnC,wBAAqC;AACrC,qBAA+B;AAC/B,kBAA6D;AAS7D,oBAA+B;AAiB/B,oBAAuB;AACvB,IAAAA,iBAA4C;AAE5C,wBAGO;AAKA,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmB3B,OAAO,kBACL,UACA,QACkC;AAClC,UAAM,OAAO,IAAI,SAAS,UAAU,MAAM;AAC1C,WA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,"sources":["../src/core.ts"],"sourcesContent":["import type {\n VanaConfig,\n VanaConfigWithStorage,\n RuntimeConfig,\n VanaChainId,\n StorageRequiredMarker,\n} from \"./types\";\nimport {\n isWalletConfig,\n isChainConfig,\n isReadOnlyConfig,\n isAddressOnlyConfig,\n isVanaChainId,\n hasStorageConfig,\n} from \"./types\";\nimport type { DownloadRelayerCallbacks } from \"./types/config\";\nimport type {\n RelayerConfig,\n UnifiedRelayerRequest,\n UnifiedRelayerResponse,\n} from \"./types/relayer\";\nimport { InvalidConfigurationError } from \"./errors\";\nimport type { ControllerContext } from \"./controllers/permissions\";\nimport { PermissionsController } from \"./controllers/permissions\";\nimport { DataController } from \"./controllers/data\";\nimport { SchemaController } from \"./controllers/schemas\";\nimport { ServerController } from \"./controllers/server\";\nimport { ProtocolController } from \"./controllers/protocol\";\nimport { OperationsController } from \"./controllers/operations\";\nimport { StakingController } from \"./controllers/staking\";\nimport { StorageManager } from \"./storage\";\nimport { createWalletClient, createPublicClient, http } from \"viem\";\nimport type {\n PublicClient,\n WalletClient,\n Address,\n Hash,\n TransactionReceipt,\n Chain,\n} from \"viem\";\nimport { extractAddress } from \"./utils/wallet\";\nimport type {\n Operation,\n PollingOptions,\n TransactionResult,\n TransactionWaitOptions,\n} from \"./types/operations\";\nimport type {\n IOperationStore,\n IRelayerStateStore,\n} from \"./types/operationStore\";\nimport type { IAtomicStore } from \"./types/atomicStore\";\nimport type {\n Contract,\n Fn,\n TypedTransactionResult,\n} from \"./generated/event-types\";\nimport { chains } from \"./config/chains\";\nimport { getChainConfig, vanaMainnet } from \"./chains\";\nimport type { VanaPlatformAdapter } from \"./platform/interface\";\nimport {\n encryptBlobWithSignedKey,\n decryptBlobWithSignedKey,\n} from \"./utils/encryption\";\n\n/**\n * Factory functions for creating VanaCore instances with proper type safety\n */\nexport class VanaCoreFactory {\n /**\n * Creates a VanaCore instance that enforces storage requirements at compile time.\n * Use this factory when you know you'll need storage-dependent operations.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - Configuration that includes required storage providers\n * @returns VanaCore instance with storage validation\n * @example\n * ```typescript\n * const vanaCore = VanaCoreFactory.createWithStorage(platformAdapter, {\n * walletClient: myWalletClient,\n * storage: {\n * providers: { ipfs: new IPFSStorage() },\n * defaultProvider: 'ipfs'\n * }\n * });\n * ```\n */\n static createWithStorage(\n platform: VanaPlatformAdapter,\n config: VanaConfigWithStorage,\n ): VanaCore & StorageRequiredMarker {\n const core = new VanaCore(platform, config);\n return core as VanaCore & StorageRequiredMarker;\n }\n\n /**\n * Creates a VanaCore instance without storage requirements.\n * Storage-dependent operations will fail at runtime if not configured.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - Basic configuration without required storage\n * @returns VanaCore instance\n * @example\n * ```typescript\n * const vanaCore = VanaCoreFactory.create(platformAdapter, {\n * walletClient: myWalletClient\n * });\n * ```\n */\n static create(platform: VanaPlatformAdapter, config: VanaConfig): VanaCore {\n return new VanaCore(platform, config);\n }\n}\n\n/**\n * Provides the core SDK functionality for interacting with the Vana network.\n *\n * @remarks\n * This environment-agnostic class contains all SDK logic and accepts a platform\n * adapter to handle environment-specific operations. It initializes all controllers\n * and manages shared context between them, providing a unified interface for\n * data management, permissions, smart contracts, and storage operations.\n *\n * The class uses TypeScript overloading to enforce storage requirements at compile time.\n * Methods that require storage will throw `InvalidConfigurationError` at runtime if\n * storage providers are not configured, implementing a fail-fast approach to prevent\n * errors during expensive operations.\n *\n * **Core Architecture:**\n * - **Controllers**: Specialized modules for different Vana features (data, permissions, etc.)\n * - **Platform Adapters**: Environment-specific implementations (browser vs Node.js)\n * - **Storage Managers**: Abstraction layer for multiple storage providers\n * - **Context Sharing**: Unified configuration and services across all controllers\n *\n * For public usage, use the platform-specific factory functions:\n * - Browser: `import { Vana } from '@opendatalabs/vana-sdk/browser'`\n * - Node.js: `import { Vana } from '@opendatalabs/vana-sdk/node'`\n *\n * @example\n * ```typescript\n * // Direct instantiation (advanced usage)\n * import { VanaCore, BrowserPlatformAdapter } from '@opendatalabs/vana-sdk/browser';\n *\n * const core = new VanaCore(new BrowserPlatformAdapter(), {\n * walletClient: myWalletClient,\n * storage: {\n * providers: { ipfs: new IPFSStorage() },\n * defaultProvider: 'ipfs'\n * }\n * });\n *\n * // Access all controllers\n * const files = await core.data.getUserFiles();\n * const permissions = await core.permissions.grant({\n * grantee: '0x742d35...',\n * operation: 'read'\n * });\n * ```\n * @category Core SDK\n */\nexport class VanaCore {\n /** Manages gasless data access permissions and trusted server registry. */\n public readonly permissions: PermissionsController;\n\n /** Handles user data file operations. */\n public readonly data: DataController;\n\n /** Manages data schemas and refiners. */\n public readonly schemas: SchemaController;\n\n /** Manages asynchronous operation recovery and status checking. */\n public readonly operations: OperationsController;\n\n /** Provides personal server setup and trusted server interactions. */\n public readonly server: ServerController;\n\n /** Offers low-level access to Vana protocol smart contracts. */\n public readonly protocol: ProtocolController;\n\n /** Provides VanaPool staking information and operations. */\n public readonly staking: StakingController;\n\n /** Handles environment-specific operations like encryption and file systems. */\n protected platform: VanaPlatformAdapter;\n\n private readonly relayerConfig?: RelayerConfig;\n private readonly relayerCallback?: (\n request: UnifiedRelayerRequest,\n ) => Promise<UnifiedRelayerResponse>;\n private readonly downloadRelayer?: DownloadRelayerCallbacks;\n private readonly storageManager?: StorageManager;\n private readonly hasRequiredStorage: boolean;\n private readonly ipfsGateways?: string[];\n public readonly publicClient: PublicClient;\n private readonly walletClient?: WalletClient;\n private readonly _staticUserAddress?: Address; // For read-only mode\n protected readonly operationStore?: IOperationStore | IRelayerStateStore;\n protected readonly atomicStore?: IAtomicStore;\n\n /**\n * Initializes a new VanaCore client instance with the provided configuration.\n *\n * @remarks\n * The constructor validates the configuration, initializes storage providers if configured,\n * creates wallet and public clients, and sets up all SDK controllers with shared context.\n *\n * IMPORTANT: This constructor will validate storage requirements at runtime to fail fast.\n * Methods that require storage will throw runtime errors if storage is not configured.\n *\n * @param platform - The platform adapter for environment-specific operations\n * @param config - The configuration object specifying wallet or chain settings\n * @throws {InvalidConfigurationError} When the configuration is invalid or incomplete\n * @example\n * ```typescript\n * // Direct instantiation (consider using factory methods instead)\n * const vanaCore = new VanaCore(platformAdapter, {\n * walletClient: myWalletClient,\n * });\n * ```\n */\n constructor(platform: VanaPlatformAdapter, config: VanaConfig) {\n // Store the platform adapter\n this.platform = platform;\n\n // Validate configuration\n this.validateConfig(config);\n\n // Store operation store if provided\n this.operationStore = config?.operationStore;\n\n // Store relayer config and set up callback\n this.relayerConfig = config.relayer;\n if (config.relayer) {\n // Validate relayer type\n if (\n typeof config.relayer !== \"string\" &&\n typeof config.relayer !== \"function\"\n ) {\n throw new InvalidConfigurationError(\n \"Relayer must be either a URL string or a callback function\",\n );\n }\n\n if (typeof config.relayer === \"string\") {\n // Convenience: URL string - create HTTP transport\n const url = config.relayer;\n this.relayerCallback = async (request: UnifiedRelayerRequest) => {\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n if (!response.ok) {\n throw new Error(`Relayer request failed: ${response.statusText}`);\n }\n return response.json();\n };\n } else {\n // Direct callback function\n this.relayerCallback = config.relayer;\n }\n }\n\n // Store download relayer if provided\n this.downloadRelayer = config.downloadRelayer;\n\n // Store IPFS gateways if provided\n this.ipfsGateways = config.ipfsGateways;\n\n // Check if storage is properly configured\n this.hasRequiredStorage = hasStorageConfig(config);\n\n // Initialize storage manager if storage providers are provided\n if (config.storage?.providers) {\n this.storageManager = new StorageManager();\n\n // Register all provided storage providers\n for (const [name, provider] of Object.entries(config.storage.providers)) {\n const isDefault = name === config.storage.defaultProvider;\n this.storageManager.register(name, provider, isDefault);\n }\n\n // If no default was explicitly set but providers exist, use the first one\n if (\n !config.storage.defaultProvider &&\n Object.keys(config.storage.providers).length > 0\n ) {\n const firstProviderName = Object.keys(config.storage.providers)[0];\n this.storageManager.setDefaultProvider(firstProviderName);\n }\n }\n\n // Initialize clients based on configuration type\n let walletClient: WalletClient | undefined;\n let publicClient: PublicClient;\n let staticUserAddress: Address | undefined; // Only for read-only mode\n let chainToUse: Chain;\n\n if (isWalletConfig(config)) {\n // Full mode with wallet client\n walletClient = config.walletClient;\n chainToUse = (walletClient.chain as Chain) ?? vanaMainnet;\n\n // In wallet mode, address is dynamic (not stored)\n staticUserAddress = undefined;\n\n // Use provided publicClient or create one\n if (\"publicClient\" in config && config.publicClient) {\n publicClient = config.publicClient;\n } else {\n publicClient = createPublicClient({\n chain: chainToUse,\n transport: http(),\n });\n }\n } else if (isReadOnlyConfig(config)) {\n // Read-only mode with public client and address\n walletClient = undefined;\n publicClient = config.publicClient;\n staticUserAddress = config.address;\n chainToUse = config.publicClient.chain ?? vanaMainnet;\n } else if (isAddressOnlyConfig(config)) {\n // Read-only mode with just address (create public client)\n walletClient = undefined;\n staticUserAddress = config.address;\n chainToUse = config.chain ?? vanaMainnet;\n\n publicClient = createPublicClient({\n chain: chainToUse,\n transport: http(),\n });\n } else if (isChainConfig(config)) {\n // Legacy chain configuration - create wallet client\n if (!config.account) {\n throw new InvalidConfigurationError(\n \"Account is required when using ChainConfig\",\n );\n }\n\n const chain = chains[config.chainId];\n if (!chain) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${config.chainId}`,\n );\n }\n\n chainToUse = chain;\n walletClient = createWalletClient({\n chain,\n transport: http(config.rpcUrl ?? chain.rpcUrls.default.http[0]),\n account: config.account,\n });\n // In wallet mode, address is dynamic (not stored)\n staticUserAddress = undefined;\n publicClient = createPublicClient({\n chain,\n transport: http(),\n });\n } else {\n throw new InvalidConfigurationError(\n \"Invalid configuration: must provide either walletClient, publicClient + address, or address alone\",\n );\n }\n\n // Store the clients and static address for later use\n this.publicClient = publicClient;\n this.walletClient = walletClient;\n this._staticUserAddress = staticUserAddress;\n\n // Get default service URLs from chain config if not provided\n const chainConfig = getChainConfig(chainToUse.id);\n const subgraphUrl = config.subgraphUrl ?? chainConfig?.subgraphUrl;\n const personalServerUrl =\n config.defaultPersonalServerUrl ?? chainConfig?.personalServerUrl;\n\n // Create shared context for all controllers with dynamic userAddress getter\n const self = this; // Capture VanaCore instance for getter delegation\n const sharedContext: ControllerContext = {\n walletClient,\n publicClient,\n get userAddress() {\n // Delegate to VanaCore's getter for dynamic resolution\n return self.userAddress;\n },\n applicationClient: walletClient, // Using same wallet for now\n relayer: this.relayerCallback,\n downloadRelayer: this.downloadRelayer,\n storageManager: this.storageManager,\n subgraphUrl,\n platform: this.platform, // Pass the platform adapter to controllers\n validateStorageRequired: this.validateStorageRequired.bind(this),\n hasStorage: this.hasStorage.bind(this),\n ipfsGateways: this.ipfsGateways,\n defaultPersonalServerUrl: personalServerUrl,\n waitForTransactionEvents: this.waitForTransactionEvents.bind(this),\n waitForOperation: this.waitForOperation.bind(this),\n operationStore: this.operationStore,\n };\n\n // Initialize controllers\n this.permissions = new PermissionsController(sharedContext);\n this.data = new DataController(sharedContext);\n this.schemas = new SchemaController(sharedContext);\n this.operations = new OperationsController(sharedContext);\n this.server = new ServerController(sharedContext);\n this.protocol = new ProtocolController(sharedContext);\n this.staking = new StakingController(sharedContext);\n }\n\n /**\n * Validates that storage is available for storage-dependent operations.\n * This method enforces the fail-fast principle by checking storage availability\n * at method call time rather than during expensive operations.\n *\n * @throws {InvalidConfigurationError} When storage is required but not configured\n * @example\n * ```typescript\n * // This will throw if storage is not configured\n * vana.validateStorageRequired();\n * await vana.data.uploadFile(file); // Safe to proceed\n * ```\n */\n public validateStorageRequired(): void {\n if (!this.hasRequiredStorage) {\n throw new InvalidConfigurationError(\n \"Storage configuration is required for this operation. \" +\n \"Please configure storage providers in VanaConfig.storage, \" +\n \"provide a relayer configuration, \" +\n \"or pass pre-stored URLs to avoid this dependency. \" +\n \"\\n\\nFor better type safety, consider using VanaCoreFactory.createWithStorage() \" +\n \"with VanaConfigWithStorage to catch this error at compile time.\",\n );\n }\n }\n\n /**\n * Checks whether storage is configured without throwing an error.\n *\n * @returns True if storage is properly configured\n * @example\n * ```typescript\n * if (vana.hasStorage()) {\n * await vana.data.uploadFile(file);\n * } else {\n * console.warn('Storage not configured - using pre-stored URLs only');\n * }\n * ```\n */\n public hasStorage(): boolean {\n return this.hasRequiredStorage;\n }\n\n /**\n * Type guard to check if this instance has storage enabled at compile time.\n * Use this when you need TypeScript to understand that storage is available.\n *\n * @returns True if storage is configured, with type narrowing\n * @example\n * ```typescript\n * if (vana.isStorageEnabled()) {\n * // TypeScript knows storage is available here\n * await vana.data.uploadFile(file);\n * }\n * ```\n */\n public isStorageEnabled(): this is VanaCore & StorageRequiredMarker {\n return this.hasRequiredStorage;\n }\n\n /**\n * Validates the provided configuration object against all requirements.\n *\n * @remarks\n * This method performs comprehensive validation of wallet client configuration,\n * chain configuration, storage providers, and relayer callbacks.\n * @param config - The configuration object to validate\n * @throws {InvalidConfigurationError} When any configuration parameter is invalid\n */\n private validateConfig(config: VanaConfig): void {\n if (!config) {\n throw new InvalidConfigurationError(\"Configuration object is required\");\n }\n\n // Validate storage configuration if provided\n if (config.storage?.providers) {\n if (typeof config.storage.providers !== \"object\") {\n throw new InvalidConfigurationError(\n \"storage.providers must be an object\",\n );\n }\n\n // Validate that all providers have required methods\n for (const [name, provider] of Object.entries(config.storage.providers)) {\n if (!provider || typeof provider !== \"object\") {\n throw new InvalidConfigurationError(\n `Storage provider '${name}' must be a valid StorageProvider object`,\n );\n }\n }\n\n // Validate default provider if specified\n if (config.storage.defaultProvider) {\n if (!(config.storage.defaultProvider in config.storage.providers)) {\n throw new InvalidConfigurationError(\n `Default storage provider '${config.storage.defaultProvider}' not found in providers`,\n );\n }\n }\n }\n\n if (isWalletConfig(config)) {\n // Validate WalletConfig\n if (!config.walletClient) {\n throw new InvalidConfigurationError(\"walletClient is required\");\n }\n\n // Validate that walletClient is actually a WalletClient\n if (\n typeof config.walletClient !== \"object\" ||\n !config.walletClient.signTypedData\n ) {\n throw new InvalidConfigurationError(\n \"walletClient must be a valid viem WalletClient\",\n );\n }\n\n // Validate that wallet client has a chain\n if (!config.walletClient.chain) {\n throw new InvalidConfigurationError(\n \"walletClient must have a chain configured\",\n );\n }\n\n // Validate that the chain is supported\n if (!isVanaChainId(config.walletClient.chain.id)) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${String(config.walletClient.chain.id)}. Supported chains: 14800 (Moksha testnet), 1480 (Vana mainnet)`,\n );\n }\n } else if (isChainConfig(config)) {\n // Validate ChainConfig\n if (!isVanaChainId(config.chainId)) {\n throw new InvalidConfigurationError(\n `Unsupported chain ID: ${String(config.chainId)}. Supported chains: 14800 (Moksha testnet), 1480 (Vana mainnet)`,\n );\n }\n\n // Validate rpcUrl if provided\n if (config.rpcUrl) {\n if (typeof config.rpcUrl !== \"string\") {\n throw new InvalidConfigurationError(\"rpcUrl must be a string\");\n }\n\n if (config.rpcUrl.trim() === \"\") {\n throw new InvalidConfigurationError(\"rpcUrl cannot be empty\");\n }\n\n // Basic URL validation for RPC URL\n try {\n new URL(config.rpcUrl);\n } catch {\n throw new InvalidConfigurationError(\"rpcUrl must be a valid URL\");\n }\n }\n\n // Account is optional for ChainConfig, but if provided, validate it\n if (config.account) {\n if (typeof config.account !== \"object\" || !config.account.address) {\n throw new InvalidConfigurationError(\n \"account must be a valid viem Account object\",\n );\n }\n }\n } else if (isReadOnlyConfig(config)) {\n // Validate read-only config with publicClient and address\n if (!config.publicClient) {\n throw new InvalidConfigurationError(\n \"publicClient is required for read-only configuration\",\n );\n }\n if (!config.address) {\n throw new InvalidConfigurationError(\n \"address is required for read-only configuration\",\n );\n }\n } else if (isAddressOnlyConfig(config)) {\n // Validate address-only config\n if (!config.address) {\n throw new InvalidConfigurationError(\n \"address is required for address-only configuration\",\n );\n }\n // chain is optional, will use default\n } else {\n throw new InvalidConfigurationError(\n \"Invalid configuration: must provide either walletClient, publicClient + address, or address alone\",\n );\n }\n }\n\n /**\n * Gets the current chain ID from the wallet client.\n *\n * @returns The numeric chain ID of the connected network\n * @example\n * ```typescript\n * const chainId = vana.chainId;\n * console.log(`Connected to chain: ${chainId}`); // e.g., \"Connected to chain: 14800\"\n * ```\n */\n get chainId(): number {\n return this.protocol.getChainId();\n }\n\n /**\n * Gets the current chain name from the wallet client.\n *\n * @returns The human-readable name of the connected network\n * @example\n * ```typescript\n * const chainName = vana.chainName;\n * console.log(`Connected to: ${chainName}`); // e.g., \"Connected to: Moksha Testnet\"\n * ```\n */\n get chainName(): string {\n return this.protocol.getChainName();\n }\n\n /**\n * The user's wallet address.\n * In wallet mode, this always returns the current wallet account address.\n * In read-only mode, this returns the static address provided during initialization.\n *\n * @example\n * ```typescript\n * const address = vana.userAddress;\n * console.log(`User address: ${address}`); // e.g., \"User address: 0x742d35...\"\n * ```\n */\n get userAddress(): Address {\n // In wallet mode: dynamically read from wallet\n if (this.walletClient?.account) {\n return extractAddress(this.walletClient.account);\n }\n\n // In read-only mode: use static address\n if (this._staticUserAddress) {\n return this._staticUserAddress;\n }\n\n throw new Error(\"No user address available\");\n }\n\n /**\n * Retrieves comprehensive runtime configuration information.\n *\n * @returns The current runtime configuration including chain, storage, and relayer settings\n * @example\n * ```typescript\n * const config = vana.getConfig();\n * console.log(`Chain: ${config.chainName} (${config.chainId})`);\n * console.log(`Storage providers: ${config.storageProviders.join(\", \")}`);\n * ```\n */\n getConfig(): RuntimeConfig {\n return {\n chainId: this.chainId as VanaChainId,\n chainName: this.chainName,\n relayerConfig: this.relayerConfig,\n storageProviders: this.storageManager?.getStorageProviders() ?? [],\n defaultStorageProvider: this.storageManager?.getDefaultStorageProvider(),\n };\n }\n\n /**\n * Sets the platform adapter for environment-specific operations.\n * This is useful for testing and advanced use cases where you need\n * to override the default platform detection.\n *\n * @param adapter - The platform adapter to use\n * @example\n * ```typescript\n * // For testing with a mock adapter\n * const mockAdapter = new MockPlatformAdapter();\n * vana.setPlatformAdapter(mockAdapter);\n *\n * // For advanced use cases with custom adapters\n * const customAdapter = new CustomPlatformAdapter();\n * vana.setPlatformAdapter(customAdapter);\n * ```\n */\n setPlatformAdapter(adapter: VanaPlatformAdapter): void {\n this.platform = adapter;\n\n // Note: Controllers will use the new platform adapter on their next operation\n // since they access this.platform from the shared context\n }\n\n /**\n * Gets the current platform adapter.\n * This is useful for advanced use cases where you need to access\n * the platform adapter directly.\n *\n * @returns The current platform adapter\n * @example\n * ```typescript\n * const adapter = vana.getPlatformAdapter();\n * const encrypted = await adapter.encrypt(data, key);\n * ```\n */\n getPlatformAdapter(): VanaPlatformAdapter {\n return this.platform;\n }\n\n /**\n * Encrypts data using the Vana protocol standard encryption.\n *\n * @remarks\n * This method implements the Vana network's standard encryption protocol using\n * platform-appropriate cryptographic libraries. It automatically handles different\n * input types (string or Blob) and produces encrypted output suitable for secure\n * storage or transmission. The encryption is compatible with the network's\n * decryption protocols and can be decrypted by authorized parties.\n *\n * @param data - The data to encrypt (string or Blob)\n * @param key - The encryption key (typically generated via `generateEncryptionKey`)\n * @returns The encrypted data as a Blob\n * @throws {Error} When encryption fails due to invalid key or data format\n * @example\n * ```typescript\n * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';\n *\n * // Generate encryption key from wallet signature\n * const encryptionKey = await generateEncryptionKey(vana.walletClient);\n *\n * // Encrypt string data\n * const sensitiveData = \"User's private information\";\n * const encrypted = await vana.encryptBlob(sensitiveData, encryptionKey);\n *\n * // Encrypt file data\n * const fileBlob = new Blob([fileContent], { type: 'application/json' });\n * const encryptedFile = await vana.encryptBlob(fileBlob, encryptionKey);\n *\n * // Store encrypted data safely\n * await storageProvider.upload(encrypted, 'encrypted-data.bin');\n * ```\n */\n public async encryptBlob(data: string | Blob, key: string): Promise<Blob> {\n return encryptBlobWithSignedKey(data, key, this.platform);\n }\n\n /**\n * Decrypts data that was encrypted using the Vana protocol.\n *\n * @remarks\n * This method decrypts data that was previously encrypted using the Vana network's\n * standard encryption protocol. It requires the same wallet signature that was used\n * for encryption and automatically uses the appropriate platform adapter for\n * cryptographic operations. The decrypted output maintains the original data format.\n *\n * @param encryptedData - The encrypted data (string or Blob)\n * @param walletSignature - The wallet signature used as decryption key\n * @returns The decrypted data as a Blob\n * @throws {Error} When decryption fails due to invalid signature or corrupted data\n * @example\n * ```typescript\n * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';\n *\n * // Retrieve encrypted data from storage\n * const encryptedBlob = await storageProvider.download('encrypted-data.bin');\n *\n * // Generate the same key used for encryption\n * const decryptionKey = await generateEncryptionKey(vana.walletClient);\n *\n * // Decrypt the data\n * const decrypted = await vana.decryptBlob(encryptedBlob, decryptionKey);\n *\n * // Convert back to original format\n * const originalText = await decrypted.text();\n * const originalJson = JSON.parse(originalText);\n *\n * console.log('Decrypted data:', originalJson);\n * ```\n *\n * @example\n * ```typescript\n * // Decrypt file downloaded from Vana network\n * const userFiles = await vana.data.getUserFiles();\n * const file = userFiles[0];\n *\n * // Download encrypted content\n * const encrypted = await fetch(file.url).then(r => r.blob());\n *\n * // Decrypt with user's key\n * const decryptionKey = await generateEncryptionKey(vana.walletClient);\n * const decrypted = await vana.decryptBlob(encrypted, decryptionKey);\n *\n * // Process original data\n * const fileContent = await decrypted.arrayBuffer();\n * ```\n */\n public async decryptBlob(\n encryptedData: string | Blob,\n walletSignature: string,\n ): Promise<Blob> {\n return decryptBlobWithSignedKey(\n encryptedData,\n walletSignature,\n this.platform,\n );\n }\n\n /**\n * Waits for an operation to complete and returns the final result.\n *\n * @remarks\n * This method polls the operation status at regular intervals until it\n * reaches a terminal state (succeeded, failed, or canceled). Supports\n * ergonomic overloads to accept either an Operation object or just the ID.\n *\n * @param opOrId - Either an Operation object or operation ID string\n * @param options - Optional polling configuration\n * @returns The completed operation with result or error\n * @throws {PersonalServerError} When the operation fails or times out\n * @example\n * ```typescript\n * // Using operation object\n * const operation = await vana.server.createOperation({ permissionId: 123 });\n * const completed = await vana.waitForOperation(operation);\n *\n * // Using just the ID\n * const completed = await vana.waitForOperation(\"op_abc123\");\n *\n * // With custom timeout\n * const completed = await vana.waitForOperation(operation, {\n * timeout: 60000,\n * pollingInterval: 1000\n * });\n * ```\n */\n public async waitForOperation(\n opOrId: Operation | string,\n options?: PollingOptions,\n ): Promise<Operation> {\n return this.server.waitForOperation(opOrId, options);\n }\n\n /**\n * Waits for a transaction to be confirmed and returns the receipt.\n *\n * @remarks\n * This method polls for transaction confirmation on the blockchain.\n * Supports ergonomic overloads to accept either a transaction result\n * object or just the hash string.\n *\n * @param hashOrObj - Either a TransactionResult object or hash string\n * @param options - Optional wait configuration\n * @returns The transaction receipt with logs and status\n * @example\n * ```typescript\n * // Using transaction result object\n * const tx = await vana.permissions.grant(params);\n * const receipt = await vana.waitForTransactionReceipt(tx);\n *\n * // Using just the hash\n * const receipt = await vana.waitForTransactionReceipt(\"0x123...\");\n *\n * // With custom confirmations\n * const receipt = await vana.waitForTransactionReceipt(tx, {\n * confirmations: 3,\n * timeout: 60000\n * });\n * ```\n */\n public async waitForTransactionReceipt(\n hashOrObj: TransactionResult | { hash: Hash } | Hash,\n options?: TransactionWaitOptions,\n ): Promise<TransactionReceipt> {\n const hash = typeof hashOrObj === \"string\" ? hashOrObj : hashOrObj.hash;\n\n return this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: options?.confirmations,\n pollingInterval: options?.pollingInterval,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Waits for transaction confirmation and extracts blockchain event data.\n *\n * @remarks\n * This method leverages the context-carrying POJO architecture. When passed a\n * `TransactionResult` with an `operation` field, it automatically parses the\n * correct events from the transaction logs. For legacy compatibility, it accepts\n * raw hashes but will not parse events without operation context.\n *\n * @param transaction - Transaction result with operation context\n * @param options - Optional confirmation and timeout settings\n * @returns Parsed event data specific to the transaction's operation type\n * @throws {NetworkError} When transaction confirmation times out\n * @throws {BlockchainError} When expected events are not found in the transaction\n *\n * @example\n * ```typescript\n * // Recommended: Pass the transaction result for automatic event parsing\n * const tx = await vana.permissions.submitAddServerFilesAndPermissions(params);\n * const events = await vana.waitForTransactionEvents<{ permissionId: bigint }>(tx);\n * console.log(`Permission ID: ${events.permissionId}`);\n *\n * // Legacy: Raw hash without event parsing (returns receipt)\n * const receipt = await vana.waitForTransactionEvents(\"0x123...\");\n * ```\n *\n * @see For understanding transaction flows, visit https://docs.vana.org/docs/transactions\n */\n public async waitForTransactionEvents<C extends Contract, F extends Fn<C>>(\n transaction: TransactionResult<C, F>,\n options?: TransactionWaitOptions,\n ): Promise<TypedTransactionResult<C, F>> {\n // Import the POJO-based parser\n const { parseTransaction } = await import(\"./utils/parseTransactionPojo\");\n\n // Wait for the transaction to be mined\n const receipt = await this.waitForTransactionReceipt(\n transaction.hash,\n options,\n );\n\n // Parse events using our heuristic-free POJO system\n const result = parseTransaction(transaction, receipt);\n\n // Return the strongly-typed result\n // TypeScript knows exactly what events are possible!\n return result;\n }\n\n /**\n * Enhances a unified relayer response with client-side behavior.\n *\n * @remarks\n * This method wraps a relayer response in an enhanced object that provides\n * a fluent `.wait()` method for handling asynchronous operations. The enhanced\n * response intelligently handles both submitted transactions (via hash) and\n * pending operations (via operationId).\n *\n * @param response - The unified relayer response to enhance\n * @returns EnhancedTransactionResponse if the response can be enhanced, null otherwise\n *\n * @example\n * ```typescript\n * // Enhance a relayer response for fluent waiting\n * const response = await handleRelayerOperation(vana, request);\n * const enhanced = vana.enhanceRelayerResponse(response);\n * if (enhanced) {\n * const result = await enhanced.wait();\n * if (result.expectedEvents?.FileAdded) {\n * console.log('File ID:', result.expectedEvents.FileAdded.fileId);\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With status updates for pending operations\n * const enhanced = vana.enhanceRelayerResponse(response);\n * if (enhanced) {\n * const result = await enhanced.wait({\n * onStatusUpdate: (status) => {\n * console.log('Operation status:', status.type);\n * },\n * timeout: 60000 // 1 minute timeout\n * });\n * }\n * ```\n *\n * @category Relayer\n * @since 0.2.0\n */\n public async enhanceRelayerResponse(\n response: UnifiedRelayerResponse,\n ): Promise<any> {\n const { enhanceResponse } = await import(\"./client/enhancedResponse\");\n return enhanceResponse(response, this);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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,MAAM,KAAK;AAAA,MACzB,YAAY;AAAA,MACZ;AAAA,IACF;AAGA,UAAM,SAAS,iBAAiB,aAAa,OAAO;AAIpD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA4CA,MAAa,uBACX,UACc;AACd,UAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,2BAA2B;AACpE,WAAO,gBAAgB,UAAU,IAAI;AAAA,EACvC;AACF;","names":["import_chains"]}
package/dist/core.d.ts CHANGED
@@ -6,6 +6,7 @@ import { SchemaController } from "./controllers/schemas";
6
6
  import { ServerController } from "./controllers/server";
7
7
  import { ProtocolController } from "./controllers/protocol";
8
8
  import { OperationsController } from "./controllers/operations";
9
+ import { StakingController } from "./controllers/staking";
9
10
  import type { PublicClient, Address, Hash, TransactionReceipt } from "viem";
10
11
  import type { Operation, PollingOptions, TransactionResult, TransactionWaitOptions } from "./types/operations";
11
12
  import type { IOperationStore, IRelayerStateStore } from "./types/operationStore";
@@ -110,6 +111,8 @@ export declare class VanaCore {
110
111
  readonly server: ServerController;
111
112
  /** Offers low-level access to Vana protocol smart contracts. */
112
113
  readonly protocol: ProtocolController;
114
+ /** Provides VanaPool staking information and operations. */
115
+ readonly staking: StakingController;
113
116
  /** Handles environment-specific operations like encryption and file systems. */
114
117
  protected platform: VanaPlatformAdapter;
115
118
  private readonly relayerConfig?;
package/dist/core.js CHANGED
@@ -13,6 +13,7 @@ import { SchemaController } from "./controllers/schemas";
13
13
  import { ServerController } from "./controllers/server";
14
14
  import { ProtocolController } from "./controllers/protocol";
15
15
  import { OperationsController } from "./controllers/operations";
16
+ import { StakingController } from "./controllers/staking";
16
17
  import { StorageManager } from "./storage";
17
18
  import { createWalletClient, createPublicClient, http } from "viem";
18
19
  import { extractAddress } from "./utils/wallet";
@@ -76,6 +77,8 @@ class VanaCore {
76
77
  server;
77
78
  /** Offers low-level access to Vana protocol smart contracts. */
78
79
  protocol;
80
+ /** Provides VanaPool staking information and operations. */
81
+ staking;
79
82
  /** Handles environment-specific operations like encryption and file systems. */
80
83
  platform;
81
84
  relayerConfig;
@@ -245,6 +248,7 @@ class VanaCore {
245
248
  this.operations = new OperationsController(sharedContext);
246
249
  this.server = new ServerController(sharedContext);
247
250
  this.protocol = new ProtocolController(sharedContext);
251
+ this.staking = new StakingController(sharedContext);
248
252
  }
249
253
  /**
250
254
  * Validates that storage is available for storage-dependent operations.