Vana SDK - v0.1.0
    Preparing search index...

    Class DataController

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

    This controller handles the complete file lifecycle from encrypted upload to blockchain registration and decryption. It provides methods for querying user files, uploading new encrypted content, managing file schemas, and handling permissions for secure data sharing. All operations respect the user's privacy through client-side encryption before any data leaves the user's device.

    The controller integrates with multiple storage providers (IPFS, Pinata, Google Drive) and supports both gasless transactions via relayers and direct blockchain interaction. File metadata and access permissions are stored on the Vana blockchain while encrypted file content is stored on decentralized storage networks.

    // Upload an encrypted file with automatic schema validation
    const result = await vana.data.uploadEncryptedFile(
    encryptedBlob,
    "personal-data.json"
    );

    // Query files owned by a user
    const files = await vana.data.getUserFiles({
    owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
    });

    // Decrypt accessible file content
    const decryptedData = await vana.data.decryptFile(files[0]);

    [URL_PLACEHOLDER] | Vana Data Registry Documentation for conceptual overview

    Index

    Methods

    • Uploads user data with automatic encryption and blockchain registration.

      Parameters

      Returns Promise<UploadResult>

      Promise resolving to upload results with file ID and transaction hash

      This is the primary method for uploading user data to the Vana network. It handles the complete workflow including content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      The method automatically:

      • Normalizes input content to a Blob
      • Validates data against schema if provided
      • Generates encryption keys and encrypts the data
      • Uploads to the configured storage provider
      • Grants permissions to specified applications
      • Registers the file on the blockchain

      When using permissions with encryption enabled (default), you must provide the public key for each permission recipient.

      When wallet is not connected or storage is not configured

      When schema validation fails

      When upload or blockchain registration fails

      // 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 permissions (encrypted - requires publicKey)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      grantee: "0x1234...",
      operation: "llm_inference",
      parameters: { model: "gpt-4" },
      publicKey: "0x04..." // Required when encrypt is true (default)
      }]
      });

      // Upload without encryption
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false,
      permissions: [{
      grantee: "0x1234...",
      operation: "read",
      parameters: {}
      }]
      });
    • Uploads user data with automatic encryption and blockchain registration.

      Parameters

      Returns Promise<UploadResult>

      Promise resolving to upload results with file ID and transaction hash

      This is the primary method for uploading user data to the Vana network. It handles the complete workflow including content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      The method automatically:

      • Normalizes input content to a Blob
      • Validates data against schema if provided
      • Generates encryption keys and encrypts the data
      • Uploads to the configured storage provider
      • Grants permissions to specified applications
      • Registers the file on the blockchain

      When using permissions with encryption enabled (default), you must provide the public key for each permission recipient.

      When wallet is not connected or storage is not configured

      When schema validation fails

      When upload or blockchain registration fails

      // 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 permissions (encrypted - requires publicKey)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      grantee: "0x1234...",
      operation: "llm_inference",
      parameters: { model: "gpt-4" },
      publicKey: "0x04..." // Required when encrypt is true (default)
      }]
      });

      // Upload without encryption
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false,
      permissions: [{
      grantee: "0x1234...",
      operation: "read",
      parameters: {}
      }]
      });
    • Uploads user data with automatic encryption and blockchain registration.

      Parameters

      • params: UploadParams

        Upload parameters including content, filename, schema, and permissions

      Returns Promise<UploadResult>

      Promise resolving to upload results with file ID and transaction hash

      This is the primary method for uploading user data to the Vana network. It handles the complete workflow including content normalization, schema validation, encryption, storage upload, permission granting, and blockchain registration.

      The method automatically:

      • Normalizes input content to a Blob
      • Validates data against schema if provided
      • Generates encryption keys and encrypts the data
      • Uploads to the configured storage provider
      • Grants permissions to specified applications
      • Registers the file on the blockchain

      When using permissions with encryption enabled (default), you must provide the public key for each permission recipient.

      When wallet is not connected or storage is not configured

      When schema validation fails

      When upload or blockchain registration fails

      // 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 permissions (encrypted - requires publicKey)
      const result = await vana.data.upload({
      content: "Data for AI analysis",
      filename: "analysis.txt",
      permissions: [{
      grantee: "0x1234...",
      operation: "llm_inference",
      parameters: { model: "gpt-4" },
      publicKey: "0x04..." // Required when encrypt is true (default)
      }]
      });

      // Upload without encryption
      const result = await vana.data.upload({
      content: "Public data",
      filename: "public.txt",
      encrypt: false,
      permissions: [{
      grantee: "0x1234...",
      operation: "read",
      parameters: {}
      }]
      });
    • Decrypts a file owned by the user using their wallet signature.

      Parameters

      • file: UserFile

        The user file to decrypt (typically from getUserFiles)

      • OptionalencryptionSeed: string

        Optional custom encryption seed (defaults to Vana standard)

      Returns Promise<Blob>

      Promise resolving to the decrypted file content as a Blob

      This is the high-level convenience method for decrypting user files, serving as the symmetrical counterpart to the upload method. It handles the complete decryption workflow including key generation, URL protocol detection, content fetching, and decryption.

      The method automatically:

      • Generates the decryption key from the user's wallet signature
      • Determines the appropriate fetch method based on the file URL protocol
      • Fetches the encrypted content from IPFS or standard HTTP URLs
      • Decrypts the content using the generated key

      For IPFS URLs, the method uses gateway fallback for improved reliability. For standard HTTP URLs, it uses a simple fetch. If you need custom authentication headers or specific gateway configurations, use the low-level primitives directly.

      When the wallet is not connected

      When fetching the encrypted content fails

      When decryption fails (wrong key or corrupted data)

      // 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 data files owned by a specific user address.

      Parameters

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

        The query parameters object

        • owner: `0x${string}`

          The wallet address of the file owner to query

        • OptionalsubgraphUrl?: string

          Optional subgraph URL to override the default endpoint

      Returns Promise<UserFile[]>

      A Promise that resolves to an array of UserFile objects with metadata

      This method queries the Vana subgraph to find files directly owned by the user. It efficiently handles large datasets by using the File entity's owner field and returns complete file metadata without additional contract calls.

      When the subgraph is unavailable or returns invalid data

      // Query files for a specific user
      const files = await vana.data.getUserFiles({
      owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
      });

      files.forEach(file => {
      console.log(`File ${file.id}: ${file.url} (Schema: ${file.schemaId})`);
      });
    • Retrieves a list of permissions granted by a user using the new subgraph entities.

      This method queries the Vana subgraph to find permissions directly granted by the user using the new Permission entity. It efficiently handles millions of permissions by:

      1. Querying the subgraph for user's directly granted permissions
      2. Returning complete permission information from subgraph
      3. No need for additional contract calls as all data comes from subgraph

      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

      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 subgraph is unavailable or returns invalid data

    • Retrieves a list of trusted servers for a user using the new subgraph entities.

      This method queries the Vana subgraph to find trusted servers directly associated with the user with support for both subgraph and direct RPC queries.

      This method supports multiple query modes:

      • 'subgraph': Fast query via subgraph (requires subgraphUrl)
      • 'rpc': Direct contract queries (slower but no external dependencies)
      • 'auto': Try subgraph first, fallback to RPC if unavailable

      Parameters

      Returns Promise<GetUserTrustedServersResult>

      Promise resolving to trusted servers with metadata about the query

      Error if query fails in both modes (when using 'auto')

      // Use subgraph for fast queries
      const result = await vana.data.getUserTrustedServers({
      user: '0x...',
      mode: 'subgraph',
      subgraphUrl: 'https://...'
      });

      // Use direct RPC (no external dependencies)
      const result = await vana.data.getUserTrustedServers({
      user: '0x...',
      mode: 'rpc',
      limit: 10
      });

      // Auto-fallback mode
      const result = await vana.data.getUserTrustedServers({
      user: '0x...',
      mode: 'auto' // tries subgraph first, falls back to RPC
      });
    • Gets the total number of files in the registry from the contract.

      Returns Promise<number>

      Promise resolving to the total file count

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

      // Use for pagination calculations
      const filesPerPage = 20;
      const totalPages = Math.ceil(totalFiles / filesPerPage);
      console.log(`Total pages: ${totalPages}`);
    • Retrieves details for a specific file by its ID.

      Parameters

      • fileId: number

        The file ID to look up

      Returns Promise<UserFile>

      Promise resolving to UserFile object

      try {
      const file = await vana.data.getFileById(123);
      console.log('File details:', {
      id: file.id,
      url: file.url,
      owner: file.ownerAddress,
      addedAt: file.addedAtBlock
      });
      } catch (error) {
      console.error('File not found or error retrieving file:', error);
      }

      This method queries the DataRegistry contract directly to get file details for any file ID, regardless of user ownership. This is useful for file lookup functionality where users can search for specific files by ID.

    • Uploads an encrypted file to storage and registers it on the blockchain.

      Parameters

      • encryptedFile: Blob

        The encrypted file blob to upload

      • Optionalfilename: string

        Optional filename for the upload

      • OptionalproviderName: string

        Optional storage provider to use

      Returns Promise<UploadEncryptedFileResult>

      Promise resolving to upload result with file ID and storage URL

      This method handles the complete flow of:

      1. Uploading the encrypted file to the specified storage provider
      2. Registering the file URL on the DataRegistry contract via relayer
      3. Returning the assigned file ID and storage URL

      Use vana.data.upload() instead for the high-level API with automatic encryption

    • Uploads an encrypted file to storage and registers it on the blockchain with a schema.

      Parameters

      • encryptedFile: Blob

        The encrypted file blob to upload

      • schemaId: number

        The schema ID to associate with the file

      • Optionalfilename: string

        Optional filename for the upload

      • OptionalproviderName: string

        Optional storage provider to use

      Returns Promise<UploadEncryptedFileResult>

      Promise resolving to upload result with file ID and storage URL

      This method handles the complete flow of:

      1. Uploading the encrypted file to the specified storage provider
      2. Registering the file URL on the DataRegistry contract with a schema ID
      3. Returning the assigned file ID and storage URL

      Use vana.data.upload() instead for the high-level API with automatic encryption and schema validation

    • Registers a file URL directly on the blockchain with a schema ID.

      Parameters

      • url: string

        The URL of the file to register

      • schemaId: number

        The schema ID to associate with the file

      Returns Promise<{ fileId: number; transactionHash: `0x${string}` }>

      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.

    • 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

      Returns Promise<{ fileId: number; transactionHash: string }>

      Promise resolving to file ID and transaction hash

      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}`; key: string }[] = []

        Array of permissions to grant (account and encrypted key)

      • schemaId: number = 0

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

      Returns Promise<{ fileId: number; transactionHash: string }>

      Promise resolving to object with fileId and transactionHash

    • Retrieves a schema by its ID.

      Parameters

      • schemaId: number

        The schema ID to retrieve

      Returns Promise<Schema>

      Promise resolving to the schema information

      Use vana.schemas.get() instead

    • Gets the total number of schemas in the registry.

      Returns Promise<number>

      Promise resolving to the total schema count

      Use vana.schemas.count() instead

    • Validates if a schema ID exists in the registry.

      Parameters

      • schemaId: number

        The schema ID to validate

      Returns Promise<boolean>

      Promise resolving to boolean indicating if the schema ID is valid

    • Uploads an encrypted file and grants permission to a party with a public key.

      This method handles the complete workflow:

      1. Encrypts the file with the user's encryption key
      2. Uploads the encrypted file to storage
      3. Encrypts the user's encryption key with the provided public key
      4. Registers the file with permissions

      Parameters

      • data: Blob

        The file data to encrypt and upload

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

        Array of permissions to grant, each with account address and public key

      • Optionalfilename: string

        Optional filename for the upload

      • OptionalproviderName: string

        Optional storage provider to use

      Returns Promise<UploadEncryptedFileResult>

      Promise resolving to upload result with file ID and storage URL

    • 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

      Parameters

      • fileId: number

        The ID of the file to add permissions for

      • account: `0x${string}`

        The address of the account to grant permission to

      • publicKey: string

        The public key to encrypt the user's encryption key with

      Returns Promise<string>

      Promise resolving to the transaction hash

    • 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

      • Optionalaccount: `0x${string}`

        The account address that has permission (defaults to current wallet account)

      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.

      When the fetch fails or returns a non-ok response

      // 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.

      When all gateways fail to fetch the content

      // 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 against the Vana meta-schema.

      Parameters

      • schema: unknown

        The data schema to validate

      Returns asserts schema is DataSchema

      Assertion that schema is valid (throws if invalid)

      SchemaValidationError if invalid

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

      vana.data.validateDataSchema(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 schema from a URL, then returns the parsed data schema.

      Parameters

      • url: string

        The URL to fetch the 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);
      }
    • Retrieves a schema by ID and fetches its definition URL to get the full data schema.

      Parameters

      • schemaId: number

        The schema ID to retrieve and validate

      Returns Promise<DataSchema>

      The validated data schema

      SchemaValidationError if schema is invalid

      // Get schema from registry and validate its schema
      const schema = await vana.data.getValidatedSchema(123);

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