Vana SDK - v2.2.2
    Preparing search index...

    Class VanaBrowserImpl

    Internal implementation class for browser environments. This class is not exported directly - use the Vana factory function instead.

    Hierarchy (View Summary)

    Index

    Properties

    Manages gasless data access permissions and trusted server registry.

    Handles user data file operations.

    Manages data schemas and refiners.

    Manages asynchronous operation recovery and status checking.

    Provides personal server setup and trusted server interactions.

    Offers low-level access to Vana protocol smart contracts.

    Accessors

    • get chainId(): number

      Gets the current chain ID from the wallet client.

      Returns number

      The numeric chain ID of the connected network

      const chainId = vana.chainId;
      console.log(`Connected to chain: ${chainId}`); // e.g., "Connected to chain: 14800"
    • get chainName(): string

      Gets the current chain name from the wallet client.

      Returns string

      The human-readable name of the connected network

      const chainName = vana.chainName;
      console.log(`Connected to: ${chainName}`); // e.g., "Connected to: Moksha Testnet"
    • get userAddress(): `0x${string}`

      The user's wallet address. In wallet mode, this always returns the current wallet account address. In read-only mode, this returns the static address provided during initialization.

      Returns `0x${string}`

      const address = vana.userAddress;
      console.log(`User address: ${address}`); // e.g., "User address: 0x742d35..."

    Methods - Reference

    • Validates that storage is available for storage-dependent operations. This method enforces the fail-fast principle by checking storage availability at method call time rather than during expensive operations.

      Returns void

      When storage is required but not configured

      // This will throw if storage is not configured
      vana.validateStorageRequired();
      await vana.data.uploadFile(file); // Safe to proceed
    • Checks whether storage is configured without throwing an error.

      Returns boolean

      True if storage is properly configured

      if (vana.hasStorage()) {
      await vana.data.uploadFile(file);
      } else {
      console.warn('Storage not configured - using pre-stored URLs only');
      }
    • Retrieves comprehensive runtime configuration information.

      Returns RuntimeConfig

      The current runtime configuration including chain, storage, and relayer settings

      const config = vana.getConfig();
      console.log(`Chain: ${config.chainName} (${config.chainId})`);
      console.log(`Storage providers: ${config.storageProviders.join(", ")}`);
    • Sets the platform adapter for environment-specific operations. This is useful for testing and advanced use cases where you need to override the default platform detection.

      Parameters

      Returns void

      // For testing with a mock adapter
      const mockAdapter = new MockPlatformAdapter();
      vana.setPlatformAdapter(mockAdapter);

      // For advanced use cases with custom adapters
      const customAdapter = new CustomPlatformAdapter();
      vana.setPlatformAdapter(customAdapter);
    • Encrypts data using the Vana protocol standard encryption.

      Parameters

      • data: string | Blob

        The data to encrypt (string or Blob)

      • key: string

        The encryption key (typically generated via generateEncryptionKey)

      Returns Promise<Blob>

      The encrypted data as a Blob

      This method implements the Vana network's standard encryption protocol using platform-appropriate cryptographic libraries. It automatically handles different input types (string or Blob) and produces encrypted output suitable for secure storage or transmission. The encryption is compatible with the network's decryption protocols and can be decrypted by authorized parties.

      When encryption fails due to invalid key or data format

      import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';

      // Generate encryption key from wallet signature
      const encryptionKey = await generateEncryptionKey(vana.walletClient);

      // Encrypt string data
      const sensitiveData = "User's private information";
      const encrypted = await vana.encryptBlob(sensitiveData, encryptionKey);

      // Encrypt file data
      const fileBlob = new Blob([fileContent], { type: 'application/json' });
      const encryptedFile = await vana.encryptBlob(fileBlob, encryptionKey);

      // Store encrypted data safely
      await storageProvider.upload(encrypted, 'encrypted-data.bin');
    • Decrypts data that was encrypted using the Vana protocol.

      Parameters

      • encryptedData: string | Blob

        The encrypted data (string or Blob)

      • walletSignature: string

        The wallet signature used as decryption key

      Returns Promise<Blob>

      The decrypted data as a Blob

      This method decrypts data that was previously encrypted using the Vana network's standard encryption protocol. It requires the same wallet signature that was used for encryption and automatically uses the appropriate platform adapter for cryptographic operations. The decrypted output maintains the original data format.

      When decryption fails due to invalid signature or corrupted data

      import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';

      // Retrieve encrypted data from storage
      const encryptedBlob = await storageProvider.download('encrypted-data.bin');

      // Generate the same key used for encryption
      const decryptionKey = await generateEncryptionKey(vana.walletClient);

      // Decrypt the data
      const decrypted = await vana.decryptBlob(encryptedBlob, decryptionKey);

      // Convert back to original format
      const originalText = await decrypted.text();
      const originalJson = JSON.parse(originalText);

      console.log('Decrypted data:', originalJson);
      // Decrypt file downloaded from Vana network
      const userFiles = await vana.data.getUserFiles();
      const file = userFiles[0];

      // Download encrypted content
      const encrypted = await fetch(file.url).then(r => r.blob());

      // Decrypt with user's key
      const decryptionKey = await generateEncryptionKey(vana.walletClient);
      const decrypted = await vana.decryptBlob(encrypted, decryptionKey);

      // Process original data
      const fileContent = await decrypted.arrayBuffer();
    • Waits for an operation to complete and returns the final result.

      Parameters

      • opOrId:
            | string
            | {
                kind: "OperationStatus";
                id: string;
                status: "starting"
                | "processing"
                | "succeeded"
                | "failed"
                | "canceled";
                started_at?: string | null;
                finished_at?: string | null;
                result?: { [key: string]: unknown } | null;
            }

        Either an Operation object or operation ID string

        • string
        • {
              kind: "OperationStatus";
              id: string;
              status: "starting" | "processing" | "succeeded" | "failed" | "canceled";
              started_at?: string | null;
              finished_at?: string | null;
              result?: { [key: string]: unknown } | null;
          }
          • kind: "OperationStatus"

            Kind

            Resource type identifier for response routing

            OperationStatus
            
            OperationStatus
            
          • id: string

            Id

            Unique operation identifier

            cm4xp9qkw0001qj0g8xqg8xqg
            
          • status: "starting" | "processing" | "succeeded" | "failed" | "canceled"

            Status

            Current operation status. Transitions: starting → processing → (succeeded|failed|canceled)

            processing
            @enum {string}
          • Optionalstarted_at?: string | null

            Started At

            ISO 8601 timestamp when operation began processing

            2024-01-01T00:00:01Z
            
          • Optionalfinished_at?: string | null

            Finished At

            ISO 8601 timestamp when operation completed (succeeded, failed, or canceled)

            2024-01-01T00:00:05Z
            
          • Optionalresult?: { [key: string]: unknown } | null

            Result

            Operation result data as a dictionary. Format depends on operation type. For LLM inference: {'output': 'generated text'} or parsed JSON object. For JSON mode: parsed JSON object structure.

            {
            * "output": "The analysis of your data indicates positive trends in engagement metrics..."
            * }
      • Optionaloptions: PollingOptions

        Optional polling configuration

      Returns Promise<
          {
              kind: "OperationStatus";
              id: string;
              status: "starting"
              | "processing"
              | "succeeded"
              | "failed"
              | "canceled";
              started_at?: string | null;
              finished_at?: string | null;
              result?: { [key: string]: unknown } | null;
          },
      >

      The completed operation with result or error

      This method polls the operation status at regular intervals until it reaches a terminal state (succeeded, failed, or canceled). Supports ergonomic overloads to accept either an Operation object or just the ID.

      When the operation fails or times out

      // Using operation object
      const operation = await vana.server.createOperation({ permissionId: 123 });
      const completed = await vana.waitForOperation(operation);

      // Using just the ID
      const completed = await vana.waitForOperation("op_abc123");

      // With custom timeout
      const completed = await vana.waitForOperation(operation, {
      timeout: 60000,
      pollingInterval: 1000
      });
    • Waits for a transaction to be confirmed and returns the receipt.

      Parameters

      • hashOrObj:
            | `0x${string}`
            | TransactionResult<
                Contract,
                | "deposit"
                | "grantRole"
                | "initialize"
                | "pause"
                | "registerJob"
                | "renounceRole"
                | "revokeRole"
                | "unpause"
                | "updateJobStatus"
                | "upgradeToAndCall"
                | "withdraw"
                | "addComputeInstruction"
                | "updateComputeInstruction"
                | "approve"
                | "blockAddress"
                | "burn"
                | "mint"
                | "transfer"
                | "transferFrom"
                | "unblockAddress"
                | "createDAT"
                | "createToken"
                | "updateDATTemplate"
                | "updateFactoryFee"
                | "delegate"
                | "delegateBySig"
                | "overrideEpochDlpPenalty"
                | "overrideEpochPerformances"
                | "saveEpochPerformances"
                | "updateMetricWeights"
                | "deregisterDlp"
                | "migrateDlpData"
                | "registerDlp"
                | "unverifyDlp"
                | "updateDlp"
                | "updateDlpRegistrationDepositAmount"
                | "updateDlpToken"
                | "updateDlpTokenAndVerification"
                | "updateDlpVerificationBlock"
                | "allocateFunds"
                | "updateBudget"
                | "distributeRewards"
                | "withdrawEpochDlpPenaltyAmount"
                | "allocateRewards"
                | "updateAllocation"
                | "addLiquidity"
                | "removeLiquidity"
                | "splitRewardSwap"
                | "swap"
                | "updateSwapFee"
                | "addPermissionToGrantee"
                | "registerGrantee"
                | "removePermissionFromGrantee"
                | "addPermission"
                | "addServerFilesAndPermissions"
                | "revokePermission"
                | "revokePermissionWithSignature"
                | "addAndTrustServerByManager"
                | "addAndTrustServerWithSignature"
                | "addServerWithSignature"
                | "trustServer"
                | "trustServerByManager"
                | "trustServerWithSignature"
                | "untrustServer"
                | "untrustServerByManager"
                | "untrustServerWithSignature"
                | "updateServer"
                | "addRefinementService"
                | "addRefiner"
                | "addRefinerWithSchemaId"
                | "addSchema"
                | "removeRefinementService"
                | "updateDlpRefinersOwner"
                | "updateRefinerOwner"
                | "updateSchemaId"
                | "addFile"
                | "addFilePermission"
                | "addFilePermissionsAndSchema"
                | "addFileWithPermissions"
                | "addFileWithPermissionsAndSchema"
                | "addFileWithSchema"
                | "addFileWithSignature"
                | "addProof"
                | "addRefinementWithPermission"
                | "cacheResult"
                | "claimDlpPayment"
                | "executeQuery"
                | "invalidateCache"
                | "updatePermissionApproval"
                | "updateQueryLimit"
                | "getQuote"
                | "updateRouter"
                | "updateSlippage"
                | "addJob"
                | "cancelJob"
                | "claimReward"
                | "submitProof"
                | "updateFeeRecipient"
                | "updateJobTimeout"
                | "updateMinJobDuration"
                | "addTee"
                | "removeJob"
                | "removeTee"
                | "submitJob"
                | "requestContributionProof"
                | "forceFinalizedEpoch"
                | "overrideEpochDlpReward"
                | "saveEpochDlpRewards"
                | "updateDaySize"
                | "updateEpoch"
                | "updateEpochRewardAmount"
                | "updateEpochSize"
                | "addRewards"
                | "createEntity"
                | "processRewards"
                | "updateEntity"
                | "updateEntityMaxAPY"
                | "claimRewards"
                | "registerEntityStake"
                | "stake"
                | "unstake"
                | "updateMinStakeAmount"
                | "updateTreasuryAddress",
            >
            | { hash: `0x${string}` }

        Either a TransactionResult object or hash string

      • Optionaloptions: TransactionWaitOptions

        Optional wait configuration

      Returns Promise<TransactionReceipt>

      The transaction receipt with logs and status

      This method polls for transaction confirmation on the blockchain. Supports ergonomic overloads to accept either a transaction result object or just the hash string.

      // Using transaction result object
      const tx = await vana.permissions.grant(params);
      const receipt = await vana.waitForTransactionReceipt(tx);

      // Using just the hash
      const receipt = await vana.waitForTransactionReceipt("0x123...");

      // With custom confirmations
      const receipt = await vana.waitForTransactionReceipt(tx, {
      confirmations: 3,
      timeout: 60000
      });
    • Waits for transaction confirmation and extracts blockchain event data.

      Type Parameters

      • C extends Contract
      • F extends
            | "deposit"
            | "grantRole"
            | "initialize"
            | "pause"
            | "registerJob"
            | "renounceRole"
            | "revokeRole"
            | "unpause"
            | "updateJobStatus"
            | "upgradeToAndCall"
            | "withdraw"
            | "addComputeInstruction"
            | "updateComputeInstruction"
            | "approve"
            | "blockAddress"
            | "burn"
            | "mint"
            | "transfer"
            | "transferFrom"
            | "unblockAddress"
            | "createDAT"
            | "createToken"
            | "updateDATTemplate"
            | "updateFactoryFee"
            | "delegate"
            | "delegateBySig"
            | "overrideEpochDlpPenalty"
            | "overrideEpochPerformances"
            | "saveEpochPerformances"
            | "updateMetricWeights"
            | "deregisterDlp"
            | "migrateDlpData"
            | "registerDlp"
            | "unverifyDlp"
            | "updateDlp"
            | "updateDlpRegistrationDepositAmount"
            | "updateDlpToken"
            | "updateDlpTokenAndVerification"
            | "updateDlpVerificationBlock"
            | "allocateFunds"
            | "updateBudget"
            | "distributeRewards"
            | "withdrawEpochDlpPenaltyAmount"
            | "allocateRewards"
            | "updateAllocation"
            | "addLiquidity"
            | "removeLiquidity"
            | "splitRewardSwap"
            | "swap"
            | "updateSwapFee"
            | "addPermissionToGrantee"
            | "registerGrantee"
            | "removePermissionFromGrantee"
            | "addPermission"
            | "addServerFilesAndPermissions"
            | "revokePermission"
            | "revokePermissionWithSignature"
            | "addAndTrustServerByManager"
            | "addAndTrustServerWithSignature"
            | "addServerWithSignature"
            | "trustServer"
            | "trustServerByManager"
            | "trustServerWithSignature"
            | "untrustServer"
            | "untrustServerByManager"
            | "untrustServerWithSignature"
            | "updateServer"
            | "addRefinementService"
            | "addRefiner"
            | "addRefinerWithSchemaId"
            | "addSchema"
            | "removeRefinementService"
            | "updateDlpRefinersOwner"
            | "updateRefinerOwner"
            | "updateSchemaId"
            | "addFile"
            | "addFilePermission"
            | "addFilePermissionsAndSchema"
            | "addFileWithPermissions"
            | "addFileWithPermissionsAndSchema"
            | "addFileWithSchema"
            | "addFileWithSignature"
            | "addProof"
            | "addRefinementWithPermission"
            | "cacheResult"
            | "claimDlpPayment"
            | "executeQuery"
            | "invalidateCache"
            | "updatePermissionApproval"
            | "updateQueryLimit"
            | "getQuote"
            | "updateRouter"
            | "updateSlippage"
            | "addJob"
            | "cancelJob"
            | "claimReward"
            | "submitProof"
            | "updateFeeRecipient"
            | "updateJobTimeout"
            | "updateMinJobDuration"
            | "addTee"
            | "removeJob"
            | "removeTee"
            | "submitJob"
            | "requestContributionProof"
            | "forceFinalizedEpoch"
            | "overrideEpochDlpReward"
            | "saveEpochDlpRewards"
            | "updateDaySize"
            | "updateEpoch"
            | "updateEpochRewardAmount"
            | "updateEpochSize"
            | "addRewards"
            | "createEntity"
            | "processRewards"
            | "updateEntity"
            | "updateEntityMaxAPY"
            | "claimRewards"
            | "registerEntityStake"
            | "stake"
            | "unstake"
            | "updateMinStakeAmount"
            | "updateTreasuryAddress"

      Parameters

      Returns Promise<TypedTransactionResult<C, F>>

      Parsed event data specific to the transaction's operation type

      This method leverages the context-carrying POJO architecture. When passed a TransactionResult with an operation field, it automatically parses the correct events from the transaction logs. For legacy compatibility, it accepts raw hashes but will not parse events without operation context.

      When transaction confirmation times out

      When expected events are not found in the transaction

      // Recommended: Pass the transaction result for automatic event parsing
      const tx = await vana.permissions.submitAddServerFilesAndPermissions(params);
      const events = await vana.waitForTransactionEvents<{ permissionId: bigint }>(tx);
      console.log(`Permission ID: ${events.permissionId}`);

      // Legacy: Raw hash without event parsing (returns receipt)
      const receipt = await vana.waitForTransactionEvents("0x123...");

      For understanding transaction flows, visit https://docs.vana.org/docs/transactions

    Methods - Relayer

    • Enhances a unified relayer response with client-side behavior.

      Parameters

      Returns Promise<any>

      EnhancedTransactionResponse if the response can be enhanced, null otherwise

      This method wraps a relayer response in an enhanced object that provides a fluent .wait() method for handling asynchronous operations. The enhanced response intelligently handles both submitted transactions (via hash) and pending operations (via operationId).

      // Enhance a relayer response for fluent waiting
      const response = await handleRelayerOperation(vana, request);
      const enhanced = vana.enhanceRelayerResponse(response);
      if (enhanced) {
      const result = await enhanced.wait();
      if (result.expectedEvents?.FileAdded) {
      console.log('File ID:', result.expectedEvents.FileAdded.fileId);
      }
      }
      // With status updates for pending operations
      const enhanced = vana.enhanceRelayerResponse(response);
      if (enhanced) {
      const result = await enhanced.wait({
      onStatusUpdate: (status) => {
      console.log('Operation status:', status.type);
      },
      timeout: 60000 // 1 minute timeout
      });
      }

      0.2.0