@opendatalabs/vana-sdk 0.1.0-alpha.a6b60fc → 0.1.0-alpha.a78ce5c
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.
- package/dist/client/__tests__/enhancedResponse.test.d.ts +1 -0
- package/dist/client/enhancedResponse.cjs +164 -0
- package/dist/client/enhancedResponse.cjs.map +1 -0
- package/dist/client/enhancedResponse.d.ts +120 -0
- package/dist/client/enhancedResponse.js +138 -0
- package/dist/client/enhancedResponse.js.map +1 -0
- package/dist/controllers/__tests__/data-consistency-integration.test.d.ts +7 -0
- package/dist/controllers/__tests__/operations.processQueue.test.d.ts +1 -0
- package/dist/controllers/base.cjs +33 -0
- package/dist/controllers/base.cjs.map +1 -1
- package/dist/controllers/base.d.ts +10 -0
- package/dist/controllers/base.js +33 -0
- package/dist/controllers/base.js.map +1 -1
- package/dist/controllers/data.cjs +278 -159
- package/dist/controllers/data.cjs.map +1 -1
- package/dist/controllers/data.d.ts +34 -19
- package/dist/controllers/data.js +291 -162
- package/dist/controllers/data.js.map +1 -1
- package/dist/controllers/operations.cjs +430 -0
- package/dist/controllers/operations.cjs.map +1 -0
- package/dist/controllers/operations.d.ts +229 -0
- package/dist/controllers/operations.js +406 -0
- package/dist/controllers/operations.js.map +1 -0
- package/dist/controllers/permissions.cjs +605 -213
- package/dist/controllers/permissions.cjs.map +1 -1
- package/dist/controllers/permissions.d.ts +141 -34
- package/dist/controllers/permissions.js +605 -213
- package/dist/controllers/permissions.js.map +1 -1
- package/dist/controllers/schemas.cjs +81 -4
- package/dist/controllers/schemas.cjs.map +1 -1
- package/dist/controllers/schemas.d.ts +41 -0
- package/dist/controllers/schemas.js +81 -4
- package/dist/controllers/schemas.js.map +1 -1
- package/dist/controllers/server.cjs +251 -42
- package/dist/controllers/server.cjs.map +1 -1
- package/dist/controllers/server.d.ts +111 -14
- package/dist/controllers/server.js +251 -42
- package/dist/controllers/server.js.map +1 -1
- package/dist/core/__tests__/health.test.d.ts +1 -0
- package/dist/core/__tests__/inMemoryNonceManager.test.d.ts +1 -0
- package/dist/core/__tests__/nonceManager.test.d.ts +1 -0
- package/dist/core/__tests__/pollingManager.test.d.ts +4 -0
- package/dist/core/health.cjs +289 -0
- package/dist/core/health.cjs.map +1 -0
- package/dist/core/health.d.ts +143 -0
- package/dist/core/health.js +265 -0
- package/dist/core/health.js.map +1 -0
- package/dist/core/inMemoryNonceManager.cjs +138 -0
- package/dist/core/inMemoryNonceManager.cjs.map +1 -0
- package/dist/core/inMemoryNonceManager.d.ts +69 -0
- package/dist/core/inMemoryNonceManager.js +114 -0
- package/dist/core/inMemoryNonceManager.js.map +1 -0
- package/dist/core/nonceManager.cjs +304 -0
- package/dist/core/nonceManager.cjs.map +1 -0
- package/dist/core/nonceManager.d.ts +116 -0
- package/dist/core/nonceManager.js +280 -0
- package/dist/core/nonceManager.js.map +1 -0
- package/dist/core/pollingManager.cjs +292 -0
- package/dist/core/pollingManager.cjs.map +1 -0
- package/dist/core/pollingManager.d.ts +120 -0
- package/dist/core/pollingManager.js +268 -0
- package/dist/core/pollingManager.js.map +1 -0
- package/dist/core.cjs +55 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +54 -3
- package/dist/core.js +55 -1
- package/dist/core.js.map +1 -1
- package/dist/crypto/ecies/base.cjs +16 -3
- package/dist/crypto/ecies/base.cjs.map +1 -1
- package/dist/crypto/ecies/base.js +16 -3
- package/dist/crypto/ecies/base.js.map +1 -1
- package/dist/errors.cjs +29 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +64 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -1
- package/dist/generated/abi/ComputeInstructionRegistryImplementation.cjs.map +1 -1
- package/dist/generated/abi/ComputeInstructionRegistryImplementation.js.map +1 -1
- package/dist/generated/abi/DLPPerformanceImplementation.cjs +42 -0
- package/dist/generated/abi/DLPPerformanceImplementation.cjs.map +1 -1
- package/dist/generated/abi/DLPPerformanceImplementation.d.ts +32 -0
- package/dist/generated/abi/DLPPerformanceImplementation.js +42 -0
- package/dist/generated/abi/DLPPerformanceImplementation.js.map +1 -1
- package/dist/generated/abi/DLPRegistryImplementation.cjs +5 -5
- package/dist/generated/abi/DLPRegistryImplementation.cjs.map +1 -1
- package/dist/generated/abi/DLPRegistryImplementation.d.ts +4 -4
- package/dist/generated/abi/DLPRegistryImplementation.js +5 -5
- package/dist/generated/abi/DLPRegistryImplementation.js.map +1 -1
- package/dist/generated/abi/DLPRewardDeployerImplementation.cjs +166 -2
- package/dist/generated/abi/DLPRewardDeployerImplementation.cjs.map +1 -1
- package/dist/generated/abi/DLPRewardDeployerImplementation.d.ts +129 -2
- package/dist/generated/abi/DLPRewardDeployerImplementation.js +166 -2
- package/dist/generated/abi/DLPRewardDeployerImplementation.js.map +1 -1
- package/dist/generated/abi/DataPortabilityGranteesImplementation.cjs +167 -19
- package/dist/generated/abi/DataPortabilityGranteesImplementation.cjs.map +1 -1
- package/dist/generated/abi/DataPortabilityGranteesImplementation.d.ts +127 -14
- package/dist/generated/abi/DataPortabilityGranteesImplementation.js +167 -19
- package/dist/generated/abi/DataPortabilityGranteesImplementation.js.map +1 -1
- package/dist/generated/abi/DataPortabilityPermissionsImplementation.cjs +0 -19
- package/dist/generated/abi/DataPortabilityPermissionsImplementation.cjs.map +1 -1
- package/dist/generated/abi/DataPortabilityPermissionsImplementation.d.ts +0 -14
- package/dist/generated/abi/DataPortabilityPermissionsImplementation.js +0 -19
- package/dist/generated/abi/DataPortabilityPermissionsImplementation.js.map +1 -1
- package/dist/generated/abi/DataPortabilityServersImplementation.cjs +0 -19
- package/dist/generated/abi/DataPortabilityServersImplementation.cjs.map +1 -1
- package/dist/generated/abi/DataPortabilityServersImplementation.d.ts +0 -14
- package/dist/generated/abi/DataPortabilityServersImplementation.js +0 -19
- package/dist/generated/abi/DataPortabilityServersImplementation.js.map +1 -1
- package/dist/generated/abi/DataRegistryImplementation.cjs +0 -13
- package/dist/generated/abi/DataRegistryImplementation.cjs.map +1 -1
- package/dist/generated/abi/DataRegistryImplementation.d.ts +0 -10
- package/dist/generated/abi/DataRegistryImplementation.js +0 -13
- package/dist/generated/abi/DataRegistryImplementation.js.map +1 -1
- package/dist/generated/abi/SwapHelperImplementation.cjs +0 -43
- package/dist/generated/abi/SwapHelperImplementation.cjs.map +1 -1
- package/dist/generated/abi/SwapHelperImplementation.d.ts +0 -35
- package/dist/generated/abi/SwapHelperImplementation.js +0 -43
- package/dist/generated/abi/SwapHelperImplementation.js.map +1 -1
- package/dist/generated/abi/VanaEpochImplementation.cjs +195 -0
- package/dist/generated/abi/VanaEpochImplementation.cjs.map +1 -1
- package/dist/generated/abi/VanaEpochImplementation.d.ts +151 -0
- package/dist/generated/abi/VanaEpochImplementation.js +195 -0
- package/dist/generated/abi/VanaEpochImplementation.js.map +1 -1
- package/dist/generated/abi/VanaPoolEntityImplementation.cjs +22 -65
- package/dist/generated/abi/VanaPoolEntityImplementation.cjs.map +1 -1
- package/dist/generated/abi/VanaPoolEntityImplementation.d.ts +17 -51
- package/dist/generated/abi/VanaPoolEntityImplementation.js +22 -65
- package/dist/generated/abi/VanaPoolEntityImplementation.js.map +1 -1
- package/dist/generated/abi/VanaPoolStakingImplementation.cjs +113 -1
- package/dist/generated/abi/VanaPoolStakingImplementation.cjs.map +1 -1
- package/dist/generated/abi/VanaPoolStakingImplementation.d.ts +85 -1
- package/dist/generated/abi/VanaPoolStakingImplementation.js +113 -1
- package/dist/generated/abi/VanaPoolStakingImplementation.js.map +1 -1
- package/dist/generated/abi/index.d.ts +546 -146
- package/dist/generated/event-types.cjs.map +1 -1
- package/dist/generated/event-types.d.ts +14 -8
- package/dist/generated/eventRegistry.cjs +42 -18
- package/dist/generated/eventRegistry.cjs.map +1 -1
- package/dist/generated/eventRegistry.js +42 -18
- package/dist/generated/eventRegistry.js.map +1 -1
- package/dist/generated/server/server-exports.cjs +22 -0
- package/dist/generated/server/server-exports.cjs.map +1 -1
- package/dist/generated/server/server-exports.d.ts +27 -10
- package/dist/generated/server/server-exports.js +17 -0
- package/dist/generated/server/server-exports.js.map +1 -1
- package/dist/generated/server/server.cjs.map +1 -1
- package/dist/generated/server/server.d.ts +771 -402
- package/dist/generated/subgraph.cjs +797 -32
- package/dist/generated/subgraph.cjs.map +1 -1
- package/dist/generated/subgraph.d.ts +135 -0
- package/dist/generated/subgraph.js +792 -32
- package/dist/generated/subgraph.js.map +1 -1
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +10 -0
- package/dist/index.browser.js.map +1 -1
- package/dist/index.node.cjs +26 -0
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.d.ts +49 -5
- package/dist/index.node.js +25 -1
- package/dist/index.node.js.map +1 -1
- package/dist/lib/__tests__/redisAtomicStore.test.d.ts +1 -0
- package/dist/lib/redisAtomicStore.cjs +201 -0
- package/dist/lib/redisAtomicStore.cjs.map +1 -0
- package/dist/lib/redisAtomicStore.d.ts +120 -0
- package/dist/lib/redisAtomicStore.js +177 -0
- package/dist/lib/redisAtomicStore.js.map +1 -0
- package/dist/server/relayerHandler.cjs +313 -75
- package/dist/server/relayerHandler.cjs.map +1 -1
- package/dist/server/relayerHandler.d.ts +35 -2
- package/dist/server/relayerHandler.js +313 -75
- package/dist/server/relayerHandler.js.map +1 -1
- package/dist/storage/index.cjs +3 -0
- package/dist/storage/index.cjs.map +1 -1
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/index.js +2 -0
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/providers/dropbox.cjs +237 -0
- package/dist/storage/providers/dropbox.cjs.map +1 -0
- package/dist/storage/providers/dropbox.d.ts +39 -0
- package/dist/storage/providers/dropbox.js +215 -0
- package/dist/storage/providers/dropbox.js.map +1 -0
- package/dist/storage/providers/dropbox.test.d.ts +1 -0
- package/dist/tests/data-upload-owner-validation.test.d.ts +1 -0
- package/dist/types/atomicStore.cjs +31 -0
- package/dist/types/atomicStore.cjs.map +1 -0
- package/dist/types/atomicStore.d.ts +236 -0
- package/dist/types/atomicStore.js +7 -0
- package/dist/types/atomicStore.js.map +1 -0
- package/dist/types/config.cjs.map +1 -1
- package/dist/types/config.d.ts +32 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/controller-context.cjs.map +1 -1
- package/dist/types/controller-context.d.ts +4 -1
- package/dist/types/data.cjs.map +1 -1
- package/dist/types/data.d.ts +7 -4
- package/dist/types/generics.cjs.map +1 -1
- package/dist/types/generics.d.ts +1 -1
- package/dist/types/index.cjs.map +1 -1
- package/dist/types/index.d.ts +6 -3
- package/dist/types/index.js.map +1 -1
- package/dist/types/operationStore.cjs +17 -0
- package/dist/types/operationStore.cjs.map +1 -0
- package/dist/types/operationStore.d.ts +171 -0
- package/dist/types/operationStore.js +1 -0
- package/dist/types/operationStore.js.map +1 -0
- package/dist/types/operations.cjs +3 -15
- package/dist/types/operations.cjs.map +1 -1
- package/dist/types/operations.d.ts +17 -42
- package/dist/types/operations.js +2 -13
- package/dist/types/operations.js.map +1 -1
- package/dist/types/options.cjs +17 -0
- package/dist/types/options.cjs.map +1 -0
- package/dist/types/options.d.ts +308 -0
- package/dist/types/options.js +1 -0
- package/dist/types/options.js.map +1 -0
- package/dist/types/permissions.cjs.map +1 -1
- package/dist/types/permissions.d.ts +4 -0
- package/dist/types/personal.cjs.map +1 -1
- package/dist/types/personal.d.ts +19 -0
- package/dist/types/relayer.cjs.map +1 -1
- package/dist/types/relayer.d.ts +53 -9
- package/dist/types/utils.cjs.map +1 -1
- package/dist/types/utils.d.ts +0 -49
- package/dist/utils/__tests__/chainQuery.test.d.ts +1 -0
- package/dist/utils/__tests__/subgraphConsistency.test.d.ts +4 -0
- package/dist/utils/__tests__/subgraphPagination.test.d.ts +4 -0
- package/dist/utils/chainQuery.cjs +107 -0
- package/dist/utils/chainQuery.cjs.map +1 -0
- package/dist/utils/chainQuery.d.ts +31 -0
- package/dist/utils/chainQuery.js +82 -0
- package/dist/utils/chainQuery.js.map +1 -0
- package/dist/utils/grantFiles.cjs +4 -1
- package/dist/utils/grantFiles.cjs.map +1 -1
- package/dist/utils/grantFiles.js +4 -1
- package/dist/utils/grantFiles.js.map +1 -1
- package/dist/utils/ipfs.cjs +2 -4
- package/dist/utils/ipfs.cjs.map +1 -1
- package/dist/utils/ipfs.d.ts +1 -1
- package/dist/utils/ipfs.js +2 -4
- package/dist/utils/ipfs.js.map +1 -1
- package/dist/utils/subgraphConsistency.cjs +184 -0
- package/dist/utils/subgraphConsistency.cjs.map +1 -0
- package/dist/utils/subgraphConsistency.d.ts +65 -0
- package/dist/utils/subgraphConsistency.js +155 -0
- package/dist/utils/subgraphConsistency.js.map +1 -0
- package/dist/utils/subgraphMetaCache.cjs +101 -0
- package/dist/utils/subgraphMetaCache.cjs.map +1 -0
- package/dist/utils/subgraphMetaCache.d.ts +56 -0
- package/dist/utils/subgraphMetaCache.js +76 -0
- package/dist/utils/subgraphMetaCache.js.map +1 -0
- package/dist/utils/subgraphPagination.cjs +104 -0
- package/dist/utils/subgraphPagination.cjs.map +1 -0
- package/dist/utils/subgraphPagination.d.ts +78 -0
- package/dist/utils/subgraphPagination.js +78 -0
- package/dist/utils/subgraphPagination.js.map +1 -0
- package/package.json +3 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/permissions.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Base interface for types that need to be compatible with Record<string, unknown>\n *\n * @category Permissions\n */\nexport interface RecordCompatible {\n [key: string]: unknown;\n}\n\n/**\n * Contains on-chain permission data for efficient retrieval.\n *\n * @remarks\n * Provides fast access to permission metadata from subgraph without\n * IPFS calls. For detailed parameters, resolve `grantUrl` separately.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const grants = await vana.permissions.getUserPermissionGrantsOnChain();\n *\n * // Resolve details when needed\n * const details = await retrieveGrantFile(grants[0].grantUrl);\n * console.log(`Operation: ${details.operation}`);\n * ```\n */\nexport interface OnChainPermissionGrant {\n /** Unique identifier for the permission */\n id: bigint;\n /** The grant URL containing detailed permission parameters (IPFS link) */\n grantUrl: string;\n /** Cryptographic signature that authorized this permission */\n grantSignature: string;\n /** Nonce used when granting the permission */\n nonce: bigint;\n /** Block number when permission started */\n startBlock: bigint;\n /** Block number when permission was granted */\n addedAtBlock: bigint;\n /** Timestamp when permission was added */\n addedAtTimestamp: bigint;\n /** Transaction hash of the grant transaction */\n transactionHash: string;\n /** Address that granted the permission */\n grantor: Address;\n /** Grantee information */\n grantee: {\n /** Grantee ID */\n id: string;\n /** Grantee address */\n address: string;\n };\n /** Whether the permission is still active (not revoked) */\n active: boolean;\n}\n\n/**\n * Options for retrieving user permissions\n *\n * @category Permissions\n */\nexport interface GetUserPermissionsOptions {\n /** Maximum number of permissions to retrieve */\n limit?: number;\n /** Custom subgraph URL to use for querying */\n subgraphUrl?: string;\n}\n\n/**\n * Defines parameters for granting file access permissions.\n *\n * @remarks\n * Specifies application, operation, files, and parameters for\n * permission grants via `vana.permissions.grant()`.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const params: GrantPermissionParams = {\n * grantee: '0x1234...',\n * operation: 'llm_inference',\n * files: [1, 2, 3],\n * parameters: { model: 'gpt-4', maxTokens: 1000 }\n * };\n * const result = await vana.permissions.grant(params);\n * ```\n */\nexport interface GrantPermissionParams {\n /** The on-chain identity of the application */\n grantee: Address;\n /** The class of computation, e.g., \"llm_inference\" */\n operation: string;\n /**\n * Array of file IDs to grant permission for.\n * Obtain file IDs from `vana.data.getUserFiles()` or from upload results via `vana.data.upload().fileId`.\n */\n files: number[];\n /** The full, off-chain parameters (e.g., LLM prompt) */\n parameters: Record<string, unknown>;\n /** Optional pre-stored grant URL to avoid duplicate IPFS storage */\n grantUrl?: string;\n /** Optional nonce for the permission */\n nonce?: bigint;\n /** Optional expiration time for the permission */\n expiresAt?: number;\n}\n\n/**\n * Parameters for revoking a previously granted data access permission.\n *\n * Used with `PermissionsController.revoke()` to remove an application's access\n * to user data. Once revoked, the application can no longer use the permission\n * to access the specified files.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const revokeParams: RevokePermissionParams = {\n * permissionId: 123n // Permission ID to revoke\n * };\n *\n * await vana.permissions.revoke(revokeParams);\n * ```\n */\nexport interface RevokePermissionParams {\n /** The permission ID to revoke */\n permissionId: bigint;\n}\n\n/**\n * Parameters for checking if a specific permission exists and is valid.\n *\n * Used to verify whether an application has active permission to access\n * specific user files for a particular operation before attempting to use the data.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const checkParams: CheckPermissionParams = {\n * application: '0x1234...', // App address\n * operation: 'llm_inference',\n * files: [1, 2, 3], // File IDs to check\n * parameters: { model: 'gpt-4' }, // Operation parameters\n * user: '0xabcd...' // Optional specific user\n * };\n *\n * const hasPermission = await vana.permissions.check(checkParams);\n * ```\n */\nexport interface CheckPermissionParams {\n /** The application address */\n application: Address;\n /** The operation type */\n operation: string;\n /** The file IDs */\n files: number[];\n /** The grant parameters */\n parameters: Record<string, unknown>;\n /** The user address */\n user?: Address;\n}\n\n/**\n * Permission check result\n *\n * @category Permissions\n */\nexport interface PermissionCheckResult {\n /** Whether the permission exists and is valid */\n exists: boolean;\n /** The permission details if it exists */\n permission?: GrantedPermission;\n /** Reason why permission is invalid (if applicable) */\n reason?: string;\n}\n\n/**\n * EIP-712 domain definition for PermissionGrant signatures\n *\n * @category Permissions\n */\nexport interface PermissionGrantDomain {\n /** Domain name */\n name: string;\n /** Domain version */\n version: string;\n /** Chain ID */\n chainId: number;\n /** Verifying contract address */\n verifyingContract: Address;\n}\n\n/**\n * EIP-712 Permission message structure (current contract format)\n *\n * @category Permissions\n */\nexport interface PermissionGrantMessage {\n /** Application address */\n application: Address;\n /** File IDs */\n files: number[];\n /** Operation type */\n operation: string;\n /** Grant URL */\n grant: string;\n /** Parameters as JSON string */\n parameters: string;\n /** Nonce */\n nonce: bigint;\n}\n\n/**\n * EIP-712 PermissionInput message structure (new simplified format)\n *\n * @category Permissions\n */\nexport interface PermissionInputMessage extends RecordCompatible {\n /** Nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File IDs */\n fileIds: bigint[];\n}\n\n/**\n * Contract PermissionInput structure\n *\n * @category Permissions\n */\nexport interface PermissionInput {\n /** Nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File IDs to grant permission for */\n fileIds: bigint[];\n}\n\n/**\n * Contract RevokePermissionInput structure\n *\n * @category Permissions\n */\nexport interface RevokePermissionInput extends RecordCompatible {\n /** Nonce */\n nonce: bigint;\n /** Permission ID to revoke */\n permissionId: bigint;\n}\n\n/**\n * Contract Permission Info structure returned from the contract\n *\n * @category Permissions\n */\nexport interface PermissionInfo {\n /** Permission ID */\n id: bigint;\n /** Address that granted the permission */\n grantor: Address;\n /** Nonce used when creating */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** Signature bytes (removed in newer contract versions) */\n signature?: `0x${string}`;\n /** Start block */\n startBlock: bigint;\n /** End block */\n endBlock: bigint;\n /** File IDs associated with this permission */\n fileIds: readonly bigint[];\n}\n\n/**\n * EIP-712 Permission message structure (simplified future format)\n *\n * @category Permissions\n */\nexport interface SimplifiedPermissionMessage {\n /** Application address */\n application: Address;\n /** Grant URL */\n grant: string;\n /** Nonce */\n nonce: bigint;\n}\n\n/**\n * Grant file structure containing permission details.\n *\n * Grant files contain the complete specification of what an application is permitted\n * to do with user data, including operation parameters and file access rights.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const grantFile: GrantFile = {\n * grantee: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',\n * operation: 'llm_inference',\n * parameters: {\n * prompt: 'Analyze this data: {{data}}',\n * model: 'gpt-4',\n * maxTokens: 2000,\n * temperature: 0.7\n * },\n * expires: 1736467579\n * };\n * ```\n */\nexport interface GrantFile {\n /** EVM address of the application authorized to use this grant */\n grantee: Address;\n /** Operation the grantee is authorized to perform */\n operation: string;\n /** Operation-specific parameters */\n parameters: Record<string, unknown>;\n /** Optional Unix timestamp when grant expires (seconds since epoch per POSIX.1-2008) */\n expires?: number;\n}\n\n/**\n * EIP-712 typed data structure for Permission\n *\n * @category Permissions\n */\nexport interface PermissionGrantTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n Permission: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"Permission\";\n /** Message to sign */\n message: PermissionInputMessage;\n}\n\n/**\n * Generic EIP-712 typed data structure\n *\n * @category Permissions\n */\nexport interface GenericTypedData extends RecordCompatible {\n /** EIP-712 domain */\n domain: PermissionGrantDomain;\n /** EIP-712 types */\n types: Record<string, Array<{ name: string; type: string }>>;\n /** Primary type */\n primaryType: string;\n /** Message to sign */\n message: Record<string, unknown>;\n}\n\n/**\n * Represents EIP-712 typed data for permission revocation.\n *\n * @remarks\n * Used when revoking previously granted permissions through gasless transactions.\n * The message contains a nonce and the permission ID to revoke.\n *\n * @category Permissions\n */\nexport interface RevokePermissionTypedData extends GenericTypedData {\n /** EIP-712 type definitions for the RevokePermission structure */\n types: {\n RevokePermission: Array<{\n name: string;\n type: string;\n }>;\n };\n /** The primary type identifier for revocation operations */\n primaryType: \"RevokePermission\";\n /** The structured message containing revocation parameters */\n message: RevokePermissionInput;\n}\n\n/**\n * Defines all valid primary types for EIP-712 typed data in the Vana SDK.\n *\n * @remarks\n * These literal types ensure compile-time safety when handling typed data operations.\n * Each corresponds to a specific blockchain operation type.\n *\n * @category Permissions\n */\nexport type TypedDataPrimaryType =\n | \"Permission\"\n | \"RevokePermission\"\n | \"TrustServer\"\n | \"UntrustServer\"\n | \"AddServer\"\n | \"RegisterGrantee\"\n | \"ServerFilesAndPermission\";\n\n/**\n * Represents the union of all specific typed data interfaces.\n *\n * @remarks\n * Enables type-safe handling of any typed data structure in the SDK.\n * Used internally by relayer handlers and signature verification.\n *\n * @category Permissions\n */\nexport type SpecificTypedData =\n | PermissionGrantTypedData\n | RevokePermissionTypedData\n | TrustServerTypedData\n | UntrustServerTypedData\n | AddAndTrustServerTypedData\n | RegisterGranteeTypedData\n | ServerFilesAndPermissionTypedData;\n\n/**\n * Permission operation types\n *\n * @category Permissions\n */\nexport type PermissionOperation =\n | \"llm_inference\"\n | \"data_analysis\"\n | \"model_training\"\n | \"data_sharing\"\n | \"compute_task\"\n | string;\n\n/**\n * Permission status\n *\n * @category Permissions\n */\nexport type PermissionStatus = \"active\" | \"revoked\" | \"expired\" | \"pending\";\n\n/**\n * Parameters for querying permissions\n *\n * @category Permissions\n */\nexport interface QueryPermissionsParams {\n /** Filter by grantor address */\n grantor?: Address;\n /** Filter by grantee address */\n grantee?: Address;\n /** Filter by operation type */\n operation?: PermissionOperation;\n /** Filter by file IDs */\n files?: number[];\n /** Filter by status */\n status?: PermissionStatus;\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n /** Maximum number of results */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Granted permission details\n *\n * @category Permissions\n */\nexport interface GrantedPermission {\n /** Unique identifier for the permission */\n id: bigint;\n /** Array of file IDs that the permission applies to */\n files: number[];\n /** The type of operation being granted permission for */\n operation: string;\n /** Grant file reference (IPFS hash or URL) */\n grant: string;\n /** Address of the application granted permission */\n grantee: Address;\n /** Address of the user who granted permission */\n grantor: Address;\n /** Custom parameters for the operation */\n parameters: Record<string, unknown>;\n /** Whether the permission is still active */\n active: boolean;\n /** Data status for the permission */\n dataStatus?: string;\n /** Nonce used for the permission */\n nonce?: number;\n /** Timestamp when permission was granted */\n grantedAt?: number;\n /** Optional expiration timestamp */\n expiresAt?: number;\n /** Transaction hash of the grant transaction */\n transactionHash?: string;\n /** Block number when permission was granted */\n blockNumber?: bigint;\n}\n\n/**\n * Permission query result\n *\n * @category Permissions\n */\nexport interface PermissionQueryResult {\n /** Array of permissions matching the query */\n permissions: GrantedPermission[];\n /** Total number of permissions (for pagination) */\n total: number;\n /** Whether there are more results available */\n hasMore: boolean;\n}\n\n/**\n * Permission analytics data\n *\n * @category Permissions\n */\nexport interface PermissionAnalytics {\n /** Total number of permissions granted */\n totalPermissions: number;\n /** Number of active permissions */\n activePermissions: number;\n /** Number of revoked permissions */\n revokedPermissions: number;\n /** Number of expired permissions */\n expiredPermissions: number;\n /** Most common operation types */\n topOperations: Array<{\n operation: PermissionOperation;\n count: number;\n }>;\n /** Most active applications */\n topApplications: Array<{\n application: Address;\n count: number;\n }>;\n}\n\n/**\n * Server information\n *\n * @category Permissions\n */\nexport interface Server {\n /** Server ID (numeric) */\n id: number;\n /** Server owner address */\n owner: Address;\n /** Server URL */\n url: string;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Contract ServerInfo structure returned from the contract\n *\n * @category Permissions\n */\nexport interface ServerInfo {\n /** Server ID */\n id: bigint;\n /** Server owner address */\n owner: Address;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n /** Server URL */\n url: string;\n}\n\n/**\n * Parameters for adding and trusting a server\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerParams {\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Parameters for trusting a server (legacy)\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerParams instead\n */\nexport interface TrustServerParams {\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Parameters for untrusting a server\n *\n * @category Permissions\n */\nexport interface UntrustServerParams {\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Input for adding and trusting a server with signature (gasless)\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Input for trusting a server with signature (gasless)\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerInput instead\n */\nexport interface TrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Input for untrusting a server with signature (gasless)\n *\n * @category Permissions\n */\nexport interface UntrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * EIP-712 typed data for AddAndTrustServer\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n AddServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"AddServer\";\n /** Message to sign */\n message: AddAndTrustServerInput;\n}\n\n/**\n * EIP-712 typed data for TrustServer\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerTypedData instead\n */\nexport interface TrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n TrustServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"TrustServer\";\n /** Message to sign */\n message: TrustServerInput;\n}\n\n/**\n * EIP-712 typed data for UntrustServer\n *\n * @category Permissions\n */\nexport interface UntrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n UntrustServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"UntrustServer\";\n /** Message to sign */\n message: UntrustServerInput;\n}\n\n/**\n * Permission event data\n *\n * @category Permissions\n */\nexport interface PermissionEvent {\n /** Event type */\n type: \"granted\" | \"revoked\" | \"expired\";\n /** Permission details */\n permission: GrantedPermission;\n /** Block number where event occurred */\n blockNumber: bigint;\n /** Transaction hash */\n transactionHash: Hash;\n /** Event timestamp */\n timestamp: number;\n}\n\n/**\n * Enhanced trusted server information with trust status\n *\n * @category Permissions\n */\nexport interface TrustedServerInfo {\n /** Server ID */\n id: bigint;\n /** Server owner address */\n owner: Address;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n /** Server URL */\n url: string;\n /** Start block when trust relationship began */\n startBlock: bigint;\n /** End block when trust relationship ended (0 if still active) */\n endBlock: bigint;\n}\n\n/**\n * Paginated result for trusted server queries\n *\n * @category Permissions\n */\nexport interface PaginatedTrustedServers {\n /** Array of server IDs (numeric) */\n servers: number[];\n /** Total number of trusted servers */\n total: number;\n /** Offset used for this query */\n offset: number;\n /** Limit used for this query */\n limit: number;\n /** Whether there are more servers beyond this page */\n hasMore: boolean;\n}\n\n/**\n * Options for querying trusted servers\n *\n * @category Permissions\n */\nexport interface TrustedServerQueryOptions {\n /** User address to query (defaults to current user) */\n userAddress?: Address;\n /** Maximum number of servers to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n /** Whether to include full server info or just IDs */\n includeServerInfo?: boolean;\n}\n\n/**\n * Result of batch server info requests\n *\n * @category Permissions\n */\nexport interface BatchServerInfoResult {\n /** Successfully retrieved server info */\n servers: Map<number, Server>;\n /** Server IDs that failed to retrieve */\n failed: number[];\n}\n\n/**\n * Server trust status information\n *\n * @category Permissions\n */\nexport interface ServerTrustStatus {\n /** Server ID being checked (numeric) */\n serverId: number;\n /** Whether the server is trusted by the user */\n isTrusted: boolean;\n /** Index in user's trusted server list (if trusted) */\n trustIndex?: number;\n}\n\n/**\n * Grantee information\n *\n * @category Permissions\n */\nexport interface Grantee {\n /** Grantee ID (numeric) */\n id: number;\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n address: Address;\n /** Grantee public key */\n publicKey: string;\n /** Permission IDs associated with this grantee */\n permissionIds: number[];\n}\n\n/**\n * Contract GranteeInfo structure returned from the contract\n *\n * @category Permissions\n */\nexport interface GranteeInfo {\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n /** Permission IDs associated with this grantee */\n permissionIds: readonly bigint[];\n}\n\n/**\n * Parameters for registering a grantee\n *\n * @category Permissions\n */\nexport interface RegisterGranteeParams {\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n}\n\n/**\n * Input for registering a grantee with signature (gasless)\n *\n * @category Permissions\n */\nexport interface RegisterGranteeInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n}\n\n/**\n * EIP-712 typed data for RegisterGrantee\n *\n * @category Permissions\n */\nexport interface RegisterGranteeTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n RegisterGrantee: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"RegisterGrantee\";\n /** Message to sign */\n message: RegisterGranteeInput;\n}\n\n/**\n * Options for querying grantees\n *\n * @category Permissions\n */\nexport interface GranteeQueryOptions {\n /** Maximum number of grantees to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n /** Whether to include permission info or just basic info */\n includePermissions?: boolean;\n}\n\n/**\n * Paginated result for grantee queries\n *\n * @category Permissions\n */\nexport interface PaginatedGrantees {\n /** Array of grantees */\n grantees: Grantee[];\n /** Total number of grantees */\n total: number;\n /** Offset used for this query */\n offset: number;\n /** Limit used for this query */\n limit: number;\n /** Whether there are more grantees beyond this page */\n hasMore: boolean;\n}\n\n/**\n * Contract Permission structure as used in ServerFilesAndPermissionInput\n *\n * @category Permissions\n */\nexport interface Permission {\n /** Account address for the permission */\n account: Address;\n /** Permission key */\n key: string;\n}\n\n/**\n * Contract ServerFilesAndPermissionInput structure\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionInput {\n /** User nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n}\n\n/**\n * Parameters for server files and permissions operations\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionParams {\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL or grant data */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Schema IDs for each file - use 0 for files without schema validation */\n schemaIds: number[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n}\n\n/**\n * EIP-712 typed data for server files and permissions messages\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionTypedData extends GenericTypedData {\n /** Message data structure */\n message: {\n /** User nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Schema IDs for each file - use 0 for files without schema validation */\n schemaIds: bigint[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/permissions.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Base interface for types that need to be compatible with Record<string, unknown>\n *\n * @category Permissions\n */\nexport interface RecordCompatible {\n [key: string]: unknown;\n}\n\n/**\n * Contains on-chain permission data for efficient retrieval.\n *\n * @remarks\n * Provides fast access to permission metadata from subgraph without\n * IPFS calls. For detailed parameters, resolve `grantUrl` separately.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const grants = await vana.permissions.getUserPermissionGrantsOnChain();\n *\n * // Resolve details when needed\n * const details = await retrieveGrantFile(grants[0].grantUrl);\n * console.log(`Operation: ${details.operation}`);\n * ```\n */\nexport interface OnChainPermissionGrant {\n /** Unique identifier for the permission */\n id: bigint;\n /** The grant URL containing detailed permission parameters (IPFS link) */\n grantUrl: string;\n /** Cryptographic signature that authorized this permission */\n grantSignature: string;\n /** Nonce used when granting the permission */\n nonce: bigint;\n /** Block number when permission started */\n startBlock: bigint;\n /** Block number when permission was granted */\n addedAtBlock: bigint;\n /** Timestamp when permission was added */\n addedAtTimestamp: bigint;\n /** Transaction hash of the grant transaction */\n transactionHash: string;\n /** Address that granted the permission */\n grantor: Address;\n /** Grantee information */\n grantee: {\n /** Grantee ID */\n id: string;\n /** Grantee address */\n address: string;\n };\n /** Whether the permission is still active (not revoked) */\n active: boolean;\n}\n\n/**\n * Options for retrieving user permissions\n *\n * @category Permissions\n */\nexport interface GetUserPermissionsOptions {\n /** Maximum number of permissions to retrieve */\n limit?: number;\n /** Whether to fetch all permissions (ignores limit) */\n fetchAll?: boolean;\n /** Custom subgraph URL to use for querying */\n subgraphUrl?: string;\n}\n\n/**\n * Defines parameters for granting file access permissions.\n *\n * @remarks\n * Specifies application, operation, files, and parameters for\n * permission grants via `vana.permissions.grant()`.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const params: GrantPermissionParams = {\n * grantee: '0x1234...',\n * operation: 'llm_inference',\n * files: [1, 2, 3],\n * parameters: { model: 'gpt-4', maxTokens: 1000 }\n * };\n * const result = await vana.permissions.grant(params);\n * ```\n */\nexport interface GrantPermissionParams {\n /** The on-chain identity of the application */\n grantee: Address;\n /** The class of computation, e.g., \"llm_inference\" */\n operation: string;\n /**\n * Array of file IDs to grant permission for.\n * Obtain file IDs from `vana.data.getUserFiles()` or from upload results via `vana.data.upload().fileId`.\n */\n files: number[];\n /** The full, off-chain parameters (e.g., LLM prompt) */\n parameters: Record<string, unknown>;\n /** Optional JSONPath filters to apply to files, keyed by file ID */\n filters?: Record<string, string>;\n /** Optional pre-stored grant URL to avoid duplicate IPFS storage */\n grantUrl?: string;\n /** Optional nonce for the permission */\n nonce?: bigint;\n /** Optional expiration time for the permission */\n expiresAt?: number;\n}\n\n/**\n * Parameters for revoking a previously granted data access permission.\n *\n * Used with `PermissionsController.revoke()` to remove an application's access\n * to user data. Once revoked, the application can no longer use the permission\n * to access the specified files.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const revokeParams: RevokePermissionParams = {\n * permissionId: 123n // Permission ID to revoke\n * };\n *\n * await vana.permissions.revoke(revokeParams);\n * ```\n */\nexport interface RevokePermissionParams {\n /** The permission ID to revoke */\n permissionId: bigint;\n}\n\n/**\n * Parameters for checking if a specific permission exists and is valid.\n *\n * Used to verify whether an application has active permission to access\n * specific user files for a particular operation before attempting to use the data.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const checkParams: CheckPermissionParams = {\n * application: '0x1234...', // App address\n * operation: 'llm_inference',\n * files: [1, 2, 3], // File IDs to check\n * parameters: { model: 'gpt-4' }, // Operation parameters\n * user: '0xabcd...' // Optional specific user\n * };\n *\n * const hasPermission = await vana.permissions.check(checkParams);\n * ```\n */\nexport interface CheckPermissionParams {\n /** The application address */\n application: Address;\n /** The operation type */\n operation: string;\n /** The file IDs */\n files: number[];\n /** The grant parameters */\n parameters: Record<string, unknown>;\n /** The user address */\n user?: Address;\n}\n\n/**\n * Permission check result\n *\n * @category Permissions\n */\nexport interface PermissionCheckResult {\n /** Whether the permission exists and is valid */\n exists: boolean;\n /** The permission details if it exists */\n permission?: GrantedPermission;\n /** Reason why permission is invalid (if applicable) */\n reason?: string;\n}\n\n/**\n * EIP-712 domain definition for PermissionGrant signatures\n *\n * @category Permissions\n */\nexport interface PermissionGrantDomain {\n /** Domain name */\n name: string;\n /** Domain version */\n version: string;\n /** Chain ID */\n chainId: number;\n /** Verifying contract address */\n verifyingContract: Address;\n}\n\n/**\n * EIP-712 Permission message structure (current contract format)\n *\n * @category Permissions\n */\nexport interface PermissionGrantMessage {\n /** Application address */\n application: Address;\n /** File IDs */\n files: number[];\n /** Operation type */\n operation: string;\n /** Grant URL */\n grant: string;\n /** Parameters as JSON string */\n parameters: string;\n /** Nonce */\n nonce: bigint;\n}\n\n/**\n * EIP-712 PermissionInput message structure (new simplified format)\n *\n * @category Permissions\n */\nexport interface PermissionInputMessage extends RecordCompatible {\n /** Nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File IDs */\n fileIds: bigint[];\n}\n\n/**\n * Contract PermissionInput structure\n *\n * @category Permissions\n */\nexport interface PermissionInput {\n /** Nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File IDs to grant permission for */\n fileIds: bigint[];\n}\n\n/**\n * Contract RevokePermissionInput structure\n *\n * @category Permissions\n */\nexport interface RevokePermissionInput extends RecordCompatible {\n /** Nonce */\n nonce: bigint;\n /** Permission ID to revoke */\n permissionId: bigint;\n}\n\n/**\n * Contract Permission Info structure returned from the contract\n *\n * @category Permissions\n */\nexport interface PermissionInfo {\n /** Permission ID */\n id: bigint;\n /** Address that granted the permission */\n grantor: Address;\n /** Nonce used when creating */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** Signature bytes (removed in newer contract versions) */\n signature?: `0x${string}`;\n /** Start block */\n startBlock: bigint;\n /** End block */\n endBlock: bigint;\n /** File IDs associated with this permission */\n fileIds: readonly bigint[];\n}\n\n/**\n * EIP-712 Permission message structure (simplified future format)\n *\n * @category Permissions\n */\nexport interface SimplifiedPermissionMessage {\n /** Application address */\n application: Address;\n /** Grant URL */\n grant: string;\n /** Nonce */\n nonce: bigint;\n}\n\n/**\n * Grant file structure containing permission details.\n *\n * Grant files contain the complete specification of what an application is permitted\n * to do with user data, including operation parameters and file access rights.\n *\n * @category Permissions\n * @example\n * ```typescript\n * const grantFile: GrantFile = {\n * grantee: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',\n * operation: 'llm_inference',\n * parameters: {\n * prompt: 'Analyze this data: {{data}}',\n * model: 'gpt-4',\n * maxTokens: 2000,\n * temperature: 0.7\n * },\n * expires: 1736467579\n * };\n * ```\n */\nexport interface GrantFile {\n /** EVM address of the application authorized to use this grant */\n grantee: Address;\n /** Operation the grantee is authorized to perform */\n operation: string;\n /** Operation-specific parameters */\n parameters: Record<string, unknown>;\n /** Optional Unix timestamp when grant expires (seconds since epoch per POSIX.1-2008) */\n expires?: number;\n}\n\n/**\n * EIP-712 typed data structure for Permission\n *\n * @category Permissions\n */\nexport interface PermissionGrantTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n Permission: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"Permission\";\n /** Message to sign */\n message: PermissionInputMessage;\n}\n\n/**\n * Generic EIP-712 typed data structure\n *\n * @category Permissions\n */\nexport interface GenericTypedData extends RecordCompatible {\n /** EIP-712 domain */\n domain: PermissionGrantDomain;\n /** EIP-712 types */\n types: Record<string, Array<{ name: string; type: string }>>;\n /** Primary type */\n primaryType: string;\n /** Message to sign */\n message: Record<string, unknown>;\n}\n\n/**\n * Represents EIP-712 typed data for permission revocation.\n *\n * @remarks\n * Used when revoking previously granted permissions through gasless transactions.\n * The message contains a nonce and the permission ID to revoke.\n *\n * @category Permissions\n */\nexport interface RevokePermissionTypedData extends GenericTypedData {\n /** EIP-712 type definitions for the RevokePermission structure */\n types: {\n RevokePermission: Array<{\n name: string;\n type: string;\n }>;\n };\n /** The primary type identifier for revocation operations */\n primaryType: \"RevokePermission\";\n /** The structured message containing revocation parameters */\n message: RevokePermissionInput;\n}\n\n/**\n * Defines all valid primary types for EIP-712 typed data in the Vana SDK.\n *\n * @remarks\n * These literal types ensure compile-time safety when handling typed data operations.\n * Each corresponds to a specific blockchain operation type.\n *\n * @category Permissions\n */\nexport type TypedDataPrimaryType =\n | \"Permission\"\n | \"RevokePermission\"\n | \"TrustServer\"\n | \"UntrustServer\"\n | \"AddServer\"\n | \"RegisterGrantee\"\n | \"ServerFilesAndPermission\";\n\n/**\n * Represents the union of all specific typed data interfaces.\n *\n * @remarks\n * Enables type-safe handling of any typed data structure in the SDK.\n * Used internally by relayer handlers and signature verification.\n *\n * @category Permissions\n */\nexport type SpecificTypedData =\n | PermissionGrantTypedData\n | RevokePermissionTypedData\n | TrustServerTypedData\n | UntrustServerTypedData\n | AddAndTrustServerTypedData\n | RegisterGranteeTypedData\n | ServerFilesAndPermissionTypedData;\n\n/**\n * Permission operation types\n *\n * @category Permissions\n */\nexport type PermissionOperation =\n | \"llm_inference\"\n | \"data_analysis\"\n | \"model_training\"\n | \"data_sharing\"\n | \"compute_task\"\n | string;\n\n/**\n * Permission status\n *\n * @category Permissions\n */\nexport type PermissionStatus = \"active\" | \"revoked\" | \"expired\" | \"pending\";\n\n/**\n * Parameters for querying permissions\n *\n * @category Permissions\n */\nexport interface QueryPermissionsParams {\n /** Filter by grantor address */\n grantor?: Address;\n /** Filter by grantee address */\n grantee?: Address;\n /** Filter by operation type */\n operation?: PermissionOperation;\n /** Filter by file IDs */\n files?: number[];\n /** Filter by status */\n status?: PermissionStatus;\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n /** Maximum number of results */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Granted permission details\n *\n * @category Permissions\n */\nexport interface GrantedPermission {\n /** Unique identifier for the permission */\n id: bigint;\n /** Array of file IDs that the permission applies to */\n files: number[];\n /** The type of operation being granted permission for */\n operation: string;\n /** Grant file reference (IPFS hash or URL) */\n grant: string;\n /** Address of the application granted permission */\n grantee: Address;\n /** Address of the user who granted permission */\n grantor: Address;\n /** Custom parameters for the operation */\n parameters: Record<string, unknown>;\n /** Whether the permission is still active */\n active: boolean;\n /** Data status for the permission */\n dataStatus?: string;\n /** Nonce used for the permission */\n nonce?: number;\n /** Timestamp when permission was granted */\n grantedAt?: number;\n /** Optional expiration timestamp */\n expiresAt?: number;\n /** Transaction hash of the grant transaction */\n transactionHash?: string;\n /** Block number when permission was granted */\n blockNumber?: bigint;\n}\n\n/**\n * Permission query result\n *\n * @category Permissions\n */\nexport interface PermissionQueryResult {\n /** Array of permissions matching the query */\n permissions: GrantedPermission[];\n /** Total number of permissions (for pagination) */\n total: number;\n /** Whether there are more results available */\n hasMore: boolean;\n}\n\n/**\n * Permission analytics data\n *\n * @category Permissions\n */\nexport interface PermissionAnalytics {\n /** Total number of permissions granted */\n totalPermissions: number;\n /** Number of active permissions */\n activePermissions: number;\n /** Number of revoked permissions */\n revokedPermissions: number;\n /** Number of expired permissions */\n expiredPermissions: number;\n /** Most common operation types */\n topOperations: Array<{\n operation: PermissionOperation;\n count: number;\n }>;\n /** Most active applications */\n topApplications: Array<{\n application: Address;\n count: number;\n }>;\n}\n\n/**\n * Server information\n *\n * @category Permissions\n */\nexport interface Server {\n /** Server ID (numeric) */\n id: number;\n /** Server owner address */\n owner: Address;\n /** Server URL */\n url: string;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Contract ServerInfo structure returned from the contract\n *\n * @category Permissions\n */\nexport interface ServerInfo {\n /** Server ID */\n id: bigint;\n /** Server owner address */\n owner: Address;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n /** Server URL */\n url: string;\n}\n\n/**\n * Parameters for adding and trusting a server\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerParams {\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Parameters for trusting a server (legacy)\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerParams instead\n */\nexport interface TrustServerParams {\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Parameters for untrusting a server\n *\n * @category Permissions\n */\nexport interface UntrustServerParams {\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Input for adding and trusting a server with signature (gasless)\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n publicKey: string;\n}\n\n/**\n * Input for trusting a server with signature (gasless)\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerInput instead\n */\nexport interface TrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * Input for untrusting a server with signature (gasless)\n *\n * @category Permissions\n */\nexport interface UntrustServerInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Server ID (numeric) */\n serverId: number;\n}\n\n/**\n * EIP-712 typed data for AddAndTrustServer\n *\n * @category Permissions\n */\nexport interface AddAndTrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n AddServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"AddServer\";\n /** Message to sign */\n message: AddAndTrustServerInput;\n}\n\n/**\n * EIP-712 typed data for TrustServer\n *\n * @category Permissions\n * @deprecated Use AddAndTrustServerTypedData instead\n */\nexport interface TrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n TrustServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"TrustServer\";\n /** Message to sign */\n message: TrustServerInput;\n}\n\n/**\n * EIP-712 typed data for UntrustServer\n *\n * @category Permissions\n */\nexport interface UntrustServerTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n UntrustServer: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"UntrustServer\";\n /** Message to sign */\n message: UntrustServerInput;\n}\n\n/**\n * Permission event data\n *\n * @category Permissions\n */\nexport interface PermissionEvent {\n /** Event type */\n type: \"granted\" | \"revoked\" | \"expired\";\n /** Permission details */\n permission: GrantedPermission;\n /** Block number where event occurred */\n blockNumber: bigint;\n /** Transaction hash */\n transactionHash: Hash;\n /** Event timestamp */\n timestamp: number;\n}\n\n/**\n * Enhanced trusted server information with trust status\n *\n * @category Permissions\n */\nexport interface TrustedServerInfo {\n /** Server ID */\n id: bigint;\n /** Server owner address */\n owner: Address;\n /** Server address */\n serverAddress: Address;\n /** Server public key */\n publicKey: string;\n /** Server URL */\n url: string;\n /** Start block when trust relationship began */\n startBlock: bigint;\n /** End block when trust relationship ended (0 if still active) */\n endBlock: bigint;\n}\n\n/**\n * Paginated result for trusted server queries\n *\n * @category Permissions\n */\nexport interface PaginatedTrustedServers {\n /** Array of server IDs (numeric) */\n servers: number[];\n /** Total number of trusted servers */\n total: number;\n /** Offset used for this query */\n offset: number;\n /** Limit used for this query */\n limit: number;\n /** Whether there are more servers beyond this page */\n hasMore: boolean;\n}\n\n/**\n * Options for querying trusted servers\n *\n * @category Permissions\n */\nexport interface TrustedServerQueryOptions {\n /** User address to query (defaults to current user) */\n userAddress?: Address;\n /** Maximum number of servers to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n /** Whether to include full server info or just IDs */\n includeServerInfo?: boolean;\n}\n\n/**\n * Result of batch server info requests\n *\n * @category Permissions\n */\nexport interface BatchServerInfoResult {\n /** Successfully retrieved server info */\n servers: Map<number, Server>;\n /** Server IDs that failed to retrieve */\n failed: number[];\n}\n\n/**\n * Server trust status information\n *\n * @category Permissions\n */\nexport interface ServerTrustStatus {\n /** Server ID being checked (numeric) */\n serverId: number;\n /** Whether the server is trusted by the user */\n isTrusted: boolean;\n /** Index in user's trusted server list (if trusted) */\n trustIndex?: number;\n}\n\n/**\n * Grantee information\n *\n * @category Permissions\n */\nexport interface Grantee {\n /** Grantee ID (numeric) */\n id: number;\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n address: Address;\n /** Grantee public key */\n publicKey: string;\n /** Permission IDs associated with this grantee */\n permissionIds: number[];\n}\n\n/**\n * Contract GranteeInfo structure returned from the contract\n *\n * @category Permissions\n */\nexport interface GranteeInfo {\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n /** Permission IDs associated with this grantee */\n permissionIds: readonly bigint[];\n}\n\n/**\n * Parameters for registering a grantee\n *\n * @category Permissions\n */\nexport interface RegisterGranteeParams {\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n}\n\n/**\n * Input for registering a grantee with signature (gasless)\n *\n * @category Permissions\n */\nexport interface RegisterGranteeInput extends RecordCompatible {\n /** User nonce */\n nonce: bigint;\n /** Grantee owner address */\n owner: Address;\n /** Grantee address */\n granteeAddress: Address;\n /** Grantee public key */\n publicKey: string;\n}\n\n/**\n * EIP-712 typed data for RegisterGrantee\n *\n * @category Permissions\n */\nexport interface RegisterGranteeTypedData extends GenericTypedData {\n /** EIP-712 types */\n types: {\n RegisterGrantee: Array<{\n name: string;\n type: string;\n }>;\n };\n /** Primary type */\n primaryType: \"RegisterGrantee\";\n /** Message to sign */\n message: RegisterGranteeInput;\n}\n\n/**\n * Options for querying grantees\n *\n * @category Permissions\n */\nexport interface GranteeQueryOptions {\n /** Maximum number of grantees to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n /** Whether to include permission info or just basic info */\n includePermissions?: boolean;\n}\n\n/**\n * Paginated result for grantee queries\n *\n * @category Permissions\n */\nexport interface PaginatedGrantees {\n /** Array of grantees */\n grantees: Grantee[];\n /** Total number of grantees */\n total: number;\n /** Offset used for this query */\n offset: number;\n /** Limit used for this query */\n limit: number;\n /** Whether there are more grantees beyond this page */\n hasMore: boolean;\n}\n\n/**\n * Contract Permission structure as used in ServerFilesAndPermissionInput\n *\n * @category Permissions\n */\nexport interface Permission {\n /** Account address for the permission */\n account: Address;\n /** Permission key */\n key: string;\n}\n\n/**\n * Contract ServerFilesAndPermissionInput structure\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionInput {\n /** User nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n}\n\n/**\n * Parameters for server files and permissions operations\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionParams {\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL or grant data */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Schema IDs for each file - use 0 for files without schema validation */\n schemaIds: number[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n}\n\n/**\n * EIP-712 typed data for server files and permissions messages\n *\n * @category Permissions\n */\nexport interface ServerFilesAndPermissionTypedData extends GenericTypedData {\n /** Message data structure */\n message: {\n /** User nonce */\n nonce: bigint;\n /** Grantee ID */\n granteeId: bigint;\n /** Grant URL */\n grant: string;\n /** File URLs */\n fileUrls: string[];\n /** Schema IDs for each file - use 0 for files without schema validation */\n schemaIds: bigint[];\n /** Server address */\n serverAddress: Address;\n /** Server URL */\n serverUrl: string;\n /** Server public key */\n serverPublicKey: string;\n /** File permissions array - permissions for each file */\n filePermissions: Permission[][];\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
@@ -61,6 +61,8 @@ export interface OnChainPermissionGrant {
|
|
|
61
61
|
export interface GetUserPermissionsOptions {
|
|
62
62
|
/** Maximum number of permissions to retrieve */
|
|
63
63
|
limit?: number;
|
|
64
|
+
/** Whether to fetch all permissions (ignores limit) */
|
|
65
|
+
fetchAll?: boolean;
|
|
64
66
|
/** Custom subgraph URL to use for querying */
|
|
65
67
|
subgraphUrl?: string;
|
|
66
68
|
}
|
|
@@ -95,6 +97,8 @@ export interface GrantPermissionParams {
|
|
|
95
97
|
files: number[];
|
|
96
98
|
/** The full, off-chain parameters (e.g., LLM prompt) */
|
|
97
99
|
parameters: Record<string, unknown>;
|
|
100
|
+
/** Optional JSONPath filters to apply to files, keyed by file ID */
|
|
101
|
+
filters?: Record<string, string>;
|
|
98
102
|
/** Optional pre-stored grant URL to avoid duplicate IPFS storage */
|
|
99
103
|
grantUrl?: string;
|
|
100
104
|
/** Optional nonce for the permission */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/personal.ts"],"sourcesContent":["/**\n * Defines parameters for posting data requests to personal servers.\n *\n * @remarks\n * Used to initiate data access requests that require user permission.\n * The permission ID references a previously granted permission that\n * authorizes the requester to access specific user data.\n *\n * @example\n * ```typescript\n * const params: PostRequestParams = {\n * permissionId: 123\n * };\n *\n * const response = await vana.personal.postRequest(params);\n * console.log('Request posted:', response.requestId);\n * ```\n *\n * @category Personal Server\n */\nexport interface PostRequestParams {\n /**\n * References a granted permission authorizing data access.\n * Obtain via permission granting flow or query existing permissions.\n * @throws {PermissionNotFoundError} If permission ID is invalid.\n */\n permissionId: number;\n}\n\n/**\n * Defines parameters for creating server-side operations.\n *\n * @remarks\n * Initiates asynchronous operations on the personal server that\n * process user data according to granted permissions. Operations\n * run in the background and can be monitored via their operation ID.\n *\n * @example\n * ```typescript\n * const params: CreateOperationParams = {\n * permissionId: 456\n * };\n *\n * const operation = await vana.server.createOperation(params);\n * // Monitor operation status\n * const status = await vana.server.getOperationStatus(operation.id);\n * ```\n *\n * @category Personal Server\n */\nexport interface CreateOperationParams {\n /**\n * References the permission scope for this operation.\n * Determines what data and actions are allowed.\n * @throws {InsufficientPermissionsError} If permission scope is inadequate.\n */\n permissionId: number;\n}\n\n/**\n * Defines parameters for initializing personal server connections.\n *\n * @remarks\n * Establishes secure communication channels with a user's personal\n * data server. The server manages encrypted user data and enforces\n * permission-based access control. Initialization includes key exchange\n * and session establishment.\n *\n * @example\n * ```typescript\n * const params: InitPersonalServerParams = {\n * userAddress: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n * };\n *\n * const server = await vana.personal.initServer(params);\n * console.log('Connected to server:', server.baseUrl);\n * ```\n *\n * @category Personal Server\n */\nexport interface InitPersonalServerParams {\n /**\n * Identifies the user whose personal server to connect to.\n * Must be a valid Ethereum address in hex format.\n * @example '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n */\n userAddress: string;\n}\n\n/**\n * Represents comprehensive personal server identity and connection information.\n *\n * @remarks\n * Combines core server identity with connection metadata required for\n * establishing secure communication. Personal servers are user-controlled\n * nodes that store and serve encrypted personal data according to\n * user-defined permissions. This interface provides all necessary\n * information to connect to and interact with a personal server.\n *\n * @example\n * ```typescript\n * const identity: PersonalServerIdentity = {\n * kind: 'PersonalServer',\n * address: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * publicKey: '0x04...', // 65-byte uncompressed public key\n * baseUrl: 'https://ps.user.vana.com',\n * name: 'User Personal Server #1'\n * };\n *\n * // Use identity to establish encrypted connection\n * const encrypted = await crypto.encrypt(data, identity.publicKey);\n * const response = await fetch(`${identity.baseUrl}/api/data`, {\n * method: 'POST',\n * body: encrypted\n * });\n * ```\n *\n * @category Personal Server\n */\nexport interface PersonalServerIdentity {\n /**\n * Identifies the resource type for API disambiguation.\n * Always 'PersonalServer' for personal server instances.\n */\n kind: string;\n\n /**\n * Uniquely identifies the server on the blockchain.\n * Used for permission verification and identity proofs.\n * @example '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n */\n address: string;\n\n /**\n * Enables end-to-end encryption for data transmission.\n * Must be in uncompressed format (65 bytes with 0x04 prefix).\n * @example '0x04...' (130 hex characters)\n */\n publicKey: string;\n\n /**\n * Provides the HTTPS endpoint for server API requests.\n * Should not include trailing slashes or API paths.\n * @example 'https://ps.user.vana.com'\n */\n baseUrl: string;\n\n /**\n * Displays a user-friendly identifier for the server.\n * Used in UI components and logging for clarity.\n * @example 'Primary Data Server'\n */\n name: string;\n}\n\n/**\n * @remarks\n * Additional server response types are auto-generated from the OpenAPI\n * specification and available in the server-exports module. Import those\n * types directly when working with server API responses.\n *\n * @see {@link ../types/server-exports | Server Export Types}\n */\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/personal.ts"],"sourcesContent":["/**\n * Defines parameters for posting data requests to personal servers.\n *\n * @remarks\n * Used to initiate data access requests that require user permission.\n * The permission ID references a previously granted permission that\n * authorizes the requester to access specific user data.\n *\n * @example\n * ```typescript\n * const params: PostRequestParams = {\n * permissionId: 123\n * };\n *\n * const response = await vana.personal.postRequest(params);\n * console.log('Request posted:', response.requestId);\n * ```\n *\n * @category Personal Server\n */\nexport interface PostRequestParams {\n /**\n * References a granted permission authorizing data access.\n * Obtain via permission granting flow or query existing permissions.\n * @throws {PermissionNotFoundError} If permission ID is invalid.\n */\n permissionId: number;\n}\n\n/**\n * Defines parameters for creating server-side operations.\n *\n * @remarks\n * Initiates asynchronous operations on the personal server that\n * process user data according to granted permissions. Operations\n * run in the background and can be monitored via their operation ID.\n *\n * @example\n * ```typescript\n * const params: CreateOperationParams = {\n * permissionId: 456\n * };\n *\n * const operation = await vana.server.createOperation(params);\n * // Monitor operation status\n * const status = await vana.server.getOperationStatus(operation.id);\n * ```\n *\n * @category Personal Server\n */\nexport interface CreateOperationParams {\n /**\n * References the permission scope for this operation.\n * Determines what data and actions are allowed.\n * @throws {InsufficientPermissionsError} If permission scope is inadequate.\n */\n permissionId: number;\n}\n\n/**\n * Parameters for downloading an artifact from a server operation.\n *\n * @remarks\n * Artifacts are files generated during operations like Gemini agent analysis.\n * The download requires authentication using the application's signature.\n *\n * @category Personal Server\n */\nexport interface DownloadArtifactParams {\n /**\n * The operation ID that generated the artifact.\n */\n operationId: string;\n /**\n * The path to the artifact file to download.\n */\n artifactPath: string;\n}\n\n/**\n * Defines parameters for initializing personal server connections.\n *\n * @remarks\n * Establishes secure communication channels with a user's personal\n * data server. The server manages encrypted user data and enforces\n * permission-based access control. Initialization includes key exchange\n * and session establishment.\n *\n * @example\n * ```typescript\n * const params: InitPersonalServerParams = {\n * userAddress: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n * };\n *\n * const server = await vana.personal.initServer(params);\n * console.log('Connected to server:', server.baseUrl);\n * ```\n *\n * @category Personal Server\n */\nexport interface InitPersonalServerParams {\n /**\n * Identifies the user whose personal server to connect to.\n * Must be a valid Ethereum address in hex format.\n * @example '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n */\n userAddress: string;\n}\n\n/**\n * Represents comprehensive personal server identity and connection information.\n *\n * @remarks\n * Combines core server identity with connection metadata required for\n * establishing secure communication. Personal servers are user-controlled\n * nodes that store and serve encrypted personal data according to\n * user-defined permissions. This interface provides all necessary\n * information to connect to and interact with a personal server.\n *\n * @example\n * ```typescript\n * const identity: PersonalServerIdentity = {\n * kind: 'PersonalServer',\n * address: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * publicKey: '0x04...', // 65-byte uncompressed public key\n * baseUrl: 'https://ps.user.vana.com',\n * name: 'User Personal Server #1'\n * };\n *\n * // Use identity to establish encrypted connection\n * const encrypted = await crypto.encrypt(data, identity.publicKey);\n * const response = await fetch(`${identity.baseUrl}/api/data`, {\n * method: 'POST',\n * body: encrypted\n * });\n * ```\n *\n * @category Personal Server\n */\nexport interface PersonalServerIdentity {\n /**\n * Identifies the resource type for API disambiguation.\n * Always 'PersonalServer' for personal server instances.\n */\n kind: string;\n\n /**\n * Uniquely identifies the server on the blockchain.\n * Used for permission verification and identity proofs.\n * @example '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n */\n address: string;\n\n /**\n * Enables end-to-end encryption for data transmission.\n * Must be in uncompressed format (65 bytes with 0x04 prefix).\n * @example '0x04...' (130 hex characters)\n */\n publicKey: string;\n\n /**\n * Provides the HTTPS endpoint for server API requests.\n * Should not include trailing slashes or API paths.\n * @example 'https://ps.user.vana.com'\n */\n baseUrl: string;\n\n /**\n * Displays a user-friendly identifier for the server.\n * Used in UI components and logging for clarity.\n * @example 'Primary Data Server'\n */\n name: string;\n}\n\n/**\n * @remarks\n * Additional server response types are auto-generated from the OpenAPI\n * specification and available in the server-exports module. Import those\n * types directly when working with server API responses.\n *\n * @see {@link ../types/server-exports | Server Export Types}\n */\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/dist/types/personal.d.ts
CHANGED
|
@@ -55,6 +55,25 @@ export interface CreateOperationParams {
|
|
|
55
55
|
*/
|
|
56
56
|
permissionId: number;
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Parameters for downloading an artifact from a server operation.
|
|
60
|
+
*
|
|
61
|
+
* @remarks
|
|
62
|
+
* Artifacts are files generated during operations like Gemini agent analysis.
|
|
63
|
+
* The download requires authentication using the application's signature.
|
|
64
|
+
*
|
|
65
|
+
* @category Personal Server
|
|
66
|
+
*/
|
|
67
|
+
export interface DownloadArtifactParams {
|
|
68
|
+
/**
|
|
69
|
+
* The operation ID that generated the artifact.
|
|
70
|
+
*/
|
|
71
|
+
operationId: string;
|
|
72
|
+
/**
|
|
73
|
+
* The path to the artifact file to download.
|
|
74
|
+
*/
|
|
75
|
+
artifactPath: string;
|
|
76
|
+
}
|
|
58
77
|
/**
|
|
59
78
|
* Defines parameters for initializing personal server connections.
|
|
60
79
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/relayer.ts"],"sourcesContent":["/**\n * Defines types for gasless transaction relayers and server operations.\n *\n * @remarks\n * This module provides comprehensive type definitions for interacting with\n * relayer services that enable gasless transactions and auxiliary operations.\n * It includes both legacy v1 types and the simplified v2 unified interface.\n *\n * @category Types\n * @module types/relayer\n */\n\nimport type { Hash, Address } from \"viem\";\nimport type {\n GrantFile,\n PermissionGrantTypedData,\n GenericTypedData,\n} from \"./permissions\";\n\n/**\n * Represents the response from storing grant files via relayer.\n *\n * @remarks\n * Contains storage location, metadata, and error information for\n * grant file upload operations.\n *\n * @category Advanced\n */\nexport interface RelayerStorageResponse {\n /** The IPFS URL where the grant file is stored */\n grantUrl: string;\n /** Success status */\n success: boolean;\n /** Optional error message */\n error?: string;\n /** Storage metadata */\n metadata?: {\n /** IPFS hash */\n ipfsHash: string;\n /** File size in bytes */\n size: number;\n /** Upload timestamp */\n timestamp: number;\n };\n}\n\n/**\n * Represents the response from submitting transactions via relayer.\n *\n * @remarks\n * Contains transaction hash, status, and metadata for gasless\n * transaction submissions.\n *\n * @category Advanced\n */\nexport interface RelayerTransactionResponse {\n /** The transaction hash of the submitted transaction */\n transactionHash: Hash;\n /** Success status */\n success: boolean;\n /** Optional error message */\n error?: string;\n /** Transaction metadata */\n metadata?: {\n /** Gas used */\n gasUsed?: bigint;\n /** Gas price */\n gasPrice?: bigint;\n /** Block number */\n blockNumber?: bigint;\n /** Transaction status */\n status?: \"pending\" | \"confirmed\" | \"failed\";\n };\n}\n\n/**\n * Specifies parameters for storing grant files via relayer.\n *\n * @remarks\n * Includes the grant file and optional storage configuration\n * such as encryption and pinning duration.\n *\n * @category Advanced\n */\nexport interface RelayerStoreParams {\n /** The grant file to store */\n grantFile: GrantFile;\n /** Optional storage options */\n options?: {\n /** IPFS pin duration in seconds */\n pinDuration?: number;\n /** Whether to use encryption */\n encrypt?: boolean;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n };\n}\n\n/**\n * Specifies parameters for submitting gasless transactions.\n *\n * @remarks\n * Contains signed typed data and transaction configuration options\n * for relayer submission.\n *\n * @category Advanced\n */\nexport interface RelayerSubmitParams {\n /** The signed typed data */\n typedData: PermissionGrantTypedData;\n /** The signature */\n signature: string;\n /** Optional transaction options */\n options?: {\n /** Gas limit */\n gasLimit?: bigint;\n /** Priority level */\n priority?: \"low\" | \"medium\" | \"high\";\n /** Whether to wait for confirmation */\n waitForConfirmation?: boolean;\n };\n}\n\n/**\n * Represents the current status and capabilities of a relayer service.\n *\n * @remarks\n * Provides information about supported chains, rate limits, and\n * current operational status for monitoring and decision-making.\n *\n * @category Advanced\n */\nexport interface RelayerStatus {\n /** Whether the relayer is online */\n online: boolean;\n /** Service version */\n version: string;\n /** Supported chains */\n supportedChains: number[];\n /** Current chain status */\n chainStatus: Record<\n number,\n {\n /** Whether the chain is supported */\n supported: boolean;\n /** Current block number */\n currentBlock: bigint;\n /** Gas price estimation */\n gasPrice: bigint;\n /** Queue size */\n queueSize: number;\n }\n >;\n /** Rate limit information */\n rateLimits: {\n /** Requests per minute */\n requestsPerMinute: number;\n /** Storage requests per hour */\n storageRequestsPerHour: number;\n /** Transaction requests per hour */\n transactionRequestsPerHour: number;\n };\n}\n\n/**\n * Configures behavior for relayer requests.\n *\n * @remarks\n * Controls timeout, retry logic, headers, and priority for\n * relayer operation requests.\n *\n * @category Advanced\n */\nexport interface RelayerRequestOptions {\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Whether to retry on failure */\n retry?: boolean;\n /** Custom headers */\n headers?: Record<string, string>;\n /** Request priority */\n priority?: \"low\" | \"medium\" | \"high\";\n}\n\n/**\n * Represents an error response from the relayer service.\n *\n * @remarks\n * Provides structured error information including codes, messages,\n * and debugging details for error handling and recovery.\n *\n * @category Advanced\n */\nexport interface RelayerErrorResponse {\n /** Error code */\n code: string;\n /** Error message */\n message: string;\n /** Additional error details */\n details?: Record<string, unknown>;\n /** Request ID for debugging */\n requestId?: string;\n /** Timestamp of error */\n timestamp: number;\n}\n\n/**\n * Provides information about the relayer's processing queue.\n *\n * @remarks\n * Includes queue size, position, estimated processing time, and\n * performance statistics for queue monitoring.\n *\n * @category Advanced\n */\nexport interface RelayerQueueInfo {\n /** Current queue size */\n size: number;\n /** Estimated processing time in seconds */\n estimatedProcessingTime: number;\n /** Queue position for a specific request */\n position?: number;\n /** Processing statistics */\n stats: {\n /** Average processing time in seconds */\n averageProcessingTime: number;\n /** Requests processed in last hour */\n requestsProcessedHour: number;\n /** Success rate percentage */\n successRate: number;\n };\n}\n\n/**\n * Tracks the status of a transaction submitted via relayer.\n *\n * @remarks\n * Provides detailed tracking information including confirmation status,\n * gas usage, and historical status checks.\n *\n * @category Advanced\n */\nexport interface RelayerTransactionStatus {\n /** Transaction hash */\n transactionHash: Hash;\n /** Current status */\n status: \"pending\" | \"confirmed\" | \"failed\";\n /** Block number if confirmed */\n blockNumber?: bigint;\n /** Gas used */\n gasUsed?: bigint;\n /** Error message if failed */\n error?: string;\n /** Status checks performed */\n checks: Array<{\n /** Check timestamp */\n timestamp: number;\n /** Status at time of check */\n status: string;\n /** Block number at time of check */\n blockNumber: bigint;\n }>;\n}\n\n/**\n * Provides performance metrics for the relayer service.\n *\n * @remarks\n * Includes transaction statistics, success rates, processing times,\n * and uptime information for monitoring and optimization.\n *\n * @category Advanced\n */\nexport interface RelayerMetrics {\n /** Total transactions processed */\n totalTransactions: number;\n /** Successful transactions */\n successfulTransactions: number;\n /** Failed transactions */\n failedTransactions: number;\n /** Average processing time in seconds */\n averageProcessingTime: number;\n /** Current queue size */\n queueSize: number;\n /** Uptime percentage */\n uptime: number;\n /** Last 24 hour statistics */\n last24Hours: {\n /** Transactions processed */\n transactions: number;\n /** Success rate */\n successRate: number;\n /** Average response time */\n averageResponseTime: number;\n };\n}\n\n/**\n * Configures webhook notifications for relayer events.\n *\n * @remarks\n * Enables asynchronous notifications for transaction confirmations,\n * failures, and storage completions.\n *\n * @category Advanced\n */\nexport interface RelayerWebhookConfig {\n /** Webhook URL */\n url: string;\n /** Events to subscribe to */\n events: Array<\n \"transaction_confirmed\" | \"transaction_failed\" | \"storage_complete\"\n >;\n /** Webhook secret for signature verification */\n secret?: string;\n /** Whether webhook is active */\n active: boolean;\n}\n\n/**\n * Represents a webhook event payload from the relayer.\n *\n * @remarks\n * Contains event data, timestamp, and signature for verification\n * of webhook authenticity.\n *\n * @category Advanced\n */\nexport interface RelayerWebhookPayload {\n /** Event type */\n event: string;\n /** Event data */\n data: Record<string, unknown>;\n /** Timestamp */\n timestamp: number;\n /** Webhook ID */\n webhookId: string;\n /** Signature for verification */\n signature: string;\n}\n\n// ===== NEW SIMPLIFIED RELAYER TYPES (v2) =====\n\n/**\n * Handles both EIP-712 signed operations and direct server operations through a single interface.\n *\n * @remarks\n * This discriminated union provides type safety through TypeScript's narrowing.\n * The `type` field determines which operation variant is being used.\n * Signed operations require blockchain transactions, while direct operations\n * handle auxiliary tasks like file storage.\n *\n * @category Relayer\n * @see {@link https://docs.vana.org/docs/gasless-transactions | Gasless Transactions Guide}\n */\nexport type UnifiedRelayerRequest = SignedRelayerRequest | DirectRelayerRequest;\n\n/**\n * Represents an EIP-712 signed operation for gasless transaction submission.\n *\n * @remarks\n * Signed requests contain typed data and signatures that are verified\n * on-chain by smart contracts. The relayer pays gas fees on behalf of users.\n *\n * @category Relayer\n */\nexport interface SignedRelayerRequest {\n /** Discriminator field identifying this as a signed operation */\n type: \"signed\";\n /** Operation identifier for routing (e.g., 'submitAddPermission') */\n operation: SignedOperationType;\n /** EIP-712 typed data structure for the operation */\n typedData: GenericTypedData;\n /** User's signature of the typed data */\n signature: Hash;\n /** Optional address for additional signer verification */\n expectedUserAddress?: Address;\n}\n\n/**\n * Enumerates supported EIP-712 signed operation types.\n *\n * @remarks\n * Each operation type corresponds to a specific smart contract\n * function that accepts gasless transactions.\n *\n * @category Relayer\n */\nexport type SignedOperationType =\n | \"submitAddPermission\"\n | \"submitPermissionRevoke\"\n | \"submitTrustServer\"\n | \"submitAddAndTrustServer\"\n | \"submitUntrustServer\"\n | \"submitAddServerFilesAndPermissions\"\n | \"submitRegisterGrantee\";\n\n/**\n * Represents direct server operations that don't require blockchain signatures.\n *\n * @remarks\n * Direct requests handle auxiliary operations like file uploads and grant storage.\n * These operations may still result in blockchain transactions but don't require\n * user signatures for gasless submission.\n *\n * @category Relayer\n */\nexport type DirectRelayerRequest =\n | {\n type: \"direct\";\n operation: \"submitFileAddition\";\n params: {\n url: string;\n userAddress: Address;\n };\n }\n | {\n type: \"direct\";\n operation: \"submitFileAdditionWithPermissions\";\n params: {\n url: string;\n userAddress: Address;\n permissions: Array<{ account: Address; key: string }>;\n };\n }\n | {\n type: \"direct\";\n operation: \"submitFileAdditionComplete\";\n params: {\n url: string;\n userAddress: Address;\n permissions: Array<{ account: Address; key: string }>;\n schemaId: number;\n ownerAddress?: Address;\n };\n }\n | {\n type: \"direct\";\n operation: \"storeGrantFile\";\n params: GrantFile;\n };\n\n/**\n * Provides type-safe responses for all relayer operations.\n *\n * @remarks\n * The discriminated union ensures proper error handling and result typing.\n * Check the `type` field to determine success or failure before accessing results.\n *\n * @category Relayer\n */\nexport type UnifiedRelayerResponse =\n | {\n type: \"signed\";\n hash: Hash;\n }\n | {\n type: \"direct\";\n result: { fileId: number; transactionHash: Hash } | { url: string } | any;\n }\n | {\n type: \"error\";\n error: string;\n };\n\n/**\n * Simplified relayer configuration.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Option 1: Simple URL (SDK handles the transport)\n * const vana = Vana({\n * walletClient,\n * relayer: '/api/relay'\n * });\n *\n * // Option 2: Full control with callback\n * const vana = Vana({\n * walletClient,\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * });\n * ```\n */\nexport type RelayerConfig =\n | string\n | ((request: UnifiedRelayerRequest) => Promise<UnifiedRelayerResponse>);\n\n/**\n * Simplified relayer callbacks interface (v2).\n * A single callback handles all relayer operations.\n *\n * @category Configuration\n * @example\n * ```typescript\n * const relayerCallbacks: RelayerCallbacksV2 = {\n * submit: async (request) => {\n * // Send to your server endpoint\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * };\n * ```\n */\nexport interface RelayerCallbacksV2 {\n /**\n * Submits any relayer operation to the server.\n *\n * @remarks\n * This single callback handles all operations:\n * - EIP-712 signed operations (permissions, server trust, etc.)\n * - Direct operations (file additions, grant storage)\n *\n * On your server, pass the entire request object to the SDK's\n * `handleRelayerOperation` helper function.\n *\n * @param request - The unified request object.\n * Check `type` field to determine operation variant.\n * @returns Promise resolving to operation-specific response\n *\n * @example\n * ```typescript\n * async submit(request) {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n submit: (request: UnifiedRelayerRequest) => Promise<UnifiedRelayerResponse>;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/relayer.ts"],"sourcesContent":["/**\n * Defines types for gasless transaction relayers and server operations.\n *\n * @remarks\n * This module provides comprehensive type definitions for interacting with\n * relayer services that enable gasless transactions and auxiliary operations.\n * It includes both legacy v1 types and the simplified v2 unified interface.\n *\n * @category Types\n * @module types/relayer\n */\n\nimport type { Hash, Address, TransactionReceipt } from \"viem\";\nimport type {\n GrantFile,\n PermissionGrantTypedData,\n GenericTypedData,\n} from \"./permissions\";\nimport type { Contract, Fn } from \"../generated/event-types\";\n\n/**\n * Represents the response from storing grant files via relayer.\n *\n * @remarks\n * Contains storage location, metadata, and error information for\n * grant file upload operations.\n *\n * @category Advanced\n */\nexport interface RelayerStorageResponse {\n /** The IPFS URL where the grant file is stored */\n grantUrl: string;\n /** Success status */\n success: boolean;\n /** Optional error message */\n error?: string;\n /** Storage metadata */\n metadata?: {\n /** IPFS hash */\n ipfsHash: string;\n /** File size in bytes */\n size: number;\n /** Upload timestamp */\n timestamp: number;\n };\n}\n\n/**\n * Represents the response from submitting transactions via relayer.\n *\n * @remarks\n * Contains transaction hash, status, and metadata for gasless\n * transaction submissions.\n *\n * @category Advanced\n */\nexport interface RelayerTransactionResponse {\n /** The transaction hash of the submitted transaction */\n transactionHash: Hash;\n /** Success status */\n success: boolean;\n /** Optional error message */\n error?: string;\n /** Transaction metadata */\n metadata?: {\n /** Gas used */\n gasUsed?: bigint;\n /** Gas price */\n gasPrice?: bigint;\n /** Block number */\n blockNumber?: bigint;\n /** Transaction status */\n status?: \"pending\" | \"confirmed\" | \"failed\";\n };\n}\n\n/**\n * Specifies parameters for storing grant files via relayer.\n *\n * @remarks\n * Includes the grant file and optional storage configuration\n * such as encryption and pinning duration.\n *\n * @category Advanced\n */\nexport interface RelayerStoreParams {\n /** The grant file to store */\n grantFile: GrantFile;\n /** Optional storage options */\n options?: {\n /** IPFS pin duration in seconds */\n pinDuration?: number;\n /** Whether to use encryption */\n encrypt?: boolean;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n };\n}\n\n/**\n * Specifies parameters for submitting gasless transactions.\n *\n * @remarks\n * Contains signed typed data and transaction configuration options\n * for relayer submission.\n *\n * @category Advanced\n */\nexport interface RelayerSubmitParams {\n /** The signed typed data */\n typedData: PermissionGrantTypedData;\n /** The signature */\n signature: string;\n /** Optional transaction options */\n options?: {\n /** Gas limit */\n gasLimit?: bigint;\n /** Priority level */\n priority?: \"low\" | \"medium\" | \"high\";\n /** Whether to wait for confirmation */\n waitForConfirmation?: boolean;\n };\n}\n\n/**\n * Represents the current status and capabilities of a relayer service.\n *\n * @remarks\n * Provides information about supported chains, rate limits, and\n * current operational status for monitoring and decision-making.\n *\n * @category Advanced\n */\nexport interface RelayerStatus {\n /** Whether the relayer is online */\n online: boolean;\n /** Service version */\n version: string;\n /** Supported chains */\n supportedChains: number[];\n /** Current chain status */\n chainStatus: Record<\n number,\n {\n /** Whether the chain is supported */\n supported: boolean;\n /** Current block number */\n currentBlock: bigint;\n /** Gas price estimation */\n gasPrice: bigint;\n /** Queue size */\n queueSize: number;\n }\n >;\n /** Rate limit information */\n rateLimits: {\n /** Requests per minute */\n requestsPerMinute: number;\n /** Storage requests per hour */\n storageRequestsPerHour: number;\n /** Transaction requests per hour */\n transactionRequestsPerHour: number;\n };\n}\n\n/**\n * Configures behavior for relayer requests.\n *\n * @remarks\n * Controls timeout, retry logic, headers, and priority for\n * relayer operation requests.\n *\n * @category Advanced\n */\nexport interface RelayerRequestOptions {\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Whether to retry on failure */\n retry?: boolean;\n /** Custom headers */\n headers?: Record<string, string>;\n /** Request priority */\n priority?: \"low\" | \"medium\" | \"high\";\n}\n\n/**\n * Represents an error response from the relayer service.\n *\n * @remarks\n * Provides structured error information including codes, messages,\n * and debugging details for error handling and recovery.\n *\n * @category Advanced\n */\nexport interface RelayerErrorResponse {\n /** Error code */\n code: string;\n /** Error message */\n message: string;\n /** Additional error details */\n details?: Record<string, unknown>;\n /** Request ID for debugging */\n requestId?: string;\n /** Timestamp of error */\n timestamp: number;\n}\n\n/**\n * Provides information about the relayer's processing queue.\n *\n * @remarks\n * Includes queue size, position, estimated processing time, and\n * performance statistics for queue monitoring.\n *\n * @category Advanced\n */\nexport interface RelayerQueueInfo {\n /** Current queue size */\n size: number;\n /** Estimated processing time in seconds */\n estimatedProcessingTime: number;\n /** Queue position for a specific request */\n position?: number;\n /** Processing statistics */\n stats: {\n /** Average processing time in seconds */\n averageProcessingTime: number;\n /** Requests processed in last hour */\n requestsProcessedHour: number;\n /** Success rate percentage */\n successRate: number;\n };\n}\n\n/**\n * Tracks the status of a transaction submitted via relayer.\n *\n * @remarks\n * Provides detailed tracking information including confirmation status,\n * gas usage, and historical status checks.\n *\n * @category Advanced\n */\nexport interface RelayerTransactionStatus {\n /** Transaction hash */\n transactionHash: Hash;\n /** Current status */\n status: \"pending\" | \"confirmed\" | \"failed\";\n /** Block number if confirmed */\n blockNumber?: bigint;\n /** Gas used */\n gasUsed?: bigint;\n /** Error message if failed */\n error?: string;\n /** Status checks performed */\n checks: Array<{\n /** Check timestamp */\n timestamp: number;\n /** Status at time of check */\n status: string;\n /** Block number at time of check */\n blockNumber: bigint;\n }>;\n}\n\n/**\n * Provides performance metrics for the relayer service.\n *\n * @remarks\n * Includes transaction statistics, success rates, processing times,\n * and uptime information for monitoring and optimization.\n *\n * @category Advanced\n */\nexport interface RelayerMetrics {\n /** Total transactions processed */\n totalTransactions: number;\n /** Successful transactions */\n successfulTransactions: number;\n /** Failed transactions */\n failedTransactions: number;\n /** Average processing time in seconds */\n averageProcessingTime: number;\n /** Current queue size */\n queueSize: number;\n /** Uptime percentage */\n uptime: number;\n /** Last 24 hour statistics */\n last24Hours: {\n /** Transactions processed */\n transactions: number;\n /** Success rate */\n successRate: number;\n /** Average response time */\n averageResponseTime: number;\n };\n}\n\n/**\n * Configures webhook notifications for relayer events.\n *\n * @remarks\n * Enables asynchronous notifications for transaction confirmations,\n * failures, and storage completions.\n *\n * @category Advanced\n */\nexport interface RelayerWebhookConfig {\n /** Webhook URL */\n url: string;\n /** Events to subscribe to */\n events: Array<\n \"transaction_confirmed\" | \"transaction_failed\" | \"storage_complete\"\n >;\n /** Webhook secret for signature verification */\n secret?: string;\n /** Whether webhook is active */\n active: boolean;\n}\n\n/**\n * Represents a webhook event payload from the relayer.\n *\n * @remarks\n * Contains event data, timestamp, and signature for verification\n * of webhook authenticity.\n *\n * @category Advanced\n */\nexport interface RelayerWebhookPayload {\n /** Event type */\n event: string;\n /** Event data */\n data: Record<string, unknown>;\n /** Timestamp */\n timestamp: number;\n /** Webhook ID */\n webhookId: string;\n /** Signature for verification */\n signature: string;\n}\n\n// ===== NEW SIMPLIFIED RELAYER TYPES (v2) =====\n\n/**\n * Handles both EIP-712 signed operations and direct server operations through a single interface.\n *\n * @remarks\n * This discriminated union provides type safety through TypeScript's narrowing.\n * The `type` field determines which operation variant is being used.\n * Signed operations require blockchain transactions, while direct operations\n * handle auxiliary tasks like file storage.\n *\n * @category Relayer\n * @see {@link https://docs.vana.org/docs/gasless-transactions | Gasless Transactions Guide}\n */\nexport type UnifiedRelayerRequest =\n | SignedRelayerRequest\n | DirectRelayerRequest\n | {\n type: \"status_check\";\n operationId: string;\n };\n\n/**\n * Represents an EIP-712 signed operation for gasless transaction submission.\n *\n * @remarks\n * Signed requests contain typed data and signatures that are verified\n * on-chain by smart contracts. The relayer pays gas fees on behalf of users.\n *\n * @category Relayer\n */\nexport interface SignedRelayerRequest {\n /** Discriminator field identifying this as a signed operation */\n type: \"signed\";\n /** Operation identifier for routing (e.g., 'submitAddPermission') */\n operation: SignedOperationType;\n /** EIP-712 typed data structure for the operation */\n typedData: GenericTypedData;\n /** User's signature of the typed data */\n signature: Hash;\n /** Optional address for additional signer verification */\n expectedUserAddress?: Address;\n}\n\n/**\n * Enumerates supported EIP-712 signed operation types.\n *\n * @remarks\n * Each operation type corresponds to a specific smart contract\n * function that accepts gasless transactions.\n *\n * @category Relayer\n */\nexport type SignedOperationType =\n | \"submitAddPermission\"\n | \"submitPermissionRevoke\"\n | \"submitTrustServer\"\n | \"submitAddAndTrustServer\"\n | \"submitUntrustServer\"\n | \"submitAddServerFilesAndPermissions\";\n// | \"submitRegisterGrantee\"; // TODO: Add when contract supports registerGranteeWithSignature\n\n/**\n * Represents direct server operations that don't require blockchain signatures.\n *\n * @remarks\n * Direct requests handle auxiliary operations like file uploads and grant storage.\n * These operations may still result in blockchain transactions but don't require\n * user signatures for gasless submission.\n *\n * @category Relayer\n */\nexport type DirectRelayerRequest =\n | {\n type: \"direct\";\n operation: \"submitFileAddition\";\n params: {\n url: string;\n userAddress: Address;\n };\n }\n | {\n type: \"direct\";\n operation: \"submitFileAdditionWithPermissions\";\n params: {\n url: string;\n userAddress: Address;\n permissions: Array<{ account: Address; key: string }>;\n };\n }\n | {\n type: \"direct\";\n operation: \"submitFileAdditionComplete\";\n params: {\n url: string;\n userAddress: Address;\n permissions: Array<{ account: Address; key: string }>;\n schemaId: number;\n ownerAddress?: Address;\n };\n }\n | {\n type: \"direct\";\n operation: \"storeGrantFile\";\n params: GrantFile;\n }\n | {\n type: \"direct\";\n operation: \"submitRegisterGrantee\";\n params: {\n owner: Address;\n granteeAddress: Address;\n publicKey: string;\n };\n };\n\n/**\n * Context for transaction operations to enable proper event parsing.\n *\n * @remarks\n * This context is preserved in relayer responses to enable client-side\n * event parsing without requiring manual reconstruction of transaction details.\n *\n * @category Relayer\n */\nexport interface TransactionContext {\n /** The contract that was called */\n contract: Contract;\n /** The function that was called on the contract */\n fn: Fn<Contract>;\n /** The address that initiated the transaction */\n from: Address;\n}\n\n/**\n * Provides type-safe responses for all relayer operations.\n *\n * @remarks\n * The discriminated union ensures proper error handling and result typing.\n * Check the `type` field to determine success or failure before accessing results.\n * The new async pattern returns pending operations with operationIds for polling.\n *\n * Transaction responses include optional context to enable client-side event parsing\n * through the enhanced response pattern.\n *\n * @category Relayer\n */\nexport type UnifiedRelayerResponse =\n | {\n type: \"pending\";\n operationId: string;\n }\n | {\n type: \"submitted\";\n hash: Hash;\n /** Optional context for client-side event parsing and enhanced responses */\n context?: TransactionContext;\n }\n | {\n type: \"confirmed\";\n hash: Hash;\n // Receipt is optional; a performance hint for the client SDK's polling logic.\n receipt?: TransactionReceipt;\n }\n | {\n type: \"signed\";\n hash: Hash;\n /** Optional context for client-side event parsing and enhanced responses */\n context?: TransactionContext;\n }\n | {\n /** Non-transactional operations that complete immediately (e.g., IPFS uploads, file info) */\n type: \"direct\";\n /** The result data from the operation, structure depends on the specific operation */\n result: unknown;\n }\n | {\n type: \"error\";\n error: string;\n };\n\n/**\n * Simplified relayer configuration.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Option 1: Simple URL (SDK handles the transport)\n * const vana = Vana({\n * walletClient,\n * relayer: '/api/relay'\n * });\n *\n * // Option 2: Full control with callback\n * const vana = Vana({\n * walletClient,\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * });\n * ```\n */\nexport type RelayerConfig =\n | string\n | ((request: UnifiedRelayerRequest) => Promise<UnifiedRelayerResponse>);\n\n/**\n * Simplified relayer callbacks interface (v2).\n * A single callback handles all relayer operations.\n *\n * @category Configuration\n * @example\n * ```typescript\n * const relayerCallbacks: RelayerCallbacksV2 = {\n * submit: async (request) => {\n * // Send to your server endpoint\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * };\n * ```\n */\nexport interface RelayerCallbacksV2 {\n /**\n * Submits any relayer operation to the server.\n *\n * @remarks\n * This single callback handles all operations:\n * - EIP-712 signed operations (permissions, server trust, etc.)\n * - Direct operations (file additions, grant storage)\n *\n * On your server, pass the entire request object to the SDK's\n * `handleRelayerOperation` helper function.\n *\n * @param request - The unified request object.\n * Check `type` field to determine operation variant.\n * @returns Promise resolving to operation-specific response\n *\n * @example\n * ```typescript\n * async submit(request) {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n submit: (request: UnifiedRelayerRequest) => Promise<UnifiedRelayerResponse>;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/dist/types/relayer.d.ts
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
* @category Types
|
|
10
10
|
* @module types/relayer
|
|
11
11
|
*/
|
|
12
|
-
import type { Hash, Address } from "viem";
|
|
12
|
+
import type { Hash, Address, TransactionReceipt } from "viem";
|
|
13
13
|
import type { GrantFile, PermissionGrantTypedData, GenericTypedData } from "./permissions";
|
|
14
|
+
import type { Contract, Fn } from "../generated/event-types";
|
|
14
15
|
/**
|
|
15
16
|
* Represents the response from storing grant files via relayer.
|
|
16
17
|
*
|
|
@@ -328,7 +329,10 @@ export interface RelayerWebhookPayload {
|
|
|
328
329
|
* @category Relayer
|
|
329
330
|
* @see {@link https://docs.vana.org/docs/gasless-transactions | Gasless Transactions Guide}
|
|
330
331
|
*/
|
|
331
|
-
export type UnifiedRelayerRequest = SignedRelayerRequest | DirectRelayerRequest
|
|
332
|
+
export type UnifiedRelayerRequest = SignedRelayerRequest | DirectRelayerRequest | {
|
|
333
|
+
type: "status_check";
|
|
334
|
+
operationId: string;
|
|
335
|
+
};
|
|
332
336
|
/**
|
|
333
337
|
* Represents an EIP-712 signed operation for gasless transaction submission.
|
|
334
338
|
*
|
|
@@ -359,7 +363,7 @@ export interface SignedRelayerRequest {
|
|
|
359
363
|
*
|
|
360
364
|
* @category Relayer
|
|
361
365
|
*/
|
|
362
|
-
export type SignedOperationType = "submitAddPermission" | "submitPermissionRevoke" | "submitTrustServer" | "submitAddAndTrustServer" | "submitUntrustServer" | "submitAddServerFilesAndPermissions"
|
|
366
|
+
export type SignedOperationType = "submitAddPermission" | "submitPermissionRevoke" | "submitTrustServer" | "submitAddAndTrustServer" | "submitUntrustServer" | "submitAddServerFilesAndPermissions";
|
|
363
367
|
/**
|
|
364
368
|
* Represents direct server operations that don't require blockchain signatures.
|
|
365
369
|
*
|
|
@@ -405,27 +409,67 @@ export type DirectRelayerRequest = {
|
|
|
405
409
|
type: "direct";
|
|
406
410
|
operation: "storeGrantFile";
|
|
407
411
|
params: GrantFile;
|
|
412
|
+
} | {
|
|
413
|
+
type: "direct";
|
|
414
|
+
operation: "submitRegisterGrantee";
|
|
415
|
+
params: {
|
|
416
|
+
owner: Address;
|
|
417
|
+
granteeAddress: Address;
|
|
418
|
+
publicKey: string;
|
|
419
|
+
};
|
|
408
420
|
};
|
|
421
|
+
/**
|
|
422
|
+
* Context for transaction operations to enable proper event parsing.
|
|
423
|
+
*
|
|
424
|
+
* @remarks
|
|
425
|
+
* This context is preserved in relayer responses to enable client-side
|
|
426
|
+
* event parsing without requiring manual reconstruction of transaction details.
|
|
427
|
+
*
|
|
428
|
+
* @category Relayer
|
|
429
|
+
*/
|
|
430
|
+
export interface TransactionContext {
|
|
431
|
+
/** The contract that was called */
|
|
432
|
+
contract: Contract;
|
|
433
|
+
/** The function that was called on the contract */
|
|
434
|
+
fn: Fn<Contract>;
|
|
435
|
+
/** The address that initiated the transaction */
|
|
436
|
+
from: Address;
|
|
437
|
+
}
|
|
409
438
|
/**
|
|
410
439
|
* Provides type-safe responses for all relayer operations.
|
|
411
440
|
*
|
|
412
441
|
* @remarks
|
|
413
442
|
* The discriminated union ensures proper error handling and result typing.
|
|
414
443
|
* Check the `type` field to determine success or failure before accessing results.
|
|
444
|
+
* The new async pattern returns pending operations with operationIds for polling.
|
|
445
|
+
*
|
|
446
|
+
* Transaction responses include optional context to enable client-side event parsing
|
|
447
|
+
* through the enhanced response pattern.
|
|
415
448
|
*
|
|
416
449
|
* @category Relayer
|
|
417
450
|
*/
|
|
418
451
|
export type UnifiedRelayerResponse = {
|
|
452
|
+
type: "pending";
|
|
453
|
+
operationId: string;
|
|
454
|
+
} | {
|
|
455
|
+
type: "submitted";
|
|
456
|
+
hash: Hash;
|
|
457
|
+
/** Optional context for client-side event parsing and enhanced responses */
|
|
458
|
+
context?: TransactionContext;
|
|
459
|
+
} | {
|
|
460
|
+
type: "confirmed";
|
|
461
|
+
hash: Hash;
|
|
462
|
+
receipt?: TransactionReceipt;
|
|
463
|
+
} | {
|
|
419
464
|
type: "signed";
|
|
420
465
|
hash: Hash;
|
|
466
|
+
/** Optional context for client-side event parsing and enhanced responses */
|
|
467
|
+
context?: TransactionContext;
|
|
421
468
|
} | {
|
|
469
|
+
/** Non-transactional operations that complete immediately (e.g., IPFS uploads, file info) */
|
|
422
470
|
type: "direct";
|
|
423
|
-
result
|
|
424
|
-
|
|
425
|
-
transactionHash: Hash;
|
|
426
|
-
} | {
|
|
427
|
-
url: string;
|
|
428
|
-
} | any;
|
|
471
|
+
/** The result data from the operation, structure depends on the specific operation */
|
|
472
|
+
result: unknown;
|
|
429
473
|
} | {
|
|
430
474
|
type: "error";
|
|
431
475
|
error: string;
|
package/dist/types/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/utils.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Makes all properties in T optional except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are optional, but specific properties remain required.\n * Commonly used for update operations where only certain fields must be provided.\n *\n * @example\n * ```typescript\n * interface User {\n * id: string;\n * name: string;\n * email: string;\n * age: number;\n * }\n *\n * // Only 'id' is required, all other properties are optional\n * type UserUpdate = PartialExcept<User, 'id'>;\n *\n * const update: UserUpdate = {\n * id: '123', // Required\n * name: 'John' // Optional\n * // email and age are also optional\n * };\n * ```\n * @category Reference\n */\nexport type PartialExcept<T, K extends keyof T> = Partial<T> & Pick<T, K>;\n\n/**\n * Makes all properties in T required except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are required, but specific properties remain optional.\n * Commonly used for creation operations where most fields are mandatory.\n *\n * @example\n * ```typescript\n * interface Config {\n * apiUrl: string;\n * timeout?: number;\n * retries?: number;\n * debug?: boolean;\n * }\n *\n * // All properties required except 'debug'\n * type StrictConfig = RequiredExcept<Config, 'debug'>;\n *\n * const config: StrictConfig = {\n * apiUrl: 'https://api.vana.com', // Required\n * timeout: 5000, // Required (was optional, now required)\n * retries: 3, // Required (was optional, now required)\n * // debug remains optional\n * };\n * ```\n * @category Reference\n */\nexport type RequiredExcept<T, K extends keyof T> = Required<T> &\n Partial<Pick<T, K>>;\n\n/**\n * Extracts the return type of a promise\n *\n * @remarks\n * This utility type unwraps the type contained within a Promise.\n * If the type is not a Promise, it returns the type unchanged.\n * Note: TypeScript 4.5+ includes a built-in Awaited type with similar functionality.\n *\n * @example\n * ```typescript\n * type AsyncString = Promise<string>;\n * type SyncString = string;\n *\n * // Extracts 'string' from Promise<string>\n * type Result1 = Awaited<AsyncString>; // string\n *\n * // Returns 'string' unchanged since it's not a Promise\n * type Result2 = Awaited<SyncString>; // string\n *\n * // Practical usage with async functions\n * async function fetchUser(): Promise<{ id: string; name: string }> {\n * // ...\n * }\n *\n * type User = Awaited<ReturnType<typeof fetchUser>>; // { id: string; name: string }\n * ```\n * @category Reference\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Creates a type that accepts either T or a Promise<T>\n *\n * @remarks\n * This utility type is useful for functions that can work with both\n * synchronous and asynchronous values. It allows flexible APIs that\n * can accept immediate values or promises that resolve to those values.\n *\n * @example\n * ```typescript\n * // Function that accepts either a value or a promise of that value\n * async function processData(data: MaybePromise<string>): Promise<string> {\n * // await works on both promises and regular values\n * const resolved = await data;\n * return resolved.toUpperCase();\n * }\n *\n * // Both calls are valid:\n * processData('hello'); // Synchronous value\n * processData(Promise.resolve('world')); // Asynchronous value\n *\n * // Common use case in SDK callbacks\n * interface StorageProvider {\n * // Provider can implement sync or async file reading\n * read(path: string): MaybePromise<Buffer>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Creates a type that accepts either T or an array of T\n *\n * @remarks\n * This utility type is useful for functions that can accept either a single\n * value or an array of values, providing a more flexible API. The implementation\n * can normalize the input to always work with arrays internally.\n *\n * @example\n * ```typescript\n * // Function that accepts either a single ID or multiple IDs\n * function deleteItems(ids: MaybeArray<string>): void {\n * // Normalize to array\n * const idArray = Array.isArray(ids) ? ids : [ids];\n * idArray.forEach(id => console.log(`Deleting ${id}`));\n * }\n *\n * // Both calls are valid:\n * deleteItems('item-1'); // Single item\n * deleteItems(['item-1', 'item-2', 'item-3']); // Multiple items\n *\n * // Common use case in permissions\n * interface GrantPermissionsParams {\n * permissions: MaybeArray<Permission>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybeArray<T> = T | T[];\n\n/**\n * Pagination parameters for controlling result set size and navigation.\n *\n * Used across SDK methods that return lists of items to control how many items\n * are returned and to navigate through large result sets efficiently.\n *\n * @category Reference\n * @example\n * ```typescript\n * const pagination: PaginationParams = {\n * limit: 20, // Return 20 items\n * offset: 40, // Skip first 40 items (page 3)\n * cursor: 'eyJpZCI6MTIzfQ==' // Or use cursor-based pagination\n * };\n *\n * const files = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination\n * });\n * ```\n */\nexport interface PaginationParams {\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Cursor for cursor-based pagination */\n cursor?: string;\n}\n\n/**\n * Pagination result containing items and metadata for navigating large datasets.\n *\n * @remarks\n * This interface standardizes paginated responses across the SDK, providing\n * consistent metadata for implementing pagination UI components and handling\n * multi-page data fetching. Supports both offset-based and cursor-based pagination.\n *\n * @example\n * ```typescript\n * // Fetching paginated user files\n * async function getAllUserFiles(userAddress: string): Promise<File[]> {\n * const allFiles: File[] = [];\n * let cursor: string | undefined;\n *\n * do {\n * const result: PaginationResult<File> = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination: { limit: 50, cursor }\n * });\n *\n * allFiles.push(...result.items);\n * cursor = result.nextCursor;\n *\n * console.log(`Fetched ${result.count} of ${result.total} files`);\n * } while (result.hasMore);\n *\n * return allFiles;\n * }\n * ```\n * @category Reference\n */\nexport interface PaginationResult<T> {\n /** Array of items */\n items: T[];\n /** Total number of items available */\n total: number;\n /** Number of items returned */\n count: number;\n /** Whether there are more items available */\n hasMore: boolean;\n /** Cursor for next page */\n nextCursor?: string;\n}\n\n/**\n * Block range parameters for filtering blockchain events and transactions.\n *\n * @remarks\n * Used to specify a range of blocks when querying blockchain data.\n * Both parameters are optional - omitting fromBlock starts from genesis,\n * omitting toBlock goes to the latest block. Be cautious with large ranges\n * as they may result in heavy RPC loads or timeouts.\n *\n * @example\n * ```typescript\n * // Get events from the last 1000 blocks\n * const currentBlock = await vana.protocol.getBlockNumber();\n * const events = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: currentBlock - 1000n,\n * toBlock: currentBlock\n * }\n * });\n *\n * // Get all historical events (use with caution)\n * const allEvents = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: 0n\n * // toBlock omitted = up to latest\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface BlockRange {\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n}\n\n/**\n * Transaction options for customizing blockchain transaction parameters.\n *\n * @remarks\n * Provides fine-grained control over transaction execution. Supports both\n * legacy (gasPrice) and EIP-1559 (maxFeePerGas) transaction types. When\n * not specified, the SDK will use appropriate defaults based on network\n * conditions. Use these options to optimize for speed or cost.\n *\n * @example\n * ```typescript\n * // High priority transaction with EIP-1559 pricing\n * await vana.permissions.grant(params, {\n * maxFeePerGas: 100n * 10n ** 9n, // 100 gwei\n * maxPriorityFeePerGas: 2n * 10n ** 9n, // 2 gwei tip\n * timeout: 180000, // 3 minutes\n * });\n *\n * // Legacy transaction with specific gas limit\n * await vana.data.registerFile(params, {\n * gasLimit: 500000n,\n * gasPrice: 50n * 10n ** 9n, // 50 gwei\n * timeout: 600000, // 10 minutes\n * });\n *\n * // Send ETH with the transaction\n * await vana.protocol.execute(params, {\n * value: 10n ** 18n, // 1 ETH\n * gasLimit: 21000n\n * });\n * ```\n * @category Reference\n */\nexport interface TransactionOptions {\n /** Gas limit */\n gasLimit?: bigint;\n /** Gas price */\n gasPrice?: bigint;\n /** Max fee per gas (EIP-1559) */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas (EIP-1559) */\n maxPriorityFeePerGas?: bigint;\n /** Nonce */\n nonce?: number;\n /** Value to send with transaction */\n value?: bigint;\n /** Transaction timeout in milliseconds for receipt waiting (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Transaction receipt with additional metadata for tracking transaction results.\n *\n * @remarks\n * Provides comprehensive information about executed transactions including\n * gas usage, success status, and emitted events. Use the logs array to\n * decode events emitted by smart contracts during transaction execution.\n * The receipt is available after a transaction is mined and included in a block.\n *\n * @example\n * ```typescript\n * // Execute transaction and wait for receipt\n * const receipt = await vana.permissions.grant({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Check transaction success\n * if (receipt.status === 'success') {\n * console.log(`Gas used: ${receipt.gasUsed}`);\n * console.log(`Block: ${receipt.blockNumber}`);\n *\n * // Decode events from logs\n * receipt.logs.forEach(log => {\n * if (log.topics[0] === PERMISSION_GRANTED_TOPIC) {\n * console.log('Permission granted event detected');\n * }\n * });\n * } else {\n * console.error('Transaction reverted');\n * }\n * ```\n * @category Reference\n */\nexport interface TransactionReceipt {\n /** Transaction hash */\n transactionHash: Hash;\n /** Block number */\n blockNumber: bigint;\n /** Block hash */\n blockHash: Hash;\n /** Gas used */\n gasUsed: bigint;\n /** Transaction status */\n status: \"success\" | \"reverted\";\n /** Contract address if contract deployment */\n contractAddress?: Address;\n /** Event logs */\n logs: Array<{\n address: Address;\n topics: Hash[];\n data: string;\n }>;\n}\n\n/**\n * Response wrapper for API results providing consistent error handling.\n *\n * @remarks\n * Standardizes API responses across the SDK, making it easy to handle\n * both successful and failed requests. The generic type parameter T\n * represents the expected data type for successful responses. Check\n * the success flag before accessing data to ensure type safety.\n *\n * @example\n * ```typescript\n * // Handling API responses\n * async function fetchUserData(userId: string): Promise<User | null> {\n * const response: ApiResponse<User> = await api.getUser(userId);\n *\n * if (response.success) {\n * console.log('User fetched:', response.data.name);\n * // Access metadata if available\n * if (response.metadata?.cached) {\n * console.log('Data was cached');\n * }\n * return response.data;\n * } else {\n * console.error('Failed to fetch user:', response.error);\n * return null;\n * }\n * }\n *\n * // Type-safe error handling\n * interface UserData {\n * id: string;\n * name: string;\n * }\n *\n * const result: ApiResponse<UserData> = await api.call('/users/123');\n * if (result.success) {\n * // TypeScript knows result.data is UserData here\n * console.log(result.data.name);\n * }\n * ```\n * @category Reference\n */\nexport interface ApiResponse<T> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if not successful */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Retry configuration for handling transient failures with exponential backoff.\n *\n * @remarks\n * Configures automatic retry behavior for operations that may fail due to\n * temporary issues like network problems or rate limits. Supports exponential\n * backoff to avoid overwhelming services. The shouldRetry function allows\n * custom logic to determine which errors warrant a retry attempt.\n *\n * @example\n * ```typescript\n * // Simple retry configuration\n * const basicRetry: RetryConfig = {\n * attempts: 3,\n * delay: 1000 // 1 second between retries\n * };\n *\n * // Exponential backoff configuration\n * const exponentialRetry: RetryConfig = {\n * attempts: 5,\n * delay: 1000,\n * backoffMultiplier: 2, // Double delay each time\n * maxDelay: 30000, // Cap at 30 seconds\n * shouldRetry: (error) => {\n * // Only retry network and timeout errors\n * return error.name === 'NetworkError' ||\n * error.message.includes('timeout');\n * }\n * };\n *\n * // Usage with SDK\n * const vana = new Vana({\n * retryConfig: exponentialRetry\n * });\n * ```\n * @category Reference\n */\nexport interface RetryConfig {\n /** Number of retry attempts */\n attempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /** Backoff multiplier */\n backoffMultiplier?: number;\n /** Maximum delay in milliseconds */\n maxDelay?: number;\n /** Function to determine if error should be retried */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Cache configuration for optimizing repeated data fetches.\n *\n * @remarks\n * Configures in-memory caching behavior to reduce redundant API calls and\n * improve performance. The cache automatically evicts expired entries based\n * on TTL and removes least-recently-used items when maxSize is reached.\n * Use appropriate TTL values based on your data freshness requirements.\n *\n * @example\n * ```typescript\n * // Short-lived cache for frequently changing data\n * const userCache: CacheConfig = {\n * ttl: 60000, // 1 minute\n * maxSize: 100, // Store up to 100 users\n * prefix: 'user:' // Cache keys like 'user:123'\n * };\n *\n * // Long-lived cache for stable data\n * const schemaCache: CacheConfig = {\n * ttl: 3600000, // 1 hour\n * maxSize: 1000, // Store up to 1000 schemas\n * prefix: 'schema:'\n * };\n *\n * // Disable caching by setting TTL to 0\n * const noCache: CacheConfig = {\n * ttl: 0 // No caching\n * };\n * ```\n * @category Reference\n */\nexport interface CacheConfig {\n /** Cache TTL in milliseconds */\n ttl: number;\n /** Maximum cache size */\n maxSize?: number;\n /** Cache key prefix */\n prefix?: string;\n}\n\n/**\n * Validation result for data integrity checks and schema validation.\n *\n * @remarks\n * Provides detailed feedback about validation outcomes, distinguishing between\n * errors (which prevent processing) and warnings (which indicate potential issues).\n * Used throughout the SDK for validating permissions, file formats, schemas,\n * and API parameters before operations.\n *\n * @example\n * ```typescript\n * // Validating user input\n * function validateFileUpload(file: File): ValidationResult {\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * // Check file size\n * if (file.size > 100 * 1024 * 1024) {\n * errors.push('File size exceeds 100MB limit');\n * } else if (file.size > 50 * 1024 * 1024) {\n * warnings.push('Large file may take time to upload');\n * }\n *\n * // Check file type\n * if (!file.type.startsWith('image/')) {\n * errors.push('Only image files are allowed');\n * }\n *\n * return {\n * valid: errors.length === 0,\n * errors,\n * warnings\n * };\n * }\n *\n * // Using validation result\n * const result = validateFileUpload(file);\n * if (!result.valid) {\n * console.error('Validation failed:', result.errors.join(', '));\n * } else {\n * if (result.warnings.length > 0) {\n * console.warn('Warnings:', result.warnings.join(', '));\n * }\n * // Proceed with upload\n * }\n * ```\n * @category Reference\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation errors */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n}\n\n/**\n * Status information for health checks and service monitoring.\n *\n * @remarks\n * Used to report the health status of various SDK components including\n * storage providers, RPC connections, and personal servers. The details\n * field can contain provider-specific information for debugging.\n * Timestamps use Unix epoch milliseconds.\n *\n * @example\n * ```typescript\n * // Checking storage provider health\n * const status: StatusInfo = await storage.getStatus();\n *\n * if (!status.healthy) {\n * console.error(`Storage unhealthy: ${status.message}`);\n * // Check how long the issue has persisted\n * const downtime = Date.now() - status.lastCheck;\n * if (downtime > 300000) { // 5 minutes\n * // Switch to backup provider\n * }\n * }\n *\n * // Detailed status with custom fields\n * const serverStatus: StatusInfo = {\n * healthy: true,\n * message: 'All systems operational',\n * lastCheck: Date.now(),\n * details: {\n * uptime: 3600000, // 1 hour\n * requestsServed: 1234,\n * avgResponseTime: 145, // ms\n * activeConnections: 23\n * }\n * };\n * ```\n * @category Reference\n */\nexport interface StatusInfo {\n /** Whether the service is healthy */\n healthy: boolean;\n /** Status message */\n message?: string;\n /** Last check timestamp */\n lastCheck: number;\n /** Additional status details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Rate limit information for API throttling and quota management.\n *\n * @remarks\n * Provides visibility into rate limiting status to help applications\n * implement appropriate backoff strategies. Rate limits protect services\n * from overload and ensure fair resource usage. Use this information\n * to pace requests and avoid hitting limits.\n *\n * @example\n * ```typescript\n * // Check rate limit before making requests\n * const rateLimit: RateLimitInfo = await api.getRateLimit();\n *\n * console.log(`Requests: ${rateLimit.requests}/${rateLimit.limit}`);\n * console.log(`Resets in: ${rateLimit.resetTime} seconds`);\n *\n * // Implement backoff if approaching limit\n * if (rateLimit.requests >= rateLimit.limit * 0.9) {\n * console.warn('Approaching rate limit, slowing down');\n * await new Promise(resolve =>\n * setTimeout(resolve, rateLimit.resetTime * 1000)\n * );\n * }\n *\n * // Calculate requests per second allowed\n * const rps = rateLimit.limit / rateLimit.window;\n * console.log(`Max ${rps} requests per second allowed`);\n * ```\n * @category Reference\n */\nexport interface RateLimitInfo {\n /** Current request count */\n requests: number;\n /** Maximum requests allowed */\n limit: number;\n /** Time window in seconds */\n window: number;\n /** Time until reset in seconds */\n resetTime: number;\n}\n\n/**\n * File upload progress tracking for user feedback and monitoring.\n *\n * @remarks\n * Provides real-time progress information during file uploads, enabling\n * applications to show progress bars and estimated completion times.\n * The speed calculation is typically based on a rolling average to\n * smooth out network fluctuations.\n *\n * @example\n * ```typescript\n * // Upload with progress tracking\n * await vana.data.upload(file, {\n * onProgress: (progress: UploadProgress) => {\n * // Update progress bar\n * progressBar.style.width = `${progress.percentage}%`;\n *\n * // Show upload speed\n * const speedMBps = (progress.speed / 1024 / 1024).toFixed(2);\n * speedDisplay.textContent = `${speedMBps} MB/s`;\n *\n * // Show time remaining\n * const minutes = Math.floor(progress.estimatedTimeRemaining / 60);\n * const seconds = progress.estimatedTimeRemaining % 60;\n * timeDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n *\n * // Log progress milestones\n * if (progress.percentage === 25 ||\n * progress.percentage === 50 ||\n * progress.percentage === 75) {\n * console.log(`Upload ${progress.percentage}% complete`);\n * }\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface UploadProgress {\n /** Bytes uploaded */\n loaded: number;\n /** Total bytes to upload */\n total: number;\n /** Upload percentage (0-100) */\n percentage: number;\n /** Upload speed in bytes per second */\n speed: number;\n /** Estimated time remaining in seconds */\n estimatedTimeRemaining: number;\n}\n\n/**\n * Network information for blockchain connectivity and monitoring.\n *\n * @remarks\n * Provides comprehensive details about the connected blockchain network,\n * including configuration URLs and real-time status. Use this information\n * to verify network connectivity, display network details to users, and\n * construct explorer links for transactions.\n *\n * @example\n * ```typescript\n * // Get current network info\n * const network: NetworkInfo = await vana.protocol.getNetworkInfo();\n *\n * console.log(`Connected to: ${network.chainName} (ID: ${network.chainId})`);\n * console.log(`Current block: ${network.currentBlock}`);\n *\n * // Check network health\n * if (network.status !== 'healthy') {\n * console.warn(`Network ${network.status}: consider switching RPC`);\n * }\n *\n * // Generate explorer link for transaction\n * function getExplorerLink(txHash: string): string {\n * if (!network.explorerUrl) {\n * return `Transaction: ${txHash}`;\n * }\n * return `${network.explorerUrl}/tx/${txHash}`;\n * }\n *\n * // Verify expected network\n * const EXPECTED_CHAIN_ID = 1337; // Vana testnet\n * if (network.chainId !== EXPECTED_CHAIN_ID) {\n * throw new Error(`Wrong network! Expected ${EXPECTED_CHAIN_ID}, got ${network.chainId}`);\n * }\n * ```\n * @category Reference\n */\nexport interface NetworkInfo {\n /** Chain ID */\n chainId: number;\n /** Chain name */\n chainName: string;\n /** RPC URL */\n rpcUrl: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** Current block number */\n currentBlock: bigint;\n /** Network status */\n status: \"healthy\" | \"degraded\" | \"down\";\n}\n\n/**\n * Gas estimate information for transaction cost prediction.\n *\n * @remarks\n * Provides detailed gas pricing estimates to help users understand transaction\n * costs before execution. Supports both legacy (gasPrice) and EIP-1559\n * (maxFeePerGas) pricing models. The estimatedCost is calculated based on\n * current network conditions and may vary by the time of actual execution.\n *\n * @example\n * ```typescript\n * // Get gas estimate before transaction\n * const estimate: GasEstimate = await vana.permissions.estimateGas({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Convert to human-readable format\n * const costInEth = Number(estimate.estimatedCost) / 1e18;\n * console.log(`Estimated cost: ${costInEth.toFixed(6)} ETH`);\n *\n * // Check if user has sufficient balance\n * const balance = await vana.protocol.getBalance(userAddress);\n * if (balance < estimate.estimatedCost) {\n * throw new Error(`Insufficient balance. Need ${costInEth} ETH`);\n * }\n *\n * // Use estimate for transaction with buffer\n * await vana.permissions.grant(params, {\n * gasLimit: estimate.gasLimit * 110n / 100n, // 10% buffer\n * maxFeePerGas: estimate.maxFeePerGas,\n * maxPriorityFeePerGas: estimate.maxPriorityFeePerGas\n * });\n * ```\n * @category Reference\n */\nexport interface GasEstimate {\n /** Gas limit */\n gasLimit: bigint;\n /** Gas price */\n gasPrice: bigint;\n /** Max fee per gas */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas */\n maxPriorityFeePerGas?: bigint;\n /** Estimated cost in wei */\n estimatedCost: bigint;\n}\n\n/**\n * Time range parameters for filtering operations by time period.\n *\n * Used in various SDK methods to specify date/time ranges for queries,\n * analytics, and data filtering operations. Times are specified as Unix timestamps.\n *\n * @category Reference\n * @example\n * ```typescript\n * const lastWeek: TimeRange = {\n * from: Date.now() - (7 * 24 * 60 * 60 * 1000), // 7 days ago\n * to: Date.now()\n * };\n *\n * const permissions = await vana.permissions.getUserPermissions({\n * timeRange: lastWeek\n * });\n * ```\n */\nexport interface TimeRange {\n /** Start time (Unix timestamp) */\n from?: number;\n /** End time (Unix timestamp) */\n to?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/utils.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Makes all properties in T optional except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are optional, but specific properties remain required.\n * Commonly used for update operations where only certain fields must be provided.\n *\n * @example\n * ```typescript\n * interface User {\n * id: string;\n * name: string;\n * email: string;\n * age: number;\n * }\n *\n * // Only 'id' is required, all other properties are optional\n * type UserUpdate = PartialExcept<User, 'id'>;\n *\n * const update: UserUpdate = {\n * id: '123', // Required\n * name: 'John' // Optional\n * // email and age are also optional\n * };\n * ```\n * @category Reference\n */\nexport type PartialExcept<T, K extends keyof T> = Partial<T> & Pick<T, K>;\n\n/**\n * Makes all properties in T required except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are required, but specific properties remain optional.\n * Commonly used for creation operations where most fields are mandatory.\n *\n * @example\n * ```typescript\n * interface Config {\n * apiUrl: string;\n * timeout?: number;\n * retries?: number;\n * debug?: boolean;\n * }\n *\n * // All properties required except 'debug'\n * type StrictConfig = RequiredExcept<Config, 'debug'>;\n *\n * const config: StrictConfig = {\n * apiUrl: 'https://api.vana.com', // Required\n * timeout: 5000, // Required (was optional, now required)\n * retries: 3, // Required (was optional, now required)\n * // debug remains optional\n * };\n * ```\n * @category Reference\n */\nexport type RequiredExcept<T, K extends keyof T> = Required<T> &\n Partial<Pick<T, K>>;\n\n/**\n * Extracts the return type of a promise\n *\n * @remarks\n * This utility type unwraps the type contained within a Promise.\n * If the type is not a Promise, it returns the type unchanged.\n * Note: TypeScript 4.5+ includes a built-in Awaited type with similar functionality.\n *\n * @example\n * ```typescript\n * type AsyncString = Promise<string>;\n * type SyncString = string;\n *\n * // Extracts 'string' from Promise<string>\n * type Result1 = Awaited<AsyncString>; // string\n *\n * // Returns 'string' unchanged since it's not a Promise\n * type Result2 = Awaited<SyncString>; // string\n *\n * // Practical usage with async functions\n * async function fetchUser(): Promise<{ id: string; name: string }> {\n * // ...\n * }\n *\n * type User = Awaited<ReturnType<typeof fetchUser>>; // { id: string; name: string }\n * ```\n * @category Reference\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Creates a type that accepts either T or a Promise<T>\n *\n * @remarks\n * This utility type is useful for functions that can work with both\n * synchronous and asynchronous values. It allows flexible APIs that\n * can accept immediate values or promises that resolve to those values.\n *\n * @example\n * ```typescript\n * // Function that accepts either a value or a promise of that value\n * async function processData(data: MaybePromise<string>): Promise<string> {\n * // await works on both promises and regular values\n * const resolved = await data;\n * return resolved.toUpperCase();\n * }\n *\n * // Both calls are valid:\n * processData('hello'); // Synchronous value\n * processData(Promise.resolve('world')); // Asynchronous value\n *\n * // Common use case in SDK callbacks\n * interface StorageProvider {\n * // Provider can implement sync or async file reading\n * read(path: string): MaybePromise<Buffer>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Creates a type that accepts either T or an array of T\n *\n * @remarks\n * This utility type is useful for functions that can accept either a single\n * value or an array of values, providing a more flexible API. The implementation\n * can normalize the input to always work with arrays internally.\n *\n * @example\n * ```typescript\n * // Function that accepts either a single ID or multiple IDs\n * function deleteItems(ids: MaybeArray<string>): void {\n * // Normalize to array\n * const idArray = Array.isArray(ids) ? ids : [ids];\n * idArray.forEach(id => console.log(`Deleting ${id}`));\n * }\n *\n * // Both calls are valid:\n * deleteItems('item-1'); // Single item\n * deleteItems(['item-1', 'item-2', 'item-3']); // Multiple items\n *\n * // Common use case in permissions\n * interface GrantPermissionsParams {\n * permissions: MaybeArray<Permission>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybeArray<T> = T | T[];\n\n/**\n * Pagination parameters for controlling result set size and navigation.\n *\n * Used across SDK methods that return lists of items to control how many items\n * are returned and to navigate through large result sets efficiently.\n *\n * @category Reference\n * @example\n * ```typescript\n * const pagination: PaginationParams = {\n * limit: 20, // Return 20 items\n * offset: 40, // Skip first 40 items (page 3)\n * cursor: 'eyJpZCI6MTIzfQ==' // Or use cursor-based pagination\n * };\n *\n * const files = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination\n * });\n * ```\n */\nexport interface PaginationParams {\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Cursor for cursor-based pagination */\n cursor?: string;\n}\n\n/**\n * Pagination result containing items and metadata for navigating large datasets.\n *\n * @remarks\n * This interface standardizes paginated responses across the SDK, providing\n * consistent metadata for implementing pagination UI components and handling\n * multi-page data fetching. Supports both offset-based and cursor-based pagination.\n *\n * @example\n * ```typescript\n * // Fetching paginated user files\n * async function getAllUserFiles(userAddress: string): Promise<File[]> {\n * const allFiles: File[] = [];\n * let cursor: string | undefined;\n *\n * do {\n * const result: PaginationResult<File> = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination: { limit: 50, cursor }\n * });\n *\n * allFiles.push(...result.items);\n * cursor = result.nextCursor;\n *\n * console.log(`Fetched ${result.count} of ${result.total} files`);\n * } while (result.hasMore);\n *\n * return allFiles;\n * }\n * ```\n * @category Reference\n */\nexport interface PaginationResult<T> {\n /** Array of items */\n items: T[];\n /** Total number of items available */\n total: number;\n /** Number of items returned */\n count: number;\n /** Whether there are more items available */\n hasMore: boolean;\n /** Cursor for next page */\n nextCursor?: string;\n}\n\n/**\n * Block range parameters for filtering blockchain events and transactions.\n *\n * @remarks\n * Used to specify a range of blocks when querying blockchain data.\n * Both parameters are optional - omitting fromBlock starts from genesis,\n * omitting toBlock goes to the latest block. Be cautious with large ranges\n * as they may result in heavy RPC loads or timeouts.\n *\n * @example\n * ```typescript\n * // Get events from the last 1000 blocks\n * const currentBlock = await vana.protocol.getBlockNumber();\n * const events = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: currentBlock - 1000n,\n * toBlock: currentBlock\n * }\n * });\n *\n * // Get all historical events (use with caution)\n * const allEvents = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: 0n\n * // toBlock omitted = up to latest\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface BlockRange {\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n}\n\n/**\n * Transaction receipt with additional metadata for tracking transaction results.\n *\n * @remarks\n * Provides comprehensive information about executed transactions including\n * gas usage, success status, and emitted events. Use the logs array to\n * decode events emitted by smart contracts during transaction execution.\n * The receipt is available after a transaction is mined and included in a block.\n *\n * @example\n * ```typescript\n * // Execute transaction and wait for receipt\n * const receipt = await vana.permissions.grant({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Check transaction success\n * if (receipt.status === 'success') {\n * console.log(`Gas used: ${receipt.gasUsed}`);\n * console.log(`Block: ${receipt.blockNumber}`);\n *\n * // Decode events from logs\n * receipt.logs.forEach(log => {\n * if (log.topics[0] === PERMISSION_GRANTED_TOPIC) {\n * console.log('Permission granted event detected');\n * }\n * });\n * } else {\n * console.error('Transaction reverted');\n * }\n * ```\n * @category Reference\n */\nexport interface TransactionReceipt {\n /** Transaction hash */\n transactionHash: Hash;\n /** Block number */\n blockNumber: bigint;\n /** Block hash */\n blockHash: Hash;\n /** Gas used */\n gasUsed: bigint;\n /** Transaction status */\n status: \"success\" | \"reverted\";\n /** Contract address if contract deployment */\n contractAddress?: Address;\n /** Event logs */\n logs: Array<{\n address: Address;\n topics: Hash[];\n data: string;\n }>;\n}\n\n/**\n * Response wrapper for API results providing consistent error handling.\n *\n * @remarks\n * Standardizes API responses across the SDK, making it easy to handle\n * both successful and failed requests. The generic type parameter T\n * represents the expected data type for successful responses. Check\n * the success flag before accessing data to ensure type safety.\n *\n * @example\n * ```typescript\n * // Handling API responses\n * async function fetchUserData(userId: string): Promise<User | null> {\n * const response: ApiResponse<User> = await api.getUser(userId);\n *\n * if (response.success) {\n * console.log('User fetched:', response.data.name);\n * // Access metadata if available\n * if (response.metadata?.cached) {\n * console.log('Data was cached');\n * }\n * return response.data;\n * } else {\n * console.error('Failed to fetch user:', response.error);\n * return null;\n * }\n * }\n *\n * // Type-safe error handling\n * interface UserData {\n * id: string;\n * name: string;\n * }\n *\n * const result: ApiResponse<UserData> = await api.call('/users/123');\n * if (result.success) {\n * // TypeScript knows result.data is UserData here\n * console.log(result.data.name);\n * }\n * ```\n * @category Reference\n */\nexport interface ApiResponse<T> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if not successful */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Retry configuration for handling transient failures with exponential backoff.\n *\n * @remarks\n * Configures automatic retry behavior for operations that may fail due to\n * temporary issues like network problems or rate limits. Supports exponential\n * backoff to avoid overwhelming services. The shouldRetry function allows\n * custom logic to determine which errors warrant a retry attempt.\n *\n * @example\n * ```typescript\n * // Simple retry configuration\n * const basicRetry: RetryConfig = {\n * attempts: 3,\n * delay: 1000 // 1 second between retries\n * };\n *\n * // Exponential backoff configuration\n * const exponentialRetry: RetryConfig = {\n * attempts: 5,\n * delay: 1000,\n * backoffMultiplier: 2, // Double delay each time\n * maxDelay: 30000, // Cap at 30 seconds\n * shouldRetry: (error) => {\n * // Only retry network and timeout errors\n * return error.name === 'NetworkError' ||\n * error.message.includes('timeout');\n * }\n * };\n *\n * // Usage with SDK\n * const vana = new Vana({\n * retryConfig: exponentialRetry\n * });\n * ```\n * @category Reference\n */\nexport interface RetryConfig {\n /** Number of retry attempts */\n attempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /** Backoff multiplier */\n backoffMultiplier?: number;\n /** Maximum delay in milliseconds */\n maxDelay?: number;\n /** Function to determine if error should be retried */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Cache configuration for optimizing repeated data fetches.\n *\n * @remarks\n * Configures in-memory caching behavior to reduce redundant API calls and\n * improve performance. The cache automatically evicts expired entries based\n * on TTL and removes least-recently-used items when maxSize is reached.\n * Use appropriate TTL values based on your data freshness requirements.\n *\n * @example\n * ```typescript\n * // Short-lived cache for frequently changing data\n * const userCache: CacheConfig = {\n * ttl: 60000, // 1 minute\n * maxSize: 100, // Store up to 100 users\n * prefix: 'user:' // Cache keys like 'user:123'\n * };\n *\n * // Long-lived cache for stable data\n * const schemaCache: CacheConfig = {\n * ttl: 3600000, // 1 hour\n * maxSize: 1000, // Store up to 1000 schemas\n * prefix: 'schema:'\n * };\n *\n * // Disable caching by setting TTL to 0\n * const noCache: CacheConfig = {\n * ttl: 0 // No caching\n * };\n * ```\n * @category Reference\n */\nexport interface CacheConfig {\n /** Cache TTL in milliseconds */\n ttl: number;\n /** Maximum cache size */\n maxSize?: number;\n /** Cache key prefix */\n prefix?: string;\n}\n\n/**\n * Validation result for data integrity checks and schema validation.\n *\n * @remarks\n * Provides detailed feedback about validation outcomes, distinguishing between\n * errors (which prevent processing) and warnings (which indicate potential issues).\n * Used throughout the SDK for validating permissions, file formats, schemas,\n * and API parameters before operations.\n *\n * @example\n * ```typescript\n * // Validating user input\n * function validateFileUpload(file: File): ValidationResult {\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * // Check file size\n * if (file.size > 100 * 1024 * 1024) {\n * errors.push('File size exceeds 100MB limit');\n * } else if (file.size > 50 * 1024 * 1024) {\n * warnings.push('Large file may take time to upload');\n * }\n *\n * // Check file type\n * if (!file.type.startsWith('image/')) {\n * errors.push('Only image files are allowed');\n * }\n *\n * return {\n * valid: errors.length === 0,\n * errors,\n * warnings\n * };\n * }\n *\n * // Using validation result\n * const result = validateFileUpload(file);\n * if (!result.valid) {\n * console.error('Validation failed:', result.errors.join(', '));\n * } else {\n * if (result.warnings.length > 0) {\n * console.warn('Warnings:', result.warnings.join(', '));\n * }\n * // Proceed with upload\n * }\n * ```\n * @category Reference\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation errors */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n}\n\n/**\n * Status information for health checks and service monitoring.\n *\n * @remarks\n * Used to report the health status of various SDK components including\n * storage providers, RPC connections, and personal servers. The details\n * field can contain provider-specific information for debugging.\n * Timestamps use Unix epoch milliseconds.\n *\n * @example\n * ```typescript\n * // Checking storage provider health\n * const status: StatusInfo = await storage.getStatus();\n *\n * if (!status.healthy) {\n * console.error(`Storage unhealthy: ${status.message}`);\n * // Check how long the issue has persisted\n * const downtime = Date.now() - status.lastCheck;\n * if (downtime > 300000) { // 5 minutes\n * // Switch to backup provider\n * }\n * }\n *\n * // Detailed status with custom fields\n * const serverStatus: StatusInfo = {\n * healthy: true,\n * message: 'All systems operational',\n * lastCheck: Date.now(),\n * details: {\n * uptime: 3600000, // 1 hour\n * requestsServed: 1234,\n * avgResponseTime: 145, // ms\n * activeConnections: 23\n * }\n * };\n * ```\n * @category Reference\n */\nexport interface StatusInfo {\n /** Whether the service is healthy */\n healthy: boolean;\n /** Status message */\n message?: string;\n /** Last check timestamp */\n lastCheck: number;\n /** Additional status details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Rate limit information for API throttling and quota management.\n *\n * @remarks\n * Provides visibility into rate limiting status to help applications\n * implement appropriate backoff strategies. Rate limits protect services\n * from overload and ensure fair resource usage. Use this information\n * to pace requests and avoid hitting limits.\n *\n * @example\n * ```typescript\n * // Check rate limit before making requests\n * const rateLimit: RateLimitInfo = await api.getRateLimit();\n *\n * console.log(`Requests: ${rateLimit.requests}/${rateLimit.limit}`);\n * console.log(`Resets in: ${rateLimit.resetTime} seconds`);\n *\n * // Implement backoff if approaching limit\n * if (rateLimit.requests >= rateLimit.limit * 0.9) {\n * console.warn('Approaching rate limit, slowing down');\n * await new Promise(resolve =>\n * setTimeout(resolve, rateLimit.resetTime * 1000)\n * );\n * }\n *\n * // Calculate requests per second allowed\n * const rps = rateLimit.limit / rateLimit.window;\n * console.log(`Max ${rps} requests per second allowed`);\n * ```\n * @category Reference\n */\nexport interface RateLimitInfo {\n /** Current request count */\n requests: number;\n /** Maximum requests allowed */\n limit: number;\n /** Time window in seconds */\n window: number;\n /** Time until reset in seconds */\n resetTime: number;\n}\n\n/**\n * File upload progress tracking for user feedback and monitoring.\n *\n * @remarks\n * Provides real-time progress information during file uploads, enabling\n * applications to show progress bars and estimated completion times.\n * The speed calculation is typically based on a rolling average to\n * smooth out network fluctuations.\n *\n * @example\n * ```typescript\n * // Upload with progress tracking\n * await vana.data.upload(file, {\n * onProgress: (progress: UploadProgress) => {\n * // Update progress bar\n * progressBar.style.width = `${progress.percentage}%`;\n *\n * // Show upload speed\n * const speedMBps = (progress.speed / 1024 / 1024).toFixed(2);\n * speedDisplay.textContent = `${speedMBps} MB/s`;\n *\n * // Show time remaining\n * const minutes = Math.floor(progress.estimatedTimeRemaining / 60);\n * const seconds = progress.estimatedTimeRemaining % 60;\n * timeDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n *\n * // Log progress milestones\n * if (progress.percentage === 25 ||\n * progress.percentage === 50 ||\n * progress.percentage === 75) {\n * console.log(`Upload ${progress.percentage}% complete`);\n * }\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface UploadProgress {\n /** Bytes uploaded */\n loaded: number;\n /** Total bytes to upload */\n total: number;\n /** Upload percentage (0-100) */\n percentage: number;\n /** Upload speed in bytes per second */\n speed: number;\n /** Estimated time remaining in seconds */\n estimatedTimeRemaining: number;\n}\n\n/**\n * Network information for blockchain connectivity and monitoring.\n *\n * @remarks\n * Provides comprehensive details about the connected blockchain network,\n * including configuration URLs and real-time status. Use this information\n * to verify network connectivity, display network details to users, and\n * construct explorer links for transactions.\n *\n * @example\n * ```typescript\n * // Get current network info\n * const network: NetworkInfo = await vana.protocol.getNetworkInfo();\n *\n * console.log(`Connected to: ${network.chainName} (ID: ${network.chainId})`);\n * console.log(`Current block: ${network.currentBlock}`);\n *\n * // Check network health\n * if (network.status !== 'healthy') {\n * console.warn(`Network ${network.status}: consider switching RPC`);\n * }\n *\n * // Generate explorer link for transaction\n * function getExplorerLink(txHash: string): string {\n * if (!network.explorerUrl) {\n * return `Transaction: ${txHash}`;\n * }\n * return `${network.explorerUrl}/tx/${txHash}`;\n * }\n *\n * // Verify expected network\n * const EXPECTED_CHAIN_ID = 1337; // Vana testnet\n * if (network.chainId !== EXPECTED_CHAIN_ID) {\n * throw new Error(`Wrong network! Expected ${EXPECTED_CHAIN_ID}, got ${network.chainId}`);\n * }\n * ```\n * @category Reference\n */\nexport interface NetworkInfo {\n /** Chain ID */\n chainId: number;\n /** Chain name */\n chainName: string;\n /** RPC URL */\n rpcUrl: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** Current block number */\n currentBlock: bigint;\n /** Network status */\n status: \"healthy\" | \"degraded\" | \"down\";\n}\n\n/**\n * Gas estimate information for transaction cost prediction.\n *\n * @remarks\n * Provides detailed gas pricing estimates to help users understand transaction\n * costs before execution. Supports both legacy (gasPrice) and EIP-1559\n * (maxFeePerGas) pricing models. The estimatedCost is calculated based on\n * current network conditions and may vary by the time of actual execution.\n *\n * @example\n * ```typescript\n * // Get gas estimate before transaction\n * const estimate: GasEstimate = await vana.permissions.estimateGas({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Convert to human-readable format\n * const costInEth = Number(estimate.estimatedCost) / 1e18;\n * console.log(`Estimated cost: ${costInEth.toFixed(6)} ETH`);\n *\n * // Check if user has sufficient balance\n * const balance = await vana.protocol.getBalance(userAddress);\n * if (balance < estimate.estimatedCost) {\n * throw new Error(`Insufficient balance. Need ${costInEth} ETH`);\n * }\n *\n * // Use estimate for transaction with buffer\n * await vana.permissions.grant(params, {\n * gasLimit: estimate.gasLimit * 110n / 100n, // 10% buffer\n * maxFeePerGas: estimate.maxFeePerGas,\n * maxPriorityFeePerGas: estimate.maxPriorityFeePerGas\n * });\n * ```\n * @category Reference\n */\nexport interface GasEstimate {\n /** Gas limit */\n gasLimit: bigint;\n /** Gas price */\n gasPrice: bigint;\n /** Max fee per gas */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas */\n maxPriorityFeePerGas?: bigint;\n /** Estimated cost in wei */\n estimatedCost: bigint;\n}\n\n/**\n * Time range parameters for filtering operations by time period.\n *\n * Used in various SDK methods to specify date/time ranges for queries,\n * analytics, and data filtering operations. Times are specified as Unix timestamps.\n *\n * @category Reference\n * @example\n * ```typescript\n * const lastWeek: TimeRange = {\n * from: Date.now() - (7 * 24 * 60 * 60 * 1000), // 7 days ago\n * to: Date.now()\n * };\n *\n * const permissions = await vana.permissions.getUserPermissions({\n * timeRange: lastWeek\n * });\n * ```\n */\nexport interface TimeRange {\n /** Start time (Unix timestamp) */\n from?: number;\n /** End time (Unix timestamp) */\n to?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/dist/types/utils.d.ts
CHANGED
|
@@ -255,55 +255,6 @@ export interface BlockRange {
|
|
|
255
255
|
/** Ending block number */
|
|
256
256
|
toBlock?: bigint;
|
|
257
257
|
}
|
|
258
|
-
/**
|
|
259
|
-
* Transaction options for customizing blockchain transaction parameters.
|
|
260
|
-
*
|
|
261
|
-
* @remarks
|
|
262
|
-
* Provides fine-grained control over transaction execution. Supports both
|
|
263
|
-
* legacy (gasPrice) and EIP-1559 (maxFeePerGas) transaction types. When
|
|
264
|
-
* not specified, the SDK will use appropriate defaults based on network
|
|
265
|
-
* conditions. Use these options to optimize for speed or cost.
|
|
266
|
-
*
|
|
267
|
-
* @example
|
|
268
|
-
* ```typescript
|
|
269
|
-
* // High priority transaction with EIP-1559 pricing
|
|
270
|
-
* await vana.permissions.grant(params, {
|
|
271
|
-
* maxFeePerGas: 100n * 10n ** 9n, // 100 gwei
|
|
272
|
-
* maxPriorityFeePerGas: 2n * 10n ** 9n, // 2 gwei tip
|
|
273
|
-
* timeout: 180000, // 3 minutes
|
|
274
|
-
* });
|
|
275
|
-
*
|
|
276
|
-
* // Legacy transaction with specific gas limit
|
|
277
|
-
* await vana.data.registerFile(params, {
|
|
278
|
-
* gasLimit: 500000n,
|
|
279
|
-
* gasPrice: 50n * 10n ** 9n, // 50 gwei
|
|
280
|
-
* timeout: 600000, // 10 minutes
|
|
281
|
-
* });
|
|
282
|
-
*
|
|
283
|
-
* // Send ETH with the transaction
|
|
284
|
-
* await vana.protocol.execute(params, {
|
|
285
|
-
* value: 10n ** 18n, // 1 ETH
|
|
286
|
-
* gasLimit: 21000n
|
|
287
|
-
* });
|
|
288
|
-
* ```
|
|
289
|
-
* @category Reference
|
|
290
|
-
*/
|
|
291
|
-
export interface TransactionOptions {
|
|
292
|
-
/** Gas limit */
|
|
293
|
-
gasLimit?: bigint;
|
|
294
|
-
/** Gas price */
|
|
295
|
-
gasPrice?: bigint;
|
|
296
|
-
/** Max fee per gas (EIP-1559) */
|
|
297
|
-
maxFeePerGas?: bigint;
|
|
298
|
-
/** Max priority fee per gas (EIP-1559) */
|
|
299
|
-
maxPriorityFeePerGas?: bigint;
|
|
300
|
-
/** Nonce */
|
|
301
|
-
nonce?: number;
|
|
302
|
-
/** Value to send with transaction */
|
|
303
|
-
value?: bigint;
|
|
304
|
-
/** Transaction timeout in milliseconds for receipt waiting (default: 30000) */
|
|
305
|
-
timeout?: number;
|
|
306
|
-
}
|
|
307
258
|
/**
|
|
308
259
|
* Transaction receipt with additional metadata for tracking transaction results.
|
|
309
260
|
*
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|