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

    Class DataController

    Manages encrypted user data files and blockchain registration on the Vana network.

    The DataController provides comprehensive file lifecycle management from encrypted upload through blockchain registration to decryption. Client-side encryption ensures data privacy before transmission. The controller integrates with multiple storage providers (IPFS, Pinata, Google Drive) and supports both gasless transactions via relayers and direct blockchain interaction.

    Architecture: Files use dual storage: encrypted content on decentralized storage (IPFS/Pinata/Google Drive), metadata and permissions on blockchain. This design minimizes on-chain data while maintaining decentralization and access control.

    Method Selection:

    • upload() - Complete workflow: encryption, storage, blockchain registration
    • getUserFiles() - Query file metadata from blockchain/subgraph
    • decryptFile() - Decrypt files you have permission to access
    • getFileById() - Retrieve specific file metadata by ID

    Storage Requirements:

    • Methods requiring storage: upload(), encryptFile()
    • Methods working without storage: getUserFiles(), decryptFile(), getFileById()

    Permission Model:

    • File permissions (decryption access) are handled during upload
    • Operation permissions (what can be done with data) use vana.permissions.grant()
    // Upload encrypted file with schema validation
    const result = await vana.data.upload({
    content: { name: "Alice", age: 30 },
    filename: "profile.json",
    schemaId: 1
    });
    console.log(`File uploaded: ID ${result.fileId}, URL ${result.url}`);

    // Query user's files
    const files = await vana.data.getUserFiles({
    owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
    });
    files.forEach(file => console.log(`File ${file.id}: ${file.url}`));

    // Decrypt accessible file
    const decryptedData = await vana.data.decryptFile(files[0]);
    console.log("Decrypted content:", decryptedData);

    For conceptual overview, visit https://docs.vana.org/docs/data-registry

    Hierarchy

    • BaseController
      • DataController
    Index

    Methods

    • Uploads data with automatic encryption and blockchain registration.

      Parameters

      • params: EncryptedUploadParams

        Upload configuration object

        Upload parameters with encryption enabled.

        • content: string | Blob | Buffer<ArrayBufferLike>

          Raw file data as string, Blob, or Buffer.

        • Optionalfilename?: string

          Optional filename for the uploaded file.

        • OptionalschemaId?: number

          Optional schema ID for data validation.

        • OptionalproviderName?: string

          Optional storage provider name.

        • Optionalowner?: `0x${string}`

          Optional owner address (defaults to current wallet address).

        • OptionalschemaValidation?: "strict" | "warn" | "skip"

          Schema validation mode when schemaId is provided:

          • 'strict': Throw error on validation failure (default)
          • 'warn': Log warning and continue on validation failure
          • 'skip': Skip validation entirely
        • Optionalpermissions?: FilePermissionParams[]

          File permissions with required public keys for encrypted data sharing.

        • encrypt: true

          Encryption is enabled.

      Returns Promise<UploadResult>

      Upload result with file ID, URL, and transaction hash

      Primary method for uploading data to Vana. Handles complete workflow: content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      Automatic Processing:

      • Normalizes content to Blob format
      • Validates against schema if provided
      • Generates encryption keys
      • Uploads to configured storage
      • Grants decryption permissions
      • Registers on blockchain

      TypeScript Overloads:

      • EncryptedUploadParams: When encrypt: true (default), permissions require publicKey
      • UnencryptedUploadParams: When encrypt: false, permissions optional
      • UploadParams: General signature for runtime determination

      Permission Separation:

      • File permissions (here): Decryption access only
      • Operation permissions: Use vana.permissions.grant() separately

      Owner/Encryption Constraint: When encryption is enabled (default), the owner parameter must match the connected wallet address. This ensures only the wallet that performs encryption can decrypt the file. For delegation scenarios where the owner differs from the connected wallet, set encrypt: false.

      When encryption is enabled and owner differs from wallet. Set encrypt: false for delegation scenarios, or omit owner to use connected wallet.

      Storage not configured. Configure storage providers in VanaConfig.

      No wallet addresses available. Ensure wallet is connected.

      Data doesn't match schema. Verify data structure matches schema from vana.schemas.get(schemaId).

      Upload failed with specific error message.

      // Basic file upload
      const result = await vana.data.upload({
      content: "My personal data",
      filename: "diary.txt"
      });

      // Upload with schema validation
      const result = await vana.data.upload({
      content: { name: "John", age: 30 },
      filename: "profile.json",
      schemaId: 1
      });

      // Upload with file permissions (for decryption access)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      account: "0x1234...", // Server address that can decrypt
      publicKey: "0x04..." // Server's public key for encryption
      }]
      });

      // After upload, grant operation permissions separately:
      // await vana.permissions.grant({
      // grantee: "0x1234...",
      // fileIds: [result.fileId],
      // operation: "llm_inference",
      // parameters: { model: "gpt-4" }
      // });

      // Upload without encryption (public data)
      // Note: Cast to UnencryptedUploadParams for TypeScript
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false
      } as const); // 'as const' ensures TypeScript infers encrypt: false literally

      // Upload on behalf of another user (delegation without encryption)
      const result = await vana.data.upload({
      content: "User's data",
      filename: "delegated.txt",
      owner: "0x5678...", // Different from connected wallet
      encrypt: false // Required when owner differs from wallet
      });
    • Uploads data with automatic encryption and blockchain registration.

      Parameters

      • params: UnencryptedUploadParams

        Upload configuration object

        Upload parameters with encryption disabled.

        • content: string | Blob | Buffer<ArrayBufferLike>

          Raw file data as string, Blob, or Buffer.

        • Optionalfilename?: string

          Optional filename for the uploaded file.

        • OptionalschemaId?: number

          Optional schema ID for data validation.

        • Optionalpermissions?: FilePermissionParams[]

          Optional file permissions to grant decryption access during upload.

        • OptionalproviderName?: string

          Optional storage provider name.

        • Optionalowner?: `0x${string}`

          Optional owner address (defaults to current wallet address).

        • OptionalschemaValidation?: "strict" | "warn" | "skip"

          Schema validation mode when schemaId is provided:

          • 'strict': Throw error on validation failure (default)
          • 'warn': Log warning and continue on validation failure
          • 'skip': Skip validation entirely
        • encrypt: false

          Encryption is disabled.

      Returns Promise<UploadResult>

      Upload result with file ID, URL, and transaction hash

      Primary method for uploading data to Vana. Handles complete workflow: content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      Automatic Processing:

      • Normalizes content to Blob format
      • Validates against schema if provided
      • Generates encryption keys
      • Uploads to configured storage
      • Grants decryption permissions
      • Registers on blockchain

      TypeScript Overloads:

      • EncryptedUploadParams: When encrypt: true (default), permissions require publicKey
      • UnencryptedUploadParams: When encrypt: false, permissions optional
      • UploadParams: General signature for runtime determination

      Permission Separation:

      • File permissions (here): Decryption access only
      • Operation permissions: Use vana.permissions.grant() separately

      Owner/Encryption Constraint: When encryption is enabled (default), the owner parameter must match the connected wallet address. This ensures only the wallet that performs encryption can decrypt the file. For delegation scenarios where the owner differs from the connected wallet, set encrypt: false.

      When encryption is enabled and owner differs from wallet. Set encrypt: false for delegation scenarios, or omit owner to use connected wallet.

      Storage not configured. Configure storage providers in VanaConfig.

      No wallet addresses available. Ensure wallet is connected.

      Data doesn't match schema. Verify data structure matches schema from vana.schemas.get(schemaId).

      Upload failed with specific error message.

      // Basic file upload
      const result = await vana.data.upload({
      content: "My personal data",
      filename: "diary.txt"
      });

      // Upload with schema validation
      const result = await vana.data.upload({
      content: { name: "John", age: 30 },
      filename: "profile.json",
      schemaId: 1
      });

      // Upload with file permissions (for decryption access)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      account: "0x1234...", // Server address that can decrypt
      publicKey: "0x04..." // Server's public key for encryption
      }]
      });

      // After upload, grant operation permissions separately:
      // await vana.permissions.grant({
      // grantee: "0x1234...",
      // fileIds: [result.fileId],
      // operation: "llm_inference",
      // parameters: { model: "gpt-4" }
      // });

      // Upload without encryption (public data)
      // Note: Cast to UnencryptedUploadParams for TypeScript
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false
      } as const); // 'as const' ensures TypeScript infers encrypt: false literally

      // Upload on behalf of another user (delegation without encryption)
      const result = await vana.data.upload({
      content: "User's data",
      filename: "delegated.txt",
      owner: "0x5678...", // Different from connected wallet
      encrypt: false // Required when owner differs from wallet
      });
    • Uploads data with automatic encryption and blockchain registration.

      Parameters

      • params: UploadParams

        Upload configuration object

        High-level parameters for uploading user data with automatic encryption and blockchain registration.

        • content: string | Blob | Buffer<ArrayBufferLike>

          Raw file data as string, Blob, or Buffer.

        • Optionalfilename?: string

          Optional filename for the uploaded file.

        • OptionalschemaId?: number

          Optional schema ID for data validation.

        • Optionalpermissions?: FilePermissionParams[]

          Optional file permissions to grant decryption access during upload.

        • Optionalencrypt?: boolean

          Whether to encrypt the data (defaults to true).

        • OptionalproviderName?: string

          Optional storage provider name.

        • Optionalowner?: `0x${string}`

          Optional owner address (defaults to current wallet address).

        • OptionalschemaValidation?: "strict" | "warn" | "skip"

          Schema validation mode when schemaId is provided:

          • 'strict': Throw error on validation failure (default)
          • 'warn': Log warning and continue on validation failure
          • 'skip': Skip validation entirely

      Returns Promise<UploadResult>

      Upload result with file ID, URL, and transaction hash

      Primary method for uploading data to Vana. Handles complete workflow: content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      Automatic Processing:

      • Normalizes content to Blob format
      • Validates against schema if provided
      • Generates encryption keys
      • Uploads to configured storage
      • Grants decryption permissions
      • Registers on blockchain

      TypeScript Overloads:

      • EncryptedUploadParams: When encrypt: true (default), permissions require publicKey
      • UnencryptedUploadParams: When encrypt: false, permissions optional
      • UploadParams: General signature for runtime determination

      Permission Separation:

      • File permissions (here): Decryption access only
      • Operation permissions: Use vana.permissions.grant() separately

      Owner/Encryption Constraint: When encryption is enabled (default), the owner parameter must match the connected wallet address. This ensures only the wallet that performs encryption can decrypt the file. For delegation scenarios where the owner differs from the connected wallet, set encrypt: false.

      When encryption is enabled and owner differs from wallet. Set encrypt: false for delegation scenarios, or omit owner to use connected wallet.

      Storage not configured. Configure storage providers in VanaConfig.

      No wallet addresses available. Ensure wallet is connected.

      Data doesn't match schema. Verify data structure matches schema from vana.schemas.get(schemaId).

      Upload failed with specific error message.

      // Basic file upload
      const result = await vana.data.upload({
      content: "My personal data",
      filename: "diary.txt"
      });

      // Upload with schema validation
      const result = await vana.data.upload({
      content: { name: "John", age: 30 },
      filename: "profile.json",
      schemaId: 1
      });

      // Upload with file permissions (for decryption access)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      account: "0x1234...", // Server address that can decrypt
      publicKey: "0x04..." // Server's public key for encryption
      }]
      });

      // After upload, grant operation permissions separately:
      // await vana.permissions.grant({
      // grantee: "0x1234...",
      // fileIds: [result.fileId],
      // operation: "llm_inference",
      // parameters: { model: "gpt-4" }
      // });

      // Upload without encryption (public data)
      // Note: Cast to UnencryptedUploadParams for TypeScript
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false
      } as const); // 'as const' ensures TypeScript infers encrypt: false literally

      // Upload on behalf of another user (delegation without encryption)
      const result = await vana.data.upload({
      content: "User's data",
      filename: "delegated.txt",
      owner: "0x5678...", // Different from connected wallet
      encrypt: false // Required when owner differs from wallet
      });
    • Encrypts data using wallet-derived encryption.

      Parameters

      • data: string | object | Blob

        The data to encrypt (Blob, string, or object)

      • Optionaloptions: EncryptFileOptions

        Optional encryption configuration

      Returns Promise<EncryptFileResult>

      Promise resolving to encrypted data and the encryption key used

      This method provides secure, wallet-based encryption for data before uploading to the Vana network. It's the counterpart to decryptFile for preparing data for secure storage.

      The method automatically:

      • Generates an encryption key from the user's wallet signature
      • Converts the input data to a Blob if necessary
      • Encrypts the data using the generated key
      • Returns both the encrypted data and the encryption key

      The encryption key returned can be stored and later used for decryption, or shared with others to grant them decryption access.

      When wallet is not connected or encryption fails

      // Encrypt a string
      const { encryptedData, encryptionKey } = await vana.data.encryptFile(
      "My secret data"
      );

      // Encrypt JSON with custom MIME type
      const { encryptedData, encryptionKey } = await vana.data.encryptFile(
      { name: "Alice", age: 30 },
      { mimeType: "application/json" }
      );

      // With custom encryption seed
      const { encryptedData, encryptionKey } = await vana.data.encryptFile(
      "Secret message",
      { seed: "My custom encryption seed" }
      );

      // Upload the encrypted data
      const result = await vana.data.uploadToStorage(encryptedData);
    • Decrypts a file using wallet-derived decryption key.

      Parameters

      • file: UserFile

        UserFile object from getUserFiles()

      • Optionaloptions: DecryptFileOptions

        Decryption options

        Options for decrypting a file

        • Optionalseed?: string

          Encryption seed for key derivation. Defaults to DEFAULT_ENCRYPTION_SEED

      Returns Promise<Blob>

      Decrypted content as Blob

      Counterpart to upload() for decrypting user files. Automatically generates decryption key from wallet, fetches encrypted content, and decrypts. Supports IPFS (with gateway fallback) and HTTP URLs.

      No wallet connected. Connect wallet before decrypting.

      Network error accessing file. Check CORS settings or server availability.

      File not found (404). File no longer available at stored URL.

      Access denied (403). No permission to access file.

      Invalid file format. File not encrypted with Vana protocol.

      Wrong encryption key. Verify seed matches upload or use default.

      // Basic file decryption
      const files = await vana.data.getUserFiles({ owner: userAddress });
      const decryptedBlob = await vana.data.decryptFile(files[0]);

      // Convert to text
      const text = await decryptedBlob.text();
      console.log('Decrypted content:', text);

      // Convert to JSON
      const json = JSON.parse(await decryptedBlob.text());
      console.log('Decrypted data:', json);

      // With custom encryption seed
      const decryptedBlob = await vana.data.decryptFile(
      files[0],
      "My custom encryption seed"
      );

      // Save to file (in Node.js)
      const buffer = await decryptedBlob.arrayBuffer();
      fs.writeFileSync('decrypted-file.txt', Buffer.from(buffer));
    • Retrieves all files owned by a specific user address.

      Parameters

      • params: { owner: `0x${string}`; subgraphUrl?: string }

        Query configuration

        • owner: `0x${string}`

          Wallet address of the file owner

        • OptionalsubgraphUrl?: string

          Subgraph endpoint override. Defaults to context configuration.

      • Optionaloptions: ConsistencyOptions & PaginationOptions

      Returns Promise<UserFile[]>

      Array of UserFile objects sorted by timestamp (newest first)

      Queries the Vana subgraph for files owned by the specified address. Automatically deduplicates by file ID, keeping the latest version when duplicates exist from re-indexing or chain reorganizations. Enriches results with DLP proof data when available.

      Subgraph URL not configured. Provide subgraphUrl parameter or configure in Vana constructor.

      Subgraph request failed. Check network connectivity and subgraph availability.

      Subgraph returned errors. Review query parameters and subgraph logs.

      const files = await vana.data.getUserFiles({
      owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
      });

      files.forEach(file => {
      console.log(`File ${file.id}: ${file.url}`);
      console.log(` Schema: ${file.schemaId}`);
      console.log(` DLPs: ${file.dlpIds?.join(", ") || "none"}`);
      });
    • Retrieves information about a specific Data Liquidity Pool (DLP).

      Parameters

      • dlpId: number

        The unique identifier of the DLP

      • options: { subgraphUrl?: string; minBlock?: number; waitForSync?: number } = {}

        Optional parameters

        • OptionalsubgraphUrl?: string

          Custom subgraph URL to override default

        • OptionalminBlock?: number
        • OptionalwaitForSync?: number

      Returns Promise<
          {
              id: number;
              name: string;
              metadata?: string;
              status?: number;
              address?: `0x${string}`;
              owner?: `0x${string}`;
          },
      >

      Promise resolving to DLP information

      DLPs are entities that process and verify data files in the Vana network. This method fetches DLP metadata including name, status, and performance rating. Uses subgraph first for efficiency, falls back to chain if unavailable.

      When DLP cannot be found - "DLP not found: {dlpId}"

      When query fails - "Failed to fetch DLP: {error}"

      const dlp = await vana.data.getDLP(26);
      console.log(`DLP ${dlp.name}: ${dlp.status}`);
    • Lists all Data Liquidity Pools (DLPs) with optional pagination.

      Parameters

      • options: { limit?: number; offset?: number; subgraphUrl?: string } = {}

        Optional parameters for pagination and filtering

        • Optionallimit?: number

          Maximum number of DLPs to return (default: 100)

        • Optionaloffset?: number

          Number of DLPs to skip (default: 0)

        • OptionalsubgraphUrl?: string

          Custom subgraph URL to override default

      Returns Promise<
          {
              id: number;
              name: string;
              metadata?: string;
              status?: number;
              address?: `0x${string}`;
              owner?: `0x${string}`;
          }[],
      >

      Promise resolving to array of DLP information

      Fetches a paginated list of all DLPs registered in the network. Uses subgraph for efficient querying with fallback to chain multicall.

      When query fails - "Failed to list DLPs: {error}"

      // Get first 10 DLPs
      const dlps = await vana.data.listDLPs({ limit: 10 });
      dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));

      // Get next page
      const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
    • Retrieves a list of permissions granted by a user.

      This method supports automatic fallback between subgraph and RPC modes:

      • If subgraph URL is available, tries subgraph query first
      • Falls back to direct contract queries via RPC if subgraph fails
      • RPC mode uses gasAwareMulticall for efficient batch queries

      Parameters

      • params: { user: `0x${string}`; subgraphUrl?: string }

        Object containing the user address and optional subgraph URL

        • user: `0x${string}`

          The wallet address of the user to query permissions for

        • OptionalsubgraphUrl?: string

          Optional subgraph URL to override the default

      • Optionaloptions: ConsistencyOptions & PaginationOptions

      Returns Promise<
          {
              id: string;
              grant: string;
              nonce: bigint;
              signature: string;
              addedAtBlock: bigint;
              addedAtTimestamp: bigint;
              transactionHash: `0x${string}`;
              user: `0x${string}`;
          }[],
      >

      Promise resolving to an array of permission objects

      Error if both subgraph and RPC queries fail

    • Retrieves a list of trusted servers for a user.

      This method supports automatic fallback between subgraph and RPC modes:

      • If subgraph URL is available, tries subgraph query first for fast results
      • Falls back to direct contract queries via RPC if subgraph fails
      • RPC mode uses gasAwareMulticall for efficient batch queries

      Parameters

      • params: GetUserTrustedServersParams

        Query parameters including user address and optional pagination

        Parameters for getUserTrustedServers method

        • user: `0x${string}`

          User address to query trusted servers for

        • OptionalsubgraphUrl?: string

          Optional subgraph URL to override default

      • Optionaloptions: ConsistencyOptions & PaginationOptions

      Returns Promise<TrustedServer[]>

      Promise resolving to an array of trusted server objects

      Error if both subgraph and RPC queries fail

      // Basic usage with automatic fallback
      const servers = await vana.data.getUserTrustedServers({
      user: '0x...'
      });

      // With pagination
      const servers = await vana.data.getUserTrustedServers({
      user: '0x...',
      limit: 10,
      offset: 20
      });

      // With custom subgraph URL
      const servers = await vana.data.getUserTrustedServers({
      user: '0x...',
      subgraphUrl: 'https://custom-subgraph.com/graphql'
      });
    • Retrieves total file count from Data Registry.

      Returns Promise<number>

      Total number of registered files

      Queries blockchain for complete file count across all users. Useful for pagination and network statistics.

      Chain ID not available. Ensure network connection.

      Contract read failed. Check RPC availability.

      const total = await vana.data.getTotalFilesCount();
      console.log(`Total files: ${total}`);

      // Calculate pagination
      const pages = Math.ceil(total / 20);
    • Retrieves file metadata by ID from the blockchain.

      Parameters

      • fileId: number

        Numeric file ID to retrieve

      Returns Promise<UserFile>

      UserFile object with metadata

      Queries DataRegistry contract directly for file details. Works for any file ID regardless of ownership, enabling cross-user file discovery and verification.

      Chain ID not available. Ensure proper network connection.

      File not found. Verify file ID exists on-chain.

      Contract call failed. Check network and RPC availability.

      const file = await vana.data.getFileById(123);
      console.log(`File ${file.id}:`);
      console.log(` URL: ${file.url}`);
      console.log(` Owner: ${file.ownerAddress}`);
      console.log(` Block: ${file.addedAtBlock}`);
    • Registers a file URL directly on the blockchain with a schema ID.

      Parameters

      • url: string

        The URL of the file to register (IPFS or HTTP/HTTPS)

      • schemaId: number

        The schema ID to associate with the file

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFileWithSchema">>

      Promise resolving to the file ID and transaction hash

      This method registers an existing file URL on the DataRegistry contract with a schema ID, without uploading any data. Useful when you have already uploaded content to storage and just need to register it on-chain.

      When chain ID is not available - "Chain ID not available"

      When wallet address is unavailable - "No addresses available"

      When transaction fails - "Failed to register file with schema"

      const { fileId, transactionHash } = await vana.data.registerFileWithSchema(
      "ipfs://QmXxx...",
      1
      );
      console.log(`File ${fileId} registered with schema in tx ${transactionHash}`);
    • Adds a file with permissions to the DataRegistry contract.

      Parameters

      • url: string

        The file URL to register

      • ownerAddress: `0x${string}`

        The address of the file owner

      • permissions: { account: `0x${string}`; key: string }[] = []

        Array of permissions to set for the file

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFileWithPermissions">>

      Promise resolving to file ID and transaction hash

      When chain ID is not available

      When contract execution fails

      When transaction receipt is not available

      When FileAdded event cannot be parsed

      This method handles the core logic of registering a file with specific permissions on the DataRegistry contract. It can be used by both direct transactions and relayer services.

    • Adds a file to the registry with permissions and schema. This combines the functionality of addFileWithPermissions and schema validation.

      Parameters

      • url: string

        The URL of the file to register

      • ownerAddress: `0x${string}`

        The address of the file owner

      • permissions: { account: `0x${string}`; publicKey: string }[] = []

        Array of permissions to grant, each with account and publicKey properties

      • schemaId: number = 0

        The schema ID to associate with the file (0 for no schema)

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFileWithPermissionsAndSchema">>

      Promise resolving to TransactionResult with fileId and transactionHash

      This method automatically encrypts permissions when a publicKey is provided. It generates the user's encryption key and encrypts it with each recipient's public key before registering on the blockchain.

      "Chain ID not available" - When wallet chain is not configured

      "Failed to generate encryption key" - When encryption key generation fails

      "Permission for {account} must include 'publicKey'" - When publicKey is missing

      "Failed to add file with permissions and schema: {error}" - When transaction fails

      // Get server's public key
      const serverIdentity = await vana.server.getIdentity({
      userAddress: "0x..."
      });

      // Add file with permissions and schema
      const result = await vana.data.addFileWithPermissionsAndSchema(
      "ipfs://QmXxx...",
      ownerAddress,
      [{
      account: serverIdentity.address,
      publicKey: serverIdentity.publicKey
      }],
      schemaId
      );

      console.log(`File ${result.fileId} registered in tx ${result.hash}`);
    • Adds a file with pre-encrypted permissions and schema to the DataRegistry.

      Parameters

      • url: string

        The storage URL of the file (e.g., IPFS URL)

      • ownerAddress: `0x${string}`

        The address that will own this file

      • permissions: { account: `0x${string}`; key: string }[] = []

        Array of pre-encrypted permissions with 'account' and 'key' fields

      • schemaId: number = 0

        Optional schema ID for data validation (defaults to 0)

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFileWithPermissionsAndSchema">>

      Promise resolving to transaction result with hash and contract details

      This method is designed for relay services and advanced use cases where permissions have already been encrypted client-side. Unlike addFileWithPermissionsAndSchema(), this method expects permissions in the encrypted format with a 'key' field instead of 'publicKey'.

      This is typically used by relay endpoints that receive pre-encrypted data from the client SDK's upload() method, avoiding double encryption.

      When chain ID is not available

      When wallet is not connected

      When transaction fails

      // In a relay endpoint that receives pre-encrypted permissions
      const result = await vana.data.addFileWithEncryptedPermissionsAndSchema(
      "ipfs://QmXxx...",
      ownerAddress,
      [
      {
      account: "0xServerAddress...",
      key: "encrypted_key_string" // Already encrypted by client
      }
      ],
      schemaId
      );

      console.log(`File registered in tx ${result.hash}`);
    • Registers a data refiner for processing templates.

      Parameters

      • params: AddRefinerParams

        Refiner configuration

        Parameters for registering a new data refiner in the Vana network.

        Refiners are processors that transform and validate user data according to specific schemas and instructions. They enable applications to work with structured, verified user data while maintaining privacy and user control.

        • dlpId: number

          DLP ID this refiner belongs to

        • name: string

          Refiner name

        • schemaId: number

          Schema ID to associate with this refiner

        • refinementInstructionUrl: string

          URL containing refinement instructions

      • Optionaloptions: TransactionOptions

      Returns Promise<AddRefinerResult>

      Refiner ID and transaction hash

      Refiners define data transformation rules for DLPs. Associates schema, instructions, and processing logic.

      Chain ID not available. Ensure network connection.

      Transaction failed. Check wallet balance and network status.

      const result = await vana.data.addRefiner({
      dlpId: 1,
      name: "Sentiment Analyzer",
      schemaId: 42,
      refinementInstructionUrl: "ipfs://QmXxx..."
      });
      console.log(`Refiner ${result.refinerId} created`);
    • Retrieves refiner configuration by ID.

      Parameters

      • refinerId: number

        Numeric refiner ID

      Returns Promise<Refiner>

      Refiner configuration object

      Queries DataRefinerRegistry for refiner details. Returns DLP association, schema, and processing instructions.

      Chain ID not available. Ensure network connection.

      Refiner not found. Verify refiner ID exists.

      Contract read failed. Check network and RPC status.

      const refiner = await vana.data.getRefiner(1);
      console.log(`Refiner: ${refiner.name}`);
      console.log(`DLP: ${refiner.dlpId}`);
      console.log(`Schema: ${refiner.schemaId}`);
    • Validates schema ID existence.

      Parameters

      • schemaId: number

        Numeric schema ID to validate

      Returns Promise<boolean>

      True if schema exists, false otherwise

      Verifies schema registration in DataRegistry. Check before using schemas for uploads.

      Chain ID not available. Ensure network connection.

      Contract read failed. Check RPC availability.

      const valid = await vana.data.isValidSchemaId(42);
      if (valid) {
      // Safe to use schema 42
      await vana.data.upload({ schemaId: 42, ... });
      }
    • Gets the total number of refiners in the registry.

      Returns Promise<number>

      Promise resolving to the total refiner count

      Queries the DataRefinerRegistry contract to get the total count of all registered refiners across all DLPs.

      const count = await vana.data.getRefinersCount();
      console.log(`Total refiners registered: ${count}`);
    • Updates the schema ID for an existing refiner.

      Parameters

      • params: UpdateSchemaIdParams

        Update parameters

        Parameters for updating a refiner's schema ID

        • refinerId: number

          Refiner ID to update

        • newSchemaId: number

          New schema ID to associate with the refiner

      • Optionaloptions: TransactionOptions

      Returns Promise<UpdateSchemaIdResult>

      Promise resolving to the transaction hash

      Allows the owner of a refiner to update its associated schema ID. This is useful when refiner output format needs to change.

      When chain ID is not available - "Chain ID not available"

      When transaction fails - "Failed to update schema ID: {error}"

      const result = await vana.data.updateSchemaId({
      refinerId: 1,
      newSchemaId: 55
      });
      console.log(`Schema updated in tx ${result.transactionHash}`);
    • Uploads content to storage without registering it on the blockchain. This method only handles the storage upload and returns the file URL.

      Parameters

      • content: string | object | Blob | Buffer<ArrayBufferLike>

        The content to upload (string, Blob, Buffer, or object - objects will be JSON stringified)

      • Optionalfilename: string

        Optional filename for the uploaded file (defaults to timestamp-based name)

      • encrypt: boolean = false

        Optional flag to encrypt the content before upload

      • OptionalproviderName: string

        Optional specific storage provider to use

      Returns Promise<StorageUploadResult>

      Promise resolving to the storage upload result with url, size, and contentType

    • Adds a permission for a party to access an existing file.

      This method handles the complete workflow:

      1. Gets the user's encryption key
      2. Encrypts the user's encryption key with the provided public key
      3. Adds the permission to the file
      4. Returns the permission data from the blockchain event

      For advanced users who need more control over transaction timing, use submitFilePermission() instead.

      Parameters

      • params: AddFilePermissionParams

        Parameters for adding file permission

        Parameters for adding permission to a file

        • fileId: number

          The file ID to grant permission for

        • account: `0x${string}`

          The account to grant permission to

        • publicKey: string

          The public key of the account for encryption

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFilePermission">>

      Promise resolving to permission data from PermissionGranted event

      "No addresses available in wallet client" - When wallet is not connected

      "Chain ID not available" - When wallet chain is not configured

      "Failed to add permission to file: {error}" - When transaction fails or user doesn't own file

      const result = await vana.data.addPermissionToFile({
      fileId: 123,
      account: "0xRecipientAddress...",
      publicKey: "0xRecipientPublicKey..."
      });
      console.log(`Permission granted to ${result.account} for file ${result.fileId}`);
      console.log(`Transaction: ${result.transactionHash}`);
    • Submits a file permission transaction to the blockchain.

      Parameters

      • fileId: number

        The ID of the file to grant permission for

      • account: `0x${string}`

        The recipient's wallet address that will access the file

      • publicKey: string

        The recipient's public key for encryption. Obtain via vana.server.getIdentity(account).publicKey

      • Optionaloptions: TransactionOptions

      Returns Promise<TransactionResult<"DataRegistry", "addFilePermission">>

      Promise resolving to TransactionResult for tracking the transaction

      This method supports gasless transactions via relayer callbacks when configured. It encrypts the user's encryption key with the recipient's public key before submission. Use this when you want to handle transaction confirmation and event parsing separately.

      When chain ID is not available

      When encryption key generation fails

      When public key encryption fails

      const tx = await vana.data.submitFilePermission(
      fileId,
      "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
      recipientPublicKey
      );
      const result = await tx.waitForEvents();
      console.log(`Permission granted with ID: ${result.permissionId}`);
    • Gets the encrypted key for a specific account's permission to access a file.

      Parameters

      • fileId: number

        The ID of the file

      • account: `0x${string}`

        The account address to get the permission for

      Returns Promise<string>

      Promise resolving to the encrypted key for that account

    • Decrypts a file that the user has permission to access using their private key.

      This method handles the complete workflow for servers or other permitted parties:

      1. Gets the encrypted encryption key from file permissions
      2. Decrypts the encryption key using the provided private key
      3. Downloads and decrypts the file data

      Parameters

      • file: UserFile

        The file to decrypt

      • privateKey: string

        The private key to decrypt the user's encryption key

      • Optionaloptions: DecryptFileWithPermissionOptions

        Optional decryption configuration

        Options for decrypting a file with permission

        • Optionalaccount?: `0x${string}`

          Optional account address to verify permission against

      Returns Promise<Blob>

      Promise resolving to the decrypted file data

    • Simple network-agnostic fetch utility for retrieving file content.

      Parameters

      • url: string

        The URL to fetch content from

      Returns Promise<Blob>

      Promise resolving to the fetched content as a Blob

      This is a thin wrapper around the global fetch API that returns the response as a Blob. It provides a consistent interface for fetching encrypted content before decryption. For IPFS URLs, consider using fetchFromIPFS for better reliability.

      "HTTP error! status: {status} {statusText}" - When server returns error status

      "Empty response" - When server returns no content

      "Network error: Failed to fetch from {url}" - When network request fails

      // Fetch and decrypt a file
      const encryptionKey = await generateEncryptionKey(walletClient);
      const encryptedBlob = await vana.data.fetch(file.url);
      const decryptedBlob = await decryptBlob(encryptedBlob, encryptionKey, platform);

      // With custom headers for authentication
      const response = await fetch(file.url, {
      headers: { 'Authorization': 'Bearer token' }
      });
      const encryptedBlob = await response.blob();
    • Specialized IPFS fetcher with gateway fallback mechanism.

      Parameters

      • url: string

        The IPFS URL (ipfs://...) or CID to fetch

      • Optionaloptions: { gateways?: string[] }

        Optional configuration

        • Optionalgateways?: string[]

          Array of IPFS gateway URLs to try (must end with /)

      Returns Promise<Blob>

      Promise resolving to the fetched content as a Blob

      This method provides robust IPFS content fetching by trying multiple gateways in sequence until one succeeds. It supports both ipfs:// URLs and raw CIDs.

      The default gateway list includes public gateways, but you should provide your own gateways for production use to ensure reliability and privacy.

      "Invalid IPFS URL format" - When URL is not ipfs:// or valid CID

      "Empty response" - When gateway returns no content

      "HTTP error! status: {status}" - When gateway returns error status

      "Failed to fetch IPFS content {cid} from all gateways" - When all gateways fail

      // Fetch from IPFS with custom gateways
      const encryptedBlob = await vana.data.fetchFromIPFS(file.url, {
      gateways: [
      'https://my-private-gateway.com/ipfs/',
      'https://dweb.link/ipfs/',
      'https://ipfs.io/ipfs/'
      ]
      });

      // Decrypt the fetched content
      const encryptionKey = await generateEncryptionKey(walletClient);
      const decryptedBlob = await decryptBlob(encryptedBlob, encryptionKey, platform);

      // With raw CID
      const blob = await vana.data.fetchFromIPFS('QmXxx...', {
      gateways: ['https://ipfs.io/ipfs/']
      });
    • Validates a data schema definition against the Vana meta-schema.

      Parameters

      • schema: unknown

        The data schema definition to validate

      Returns DataSchema

      The validated DataSchema

      SchemaValidationError if invalid

      const schema = {
      name: "User Profile",
      version: "1.0.0",
      dialect: "json",
      schema: {
      type: "object",
      properties: {
      name: { type: "string" },
      age: { type: "number" }
      }
      }
      };

      const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
    • Validates data against a JSON Schema from a data schema.

      Parameters

      • data: unknown

        The data to validate

      • schema: DataSchema

        The data schema containing the schema

      Returns void

      Void (throws if validation fails)

      SchemaValidationError if invalid

      const schema = {
      name: "User Profile",
      version: "1.0.0",
      dialect: "json",
      schema: {
      type: "object",
      properties: {
      name: { type: "string" },
      age: { type: "number" }
      },
      required: ["name"]
      }
      };

      const userData = { name: "Alice", age: 30 };
      vana.data.validateDataAgainstSchema(userData, schema);
    • Fetches and validates a data schema from a URL, then returns the parsed data schema.

      Parameters

      • url: string

        The URL to fetch the data schema from

      Returns Promise<DataSchema>

      The validated data schema

      SchemaValidationError if invalid or fetch fails

      // Fetch and validate a schema from IPFS or HTTP
      const schema = await vana.data.fetchAndValidateSchema("https://example.com/schema.json");
      console.log(schema.name, schema.dialect);

      // Use the schema to validate user data
      if (schema.dialect === "json") {
      vana.data.validateDataAgainstSchema(userData, schema);
      }