@opendatalabs/vana-sdk
Version:
A TypeScript library for interacting with Vana Network smart contracts.
1,709 lines (1,701 loc) • 1.06 MB
text/typescript
import * as viem from 'viem';
import { Chain, Address, Hash, WalletClient, Account, Abi, GetContractReturnType, PublicClient } from 'viem';
export { Abi, Account, Address, Chain, GetContractReturnType, Hash, PublicClient, WalletClient } from 'viem';
import { Abi as Abi$1 } from 'abitype';
/**
* Supported Vana chain IDs
*/
type VanaChainId = 14800 | 1480;
/**
* Supported Vana chains
*/
type VanaChain = Chain & {
id: VanaChainId;
};
/**
* Type guard to check if a chain ID is supported
*
* @param chainId - The chain ID to validate
* @returns True if the chain ID is a supported Vana chain ID
*/
declare function isVanaChainId(chainId: number): chainId is VanaChainId;
/**
* Type guard to check if a chain is a Vana chain
*
* @param chain - The chain object to validate
* @returns True if the chain is a supported Vana chain
*/
declare function isVanaChain(chain: Chain): chain is VanaChain;
/**
* Interface for storage providers that handle file upload, download, and management operations.
*
* Storage providers abstract different storage backends (IPFS, Google Drive, Pinata, etc.)
* behind a common interface. The SDK uses these providers to store encrypted user data
* and permission grants in a decentralized manner.
*
* @category Storage
* @example
* ```typescript
* // Implement a custom storage provider
* class MyStorageProvider implements StorageProvider {
* async upload(file: Blob, filename?: string): Promise<StorageUploadResult> {
* // Custom upload logic
* return { url: 'https://my-storage.com/file.dat', size: file.size };
* }
*
* async download(url: string): Promise<Blob> {
* // Custom download logic
* const response = await fetch(url);
* return response.blob();
* }
*
* async list(options?: StorageListOptions): Promise<StorageFile[]> {
* // Return list of files
* return [];
* }
*
* async delete(url: string): Promise<void> {
* // Delete file implementation
* }
* }
* ```
*/
interface StorageProvider {
/**
* Upload a file to the storage provider
*
* @param file - The file to upload
* @param filename - Optional custom filename
* @returns Promise with storage URL and metadata
*/
upload(file: Blob, filename?: string): Promise<StorageUploadResult>;
/**
* Download a file from the storage provider
*
* @param url - The storage URL
* @returns Promise with file blob
*/
download(url: string): Promise<Blob>;
/**
* List files from the storage provider
*
* @param options - Optional filtering and pagination
* @returns Promise with file list
*/
list(options?: StorageListOptions): Promise<StorageFile[]>;
/**
* Delete a file from the storage provider
*
* @param url - The storage URL
* @returns Promise with success status
*/
delete(url: string): Promise<boolean>;
/**
* Get provider-specific configuration
*
* @returns Provider configuration object
*/
getConfig(): StorageProviderConfig;
}
interface StorageUploadResult {
/** Public URL to access the file */
url: string;
/** File size in bytes */
size: number;
/** Content type/MIME type */
contentType: string;
/** Provider-specific metadata */
metadata?: Record<string, unknown>;
}
interface StorageFile {
/** File identifier */
id: string;
/** File name */
name: string;
/** Public URL to access the file */
url: string;
/** File size in bytes */
size: number;
/** Content type/MIME type */
contentType: string;
/** Upload timestamp */
createdAt: Date;
/** Provider-specific metadata */
metadata?: Record<string, unknown>;
}
interface StorageListOptions {
/** Maximum number of files to return */
limit?: number;
/** Pagination cursor/offset */
offset?: string | number;
/** Filter by file name pattern */
namePattern?: string;
/** Filter by content type */
contentType?: string;
}
interface StorageProviderConfig {
/** Provider name */
name: string;
/** Provider type */
type: string;
/** Whether authentication is required */
requiresAuth: boolean;
/** Supported features */
features: {
upload: boolean;
download: boolean;
list: boolean;
delete: boolean;
};
}
declare class StorageError extends Error {
readonly code: string;
readonly provider: string;
constructor(message: string, code: string, provider: string, options?: {
cause?: Error;
});
}
/**
* Represents a granted permission from the DataPermissions contract.
*
* This interface describes the structure of permissions that have been granted
* on-chain, including all the metadata and parameters associated with the permission.
* Used when querying user permissions or checking access rights.
*
* @category Permissions
*/
interface GrantedPermission {
/** Unique identifier for the permission */
id: bigint;
/** Array of file IDs included in the permission */
files: number[];
/** Type of operation permitted (e.g., "llm_inference") */
operation?: string;
/** The grant URL containing all permission details */
grant: string;
/** The parameters associated with the permission */
parameters?: Record<string, unknown>;
/** Optional nonce used when granting the permission */
nonce?: number;
/** Optional block number when permission was granted */
grantedAt?: number;
/** Address that granted the permission */
grantor: Address;
/** Address that received the permission */
grantee: Address;
/** Whether the permission is still active */
active: boolean;
/** Expiration timestamp if applicable */
expiresAt?: number;
}
/**
* Parameters for granting data access permission to an application.
*
* This interface defines the required and optional parameters when granting
* an application permission to access specific files for a particular operation.
* Used with `vana.permissions.grant()`.
*
* @category Permissions
* @example
* ```typescript
* const params: GrantPermissionParams = {
* to: '0x1234...', // Application address
* operation: 'llm_inference',
* files: [1, 2, 3], // File IDs to grant access to
* parameters: {
* model: 'gpt-4',
* maxTokens: 1000,
* prompt: 'Analyze my data'
* }
* };
* ```
*/
interface GrantPermissionParams$1 {
/** The on-chain identity of the application */
to: Address;
/** The class of computation, e.g., "llm_inference" */
operation: string;
/** Array of file IDs to grant permission for */
files: number[];
/** The full, off-chain parameters (e.g., LLM prompt) */
parameters: Record<string, unknown>;
/** Optional pre-stored grant URL to avoid duplicate IPFS storage */
grantUrl?: string;
/** Optional nonce for the permission */
nonce?: bigint;
/** Optional expiration time for the permission */
expiresAt?: number;
}
/**
* Parameters for revoking a previously granted data access permission.
*
* Used with `PermissionsController.revoke()` to remove an application's access
* to user data. Once revoked, the application can no longer use the permission
* to access the specified files.
*
* @category Permissions
* @example
* ```typescript
* const revokeParams: RevokePermissionParams = {
* permissionId: 123n // Permission ID to revoke
* };
*
* await vana.permissions.revoke(revokeParams);
* ```
*/
interface RevokePermissionParams {
/** The permission ID to revoke */
permissionId: bigint;
}
/**
* Parameters for checking if a specific permission exists and is valid.
*
* Used to verify whether an application has active permission to access
* specific user files for a particular operation before attempting to use the data.
*
* @category Permissions
* @example
* ```typescript
* const checkParams: CheckPermissionParams = {
* application: '0x1234...', // App address
* operation: 'llm_inference',
* files: [1, 2, 3], // File IDs to check
* parameters: { model: 'gpt-4' }, // Operation parameters
* user: '0xabcd...' // Optional specific user
* };
*
* const hasPermission = await vana.permissions.check(checkParams);
* ```
*/
interface CheckPermissionParams {
/** The application address */
application: Address;
/** The operation type */
operation: string;
/** The file IDs */
files: number[];
/** The grant parameters */
parameters: Record<string, unknown>;
/** The user address */
user?: Address;
}
/**
* Permission check result
*
* @category Permissions
*/
interface PermissionCheckResult {
/** Whether the permission exists and is valid */
exists: boolean;
/** The permission details if it exists */
permission?: GrantedPermission;
/** Reason why permission is invalid (if applicable) */
reason?: string;
}
/**
* EIP-712 domain definition for PermissionGrant signatures
*
* @category Permissions
*/
interface PermissionGrantDomain {
/** Domain name */
name: string;
/** Domain version */
version: string;
/** Chain ID */
chainId: number;
/** Verifying contract address */
verifyingContract: Address;
}
/**
* EIP-712 Permission message structure (current contract format)
*
* @category Permissions
*/
interface PermissionGrantMessage {
/** Application address */
application: Address;
/** File IDs */
files: number[];
/** Operation type */
operation: string;
/** Grant URL */
grant: string;
/** Parameters as JSON string */
parameters: string;
/** Nonce */
nonce: bigint;
}
/**
* EIP-712 PermissionInput message structure (new simplified format)
*
* @category Permissions
*/
interface PermissionInputMessage {
/** Nonce */
nonce: bigint;
/** Grant URL */
grant: string;
/** File IDs */
fileIds: bigint[];
}
/**
* Contract RevokePermissionInput structure
*
* @category Permissions
*/
interface RevokePermissionInput {
/** Nonce */
nonce: bigint;
/** Permission ID to revoke */
permissionId: bigint;
}
/**
* Contract Permission Info structure returned from the contract
*
* @category Permissions
*/
interface PermissionInfo {
/** Permission ID */
id: bigint;
/** Address that granted the permission */
grantor: Address;
/** Nonce used when creating */
nonce: bigint;
/** Grant URL */
grant: string;
/** Signature bytes */
signature: `0x${string}`;
/** Whether the permission is active */
isActive: boolean;
/** File IDs associated with this permission */
fileIds: bigint[];
}
/**
* EIP-712 Permission message structure (simplified future format)
*
* @category Permissions
*/
interface SimplifiedPermissionMessage {
/** Application address */
application: Address;
/** Grant URL */
grant: string;
/** Nonce */
nonce: bigint;
}
/**
* Grant file structure containing permission details.
*
* Grant files contain the complete specification of what an application is permitted
* to do with user data, including operation parameters and file access rights.
*
* @category Permissions
* @example
* ```typescript
* const grantFile: GrantFile = {
* grantee: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
* operation: 'llm_inference',
* parameters: {
* prompt: 'Analyze this data: {{data}}',
* model: 'gpt-4',
* maxTokens: 2000,
* temperature: 0.7
* },
* expires: 1736467579
* };
* ```
*/
interface GrantFile {
/** EVM address of the application authorized to use this grant */
grantee: Address;
/** Operation the grantee is authorized to perform */
operation: string;
/** Operation-specific parameters */
parameters: Record<string, unknown>;
/** Optional Unix timestamp when grant expires (seconds since epoch per POSIX.1-2008) */
expires?: number;
}
/**
* EIP-712 typed data structure for Permission
*
* @category Permissions
*/
interface PermissionGrantTypedData {
/** EIP-712 domain */
domain: PermissionGrantDomain;
/** EIP-712 types */
types: {
Permission: Array<{
name: string;
type: string;
}>;
};
/** Primary type */
primaryType: "Permission";
/** Message to sign */
message: PermissionInputMessage;
}
/**
* Generic EIP-712 typed data structure
*
* @category Permissions
*/
interface GenericTypedData {
/** EIP-712 domain */
domain: PermissionGrantDomain;
/** EIP-712 types */
types: Record<string, Array<{
name: string;
type: string;
}>>;
/** Primary type */
primaryType: string;
/** Message to sign */
message: Record<string, unknown>;
}
/**
* Permission operation types
*
* @category Permissions
*/
type PermissionOperation = "llm_inference" | "data_analysis" | "model_training" | "data_sharing" | "compute_task" | string;
/**
* Permission status
*
* @category Permissions
*/
type PermissionStatus = "active" | "revoked" | "expired" | "pending";
/**
* Parameters for querying permissions
*
* @category Permissions
*/
interface QueryPermissionsParams {
/** Filter by grantor address */
grantor?: Address;
/** Filter by grantee address */
grantee?: Address;
/** Filter by operation type */
operation?: PermissionOperation;
/** Filter by file IDs */
files?: number[];
/** Filter by status */
status?: PermissionStatus;
/** Starting block number */
fromBlock?: bigint;
/** Ending block number */
toBlock?: bigint;
/** Maximum number of results */
limit?: number;
/** Offset for pagination */
offset?: number;
}
/**
* Permission query result
*
* @category Permissions
*/
interface PermissionQueryResult {
/** Array of permissions matching the query */
permissions: GrantedPermission[];
/** Total number of permissions (for pagination) */
total: number;
/** Whether there are more results available */
hasMore: boolean;
}
/**
* Permission analytics data
*
* @category Permissions
*/
interface PermissionAnalytics {
/** Total number of permissions granted */
totalPermissions: number;
/** Number of active permissions */
activePermissions: number;
/** Number of revoked permissions */
revokedPermissions: number;
/** Number of expired permissions */
expiredPermissions: number;
/** Most common operation types */
topOperations: Array<{
operation: PermissionOperation;
count: number;
}>;
/** Most active applications */
topApplications: Array<{
application: Address;
count: number;
}>;
}
/**
* Server information
*
* @category Permissions
*/
interface Server {
/** Server URL */
url: string;
}
/**
* Parameters for trusting a server
*
* @category Permissions
*/
interface TrustServerParams {
/** Server ID (address) */
serverId: Address;
/** Server URL */
serverUrl: string;
}
/**
* Parameters for untrusting a server
*
* @category Permissions
*/
interface UntrustServerParams {
/** Server ID (address) */
serverId: Address;
}
/**
* Input for trusting a server with signature (gasless)
*
* @category Permissions
*/
interface TrustServerInput {
/** User nonce */
nonce: bigint;
/** Server ID (address) */
serverId: Address;
/** Server URL */
serverUrl: string;
}
/**
* Input for untrusting a server with signature (gasless)
*
* @category Permissions
*/
interface UntrustServerInput {
/** User nonce */
nonce: bigint;
/** Server ID (address) */
serverId: Address;
}
/**
* EIP-712 typed data for TrustServer
*
* @category Permissions
*/
interface TrustServerTypedData {
/** EIP-712 domain */
domain: PermissionGrantDomain;
/** EIP-712 types */
types: {
TrustServer: Array<{
name: string;
type: string;
}>;
};
/** Primary type */
primaryType: "TrustServer";
/** Message to sign */
message: TrustServerInput;
}
/**
* EIP-712 typed data for UntrustServer
*
* @category Permissions
*/
interface UntrustServerTypedData {
/** EIP-712 domain */
domain: PermissionGrantDomain;
/** EIP-712 types */
types: {
UntrustServer: Array<{
name: string;
type: string;
}>;
};
/** Primary type */
primaryType: "UntrustServer";
/** Message to sign */
message: UntrustServerInput;
}
/**
* Permission event data
*
* @category Permissions
*/
interface PermissionEvent {
/** Event type */
type: "granted" | "revoked" | "expired";
/** Permission details */
permission: GrantedPermission;
/** Block number where event occurred */
blockNumber: bigint;
/** Transaction hash */
transactionHash: Hash;
/** Event timestamp */
timestamp: number;
}
/**
* Enhanced trusted server information with trust status
*
* @category Permissions
*/
interface TrustedServerInfo {
/** Server ID (address) */
serverId: Address;
/** Server URL */
url: string;
/** Whether this server is trusted by the user */
isTrusted: boolean;
/** Index in user's trusted server list (if trusted) */
trustIndex?: number;
}
/**
* Paginated result for trusted server queries
*
* @category Permissions
*/
interface PaginatedTrustedServers {
/** Array of server addresses */
servers: Address[];
/** Total number of trusted servers */
total: number;
/** Offset used for this query */
offset: number;
/** Limit used for this query */
limit: number;
/** Whether there are more servers beyond this page */
hasMore: boolean;
}
/**
* Options for querying trusted servers
*
* @category Permissions
*/
interface TrustedServerQueryOptions {
/** User address to query (defaults to current user) */
userAddress?: Address;
/** Maximum number of servers to return */
limit?: number;
/** Offset for pagination */
offset?: number;
/** Whether to include full server info or just IDs */
includeServerInfo?: boolean;
}
/**
* Result of batch server info requests
*
* @category Permissions
*/
interface BatchServerInfoResult {
/** Successfully retrieved server info */
servers: Map<Address, {
url: string;
}>;
/** Server IDs that failed to retrieve */
failed: Address[];
}
/**
* Server trust status information
*
* @category Permissions
*/
interface ServerTrustStatus {
/** Server ID being checked */
serverId: Address;
/** Whether the server is trusted by the user */
isTrusted: boolean;
/** Index in user's trusted server list (if trusted) */
trustIndex?: number;
}
/**
* Configuration for storage providers used by the SDK.
*
* Allows you to configure multiple storage backends (IPFS, Pinata, Google Drive, etc.)
* and specify which one to use by default for file operations.
*
* @category Configuration
* @example
* ```typescript
* const storage: StorageConfig = {
* providers: {
* ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' }),
* pinata: new PinataStorage({ apiKey: 'your-key', secretKey: 'your-secret' })
* },
* defaultProvider: 'ipfs'
* };
* ```
*/
interface StorageConfig {
/** Map of provider name to storage provider instance */
providers: Record<string, StorageProvider>;
/** Default provider name to use when none specified */
defaultProvider?: string;
}
/**
* Relayer callback functions for handling gasless transactions.
*
* Instead of hardcoding HTTP/REST API calls, users can provide custom callback
* functions to handle transaction relay in any way they choose (HTTP, WebSocket,
* direct blockchain submission, etc.).
*
* @category Configuration
* @example
* ```typescript
* const relayerCallbacks: RelayerCallbacks = {
* async submitPermissionGrant(typedData, signature) {
* // Custom implementation - could be HTTP, WebSocket, etc.
* const response = await fetch('https://my-relayer.com/api/grant', {
* method: 'POST',
* headers: { 'Content-Type': 'application/json' },
* body: JSON.stringify({ typedData, signature })
* });
* const result = await response.json();
* return result.transactionHash;
* },
*
* async submitFileAddition(url, userAddress) {
* // Custom relay implementation
* return await myCustomRelayer.addFile(url, userAddress);
* }
* };
* ```
*/
interface RelayerCallbacks {
/**
* Submit a signed permission grant transaction for relay
*
* @param typedData - The EIP-712 typed data that was signed
* @param signature - The user's signature
* @returns Promise resolving to the transaction hash
*/
submitPermissionGrant?: (typedData: PermissionGrantTypedData, signature: Hash) => Promise<Hash>;
/**
* Submit a signed permission revocation transaction for relay
*
* @param typedData - The EIP-712 typed data that was signed
* @param signature - The user's signature
* @returns Promise resolving to the transaction hash
*/
submitPermissionRevoke?: (typedData: GenericTypedData, signature: Hash) => Promise<Hash>;
/**
* Submit a signed trust server transaction for relay
*
* @param typedData - The EIP-712 typed data that was signed
* @param signature - The user's signature
* @returns Promise resolving to the transaction hash
*/
submitTrustServer?: (typedData: TrustServerTypedData, signature: Hash) => Promise<Hash>;
/**
* Submit a signed untrust server transaction for relay
*
* @param typedData - The EIP-712 typed data that was signed
* @param signature - The user's signature
* @returns Promise resolving to the transaction hash
*/
submitUntrustServer?: (typedData: UntrustServerTypedData, signature: Hash) => Promise<Hash>;
/**
* Submit a file addition for relay
*
* @param url - The file URL to register
* @param userAddress - The user's address
* @returns Promise resolving to object with fileId and transactionHash
*/
submitFileAddition?: (url: string, userAddress: string) => Promise<{
fileId: number;
transactionHash: Hash;
}>;
/**
* Submit a file addition with permissions for relay
*
* @param url - The file URL to register
* @param userAddress - The user's address
* @param permissions - Array of encrypted permissions
* @returns Promise resolving to object with fileId and transactionHash
*/
submitFileAdditionWithPermissions?: (url: string, userAddress: string, permissions: Array<{
account: string;
key: string;
}>) => Promise<{
fileId: number;
transactionHash: Hash;
}>;
/**
* Store a grant file for relay (e.g., upload to IPFS)
*
* @param grantData - The grant file data
* @returns Promise resolving to the storage URL
*/
storeGrantFile?: (grantData: GrantFile) => Promise<string>;
}
/**
* Base configuration interface
*
* @category Configuration
*/
interface BaseConfig {
/**
* Optional relayer callback functions for handling gasless transactions.
* Provides flexible relay mechanism - can use HTTP, WebSocket, or any custom implementation.
*/
relayerCallbacks?: RelayerCallbacks;
/** Optional storage providers configuration for file upload/download */
storage?: StorageConfig;
/**
* Optional subgraph URL for querying user files and permissions.
* If not provided, defaults to the built-in subgraph URL for the current chain.
* Can be overridden per method call if needed.
*/
subgraphUrl?: string;
}
/**
* Configuration with wallet client
*
* @category Configuration
*/
interface WalletConfig extends BaseConfig {
/** The viem WalletClient instance used for signing transactions */
walletClient: WalletClient & {
chain: VanaChain;
};
}
/**
* Configuration with chain and account details
*
* @category Configuration
*/
interface ChainConfig extends BaseConfig {
/** The chain ID for Vana network */
chainId: VanaChainId;
/** RPC URL for the chain (optional, will use default for the chain if not provided) */
rpcUrl?: string;
/** Optional account for signing transactions */
account?: Account;
}
/**
* Main configuration interface for initializing the Vana SDK.
*
* You can configure the SDK using either a pre-configured wallet client
* (WalletConfig) or by providing chain and account details (ChainConfig).
* Both approaches support optional storage providers and relayer configuration.
*
* @category Configuration
* @example
* ```typescript
* // Using WalletConfig with pre-configured client
* const config: VanaConfig = {
* walletClient: createWalletClient({
* account: privateKeyToAccount('0x...'),
* chain: moksha,
* transport: http()
* }),
* relayerCallbacks: {
* submitPermissionGrant: async (typedData, signature) => {
* // Custom relay implementation
* return await myRelayer.submit(typedData, signature);
* }
* }
* };
*
* // Using ChainConfig with chain ID and account
* const config: VanaConfig = {
* chainId: 14800,
* account: privateKeyToAccount('0x...'),
* relayerCallbacks: {
* submitPermissionGrant: async (typedData, signature) => {
* // Custom relay implementation
* return await myRelayer.submit(typedData, signature);
* }
* }
* };
* ```
*/
type VanaConfig = WalletConfig | ChainConfig;
/**
* Runtime configuration information
*
* @category Configuration
*/
interface RuntimeConfig {
/** Current chain ID */
chainId: VanaChainId;
/** Current chain name */
chainName: string;
/** Available storage providers */
storageProviders: string[];
/** Default storage provider */
defaultStorageProvider?: string;
/** Current relayer callbacks configuration */
relayerCallbacks?: RelayerCallbacks;
}
/**
* Validates whether a configuration object is a WalletConfig.
*
* @param config - The configuration object to check
* @returns True if the config is a WalletConfig (contains walletClient)
* @example
* ```typescript
* if (isWalletConfig(config)) {
* console.log('Using wallet client:', config.walletClient.account?.address);
* } else {
* console.log('Using chain config with chain ID:', config.chainId);
* }
* ```
*/
declare function isWalletConfig(config: VanaConfig): config is WalletConfig;
/**
* Validates whether a configuration object is a ChainConfig.
*
* @param config - The configuration object to check
* @returns True if the config is a ChainConfig (contains chainId but not walletClient)
* @example
* ```typescript
* if (isChainConfig(config)) {
* console.log('Chain ID:', config.chainId);
* console.log('RPC URL:', config.rpcUrl);
* } else {
* console.log('Using pre-configured wallet client');
* }
* ```
*/
declare function isChainConfig(config: VanaConfig): config is ChainConfig;
/**
* Configuration validation options
*
* @category Configuration
*/
interface ConfigValidationOptions {
/** Whether to validate storage providers */
validateStorage?: boolean;
/** Whether to validate relayer URL */
validateRelayer?: boolean;
/** Whether to validate chain configuration */
validateChain?: boolean;
}
/**
* Configuration validation result
*
* @category Configuration
*/
interface ConfigValidationResult {
/** Whether the configuration is valid */
valid: boolean;
/** List of validation errors */
errors: string[];
/** List of validation warnings */
warnings: string[];
}
/**
* Union type of all canonical Vana contract names
*/
type VanaContractName = "DataPermissions" | "DataRegistry" | "TeePool" | "ComputeEngine" | "TeePoolPhala" | "DataRefinerRegistry" | "QueryEngine" | "ComputeInstructionRegistry" | "TeePoolEphemeralStandard" | "TeePoolPersistentStandard" | "TeePoolPersistentGpu" | "TeePoolDedicatedStandard" | "TeePoolDedicatedGpu" | "VanaEpoch" | "DLPRegistry" | "DLPRegistryTreasury" | "DLPPerformance" | "DLPRewardDeployer" | "DLPRewardDeployerTreasury" | "DLPRewardSwap" | "SwapHelper" | "VanaPoolStaking" | "VanaPoolEntity" | "VanaPoolTreasury" | "DAT" | "DATFactory" | "DATPausable" | "DATVotes" | "DataLiquidityPool" | "DLPRoot";
/**
* Contract information with typed address and ABI
*/
interface ContractInfo<TAbi extends Abi = Abi> {
/** The contract's deployed address */
address: Address;
/** The contract's ABI */
abi: TAbi;
}
/**
* Contract deployment information
*/
interface ContractDeployment {
/** The contract's deployed address */
address: Address;
/** Block number where contract was deployed */
blockNumber: bigint;
/** Transaction hash of deployment */
transactionHash: Hash;
}
/**
* Typed contract instance
*/
type VanaContractInstance<TAbi extends Abi = Abi> = GetContractReturnType<TAbi>;
/**
* Contract addresses mapping by chain and contract name
*/
type ContractAddresses = {
[chainId: number]: {
[contractName in VanaContractName]?: Address;
};
};
/**
* Contract method parameters for typed interactions
*/
type ContractMethodParams<TAbi extends Abi, TFunctionName extends string> = TAbi extends readonly unknown[] ? TAbi[number] extends {
name: TFunctionName;
type: "function";
inputs: infer TInputs;
} ? TInputs extends readonly unknown[] ? {
[K in keyof TInputs]: TInputs[K] extends {
name: infer TName;
type: infer TType;
} ? TName extends string ? TType extends "address" ? Address : TType extends "uint256" ? bigint : TType extends "string" ? string : TType extends "bool" ? boolean : TType extends "bytes32" ? Hash : unknown : never : never;
} : never : never : never;
/**
* Contract method return type for typed interactions
*/
type ContractMethodReturnType<TAbi extends Abi, TFunctionName extends string> = TAbi extends readonly unknown[] ? TAbi[number] extends {
name: TFunctionName;
type: "function";
outputs: infer TOutputs;
} ? TOutputs extends readonly unknown[] ? TOutputs["length"] extends 1 ? TOutputs[0] extends {
type: infer TType;
} ? TType extends "address" ? Address : TType extends "uint256" ? bigint : TType extends "string" ? string : TType extends "bool" ? boolean : TType extends "bytes32" ? Hash : unknown : unknown : {
[K in keyof TOutputs]: TOutputs[K] extends {
name: infer TName;
type: infer TType;
} ? TName extends string ? TType extends "address" ? Address : TType extends "uint256" ? bigint : TType extends "string" ? string : TType extends "bool" ? boolean : TType extends "bytes32" ? Hash : unknown : never : never;
} : never : never : never;
/**
* Represents a registered data file in the Vana network with complete blockchain metadata.
*
* @remarks
* This interface describes files that have been uploaded to storage and registered
* on the Vana blockchain, including their storage location, ownership, and blockchain
* tracking information. Each file receives a unique ID and is linked to the owner's
* address for permission management. Used throughout the SDK for file operations
* and access control workflows.
*
* @category Data Management
*/
interface UserFile$1 {
/** Unique identifier assigned by the Data Registry contract. */
id: number;
/** Storage URL where the encrypted file content is hosted. */
url: string;
/** Wallet address of the user who owns this file. */
ownerAddress: Address;
/** Block number when this file was registered on-chain. */
addedAtBlock: bigint;
/** Schema identifier for data validation and structure definition. */
schemaId?: number;
/** Unix timestamp when the file was registered on-chain. */
addedAtTimestamp?: bigint;
/** Transaction hash of the on-chain file registration. */
transactionHash?: Address;
/** Additional file properties and custom application data. */
metadata?: FileMetadata;
}
/**
* Provides optional metadata for uploaded files and content description.
*
* @remarks
* This interface contains descriptive information about uploaded files, including
* file properties and custom application-specific data that can be used for
* organization, validation, and display purposes.
* @category Data Management
*/
interface FileMetadata {
/** Original filename as provided by the user or application. */
name?: string;
/** Total file size in bytes for storage tracking. */
size?: number;
/** MIME type identifier for content type recognition. */
mimeType?: string;
/** Hash value for file integrity verification. */
checksum?: string;
/** ISO 8601 timestamp when the file was uploaded. */
uploadedAt?: string;
/** Application-specific metadata for custom use cases. */
custom?: Record<string, unknown>;
}
/**
* Defines parameters for uploading files to storage providers with encryption options.
*
* @remarks
* Used with DataController upload methods and storage operations. Supports multiple
* content formats, optional encryption, and custom storage provider selection with
* comprehensive metadata tracking.
* @example
* ```typescript
* const uploadParams: UploadFileParams = {
* content: new TextEncoder().encode(JSON.stringify(userData)),
* metadata: {
* name: "personal-profile.json",
* mimeType: "application/json",
* size: 2048,
* },
* storageProvider: "ipfs",
* encrypt: true,
* };
*
* const result = await vana.data.uploadFile(uploadParams);
* ```
* @category Data Management
*/
interface UploadFileParams {
/** Raw file data in bytes, buffer, or string format. */
content: Uint8Array | Buffer | string;
/** Descriptive metadata for file organization and tracking. */
metadata?: FileMetadata;
/** Storage provider name or uses configured default if unspecified. */
storageProvider?: string;
/** Enables automatic encryption before upload to storage. */
encrypt?: boolean;
/** Custom encryption key or generates one automatically if encryption enabled. */
encryptionKey?: string;
}
/**
* Contains the result of a successful file upload operation.
*
* @remarks
* This interface provides the essential information returned after uploading
* a file to a storage provider, including access URL, size verification,
* and encryption details when applicable.
* @category Data Management
*/
interface UploadFileResult {
/** Public URL where the uploaded file can be accessed. */
url: string;
/** Actual file size in bytes after upload processing. */
size: number;
/** Hash value for verifying file integrity after upload. */
checksum?: string;
/** Encryption metadata when file was encrypted before storage. */
encryption?: EncryptionInfo;
}
/**
* Result of uploading an encrypted file to storage and blockchain
*
* @category Data Management
*/
interface UploadEncryptedFileResult extends UploadFileResult {
/** The new file ID assigned by the DataRegistry */
fileId: number;
/** Transaction hash of the file registration */
transactionHash?: Hash;
}
/**
* Encryption information for a file
*
* @category Data Management
*/
interface EncryptionInfo {
/** Encryption algorithm used */
algorithm: string;
/** Key derivation function */
kdf?: string;
/** Initialization vector */
iv?: string;
/** Salt used for key derivation */
salt?: string;
/** Key identifier */
keyId?: string;
}
/**
* Parameters for getting user files
*
* @category Data Management
*/
interface GetUserFilesParams {
/** Owner address to filter by */
owner?: Address;
/** Starting block number for filtering */
fromBlock?: bigint;
/** Ending block number for filtering */
toBlock?: bigint;
/** Maximum number of files to return */
limit?: number;
/** Offset for pagination */
offset?: number;
}
/**
* Parameters for getting a specific file
*
* @category Data Management
*/
interface GetFileParams {
/** File ID to retrieve */
fileId: number;
/** Whether to include metadata */
includeMetadata?: boolean;
}
/**
* Parameters for downloading a file
*
* @category Data Management
*/
interface DownloadFileParams {
/** File URL or ID to download */
file: string | number;
/** Storage provider to use */
storageProvider?: string;
/** Decryption key if file is encrypted */
decryptionKey?: string;
}
/**
* Result of downloading a file
*
* @category Data Management
*/
interface DownloadFileResult {
/** File content */
content: Uint8Array;
/** File metadata */
metadata?: FileMetadata;
/** Whether the file was encrypted */
wasEncrypted?: boolean;
}
/**
* Parameters for deleting a file
*
* @category Data Management
*/
interface DeleteFileParams {
/** File ID to delete */
fileId: number;
/** Whether to also delete from storage */
deleteFromStorage?: boolean;
/** Storage provider to delete from */
storageProvider?: string;
}
/**
* Result of deleting a file
*
* @category Data Management
*/
interface DeleteFileResult {
/** Whether the file was successfully deleted from the registry */
registryDeleted: boolean;
/** Whether the file was successfully deleted from storage */
storageDeleted?: boolean;
/** Transaction hash of the deletion */
transactionHash?: Hash;
}
/**
* File access permissions
*
* @category Data Management
*/
interface FileAccessPermissions {
/** Whether the file can be read */
read: boolean;
/** Whether the file can be written */
write: boolean;
/** Whether the file can be deleted */
delete: boolean;
/** Whether the file can be shared */
share: boolean;
}
/**
* File sharing configuration
*
* @category Data Management
*/
interface FileSharingConfig {
/** Addresses that can access the file */
allowedAddresses?: Address[];
/** Expiration time for shared access */
expiresAt?: Date;
/** Required permissions for shared access */
permissions: FileAccessPermissions;
}
/**
* Batch upload parameters
*
* @category Data Management
*/
interface BatchUploadParams {
/** Array of files to upload */
files: UploadFileParams[];
/** Storage provider to use for all files */
storageProvider?: string;
/** Whether to encrypt all files */
encrypt?: boolean;
/** Encryption key for all files */
encryptionKey?: string;
}
/**
* Batch upload result
*
* @category Data Management
*/
interface BatchUploadResult {
/** Results for each uploaded file */
results: UploadEncryptedFileResult[];
/** Overall success status */
success: boolean;
/** Any errors that occurred */
errors?: string[];
}
/**
* Represents a data schema in the refiner registry.
*
* Schemas define the structure and validation rules for user data processed by refiners.
* They ensure data quality and consistency across the Vana network by specifying how
* raw user data should be formatted, validated, and processed.
*
* @category Data Management
* @example
* ```typescript
* const socialMediaSchema: Schema = {
* id: 5,
* name: 'Social Media Profile',
* type: 'JSON',
* url: 'ipfs://QmSchema...', // Schema definition file
* description: 'Schema for validating social media profile data'
* };
* ```
*/
interface Schema {
/** Schema ID */
id: number;
/** Schema name */
name: string;
/** Schema type */
type: string;
/** URL containing the schema definition */
definitionUrl: string;
}
/**
* Represents a refiner with schema information
*
* @category Data Management
*/
interface Refiner {
/** Refiner ID */
id: number;
/** DLP ID this refiner belongs to */
dlpId: number;
/** Owner address */
owner: Address;
/** Refiner name */
name: string;
/** Schema ID associated with this refiner */
schemaId: number;
/** URL containing refinement instructions */
refinementInstructionUrl: string;
}
/**
* Parameters for adding a new schema
*
* @category Data Management
*/
interface AddSchemaParams {
/** Schema name */
name: string;
/** Schema type */
type: string;
/** URL containing the schema definition */
definitionUrl: string;
}
/**
* Result of adding a schema
*
* @category Data Management
*/
interface AddSchemaResult {
/** The new schema ID assigned by the contract */
schemaId: number;
/** Transaction hash of the schema registration */
transactionHash: Hash;
}
/**
* 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.
*
* @category Data Management
* @example
* ```typescript
* const refinerParams: AddRefinerParams = {
* dlpId: 1, // Data Liquidity Pool ID
* name: 'Social Media Refiner',
* schemaId: 5, // Pre-defined schema for social media data
* refinementInstructionUrl: 'ipfs://Qm...' // Instructions for data processing
* };
* ```
*/
interface AddRefinerParams {
/** DLP ID this refiner belongs to */
dlpId: number;
/** Refiner name */
name: string;
/** Schema ID to associate with this refiner */
schemaId: number;
/** URL containing refinement instructions */
refinementInstructionUrl: string;
}
/**
* Result of adding a refiner
*
* @category Data Management
*/
interface AddRefinerResult {
/** The new refiner ID assigned by the contract */
refinerId: number;
/** Transaction hash of the refiner registration */
transactionHash: Hash;
}
/**
* Parameters for updating a refiner's schema ID
*
* @category Data Management
*/
interface UpdateSchemaIdParams {
/** Refiner ID to update */
refinerId: number;
/** New schema ID to associate with the refiner */
newSchemaId: number;
}
/**
* Result of updating a refiner's schema ID
*
* @category Data Management
*/
interface UpdateSchemaIdResult {
/** Transaction hash of the update */
transactionHash: Hash;
}
/**
* Query mode for trusted server retrieval
*
* @category Data Management
*/
type TrustedServerQueryMode = "subgraph" | "rpc" | "auto";
/**
* Trusted server data structure (unified format for both subgraph and RPC modes)
*
* @category Data Management
*/
interface TrustedServer {
/** Unique identifier for the trusted server relationship */
id: string;
/** Server address (EVM address) */
serverAddress: Address;
/** Server URL */
serverUrl: string;
/** Timestamp when server was trusted */
trustedAt: bigint;
/** User who trusted the server */
user: Address;
/** Index in user's trusted server list (only available in RPC mode) */
trustIndex?: number;
}
/**
* Parameters for getUserTrustedServers with dual-mode support
*
* @category Data Management
*/
interface GetUserTrustedServersParams {
/** User address to query */
user: Address;
/** Query mode: 'subgraph' (fast, requires subgraph), 'rpc' (direct contract), or 'auto' (tries subgraph first) */
mode?: TrustedServerQueryMode;
/** Subgraph URL (required for subgraph mode) */
subgraphUrl?: string;
/** Pagination limit (applies to RPC mode) */
limit?: number;
/** Pagination offset (applies to RPC mode) */
offset?: number;
}
/**
* Result of getUserTrustedServers query
*
* @category Data Management
*/
interface GetUserTrustedServersResult {
/** Array of trusted servers */
servers: TrustedServer[];
/** Query mode that was actually used */
usedMode: TrustedServerQueryMode;
/** Total count (only available in RPC mode) */
total?: number;
/** Whether there are more servers (pagination info for RPC mode) */
hasMore?: boolean;
/** Any warnings or fallback information */
warnings?: string[];
}
/**
* Data schema interface following the Vana schema specification
*
* @category Configuration
*/
interface DataSchema {
/** The name of the data schema */
name: string;
/** The version of the data schema */
version: string;
/** Optional description of the data schema */
description?: string;
/** The dialect type - either SQLite or JSON */
dialect: "sqlite" | "json";
/** Optional version of the dialect */
dialectVersion?: string;
/** The actual schema definition as string or object */
schema: string | object;
}
/**
* Error thrown when schema validation fails
*/
declare class SchemaValidationError extends Error {
errors: Array<{
instancePath: string;
schemaPath: string;
keyword: string;
params: Record<string, unknown>;
message?: string;
}>;
constructor(message: string, errors: Array<{
instancePath: string;
schemaPath: string;
keyword: string;
params: Record<string, unknown>;
message?: string;
}>);
}
/**
* Schema validation utility class
*/
declare class SchemaValidator {
private ajv;
private dataSchemaValidator;
constructor();
/**
* Validates a data schema against the Vana meta-schema
*
* @param schema - The data schema to validate
* @throws SchemaValidationError if invalid
* @example
* ```typescript
* const validator = new SchemaValidator();
*
* const schema = {
* name: "User Profile",
* version: "1.0.0",
* dialect: "json",
* schema: {
* type: "object",
* properties: {
* name: { type: "string" },
* age: { type: "number" }
* }
* }
* };
*
* validator.validateDataSchema(schema); // throws if invalid
* ```
*/
validateDataSchema(schema: unknown): asserts schema is DataSchema;
/**
* Validates data against a JSON Schema from a data schema
*
* @param data - The data to validate
* @param schema - The data schema containing the schema
* @throws SchemaValidationError if invalid
* @example
* ```typescript
* const validator = new SchemaValidator();
*
* 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 };
* validator.validateDataAgainstSchema(userData, schema);
* ```
*/
validateDataAgainstSchema(data: unknown, schema: DataSchema): void;
/**
* Validates a SQLite DDL string for basic syntax
* Note: This is a basic validation, full SQL parsing would require a proper SQL parser
*
* @param ddl - The DDL string to validate
* @param dialectVersion - Optional SQLite version (e.g., "3" for SQLite v3)
* @throws SchemaValidationError if invalid
*/
validateSQLiteDDL(ddl: string, dialectVersion?: string): void;
/**
* Fetches and validates a schema from a URL
*
* @param url - The URL to fetch the schema from
* @returns The validated data schema
* @throws SchemaValidationError if invalid or fetch fails
* @example
* ```typescript
* const validator = new SchemaValidator();
* const schema = await validator.fetchAndValidateSchema("https://example.com/schema.json");
* ```
*/
fetchAndValidateSchema(url: string): Promise<DataSchema>;
}
/**
* Global schema validator instance
*/
declare const schemaValidator: SchemaValidator;
/**
* Convenience function to validate a data schema
*
* @param schema - The data schema to validate
* @returns void - Assertion function that doesn't return a value
* @throws SchemaValidationError if invalid
*/
declare function validateDataSchema(schema: unknown): asserts schema is DataSchema;
/**
* Convenience function to validate data against a schema
*
* @param data - The data to validate
* @param schema - The data schema containing the schema
* @returns void - Function doesn't return a value
* @throws SchemaValidationError if invalid
*/
declare function validateDataAgainstSchema(data: unknown, schema: DataSchema): void;
/**
* Convenience function to fetch and validate a schema from a URL
*
* @param url - The URL to fetch the schema from
* @returns The validated data schema
* @throws SchemaValidationError if invalid or fetch fails
*/
declare function fetchAndValidateSchema(url: string): Promise<DataSchema>;
/**
* Parameters for the `vana.personal.postRequest` method.
*/
interface PostRequestParams {
/** The permission ID */
permissionId: number;
}
/**
* Parameters for the `vana.personal.initPersonalServer` method.
*/
interface InitPersonalServerParams {
/** The user's wallet address */
userAddress: string;
}
/**
* Response from the personal server containing a link to get results or cancel computation.
*/
interface ReplicatePredictionResponse {
/** The prediction ID for tracking the computation */
id: string;
/** The status of the computation */
status: "starting" | "processing" | "succeeded" | "failed" | "canceled";
/** URL to check the status and get results */
urls: {
get: string;
cancel: string;
};
/** The input parameters used for the computation */
input: Record<string, unknown>;
/** Optional output if computation is complete */
output?: unknown;
/** Opti