@opendatalabs/vana-sdk 0.1.0-alpha.8fd7ef5 → 0.1.0-alpha.a145c3c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -236,7 +236,8 @@ interface GrantPermissionParams$1 {
236
236
  grantee: Address;
237
237
  /** The class of computation, e.g., "llm_inference" */
238
238
  operation: string;
239
- /** Array of file IDs to grant permission for */
239
+ /** Array of file IDs to grant permission for.
240
+ * Obtain file IDs from `vana.data.getUserFiles()` or from upload results via `vana.data.upload().fileId`. */
240
241
  files: number[];
241
242
  /** The full, off-chain parameters (e.g., LLM prompt) */
242
243
  parameters: Record<string, unknown>;
@@ -785,6 +786,12 @@ interface StorageRequiredMarker {
785
786
  * Allows you to configure multiple storage backends (IPFS, Pinata, Google Drive, etc.)
786
787
  * and specify which one to use by default for file operations.
787
788
  *
789
+ * **Provider Selection:**
790
+ * - IPFS: Decentralized, permanent storage ideal for production
791
+ * - Pinata: Managed IPFS with guaranteed availability
792
+ * - Google Drive: Centralized, suitable for development/testing
793
+ * - Custom providers: Implement StorageProvider interface
794
+ *
788
795
  * @category Configuration
789
796
  * @example
790
797
  * ```typescript
@@ -798,9 +805,12 @@ interface StorageRequiredMarker {
798
805
  * ```
799
806
  */
800
807
  interface StorageConfig {
801
- /** Map of provider name to storage provider instance */
808
+ /** Map of provider name to storage provider instance.
809
+ * Common provider names: "ipfs", "pinata", "googledrive", "s3".
810
+ * Custom names allowed for custom provider implementations. */
802
811
  providers: Record<string, StorageProvider>;
803
- /** Default provider name to use when none specified */
812
+ /** Default provider name to use when none specified.
813
+ * Must match a key in the providers map. Falls back to first provider if not specified. */
804
814
  defaultProvider?: string;
805
815
  }
806
816
  /**
@@ -937,18 +947,22 @@ interface BaseConfig {
937
947
  * Provides flexible relay mechanism - can use HTTP, WebSocket, or any custom implementation.
938
948
  */
939
949
  relayerCallbacks?: RelayerCallbacks;
940
- /** Optional storage providers configuration for file upload/download */
950
+ /** Optional storage providers configuration for file upload/download.
951
+ * Required for: upload(), grant() without pre-stored URLs, schema operations.
952
+ * See StorageConfig for provider selection guidance. */
941
953
  storage?: StorageConfig;
942
954
  /**
943
955
  * Optional subgraph URL for querying user files and permissions.
944
956
  * If not provided, defaults to the built-in subgraph URL for the current chain.
945
957
  * Can be overridden per method call if needed.
958
+ * Obtain chain-specific URLs from Vana documentation or deployment info.
946
959
  */
947
960
  subgraphUrl?: string;
948
961
  /**
949
962
  * Optional default IPFS gateways to use for fetching files.
950
963
  * These gateways will be used by default in fetchFromIPFS unless overridden per-call.
951
964
  * If not provided, the SDK will use public gateways.
965
+ * Order matters: first successful gateway is used.
952
966
  *
953
967
  * @example ['https://gateway.pinata.cloud', 'https://ipfs.io']
954
968
  */
@@ -1010,11 +1024,17 @@ interface WalletConfigWithStorage extends BaseConfigWithStorage {
1010
1024
  * @category Configuration
1011
1025
  */
1012
1026
  interface ChainConfig extends BaseConfig {
1013
- /** The chain ID for Vana network */
1027
+ /** The chain ID for Vana network.
1028
+ * Supported: 14800 (Vana Mainnet), 14801 (Moksha Testnet), 31337 (Local Development).
1029
+ * Use chain constants from '@vana/sdk' for type safety. */
1014
1030
  chainId: VanaChainId;
1015
- /** RPC URL for the chain (optional, will use default for the chain if not provided) */
1031
+ /** RPC URL for the chain (optional, will use default for the chain if not provided).
1032
+ * Default URLs: mainnet (https://rpc.vana.org), testnet (https://rpc.moksha.vana.org).
1033
+ * Override for custom nodes or local development. */
1016
1034
  rpcUrl?: string;
1017
- /** Optional account for signing transactions */
1035
+ /** Optional account for signing transactions.
1036
+ * Can be: privateKeyToAccount(), mnemonicToAccount(), or custom Account implementation.
1037
+ * Required for write operations; read-only operations work without account. */
1018
1038
  account?: Account;
1019
1039
  }
1020
1040
  /**
@@ -1272,7 +1292,8 @@ interface UserFile$1 {
1272
1292
  ownerAddress: Address;
1273
1293
  /** Block number when this file was registered on-chain. */
1274
1294
  addedAtBlock: bigint;
1275
- /** Schema identifier for data validation and structure definition. */
1295
+ /** Schema identifier for data validation and structure definition.
1296
+ * Obtain schema IDs from `vana.schemas.list()` or when creating schemas via `vana.schemas.create()`. */
1276
1297
  schemaId?: number;
1277
1298
  /** Unix timestamp when the file was registered on-chain. */
1278
1299
  addedAtTimestamp?: bigint;
@@ -1403,15 +1424,16 @@ interface UnencryptedUploadParams extends Omit<UploadParams, "encrypt"> {
1403
1424
  interface PermissionParams {
1404
1425
  /** The address of the application to grant permission to. */
1405
1426
  grantee: Address;
1406
- /** The operation type (e.g., "llm_inference"). */
1427
+ /** The operation type (e.g., "llm_inference", "data_analysis", "compute_task"). */
1407
1428
  operation: string;
1408
- /** Additional parameters for the permission. */
1429
+ /** Additional parameters for the permission (operation-specific configuration). */
1409
1430
  parameters: Record<string, unknown>;
1410
- /** Optional nonce for the permission. */
1431
+ /** Optional nonce for the permission (auto-generated if not provided). */
1411
1432
  nonce?: bigint;
1412
- /** Optional expiration timestamp. */
1433
+ /** Optional expiration timestamp (Unix seconds, no expiration if not provided). */
1413
1434
  expiresAt?: number;
1414
- /** Public key of the recipient to encrypt the data key for (required for upload with permissions). */
1435
+ /** Public key of the recipient to encrypt the data key for (required for upload with permissions).
1436
+ * Obtain via `vana.server.getIdentity(recipientAddress).public_key` for personal servers. */
1415
1437
  publicKey?: string;
1416
1438
  }
1417
1439
  /**
@@ -1479,11 +1501,11 @@ interface UploadFileParams {
1479
1501
  content: Uint8Array | Buffer | string;
1480
1502
  /** Descriptive metadata for file organization and tracking. */
1481
1503
  metadata?: FileMetadata;
1482
- /** Storage provider name or uses configured default if unspecified. */
1504
+ /** Storage provider name ("ipfs" or custom provider, uses configured default if unspecified). */
1483
1505
  storageProvider?: string;
1484
- /** Enables automatic encryption before upload to storage. */
1506
+ /** Enables automatic encryption before upload to storage (defaults to false). */
1485
1507
  encrypt?: boolean;
1486
- /** Custom encryption key or generates one automatically if encryption enabled. */
1508
+ /** Custom encryption key (auto-generated if encryption enabled and not provided). */
1487
1509
  encryptionKey?: string;
1488
1510
  }
1489
1511
  /**
@@ -2558,6 +2580,15 @@ declare class StorageManager {
2558
2580
  *
2559
2581
  * This interface abstracts all environment-specific dependencies to ensure
2560
2582
  * the SDK works seamlessly across Node.js and browser/SSR environments.
2583
+ *
2584
+ * **Implementation Context:**
2585
+ * - Node.js: Uses native crypto modules and full OpenPGP support
2586
+ * - Browser: Uses Web Crypto API and browser-compatible libraries
2587
+ * - SSR: Automatically selects appropriate implementation based on runtime
2588
+ *
2589
+ * **Usage Notes:**
2590
+ * Platform adapters are automatically selected by the SDK. Direct usage is only
2591
+ * needed for custom implementations or testing.
2561
2592
  */
2562
2593
  /**
2563
2594
  * Platform type identifier
@@ -2570,6 +2601,11 @@ interface VanaCryptoAdapter {
2570
2601
  /**
2571
2602
  * Encrypt data with a public key using asymmetric cryptography
2572
2603
  *
2604
+ * **Usage Context:**
2605
+ * - Used internally for file encryption before storage
2606
+ * - Public key format: Armored PGP public key string
2607
+ * - Returns base64-encoded encrypted data
2608
+ *
2573
2609
  * @param data The data to encrypt
2574
2610
  * @param publicKey The public key for encryption
2575
2611
  * @returns Promise resolving to encrypted data
@@ -2596,6 +2632,11 @@ interface VanaCryptoAdapter {
2596
2632
  * Encrypt data with a wallet's public key using ECDH cryptography
2597
2633
  * Uses platform-appropriate ECDH implementation (eccrypto vs eccrypto-js)
2598
2634
  *
2635
+ * **Usage Context:**
2636
+ * - Used for sharing encryption keys with permission recipients
2637
+ * - Public key format: Compressed or uncompressed secp256k1 hex string
2638
+ * - Compatible with Ethereum wallet public keys
2639
+ *
2599
2640
  * @param data The data to encrypt (string)
2600
2641
  * @param publicKey The wallet's public key (secp256k1)
2601
2642
  * @returns Promise resolving to encrypted data as hex string
@@ -2682,6 +2723,22 @@ interface VanaHttpAdapter {
2682
2723
  }
2683
2724
  /**
2684
2725
  * Main platform adapter interface that combines all platform-specific functionality
2726
+ *
2727
+ * **Implementation Guidelines:**
2728
+ * 1. All methods must maintain consistent behavior across platforms
2729
+ * 2. Error types and messages should be unified
2730
+ * 3. Data formats (encoding, serialization) must be identical
2731
+ * 4. Performance characteristics can vary but API must be consistent
2732
+ *
2733
+ * **Custom Implementation Example:**
2734
+ * ```typescript
2735
+ * class CustomPlatformAdapter implements VanaPlatformAdapter {
2736
+ * crypto = new CustomCryptoAdapter();
2737
+ * pgp = new CustomPGPAdapter();
2738
+ * http = new CustomHttpAdapter();
2739
+ * platform = 'browser' as const;
2740
+ * }
2741
+ * ```
2685
2742
  */
2686
2743
  interface VanaPlatformAdapter {
2687
2744
  /**
@@ -2745,15 +2802,27 @@ interface ControllerContext$1 {
2745
2802
  * The controller also manages trusted servers that can process user data and provides
2746
2803
  * methods for revoking permissions when access is no longer needed.
2747
2804
  *
2748
- * All permission operations support both gasless transactions via relayers and direct
2749
- * blockchain transactions. Grant files containing detailed permission parameters are
2750
- * stored on IPFS while permission references are recorded on the blockchain.
2805
+ * **Permission Architecture:**
2806
+ * Permissions use dual storage: detailed parameters stored on IPFS, references stored on blockchain.
2807
+ * This enables complex permissions while maintaining minimal on-chain data.
2808
+ *
2809
+ * **Method Selection:**
2810
+ * - `grant()` creates new permissions with automatic IPFS upload and blockchain registration
2811
+ * - `prepareGrant()` allows preview before signing for interactive applications
2812
+ * - `revoke()` removes permissions by ID, supporting both gasless and direct transactions
2813
+ * - `getUserPermissionGrantsOnChain()` queries existing permissions efficiently
2814
+ * - `trustServer()` and `untrustServer()` manage server access for data processing
2815
+ *
2816
+ * **Transaction Types:**
2817
+ * Methods with gasless support: `grant()`, `revoke()`, `trustServer()`, `untrustServer()`
2818
+ * Methods requiring direct transactions: none (all support both gasless and direct)
2751
2819
  * @example
2752
2820
  * ```typescript
2753
2821
  * // Grant permission for an app to access your data
2754
2822
  * const txHash = await vana.permissions.grant({
2755
2823
  * grantee: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
2756
2824
  * operation: "llm_inference",
2825
+ * files: [1, 2, 3],
2757
2826
  * parameters: { model: "gpt-4", maxTokens: 1000 },
2758
2827
  * });
2759
2828
  *
@@ -2764,7 +2833,7 @@ interface ControllerContext$1 {
2764
2833
  * });
2765
2834
  *
2766
2835
  * // Query current permissions
2767
- * const permissions = await vana.permissions.getUserPermissions();
2836
+ * const permissions = await vana.permissions.getUserPermissionGrantsOnChain();
2768
2837
  * ```
2769
2838
  * @category Permissions
2770
2839
  * @see {@link [URL_PLACEHOLDER] | Vana Permissions System} for conceptual overview
@@ -2932,6 +3001,8 @@ declare class PermissionsController {
2932
3001
  * Revokes a previously granted permission.
2933
3002
  *
2934
3003
  * @param params - Parameters for revoking the permission
3004
+ * @param params.permissionId - Permission identifier as bigint for contract compatibility.
3005
+ * Obtain from permission grants via `getUserPermissionGrantsOnChain()`.
2935
3006
  * @returns Promise resolving to transaction hash
2936
3007
  * @example
2937
3008
  * ```typescript
@@ -3241,9 +3312,20 @@ interface CreateSchemaResult {
3241
3312
  * validation, IPFS upload, and blockchain registration. It provides methods for managing
3242
3313
  * both schemas (data structure definitions) and refiners (data processing definitions).
3243
3314
  *
3244
- * Schemas are public protocol entities that define data structures and validation rules.
3245
- * Unlike private user data, schemas are stored unencrypted on IPFS to enable public
3246
- * access and reusability across the network.
3315
+ * **Schema Storage:**
3316
+ * Schemas are stored unencrypted on IPFS for public access and reusability across the network.
3317
+ * Schema definitions use JSON Schema format for data validation and structure definition.
3318
+ *
3319
+ * **Method Selection:**
3320
+ * - `create()` validates, uploads to IPFS, and registers new schemas on blockchain
3321
+ * - `get()` retrieves existing schema metadata by ID from blockchain contracts
3322
+ * - `count()` returns total number of registered schemas for pagination
3323
+ * - `list()` provides paginated access to all schemas with optional filtering
3324
+ * - `addSchema()` provides lower-level schema registration with pre-uploaded URLs
3325
+ *
3326
+ * **Storage Requirements:**
3327
+ * Methods requiring storage configuration: `create()`
3328
+ * Methods working without storage: `get()`, `count()`, `list()`, `addSchema()`
3247
3329
  *
3248
3330
  * @example
3249
3331
  * ```typescript
@@ -5301,13 +5383,23 @@ interface GrantPermissionParams {
5301
5383
  * and supports both gasless transactions via relayers and direct blockchain interaction.
5302
5384
  * File metadata and access permissions are stored on the Vana blockchain while encrypted
5303
5385
  * file content is stored on decentralized storage networks.
5386
+ *
5387
+ * **Method Selection:**
5388
+ * - `upload()` handles encryption, storage, and blockchain registration automatically
5389
+ * - `getUserFiles()` queries existing file metadata from blockchain and subgraph
5390
+ * - `decryptFile()` decrypts files for which you have access permissions
5391
+ * - `getFileById()` retrieves specific file metadata when you have the file ID
5392
+ *
5393
+ * **Storage Requirements:**
5394
+ * Methods requiring storage configuration: `upload()`
5395
+ * Methods working without storage: `getUserFiles()`, `decryptFile()`, `getFileById()`
5304
5396
  * @example
5305
5397
  * ```typescript
5306
5398
  * // Upload an encrypted file with automatic schema validation
5307
- * const result = await vana.data.uploadEncryptedFile(
5308
- * encryptedBlob,
5309
- * "personal-data.json"
5310
- * );
5399
+ * const result = await vana.data.upload({
5400
+ * content: "My personal data",
5401
+ * filename: "personal-data.json"
5402
+ * });
5311
5403
  *
5312
5404
  * // Query files owned by a user
5313
5405
  * const files = await vana.data.getUserFiles({
@@ -5343,10 +5435,16 @@ declare class DataController {
5343
5435
  * for each permission recipient.
5344
5436
  *
5345
5437
  * @param params - Upload parameters including content, filename, schema, and permissions
5438
+ * @param params.permissions.publicKey - The recipient's public key for encryption.
5439
+ * Obtain via `vana.server.getIdentity(userAddress).public_key` for personal servers.
5440
+ * @param params.permissions.grantee - The application's wallet address that will access the data.
5346
5441
  * @returns Promise resolving to upload results with file ID and transaction hash
5347
- * @throws {Error} When wallet is not connected or storage is not configured
5348
- * @throws {SchemaValidationError} When schema validation fails
5349
- * @throws {Error} When upload or blockchain registration fails
5442
+ * @throws {Error} When wallet is not connected or storage is not configured.
5443
+ * Configure storage providers in VanaConfig or check wallet connection.
5444
+ * @throws {SchemaValidationError} When data format doesn't match the specified schema.
5445
+ * Verify data structure matches schema definition from `vana.schemas.get(schemaId)`.
5446
+ * @throws {Error} When upload or blockchain registration fails.
5447
+ * Check network connection and storage provider availability.
5350
5448
  * @example
5351
5449
  * ```typescript
5352
5450
  * // Basic file upload
@@ -5370,7 +5468,7 @@ declare class DataController {
5370
5468
  * grantee: "0x1234...",
5371
5469
  * operation: "llm_inference",
5372
5470
  * parameters: { model: "gpt-4" },
5373
- * publicKey: "0x04..." // Required when encrypt is true (default)
5471
+ * publicKey: "0x04..." // Obtain via vana.server.getIdentity(userAddress).public_key
5374
5472
  * }]
5375
5473
  * });
5376
5474
  *
@@ -5964,23 +6062,33 @@ declare class DataController {
5964
6062
  * cryptographic keys for secure data sharing. All server interactions use the
5965
6063
  * Replicate API infrastructure with proper authentication and error handling.
5966
6064
  *
5967
- * Personal servers enable privacy-preserving computation on user data, while identity
5968
- * servers provide deterministic key derivation for secure communication without
5969
- * requiring servers to be online during key retrieval.
6065
+ * **Server Identity System:**
6066
+ * Personal servers use deterministic key derivation: each user address maps to a specific server identity.
6067
+ * This enables secure communication without requiring servers to be online during key retrieval.
6068
+ *
6069
+ * **Method Selection:**
6070
+ * - `getIdentity()` retrieves server public keys and addresses for encryption setup
6071
+ * - `createOperation()` submits computation requests with signed permission verification
6072
+ * - `getOperation()` polls operation status and retrieves results when complete
6073
+ * - `cancelOperation()` stops running operations when cancellation is supported
6074
+ *
6075
+ * **Workflow Pattern:**
6076
+ * Typical flow: Get identity → Create operation → Poll status → Retrieve results
6077
+ *
5970
6078
  * @example
5971
6079
  * ```typescript
5972
- * // Post a request to a personal server
5973
- * const response = await vana.server.postRequest({
5974
- * permissionId: 123,
6080
+ * // Get a server's identity including public key for encryption
6081
+ * const identity = await vana.server.getIdentity({
6082
+ * userAddress: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
5975
6083
  * });
5976
6084
  *
5977
- * // Get a server's identity including public key for encryption
5978
- * const identity = await vana.server.getIdentity(
5979
- * "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
5980
- * );
6085
+ * // Create an operation using a granted permission
6086
+ * const response = await vana.server.createOperation({
6087
+ * permissionId: 123,
6088
+ * });
5981
6089
  *
5982
6090
  * // Poll for computation results
5983
- * const result = await vana.server.pollStatus(response.urls.get);
6091
+ * const result = await vana.server.getOperation(response.id);
5984
6092
  * ```
5985
6093
  * @category Server Management
5986
6094
  * @see {@link [URL_PLACEHOLDER] | Vana Personal Servers} for conceptual overview
@@ -5989,6 +6097,39 @@ declare class ServerController {
5989
6097
  private readonly context;
5990
6098
  readonly PERSONAL_SERVER_BASE_URL: string | undefined;
5991
6099
  constructor(context: ControllerContext$1);
6100
+ /**
6101
+ * Retrieves the cryptographic identity of a personal server.
6102
+ *
6103
+ * @remarks
6104
+ * This method fetches the public key and metadata for a personal server,
6105
+ * which is required for encrypting data before sharing with the server.
6106
+ * The identity includes the server's public key, address, and operational
6107
+ * details needed for secure communication. This information is cached
6108
+ * by identity servers to enable offline key retrieval.
6109
+ *
6110
+ * @param request - Parameters containing the user address
6111
+ * @param request.userAddress - The wallet address associated with the personal server
6112
+ * @returns Promise resolving to the server's identity information
6113
+ * @throws {NetworkError} When the identity service is unavailable or returns invalid data
6114
+ * @throws {PersonalServerError} When server identity cannot be retrieved
6115
+ * @example
6116
+ * ```typescript
6117
+ * // Get server identity for data encryption
6118
+ * const identity = await vana.server.getIdentity({
6119
+ * userAddress: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
6120
+ * });
6121
+ *
6122
+ * console.log(`Server: ${identity.name}`);
6123
+ * console.log(`Address: ${identity.address}`);
6124
+ * console.log(`Public Key: ${identity.public_key}`);
6125
+ *
6126
+ * // Use the public key for encrypting data to share with this server
6127
+ * const encryptedData = await encryptWithWalletPublicKey(
6128
+ * userData,
6129
+ * identity.public_key
6130
+ * );
6131
+ * ```
6132
+ */
5992
6133
  getIdentity(request: InitPersonalServerParams): Promise<PersonalServerIdentity>;
5993
6134
  /**
5994
6135
  * Creates an operation via the personal server API.
@@ -5997,10 +6138,13 @@ declare class ServerController {
5997
6138
  * This method submits a computation request to the personal server API.
5998
6139
  * The response includes the operation ID.
5999
6140
  * @param params - The request parameters object
6000
- * @param params.permissionId - The permission ID authorizing this operation
6141
+ * @param params.permissionId - The permission ID authorizing this operation.
6142
+ * Obtain from granted permissions via `vana.permissions.getUserPermissionGrantsOnChain()`.
6001
6143
  * @returns A Promise that resolves to an operation response with status and control URLs
6002
- * @throws {PersonalServerError} When server request fails or parameters are invalid
6003
- * @throws {NetworkError} When personal server API communication fails
6144
+ * @throws {PersonalServerError} When server request fails or parameters are invalid.
6145
+ * Verify permissionId exists and is active for the target server.
6146
+ * @throws {NetworkError} When personal server API communication fails.
6147
+ * Check server URL configuration and network connectivity.
6004
6148
  * @example
6005
6149
  * ```typescript
6006
6150
  * const response = await vana.server.createOperation({
@@ -6040,6 +6184,50 @@ declare class ServerController {
6040
6184
  * ```
6041
6185
  */
6042
6186
  getOperation(operationId: string): Promise<GetOperationResponse>;
6187
+ /**
6188
+ * Cancels a running operation on the personal server.
6189
+ *
6190
+ * @remarks
6191
+ * This method attempts to cancel an operation that is currently processing
6192
+ * on the personal server. The operation must be in a cancellable state
6193
+ * (typically `starting` or `processing`). Not all operations support
6194
+ * cancellation, and cancellation may not be immediate. The server will
6195
+ * attempt to stop the operation and update its status to `canceled`.
6196
+ *
6197
+ * **Cancellation Behavior:**
6198
+ * - Operations in `succeeded` or `failed` states cannot be canceled
6199
+ * - Some long-running operations may take time to respond to cancellation
6200
+ * - Always verify cancellation by polling the operation status afterward
6201
+ *
6202
+ * @param operationId - The unique identifier of the operation to cancel,
6203
+ * obtained from `createOperation()` response
6204
+ * @returns Promise that resolves when the cancellation request is accepted
6205
+ * @throws {PersonalServerError} When the operation cannot be canceled or doesn't exist.
6206
+ * Check operation status - it may already be completed or failed.
6207
+ * @throws {NetworkError} When unable to reach the personal server API.
6208
+ * Verify server URL and network connectivity.
6209
+ * @example
6210
+ * ```typescript
6211
+ * // Start a long-running operation
6212
+ * const operation = await vana.server.createOperation({
6213
+ * permissionId: 123
6214
+ * });
6215
+ *
6216
+ * // Cancel if needed
6217
+ * try {
6218
+ * await vana.server.cancelOperation(operation.id);
6219
+ * console.log("Cancellation requested");
6220
+ *
6221
+ * // Verify cancellation
6222
+ * const status = await vana.server.getOperation(operation.id);
6223
+ * if (status.status === "canceled") {
6224
+ * console.log("Operation successfully canceled");
6225
+ * }
6226
+ * } catch (error) {
6227
+ * console.error("Failed to cancel:", error);
6228
+ * }
6229
+ * ```
6230
+ */
6043
6231
  cancelOperation(operationId: string): Promise<void>;
6044
6232
  /**
6045
6233
  * Makes the request to the personal server API.
@@ -30935,19 +31123,26 @@ declare function clearContractCache(contract?: VanaContract, chainId?: number):
30935
31123
  * Most developers should use the higher-level DataController and PermissionsController
30936
31124
  * instead of this advanced API.
30937
31125
  *
31126
+ * **Contract Selection:**
30938
31127
  * The controller automatically handles chain detection and provides only contracts that
30939
31128
  * are deployed on the current network. All contract instances are fully typed for
30940
31129
  * enhanced developer experience and type safety.
30941
31130
  *
30942
- * **Use this controller when:**
30943
- * - High-level controllers don't provide needed functionality
30944
- * - You need direct contract method calls or event access
30945
- * - You're building custom integrations or tooling
30946
- * - You need advanced querying capabilities
31131
+ * **Method Selection:**
31132
+ * - `getContract()` retrieves contract address and ABI for manual interaction
31133
+ * - `createContract()` returns fully typed contract instance with read/write methods
31134
+ * - `getAvailableContracts()` lists all contracts deployed on current chain
31135
+ * - `isContractAvailable()` checks if specific contract exists on current chain
31136
+ * - `getChainId()` and `getChainName()` provide current network information
31137
+ *
31138
+ * **Usage Guidelines:**
31139
+ * Use this controller when high-level controllers don't provide needed functionality.
31140
+ * Most developers should use `vana.data.*` for files and `vana.permissions.*` for access control.
31141
+ *
31142
+ * **Type Safety:**
31143
+ * Use `as const` assertion with contract names for full TypeScript type inference.
31144
+ * Contract instances provide complete typing for all methods, parameters, and return values.
30947
31145
  *
30948
- * **Most developers should use instead:**
30949
- * - `vana.data.*` for file management operations
30950
- * - `vana.permissions.*` for access control workflows
30951
31146
  * @example
30952
31147
  * ```typescript
30953
31148
  * // Get contract info for direct interaction
@@ -30978,7 +31173,8 @@ declare class ProtocolController {
30978
31173
  * are actually deployed on the current network.
30979
31174
  * @param contractName - The name of the Vana contract to retrieve (use const assertion for full typing)
30980
31175
  * @returns An object containing the contract's address and fully typed ABI
30981
- * @throws {ContractNotFoundError} When the contract is not deployed on the current chain
31176
+ * @throws {ContractNotFoundError} When the contract is not deployed on the current chain.
31177
+ * Verify contract name spelling and check current network with `getChainId()`.
30982
31178
  * @example
30983
31179
  * ```typescript
30984
31180
  * // Get contract info with full type inference
@@ -31095,19 +31291,43 @@ declare class VanaCoreFactory {
31095
31291
  * @remarks
31096
31292
  * This environment-agnostic class contains all SDK logic and accepts a platform
31097
31293
  * adapter to handle environment-specific operations. It initializes all controllers
31098
- * and manages shared context between them.
31294
+ * and manages shared context between them, providing a unified interface for
31295
+ * data management, permissions, smart contracts, and storage operations.
31099
31296
  *
31100
31297
  * The class uses TypeScript overloading to enforce storage requirements at compile time.
31101
- * When storage is required for certain operations, the constructor will fail fast at runtime.
31298
+ * Methods that require storage will throw `InvalidConfigurationError` at runtime if
31299
+ * storage providers are not configured, implementing a fail-fast approach to prevent
31300
+ * errors during expensive operations.
31301
+ *
31302
+ * **Core Architecture:**
31303
+ * - **Controllers**: Specialized modules for different Vana features (data, permissions, etc.)
31304
+ * - **Platform Adapters**: Environment-specific implementations (browser vs Node.js)
31305
+ * - **Storage Managers**: Abstraction layer for multiple storage providers
31306
+ * - **Context Sharing**: Unified configuration and services across all controllers
31307
+ *
31308
+ * For public usage, use the platform-specific factory functions:
31309
+ * - Browser: `import { Vana } from '@opendatalabs/vana-sdk/browser'`
31310
+ * - Node.js: `import { Vana } from '@opendatalabs/vana-sdk/node'`
31102
31311
  *
31103
- * For public usage, use the platform-specific Vana classes that extend this core:
31104
- * - Use `Vana({config)` from the main package import
31105
31312
  * @example
31106
31313
  * ```typescript
31107
- * // Direct instantiation (typically used internally)
31108
- * const core = new VanaCore({
31314
+ * // Direct instantiation (advanced usage)
31315
+ * import { VanaCore, BrowserPlatformAdapter } from '@opendatalabs/vana-sdk/browser';
31316
+ *
31317
+ * const core = new VanaCore(new BrowserPlatformAdapter(), {
31109
31318
  * walletClient: myWalletClient,
31110
- * }, platformAdapter);
31319
+ * storage: {
31320
+ * providers: { ipfs: new IPFSStorage() },
31321
+ * defaultProvider: 'ipfs'
31322
+ * }
31323
+ * });
31324
+ *
31325
+ * // Access all controllers
31326
+ * const files = await core.data.getUserFiles();
31327
+ * const permissions = await core.permissions.grant({
31328
+ * grantee: '0x742d35...',
31329
+ * operation: 'read'
31330
+ * });
31111
31331
  * ```
31112
31332
  * @category Core SDK
31113
31333
  */
@@ -31280,30 +31500,86 @@ declare class VanaCore {
31280
31500
  getPlatformAdapter(): VanaPlatformAdapter;
31281
31501
  /**
31282
31502
  * Encrypts data using the Vana protocol standard encryption.
31283
- * This method automatically uses the correct platform adapter for the current environment.
31284
31503
  *
31285
- * @param data The data to encrypt (string or Blob)
31286
- * @param key The key to use as encryption key
31287
- * @returns The encrypted data as Blob
31504
+ * @remarks
31505
+ * This method implements the Vana network's standard encryption protocol using
31506
+ * platform-appropriate cryptographic libraries. It automatically handles different
31507
+ * input types (string or Blob) and produces encrypted output suitable for secure
31508
+ * storage or transmission. The encryption is compatible with the network's
31509
+ * decryption protocols and can be decrypted by authorized parties.
31510
+ *
31511
+ * @param data - The data to encrypt (string or Blob)
31512
+ * @param key - The encryption key (typically generated via `generateEncryptionKey`)
31513
+ * @returns The encrypted data as a Blob
31514
+ * @throws {Error} When encryption fails due to invalid key or data format
31288
31515
  * @example
31289
31516
  * ```typescript
31290
- * const encryptionKey = await generateEncryptionKey(walletClient);
31291
- * const encrypted = await vana.encryptBlob("sensitive data", encryptionKey);
31517
+ * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';
31518
+ *
31519
+ * // Generate encryption key from wallet signature
31520
+ * const encryptionKey = await generateEncryptionKey(vana.walletClient);
31521
+ *
31522
+ * // Encrypt string data
31523
+ * const sensitiveData = "User's private information";
31524
+ * const encrypted = await vana.encryptBlob(sensitiveData, encryptionKey);
31525
+ *
31526
+ * // Encrypt file data
31527
+ * const fileBlob = new Blob([fileContent], { type: 'application/json' });
31528
+ * const encryptedFile = await vana.encryptBlob(fileBlob, encryptionKey);
31529
+ *
31530
+ * // Store encrypted data safely
31531
+ * await storageProvider.upload(encrypted, 'encrypted-data.bin');
31292
31532
  * ```
31293
31533
  */
31294
31534
  encryptBlob(data: string | Blob, key: string): Promise<Blob>;
31295
31535
  /**
31296
31536
  * Decrypts data that was encrypted using the Vana protocol.
31297
- * This method automatically uses the correct platform adapter for the current environment.
31298
31537
  *
31299
- * @param encryptedData The encrypted data (string or Blob)
31300
- * @param walletSignature The wallet signature to use as decryption key
31301
- * @returns The decrypted data as Blob
31538
+ * @remarks
31539
+ * This method decrypts data that was previously encrypted using the Vana network's
31540
+ * standard encryption protocol. It requires the same wallet signature that was used
31541
+ * for encryption and automatically uses the appropriate platform adapter for
31542
+ * cryptographic operations. The decrypted output maintains the original data format.
31543
+ *
31544
+ * @param encryptedData - The encrypted data (string or Blob)
31545
+ * @param walletSignature - The wallet signature used as decryption key
31546
+ * @returns The decrypted data as a Blob
31547
+ * @throws {Error} When decryption fails due to invalid signature or corrupted data
31302
31548
  * @example
31303
31549
  * ```typescript
31304
- * const encryptionKey = await generateEncryptionKey(walletClient);
31305
- * const decrypted = await vana.decryptBlob(encryptedData, encryptionKey);
31306
- * const text = await decrypted.text();
31550
+ * import { generateEncryptionKey } from '@opendatalabs/vana-sdk/node';
31551
+ *
31552
+ * // Retrieve encrypted data from storage
31553
+ * const encryptedBlob = await storageProvider.download('encrypted-data.bin');
31554
+ *
31555
+ * // Generate the same key used for encryption
31556
+ * const decryptionKey = await generateEncryptionKey(vana.walletClient);
31557
+ *
31558
+ * // Decrypt the data
31559
+ * const decrypted = await vana.decryptBlob(encryptedBlob, decryptionKey);
31560
+ *
31561
+ * // Convert back to original format
31562
+ * const originalText = await decrypted.text();
31563
+ * const originalJson = JSON.parse(originalText);
31564
+ *
31565
+ * console.log('Decrypted data:', originalJson);
31566
+ * ```
31567
+ *
31568
+ * @example
31569
+ * ```typescript
31570
+ * // Decrypt file downloaded from Vana network
31571
+ * const userFiles = await vana.data.getUserFiles();
31572
+ * const file = userFiles[0];
31573
+ *
31574
+ * // Download encrypted content
31575
+ * const encrypted = await fetch(file.url).then(r => r.blob());
31576
+ *
31577
+ * // Decrypt with user's key
31578
+ * const decryptionKey = await generateEncryptionKey(vana.walletClient);
31579
+ * const decrypted = await vana.decryptBlob(encrypted, decryptionKey);
31580
+ *
31581
+ * // Process original data
31582
+ * const fileContent = await decrypted.arrayBuffer();
31307
31583
  * ```
31308
31584
  */
31309
31585
  decryptBlob(encryptedData: string | Blob, walletSignature: string): Promise<Blob>;
@@ -31351,7 +31627,32 @@ declare class UserRejectedRequestError extends VanaError {
31351
31627
  constructor(message?: string);
31352
31628
  }
31353
31629
  /**
31354
- * Error thrown when the SDK configuration is invalid.
31630
+ * Thrown when the SDK configuration contains invalid or missing parameters.
31631
+ *
31632
+ * @remarks
31633
+ * This error occurs during SDK initialization when required configuration
31634
+ * parameters are missing, invalid, or incompatible. Common causes include
31635
+ * missing wallet clients, invalid chain IDs, malformed storage provider
31636
+ * configurations, or incompatible parameter combinations.
31637
+ *
31638
+ * Applications should catch this error during initialization and provide
31639
+ * clear feedback to users about configuration requirements.
31640
+ *
31641
+ * @example
31642
+ * ```typescript
31643
+ * try {
31644
+ * const vana = Vana({
31645
+ * chainId: 999999, // Invalid chain ID
31646
+ * account: null // Missing account
31647
+ * });
31648
+ * } catch (error) {
31649
+ * if (error instanceof InvalidConfigurationError) {
31650
+ * console.error('Configuration error:', error.message);
31651
+ * // Show user-friendly configuration help
31652
+ * }
31653
+ * }
31654
+ * ```
31655
+ * @category Error Handling
31355
31656
  */
31356
31657
  declare class InvalidConfigurationError extends VanaError {
31357
31658
  constructor(message: string);
@@ -31369,20 +31670,92 @@ declare class ContractNotFoundError extends VanaError {
31369
31670
  constructor(contractName: string, chainId: number);
31370
31671
  }
31371
31672
  /**
31372
- * Error thrown when a blockchain operation fails.
31673
+ * Thrown when blockchain operations fail due to network, contract, or transaction issues.
31674
+ *
31675
+ * @remarks
31676
+ * This error encompasses various blockchain-related failures including network
31677
+ * connectivity issues, contract execution failures, insufficient gas, invalid
31678
+ * transaction parameters, or smart contract reverts. The original error is
31679
+ * preserved to provide detailed debugging information while maintaining a
31680
+ * consistent SDK error interface.
31681
+ *
31682
+ * Common causes:
31683
+ * - Network connectivity problems
31684
+ * - Insufficient gas or gas price too low
31685
+ * - Contract function reverts
31686
+ * - Invalid transaction parameters
31687
+ * - Blockchain congestion or downtime
31688
+ *
31689
+ * @example
31690
+ * ```typescript
31691
+ * try {
31692
+ * await vana.permissions.grant({
31693
+ * grantee: '0x742d35...',
31694
+ * operation: 'read'
31695
+ * });
31696
+ * } catch (error) {
31697
+ * if (error instanceof BlockchainError) {
31698
+ * console.error('Blockchain operation failed:', error.message);
31699
+ *
31700
+ * // Check if it's a network issue
31701
+ * if (error.originalError?.message.includes('network')) {
31702
+ * // Retry with exponential backoff
31703
+ * await retryOperation();
31704
+ * }
31705
+ * }
31706
+ * }
31707
+ * ```
31708
+ * @category Error Handling
31373
31709
  */
31374
31710
  declare class BlockchainError extends VanaError {
31375
31711
  readonly originalError?: Error | undefined;
31376
31712
  constructor(message: string, originalError?: Error | undefined);
31377
31713
  }
31378
31714
  /**
31379
- * Error thrown when parameter serialization fails.
31715
+ * Thrown when data serialization or deserialization operations fail.
31716
+ *
31717
+ * @remarks
31718
+ * This error occurs when the SDK cannot properly serialize parameters for
31719
+ * blockchain transactions, IPFS storage, or API calls. Common causes include
31720
+ * circular references in objects, unsupported data types, or malformed JSON.
31721
+ * It's typically encountered during grant file creation, storage operations,
31722
+ * or when preparing transaction data.
31723
+ *
31724
+ * @example
31725
+ * ```typescript
31726
+ * try {
31727
+ * // Object with circular reference causes serialization error
31728
+ * const obj = { name: 'test' };
31729
+ * obj.self = obj; // Circular reference
31730
+ *
31731
+ * await vana.data.upload({
31732
+ * content: obj,
31733
+ * filename: 'data.json'
31734
+ * });
31735
+ * } catch (error) {
31736
+ * if (error instanceof SerializationError) {
31737
+ * console.error('Data serialization failed:', error.message);
31738
+ * // Clean data before retry
31739
+ * const cleanedData = removeCircularReferences(obj);
31740
+ * await vana.data.upload({
31741
+ * content: cleanedData,
31742
+ * filename: 'data.json'
31743
+ * });
31744
+ * }
31745
+ * }
31746
+ * ```
31747
+ * @category Error Handling
31380
31748
  */
31381
31749
  declare class SerializationError extends VanaError {
31382
31750
  constructor(message: string);
31383
31751
  }
31384
31752
  /**
31385
31753
  * Error thrown when a signature operation fails.
31754
+ *
31755
+ * @remarks
31756
+ * Recovery strategies: Check wallet connection and account unlock status,
31757
+ * retry operation with explicit user interaction, or for gasless operations
31758
+ * consider switching to direct transactions.
31386
31759
  */
31387
31760
  declare class SignatureError extends VanaError {
31388
31761
  readonly originalError?: Error | undefined;
@@ -31390,6 +31763,10 @@ declare class SignatureError extends VanaError {
31390
31763
  }
31391
31764
  /**
31392
31765
  * Error thrown when a network operation fails.
31766
+ *
31767
+ * @remarks
31768
+ * Recovery strategies: Check network connectivity, retry with exponential backoff,
31769
+ * verify API endpoints are accessible, or switch to alternative network providers.
31393
31770
  */
31394
31771
  declare class NetworkError extends VanaError {
31395
31772
  readonly originalError?: Error | undefined;
@@ -31397,12 +31774,20 @@ declare class NetworkError extends VanaError {
31397
31774
  }
31398
31775
  /**
31399
31776
  * Error thrown when the nonce retrieval fails.
31777
+ *
31778
+ * @remarks
31779
+ * Recovery strategies: Retry nonce retrieval after brief delay, check wallet connection
31780
+ * and account status, or use manual nonce specification if supported by the operation.
31400
31781
  */
31401
31782
  declare class NonceError extends VanaError {
31402
31783
  constructor(message: string);
31403
31784
  }
31404
31785
  /**
31405
31786
  * Error thrown when a personal server operation fails.
31787
+ *
31788
+ * @remarks
31789
+ * Recovery strategies: Verify server URL accessibility, check server trust status via
31790
+ * `vana.permissions.getUserTrustedServers()`, or retry after server becomes available.
31406
31791
  */
31407
31792
  declare class PersonalServerError extends VanaError {
31408
31793
  readonly originalError?: Error | undefined;
@@ -31461,21 +31846,93 @@ declare const DEFAULT_ENCRYPTION_SEED = "Please sign to retrieve your encryption
31461
31846
  */
31462
31847
  declare function generateEncryptionKey(wallet: WalletClient, seed?: string): Promise<string>;
31463
31848
  /**
31464
- * Encrypt data with a wallet's public key using platform-appropriate cryptography
31849
+ * Encrypts data using a wallet's public key for secure sharing with specific recipients.
31465
31850
  *
31466
- * @param data The data to encrypt (as string or Blob)
31467
- * @param publicKey The public key for encryption
31468
- * @param platformAdapter - The platform adapter for crypto operations
31469
- * @returns The encrypted data
31851
+ * @remarks
31852
+ * This function implements asymmetric encryption using the recipient's public key,
31853
+ * enabling secure data sharing where only the holder of the corresponding private key
31854
+ * can decrypt the data. It automatically handles different data types and uses
31855
+ * platform-appropriate cryptographic libraries for maximum compatibility.
31856
+ *
31857
+ * This is commonly used when granting permissions to applications or servers,
31858
+ * where the data needs to be encrypted for a specific recipient's public key.
31859
+ *
31860
+ * @param data - The data to encrypt (string or Blob)
31861
+ * @param publicKey - The recipient's public key in hexadecimal format
31862
+ * @param platformAdapter - The platform adapter providing cryptographic operations
31863
+ * @returns Promise resolving to the encrypted data as a string
31864
+ * @throws {Error} When encryption fails due to invalid key or data format
31865
+ * @example
31866
+ * ```typescript
31867
+ * // Encrypt data for a specific application's public key
31868
+ * const appPublicKey = "0x04a1b2c3..."; // Application's public key
31869
+ * const sensitiveData = "User's private information";
31870
+ *
31871
+ * const encrypted = await encryptWithWalletPublicKey(
31872
+ * sensitiveData,
31873
+ * appPublicKey,
31874
+ * platformAdapter
31875
+ * );
31876
+ *
31877
+ * console.log('Encrypted for app:', encrypted);
31878
+ *
31879
+ * // Encrypt file data for server processing
31880
+ * const fileBlob = new File(['{"name":"John","age":30}'], 'profile.json');
31881
+ * const encryptedFile = await encryptWithWalletPublicKey(
31882
+ * fileBlob,
31883
+ * serverPublicKey,
31884
+ * platformAdapter
31885
+ * );
31886
+ * ```
31470
31887
  */
31471
31888
  declare function encryptWithWalletPublicKey(data: string | Blob, publicKey: string, platformAdapter: VanaPlatformAdapter): Promise<string>;
31472
31889
  /**
31473
- * Decrypt data with a wallet's private key using platform-appropriate cryptography
31890
+ * Decrypts data that was encrypted with the corresponding public key.
31474
31891
  *
31475
- * @param encryptedData The encrypted data
31476
- * @param privateKey The private key for decryption
31477
- * @param platformAdapter - The platform adapter for crypto operations
31478
- * @returns The decrypted data as string
31892
+ * @remarks
31893
+ * This function performs asymmetric decryption using the recipient's private key
31894
+ * to decrypt data that was encrypted with the corresponding public key. It's the
31895
+ * counterpart to `encryptWithWalletPublicKey` and is typically used by applications
31896
+ * or servers to decrypt data that was shared with them by users.
31897
+ *
31898
+ * The function automatically handles platform-specific cryptographic operations
31899
+ * and provides consistent behavior across browser and Node.js environments.
31900
+ *
31901
+ * @param encryptedData - The encrypted data string to decrypt
31902
+ * @param privateKey - The private key corresponding to the public key used for encryption
31903
+ * @param platformAdapter - The platform adapter providing cryptographic operations
31904
+ * @returns Promise resolving to the decrypted data as a string
31905
+ * @throws {Error} When decryption fails due to invalid key, corrupted data, or key mismatch
31906
+ * @example
31907
+ * ```typescript
31908
+ * // Decrypt data received from a user (server-side)
31909
+ * const encryptedUserData = "encrypted_string_from_user";
31910
+ * const serverPrivateKey = process.env.SERVER_PRIVATE_KEY;
31911
+ *
31912
+ * const decrypted = await decryptWithWalletPrivateKey(
31913
+ * encryptedUserData,
31914
+ * serverPrivateKey,
31915
+ * platformAdapter
31916
+ * );
31917
+ *
31918
+ * const userData = JSON.parse(decrypted);
31919
+ * console.log('User data:', userData);
31920
+ *
31921
+ * // Handle decryption errors gracefully
31922
+ * try {
31923
+ * const result = await decryptWithWalletPrivateKey(
31924
+ * encryptedData,
31925
+ * privateKey,
31926
+ * platformAdapter
31927
+ * );
31928
+ * } catch (error) {
31929
+ * if (error.message.includes('invalid key')) {
31930
+ * console.error('Key mismatch - data not encrypted for this recipient');
31931
+ * } else {
31932
+ * console.error('Decryption failed:', error.message);
31933
+ * }
31934
+ * }
31935
+ * ```
31479
31936
  */
31480
31937
  declare function decryptWithWalletPrivateKey(encryptedData: string, privateKey: string, platformAdapter: VanaPlatformAdapter): Promise<string>;
31481
31938
  /**
@@ -31626,6 +32083,11 @@ declare function decryptBlobWithSignedKey(encryptedData: string | Blob, key: str
31626
32083
  /**
31627
32084
  * Format a bigint or BigNumber to a regular number
31628
32085
  *
32086
+ * **Edge Cases:**
32087
+ * - Values exceeding JavaScript's MAX_SAFE_INTEGER (2^53-1) lose precision
32088
+ * - Negative values are supported
32089
+ * - String values must be valid numeric strings or will return NaN
32090
+ *
31629
32091
  * @param value BigInt, BigNumber or numeric string to convert
31630
32092
  * @returns Regular JavaScript number
31631
32093
  */
@@ -31633,6 +32095,12 @@ declare function formatNumber(value: bigint | string | number): number;
31633
32095
  /**
31634
32096
  * Format wei value to ETH with specified decimal places
31635
32097
  *
32098
+ * **Edge Cases:**
32099
+ * - Truncates (not rounds) to specified decimal places
32100
+ * - Negative values are supported
32101
+ * - Zero values return "0.0000" (based on decimals)
32102
+ * - Very small values may display as "0.0000" due to truncation
32103
+ *
31636
32104
  * @param wei Value in wei (as bigint, string, or number)
31637
32105
  * @param decimals Number of decimal places to display (default: 4)
31638
32106
  * @returns Formatted ETH value as string
@@ -31650,6 +32118,11 @@ declare function formatToken(amount: bigint | string | number, decimals?: number
31650
32118
  /**
31651
32119
  * Format an address for display (showing first 6 and last 4 characters)
31652
32120
  *
32121
+ * **Edge Cases:**
32122
+ * - Addresses shorter than 10 characters are returned unchanged
32123
+ * - Works with both checksummed and lowercase addresses
32124
+ * - Does not validate address format
32125
+ *
31653
32126
  * @param address EVM address
31654
32127
  * @returns Shortened address string
31655
32128
  */
@@ -31977,6 +32450,12 @@ declare function convertIpfsUrl(url: string, gateway?: string): string;
31977
32450
  /**
31978
32451
  * Extract IPFS hash from various URL formats
31979
32452
  *
32453
+ * **Edge Cases:**
32454
+ * - Returns null for non-IPFS URLs or malformed hashes
32455
+ * - Handles both CIDv0 (starts with Qm) and CIDv1 formats
32456
+ * - Minimum 46 characters required for standalone hash detection
32457
+ * - Gateway paths with subdirectories are not supported
32458
+ *
31980
32459
  * @param url - The URL to extract hash from
31981
32460
  * @returns The IPFS hash or null if not found
31982
32461
  * @example
@@ -31984,6 +32463,8 @@ declare function convertIpfsUrl(url: string, gateway?: string): string;
31984
32463
  * extractIpfsHash("ipfs://QmHash123") // Returns: "QmHash123"
31985
32464
  * extractIpfsHash("https://gateway.pinata.cloud/ipfs/QmHash123") // Returns: "QmHash123"
31986
32465
  * extractIpfsHash("QmHash123456789012345678901234567890123456") // Returns: "QmHash123456789012345678901234567890123456"
32466
+ * extractIpfsHash("https://example.com/file.json") // Returns: null (not IPFS)
32467
+ * extractIpfsHash("ipfs://QmHash/subdirectory") // Returns: null (subdirectories not supported)
31987
32468
  * ```
31988
32469
  */
31989
32470
  declare function extractIpfsHash(url: string): string | null;
@@ -32004,6 +32485,13 @@ declare function convertIpfsUrlWithFallbacks(url: string): string[];
32004
32485
  /**
32005
32486
  * Fetch content from IPFS with automatic gateway fallbacks
32006
32487
  *
32488
+ * **Edge Cases:**
32489
+ * - Non-IPFS URLs are fetched directly without fallback
32490
+ * - 10-second timeout per gateway attempt to prevent hanging
32491
+ * - Rate-limited gateways (429) are skipped immediately
32492
+ * - Exponential backoff between retries (1s, 2s, 3s, etc.)
32493
+ * - AbortSignal in options is merged with timeout signal
32494
+ *
32007
32495
  * @param url - The IPFS URL to fetch
32008
32496
  * @param options - Optional fetch options
32009
32497
  * @returns Promise resolving to Response object
@@ -32442,31 +32930,94 @@ declare class VanaBrowserImpl extends VanaCore {
32442
32930
  /**
32443
32931
  * Creates a new Vana SDK instance configured for browser environments.
32444
32932
  *
32445
- * This function automatically provides the correct TypeScript types based on your configuration:
32446
- * - With storage config: All methods including storage-dependent ones are available
32447
- * - Without storage: Storage-dependent methods are not available at compile time
32448
- *
32449
- * @param config - The configuration object containing wallet client and optional storage settings
32450
- * @returns A Vana SDK instance configured for browser use
32933
+ * @remarks
32934
+ * This is the primary entry point for browser applications using the Vana SDK. The function
32935
+ * automatically detects your configuration type and provides compile-time type safety:
32936
+ * - **With storage configured**: All methods including file upload/download are available
32937
+ * - **Without storage**: Storage-dependent methods throw runtime errors and are excluded from TypeScript
32938
+ *
32939
+ * The SDK supports multiple wallet configurations (direct WalletClient or chain config),
32940
+ * various storage providers (IPFS, Pinata, Google Drive), and gasless transactions via relayers.
32941
+ * All operations are optimized for browser environments with proper bundle size optimization.
32942
+ *
32943
+ * @param config - Configuration object containing wallet, storage, and relayer settings
32944
+ * @returns A fully configured Vana SDK instance for browser use
32945
+ * @throws {InvalidConfigurationError} When configuration parameters are invalid or missing
32451
32946
  * @example
32452
32947
  * ```typescript
32453
- * // With storage - all methods available
32948
+ * import { Vana } from '@opendatalabs/vana-sdk/browser';
32949
+ * import { createWalletClient, custom } from 'viem';
32950
+ * import { IPFSStorage } from '@opendatalabs/vana-sdk/browser';
32951
+ *
32952
+ * // Complete setup with storage and wallet
32953
+ * const walletClient = createWalletClient({
32954
+ * chain: mokshaTestnet,
32955
+ * transport: custom(window.ethereum)
32956
+ * });
32957
+ *
32454
32958
  * const vana = Vana({
32455
32959
  * walletClient,
32456
- * storage: { providers: { ipfs: new IPFSStorage() }, defaultProvider: 'ipfs' }
32960
+ * storage: {
32961
+ * providers: {
32962
+ * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' }),
32963
+ * pinata: new PinataStorage({ apiKey: process.env.PINATA_KEY })
32964
+ * },
32965
+ * defaultProvider: 'ipfs'
32966
+ * },
32967
+ * relayerCallbacks: {
32968
+ * async submitPermissionGrant(typedData, signature) {
32969
+ * const response = await fetch('/api/relay/grant', {
32970
+ * method: 'POST',
32971
+ * body: JSON.stringify({ typedData, signature })
32972
+ * });
32973
+ * return (await response.json()).transactionHash;
32974
+ * }
32975
+ * }
32457
32976
  * });
32458
- * await vana.data.uploadFile(file); // ✅ Works - TypeScript knows storage is available
32459
32977
  *
32460
- * // Without storage - storage methods unavailable at compile time
32461
- * const vanaNoStorage = Vana({ walletClient });
32462
- * // await vanaNoStorage.data.uploadFile(file); // ❌ TypeScript error
32978
+ * // All operations now available
32979
+ * const files = await vana.data.getUserFiles();
32980
+ * const permissions = await vana.permissions.getUserPermissions();
32981
+ * await vana.data.upload({ content: 'My data', filename: 'data.txt' });
32982
+ * ```
32983
+ *
32984
+ * @example
32985
+ * ```typescript
32986
+ * // Minimal setup without storage (read-only operations)
32987
+ * const vanaReadOnly = Vana({ walletClient });
32988
+ *
32989
+ * // These work without storage
32990
+ * const files = await vanaReadOnly.data.getUserFiles();
32991
+ * const permissions = await vanaReadOnly.permissions.getUserPermissions();
32992
+ *
32993
+ * // This would throw a runtime error
32994
+ * // await vanaReadOnly.data.upload(params); // ❌ InvalidConfigurationError
32463
32995
  *
32464
- * // Runtime check still available
32465
- * if (vanaNoStorage.isStorageEnabled()) {
32466
- * // TypeScript now knows storage methods are safe to use
32467
- * await vanaNoStorage.data.uploadFile(file); // ✅ Works
32996
+ * // Safe runtime check
32997
+ * if (vanaReadOnly.isStorageEnabled()) {
32998
+ * await vanaReadOnly.data.upload(params); // TypeScript allows this
32999
+ * } else {
33000
+ * console.log('Storage not configured - upload unavailable');
32468
33001
  * }
32469
33002
  * ```
33003
+ *
33004
+ * @example
33005
+ * ```typescript
33006
+ * // Using chain configuration instead of wallet client
33007
+ * const vana = Vana({
33008
+ * chainId: 14800, // Moksha testnet
33009
+ * account: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',
33010
+ * rpcUrl: 'https://rpc.moksha.vana.org',
33011
+ * storage: {
33012
+ * providers: { ipfs: new IPFSStorage() },
33013
+ * defaultProvider: 'ipfs'
33014
+ * }
33015
+ * });
33016
+ * ```
33017
+ *
33018
+ * @see {@link https://docs.vana.org/docs/sdk/getting-started | Getting Started Guide} for setup tutorials
33019
+ * @see {@link VanaCore} for the underlying implementation details
33020
+ * @category Core SDK
32470
33021
  */
32471
33022
  declare function Vana(config: VanaConfigWithStorage): VanaBrowserImpl & StorageRequiredMarker;
32472
33023
  declare function Vana(config: VanaConfig): VanaBrowserImpl;
@@ -32477,4 +33028,4 @@ declare function Vana(config: VanaConfig): VanaBrowserImpl;
32477
33028
  */
32478
33029
  type VanaInstance = VanaBrowserImpl;
32479
33030
 
32480
- export { type $defs, type APIResponse, type AddRefinerParams, type AddRefinerResult, type AddSchemaParams, type AddSchemaResult, type AllKeys, ApiClient, type ApiClientConfig, type ApiResponse, AsyncQueue, type AsyncResult, type AuthenticationErrorResponse, type Awaited, type BaseConfig, type BaseConfigWithStorage, BaseController, type BatchServerInfoResult, type BatchUploadParams, type BatchUploadResult, type BlockRange, BlockchainError, type BlockchainErrorResponse, type Brand, BrowserPlatformAdapter, type Cache, type CacheConfig, type ChainConfig, type ChainConfigWithStorage, type CheckPermissionParams, CircuitBreaker, type ComputeErrorResponse, type ConditionalOptional, type ConfigValidationOptions, type ConfigValidationResult, type ContractAddresses, type ContractCall, type ContractDeployment, ContractFactory, type ContractInfo, type ContractMethodParams, type ContractMethodReturnType, ContractNotFoundError, type Controller, type ControllerContext, type CreateOperationParams, type CreateOperationRequest, type CreateOperationResponse, type CreateSchemaParams, type CreateSchemaResult, DEFAULT_ENCRYPTION_SEED, DEFAULT_IPFS_GATEWAY, DataController, type DataSchema, type DecryptionErrorResponse, type DeepPartial, type DeepReadonly, type DeleteFileParams, type DeleteFileResult, type DownloadFileParams, type DownloadFileResult, type EncryptedPermissionParams, type EncryptedUploadParams, type EncryptionInfo, type ErrorResponse, EventEmitter, type EventFilter, type EventLog, type Factory, type FileAccessErrorResponse, type FileAccessPermissions, type FileMetadata, type FileSharingConfig, type GasEstimate, type GenericRequest, type GenericResponse, type GenericTypedData, type GetFileParams, type GetOperationResponse, type GetUserFilesParams, type GetUserPermissionsOptions, type GetUserTrustedServersParams, type GetUserTrustedServersResult, GoogleDriveStorage, GrantExpiredError, type GrantFile, type GrantPermissionParams, GrantSchemaError, GrantValidationError, type GrantValidationErrorResponse, type GrantValidationOptions, type GrantValidationResult, GranteeMismatchError, type HttpMethod, IPFS_GATEWAYS, type IdentityResponseModel, type InitPersonalServerParams, type InternalServerErrorResponse, InvalidConfigurationError, IpfsStorage, type MaybeArray, type MaybePromise, MemoryCache, type Middleware, MiddlewarePipeline, NetworkError, type NetworkInfo, type Nominal, type NonNullable, NonceError, type NotFoundErrorResponse, type Observable, type Observer, type OmitByType, type OnChainPermissionGrant, type OperationErrorResponse, OperationNotAllowedError, type OptionalKeys, type PaginatedTrustedServers, type PaginationParams, type PaginationResult, type PartialExcept, type PermissionAnalytics, type PermissionCheckResult, PermissionError, type PermissionEvent, type PermissionGrantDomain, type PermissionGrantMessage, type PermissionGrantTypedData, type PermissionInfo, type PermissionInputMessage, type PermissionOperation, type PermissionParams, type PermissionQueryResult, type PermissionStatus, PermissionsController, PersonalServerError, type PersonalServerIdentity, type PersonalServerModel, type PickByType, type PinataListResponse, type PinataPin, PinataStorage, type PinataUploadResponse, type Plugin, type PostRequestParams, type PromiseResult, ProtocolController, type QueryPermissionsParams, type RateLimitInfo, RateLimiter, type RateLimiterConfig, type Refiner, type RelayerCallbacks, type RelayerConfig, RelayerError, type RelayerErrorResponse, type RelayerMetrics, type RelayerQueueInfo, type RelayerRequestOptions, type RelayerStatus, type RelayerStorageResponse, type RelayerStoreParams, type RelayerSubmitParams, type RelayerTransactionResponse, type RelayerTransactionStatus, type RelayerWebhookConfig, type RelayerWebhookPayload, type ReplicateAPIResponse, type ReplicateStatus, type Repository, type RequestOptions, type RequireKeys, type RequiredExcept, type RetryConfig, RetryUtility, type RevokePermissionInput, type RevokePermissionParams, type RuntimeConfig, type Schema, SchemaValidationError, SchemaValidator, SerializationError, type Server, type components as ServerComponents, ServerController, type $defs as ServerDefs, type operations as ServerOperations, type paths as ServerPaths, ServerProxyStorage, type ServerTrustStatus, ServerUrlMismatchError, type webhooks as ServerWebhooks, type Service, SignatureError, type SimplifiedPermissionMessage, type StateMachine, type StatusInfo, type StorageConfig, StorageError, type StorageFile, type StorageListOptions, StorageManager, type StorageProvider, type StorageProviderConfig, type StorageRequiredMarker, type StorageUploadResult, type TimeRange, type TransactionOptions, type TransactionReceipt, type Transformer, type TrustServerInput, type TrustServerParams, type TrustServerTypedData, type TrustedServer, type TrustedServerInfo, type TrustedServerQueryMode, type TrustedServerQueryOptions, type UnencryptedUploadParams, type UntrustServerInput, type UntrustServerParams, type UntrustServerTypedData, type UpdateSchemaIdParams, type UpdateSchemaIdResult, type UploadEncryptedFileResult, type UploadFileParams, type UploadFileResult, type UploadParams, type UploadProgress, type UploadResult, type UserFile, UserRejectedRequestError, type ValidationErrorResponse, type ValidationResult, type Validator, Vana, VanaBrowserImpl, type VanaChain, type VanaChainConfig, type VanaChainId, type VanaConfig, type VanaConfigWithStorage, type VanaContract, type VanaContract as VanaContractAbi, type VanaContractInstance, type VanaContractName, VanaCore, VanaCoreFactory, VanaError, type VanaInstance, type VanaPlatformAdapter, type WalletConfig, type WalletConfigWithStorage, __contractCache, chains, checkGrantAccess, clearContractCache, type components, convertIpfsUrl, convertIpfsUrlWithFallbacks, createAndStoreGrant, createBrowserPlatformAdapter, createGrantFile, createPlatformAdapterSafe, createValidatedGrant, decryptBlobWithSignedKey, decryptWithPrivateKey, decryptWithWalletPrivateKey, Vana as default, detectPlatform, encryptBlobWithSignedKey, encryptFileKey, encryptWithWalletPublicKey, extractIpfsHash, fetchAndValidateSchema, fetchWithFallbacks, formatEth, formatNumber, formatToken, generateEncryptionKey, generateEncryptionKeyPair, generatePGPKeyPair, getAbi, getAllChains, getChainConfig, getContractAddress, getContractController, getContractInfo, getEncryptionParameters, getGatewayUrls, getGrantFileHash, getGrantTimeRemaining, getPlatformCapabilities, hasStorageConfig, isAPIResponse, isChainConfig, isGrantExpired, isIpfsUrl, isPlatformSupported, isReplicateAPIResponse, isVanaChain, isVanaChainId, isWalletConfig, moksha, mokshaTestnet, type operations, parseReplicateOutput, type paths, retrieveAndValidateGrant, retrieveGrantFile, safeParseJSON, schemaValidator, shortenAddress, storeGrantFile, summarizeGrant, validateDataAgainstSchema, validateDataSchema, validateGrant, validateGrantExpiry, validateGrantFile, validateGranteeAccess, validateOperationAccess, vanaMainnet, type webhooks };
33031
+ export { type $defs, type APIResponse, type AddRefinerParams, type AddRefinerResult, type AddSchemaParams, type AddSchemaResult, type AllKeys, ApiClient, type ApiClientConfig, type ApiResponse, AsyncQueue, type AsyncResult, type AuthenticationErrorResponse, type Awaited, type BaseConfig, type BaseConfigWithStorage, BaseController, type BatchServerInfoResult, type BatchUploadParams, type BatchUploadResult, type BlockRange, BlockchainError, type BlockchainErrorResponse, type Brand, BrowserPlatformAdapter, type Cache, type CacheConfig, type ChainConfig, type ChainConfigWithStorage, type CheckPermissionParams, CircuitBreaker, type ComputeErrorResponse, type ConditionalOptional, type ConfigValidationOptions, type ConfigValidationResult, type ContractAddresses, type ContractCall, type ContractDeployment, ContractFactory, type ContractInfo, type ContractMethodParams, type ContractMethodReturnType, ContractNotFoundError, type Controller, type ControllerContext, type CreateOperationParams, type CreateOperationRequest, type CreateOperationResponse, type CreateSchemaParams, type CreateSchemaResult, DEFAULT_ENCRYPTION_SEED, DEFAULT_IPFS_GATEWAY, DataController, type DataSchema, type DecryptionErrorResponse, type DeepPartial, type DeepReadonly, type DeleteFileParams, type DeleteFileResult, type DownloadFileParams, type DownloadFileResult, type EncryptedPermissionParams, type EncryptedUploadParams, type EncryptionInfo, type ErrorResponse, EventEmitter, type EventFilter, type EventLog, type Factory, type FileAccessErrorResponse, type FileAccessPermissions, type FileMetadata, type FileSharingConfig, type GasEstimate, type GenericRequest, type GenericResponse, type GenericTypedData, type GetFileParams, type GetOperationResponse, type GetUserFilesParams, type GetUserPermissionsOptions, type GetUserTrustedServersParams, type GetUserTrustedServersResult, GoogleDriveStorage, GrantExpiredError, type GrantFile, type GrantPermissionParams, GrantSchemaError, GrantValidationError, type GrantValidationErrorResponse, type GrantValidationOptions, type GrantValidationResult, type GrantedPermission, GranteeMismatchError, type HttpMethod, IPFS_GATEWAYS, type IdentityResponseModel, type InitPersonalServerParams, type InternalServerErrorResponse, InvalidConfigurationError, IpfsStorage, type MaybeArray, type MaybePromise, MemoryCache, type Middleware, MiddlewarePipeline, NetworkError, type NetworkInfo, type Nominal, type NonNullable, NonceError, type NotFoundErrorResponse, type Observable, type Observer, type OmitByType, type OnChainPermissionGrant, type OperationErrorResponse, OperationNotAllowedError, type OptionalKeys, type PaginatedTrustedServers, type PaginationParams, type PaginationResult, type PartialExcept, type PermissionAnalytics, type PermissionCheckResult, PermissionError, type PermissionEvent, type PermissionGrantDomain, type PermissionGrantMessage, type PermissionGrantTypedData, type PermissionInfo, type PermissionInputMessage, type PermissionOperation, type PermissionParams, type PermissionQueryResult, type PermissionStatus, PermissionsController, PersonalServerError, type PersonalServerIdentity, type PersonalServerModel, type PickByType, type PinataListResponse, type PinataPin, PinataStorage, type PinataUploadResponse, type Plugin, type PostRequestParams, type PromiseResult, ProtocolController, type QueryPermissionsParams, type RateLimitInfo, RateLimiter, type RateLimiterConfig, type Refiner, type RelayerCallbacks, type RelayerConfig, RelayerError, type RelayerErrorResponse, type RelayerMetrics, type RelayerQueueInfo, type RelayerRequestOptions, type RelayerStatus, type RelayerStorageResponse, type RelayerStoreParams, type RelayerSubmitParams, type RelayerTransactionResponse, type RelayerTransactionStatus, type RelayerWebhookConfig, type RelayerWebhookPayload, type ReplicateAPIResponse, type ReplicateStatus, type Repository, type RequestOptions, type RequireKeys, type RequiredExcept, type RetryConfig, RetryUtility, type RevokePermissionInput, type RevokePermissionParams, type RuntimeConfig, type Schema, SchemaValidationError, SchemaValidator, SerializationError, type Server, type components as ServerComponents, ServerController, type $defs as ServerDefs, type operations as ServerOperations, type paths as ServerPaths, ServerProxyStorage, type ServerTrustStatus, ServerUrlMismatchError, type webhooks as ServerWebhooks, type Service, SignatureError, type SimplifiedPermissionMessage, type StateMachine, type StatusInfo, type StorageConfig, StorageError, type StorageFile, type StorageListOptions, StorageManager, type StorageProvider, type StorageProviderConfig, type StorageRequiredMarker, type StorageUploadResult, type TimeRange, type TransactionOptions, type TransactionReceipt, type Transformer, type TrustServerInput, type TrustServerParams, type TrustServerTypedData, type TrustedServer, type TrustedServerInfo, type TrustedServerQueryMode, type TrustedServerQueryOptions, type UnencryptedUploadParams, type UntrustServerInput, type UntrustServerParams, type UntrustServerTypedData, type UpdateSchemaIdParams, type UpdateSchemaIdResult, type UploadEncryptedFileResult, type UploadFileParams, type UploadFileResult, type UploadParams, type UploadProgress, type UploadResult, type UserFile, UserRejectedRequestError, type ValidationErrorResponse, type ValidationResult, type Validator, Vana, VanaBrowserImpl, type VanaChain, type VanaChainConfig, type VanaChainId, type VanaConfig, type VanaConfigWithStorage, type VanaContract, type VanaContract as VanaContractAbi, type VanaContractInstance, type VanaContractName, VanaCore, VanaCoreFactory, VanaError, type VanaInstance, type VanaPlatformAdapter, type WalletConfig, type WalletConfigWithStorage, __contractCache, chains, checkGrantAccess, clearContractCache, type components, convertIpfsUrl, convertIpfsUrlWithFallbacks, createAndStoreGrant, createBrowserPlatformAdapter, createGrantFile, createPlatformAdapterSafe, createValidatedGrant, decryptBlobWithSignedKey, decryptWithPrivateKey, decryptWithWalletPrivateKey, Vana as default, detectPlatform, encryptBlobWithSignedKey, encryptFileKey, encryptWithWalletPublicKey, extractIpfsHash, fetchAndValidateSchema, fetchWithFallbacks, formatEth, formatNumber, formatToken, generateEncryptionKey, generateEncryptionKeyPair, generatePGPKeyPair, getAbi, getAllChains, getChainConfig, getContractAddress, getContractController, getContractInfo, getEncryptionParameters, getGatewayUrls, getGrantFileHash, getGrantTimeRemaining, getPlatformCapabilities, hasStorageConfig, isAPIResponse, isChainConfig, isGrantExpired, isIpfsUrl, isPlatformSupported, isReplicateAPIResponse, isVanaChain, isVanaChainId, isWalletConfig, moksha, mokshaTestnet, type operations, parseReplicateOutput, type paths, retrieveAndValidateGrant, retrieveGrantFile, safeParseJSON, schemaValidator, shortenAddress, storeGrantFile, summarizeGrant, validateDataAgainstSchema, validateDataSchema, validateGrant, validateGrantExpiry, validateGrantFile, validateGranteeAccess, validateOperationAccess, vanaMainnet, type webhooks };