{"version":3,"sources":["../../src/web/index.ts","../../src/errors/IdentityKitError.ts","../../src/types/crypto.ts","../../src/cache/InMemoryLRUDIDDocumentCache.ts","../../src/vdr/VDRRegistry.ts","../../src/multibase/base.ts","../../src/utils/bytes.ts","../../src/multibase/key.ts","../../src/multibase/did.ts","../../src/utils/did.ts","../../src/utils/DebugLogger.ts","../../src/vdr/abstractVDR.ts","../../src/vdr/keyVDR.ts","../../src/vdr/roochVDR.ts","../../src/crypto/providers/ed25519.ts","../../src/crypto/providers/secp256k1.ts","../../src/crypto/providers/ecdsa_r1.ts","../../src/crypto/factory.ts","../../src/crypto/utils.ts","../../src/crypto/EcdsaR1PublicKey.ts","../../src/signers/keyStoreUtils.ts","../../src/signers/types.ts","../../src/signers/didAccountSigner.ts","../../src/vdr/roochVDRTypes.ts","../../src/utils/sessionScopes.ts","../../src/vdr/index.ts","../../src/keys/KeyStore.ts","../../src/keys/StoredKeyCodec.ts","../../src/keys/KeyManager.ts","../../src/IdentityEnv.ts","../../src/IdentityKit.ts","../../src/CadopIdentityKit.ts","../../src/auth/v1/index.ts","../../src/auth/v1/utils.ts","../../src/auth/v1/nonceStore.ts","../../src/auth/index.ts","../../src/web/keystore/LocalStorageKeyStore.ts","../../src/web/keystore/IndexedDBKeyStore.ts","../../src/deeplink/shared.ts","../../src/web/deeplink/DeepLinkManager.ts","../../src/web/IdentityKitWeb.ts","../../src/web/react/useIdentityKit.ts"],"sourcesContent":["/**\n * Web-specific functionality for @nuwa-ai/identity-kit\n *\n * This module provides browser-specific implementations including:\n * - LocalStorage and IndexedDB KeyStore implementations\n * - DeepLink management for CADOP integration\n * - High-level IdentityKitWeb API\n * - React hooks (when React is available)\n *\n * Note: All exports include runtime environment checks to ensure\n * they only work in appropriate environments (browser for web features,\n * React available for hooks, etc.)\n */\n\n// Always export types for better TypeScript support\nexport type { IdentityKitWebOptions } from './IdentityKitWeb';\nexport type { ConnectOptions, AuthResult } from './deeplink/DeepLinkManager';\nexport type {\n  IdentityKitState,\n  IdentityKitHook,\n  UseIdentityKitOptions,\n} from './react/useIdentityKit';\n\n// Re-export core functionality\nexport { VDRRegistry } from '../index';\n\n// KeyStore implementations (with runtime browser checks)\nexport { LocalStorageKeyStore } from './keystore/LocalStorageKeyStore';\nexport { IndexedDBKeyStore } from './keystore/IndexedDBKeyStore';\n\n// DeepLink functionality (with runtime browser checks)\nexport { DeepLinkManager } from './deeplink/DeepLinkManager';\n\n// Main IdentityKitWeb class (with runtime browser checks)\nexport { IdentityKitWeb } from './IdentityKitWeb';\n\n// React hooks (with runtime React availability checks)\nexport { useIdentityKit } from './react/useIdentityKit';\n\n// Create registry instance\nimport { VDRRegistry } from '../index';\nexport const registry = VDRRegistry.getInstance();\n","/**\n * Unified error handling for IdentityKit\n */\n\n/**\n * Error codes for IdentityKit operations\n */\nexport enum IdentityKitErrorCode {\n  // Configuration and initialization\n  INVALID_CONFIGURATION = 'INVALID_CONFIGURATION',\n  ENVIRONMENT_NOT_SUPPORTED = 'ENVIRONMENT_NOT_SUPPORTED',\n  INITIALIZATION_FAILED = 'INITIALIZATION_FAILED',\n\n  // DID operations\n  DID_NOT_FOUND = 'DID_NOT_FOUND',\n  DID_INVALID_FORMAT = 'DID_INVALID_FORMAT',\n  DID_METHOD_NOT_SUPPORTED = 'DID_METHOD_NOT_SUPPORTED',\n  DID_CREATION_FAILED = 'DID_CREATION_FAILED',\n  DID_RESOLUTION_FAILED = 'DID_RESOLUTION_FAILED',\n  DID_NOT_SET = 'DID_NOT_SET',\n  DID_SERVICE_NOT_FOUND = 'DID_SERVICE_NOT_FOUND',\n  DID_VERIFICATION_METHOD_NOT_FOUND = 'DID_VERIFICATION_METHOD_NOT_FOUND',\n\n  // VDR (Verifiable Data Registry) operations\n  VDR_NOT_AVAILABLE = 'VDR_NOT_AVAILABLE',\n  VDR_OPERATION_FAILED = 'VDR_OPERATION_FAILED',\n  VDR_NETWORK_ERROR = 'VDR_NETWORK_ERROR',\n  VDR_INVALID_RESPONSE = 'VDR_INVALID_RESPONSE',\n\n  // Key management\n  KEY_NOT_FOUND = 'KEY_NOT_FOUND',\n  KEY_INVALID_FORMAT = 'KEY_INVALID_FORMAT',\n  KEY_GENERATION_FAILED = 'KEY_GENERATION_FAILED',\n  KEY_IMPORT_FAILED = 'KEY_IMPORT_FAILED',\n  KEY_STORAGE_ERROR = 'KEY_STORAGE_ERROR',\n  KEY_PERMISSION_DENIED = 'KEY_PERMISSION_DENIED',\n  KEY_VALIDATION_FAILED = 'KEY_VALIDATION_FAILED',\n  KEY_PRIVATE_KEY_NOT_AVAILABLE = 'KEY_PRIVATE_KEY_NOT_AVAILABLE',\n  KEY_DID_MISMATCH = 'KEY_DID_MISMATCH',\n  KEY_ID_MISMATCH = 'KEY_ID_MISMATCH',\n  KEY_TYPE_NOT_SUPPORTED = 'KEY_TYPE_NOT_SUPPORTED',\n  KEY_ALREADY_EXISTS = 'KEY_ALREADY_EXISTS',\n\n  // Signing operations\n  SIGNING_FAILED = 'SIGNING_FAILED',\n  SIGNATURE_VERIFICATION_FAILED = 'SIGNATURE_VERIFICATION_FAILED',\n  SIGNER_NOT_AVAILABLE = 'SIGNER_NOT_AVAILABLE',\n  SIGNER_INVALID_DID = 'SIGNER_INVALID_DID',\n  SIGNER_NO_KEYS = 'SIGNER_NO_KEYS',\n\n  // Authentication (from existing AuthErrorCode)\n  AUTH_INVALID_HEADER = 'AUTH_INVALID_HEADER',\n  AUTH_INVALID_BASE64 = 'AUTH_INVALID_BASE64',\n  AUTH_INVALID_JSON = 'AUTH_INVALID_JSON',\n  AUTH_MISSING_SIGNATURE = 'AUTH_MISSING_SIGNATURE',\n  AUTH_TIMESTAMP_OUT_OF_WINDOW = 'AUTH_TIMESTAMP_OUT_OF_WINDOW',\n  AUTH_NONCE_REPLAYED = 'AUTH_NONCE_REPLAYED',\n  AUTH_DID_DOCUMENT_NOT_FOUND = 'AUTH_DID_DOCUMENT_NOT_FOUND',\n  AUTH_VERIFICATION_METHOD_NOT_FOUND = 'AUTH_VERIFICATION_METHOD_NOT_FOUND',\n  AUTH_INVALID_PUBLIC_KEY = 'AUTH_INVALID_PUBLIC_KEY',\n  AUTH_DID_MISMATCH = 'AUTH_DID_MISMATCH',\n\n  // Web-specific operations\n  WEB_BROWSER_NOT_SUPPORTED = 'WEB_BROWSER_NOT_SUPPORTED',\n  WEB_STORAGE_NOT_AVAILABLE = 'WEB_STORAGE_NOT_AVAILABLE',\n  WEB_DEEPLINK_FAILED = 'WEB_DEEPLINK_FAILED',\n  WEB_CADOP_CONNECTION_FAILED = 'WEB_CADOP_CONNECTION_FAILED',\n  WEB_OAUTH_CALLBACK_FAILED = 'WEB_OAUTH_CALLBACK_FAILED',\n  WEB_NOT_CONNECTED = 'WEB_NOT_CONNECTED',\n  WEB_CALLBACK_FAILED = 'WEB_CALLBACK_FAILED',\n\n  // React-specific operations\n  REACT_NOT_AVAILABLE = 'REACT_NOT_AVAILABLE',\n  REACT_HOOK_MISUSE = 'REACT_HOOK_MISUSE',\n\n  // Crypto operations\n  CRYPTO_PROVIDER_NOT_FOUND = 'CRYPTO_PROVIDER_NOT_FOUND',\n  CRYPTO_OPERATION_FAILED = 'CRYPTO_OPERATION_FAILED',\n  CRYPTO_KEY_DERIVATION_FAILED = 'CRYPTO_KEY_DERIVATION_FAILED',\n\n  // Multibase operations\n  MULTIBASE_DECODE_FAILED = 'MULTIBASE_DECODE_FAILED',\n  MULTIBASE_ENCODE_FAILED = 'MULTIBASE_ENCODE_FAILED',\n  MULTIBASE_INVALID_FORMAT = 'MULTIBASE_INVALID_FORMAT',\n\n  // Validation operations\n  SCOPE_VALIDATION_FAILED = 'SCOPE_VALIDATION_FAILED',\n  SCOPE_INVALID_FORMAT = 'SCOPE_INVALID_FORMAT',\n  VALIDATION_FAILED = 'VALIDATION_FAILED',\n  INVALID_INPUT_FORMAT = 'INVALID_INPUT_FORMAT',\n\n  // DeepLink operations\n  DEEPLINK_INVALID_STATE = 'DEEPLINK_INVALID_STATE',\n  DEEPLINK_CALLBACK_FAILED = 'DEEPLINK_CALLBACK_FAILED',\n\n  // Storage operations\n  STORAGE_QUOTA_EXCEEDED = 'STORAGE_QUOTA_EXCEEDED',\n  STORAGE_OPERATION_FAILED = 'STORAGE_OPERATION_FAILED',\n\n  // Signer operations\n  SIGNER_CONVERSION_FAILED = 'SIGNER_CONVERSION_FAILED',\n  SIGNER_OPERATION_FAILED = 'SIGNER_OPERATION_FAILED',\n\n  // Permission operations\n  PERMISSION_DENIED = 'PERMISSION_DENIED',\n  OPERATION_NOT_PERMITTED = 'OPERATION_NOT_PERMITTED',\n\n  // Generic errors\n  OPERATION_NOT_SUPPORTED = 'OPERATION_NOT_SUPPORTED',\n  INVALID_PARAMETER = 'INVALID_PARAMETER',\n  INTERNAL_ERROR = 'INTERNAL_ERROR',\n  NETWORK_ERROR = 'NETWORK_ERROR',\n  TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n}\n\n/**\n * Base error class for all IdentityKit errors\n */\nexport class IdentityKitError extends Error {\n  public readonly code: IdentityKitErrorCode;\n  public readonly category: string;\n  public readonly details?: unknown;\n  public readonly cause?: Error;\n\n  constructor(\n    code: IdentityKitErrorCode,\n    message: string,\n    options?: {\n      category?: string;\n      details?: unknown;\n      cause?: Error;\n    }\n  ) {\n    super(message);\n    this.name = 'IdentityKitError';\n    this.code = code;\n    this.category = options?.category || this.inferCategory(code);\n    this.details = options?.details;\n    this.cause = options?.cause;\n\n    // Maintain proper stack trace\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, this.constructor);\n    }\n\n    // Chain the original error stack if available\n    if (options?.cause) {\n      this.stack = `${this.stack}\\nCaused by: ${options.cause.stack}`;\n    }\n  }\n\n  /**\n   * Infer error category from error code\n   */\n  private inferCategory(code: IdentityKitErrorCode): string {\n    if (code.startsWith('AUTH_')) return 'authentication';\n    if (code.startsWith('DID_')) return 'did';\n    if (code.startsWith('VDR_')) return 'vdr';\n    if (code.startsWith('KEY_')) return 'key-management';\n    if (code.startsWith('WEB_')) return 'web';\n    if (code.startsWith('REACT_')) return 'react';\n    if (code.startsWith('CRYPTO_')) return 'crypto';\n    if (code.startsWith('MULTIBASE_')) return 'multibase';\n    if (code.startsWith('SCOPE_') || code.startsWith('VALIDATION_')) return 'validation';\n    if (code.startsWith('DEEPLINK_')) return 'deeplink';\n    if (code.startsWith('STORAGE_')) return 'storage';\n    if (code.startsWith('SIGNER_')) return 'signer';\n    if (code.includes('SIGNING') || code.includes('SIGNATURE')) return 'signing';\n    if (code.includes('NETWORK')) return 'network';\n    if (code.includes('PERMISSION')) return 'permission';\n    return 'general';\n  }\n\n  /**\n   * Convert to a plain object for serialization\n   */\n  toJSON(): {\n    name: string;\n    code: string;\n    category: string;\n    message: string;\n    details?: unknown;\n    stack?: string;\n  } {\n    return {\n      name: this.name,\n      code: this.code,\n      category: this.category,\n      message: this.message,\n      details: this.details,\n      stack: this.stack,\n    };\n  }\n\n  /**\n   * Get a user-friendly error message with suggestions\n   */\n  getUserMessage(): string {\n    const suggestions = this.getSuggestions();\n    let message = this.message;\n\n    if (suggestions.length > 0) {\n      message += '\\n\\nSuggestions:\\n' + suggestions.map(s => `• ${s}`).join('\\n');\n    }\n\n    return message;\n  }\n\n  /**\n   * Get contextual suggestions based on error code\n   */\n  private getSuggestions(): string[] {\n    switch (this.code) {\n      case IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED:\n        return [\n          'Use a modern browser that supports required Web APIs',\n          \"Check if you're running in a browser environment\",\n        ];\n\n      case IdentityKitErrorCode.WEB_STORAGE_NOT_AVAILABLE:\n        return [\n          'Enable localStorage or IndexedDB in your browser',\n          \"Check if you're in private/incognito mode\",\n          'Consider using memory storage as fallback',\n        ];\n\n      case IdentityKitErrorCode.DID_METHOD_NOT_SUPPORTED:\n        return [\n          'Check if the DID method is registered with VDRRegistry',\n          'Verify the DID format is correct',\n        ];\n\n      case IdentityKitErrorCode.VDR_NETWORK_ERROR:\n        return [\n          'Check your network connection',\n          'Verify the RPC URL is correct and accessible',\n          'Check if the VDR service is running',\n        ];\n\n      case IdentityKitErrorCode.KEY_STORAGE_ERROR:\n        return [\n          'Check browser storage permissions',\n          'Verify storage quota is not exceeded',\n          'Try clearing browser storage and retry',\n        ];\n\n      case IdentityKitErrorCode.REACT_NOT_AVAILABLE:\n        return [\n          'Ensure React is properly installed and imported',\n          \"Check if you're using the hook in a React component\",\n        ];\n\n      case IdentityKitErrorCode.CRYPTO_PROVIDER_NOT_FOUND:\n        return [\n          'Check if the key type is supported',\n          'Verify the crypto provider factory configuration',\n        ];\n\n      case IdentityKitErrorCode.MULTIBASE_DECODE_FAILED:\n        return [\n          'Verify the encoded string format is correct',\n          'Check if the multibase prefix is valid',\n          'Ensure the input is not corrupted',\n        ];\n\n      case IdentityKitErrorCode.SCOPE_VALIDATION_FAILED:\n        return [\n          'Check the scope format: address::module::function',\n          'Verify the address format is valid',\n          'Ensure module and function names are correct',\n        ];\n\n      case IdentityKitErrorCode.DEEPLINK_INVALID_STATE:\n        return [\n          'Check if the state parameter matches the stored value',\n          'Verify the callback URL parameters are correct',\n          'Ensure the session storage is available',\n        ];\n\n      case IdentityKitErrorCode.STORAGE_QUOTA_EXCEEDED:\n        return [\n          'Clear unused data from browser storage',\n          'Check available storage quota',\n          'Consider using a different storage strategy',\n        ];\n\n      case IdentityKitErrorCode.SIGNER_CONVERSION_FAILED:\n        return [\n          'Verify the signer implements the required interface',\n          'Check if the key ID is available in the signer',\n          'Ensure the DID account signer is properly configured',\n        ];\n\n      default:\n        return [];\n    }\n  }\n}\n\n/**\n * Factory functions for creating specific error types\n */\n\nexport function createConfigurationError(\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(IdentityKitErrorCode.INVALID_CONFIGURATION, message, {\n    category: 'configuration',\n    details,\n    cause,\n  });\n}\n\nexport function createDIDError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'did',\n    details,\n    cause,\n  });\n}\n\nexport function createVDRError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'vdr',\n    details,\n    cause,\n  });\n}\n\nexport function createKeyManagementError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'key-management',\n    details,\n    cause,\n  });\n}\n\nexport function createAuthenticationError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'authentication',\n    details,\n    cause,\n  });\n}\n\nexport function createWebError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'web',\n    details,\n    cause,\n  });\n}\n\nexport function createReactError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'react',\n    details,\n    cause,\n  });\n}\n\nexport function createCryptoError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'crypto',\n    details,\n    cause,\n  });\n}\n\nexport function createMultibaseError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'multibase',\n    details,\n    cause,\n  });\n}\n\nexport function createStorageError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'storage',\n    details,\n    cause,\n  });\n}\n\nexport function createValidationError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'validation',\n    details,\n    cause,\n  });\n}\n\nexport function createSignerError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'signer',\n    details,\n    cause,\n  });\n}\n\nexport function createDeepLinkError(\n  code: IdentityKitErrorCode,\n  message: string,\n  details?: unknown,\n  cause?: Error\n): IdentityKitError {\n  return new IdentityKitError(code, message, {\n    category: 'deeplink',\n    details,\n    cause,\n  });\n}\n\n/**\n * Wrap unknown errors into IdentityKitError\n */\nexport function wrapUnknownError(\n  error: unknown,\n  context: string,\n  code: IdentityKitErrorCode = IdentityKitErrorCode.INTERNAL_ERROR\n): IdentityKitError {\n  const originalError = error instanceof Error ? error : new Error(String(error));\n\n  return new IdentityKitError(code, `${context}: ${originalError.message}`, {\n    cause: originalError,\n    details: { context },\n  });\n}\n\n/**\n * Type guard to check if an error is an IdentityKitError\n */\nexport function isIdentityKitError(error: unknown): error is IdentityKitError {\n  return error instanceof IdentityKitError;\n}\n\n/**\n * Legacy compatibility: map old AuthErrorCode to new IdentityKitErrorCode\n */\nexport const AuthErrorCodeMapping = {\n  INVALID_HEADER: IdentityKitErrorCode.AUTH_INVALID_HEADER,\n  INVALID_BASE64: IdentityKitErrorCode.AUTH_INVALID_BASE64,\n  INVALID_JSON: IdentityKitErrorCode.AUTH_INVALID_JSON,\n  MISSING_SIGNATURE: IdentityKitErrorCode.AUTH_MISSING_SIGNATURE,\n  TIMESTAMP_OUT_OF_WINDOW: IdentityKitErrorCode.AUTH_TIMESTAMP_OUT_OF_WINDOW,\n  NONCE_REPLAYED: IdentityKitErrorCode.AUTH_NONCE_REPLAYED,\n  SIGNATURE_VERIFICATION_FAILED: IdentityKitErrorCode.SIGNATURE_VERIFICATION_FAILED,\n  DID_DOCUMENT_NOT_FOUND: IdentityKitErrorCode.AUTH_DID_DOCUMENT_NOT_FOUND,\n  VERIFICATION_METHOD_NOT_FOUND: IdentityKitErrorCode.AUTH_VERIFICATION_METHOD_NOT_FOUND,\n  INVALID_PUBLIC_KEY: IdentityKitErrorCode.AUTH_INVALID_PUBLIC_KEY,\n  DID_MISMATCH: IdentityKitErrorCode.AUTH_DID_MISMATCH,\n} as const;\n","import { SignatureScheme } from '@roochnetwork/rooch-sdk';\nimport { IdentityKitErrorCode, createValidationError } from '../errors';\n\n// Cryptographic types and constants\n\n/**\n * Readable enum for supported verification key suites.\n *\n * NOTE: Replaces the old `KEY_TYPE` const object. Use this in new code to\n * improve clarity. Values keep the same long-form strings to avoid breaking\n * existing behavior when serialized into DID Documents.\n */\nexport enum KeyType {\n  ED25519 = 'Ed25519VerificationKey2020',\n  SECP256K1 = 'EcdsaSecp256k1VerificationKey2019',\n  ECDSAR1 = 'EcdsaSecp256r1VerificationKey2019',\n}\n\n/**\n * @deprecated Will be removed in the next major version. Use `KeyType` enum instead.\n */\nexport const KEY_TYPE = KeyType;\n\n/**\n * Type guard to check if a string is a valid KeyType\n */\nexport function isKeyType(value: string): value is KeyType {\n  return Object.values(KeyType).includes(value as KeyType);\n}\n\n/**\n * Convert a string to KeyType, with runtime validation\n * @throws Error if the string is not a valid KeyType\n */\nexport function toKeyType(value: string): KeyType {\n  if (isKeyType(value)) {\n    return value;\n  }\n  throw createValidationError(\n    IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n    `Invalid key type: ${value}`,\n    { value, supportedTypes: Object.values(KeyType) }\n  );\n}\n\nexport function roochSignatureSchemeToKeyType(scheme: SignatureScheme): KeyType {\n  if (scheme === 'Secp256k1') {\n    return KeyType.SECP256K1;\n  } else if (scheme === 'ED25519') {\n    return KeyType.ED25519;\n  } else if (scheme === 'EcdsaR1') {\n    return KeyType.ECDSAR1;\n  }\n  throw createValidationError(\n    IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n    `Unsupported Rooch signature scheme: ${scheme}`,\n    { scheme, supportedSchemes: ['Secp256k1', 'ED25519', 'EcdsaR1'] }\n  );\n}\n\nexport function keyTypeToRoochSignatureScheme(keyType: KeyType): SignatureScheme {\n  if (keyType === KeyType.SECP256K1) {\n    return 'Secp256k1';\n  } else if (keyType === KeyType.ED25519) {\n    return 'ED25519';\n  } else if (keyType === KeyType.ECDSAR1) {\n    return 'EcdsaR1';\n  }\n  throw createValidationError(\n    IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n    `Unsupported key type: ${keyType}`,\n    { keyType, supportedTypes: Object.values(KeyType) }\n  );\n}\n\n/**\n * https://www.w3.org/TR/webauthn-2/#typedefdef-cosealgorithmidentifier\n * Convert a WebAuthn public key algorithm to KeyType, with runtime validation\n * @throws Error if the string is not a valid KeyType\n */\nexport function algorithmToKeyType(algorithm: number): KeyType | undefined {\n  switch (algorithm) {\n    case -8:\n      return KeyType.ED25519;\n    case -7:\n      return KeyType.ECDSAR1;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Convert a KeyType to WebAuthn algorithm identifier\n */\nexport function keyTypeToAlgorithm(keyType: KeyType): number | undefined {\n  switch (keyType) {\n    case KeyType.ED25519:\n      return -8;\n    case KeyType.ECDSAR1:\n      return -7;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Get list of supported WebAuthn algorithms\n */\nexport function getSupportedAlgorithms(): number[] {\n  return [-8, -7];\n}\n\n/**\n * Type that represents either a KeyType or a string\n * Useful for functions that need to accept both strict KeyType and general string values\n */\nexport type KeyTypeInput = KeyType | string;\n\n/**\n * Represents the information needed to create a new operational key.\n */\nexport interface OperationalKeyInfo {\n  idFragment?: string; // Optional fragment for the key id (e.g., 'key-2'). If not provided, one might be generated.\n  type: string; // Cryptographic suite of the key, e.g., Ed25519VerificationKey2020\n  publicKeyMaterial: Uint8Array | JsonWebKey; // The public key material\n  controller?: string; // Defaults to the master DID if not provided\n}\n","import { DIDDocument } from '../types';\nimport { DIDDocumentCache } from './index';\n\n/**\n * A lightweight in-memory LRU cache implementation for DID Documents.\n * It is intentionally dependency-free so that the SDK does not pull in\n * additional packages by default. You can replace it with your own\n * implementation (Redis, IndexedDB, etc.) by implementing the\n * `DIDDocumentCache` interface and providing it to `VDRRegistry.setCache()`.\n */\nexport class InMemoryLRUDIDDocumentCache implements DIDDocumentCache {\n  private readonly capacity: number;\n  private readonly map: Map<string, DIDDocument | null>;\n\n  constructor(maxEntries = 1000) {\n    this.capacity = maxEntries;\n    this.map = new Map<string, DIDDocument | null>();\n  }\n\n  get(did: string): DIDDocument | null | undefined {\n    if (!this.map.has(did)) return undefined;\n    const value = this.map.get(did) ?? null;\n    // Refresh the recently used key to the end.\n    this.map.delete(did);\n    this.map.set(did, value);\n    return value;\n  }\n\n  set(did: string, doc: DIDDocument | null): void {\n    if (this.map.has(did)) {\n      this.map.delete(did);\n    } else if (this.map.size >= this.capacity) {\n      // Evict the least-recently-used entry (Map iteration order is insertion order).\n      const lruKey = this.map.keys().next().value;\n      if (lruKey !== undefined) {\n        this.map.delete(lruKey);\n      }\n    }\n    this.map.set(did, doc);\n  }\n\n  has(did: string): boolean {\n    return this.map.has(did);\n  }\n\n  delete(did: string): void {\n    this.map.delete(did);\n  }\n\n  clear(): void {\n    this.map.clear();\n  }\n}\n","import { DIDDocument, DIDResolver } from '../types';\nimport { DIDDocumentCache } from '../cache';\nimport {\n  VDRInterface,\n  DIDCreationRequest,\n  DIDCreationResult,\n  CADOPCreationRequest,\n  CADOPControllerCreationRequest,\n} from './types';\n\nimport { InMemoryLRUDIDDocumentCache } from '../cache/InMemoryLRUDIDDocumentCache';\nimport { IdentityKitErrorCode, createVDRError } from '../errors';\n\n/**\n * Global registry for VDR (Verifiable Data Registry) implementations.\n * This singleton manages all registered VDRs and maintains a DID Document cache.\n */\nexport class VDRRegistry implements DIDResolver {\n  private static instance: VDRRegistry;\n  private vdrs: Map<string, VDRInterface> = new Map();\n\n  private cache: DIDDocumentCache;\n\n  private constructor() {\n    // Use the default in-memory cache unless overridden by the developer.\n    this.cache = new InMemoryLRUDIDDocumentCache();\n  }\n\n  static getInstance(): VDRRegistry {\n    if (!this.instance) {\n      this.instance = new VDRRegistry();\n    }\n    return this.instance;\n  }\n\n  /** Register a VDR implementation for its DID method (e.g., 'key', 'rooch'). */\n  registerVDR(vdr: VDRInterface) {\n    this.vdrs.set(vdr.getMethod(), vdr);\n  }\n\n  /** Retrieve a previously registered VDR implementation by its method. */\n  getVDR(method: string): VDRInterface | undefined {\n    return this.vdrs.get(method);\n  }\n\n  /**\n   * Override the default cache implementation.\n   * This allows developers to provide their own cache (e.g., Redis, browser storage).\n   */\n  setCache(cache: DIDDocumentCache) {\n    this.cache = cache;\n  }\n\n  /** Returns the currently configured cache instance. */\n  getCache(): DIDDocumentCache {\n    return this.cache;\n  }\n\n  async resolveDID(did: string, options?: { forceRefresh?: boolean }): Promise<DIDDocument | null> {\n    const method = did.split(':')[1];\n    const vdr = this.vdrs.get(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for method: ${method}`,\n        { method, availableMethods: Array.from(this.vdrs.keys()) }\n      );\n    }\n\n    // Attempt to serve from cache if allowed.\n    if (!options?.forceRefresh) {\n      const cached = this.cache.get(did);\n      if (cached !== undefined) {\n        return cached;\n      }\n    }\n\n    const resolved = await vdr.resolve(did);\n    // Cache the resolution result (including null for negative caching).\n    this.cache.set(did, resolved);\n    return resolved;\n  }\n\n  async createDID(\n    method: string,\n    creationRequest: DIDCreationRequest,\n    options?: Record<string, any>\n  ): Promise<DIDCreationResult> {\n    const vdr = this.vdrs.get(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for method: ${method}`,\n        { method, availableMethods: Array.from(this.vdrs.keys()) }\n      );\n    }\n    const result = await vdr.create(creationRequest, options);\n    if (result.success && result.didDocument) {\n      this.cache.set(result.didDocument.id, result.didDocument);\n    }\n    return result;\n  }\n\n  async createDIDViaCADOP(\n    method: string,\n    creationRequest: CADOPCreationRequest,\n    options?: Record<string, any>\n  ): Promise<DIDCreationResult> {\n    const vdr = this.vdrs.get(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for method: ${method}`,\n        { method, availableMethods: Array.from(this.vdrs.keys()) }\n      );\n    }\n    const result = await vdr.createViaCADOP(creationRequest, options);\n    if (result.success && result.didDocument) {\n      this.cache.set(result.didDocument.id, result.didDocument);\n    }\n    return result;\n  }\n\n  async createDIDViaCADOPWithController(\n    method: string,\n    creationRequest: CADOPControllerCreationRequest,\n    options?: Record<string, any>\n  ): Promise<DIDCreationResult> {\n    const vdr = this.vdrs.get(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for method: ${method}`,\n        { method, availableMethods: Array.from(this.vdrs.keys()) }\n      );\n    }\n    const result = await vdr.createViaCADOPWithController(creationRequest, options);\n    if (result.success && result.didDocument) {\n      this.cache.set(result.didDocument.id, result.didDocument);\n    }\n    return result;\n  }\n\n  async exists(did: string): Promise<boolean> {\n    const method = did.split(':')[1];\n    const vdr = this.vdrs.get(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for method: ${method}`,\n        { method, availableMethods: Array.from(this.vdrs.keys()) }\n      );\n    }\n\n    // If we have a positive cache entry, short-circuit the call.\n    if (this.cache.has(did)) {\n      const doc = this.cache.get(did);\n      return doc !== null;\n    }\n\n    const exists = await vdr.exists(did);\n    // We don't cache the existence check result here to avoid stale data.\n    return exists;\n  }\n}\n","import { base58btc } from 'multiformats/bases/base58';\nimport { base64pad, base64, base64url, base64urlpad } from 'multiformats/bases/base64';\nimport { base16 } from 'multiformats/bases/base16';\nimport { bytesToString, stringToBytes } from '../utils/bytes';\nimport { IdentityKitErrorCode, createMultibaseError } from '../errors';\n\n/**\n * Supported multibase names – use these with the generic `encode()` API.\n */\nexport type MultibaseName =\n  | 'base58btc'\n  | 'base64pad'\n  | 'base64'\n  | 'base64url'\n  | 'base64urlpad'\n  | 'base16';\n\ntype MultibaseCodecImpl = {\n  encode: (bytes: Uint8Array) => string;\n  decode: (encoded: string) => Uint8Array;\n};\n\nconst ENCODER_MAP: Record<MultibaseName, MultibaseCodecImpl> = {\n  base58btc,\n  base64pad,\n  base64,\n  base64url,\n  base64urlpad,\n  base16,\n};\n\n/**\n * Base multibase codec implementation\n * Provides basic encoding/decoding functionality without key type awareness\n */\nexport class MultibaseCodec {\n  /**\n   * Generic encode\n   * Example: `MultibaseCodec.encode(bytes, 'base64url')`\n   */\n  static encode(data: Uint8Array | string, base: MultibaseName): string {\n    const encoder = ENCODER_MAP[base];\n    if (!encoder) {\n      throw createMultibaseError(\n        IdentityKitErrorCode.MULTIBASE_ENCODE_FAILED,\n        `Unsupported multibase: ${base}`,\n        { base, supportedBases: Object.keys(ENCODER_MAP) }\n      );\n    }\n    const bytes = typeof data === 'string' ? stringToBytes(data) : data;\n    return encoder.encode(bytes);\n  }\n\n  /**\n   * Encode bytes to base58btc format\n   * @param bytes The bytes to encode\n   * @returns base58btc encoded string with 'z' prefix\n   */\n  static encodeBase58btc(bytes: Uint8Array): string {\n    return this.encode(bytes, 'base58btc');\n  }\n\n  /**\n   * Encode bytes to base64pad format\n   * @param bytes The bytes to encode\n   * @returns base64pad encoded string with 'M' prefix\n   */\n  static encodeBase64pad(data: Uint8Array | string): string {\n    return this.encode(data, 'base64pad');\n  }\n\n  /**\n   * Encode bytes to base16 (hex) format\n   * @param bytes The bytes to encode\n   * @returns base16 encoded string with 'f' prefix\n   */\n  static encodeBase16(bytes: Uint8Array): string {\n    return this.encode(bytes, 'base16');\n  }\n\n  /**\n   * Encode bytes to base64 format\n   * @param bytes The bytes to encode\n   * @returns base64 encoded string\n   */\n  static encodeBase64(data: Uint8Array | string): string {\n    return this.encode(data, 'base64');\n  }\n\n  /**\n   * Encode bytes to base64url format (RFC4648 URL-safe, no padding)\n   * @param bytes The bytes to encode\n   * @returns base64url encoded string with 'u' prefix\n   */\n  static encodeBase64url(data: Uint8Array | string): string {\n    return this.encode(data, 'base64url');\n  }\n\n  /**\n   * Encode bytes to base64urlpad format (URL-safe with padding)\n   * @param bytes The bytes to encode\n   * @returns base64urlpad encoded string with 'U' prefix\n   */\n  static encodeBase64urlpad(data: Uint8Array | string): string {\n    return this.encode(data, 'base64urlpad');\n  }\n\n  /**\n   * Decode base58btc string to bytes\n   * @param encoded The base58btc encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase58btc(encoded: string): Uint8Array {\n    return base58btc.decode(encoded);\n  }\n\n  /**\n   * Decode base64pad string to bytes\n   * @param encoded The base64pad encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase64pad(encoded: string): Uint8Array {\n    return base64pad.decode(encoded);\n  }\n\n  /**\n   * Decode base16 string to bytes\n   * @param encoded The base16 encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase16(encoded: string): Uint8Array {\n    return base16.decode(encoded);\n  }\n\n  /**\n   * Decode base64 string to bytes\n   * @param encoded The base64 encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase64(encoded: string): Uint8Array {\n    return base64.decode(encoded);\n  }\n\n  /**\n   * Decode base64url string to bytes\n   * @param encoded The base64url encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase64url(encoded: string): Uint8Array {\n    return base64url.decode(encoded);\n  }\n\n  /**\n   * Decode base64url string to string\n   * @param encoded The base64url encoded string\n   * @returns decoded string\n   */\n  static decodeBase64urlToString(encoded: string): string {\n    return bytesToString(this.decodeBase64url(encoded));\n  }\n\n  /**\n   * Decode base64urlpad string to bytes\n   * @param encoded The base64urlpad encoded string\n   * @returns decoded bytes\n   */\n  static decodeBase64urlpad(encoded: string): Uint8Array {\n    return base64urlpad.decode(encoded);\n  }\n\n  /**\n   * Decode base64urlpad string to string\n   * @param encoded The base64urlpad encoded string\n   * @returns decoded string\n   */\n  static decodeBase64urlpadToString(encoded: string): string {\n    return bytesToString(this.decodeBase64urlpad(encoded));\n  }\n\n  /**\n   * Decode multibase encoded string to bytes\n   * After multiformats v9, there is no longer a single \"universal base\" object;\n   * the official recommendation is to manually dispatch prefixes between the few *.decoder objects you use.\n   * @param encoded The multibase encoded string\n   * @returns decoded bytes\n   */\n  static decode(encoded: string): Uint8Array {\n    // Multibase prefix is always the first character\n    const prefix = encoded[0];\n    switch (prefix) {\n      case 'z': // base58btc\n        return base58btc.decode(encoded);\n      case 'M': // base64pad (RFC4648 with padding)\n        return base64pad.decode(encoded);\n      case 'f': // base16 (hex, lowercase)\n        return base16.decode(encoded);\n      case 'm': // base64 (no padding)\n        return base64.decode(encoded);\n      case 'u': // base64url (no padding)\n        return base64url.decode(encoded);\n      case 'U': // base64urlpad (with padding)\n        return base64urlpad.decode(encoded);\n      default:\n        throw createMultibaseError(\n          IdentityKitErrorCode.MULTIBASE_DECODE_FAILED,\n          `Unsupported multibase prefix: ${prefix}`,\n          { prefix, supportedPrefixes: ['z', 'M', 'm', 'u', 'U', 'f'] }\n        );\n    }\n  }\n}\n","import { IdentityKitErrorCode, createValidationError } from '../errors';\n\nexport function stringToBytes(str: string): Uint8Array {\n  if (typeof TextEncoder !== 'undefined') {\n    return new TextEncoder().encode(str);\n  }\n  // Node.js < 16 fallback using Buffer\n  if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n    return Uint8Array.from(Buffer.from(str, 'utf-8'));\n  }\n  throw createValidationError(\n    IdentityKitErrorCode.ENVIRONMENT_NOT_SUPPORTED,\n    'No TextEncoder or Buffer available in this environment.',\n    {\n      environment: typeof globalThis,\n      textEncoderAvailable: typeof TextEncoder !== 'undefined',\n      bufferAvailable: typeof Buffer !== 'undefined',\n    }\n  );\n}\n\nexport function bytesToString(bytes: Uint8Array): string {\n  if (typeof TextDecoder !== 'undefined') {\n    return new TextDecoder('utf-8').decode(bytes);\n  }\n  // Node.js < 16 fallback using Buffer\n  if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n    return Buffer.from(bytes).toString('utf-8');\n  }\n  throw createValidationError(\n    IdentityKitErrorCode.ENVIRONMENT_NOT_SUPPORTED,\n    'No TextDecoder or Buffer available in this environment.',\n    {\n      environment: typeof globalThis,\n      textDecoderAvailable: typeof TextDecoder !== 'undefined',\n      bufferAvailable: typeof Buffer !== 'undefined',\n    }\n  );\n}\n\nexport function base64urlToBytes(base64url: string): Uint8Array {\n  // Add padding if needed\n  const padding = base64url.length % 4;\n  const paddedBase64url = base64url + '='.repeat(padding === 0 ? 0 : 4 - padding);\n\n  // Convert base64url to base64\n  const base64 = paddedBase64url.replace(/-/g, '+').replace(/_/g, '/');\n\n  // Decode to bytes\n  const binaryString = atob(base64);\n  const bytes = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    bytes[i] = binaryString.charCodeAt(i);\n  }\n  return bytes;\n}\n\nexport const Bytes = {\n  stringToBytes,\n  bytesToString,\n  base64urlToBytes,\n};\n\nexport default Bytes;\n","import { KeyType, KEY_TYPE } from '../types/crypto';\nimport { MultibaseCodec } from './base';\nimport { IdentityKitErrorCode, createMultibaseError, createValidationError } from '../errors';\n\n/**\n * Key multibase codec implementation\n * Handles encoding/decoding of cryptographic keys with type information\n */\nexport class KeyMultibaseCodec {\n  private static readonly ED25519_PREFIX = new Uint8Array([0xed, 0x01]);\n  private static readonly SECP256K1_PREFIX = new Uint8Array([0xe7, 0x01]);\n  private static readonly ECDSA_R1_PREFIX = new Uint8Array([0x12, 0x00]);\n  private static readonly ED25519_KEY_LENGTH = 32;\n  private static readonly SECP256K1_KEY_LENGTH = 33;\n  private static readonly ECDSA_R1_KEY_LENGTH = 33;\n\n  /**\n   * Encode public key with multicodec prefix\n   * @param bytes The public key bytes\n   * @param keyType The key type\n   * @returns multibase encoded string\n   */\n  static encodeWithType(bytes: Uint8Array, keyType: KeyType): string {\n    // Validate key length\n    const expectedLength = this.getExpectedKeyLength(keyType);\n    if (bytes.length !== expectedLength) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        `Invalid key length for ${keyType}. Expected ${expectedLength} bytes, got ${bytes.length}`,\n        { keyType, expectedLength, actualLength: bytes.length }\n      );\n    }\n\n    const prefix = this.getMulticodecPrefix(keyType);\n    const prefixedKey = this.concatenateBytes(prefix, bytes);\n    return MultibaseCodec.encodeBase58btc(prefixedKey);\n  }\n\n  /**\n   * Decode multibase encoded key\n   * @param encoded The multibase encoded string\n   * @returns The key type and public key bytes\n   */\n  static decodeWithType(encoded: string): { keyType: KeyType; bytes: Uint8Array } {\n    try {\n      const decoded = MultibaseCodec.decodeBase58btc(encoded);\n      if (decoded.length < 2) {\n        throw createMultibaseError(\n          IdentityKitErrorCode.MULTIBASE_DECODE_FAILED,\n          'Invalid key format: too short',\n          { encoded, minimumLength: 2, actualLength: decoded.length }\n        );\n      }\n\n      const keyType = this.extractKeyType(decoded);\n      const bytes = this.extractBytes(decoded);\n\n      // Validate key length\n      const expectedLength = this.getExpectedKeyLength(keyType);\n      if (bytes.length !== expectedLength) {\n        throw createValidationError(\n          IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n          `Invalid key length for ${keyType}. Expected ${expectedLength} bytes, got ${bytes.length}`,\n          { keyType, expectedLength, actualLength: bytes.length }\n        );\n      }\n\n      return { keyType, bytes };\n    } catch (error) {\n      if (error instanceof Error && error.message === 'Non-base58btc character') {\n        throw createMultibaseError(\n          IdentityKitErrorCode.MULTIBASE_DECODE_FAILED,\n          'Invalid multibase format',\n          { encoded }\n        );\n      }\n      throw error;\n    }\n  }\n\n  private static getMulticodecPrefix(keyType: KeyType): Uint8Array {\n    switch (keyType) {\n      case KEY_TYPE.ED25519:\n        return this.ED25519_PREFIX;\n      case KEY_TYPE.SECP256K1:\n        return this.SECP256K1_PREFIX;\n      case KEY_TYPE.ECDSAR1:\n        return this.ECDSA_R1_PREFIX;\n      default:\n        throw createValidationError(\n          IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n          `Unsupported key type: ${keyType}`,\n          { keyType, supportedTypes: [KEY_TYPE.ED25519, KEY_TYPE.SECP256K1, KEY_TYPE.ECDSAR1] }\n        );\n    }\n  }\n\n  private static concatenateBytes(a: Uint8Array, b: Uint8Array): Uint8Array {\n    const result = new Uint8Array(a.length + b.length);\n    result.set(a);\n    result.set(b, a.length);\n    return result;\n  }\n\n  private static extractKeyType(prefixedBytes: Uint8Array): KeyType {\n    if (prefixedBytes[0] === 0xed && prefixedBytes[1] === 0x01) {\n      return KEY_TYPE.ED25519;\n    } else if (prefixedBytes[0] === 0xe7 && prefixedBytes[1] === 0x01) {\n      return KEY_TYPE.SECP256K1;\n    } else if (prefixedBytes[0] === 0x12 && prefixedBytes[1] === 0x00) {\n      return KEY_TYPE.ECDSAR1;\n    }\n    throw createMultibaseError(\n      IdentityKitErrorCode.MULTIBASE_DECODE_FAILED,\n      'Unknown key type prefix',\n      { prefix: Array.from(prefixedBytes.slice(0, 2)) }\n    );\n  }\n\n  private static extractBytes(prefixedBytes: Uint8Array): Uint8Array {\n    return prefixedBytes.slice(2);\n  }\n\n  private static getExpectedKeyLength(keyType: KeyType): number {\n    switch (keyType) {\n      case KEY_TYPE.ED25519:\n        return this.ED25519_KEY_LENGTH;\n      case KEY_TYPE.SECP256K1:\n        return this.SECP256K1_KEY_LENGTH;\n      case KEY_TYPE.ECDSAR1:\n        return this.ECDSA_R1_KEY_LENGTH;\n      default:\n        throw createValidationError(\n          IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n          `Unsupported key type: ${keyType}`,\n          { keyType, supportedTypes: [KEY_TYPE.ED25519, KEY_TYPE.SECP256K1, KEY_TYPE.ECDSAR1] }\n        );\n    }\n  }\n}\n","import { KeyType } from '../types/crypto';\nimport { MultibaseCodec } from './base';\nimport { KeyMultibaseCodec } from './key';\nimport { IdentityKitErrorCode, createDIDError } from '../errors';\n\n/**\n * DID key codec implementation\n * Handles encoding/decoding of did:key identifiers\n */\nexport class DidKeyCodec {\n  /**\n   * Generate did:key from public key\n   * @param publicKey The public key bytes\n   * @param keyType The key type\n   * @returns did:key identifier\n   */\n  static generateDidKey(publicKey: Uint8Array, keyType: KeyType): string {\n    // KeyMultibaseCodec.encodeWithType will validate key length\n    const multibase = KeyMultibaseCodec.encodeWithType(publicKey, keyType);\n    return `did:key:${multibase}`;\n  }\n\n  /**\n   * Parse did:key to get key type and public key\n   * @param didKey The did:key identifier\n   * @returns The key type and public key bytes\n   */\n  static parseDidKey(didKey: string): { keyType: KeyType; publicKey: Uint8Array } {\n    if (!didKey.startsWith('did:key:')) {\n      throw createDIDError(IdentityKitErrorCode.DID_INVALID_FORMAT, 'Invalid did:key format', {\n        didKey,\n        expectedPrefix: 'did:key:',\n      });\n    }\n    const multibase = didKey.substring(8);\n    const { keyType, bytes } = KeyMultibaseCodec.decodeWithType(multibase);\n    return { keyType, publicKey: bytes };\n  }\n}\n","/**\n * DID utility helpers (method, identifier & fragment parsing)\n * Used across SDK layers (VDR, Signer, KeyManager, etc.)\n */\n\nimport { IdentityKitErrorCode, createDIDError } from '../errors';\n\n/**\n * Parsed DID parts\n */\nexport interface ParsedDID {\n  /** DID method, e.g. 'key', 'rooch' */\n  method: string;\n  /** Unique identifier part (method-specific id, without fragment) */\n  identifier: string;\n  /** Optional fragment (ver. method / service id) */\n  fragment?: string;\n}\n\n/**\n * Parse a DID or DID-URL into its components.\n *\n * @param did Full DID string: `did:<method>:<identifier>[#fragment]`\n * @throws Error if input does not start with `did:` or lacks method / identifier parts.\n */\nexport function parseDid(did: string): ParsedDID {\n  if (!did.startsWith('did:')) {\n    throw createDIDError(IdentityKitErrorCode.DID_INVALID_FORMAT, `Invalid DID: ${did}`, {\n      did,\n      reason: 'DID must start with \"did:\"',\n    });\n  }\n\n  // Strip leading `did:` and split once by ':'\n  const afterPrefix = did.slice(4);\n  const methodEnd = afterPrefix.indexOf(':');\n  if (methodEnd === -1) {\n    throw createDIDError(\n      IdentityKitErrorCode.DID_INVALID_FORMAT,\n      `Invalid DID – missing method/identifier separator: ${did}`,\n      { did, reason: 'Missing method/identifier separator \":\"' }\n    );\n  }\n  const method = afterPrefix.slice(0, methodEnd);\n  const idPlusFrag = afterPrefix.slice(methodEnd + 1);\n  if (!method || !idPlusFrag) {\n    throw createDIDError(IdentityKitErrorCode.DID_INVALID_FORMAT, `Invalid DID: ${did}`, {\n      did,\n      reason: 'Empty method or identifier',\n    });\n  }\n\n  const hashIdx = idPlusFrag.indexOf('#');\n  return hashIdx === -1\n    ? { method, identifier: idPlusFrag }\n    : {\n        method,\n        identifier: idPlusFrag.slice(0, hashIdx),\n        fragment: idPlusFrag.slice(hashIdx + 1),\n      };\n}\n\n/** Get DID method string */\nexport function extractMethod(did: string): string {\n  return parseDid(did).method;\n}\n\n/** Get method-specific identifier (without fragment) */\nexport function extractIdentifier(did: string): string {\n  return parseDid(did).identifier;\n}\n\n/**\n * Extract the fragment from a DID URL or any string containing `#`.\n * Throws an error if no fragment present.\n */\nexport function extractFragment(idOrDid: string): string {\n  const idx = idOrDid.indexOf('#');\n  if (idx === -1) {\n    throw createDIDError(\n      IdentityKitErrorCode.DID_INVALID_FORMAT,\n      `No fragment found in ${idOrDid}`,\n      { idOrDid, reason: 'Missing fragment separator \"#\"' }\n    );\n  }\n  return idOrDid.slice(idx + 1);\n}\n\n/** Alias kept for back-compat with existing imports */\nexport const extractFragmentFromId = extractFragment;\n\n/** Build a canonical DID string from method & identifier */\nexport function buildDid(method: string, identifier: string): string {\n  return `did:${method}:${identifier}`;\n}\n\n/**\n * Compare two DIDs ignoring their fragments.\n */\nexport function sameDid(a: string, b: string): boolean {\n  const pa = parseDid(a);\n  const pb = parseDid(b);\n  return pa.method === pb.method && pa.identifier === pb.identifier;\n}\n\n/**\n * Return the canonical DID (strip any `#fragment`).\n */\nexport function getDidWithoutFragment(did: string): string {\n  const { method, identifier } = parseDid(did);\n  return buildDid(method, identifier);\n}\n","/* eslint-disable no-console */\n/*\n * Lightweight environment-agnostic debug logger.\n *\n * ‑ Works in both Node.js and browser.\n * ‑ Supports level filtering (debug | info | warn | error | silent).\n * ‑ Namespaced: each module/class can request its own logger via DebugLogger.get(\"MyModule\").\n * ‑ Global level can be controlled at runtime via DebugLogger.setGlobalLevel() *or*\n *   environment variable NUWA_LOG_LEVEL (node) / window.__NUWA_LOG_LEVEL__ (browser).\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n  debug: 10,\n  info: 20,\n  warn: 30,\n  error: 40,\n  silent: 50,\n};\n\nfunction detectInitialGlobalLevel(): LogLevel {\n  // Node.js: use process.env if available\n  if (typeof process !== 'undefined' && (process as any).env) {\n    const envLevel = (process as any).env.NUWA_LOG_LEVEL as string | undefined;\n    if (envLevel && envLevel in LEVEL_ORDER) return envLevel as LogLevel;\n  }\n  // Browser: allow runtime override via global variable\n  if (typeof window !== 'undefined' && (window as any).__NUWA_LOG_LEVEL__) {\n    const envLevel = (window as any).__NUWA_LOG_LEVEL__ as string;\n    if (envLevel && envLevel in LEVEL_ORDER) return envLevel as LogLevel;\n  }\n  return 'info';\n}\n\nexport class DebugLogger {\n  // ---------------------------------------------------------------------------\n  // Static section\n  // ---------------------------------------------------------------------------\n  private static globalLevel: LogLevel = detectInitialGlobalLevel();\n  private static loggers = new Map<string, DebugLogger>();\n  private static defaultNamespace = 'global';\n\n  /** Acquire (or create) a logger for the given namespace. */\n  static get(namespace: string): DebugLogger {\n    if (!DebugLogger.loggers.has(namespace)) {\n      DebugLogger.loggers.set(namespace, new DebugLogger(namespace));\n    }\n    return DebugLogger.loggers.get(namespace)!;\n  }\n\n  /** Override global log level at runtime. */\n  static setGlobalLevel(level: LogLevel): void {\n    DebugLogger.globalLevel = level;\n    // Propagate to existing instances unless they explicitly override.\n    for (const logger of DebugLogger.loggers.values()) {\n      if (!logger.levelOverridden) {\n        logger.level = level;\n      }\n    }\n  }\n\n  /** Read current global level. */\n  static getGlobalLevel(): LogLevel {\n    return DebugLogger.globalLevel;\n  }\n\n  /** Set default namespace used by static convenience methods. */\n  static setDefaultNamespace(namespace: string): void {\n    DebugLogger.defaultNamespace = namespace;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Static convenience logging methods\n  // ---------------------------------------------------------------------------\n  /**\n   * Log using the default namespace. Useful when callers don't need per-module loggers.\n   * Example: DebugLogger.debug('hello')\n   */\n  static debug(...args: unknown[]): void {\n    DebugLogger.get(DebugLogger.defaultNamespace).debug(...args);\n  }\n\n  static info(...args: unknown[]): void {\n    DebugLogger.get(DebugLogger.defaultNamespace).info(...args);\n  }\n\n  static warn(...args: unknown[]): void {\n    DebugLogger.get(DebugLogger.defaultNamespace).warn(...args);\n  }\n\n  static error(...args: unknown[]): void {\n    DebugLogger.get(DebugLogger.defaultNamespace).error(...args);\n  }\n\n  // ---------------------------------------------------------------------------\n  // Instance section\n  // ---------------------------------------------------------------------------\n  private level: LogLevel;\n  private levelOverridden = false;\n\n  private constructor(private namespace: string) {\n    this.level = DebugLogger.globalLevel;\n  }\n\n  /** Override level for this logger only. */\n  setLevel(level: LogLevel): void {\n    this.level = level;\n    this.levelOverridden = true;\n  }\n\n  // -------------------------------------------------------\n  // Logging helpers\n  // -------------------------------------------------------\n  debug(...args: unknown[]): void {\n    this._log('debug', args);\n  }\n\n  info(...args: unknown[]): void {\n    this._log('info', args);\n  }\n\n  warn(...args: unknown[]): void {\n    this._log('warn', args);\n  }\n\n  error(...args: unknown[]): void {\n    this._log('error', args);\n  }\n\n  // prettier-ignore\n  private _log(level: LogLevel, args: unknown[]): void {\n    if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) {\n      return; // filtered out\n    }\n\n    const prefix = `[${this.namespace}]`;\n\n    // Colorize in browser / modern terminal if desired; keep simple for now.\n    switch (level) {\n      case 'debug':\n        console.debug(prefix, ...args);\n        break;\n      case 'info':\n        console.info(prefix, ...args);\n        break;\n      case 'warn':\n        console.warn(prefix, ...args);\n        break;\n      case 'error':\n        console.error(prefix, ...args);\n        break;\n    }\n  }\n}\n","import {\n  DIDDocument,\n  VerificationMethod,\n  VerificationRelationship,\n  ServiceEndpoint,\n} from '../types/did';\nimport {\n  DIDCreationRequest,\n  DIDCreationResult,\n  CADOPCreationRequest,\n  CADOPControllerCreationRequest,\n  VDRInterface,\n} from './types';\nimport { parseDid } from '../utils/did';\nimport { DebugLogger } from '../utils/DebugLogger';\nimport {\n  IdentityKitErrorCode,\n  createDIDError,\n  createVDRError,\n  createValidationError,\n} from '../errors';\n\n// Unified logger for AbstractVDR\nconst logger = DebugLogger.get('AbstractVDR');\n\n/**\n * Abstract base class for implementing Verifiable Data Registry functionality\n * Provides common utility methods and enforces the VDRInterface contract\n */\nexport abstract class AbstractVDR implements VDRInterface {\n  // The DID method this VDR handles (e.g., 'key', 'web')\n  protected readonly method: string;\n\n  /**\n   * Creates a new AbstractVDR instance\n   *\n   * @param method The DID method this VDR handles\n   */\n  constructor(method: string) {\n    this.method = method;\n  }\n\n  /**\n   * Gets the DID method this VDR handles\n   *\n   * @returns The DID method string\n   */\n  getMethod(): string {\n    return this.method;\n  }\n\n  /**\n   * Validates that a given DID matches the method this VDR handles\n   *\n   * @param did The DID to validate\n   * @throws Error if the DID doesn't match this VDR's method\n   */\n  protected validateDIDMethod(did: string): void {\n    const parsedDid = parseDid(did);\n    if (parsedDid.method !== this.method) {\n      throw createDIDError(\n        IdentityKitErrorCode.DID_INVALID_FORMAT,\n        `DID ${did} is not a valid did:${this.method} identifier`,\n        { did, expectedMethod: this.method, actualMethod: parsedDid.method }\n      );\n    }\n  }\n\n  /**\n   * Validates a DID document's basic structure\n   *\n   * @param document The DID document to validate\n   * @returns true if valid, throws an error otherwise\n   */\n  protected validateDocument(document: DIDDocument): boolean {\n    if (!document.id) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'DID document must have an id',\n        { document }\n      );\n    }\n\n    this.validateDIDMethod(document.id);\n\n    if (!document['@context']) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'DID document must have a @context property',\n        { document }\n      );\n    }\n\n    if (!document.verificationMethod || document.verificationMethod.length === 0) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'DID document must have at least one verification method',\n        { document }\n      );\n    }\n\n    return true;\n  }\n\n  /**\n   * Check if a key has a specific verification relationship in a DID document\n   *\n   * @param didDocument The DID document to check\n   * @param keyId The ID of the verification method\n   * @param relationship The verification relationship to check\n   * @returns True if the key has the relationship\n   */\n  protected hasVerificationRelationship(\n    didDocument: DIDDocument,\n    keyId: string,\n    relationship: VerificationRelationship\n  ): boolean {\n    const relationshipArray = didDocument[relationship];\n    if (!relationshipArray) return false;\n\n    return relationshipArray.some(item => {\n      if (typeof item === 'string') {\n        return item === keyId;\n      } else if (typeof item === 'object' && item.id) {\n        return item.id === keyId;\n      }\n      return false;\n    });\n  }\n\n  /**\n   * Validates if a key has permission to perform an operation\n   *\n   * @param didDocument The DID document\n   * @param keyId The ID of the key\n   * @param requiredRelationship The required verification relationship\n   * @returns True if the key has permission\n   */\n  protected validateKeyPermission(\n    didDocument: DIDDocument,\n    keyId: string,\n    requiredRelationship: VerificationRelationship\n  ): boolean {\n    const keyExists = didDocument.verificationMethod?.some(vm => vm.id === keyId);\n    if (!keyExists) {\n      logger.error(`Key ${keyId} not found in DID document`);\n      return false;\n    }\n\n    const isPrimaryKey = didDocument.verificationMethod?.[0]?.id === keyId;\n    if (isPrimaryKey) {\n      return true;\n    }\n\n    const hasPermission = didDocument[requiredRelationship]?.includes(keyId);\n\n    if (!hasPermission) {\n      logger.error(`Key ${keyId} does not have ${requiredRelationship} permission`);\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Default create implementation - throws not implemented error for base class\n   * Subclasses must override this method to provide actual implementation\n   */\n  async create(request: DIDCreationRequest, options?: any): Promise<DIDCreationResult> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `create method not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'create' }\n    );\n  }\n\n  /**\n   * Default CADOP implementation - throws not implemented error\n   */\n  async createViaCADOP(request: CADOPCreationRequest, options?: any): Promise<DIDCreationResult> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `createViaCADOP not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'createViaCADOP' }\n    );\n  }\n\n  /**\n   * Default CADOP with controller implementation - throws not implemented error\n   */\n  async createViaCADOPWithController(\n    request: CADOPControllerCreationRequest,\n    options?: any\n  ): Promise<DIDCreationResult> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `createViaCADOPWithController not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'createViaCADOPWithController' }\n    );\n  }\n\n  /**\n   * Build DID Document from creation request\n   */\n  protected buildDIDDocumentFromRequest(request: DIDCreationRequest): DIDDocument {\n    const did = request.preferredDID!;\n\n    // Extract the first controller for the verification method (which only accepts string)\n    const controllerForVM = Array.isArray(request.controller)\n      ? request.controller[0]\n      : request.controller || did;\n\n    const verificationMethod: VerificationMethod = {\n      id: `${did}#account-key`,\n      type: request.keyType || 'EcdsaSecp256k1VerificationKey2019',\n      controller: controllerForVM,\n      publicKeyMultibase: request.publicKeyMultibase,\n    };\n\n    const didDocument: DIDDocument = {\n      '@context': ['https://www.w3.org/ns/did/v1'],\n      id: did,\n      controller: request.controller\n        ? Array.isArray(request.controller)\n          ? request.controller\n          : [request.controller]\n        : [did],\n      verificationMethod: [verificationMethod, ...(request.additionalVerificationMethods || [])],\n      service: request.initialServices || [],\n    };\n\n    // Set initial relationships\n    const relationships = request.initialRelationships || [\n      'authentication',\n      'assertionMethod',\n      'capabilityInvocation',\n      'capabilityDelegation',\n    ];\n\n    const vmId = verificationMethod.id;\n    relationships.forEach(rel => {\n      if (!didDocument[rel]) {\n        didDocument[rel] = [];\n      }\n      (didDocument[rel] as string[]).push(vmId);\n    });\n\n    return didDocument;\n  }\n\n  /**\n   * Resolves a DID to its corresponding DID document\n   * Implementations must provide this functionality\n   */\n  abstract resolve(did: string): Promise<DIDDocument | null>;\n\n  /**\n   * Checks if a DID exists in the registry\n   * Default implementation tries to resolve and checks if result is not null\n   */\n  async exists(did: string): Promise<boolean> {\n    try {\n      const doc = await this.resolve(did);\n      return doc !== null;\n    } catch (error) {\n      return false;\n    }\n  }\n\n  /**\n   * Add a verification method to a DID document\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async addVerificationMethod(\n    did: string,\n    verificationMethod: VerificationMethod,\n    relationships?: VerificationRelationship[],\n    options?: any\n  ): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `addVerificationMethod not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'addVerificationMethod' }\n    );\n  }\n\n  /**\n   * Remove a verification method from a DID document\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async removeVerificationMethod(did: string, id: string, options?: any): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `removeVerificationMethod not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'removeVerificationMethod' }\n    );\n  }\n\n  /**\n   * Add a service to a DID document\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async addService(did: string, service: ServiceEndpoint, options?: any): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `addService not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'addService' }\n    );\n  }\n\n  /**\n   * Remove a service from a DID document\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async removeService(did: string, id: string, options?: any): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `removeService not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'removeService' }\n    );\n  }\n\n  /**\n   * Update verification relationships for a verification method\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async updateRelationships(\n    did: string,\n    id: string,\n    add: VerificationRelationship[],\n    remove: VerificationRelationship[],\n    options?: any\n  ): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `updateRelationships not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'updateRelationships' }\n    );\n  }\n\n  /**\n   * Update the controller of a DID document\n   * Default implementation that should be overridden by specific VDR implementations\n   */\n  async updateController(\n    did: string,\n    controller: string | string[],\n    options?: any\n  ): Promise<boolean> {\n    throw createVDRError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      `updateController not implemented for ${this.method} VDR`,\n      { method: this.method, operation: 'updateController' }\n    );\n  }\n\n  /**\n   * Validates options for update operations and ensures proper permissions\n   *\n   * @param did The DID being operated on\n   * @param document The resolved DID document\n   * @param keyId The key ID used for signing\n   * @param requiredRelationship The required verification relationship for this operation\n   * @throws Error if validation fails\n   */\n  protected async validateUpdateOperation(\n    did: string,\n    document: DIDDocument | null,\n    keyId: string,\n    requiredRelationship: VerificationRelationship\n  ): Promise<DIDDocument> {\n    // Validate DID method\n    this.validateDIDMethod(did);\n\n    // Check if document exists\n    if (!document) {\n      throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n        did,\n        operation: 'validateUpdateOperation',\n      });\n    }\n\n    // Check permission\n    if (!this.validateKeyPermission(document, keyId, requiredRelationship)) {\n      throw createValidationError(\n        IdentityKitErrorCode.KEY_PERMISSION_DENIED,\n        `Key ${keyId} does not have ${requiredRelationship} permission required for this operation`,\n        { keyId, requiredRelationship, did }\n      );\n    }\n\n    return document;\n  }\n\n  /**\n   * Validates that inputs to addVerificationMethod are correct\n   *\n   * @param did The DID being operated on\n   * @param verificationMethod The verification method to validate\n   * @param document The current DID document\n   * @throws Error if validation fails\n   */\n  protected validateVerificationMethod(\n    did: string,\n    verificationMethod: VerificationMethod,\n    document: DIDDocument\n  ): void {\n    // Ensure ID starts with the DID\n    if (!verificationMethod.id.startsWith(did)) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        `Verification method ID ${verificationMethod.id} must start with DID ${did}`,\n        { verificationMethodId: verificationMethod.id, did }\n      );\n    }\n\n    // Check if method already exists\n    if (document.verificationMethod?.some(vm => vm.id === verificationMethod.id)) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        `Verification method ${verificationMethod.id} already exists`,\n        { verificationMethodId: verificationMethod.id, did }\n      );\n    }\n\n    // Validate required fields\n    if (!verificationMethod.type) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Verification method must have a type',\n        { verificationMethod, did }\n      );\n    }\n\n    if (!verificationMethod.controller) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Verification method must have a controller',\n        { verificationMethod, did }\n      );\n    }\n\n    // Check that at least one key material format is present\n    if (!verificationMethod.publicKeyMultibase && !verificationMethod.publicKeyJwk) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Verification method must have at least one form of public key material',\n        { verificationMethod, did }\n      );\n    }\n  }\n\n  /**\n   * Validates that inputs to addService are correct\n   *\n   * @param did The DID being operated on\n   * @param service The service to validate\n   * @param document The current DID document\n   * @throws Error if validation fails\n   */\n  protected validateService(did: string, service: ServiceEndpoint, document: DIDDocument): void {\n    // Ensure ID starts with the DID\n    if (!service.id.startsWith(did)) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        `Service ID ${service.id} must start with DID ${did}`,\n        { serviceId: service.id, did }\n      );\n    }\n\n    // Check if service already exists\n    if (document.service?.some(s => s.id === service.id)) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        `Service ${service.id} already exists`,\n        { serviceId: service.id, did }\n      );\n    }\n\n    // Validate required fields\n    if (!service.type) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Service must have a type',\n        { service, did }\n      );\n    }\n\n    if (!service.serviceEndpoint) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Service must have a serviceEndpoint',\n        { service, did }\n      );\n    }\n  }\n\n  /**\n   * Makes a deep copy of a DID document for modification\n   *\n   * @param document The DID document to copy\n   * @returns A deep copy of the document\n   */\n  protected copyDocument(document: DIDDocument): DIDDocument {\n    return JSON.parse(JSON.stringify(document));\n  }\n}\n","import {\n  DIDDocument,\n  VerificationMethod,\n  VerificationRelationship,\n  ServiceEndpoint,\n} from '../types/did';\nimport {\n  DIDCreationRequest,\n  DIDCreationResult,\n  CADOPCreationRequest,\n  CADOPControllerCreationRequest,\n} from './types';\nimport { AbstractVDR } from './abstractVDR';\nimport { MultibaseCodec, DidKeyCodec } from '../multibase';\nimport { DebugLogger } from '../utils/DebugLogger';\nimport {\n  IdentityKitErrorCode,\n  createDIDError,\n  createVDRError,\n  createValidationError,\n} from '../errors';\n\n/**\n * KeyVDR handles did:key DIDs\n *\n * did:key DIDs are self-resolving as they contain the public key material\n * embedded in the identifier. This implementation follows the did:key method\n * specification.\n *\n * Example did:key: did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK\n *\n * Reference: https://w3c-ccg.github.io/did-method-key/\n */\n\n// Unified logger for KeyVDR\nconst logger = DebugLogger.get('KeyVDR');\n\nexport class KeyVDR extends AbstractVDR {\n  // In-memory cache of documents, shared across all instances\n  private static documentCache: Map<string, DIDDocument> = new Map();\n\n  constructor() {\n    super('key');\n  }\n\n  /**\n   * Resets the document cache - primarily for testing purposes\n   * to ensure tests don't interfere with each other.\n   */\n  public reset(): void {\n    KeyVDR.documentCache.clear();\n  }\n\n  /**\n   * Override resolve to handle test mode\n   */\n  async resolve(did: string): Promise<DIDDocument | null> {\n    try {\n      // Check the cache first\n      if (KeyVDR.documentCache.has(did)) {\n        return KeyVDR.documentCache.get(did)!;\n      }\n\n      return null;\n    } catch (error) {\n      logger.error(`Error resolving ${did}:`, error);\n      return null;\n    }\n  }\n\n  /**\n   * Add a verification method to a did:key document\n   * For did:key, this is mostly a simulation as the document is derived from the key\n   * This operation will update the local cache but not the actual structure of the did:key\n   *\n   * @param did The DID to update\n   * @param verificationMethod The verification method to add\n   * @param relationships Optional relationships to add the verification method to\n   * @param options Additional options like keyId for signing\n   * @returns Promise resolving to true if successful in updating the cache\n   */\n  async addVerificationMethod(\n    did: string,\n    verificationMethod: VerificationMethod,\n    relationships: VerificationRelationship[] = [],\n    options?: any\n  ): Promise<boolean> {\n    try {\n      const originalDocument = await this.resolve(did);\n      if (!originalDocument) {\n        throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID ${did} not found`, { did });\n      }\n\n      // Use parent class validation methods\n      await this.validateUpdateOperation(\n        did,\n        originalDocument,\n        options?.keyId,\n        'capabilityDelegation'\n      );\n      this.validateVerificationMethod(did, verificationMethod, originalDocument);\n\n      // Check for duplicate verification method ID\n      if (originalDocument.verificationMethod?.some(vm => vm.id === verificationMethod.id)) {\n        throw createValidationError(\n          IdentityKitErrorCode.VALIDATION_FAILED,\n          `Verification method ${verificationMethod.id} already exists`,\n          { verificationMethodId: verificationMethod.id, did }\n        );\n      }\n\n      if (!originalDocument.verificationMethod) {\n        originalDocument.verificationMethod = [];\n      }\n\n      // Add the verification method\n      originalDocument.verificationMethod.push(verificationMethod);\n\n      // Add relationships without duplicates\n      relationships.forEach(relationship => {\n        if (!originalDocument[relationship]) {\n          originalDocument[relationship] = [];\n        }\n        if (!originalDocument[relationship]!.includes(verificationMethod.id)) {\n          originalDocument[relationship]!.push(verificationMethod.id);\n        }\n      });\n\n      // Update the cache\n      KeyVDR.documentCache.set(did, originalDocument);\n      return true;\n    } catch (error) {\n      logger.error(`Error adding verification method to ${did}:`, error);\n      throw error;\n    }\n  }\n\n  /**\n   * Remove a verification method from a did:key document\n   * For did:key, this is mostly a simulation as the document is derived from the key\n   * This operation will update the local cache but not the actual structure of the did:key\n   *\n   * @param did The DID to update\n   * @param keyId The ID of the verification method to remove\n   * @param options Additional options\n   * @returns Promise resolving to true if successful in updating the cache\n   */\n  async removeVerificationMethod(did: string, keyId: string, options?: any): Promise<boolean> {\n    try {\n      const originalDocument = await this.resolve(did);\n      if (!originalDocument) {\n        throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID ${did} not found`, { did });\n      }\n\n      // Use parent class validation method\n      await this.validateUpdateOperation(\n        did,\n        originalDocument,\n        options?.keyId,\n        'capabilityDelegation'\n      );\n\n      const verificationMethods = originalDocument.verificationMethod || [];\n      const vmIndex = verificationMethods.findIndex(vm => vm.id === keyId);\n      if (vmIndex === -1) {\n        // Verification method not found, silently succeed\n        return true;\n      }\n\n      const isPrimaryKey = vmIndex === 0;\n      if (isPrimaryKey) {\n        throw createValidationError(\n          IdentityKitErrorCode.OPERATION_NOT_PERMITTED,\n          `Cannot remove the primary key ${keyId} from did:key document`,\n          { keyId, did, reason: 'Primary key cannot be removed from did:key documents' }\n        );\n      }\n\n      originalDocument.verificationMethod = verificationMethods.filter(vm => vm.id !== keyId);\n\n      const relationships: VerificationRelationship[] = [\n        'authentication',\n        'assertionMethod',\n        'capabilityInvocation',\n        'capabilityDelegation',\n      ];\n      relationships.forEach(relationship => {\n        if (originalDocument[relationship]) {\n          originalDocument[relationship] = originalDocument[relationship]!.filter(\n            id => id !== keyId\n          );\n        }\n      });\n\n      KeyVDR.documentCache.set(did, originalDocument);\n      return true;\n    } catch (error) {\n      logger.error(`Error removing verification method from ${did}:`, error);\n      throw error;\n    }\n  }\n\n  /**\n   * Add a service to a did:key document\n   * For did:key, this is mostly a simulation as the document is derived from the key\n   * This operation will update the local cache but not the actual structure of the did:key\n   *\n   * @param did The DID to update\n   * @param service The service to add\n   * @param options Additional options\n   * @returns Promise resolving to true if successful in updating the cache\n   */\n  async addService(did: string, service: ServiceEndpoint, options?: any): Promise<boolean> {\n    try {\n      const originalDocument = await this.resolve(did);\n      if (!originalDocument) {\n        throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID ${did} not found`, { did });\n      }\n\n      // Use parent class validation methods\n      await this.validateUpdateOperation(\n        did,\n        originalDocument,\n        options?.keyId,\n        'capabilityInvocation'\n      );\n      this.validateService(did, service, originalDocument);\n\n      if (!originalDocument.service) {\n        originalDocument.service = [];\n      }\n      originalDocument.service.push(service);\n\n      KeyVDR.documentCache.set(did, originalDocument);\n      return true;\n    } catch (error) {\n      logger.error(`Error adding service to ${did}:`, error);\n      throw error;\n    }\n  }\n\n  /**\n   * Remove a service from a did:key document\n   * For did:key, this is mostly a simulation as the document is derived from the key\n   * This operation will update the local cache but not the actual structure of the did:key\n   *\n   * @param did The DID to update\n   * @param id The ID of the service to remove\n   * @param options Additional options\n   * @returns Promise resolving to true if successful in updating the cache\n   */\n  async removeService(did: string, serviceId: string, options?: any): Promise<boolean> {\n    try {\n      const originalDocument = await this.resolve(did);\n      if (!originalDocument) {\n        throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID ${did} not found`, { did });\n      }\n\n      // Use parent class validation method\n      await this.validateUpdateOperation(\n        did,\n        originalDocument,\n        options?.keyId,\n        'capabilityInvocation'\n      );\n\n      if (!originalDocument.service || !originalDocument.service.some(s => s.id === serviceId)) {\n        // Service not found, silently succeed\n        return true;\n      }\n\n      originalDocument.service = originalDocument.service.filter(s => s.id !== serviceId);\n\n      KeyVDR.documentCache.set(did, originalDocument);\n      return true;\n    } catch (error) {\n      logger.error(`Error removing service from ${did}:`, error);\n      throw error;\n    }\n  }\n\n  /**\n   * Override create method for did:key\n   * For did:key, we can generate the DID from the public key\n   */\n  async create(request: DIDCreationRequest): Promise<DIDCreationResult> {\n    try {\n      // Validate the key format\n      if (!request.publicKeyMultibase || !request.publicKeyMultibase.startsWith('z')) {\n        return {\n          success: false,\n          error: 'Invalid key format: publicKeyMultibase must start with \"z\"',\n        };\n      }\n\n      if (!request.preferredDID || !request.controller) {\n        return {\n          success: false,\n          error: 'Missing required parameters: preferredDID and controller',\n        };\n      }\n\n      // Use the parent class method to build the DID document\n      const didDocument = this.buildDIDDocumentFromRequest(request);\n\n      // Store the document\n      KeyVDR.documentCache.set(request.preferredDID, didDocument);\n\n      return {\n        success: true,\n        didDocument,\n      };\n    } catch (error) {\n      logger.error(`Error creating DID document:`, error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  async createViaCADOP(request: CADOPCreationRequest, _options?: any): Promise<DIDCreationResult> {\n    let { keyType, publicKey } = DidKeyCodec.parseDidKey(request.userDidKey);\n    try {\n      const didCreationRequest: DIDCreationRequest = {\n        publicKeyMultibase: MultibaseCodec.encodeBase58btc(publicKey),\n        preferredDID: request.userDidKey,\n        keyType: keyType,\n        controller: request.userDidKey,\n        initialRelationships: ['authentication', 'capabilityDelegation'],\n      };\n\n      const didDocument = this.buildDIDDocumentFromRequest(didCreationRequest);\n      KeyVDR.documentCache.set(didDocument.id!, didDocument);\n      return {\n        success: true,\n        didDocument,\n      };\n    } catch (error) {\n      logger.error(`Error creating DID document via CADOP:`, error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  async createViaCADOPWithController(\n    request: CADOPControllerCreationRequest,\n    _options?: any\n  ): Promise<DIDCreationResult> {\n    // For KeyVDR, we only support did:key controllers\n    if (!request.controllerDid.startsWith('did:key:')) {\n      return {\n        success: false,\n        error: 'KeyVDR only supports did:key controllers. Use RoochVDR for other controller types.',\n      };\n    }\n\n    try {\n      // For did:key controllers, delegate to the regular CADOP method\n      const cadopRequest: CADOPCreationRequest = {\n        userDidKey: request.controllerDid,\n        custodianServicePublicKey: request.custodianServicePublicKey,\n        custodianServiceVMType: request.custodianServiceVMType,\n        customScopes: request.customScopes,\n      };\n\n      return this.createViaCADOP(cadopRequest, _options);\n    } catch (error) {\n      logger.error(`Error creating DID document via CADOP with controller:`, error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  /**\n   * Update verification relationships for a verification method\n   */\n  async updateRelationships(\n    did: string,\n    keyId: string,\n    add: VerificationRelationship[],\n    remove: VerificationRelationship[],\n    options?: any\n  ): Promise<boolean> {\n    try {\n      const originalDocument = await this.resolve(did);\n      if (!originalDocument) {\n        throw createDIDError(IdentityKitErrorCode.DID_NOT_FOUND, `DID ${did} not found`, { did });\n      }\n\n      // Use parent class validation method\n      await this.validateUpdateOperation(\n        did,\n        originalDocument,\n        options?.keyId,\n        'capabilityDelegation'\n      );\n\n      // Check if the verification method exists\n      const verificationMethod = originalDocument.verificationMethod?.find(vm => vm.id === keyId);\n      if (!verificationMethod) {\n        throw createValidationError(\n          IdentityKitErrorCode.KEY_NOT_FOUND,\n          `Verification method ${keyId} not found`,\n          { keyId, did }\n        );\n      }\n\n      // Remove relationships\n      remove.forEach(relationship => {\n        if (originalDocument[relationship]) {\n          originalDocument[relationship] = originalDocument[relationship]!.filter(\n            id => id !== keyId\n          );\n        }\n      });\n\n      // Add relationships without duplicates\n      add.forEach(relationship => {\n        if (!originalDocument[relationship]) {\n          originalDocument[relationship] = [];\n        }\n        if (!originalDocument[relationship]!.includes(keyId)) {\n          originalDocument[relationship]!.push(keyId);\n        }\n      });\n\n      // Update the cache\n      KeyVDR.documentCache.set(did, originalDocument);\n      return true;\n    } catch (error) {\n      logger.error(`Error updating relationships for ${did}:`, error);\n      throw error;\n    }\n  }\n}\n","import {\n  RoochClient,\n  Transaction,\n  Args,\n  getRoochNodeUrl as sdkGetRoochNodeUrl,\n  Signer,\n  RoochAddress,\n  SignatureScheme,\n  Keypair,\n  PublicKey,\n  Address,\n  Bytes,\n  Authenticator,\n  BitcoinAddress,\n  ObjectStateView,\n  Ed25519PublicKey,\n  Secp256k1PublicKey,\n  EventView,\n} from '@roochnetwork/rooch-sdk';\nimport {\n  DIDDocument,\n  VerificationMethod,\n  VerificationRelationship,\n  ServiceEndpoint,\n} from '../types/did';\nimport { SignerInterface, DidAccountSigner, isSignerInterface } from '../signers';\nimport { KeyType, keyTypeToRoochSignatureScheme } from '../types/crypto';\nimport {\n  DIDCreationRequest,\n  DIDCreationResult,\n  CADOPCreationRequest,\n  CADOPControllerCreationRequest,\n} from './types';\nimport { AbstractVDR } from './abstractVDR';\nimport {\n  convertMoveDIDDocumentToInterface,\n  formatDIDString,\n  parseDIDCreatedEvent,\n  resolveDidObjectID,\n} from './roochVDRTypes';\nimport { DebugLogger } from '../utils/DebugLogger';\nimport { parseDid, extractFragmentFromId } from '../utils/did';\nimport { validateScopes, combineScopes } from '../utils/sessionScopes';\nimport {\n  IdentityKitErrorCode,\n  createVDRError,\n  createValidationError,\n  createSignerError,\n  wrapUnknownError,\n} from '../errors';\n\nexport interface RoochClientConfig {\n  url: string;\n  transport?: any;\n}\n\nexport interface RoochTransactionResult {\n  execution_info: {\n    status: {\n      type: string; // 'executed' | 'failed'\n    };\n    gas_used: string;\n  };\n  output?: {\n    events?: Array<{\n      event_type: string;\n      event_data: string;\n      event_index: string;\n      decoded_event_data?: any;\n    }>;\n  };\n  transaction: any;\n}\n\n/**\n * Options for RoochVDR configuration\n */\nexport interface RoochVDROptions {\n  /**\n   * Rooch RPC endpoint URL\n   */\n  rpcUrl?: string;\n\n  /**\n   * Network type (local, dev, test, main)\n   */\n  network?: 'local' | 'dev' | 'test' | 'main';\n\n  /**\n   * Enable debug mode for detailed logging\n   */\n  debug?: boolean;\n}\n\n/**\n * Result of store operation with actual DID address\n */\nexport interface StoreResult {\n  success: boolean;\n  actualDIDAddress?: string;\n}\n\n/**\n * Options for Rooch VDR operations\n */\nexport interface RoochVDROperationOptions {\n  /**\n   * Signer to use for this operation\n   */\n  signer?: SignerInterface | Signer;\n\n  /**\n   * Key ID to use for this operation\n   */\n  keyId?: string;\n\n  /**\n   * Custom session key scopes (for authentication VM)\n   * Only used when adding a verification method with authentication relationship\n   */\n  scopes?: string[];\n\n  /**\n   * Advanced blockchain transaction options\n   * For high-level users who need fine-grained control over transaction parameters\n   */\n  advanced?: RoochTxnOptions;\n}\n\n/**\n * Advanced Rooch blockchain transaction options\n * These options are typically only needed for advanced use cases\n */\nexport interface RoochTxnOptions {\n  /**\n   * Maximum gas limit for the transaction\n   */\n  maxGas?: number;\n}\n\n/**\n * VDR implementation for did:rooch method\n *\n * This implementation integrates with Rooch network's DID contract system\n * to provide on-chain DID document storage and management.\n */\nexport class RoochVDR extends AbstractVDR {\n  private readonly options: RoochVDROptions;\n  private client: RoochClient;\n  private readonly didContractAddress: string;\n  private readonly debug: boolean;\n  private readonly logger: DebugLogger;\n  private lastCreatedDIDAddress?: string;\n\n  constructor(options: RoochVDROptions) {\n    super('rooch');\n    this.options = options;\n    this.didContractAddress = '0x3::did';\n    this.debug = options.debug || false;\n    this.logger = DebugLogger.get('RoochVDR');\n    if (this.debug) {\n      this.logger.setLevel('debug');\n    }\n\n    let rpcUrl = options.rpcUrl;\n    if (!rpcUrl) {\n      rpcUrl = RoochVDR.getRoochNodeUrl(options.network || 'test');\n    }\n    this.logger.debug(`RoochVDR initialized with rpcUrl: ${rpcUrl}`);\n    // Initialize Rooch client\n    this.client = new RoochClient({ url: rpcUrl });\n  }\n\n  /**\n   * Log message if debug mode is enabled\n   */\n  private debugLog(message: string, data?: any) {\n    if (data !== undefined) {\n      this.logger.debug(message, data);\n    } else {\n      this.logger.debug(message);\n    }\n  }\n\n  /**\n   * Log error message (always logged regardless of debug mode)\n   */\n  private errorLog(message: string, error?: any) {\n    if (error !== undefined) {\n      this.logger.error(message, error);\n    } else {\n      this.logger.error(message);\n    }\n  }\n\n  private async convertSigner(signer: SignerInterface | Signer, keyId?: string): Promise<Signer> {\n    // If it implements SignerInterface, convert it to DidAccountSigner\n    if (isSignerInterface(signer)) {\n      return DidAccountSigner.create(signer, keyId);\n    }\n    // Fallback: assume it's Signer\n    return signer;\n  }\n\n  /**\n   * Override create method to support Rooch dynamic DID generation\n   */\n  async create(\n    request: DIDCreationRequest,\n    options?: RoochVDROperationOptions\n  ): Promise<DIDCreationResult> {\n    try {\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for create operation',\n          { operation: 'create', request }\n        );\n      }\n\n      this.debugLog('Creating DID with request:', request);\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Always combine base scopes with custom scopes\n      const finalScopes = combineScopes(request.customScopes || []);\n\n      // Validate all scopes\n      const scopeValidation = validateScopes(finalScopes);\n      if (!scopeValidation.valid) {\n        throw createValidationError(\n          IdentityKitErrorCode.SCOPE_VALIDATION_FAILED,\n          `Invalid scope format: ${scopeValidation.invalidScopes.join(', ')}`,\n          {\n            invalidScopes: scopeValidation.invalidScopes,\n            allScopes: finalScopes,\n            operation: 'create',\n          }\n        );\n      }\n\n      // Always use the scopes version since we always have scopes (at minimum base scopes)\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::create_did_object_for_self_with_custom_scopes_entry`,\n        args: [Args.string(request.publicKeyMultibase), Args.vec('string', finalScopes)],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      this.debugLog('Creating DID with scopes:', finalScopes);\n\n      this.debugLog('Creating DID Transaction:', transaction);\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      const success = result.execution_info.status.type === 'executed';\n\n      if (!success) {\n        // Return preferredDID or generate a failure placeholder on failure\n        return {\n          success: false,\n          error:\n            'Transaction execution failed, execution_info: ' +\n            JSON.stringify(result.execution_info),\n          debug: {\n            requestedDID: request.preferredDID,\n            transactionResult: result.execution_info,\n          },\n        };\n      }\n\n      // Parse the actual created DID\n      const didCreatedEvent = result.output?.events?.find(\n        (event: EventView) => event.event_type === '0x3::did::DIDCreatedEvent'\n      );\n      if (!didCreatedEvent) {\n        throw createVDRError(\n          IdentityKitErrorCode.VDR_INVALID_RESPONSE,\n          'DIDCreatedEvent not found in transaction result',\n          { transactionResult: result, events: result.output?.events, operation: 'create' }\n        );\n      }\n      let actualDID = this.parseDIDCreatedEventAndGetDID(didCreatedEvent);\n\n      this.lastCreatedDIDAddress = actualDID;\n\n      let didDocument = await this.resolve(actualDID);\n      if (!didDocument) {\n        throw createVDRError(\n          IdentityKitErrorCode.DID_RESOLUTION_FAILED,\n          `DID document not found with DID: ${actualDID}`,\n          { did: actualDID, operation: 'create' }\n        );\n      }\n\n      return {\n        success: true,\n        didDocument: didDocument,\n        transactionHash: (result as any).transaction_hash,\n        debug: {\n          requestedDID: request.preferredDID,\n          actualDID: actualDID || undefined,\n          events: result.output?.events,\n        },\n      };\n    } catch (error) {\n      this.errorLog('Error creating DID:', error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  /**\n   * Override CADOP creation method\n   */\n  async createViaCADOP(\n    request: CADOPCreationRequest,\n    options?: RoochVDROperationOptions\n  ): Promise<DIDCreationResult> {\n    try {\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No custodian signer provided for CADOP operation',\n          { operation: 'createViaCADOP', request }\n        );\n      }\n\n      this.debugLog('Creating DID via CADOP with request:', request);\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Always combine base scopes with custom scopes\n      const finalScopes = combineScopes(request.customScopes || []);\n\n      // Validate all scopes\n      const scopeValidation = validateScopes(finalScopes);\n      if (!scopeValidation.valid) {\n        throw createValidationError(\n          IdentityKitErrorCode.SCOPE_VALIDATION_FAILED,\n          `Invalid scope format: ${scopeValidation.invalidScopes.join(', ')}`,\n          {\n            invalidScopes: scopeValidation.invalidScopes,\n            allScopes: finalScopes,\n            operation: 'createViaCADOP',\n          }\n        );\n      }\n\n      // Always use the scopes version since the contract will add base scopes\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::create_did_object_via_cadop_with_did_key_and_scopes_entry`,\n        args: [\n          Args.string(request.userDidKey),\n          Args.string(request.custodianServicePublicKey),\n          Args.string(request.custodianServiceVMType),\n          Args.vec('string', finalScopes),\n        ],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      this.debugLog('Creating DID via CADOP with scopes:', finalScopes);\n\n      this.debugLog('Creating DID via CADOP Transaction:', transaction);\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      this.debugLog('Creating DID via CADOP Transaction Result:', result);\n\n      const success = result.execution_info.status.type === 'executed';\n\n      if (!success) {\n        return {\n          success: false,\n          error:\n            'CADOP transaction execution failed, execution_info: ' +\n            JSON.stringify(result.execution_info),\n        };\n      }\n\n      // Parse the created DID\n      const didCreatedEvent = result.output?.events?.find(\n        (event: any) => event.event_type === '0x3::did::DIDCreatedEvent'\n      );\n      if (!didCreatedEvent) {\n        throw createVDRError(\n          IdentityKitErrorCode.VDR_INVALID_RESPONSE,\n          'DIDCreatedEvent not found in transaction result',\n          { transactionResult: result, events: result.output?.events }\n        );\n      }\n      let actualDID = this.parseDIDCreatedEventAndGetDID(didCreatedEvent);\n      let didDocument = await this.resolve(actualDID);\n      if (!didDocument) {\n        throw createVDRError(\n          IdentityKitErrorCode.DID_RESOLUTION_FAILED,\n          `DID document not found with DID: ${actualDID}`,\n          { did: actualDID }\n        );\n      }\n      return {\n        success: true,\n        didDocument: didDocument,\n        transactionHash: (result as any).transaction_hash,\n      };\n    } catch (error) {\n      this.errorLog('Error creating DID via CADOP:', error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  /**\n   * Create DID via CADOP with controller (supports did:key, did:bitcoin, etc.)\n   */\n  async createViaCADOPWithController(\n    request: CADOPControllerCreationRequest,\n    options?: RoochVDROperationOptions\n  ): Promise<DIDCreationResult> {\n    try {\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No custodian signer provided for CADOP controller operation',\n          { operation: 'createViaCADOPWithController', request }\n        );\n      }\n\n      this.debugLog('Creating DID via CADOP with controller request:', request);\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Always combine base scopes with custom scopes\n      const finalScopes = combineScopes(request.customScopes || []);\n\n      // Validate all scopes\n      const scopeValidation = validateScopes(finalScopes);\n      if (!scopeValidation.valid) {\n        throw createValidationError(\n          IdentityKitErrorCode.SCOPE_VALIDATION_FAILED,\n          `Invalid scope format: ${scopeValidation.invalidScopes.join(', ')}`,\n          {\n            invalidScopes: scopeValidation.invalidScopes,\n            allScopes: finalScopes,\n            operation: 'createViaCADOPWithController',\n          }\n        );\n      }\n\n      // Use the new controller-based contract entry point\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::create_did_object_via_cadop_with_controller_and_scopes_entry`,\n        args: [\n          Args.string(request.controllerDid),\n          Args.string(request.controllerPublicKeyMultibase || ''),\n          Args.string(request.controllerVMType || ''),\n          Args.string(request.custodianServicePublicKey),\n          Args.string(request.custodianServiceVMType),\n          Args.vec('string', finalScopes),\n        ],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      this.debugLog('Creating DID via CADOP with controller and scopes:', finalScopes);\n      this.debugLog('Controller DID:', request.controllerDid);\n      this.debugLog('Controller public key multibase:', request.controllerPublicKeyMultibase);\n      this.debugLog('Controller VM type:', request.controllerVMType);\n\n      this.debugLog('Creating DID via CADOP with controller Transaction:', transaction);\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      this.debugLog('Creating DID via CADOP with controller Transaction Result:', result);\n\n      const success = result.execution_info.status.type === 'executed';\n\n      if (!success) {\n        return {\n          success: false,\n          error:\n            'CADOP controller transaction execution failed, execution_info: ' +\n            JSON.stringify(result.execution_info),\n        };\n      }\n\n      // Parse the created DID\n      const didCreatedEvent = result.output?.events?.find(\n        (event: any) => event.event_type === '0x3::did::DIDCreatedEvent'\n      );\n      if (!didCreatedEvent) {\n        throw createVDRError(\n          IdentityKitErrorCode.VDR_INVALID_RESPONSE,\n          'DIDCreatedEvent not found in transaction result',\n          { transactionResult: result, events: result.output?.events }\n        );\n      }\n      let actualDID = this.parseDIDCreatedEventAndGetDID(didCreatedEvent);\n      let didDocument = await this.resolve(actualDID);\n      if (!didDocument) {\n        throw createVDRError(\n          IdentityKitErrorCode.DID_RESOLUTION_FAILED,\n          `DID document not found with DID: ${actualDID}`,\n          { did: actualDID }\n        );\n      }\n      return {\n        success: true,\n        didDocument: didDocument,\n        transactionHash: (result as any).transaction_hash,\n        debug: {\n          requestedDID: request.controllerDid,\n          actualDID: actualDID,\n          events: result.output?.events,\n        },\n      };\n    } catch (error) {\n      this.errorLog('Error creating DID via CADOP with controller:', error);\n      return {\n        success: false,\n        error: error instanceof Error ? error.message : 'Unknown error',\n      };\n    }\n  }\n\n  /**\n   * Resolve DID Document from Rooch blockchain\n   *\n   * @param did The DID to resolve (e.g., \"did:rooch:0x123...\")\n   * @returns Promise resolving to the DID Document or null if not found\n   */\n  async resolve(did: string): Promise<DIDDocument | null> {\n    try {\n      this.validateDIDMethod(did);\n\n      // Extract address from did:rooch:address format\n      const { method, identifier } = parseDid(did);\n      if (method !== 'rooch') {\n        throw createVDRError(\n          IdentityKitErrorCode.DID_INVALID_FORMAT,\n          'Invalid DID format. Expected did:rooch:address',\n          { did, expectedMethod: 'rooch', actualMethod: method }\n        );\n      }\n\n      // Calculate Object ID from identifier\n      const objectId = resolveDidObjectID(identifier);\n      this.debugLog(`Resolved DID object ID: ${objectId}`);\n      const objectStates = await this.client.getObjectStates({\n        ids: [objectId],\n      });\n\n      if (!objectStates || objectStates.length === 0) {\n        return null;\n      }\n\n      let didDocObject: ObjectStateView = objectStates[0];\n      if (!didDocObject) {\n        this.debugLog(`Resolved DID document by ${did} is null`);\n        return null;\n      }\n      return convertMoveDIDDocumentToInterface(didDocObject);\n    } catch (error) {\n      this.errorLog(`Error resolving DID from Rooch network:`, error);\n      return null;\n    }\n  }\n\n  /**\n   * Check if a DID exists on the Rooch network\n   *\n   * @param did The DID to check\n   * @returns Promise resolving to true if the DID exists\n   */\n  async exists(did: string): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      // Extract address from did:rooch:address format\n      const { method, identifier } = parseDid(did);\n      if (method !== 'rooch') {\n        return false;\n      }\n\n      const address = identifier;\n\n      // Call DID contract's exists_did_for_address view function on Rooch network\n      const result = await this.client.executeViewFunction({\n        target: `${this.didContractAddress}::exists_did_for_address`,\n        args: [Args.address(address)],\n      });\n\n      return result?.vm_status === 'Executed' && result.return_values?.[0]?.decoded_value === true;\n    } catch (error) {\n      this.errorLog(`Error checking DID existence on Rooch network:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Add a verification method to a DID document on Rooch blockchain\n   */\n  async addVerificationMethod(\n    did: string,\n    verificationMethod: VerificationMethod,\n    relationships?: VerificationRelationship[],\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for addVerificationMethod operation',\n          { operation: 'addVerificationMethod', did }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      this.debugLog(`Adding verification method to DID: ${did}`);\n      this.debugLog(\n        `Using signer with address: ${didAccountSigner.getRoochAddress().toBech32Address()}`\n      );\n\n      // Check if signer has capabilityDelegation permission\n      const signerAddress = didAccountSigner.getRoochAddress\n        ? didAccountSigner.getRoochAddress().toBech32Address()\n        : null;\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityDelegation')\n      ) {\n        this.errorLog(`Signer does not have capabilityDelegation permission for ${did}`);\n        this.debugLog(\n          `Note: DID operations may require the DID account itself to sign, not the controller`\n        );\n        return false;\n      }\n\n      // Validate verification method\n      if (!verificationMethod.publicKeyMultibase) {\n        throw createValidationError(\n          IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n          'Verification method must have publicKeyMultibase',\n          { verificationMethod, did }\n        );\n      }\n\n      // Convert verification relationships to u8 values\n      const relationshipValues = this.convertVerificationRelationships(relationships || []);\n\n      // Check if we need to use scopes version for authentication relationship\n      const hasAuthentication = relationships?.includes('authentication');\n\n      // Create transaction\n      const transaction = this.createTransaction();\n\n      if (hasAuthentication) {\n        // When adding authentication VM, we need to handle scopes\n        const finalScopes = combineScopes(options?.scopes || []);\n\n        // Validate all scopes\n        const scopeValidation = validateScopes(finalScopes);\n        if (!scopeValidation.valid) {\n          throw createValidationError(\n            IdentityKitErrorCode.SCOPE_VALIDATION_FAILED,\n            `Invalid scope format: ${scopeValidation.invalidScopes.join(', ')}`,\n            {\n              invalidScopes: scopeValidation.invalidScopes,\n              allScopes: finalScopes,\n              operation: 'addVerificationMethod',\n            }\n          );\n        }\n\n        // Use the scopes version for authentication VM\n        transaction.callFunction({\n          target: `${this.didContractAddress}::add_verification_method_with_scopes_entry`,\n          args: [\n            Args.string(extractFragmentFromId(verificationMethod.id)),\n            Args.string(verificationMethod.type),\n            Args.string(verificationMethod.publicKeyMultibase),\n            Args.vec('u8', relationshipValues),\n            Args.vec('string', finalScopes),\n          ],\n          maxGas: options?.advanced?.maxGas || 100000000,\n        });\n\n        this.debugLog('Using add_verification_method_with_scopes_entry with scopes:', finalScopes);\n      } else {\n        // Use regular version for non-authentication VM\n        transaction.callFunction({\n          target: `${this.didContractAddress}::add_verification_method_entry`,\n          args: [\n            Args.string(extractFragmentFromId(verificationMethod.id)),\n            Args.string(verificationMethod.type),\n            Args.string(verificationMethod.publicKeyMultibase),\n            Args.vec('u8', relationshipValues),\n          ],\n          maxGas: options?.advanced?.maxGas || 100000000,\n        });\n\n        this.debugLog(\n          'Using regular add_verification_method_entry (no authentication relationship)'\n        );\n      }\n\n      this.debugLog(`Verification method transaction prepared`);\n      this.debugLog(`Fragment:`, extractFragmentFromId(verificationMethod.id));\n      this.debugLog(`Type:`, verificationMethod.type);\n      this.debugLog(`Relationships:`, relationshipValues);\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      this.debugLog(`Transaction execution result:`, {\n        status: result.execution_info.status,\n        gas_used: result.execution_info.gas_used,\n        events_count: result.output?.events?.length || 0,\n      });\n\n      if (result.execution_info.status.type !== 'executed') {\n        this.errorLog(`Transaction failed:`, result.execution_info);\n        if (result.execution_info.status.type === 'moveabort') {\n          this.errorLog(`Move abort code:`, (result.execution_info.status as any).abort_code);\n          this.errorLog(`Move abort location:`, (result.execution_info.status as any).location);\n        }\n        return false;\n      }\n\n      this.debugLog(`Verification method added successfully`);\n      return true;\n    } catch (error) {\n      this.errorLog(`Error adding verification method to ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Remove a verification method from a DID document on Rooch blockchain\n   */\n  async removeVerificationMethod(\n    did: string,\n    id: string,\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for removeVerificationMethod operation',\n          { operation: 'removeVerificationMethod', did, id }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      // Check if signer has capabilityDelegation permission\n      const signerAddress = didAccountSigner.getRoochAddress\n        ? didAccountSigner.getRoochAddress().toBech32Address()\n        : null;\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityDelegation')\n      ) {\n        this.errorLog(`Signer does not have capabilityDelegation permission for ${did}`);\n        return false;\n      }\n\n      // Create transaction\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::remove_verification_method_entry`,\n        args: [Args.string(extractFragmentFromId(id))],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      return result.execution_info.status.type === 'executed';\n    } catch (error) {\n      this.errorLog(`Error removing verification method from ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Add a service to a DID document on Rooch blockchain\n   */\n  async addService(\n    did: string,\n    service: ServiceEndpoint,\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for addService operation',\n          { operation: 'addService', did }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      this.debugLog(`Adding service to DID: ${did}`);\n      this.debugLog(\n        `🗝️ Using signer with address: ${didAccountSigner.getRoochAddress().toBech32Address()}`\n      );\n\n      // Check if signer has capabilityInvocation permission\n      const signerAddress = didAccountSigner.getRoochAddress\n        ? didAccountSigner.getRoochAddress().toBech32Address()\n        : null;\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityInvocation')\n      ) {\n        this.errorLog(`Signer does not have capabilityInvocation permission for ${did}`);\n        this.debugLog(\n          `💡 Note: DID operations may require the DID account itself to sign, not the controller`\n        );\n        return false;\n      }\n\n      const standardKeys = ['id', 'type', 'serviceEndpoint'];\n      const additionalProperties = Object.entries(service).reduce(\n        (acc, [key, value]) => {\n          if (!standardKeys.includes(key)) {\n            acc[key] = value ? value.toString() : '';\n          }\n          return acc;\n        },\n        {} as Record<string, string>\n      );\n\n      const propertyKeys = Object.keys(additionalProperties);\n      const propertyValues = Object.values(additionalProperties).map(value =>\n        value ? value.toString() : ''\n      );\n      this.debugLog('service', service);\n      this.debugLog('additionalProperties', additionalProperties);\n      this.debugLog('propertyKeys', propertyKeys);\n      this.debugLog('propertyValues', propertyValues);\n\n      // Create transaction for simple service (without properties)\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::add_service_with_properties_entry`,\n        args: [\n          Args.string(extractFragmentFromId(service.id)),\n          Args.string(service.type),\n          Args.string(service.serviceEndpoint),\n          Args.vec('string', propertyKeys),\n          Args.vec('string', propertyValues),\n        ],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      this.debugLog('Executing transaction: add_service_entry');\n      this.debugLog('Args:', [\n        extractFragmentFromId(service.id),\n        service.type,\n        service.serviceEndpoint,\n      ]);\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      this.debugLog('Transaction execution result:', {\n        status: result.execution_info.status,\n        gas_used: result.execution_info.gas_used,\n        events_count: result.output?.events?.length || 0,\n      });\n\n      if (result.execution_info.status.type !== 'executed') {\n        this.errorLog('Transaction failed:', result.execution_info);\n        if (result.execution_info.status.type === 'moveabort') {\n          this.errorLog('Move abort code:', (result.execution_info.status as any).abort_code);\n          this.errorLog('Move abort location:', (result.execution_info.status as any).location);\n        }\n        return false;\n      }\n\n      this.debugLog('Service added successfully');\n      return true;\n    } catch (error) {\n      this.errorLog(`Error adding service to ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Add a service with properties to a DID document on Rooch blockchain\n   */\n  async addServiceWithProperties(\n    did: string,\n    service: ServiceEndpoint & { properties?: Record<string, string> },\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for addServiceWithProperties operation',\n          { operation: 'addServiceWithProperties', did }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      // Check if signer has capabilityInvocation permission\n      const signerAddress = didAccountSigner.getRoochAddress\n        ? didAccountSigner.getRoochAddress().toBech32Address()\n        : null;\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityInvocation')\n      ) {\n        this.errorLog(`Signer does not have capabilityInvocation permission for ${did}`);\n        return false;\n      }\n\n      const properties = service.properties || {};\n      const propertyKeys = Object.keys(properties);\n      const propertyValues = Object.values(properties);\n\n      // Create transaction for service with properties\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::add_service_with_properties_entry`,\n        args: [\n          Args.string(extractFragmentFromId(service.id)),\n          Args.string(service.type),\n          Args.string(service.serviceEndpoint),\n          Args.vec('string', propertyKeys),\n          Args.vec('string', propertyValues),\n        ],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      return result.execution_info.status.type === 'executed';\n    } catch (error) {\n      this.errorLog(`Error adding service with properties to ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Remove a service from a DID document on Rooch blockchain\n   */\n  async removeService(\n    did: string,\n    id: string,\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for removeService operation',\n          { operation: 'removeService', did, id }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      // Check if signer has capabilityInvocation permission\n      const signerAddress = didAccountSigner.getRoochAddress().toBech32Address();\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityInvocation')\n      ) {\n        this.errorLog(`Signer does not have capabilityInvocation permission for ${did}`);\n        return false;\n      }\n\n      // Create transaction\n      const transaction = this.createTransaction();\n      transaction.callFunction({\n        target: `${this.didContractAddress}::remove_service_entry`,\n        args: [Args.string(extractFragmentFromId(id))],\n        maxGas: options?.advanced?.maxGas || 100000000,\n      });\n\n      // Execute transaction\n      const result = await this.client.signAndExecuteTransaction({\n        transaction,\n        signer: didAccountSigner,\n        option: { withOutput: true },\n      });\n\n      return result.execution_info.status.type === 'executed';\n    } catch (error) {\n      this.errorLog(`Error removing service from ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Update verification relationships for a verification method on Rooch blockchain\n   */\n  async updateRelationships(\n    did: string,\n    id: string,\n    add: VerificationRelationship[],\n    remove: VerificationRelationship[],\n    options?: RoochVDROperationOptions\n  ): Promise<boolean> {\n    try {\n      this.validateDIDMethod(did);\n\n      const signer = options?.signer;\n      if (!signer) {\n        throw createSignerError(\n          IdentityKitErrorCode.SIGNER_NOT_AVAILABLE,\n          'No signer provided for updateRelationships operation',\n          { operation: 'updateRelationships', did, id }\n        );\n      }\n\n      const didAccountSigner = await this.convertSigner(signer, options?.keyId);\n\n      // Pre-validate permissions by resolving the DID document\n      const currentDoc = await this.resolve(did);\n      if (!currentDoc) {\n        throw createVDRError(IdentityKitErrorCode.DID_NOT_FOUND, `DID document ${did} not found`, {\n          did,\n        });\n      }\n\n      // Check if signer has capabilityDelegation permission\n      const signerAddress = didAccountSigner.getRoochAddress().toBech32Address();\n      if (\n        signerAddress &&\n        !this.hasPermissionForOperation(currentDoc, signerAddress, 'capabilityDelegation')\n      ) {\n        this.errorLog(`Signer does not have capabilityDelegation permission for ${did}`);\n        return false;\n      }\n\n      const fragment = extractFragmentFromId(id);\n\n      // Add relationships\n      for (const relationship of add) {\n        const relationshipValue = this.convertVerificationRelationship(relationship);\n        const transaction = this.createTransaction();\n        transaction.callFunction({\n          target: `${this.didContractAddress}::add_to_verification_relationship_entry`,\n          args: [Args.string(fragment), Args.u8(relationshipValue)],\n          maxGas: options?.advanced?.maxGas || 100000000,\n        });\n\n        const result = await this.client.signAndExecuteTransaction({\n          transaction,\n          signer: didAccountSigner,\n          option: { withOutput: true },\n        });\n\n        if (result.execution_info.status.type !== 'executed') {\n          return false;\n        }\n      }\n\n      // Remove relationships\n      for (const relationship of remove) {\n        const relationshipValue = this.convertVerificationRelationship(relationship);\n        const transaction = this.createTransaction();\n        transaction.callFunction({\n          target: `${this.didContractAddress}::remove_from_verification_relationship_entry`,\n          args: [Args.string(fragment), Args.u8(relationshipValue)],\n          maxGas: options?.advanced?.maxGas || 100000000,\n        });\n\n        const result = await this.client.signAndExecuteTransaction({\n          transaction,\n          signer: didAccountSigner,\n          option: { withOutput: true },\n        });\n\n        if (result.execution_info.status.type !== 'executed') {\n          return false;\n        }\n      }\n\n      return true;\n    } catch (error) {\n      this.errorLog(`Error updating relationships for ${did}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Create a new Rooch transaction instance\n   */\n  private createTransaction(): Transaction {\n    return new Transaction();\n  }\n\n  /**\n   * Convert verification relationships to u8 values based on did.move constants\n   */\n  private convertVerificationRelationships(relationships: VerificationRelationship[]): number[] {\n    return relationships.map(rel => this.convertVerificationRelationship(rel));\n  }\n\n  /**\n   * Convert a single verification relationship to u8 value\n   */\n  private convertVerificationRelationship(relationship: VerificationRelationship): number {\n    switch (relationship) {\n      case 'authentication':\n        return 0; // VERIFICATION_RELATIONSHIP_AUTHENTICATION\n      case 'assertionMethod':\n        return 1; // VERIFICATION_RELATIONSHIP_ASSERTION_METHOD\n      case 'capabilityInvocation':\n        return 2; // VERIFICATION_RELATIONSHIP_CAPABILITY_INVOCATION\n      case 'capabilityDelegation':\n        return 3; // VERIFICATION_RELATIONSHIP_CAPABILITY_DELEGATION\n      case 'keyAgreement':\n        return 4; // VERIFICATION_RELATIONSHIP_KEY_AGREEMENT\n      default:\n        throw createValidationError(\n          IdentityKitErrorCode.INVALID_PARAMETER,\n          `Unknown verification relationship: ${relationship}`,\n          {\n            relationship,\n            validRelationships: [\n              'authentication',\n              'assertionMethod',\n              'keyAgreement',\n              'capabilityInvocation',\n              'capabilityDelegation',\n            ],\n          }\n        );\n    }\n  }\n\n  /**\n   * Check if a signer has permission to perform an operation on a DID\n   */\n  private hasPermissionForOperation(\n    didDocument: DIDDocument,\n    signerAddress: string,\n    requiredRelationship: VerificationRelationship\n  ): boolean {\n    try {\n      this.debugLog(`Checking permission for signer ${signerAddress} on DID ${didDocument.id}`);\n      this.debugLog(`Required relationship: ${requiredRelationship}`);\n      this.debugLog(`DID controllers:`, didDocument.controller);\n\n      // Create possible DID formats for the signer\n      const signerDIDHex = `did:rooch:${signerAddress}`;\n      this.debugLog(`Signer DID (hex):`, signerDIDHex);\n\n      // Extract DID address from the DID document ID\n      const didMatch = didDocument.id.match(/did:rooch:(.+)$/);\n      const didAddress = didMatch ? didMatch[1] : null;\n\n      this.debugLog(`DID account address:`, didAddress);\n      this.debugLog(`Signer address:`, signerAddress);\n\n      // **CRITICAL**: In Rooch DID system, operations must be signed by the DID account itself\n      // The DID account is created by the contract and is different from the controller\n      if (didAddress && signerAddress.toLowerCase() === didAddress.toLowerCase()) {\n        this.debugLog(`Permission granted: Signer is the DID account itself`);\n        return true;\n      }\n\n      // If signer is not the DID account, this will fail at contract level\n      this.errorLog(`Permission issue: Signer is not the DID account`);\n      this.debugLog(`In Rooch DID system:`);\n      this.debugLog(`   - DID account address: ${didAddress}`);\n      this.debugLog(`   - Signer address: ${signerAddress}`);\n      this.debugLog(`   - Operations must be signed by the DID account, not the controller`);\n      this.debugLog(`   - DID accounts can only sign via SessionKey or similar mechanism`);\n\n      // Legacy permission check (will likely fail at contract level)\n      // According to Rooch DID documentation, controllers should have management permissions\n      // Check if the signer is in the controller list\n      if (Array.isArray(didDocument.controller)) {\n        for (const controller of didDocument.controller) {\n          this.debugLog(`Checking controller:`, controller);\n\n          // Direct match (hex format)\n          if (controller === signerDIDHex) {\n            this.debugLog(`Signer is a controller (hex format) but may fail at contract level`);\n            return true;\n          }\n\n          // Try to handle bech32 format controllers\n          if (controller.includes('rooch1')) {\n            // For bech32 controllers, we need to convert addresses\n            // For now, we'll be permissive for controllers since the Rooch DID system\n            // should handle the actual authorization at the blockchain level\n            this.debugLog(\n              `Signer appears to be a controller (bech32 format) but may fail at contract level`\n            );\n            return true;\n          }\n\n          // Extract address from controller DID and compare\n          const controllerMatch = controller.match(/did:rooch:(.+)$/);\n          if (controllerMatch) {\n            const controllerAddress = controllerMatch[1];\n            if (\n              controllerAddress === signerAddress ||\n              controllerAddress.toLowerCase() === signerAddress.toLowerCase()\n            ) {\n              this.debugLog(`Address match found but may fail at contract level`);\n              return true;\n            }\n          }\n        }\n      }\n\n      // Check if signer controls any verification method with the required relationship\n      if (!didDocument.verificationMethod) {\n        this.debugLog(`No verification methods found`);\n        return false;\n      }\n\n      for (const vm of didDocument.verificationMethod) {\n        this.debugLog(`Checking verification method: ${vm.id}, controller: ${vm.controller}`);\n\n        // Check if this verification method is controlled by the signer\n        const isControlledBySigner =\n          vm.controller === signerDIDHex ||\n          vm.controller === didDocument.id ||\n          (Array.isArray(didDocument.controller) && didDocument.controller.includes(signerDIDHex));\n\n        if (isControlledBySigner) {\n          this.debugLog(`VM ${vm.id} is controlled by signer, checking relationships...`);\n\n          // Check if this verification method has the required relationship\n          const relationshipArray = didDocument[requiredRelationship] as (string | object)[];\n          if (relationshipArray) {\n            this.debugLog(`Relationship array for ${requiredRelationship}:`, relationshipArray);\n\n            const hasRelationship = relationshipArray.some(item => {\n              if (typeof item === 'string') {\n                return item === vm.id;\n              } else if (typeof item === 'object' && (item as any).id) {\n                return (item as any).id === vm.id;\n              }\n              return false;\n            });\n\n            if (hasRelationship) {\n              this.debugLog(`VM has required relationship but signer may not be DID account`);\n              return true;\n            }\n          }\n        }\n      }\n\n      this.errorLog(`Permission denied: No matching controller or VM relationship found`);\n      return false;\n    } catch (error) {\n      this.errorLog('Error checking permission:', error);\n      return false;\n    }\n  }\n\n  /**\n   * Parse DIDCreatedEvent using BCS schema and return the DID address\n   */\n  private parseDIDCreatedEventAndGetDID(event: EventView): string {\n    try {\n      const eventData = parseDIDCreatedEvent(event.event_data);\n      return eventData.did;\n    } catch (error) {\n      this.errorLog('BCS parsing failed:', error);\n      throw error;\n    }\n  }\n\n  /**\n   * Get the last created DID address from the most recent store operation\n   */\n  getLastCreatedDIDAddress(): string | undefined {\n    return this.lastCreatedDIDAddress;\n  }\n\n  /**\n   * Create a RoochVDR instance with default configuration\n   */\n  static createDefault(\n    network: 'local' | 'dev' | 'test' | 'main' = 'test',\n    rpcUrl: string | undefined = undefined\n  ): RoochVDR {\n    return new RoochVDR({\n      rpcUrl: rpcUrl || RoochVDR.getRoochNodeUrl(network),\n      network,\n    });\n  }\n\n  /**\n   * Get network-specific RPC URL\n   */\n  private static getRoochNodeUrl(network: 'local' | 'dev' | 'test' | 'main'): string {\n    // Map our network names to Rooch SDK network names\n    const networkMap: { [key: string]: string } = {\n      local: 'localnet',\n      dev: 'devnet',\n      test: 'testnet',\n      main: 'mainnet',\n    };\n\n    const roochNetwork = networkMap[network] || network;\n    return sdkGetRoochNodeUrl(roochNetwork as any);\n  }\n}\n","import { CryptoProvider } from '../providers';\nimport { KEY_TYPE, KeyType } from '../../types';\nimport { base64urlToBytes } from '../../utils/bytes';\nimport { IdentityKitErrorCode, createCryptoError } from '../../errors';\n\n// Universal helper to obtain a Web Crypto implementation in both browser and Node.js environments.\n// 1. In browsers (and newer versions of Node.js that expose `globalThis.crypto`) we return the global object.\n// 2. In other Node.js environments we fall back to the built-in `crypto.webcrypto` implementation that was\n//    imported above. This avoids using CommonJS `require`, which is not available in ESM bundles.\nfunction getCrypto(): Crypto {\n  // Use the built-in Web Crypto implementation exposed on globalThis.\n  if (typeof globalThis !== 'undefined' && (globalThis as any).crypto) {\n    return (globalThis as any).crypto as Crypto;\n  }\n\n  // If crypto is unavailable (e.g., very old Node versions), throw a descriptive error.\n  throw createCryptoError(\n    IdentityKitErrorCode.ENVIRONMENT_NOT_SUPPORTED,\n    'Web Crypto API is not available in the current runtime',\n    { environment: typeof globalThis, cryptoAvailable: false }\n  );\n}\n\nexport class Ed25519Provider implements CryptoProvider {\n  private crypto: Crypto;\n\n  constructor() {\n    this.crypto = getCrypto();\n  }\n\n  async generateKeyPair(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {\n    const generated = await this.crypto.subtle.generateKey(\n      {\n        name: 'Ed25519',\n      },\n      true,\n      ['sign', 'verify']\n    );\n\n    if (!('publicKey' in generated)) {\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_OPERATION_FAILED,\n        'Ed25519 generateKey did not return a key pair',\n        { keyType: 'Ed25519', operation: 'generateKeyPair' }\n      );\n    }\n    const { publicKey, privateKey } = generated;\n\n    const exportedPublic = new Uint8Array(await this.crypto.subtle.exportKey('raw', publicKey));\n    const exportedPrivate = new Uint8Array(await this.crypto.subtle.exportKey('pkcs8', privateKey));\n\n    return {\n      publicKey: exportedPublic,\n      privateKey: exportedPrivate,\n    };\n  }\n\n  async sign(data: Uint8Array, privateKey: Uint8Array | CryptoKey): Promise<Uint8Array> {\n    let key: CryptoKey;\n    if (privateKey instanceof Uint8Array) {\n      key = await this.crypto.subtle.importKey(\n        'pkcs8',\n        privateKey,\n        {\n          name: 'Ed25519',\n        },\n        false,\n        ['sign']\n      );\n    } else {\n      key = privateKey;\n    }\n\n    const signature = await this.crypto.subtle.sign('Ed25519', key, data);\n\n    return new Uint8Array(signature);\n  }\n\n  async verify(\n    data: Uint8Array,\n    signature: Uint8Array,\n    publicKey: Uint8Array | JsonWebKey\n  ): Promise<boolean> {\n    let key: CryptoKey;\n    if (publicKey instanceof Uint8Array) {\n      key = await this.crypto.subtle.importKey(\n        'raw',\n        publicKey,\n        {\n          name: 'Ed25519',\n        },\n        false,\n        ['verify']\n      );\n    } else {\n      key = await this.crypto.subtle.importKey(\n        'jwk',\n        publicKey,\n        {\n          name: 'Ed25519',\n        },\n        false,\n        ['verify']\n      );\n    }\n\n    return await this.crypto.subtle.verify('Ed25519', key, signature, data);\n  }\n\n  getKeyType(): KeyType {\n    return KEY_TYPE.ED25519;\n  }\n\n  async derivePublicKey(privateKey: Uint8Array): Promise<Uint8Array> {\n    // Import private key as exportable\n    const cryptoKey = await this.crypto.subtle.importKey(\n      'pkcs8',\n      privateKey,\n      { name: 'Ed25519' },\n      true,\n      ['sign']\n    );\n\n    // Generate a temporary key pair and use the same private key to get corresponding public key\n    // This is a workaround since Web Crypto API doesn't allow direct derivation\n    // We'll export as JWK and extract the public key coordinates\n    const jwk = await this.crypto.subtle.exportKey('jwk', cryptoKey);\n    if (!jwk.x) {\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_KEY_DERIVATION_FAILED,\n        'Failed to derive public key from private key',\n        { keyType: 'Ed25519', operation: 'derivePublicKey' }\n      );\n    }\n\n    // Convert base64url public key to raw bytes\n    const publicKeyBytes = base64urlToBytes(jwk.x);\n    return publicKeyBytes;\n  }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { CryptoProvider } from '../providers';\nimport { KEY_TYPE, KeyType } from '../../types';\nimport { IdentityKitErrorCode, createCryptoError } from '../../errors';\n\nexport class Secp256k1Provider implements CryptoProvider {\n  async generateKeyPair(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {\n    const privateKey = secp256k1.utils.randomPrivateKey();\n    const publicKey = secp256k1.getPublicKey(privateKey, true); // compressed format\n\n    return {\n      publicKey,\n      privateKey,\n    };\n  }\n\n  async sign(data: Uint8Array, privateKey: Uint8Array | CryptoKey): Promise<Uint8Array> {\n    if (privateKey instanceof CryptoKey) {\n      throw createCryptoError(\n        IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n        'CryptoKey is not supported for Secp256k1 signing',\n        { keyType: 'Secp256k1', operation: 'sign', privateKeyType: 'CryptoKey' }\n      );\n    }\n    const msgHash = sha256(data);\n    const signature = secp256k1.sign(msgHash, privateKey);\n    return signature.toCompactRawBytes();\n  }\n\n  async verify(\n    data: Uint8Array,\n    signature: Uint8Array,\n    publicKey: Uint8Array | JsonWebKey\n  ): Promise<boolean> {\n    if (!(publicKey instanceof Uint8Array)) {\n      throw createCryptoError(\n        IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n        'JsonWebKey is not supported for Secp256k1 verification',\n        { keyType: 'Secp256k1', operation: 'verify', publicKeyType: 'JsonWebKey' }\n      );\n    }\n    const msgHash = sha256(data);\n    return secp256k1.verify(signature, msgHash, publicKey);\n  }\n\n  getKeyType(): KeyType {\n    return KEY_TYPE.SECP256K1;\n  }\n\n  async derivePublicKey(privateKey: Uint8Array): Promise<Uint8Array> {\n    return secp256k1.getPublicKey(privateKey, true); // compressed format\n  }\n}\n","import { p256 } from '@noble/curves/p256';\nimport { bytesToHex, hexToBytes } from '@noble/curves/abstract/utils';\nimport { CryptoProvider } from '../providers';\nimport { KEY_TYPE, KeyType } from '../../types';\nimport { base64urlToBytes } from '../../utils/bytes';\nimport { IdentityKitErrorCode, createCryptoError, createValidationError } from '../../errors';\n\n// Universal helper to obtain a Web Crypto implementation in both browser and Node.js environments.\nfunction getCrypto(): Crypto {\n  if (typeof globalThis !== 'undefined' && (globalThis as any).crypto) {\n    return (globalThis as any).crypto as Crypto;\n  }\n  throw createCryptoError(\n    IdentityKitErrorCode.ENVIRONMENT_NOT_SUPPORTED,\n    'Web Crypto API is not available in the current runtime',\n    { environment: typeof globalThis, cryptoAvailable: false }\n  );\n}\n\nexport class EcdsaR1Provider implements CryptoProvider {\n  private crypto: Crypto;\n\n  constructor() {\n    this.crypto = getCrypto();\n  }\n\n  async generateKeyPair(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {\n    const generated = await this.crypto.subtle.generateKey(\n      {\n        name: 'ECDSA',\n        namedCurve: 'P-256',\n      },\n      true,\n      ['sign', 'verify']\n    );\n\n    if (!('publicKey' in generated)) {\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_OPERATION_FAILED,\n        'ECDSA P-256 generateKey did not return a key pair',\n        { keyType: 'ECDSA-R1', operation: 'generateKeyPair' }\n      );\n    }\n    const { publicKey, privateKey } = generated;\n\n    const exportedPublic = new Uint8Array(await this.crypto.subtle.exportKey('raw', publicKey));\n    const exportedPrivate = new Uint8Array(await this.crypto.subtle.exportKey('pkcs8', privateKey));\n\n    // Compress the public key to 33 bytes\n    const compressedPublicKey = this.compressPublicKey(exportedPublic);\n\n    return {\n      publicKey: compressedPublicKey,\n      privateKey: exportedPrivate,\n    };\n  }\n\n  private compressPublicKey(publicKey: Uint8Array): Uint8Array {\n    if (publicKey.length !== 65) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        `Invalid public key length. Expected 65 bytes, got ${publicKey.length}`,\n        { expectedLength: 65, actualLength: publicKey.length, keyType: 'ECDSA-R1' }\n      );\n    }\n\n    // First byte is the format (0x04 for uncompressed)\n    if (publicKey[0] !== 0x04) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        'Invalid public key format. Expected uncompressed format (0x04)',\n        { actualPrefix: publicKey[0], expectedPrefix: 0x04, keyType: 'ECDSA-R1' }\n      );\n    }\n\n    // Extract x and y coordinates\n    const x = publicKey.slice(1, 33);\n    const y = publicKey.slice(33, 65);\n\n    // Create compressed format (0x02 or 0x03) + x coordinate\n    const compressedFormat = y[31] % 2 === 0 ? 0x02 : 0x03;\n\n    const compressed = new Uint8Array(33);\n    compressed[0] = compressedFormat;\n    compressed.set(x, 1);\n\n    return compressed;\n  }\n\n  private decompressPublicKey(compressedKey: Uint8Array): Uint8Array {\n    if (compressedKey.length !== 33) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        `Invalid compressed public key length. Expected 33 bytes, got ${compressedKey.length}`,\n        { expectedLength: 33, actualLength: compressedKey.length, keyType: 'ECDSA-R1' }\n      );\n    }\n    const format = compressedKey[0];\n    if (format !== 0x02 && format !== 0x03) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        'Invalid compressed public key format. Expected 0x02 or 0x03',\n        { actualPrefix: compressedKey[0], expectedPrefixes: [0x02, 0x03], keyType: 'ECDSA-R1' }\n      );\n    }\n    try {\n      const point = p256.ProjectivePoint.fromHex(compressedKey);\n      const x = point.x;\n      const y = point.y;\n      const xBytes = hexToBytes(x.toString(16).padStart(64, '0'));\n      const yBytes = hexToBytes(y.toString(16).padStart(64, '0'));\n      const decompressed = new Uint8Array(65);\n      decompressed[0] = 0x04;\n      decompressed.set(xBytes, 1);\n      decompressed.set(yBytes, 33);\n      return decompressed;\n    } catch (err) {\n      const error = err as Error;\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_OPERATION_FAILED,\n        `Failed to decompress public key: ${error.message}`,\n        { keyType: 'ECDSA-R1', operation: 'decompressPublicKey', originalError: error.message }\n      );\n    }\n  }\n\n  async sign(data: Uint8Array, privateKey: Uint8Array | CryptoKey): Promise<Uint8Array> {\n    let key: CryptoKey;\n    if (privateKey instanceof Uint8Array) {\n      key = await this.crypto.subtle.importKey(\n        'pkcs8',\n        privateKey,\n        {\n          name: 'ECDSA',\n          namedCurve: 'P-256',\n        },\n        false,\n        ['sign']\n      );\n    } else {\n      key = privateKey;\n    }\n\n    const signature = await this.crypto.subtle.sign(\n      {\n        name: 'ECDSA',\n        hash: { name: 'SHA-256' },\n      },\n      key,\n      data\n    );\n\n    return new Uint8Array(signature);\n  }\n\n  private convertDERSignatureToRaw(derSignature: Uint8Array): Uint8Array {\n    // If DER -> convert to raw 64\n    const firstByte = derSignature[0];\n    if (firstByte === 0x30) {\n      // looks like DER\n      try {\n        const sig = p256.Signature.fromDER(derSignature);\n        return sig.toCompactRawBytes();\n      } catch (e) {\n        throw createValidationError(\n          IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n          'Invalid DER signature',\n          { keyType: 'ECDSA-R1', operation: 'parseDERSignature' }\n        );\n      }\n    }\n    // else assume already raw 64\n    return derSignature;\n  }\n\n  private convertRawToDER(raw: Uint8Array): Uint8Array {\n    if (raw.length !== 64) return raw;\n    const r = bytesToHex(raw.slice(0, 32));\n    const s = bytesToHex(raw.slice(32, 64));\n    const der = p256.Signature.fromCompact(hexToBytes(r + s)).toDERHex();\n    return hexToBytes(der);\n  }\n\n  async verify(\n    data: Uint8Array,\n    signature: Uint8Array,\n    publicKey: Uint8Array | JsonWebKey\n  ): Promise<boolean> {\n    let key: CryptoKey;\n    if (publicKey instanceof Uint8Array) {\n      // Decompress the public key before importing\n      const decompressedKey = this.decompressPublicKey(publicKey);\n      key = await this.crypto.subtle.importKey(\n        'raw',\n        decompressedKey,\n        {\n          name: 'ECDSA',\n          namedCurve: 'P-256',\n        },\n        false,\n        ['verify']\n      );\n    } else {\n      key = await this.crypto.subtle.importKey(\n        'jwk',\n        publicKey,\n        {\n          name: 'ECDSA',\n          namedCurve: 'P-256',\n        },\n        false,\n        ['verify']\n      );\n    }\n\n    return await this.crypto.subtle.verify(\n      {\n        name: 'ECDSA',\n        hash: { name: 'SHA-256' },\n      },\n      key,\n      signature,\n      data\n    );\n  }\n\n  getKeyType(): KeyType {\n    return KEY_TYPE.ECDSAR1;\n  }\n\n  async derivePublicKey(privateKey: Uint8Array): Promise<Uint8Array> {\n    // Import private key\n    const cryptoKey = await this.crypto.subtle.importKey(\n      'pkcs8',\n      privateKey,\n      { name: 'ECDSA', namedCurve: 'P-256' },\n      true,\n      ['sign']\n    );\n\n    // Export as JWK to get public key coordinates\n    const jwk = await this.crypto.subtle.exportKey('jwk', cryptoKey);\n    if (!jwk.x || !jwk.y) {\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_KEY_DERIVATION_FAILED,\n        'Failed to derive public key from private key',\n        { keyType: 'ECDSA-R1', operation: 'derivePublicKey' }\n      );\n    }\n\n    // Convert base64url coordinates to raw bytes\n    const x = base64urlToBytes(jwk.x);\n    const y = base64urlToBytes(jwk.y);\n\n    // Reconstruct uncompressed public key (0x04 + x + y)\n    const uncompressed = new Uint8Array(65);\n    uncompressed[0] = 0x04;\n    uncompressed.set(x, 1);\n    uncompressed.set(y, 33);\n\n    // Compress the public key to match our standard format\n    return this.compressPublicKey(uncompressed);\n  }\n}\n","import { CryptoProvider, CryptoProviderFactory } from './providers';\nimport { Ed25519Provider } from './providers/ed25519';\nimport { Secp256k1Provider } from './providers/secp256k1';\nimport { EcdsaR1Provider } from './providers/ecdsa_r1';\nimport { KEY_TYPE, KeyType } from '../types/crypto';\nimport { IdentityKitErrorCode, createCryptoError } from '../errors';\n\nexport class DefaultCryptoProviderFactory implements CryptoProviderFactory {\n  private providers: Map<KeyType, CryptoProvider>;\n\n  constructor() {\n    this.providers = new Map();\n    this.providers.set(KEY_TYPE.ED25519, new Ed25519Provider());\n    this.providers.set(KEY_TYPE.SECP256K1, new Secp256k1Provider());\n    this.providers.set(KEY_TYPE.ECDSAR1, new EcdsaR1Provider());\n  }\n\n  createProvider(keyType: KeyType): CryptoProvider {\n    const provider = this.providers.get(keyType);\n    if (!provider) {\n      throw createCryptoError(\n        IdentityKitErrorCode.CRYPTO_PROVIDER_NOT_FOUND,\n        `No provider available for key type: ${keyType}`,\n        { keyType, availableTypes: Array.from(this.providers.keys()) }\n      );\n    }\n    return provider;\n  }\n\n  supports(keyType: KeyType): boolean {\n    return this.providers.has(keyType);\n  }\n}\n\n/**\n * Default instance of the crypto provider factory\n */\nexport const defaultCryptoProviderFactory = new DefaultCryptoProviderFactory();\n","import { KeyType, KeyTypeInput, toKeyType } from '../types/crypto';\nimport { defaultCryptoProviderFactory } from './factory';\n\n/**\n * CryptoUtils provides cross-platform cryptographic utilities for DID operations.\n * It abstracts the complexity of different key types and formats.\n */\nexport class CryptoUtils {\n  /**\n   * Generates a key pair based on the specified curve\n   * @param type The key type to generate (Ed25519VerificationKey2020 or EcdsaSecp256k1VerificationKey2019 or EcdsaSecp256r1VerificationKey2019)\n   * @returns A key pair containing public and private keys\n   */\n  static async generateKeyPair(\n    type: KeyTypeInput = KeyType.ED25519\n  ): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {\n    const keyType = typeof type === 'string' ? toKeyType(type) : type;\n    const provider = defaultCryptoProviderFactory.createProvider(keyType);\n    return provider.generateKeyPair();\n  }\n\n  /**\n   * Signs data using the specified private key\n   * @param data The data to sign\n   * @param privateKey The private key to use for signing (can be Uint8Array or CryptoKey)\n   * @param type The key type (Ed25519VerificationKey2020 or EcdsaSecp256k1VerificationKey2019)\n   * @returns The signature as a Uint8Array\n   */\n  static async sign(\n    data: Uint8Array,\n    privateKey: Uint8Array | CryptoKey,\n    type: KeyTypeInput\n  ): Promise<Uint8Array> {\n    const keyType = typeof type === 'string' ? toKeyType(type) : type;\n    const provider = defaultCryptoProviderFactory.createProvider(keyType);\n    return provider.sign(data, privateKey);\n  }\n\n  /**\n   * Verifies a signature using the specified public key\n   * @param data The original data\n   * @param signature The signature to verify\n   * @param publicKey The public key to use for verification (can be Uint8Array or JsonWebKey)\n   * @param type The key type (Ed25519VerificationKey2020 or EcdsaSecp256k1VerificationKey2019)\n   * @returns Whether the signature is valid\n   */\n  static async verify(\n    data: Uint8Array,\n    signature: Uint8Array,\n    publicKey: Uint8Array | JsonWebKey,\n    type: KeyTypeInput\n  ): Promise<boolean> {\n    const keyType = typeof type === 'string' ? toKeyType(type) : type;\n    const provider = defaultCryptoProviderFactory.createProvider(keyType);\n    return provider.verify(data, signature, publicKey);\n  }\n\n  /**\n   * Derive public key from private key\n   * @param privateKey The private key bytes\n   * @param keyType The key type\n   * @returns The corresponding public key bytes\n   */\n  static async derivePublicKey(privateKey: Uint8Array, keyType: KeyTypeInput): Promise<Uint8Array> {\n    const type = typeof keyType === 'string' ? toKeyType(keyType) : keyType;\n    const provider = defaultCryptoProviderFactory.createProvider(type);\n    return provider.derivePublicKey(privateKey);\n  }\n\n  /**\n   * Validate the consistency between a private key and public key pair\n   * @param privateKey The private key bytes\n   * @param publicKey The public key bytes\n   * @param keyType The key type\n   * @returns true if the keys are consistent, false otherwise\n   */\n  static async validateKeyPairConsistency(\n    privateKey: Uint8Array,\n    publicKey: Uint8Array,\n    keyType: KeyTypeInput\n  ): Promise<boolean> {\n    try {\n      // Derive public key from private key\n      const derivedPublicKey = await this.derivePublicKey(privateKey, keyType);\n\n      // Compare if public keys match\n      return this.areUint8ArraysEqual(derivedPublicKey, publicKey);\n    } catch (error) {\n      console.warn('Key pair consistency validation failed:', error);\n      return false;\n    }\n  }\n\n  /**\n   * Compare two Uint8Array for equality\n   * @param a First array\n   * @param b Second array\n   * @returns true if arrays are equal, false otherwise\n   */\n  private static areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean {\n    if (a.length !== b.length) return false;\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] !== b[i]) return false;\n    }\n    return true;\n  }\n}\n","// Copyright (c) RoochNetwork\n// SPDX-License-Identifier: Apache-2.0\n\nimport { p256 } from '@noble/curves/p256';\nimport {\n  RoochAddress,\n  PublicKey,\n  PublicKeyInitData,\n  SIGNATURE_SCHEME_TO_FLAG,\n  Address,\n  Bytes,\n  blake2b,\n  fromB64,\n} from '@roochnetwork/rooch-sdk';\nimport { IdentityKitErrorCode, createValidationError } from '../errors';\n\nconst PUBLIC_KEY_SIZE = 33; // Compressed P-256 public key size\n\n/**\n * An ECDSA R1 (P-256) public key implementation for identity-kit\n * This is a temporary implementation until EcdsaR1PublicKey is available in rooch-sdk\n */\nexport class EcdsaR1PublicKey extends PublicKey<Address> {\n  static SIZE = PUBLIC_KEY_SIZE;\n\n  private readonly data: Uint8Array;\n\n  /**\n   * Create a new EcdsaR1PublicKey object\n   * @param value ECDSA R1 public key as buffer or base-64 encoded string\n   */\n  constructor(value: PublicKeyInitData) {\n    super();\n\n    if (typeof value === 'string') {\n      this.data = fromB64(value);\n    } else if (value instanceof Uint8Array) {\n      this.data = value;\n    } else {\n      this.data = Uint8Array.from(value);\n    }\n\n    if (this.data.length !== PUBLIC_KEY_SIZE) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        `Invalid public key input. Expected ${PUBLIC_KEY_SIZE} bytes, got ${this.data.length}`,\n        { expectedSize: PUBLIC_KEY_SIZE, actualSize: this.data.length, keyType: 'ECDSA-R1' }\n      );\n    }\n  }\n\n  /**\n   * Checks if two EcdsaR1 public keys are equal\n   */\n  override equals(publicKey: EcdsaR1PublicKey): boolean {\n    return super.equals(publicKey);\n  }\n\n  /**\n   * Return the byte array representation of the ECDSA R1 public key\n   */\n  toBytes(): Uint8Array {\n    return this.data;\n  }\n\n  /**\n   * Return the signature scheme flag for ECDSA R1\n   */\n  flag(): number {\n    return SIGNATURE_SCHEME_TO_FLAG.EcdsaR1;\n  }\n\n  /**\n   * Verifies that the signature is valid for the provided message\n   */\n  async verify(message: Uint8Array, signature: Uint8Array): Promise<boolean> {\n    try {\n      // Verify signature using noble curves with compressed public key bytes\n      return p256.verify(signature, message, this.toBytes());\n    } catch (error) {\n      return false;\n    }\n  }\n\n  /**\n   * Return the Rooch address associated with this ECDSA R1 public key\n   */\n  toAddress(): RoochAddress {\n    const tmp = new Uint8Array(PUBLIC_KEY_SIZE + 1);\n    tmp.set([SIGNATURE_SCHEME_TO_FLAG.EcdsaR1]);\n    tmp.set(this.toBytes(), 1);\n\n    // Each hex char represents half a byte, hence hex address doubles the length\n    const ROOCH_ADDRESS_LENGTH = 32;\n    return new RoochAddress(blake2b(tmp, { dkLen: 32 }).slice(0, ROOCH_ADDRESS_LENGTH * 2));\n  }\n}\n","import { KeyStore } from '../keys/KeyStore';\nimport { KeyType } from '../types/crypto';\nimport { MultibaseCodec } from '../multibase';\nimport { CryptoUtils } from '../crypto';\nimport { IdentityKitErrorCode, createKeyManagementError } from '../errors';\n\n/**\n * Sign data with the given KeyStore. If the KeyStore itself implements a\n * `sign()` method (e.g., for WebAuthn / non-extractable keys), that method\n * is preferred. Otherwise the private key is loaded and the signature is\n * produced via `CryptoUtils.sign()`.\n *\n * @param keyStore  The key store to use\n * @param data      The data to sign\n * @param keyId     Full verificationMethod id (did#fragment)\n */\nexport async function signWithKeyStore(\n  keyStore: KeyStore,\n  data: Uint8Array,\n  keyId: string\n): Promise<Uint8Array> {\n  if (typeof (keyStore as any).sign === 'function') {\n    // KeyStore 自带原子签名（例如 WebAuthn）\n    return (keyStore as any).sign(keyId, data);\n  }\n\n  const key = await keyStore.load(keyId);\n  if (!key) {\n    throw createKeyManagementError(IdentityKitErrorCode.KEY_NOT_FOUND, `Key not found: ${keyId}`, {\n      keyId,\n    });\n  }\n  if (!key.privateKeyMultibase) {\n    throw createKeyManagementError(\n      IdentityKitErrorCode.KEY_PRIVATE_KEY_NOT_AVAILABLE,\n      `No private key available for ${keyId}`,\n      { keyId }\n    );\n  }\n\n  const privateKeyBytes = MultibaseCodec.decode(key.privateKeyMultibase);\n  return CryptoUtils.sign(data, privateKeyBytes, key.keyType);\n}\n\n/**\n * Test whether a key can be used for signing in this KeyStore.\n */\nexport async function canSignWithKeyStore(keyStore: KeyStore, keyId: string): Promise<boolean> {\n  if (typeof (keyStore as any).sign === 'function') {\n    const keyExists = await keyStore.load(keyId);\n    return keyExists !== null;\n  }\n  const key = await keyStore.load(keyId);\n  return !!(key && key.privateKeyMultibase);\n}\n\n/**\n * Retrieve public key + type info from the KeyStore.\n */\nexport async function getKeyInfoFromKeyStore(\n  keyStore: KeyStore,\n  keyId: string\n): Promise<{ type: KeyType; publicKey: Uint8Array } | undefined> {\n  const key = await keyStore.load(keyId);\n  if (!key) return undefined;\n  const publicKeyBytes = MultibaseCodec.decode(key.publicKeyMultibase);\n  return { type: key.keyType, publicKey: publicKeyBytes };\n}\n","// Signer interfaces and types\n\nimport { KeyType } from '../types/crypto';\nimport { Signer } from '@roochnetwork/rooch-sdk';\n\n/**\n * Interface for external signers that can be used for master key operations\n * This allows the SDK to request signatures from external systems (wallets, HSMs, etc.)\n * without directly managing the private keys\n */\nexport interface SignerInterface {\n  /**\n   * List all available key IDs that this signer can use\n   * @returns Promise resolving to an array of key IDs\n   */\n  listKeyIds(): Promise<string[]>;\n\n  /**\n   * Signs data with a specified key\n   * @param data The data to sign\n   * @param keyId The ID of the key to use for signing\n   * @returns A promise that resolves to the signature\n   */\n  signWithKeyId(data: Uint8Array, keyId: string): Promise<Uint8Array>;\n\n  /**\n   * Checks if the signer can sign with a specific key\n   * @param keyId The ID of the key to check\n   * @returns A promise that resolves to true if the signer can sign with the key\n   */\n  canSignWithKeyId(keyId: string): Promise<boolean>;\n\n  /**\n   * Get the DID of the signer\n   * @returns The DID of the signer\n   */\n  getDid(): Promise<string>;\n\n  /**\n   * Get information about a specific key\n   * @param keyId The ID of the key to get information about\n   * @returns Key information or undefined if not found\n   */\n  getKeyInfo(keyId: string): Promise<{ type: KeyType; publicKey: Uint8Array } | undefined>;\n}\n\n/**\n * Type guard utilities for SignerInterface and Signer\n * These are more reliable than instanceof when dealing with cross-module dependencies\n */\n\n/**\n * Check if an object implements SignerInterface (but not Signer)\n * This is more reliable than instanceof when dealing with cross-module dependencies\n */\nexport function isSignerInterface(obj: any): obj is SignerInterface {\n  return (\n    obj &&\n    typeof obj === 'object' &&\n    typeof obj.listKeyIds === 'function' &&\n    typeof obj.signWithKeyId === 'function' &&\n    typeof obj.canSignWithKeyId === 'function' &&\n    typeof obj.getDid === 'function' &&\n    typeof obj.getKeyInfo === 'function' &&\n    // Check that it's NOT a Signer (which has different methods)\n    typeof obj.sign !== 'function'\n  );\n}\n","import {\n  RoochAddress,\n  SignatureScheme,\n  Signer,\n  Transaction,\n  Address,\n  Bytes,\n  Authenticator,\n  BitcoinAddress,\n  PublicKey,\n  Ed25519PublicKey,\n  Secp256k1PublicKey,\n} from '@roochnetwork/rooch-sdk';\nimport { SignerInterface } from './types';\nimport { KeyType, keyTypeToRoochSignatureScheme } from '../types/crypto';\nimport { parseDid } from '../utils/did';\nimport { EcdsaR1PublicKey } from '../crypto/EcdsaR1PublicKey';\nimport { IdentityKitErrorCode, createSignerError, createValidationError } from '../errors';\n\n/**\n * A Rooch Signer implementation that wraps a SignerInterface.\n * This class implements the Rooch Signer interface while delegating\n * actual signing operations to the wrapped SignerInterface.\n */\nexport class DidAccountSigner extends Signer implements SignerInterface {\n  private readonly __brandDidAccountSigner = true;\n  private did: string;\n  private keyId: string;\n  private didAddress: RoochAddress;\n  private keyType: KeyType;\n  private publicKey: Uint8Array;\n\n  private constructor(\n    private wrappedSigner: SignerInterface,\n    did: string,\n    keyId: string,\n    keyType: KeyType,\n    publicKey: Uint8Array\n  ) {\n    super();\n    this.keyId = keyId;\n    this.did = did;\n    if (!this.did.startsWith('did:rooch:')) {\n      throw createSignerError(\n        IdentityKitErrorCode.SIGNER_INVALID_DID,\n        'Signer DID must be a did:rooch DID',\n        { did: this.did, expectedMethod: 'rooch' }\n      );\n    }\n    const didParts = parseDid(did);\n    this.didAddress = new RoochAddress(didParts.identifier);\n    this.keyType = keyType;\n    this.publicKey = publicKey;\n  }\n\n  /**\n   * Create a DidAccountSigner instance from a SignerInterface\n   * @param signer The signer to wrap\n   * @param keyId Optional specific keyId to use\n   * @returns A new DidAccountSigner instance\n   */\n  /**\n   * Check if an object is a DidAccountSigner instance\n   * Safe to use instanceof within the same module\n   */\n  static isDidAccountSigner(obj: any): obj is DidAccountSigner {\n    return obj instanceof DidAccountSigner;\n  }\n\n  static async create(signer: SignerInterface, keyId?: string): Promise<DidAccountSigner> {\n    // If already a DidAccountSigner, return as is\n    if (DidAccountSigner.isDidAccountSigner(signer)) {\n      return signer;\n    }\n\n    // Get keyId if not provided\n    const actualKeyId = keyId || (await signer.listKeyIds())[0];\n    if (!actualKeyId) {\n      throw createSignerError(IdentityKitErrorCode.SIGNER_NO_KEYS, 'No available keys in signer', {\n        signer,\n      });\n    }\n\n    // Get key info\n    const keyInfo = await signer.getKeyInfo(actualKeyId);\n    if (!keyInfo) {\n      throw createSignerError(\n        IdentityKitErrorCode.KEY_NOT_FOUND,\n        `Key info not found for keyId: ${actualKeyId}`,\n        { keyId: actualKeyId, signer }\n      );\n    }\n\n    const did = await signer.getDid();\n\n    const didSigner = new DidAccountSigner(\n      signer,\n      did,\n      actualKeyId,\n      keyInfo.type,\n      keyInfo.publicKey\n    );\n\n    // If underlying signer supports WebAuthn, expose signAssertion so Authenticator picks WebAuthn envelope\n    const maybeWebAuthn = signer as any;\n    if (maybeWebAuthn && typeof maybeWebAuthn.signAssertion === 'function') {\n      (didSigner as any).signAssertion = (challenge: Bytes) =>\n        maybeWebAuthn.signAssertion(challenge);\n    }\n\n    return didSigner;\n  }\n\n  // Implement Rooch Signer interface\n  getRoochAddress(): RoochAddress {\n    return this.didAddress;\n  }\n\n  async sign(input: Bytes): Promise<Bytes> {\n    return this.wrappedSigner.signWithKeyId(input, this.keyId);\n  }\n\n  async signTransaction(input: Transaction): Promise<Authenticator> {\n    const txHash = input.hashData();\n    const vmFragment = this.getVmFragment();\n    return Authenticator.did(txHash, this, vmFragment);\n  }\n\n  getKeyScheme(): SignatureScheme {\n    return keyTypeToRoochSignatureScheme(this.keyType);\n  }\n\n  getPublicKey(): PublicKey<Address> {\n    if (this.keyType === KeyType.SECP256K1) {\n      return new Secp256k1PublicKey(this.publicKey);\n    } else if (this.keyType === KeyType.ED25519) {\n      return new Ed25519PublicKey(this.publicKey);\n    } else if (this.keyType === KeyType.ECDSAR1) {\n      return new EcdsaR1PublicKey(this.publicKey);\n    } else {\n      throw createSignerError(\n        IdentityKitErrorCode.KEY_TYPE_NOT_SUPPORTED,\n        `Unsupported key type: ${this.keyType}`,\n        { keyType: this.keyType, supportedTypes: ['Ed25519', 'Secp256k1', 'EcdsaR1'] }\n      );\n    }\n  }\n\n  getBitcoinAddress(): BitcoinAddress {\n    throw createSignerError(\n      IdentityKitErrorCode.OPERATION_NOT_SUPPORTED,\n      'Bitcoin address is not supported for DID account',\n      { operation: 'getBitcoinAddress' }\n    );\n  }\n\n  // Implement SignerInterface\n  async signWithKeyId(data: Uint8Array, keyId: string): Promise<Uint8Array> {\n    if (keyId !== this.keyId) {\n      throw createValidationError(\n        IdentityKitErrorCode.KEY_ID_MISMATCH,\n        `Key ID mismatch. Expected ${this.keyId}, got ${keyId}`,\n        { expectedKeyId: this.keyId, actualKeyId: keyId }\n      );\n    }\n    return this.sign(data);\n  }\n\n  async canSignWithKeyId(keyId: string): Promise<boolean> {\n    return keyId === this.keyId;\n  }\n\n  async listKeyIds(): Promise<string[]> {\n    return [this.keyId];\n  }\n\n  async getDid(): Promise<string> {\n    return this.did;\n  }\n\n  async getKeyInfo(keyId: string): Promise<{ type: KeyType; publicKey: Uint8Array } | undefined> {\n    if (keyId !== this.keyId) {\n      return undefined;\n    }\n    return {\n      type: this.keyType,\n      publicKey: this.publicKey,\n    };\n  }\n\n  private getVmFragment(): string {\n    const parts = this.keyId.split('#');\n    if (parts.length !== 2) {\n      throw createValidationError(\n        IdentityKitErrorCode.INVALID_INPUT_FORMAT,\n        `Invalid keyId format: ${this.keyId}. Expected format: \"did:rooch:0x123#fragment\"`,\n        { keyId: this.keyId, expectedFormat: 'did:rooch:0x123#fragment' }\n      );\n    }\n    return parts[1];\n  }\n}\n\n/**\n * Exported function for checking DidAccountSigner instances\n */\nexport function isDidAccountSigner(obj: any): obj is DidAccountSigner {\n  return Boolean(obj && obj.__brandDidAccountSigner === true);\n}\n","import {\n  bcs,\n  address,\n  sha3_256,\n  toHEX,\n  stringToBytes,\n  Serializer,\n  StructTag,\n  ObjectStateView,\n} from '@roochnetwork/rooch-sdk';\nimport { DIDDocument, ServiceEndpoint, VerificationMethod } from '../types/did';\n\n/**\n * BCS type definitions for DID related structs\n */\n\n// SimpleMap schema generator\nexport function simpleMapSchema<K, V>(keySchema: any, valueSchema: any) {\n  return bcs.struct('SimpleMap', {\n    data: bcs.vector(\n      bcs.struct('Entry', {\n        key: keySchema,\n        value: valueSchema,\n      })\n    ),\n  });\n}\n\n// Basic DID struct\nexport interface DIDStruct {\n  method: string;\n  identifier: string;\n}\n\n// Helper function to format DID string\nexport function formatDIDString(did: DIDStruct): string {\n  return `did:${did.method}:${did.identifier}`;\n}\n\n// DID Document verification method\nexport interface MoveVerificationMethod {\n  id: {\n    did: DIDStruct;\n    fragment: string;\n  };\n  type: string;\n  controller: DIDStruct;\n  public_key_multibase: string;\n}\n\n// DID Document service\nexport interface MoveService {\n  id: {\n    did: DIDStruct;\n    fragment: string;\n  };\n  type: string;\n  service_endpoint: string;\n  properties: SimpleMap<string, string>;\n}\n\n// Complete DID Document struct from Move\nexport interface MoveDIDDocument {\n  id: DIDStruct;\n  controller: DIDStruct[];\n  verification_methods: Map<string, MoveVerificationMethod>;\n  authentication: string[];\n  assertion_method: string[];\n  capability_invocation: string[];\n  capability_delegation: string[];\n  key_agreement: string[];\n  services: Map<string, MoveService>;\n  also_known_as: string[];\n}\n\n// DID Created Event data\nexport interface DIDCreatedEventData {\n  did: string;\n  object_id: string;\n  controller: string[];\n  creator_address: address;\n}\n\n/**\n * BCS Schemas\n */\n\n// Basic DID schema\nexport const DIDSchema = bcs.struct('DID', {\n  method: bcs.string(),\n  identifier: bcs.string(),\n});\n\n// DID ID schema (with fragment)\nexport const DIDIdSchema = bcs.struct('DIDID', {\n  did: DIDSchema,\n  fragment: bcs.string(),\n});\n\n// Verification Method schema\nexport const VerificationMethodSchema = bcs.struct('VerificationMethod', {\n  id: DIDIdSchema,\n  type: bcs.string(),\n  controller: DIDSchema,\n  public_key_multibase: bcs.string(),\n});\n\n// Service schema\nexport const ServiceSchema = bcs.struct('Service', {\n  id: DIDIdSchema,\n  type: bcs.string(),\n  service_endpoint: bcs.string(),\n  properties: simpleMapSchema(bcs.string(), bcs.string()),\n});\n\nexport const AccountCapSchema = bcs.struct('AccountCap', {\n  addr: bcs.Address,\n});\n\n// Complete DID Document schema\nexport const DIDDocumentSchema = bcs.struct('DIDDocument', {\n  id: DIDSchema,\n  controller: bcs.vector(DIDSchema),\n  verification_methods: simpleMapSchema(bcs.string(), VerificationMethodSchema),\n  authentication: bcs.vector(bcs.string()),\n  assertion_method: bcs.vector(bcs.string()),\n  capability_invocation: bcs.vector(bcs.string()),\n  capability_delegation: bcs.vector(bcs.string()),\n  key_agreement: bcs.vector(bcs.string()),\n  services: simpleMapSchema(bcs.string(), ServiceSchema),\n  also_known_as: bcs.vector(bcs.string()),\n  account_cap: AccountCapSchema,\n});\n\n// DID Created Event schema\nexport const DIDCreatedEventSchema = bcs.struct('DIDCreatedEvent', {\n  did: bcs.string(),\n  object_id: bcs.ObjectId,\n  controller: bcs.vector(bcs.string()),\n  creator_address: bcs.Address,\n});\n\n/**\n * SimpleMap type and conversion helpers\n */\n\n// TypeScript interface for SimpleMap\nexport interface SimpleMap<K, V> {\n  data: Array<{\n    key: K;\n    value: V;\n  }>;\n}\n\n// Convert SimpleMap to standard Map\nexport function simpleMapToMap<K, V>(simpleMap: SimpleMap<K, V>): Map<K, V> {\n  return new Map(simpleMap.data.map(entry => [entry.key, entry.value]));\n}\n\n// Convert standard Map to SimpleMap\nexport function mapToSimpleMap<K, V>(map: Map<K, V>): SimpleMap<K, V> {\n  return {\n    data: Array.from(map.entries()).map(([key, value]) => ({\n      key,\n      value,\n    })),\n  };\n}\n\n/**\n * Convert Move DID Document to standard DID Document interface\n */\nexport function convertMoveDIDDocumentToInterface(didDocObject: ObjectStateView): DIDDocument {\n  // Parse BCS hex string to bytes and deserialize\n  let bcsHex = didDocObject.value;\n  // Remove '0x' prefix if present\n  bcsHex = bcsHex.startsWith('0x') ? bcsHex.slice(2) : bcsHex;\n  let bcsBytes = new Uint8Array(\n    bcsHex.match(/.{1,2}/g)?.map((byte: string) => parseInt(byte, 16)) || []\n  );\n  let didDoc = DIDDocumentSchema.parse(bcsBytes);\n\n  // Create DID string\n  const didId = formatDIDString(didDoc.id);\n\n  // Convert controllers\n  const controllers = didDoc.controller.map(c => formatDIDString(c));\n\n  // Convert verification methods\n  const verificationMethods: VerificationMethod[] = [];\n  const verificationMethodsMap = simpleMapToMap(didDoc.verification_methods) as Map<\n    string,\n    MoveVerificationMethod\n  >;\n  verificationMethodsMap.forEach(vm => {\n    verificationMethods.push({\n      id: `${formatDIDString(vm.id.did)}#${vm.id.fragment}`,\n      type: vm.type,\n      controller: formatDIDString(vm.controller),\n      publicKeyMultibase: vm.public_key_multibase,\n    });\n  });\n\n  // Helper function to convert fragment to full DID URL\n  const convertFragmentToDIDURL = (fragment: string) => `${didId}#${fragment}`;\n\n  // Convert services\n  const services: ServiceEndpoint[] = [];\n  const servicesMap = simpleMapToMap(didDoc.services) as Map<string, MoveService>;\n  servicesMap.forEach(service => {\n    const serviceEndpoint: ServiceEndpoint = {\n      id: `${formatDIDString(service.id.did)}#${service.id.fragment}`,\n      type: service.type,\n      serviceEndpoint: service.service_endpoint,\n    };\n    let properties = simpleMapToMap(service.properties);\n    // Add properties if they exist\n    if (properties.size > 0) {\n      Object.assign(serviceEndpoint, Object.fromEntries(properties));\n    }\n\n    services.push(serviceEndpoint);\n  });\n\n  return {\n    '@context': ['https://www.w3.org/ns/did/v1'],\n    id: didId,\n    controller: controllers,\n    verificationMethod: verificationMethods,\n    authentication: didDoc.authentication.map(convertFragmentToDIDURL),\n    assertionMethod: didDoc.assertion_method.map(convertFragmentToDIDURL),\n    capabilityInvocation: didDoc.capability_invocation.map(convertFragmentToDIDURL),\n    capabilityDelegation: didDoc.capability_delegation.map(convertFragmentToDIDURL),\n    keyAgreement: didDoc.key_agreement.map(convertFragmentToDIDURL),\n    service: services,\n    alsoKnownAs: didDoc.also_known_as,\n  };\n}\n\n/**\n * Parse DID Created Event data using BCS\n */\nexport function parseDIDCreatedEvent(eventData: string): DIDCreatedEventData {\n  const hexData = eventData.startsWith('0x') ? eventData.slice(2) : eventData;\n  const bytes = new Uint8Array(\n    hexData.match(/.{1,2}/g)?.map((byte: string) => parseInt(byte, 16)) || []\n  );\n  return DIDCreatedEventSchema.parse(bytes);\n}\n\n// Define StructTag for DIDDocument\nexport const DIDDocumentStructTag = {\n  address: '0x3',\n  module: 'did',\n  name: 'DIDDocument',\n  typeParams: [],\n};\n\n/**\n * Calculate DID Object ID from identifier\n * This matches the Move function custom_object_id<ID, T>(id: ID)\n */\nexport function resolveDidObjectID(identifier: string): string {\n  return customObjectID(identifier, DIDDocumentStructTag);\n}\n\nexport function customObjectID(id: string, structTag: StructTag): string {\n  const idBytes = bcs.String.serialize(id).toBytes();\n  const typeBytes = stringToBytes('utf8', Serializer.structTagToCanonicalString(structTag));\n  const bytes = new Uint8Array(idBytes.length + typeBytes.length);\n  bytes.set(idBytes);\n  bytes.set(typeBytes, idBytes.length);\n  const hash = sha3_256(bytes);\n  return `0x${toHEX(hash)}`;\n}\n","/**\n * Session-Key Scope utilities for Rooch DID\n *\n * This module provides utilities for managing Session-Key Scopes that control\n * which contract functions a Session-Key can call on the Rooch blockchain.\n */\n\n/**\n * Build base scopes that should be available to all Session-Keys\n * These provide essential DID and payment functionality.\n *\n * @returns Array of base scope strings in \"address::module::function\" format\n */\nexport function buildBaseScopes(): string[] {\n  return [\n    '0x3::did::*', // DID contract - all functions\n    '0x3::payment_channel::*', // Payment channel contract - all functions\n    '0xeb1deb6f1190f86cd4e05a82cfa5775a8a5929da49fac3ab8f5bf23e9181e625::*::*', // Cap Registry contract - all functions\n  ];\n}\n\n/**\n * Combine base scopes with custom scopes and remove duplicates\n *\n * @param customScopes - Additional scopes to include\n * @returns Deduplicated array of scope strings\n */\nexport function combineScopes(customScopes: string[] = []): string[] {\n  const baseScopes = buildBaseScopes();\n  const allScopes = [...baseScopes, ...customScopes];\n\n  // Remove duplicates while preserving order\n  return Array.from(new Set(allScopes));\n}\n\n/**\n * Validate that a scope string has the correct format\n * Expected format: \"address::module::function\"\n * Each part can use \"*\" as a wildcard\n *\n * @param scope - Scope string to validate\n * @returns true if valid, false otherwise\n */\nexport function validateScopeFormat(scope: string): boolean {\n  if (!scope || typeof scope !== 'string') {\n    return false;\n  }\n\n  const parts = scope.split('::');\n  if (parts.length !== 3) {\n    return false;\n  }\n\n  const [address, module, func] = parts;\n\n  // Each part must be non-empty\n  if (!address || !module || !func) {\n    return false;\n  }\n\n  // Address should be either '*' or valid hex/bech32 format (basic check)\n  if (address !== '*' && !isValidAddressFormat(address)) {\n    return false;\n  }\n\n  // Module and function can be any non-empty string or '*'\n  return true;\n}\n\n/**\n * Validate multiple scope strings\n *\n * @param scopes - Array of scope strings to validate\n * @returns Object with validation result and any invalid scopes\n */\nexport function validateScopes(scopes: string[]): {\n  valid: boolean;\n  invalidScopes: string[];\n} {\n  const invalidScopes = scopes.filter(scope => !validateScopeFormat(scope));\n\n  return {\n    valid: invalidScopes.length === 0,\n    invalidScopes,\n  };\n}\n\n/**\n * Basic validation for address format\n * Accepts hex addresses (0x...) and bech32 addresses (rooch1...)\n *\n * @param address - Address string to validate\n * @returns true if format appears valid\n */\nexport function isValidAddressFormat(address: string): boolean {\n  // Hex address format (0x followed by hex characters)\n  if (address.startsWith('0x')) {\n    return /^0x[0-9a-fA-F]+$/.test(address);\n  }\n\n  // Bech32 format (rooch1 followed by valid characters)\n  if (address.startsWith('rooch1')) {\n    return /^rooch1[0-9a-z]+$/.test(address);\n  }\n\n  // Only allow specific valid formats, reject everything else\n  return false;\n}\n\n/**\n * Convert a more readable scope object to string format\n * This provides a type-safe way to construct scopes\n */\nexport interface ScopeObject {\n  address: string;\n  module: string;\n  func: string;\n}\n\n/**\n * Convert scope object to string format\n *\n * @param scope - Scope object\n * @returns Scope string in \"address::module::function\" format\n */\nexport function scopeObjectToString(scope: ScopeObject): string {\n  return `${scope.address}::${scope.module}::${scope.func}`;\n}\n\n/**\n * Convert multiple scope objects to string format\n *\n * @param scopes - Array of scope objects\n * @returns Array of scope strings\n */\nexport function scopeObjectsToStrings(scopes: ScopeObject[]): string[] {\n  return scopes.map(scopeObjectToString);\n}\n","import { VDRInterface } from './types';\nimport { KeyVDR } from './keyVDR';\nimport { RoochVDR } from './roochVDR';\nimport { VDRRegistry } from './VDRRegistry';\nimport { IdentityKitErrorCode, createVDRError } from '../errors';\n\n/**\n * Factory function to create a VDR instance based on the DID method\n *\n * @param method DID method to create a VDR for\n * @param options Optional configuration for the VDR\n * @returns A VDR instance for the specified method\n */\nexport function createVDR(method: string, options?: any): VDRInterface {\n  switch (method.toLowerCase()) {\n    case 'key':\n      return new KeyVDR();\n    case 'rooch':\n      return new RoochVDR(options);\n    // Add additional DID methods as needed\n    default:\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No built-in VDR implementation available for method '${method}'`,\n        { method, availableMethods: ['key', 'rooch'] }\n      );\n  }\n}\n\n/**\n * Helper function to create a standard set of VDRs for common methods\n *\n * @param options Configuration options for various VDRs\n * @returns An array of VDR instances\n */\nexport function createDefaultVDRs(options?: { rooch?: any }): VDRInterface[] {\n  return [new KeyVDR(), new RoochVDR(options?.rooch || {})];\n}\n\n/**\n * Quickly create a default RoochVDR instance and register it into a VDRRegistry.\n *\n * 1. If the registry (default: global singleton) already contains a `rooch` VDR,\n *    the existing instance is returned directly – calling this function is\n *    therefore idempotent.\n * 2. The `network` parameter is forwarded to `RoochVDR.createDefault`, defaulting\n *    to `'test'` for most development scenarios.\n *\n * @param network  Rooch network: 'dev' | 'test' | 'main'. Defaults to 'test'.\n * @param registry Optional registry to register into. Defaults to the global singleton.\n * @returns The (new or existing) RoochVDR instance.\n */\nexport function initRoochVDR(\n  network: 'local' | 'dev' | 'test' | 'main' = 'test',\n  rpcUrl: string | undefined = undefined,\n  registry: VDRRegistry = VDRRegistry.getInstance()\n): RoochVDR {\n  const existing = registry.getVDR('rooch');\n  if (existing) {\n    return existing as RoochVDR;\n  }\n\n  const vdr = RoochVDR.createDefault(network, rpcUrl);\n  registry.registerVDR(vdr);\n  return vdr;\n}\n\n// Export VDR implementations\nexport * from './types';\nexport * from './keyVDR';\nexport * from './abstractVDR';\nexport * from './roochVDR';\nexport * from './VDRRegistry';\n","import { KeyType } from '../types/crypto';\n\n/**\n * Represents a stored cryptographic key with its metadata\n */\nexport interface StoredKey {\n  /** Complete verification method ID (contains the DID + fragment) */\n  keyId: string;\n  /** Cryptographic curve/algorithm */\n  keyType: KeyType;\n  /** Multibase encoded public key */\n  publicKeyMultibase: string;\n  /** Optional multibase encoded private key */\n  privateKeyMultibase?: string;\n  /** Generic key-value metadata for implementation-specific extensions */\n  meta?: Record<string, any>;\n}\n\n/**\n * Interface for key storage implementations\n * Different environments (browser, node, react-native) can provide their own implementations\n */\nexport interface KeyStore {\n  /**\n   * List all available key IDs in this store\n   * @returns Promise resolving to array of key IDs\n   */\n  listKeyIds(): Promise<string[]>;\n\n  /**\n   * Load a key by its ID\n   * @param keyId Optional key ID to load (if omitted, may return a default key)\n   * @returns Promise resolving to the stored key or null if not found\n   */\n  load(keyId?: string): Promise<StoredKey | null>;\n\n  /**\n   * Save a key to storage\n   * @param key The key to save\n   */\n  save(key: StoredKey): Promise<void>;\n\n  /**\n   * Clear a specific key or all keys\n   * @param keyId Optional key ID to clear (if omitted, clears all keys)\n   */\n  clear(keyId?: string): Promise<void>;\n\n  /**\n   * Optional: Sign data directly using the specified key\n   * Implementations for WebAuthn or non-extractable CryptoKeys should provide this\n   * @param keyId ID of the key to use for signing\n   * @param data Data to sign\n   * @returns Signature as Uint8Array\n   */\n  sign?(keyId: string, data: Uint8Array): Promise<Uint8Array>;\n}\n\n/**\n * In-memory implementation of KeyStore\n * Useful for testing and SSR environments\n */\nexport class MemoryKeyStore implements KeyStore {\n  private map = new Map<string, StoredKey>();\n\n  /**\n   * List all available key IDs in this store\n   */\n  async listKeyIds(): Promise<string[]> {\n    return Array.from(this.map.keys());\n  }\n\n  /**\n   * Load a key by its ID\n   * @param keyId Key ID to load\n   */\n  async load(keyId?: string): Promise<StoredKey | null> {\n    if (!keyId) {\n      // Return first key if no specific ID requested\n      const firstKey = Array.from(this.map.values())[0];\n      return firstKey || null;\n    }\n    return this.map.get(keyId) || null;\n  }\n\n  /**\n   * Save a key to in-memory storage\n   * @param key The key to save\n   */\n  async save(key: StoredKey): Promise<void> {\n    this.map.set(key.keyId, key);\n  }\n\n  /**\n   * Clear a specific key or all keys\n   * @param keyId Optional key ID to clear (if omitted, clears all keys)\n   */\n  async clear(keyId?: string): Promise<void> {\n    if (keyId) {\n      this.map.delete(keyId);\n    } else {\n      this.map.clear();\n    }\n  }\n\n  // No sign implementation for MemoryKeyStore; relies on plaintext extraction.\n}\n","import { StoredKey } from './KeyStore';\nimport { MultibaseCodec } from '../multibase';\nimport { CryptoUtils } from '../crypto/utils';\nimport { stringToBytes, bytesToString } from '../utils/bytes';\nimport { IdentityKitErrorCode, createValidationError } from '../errors';\n\n/**\n * Codec for serializing and deserializing StoredKey objects\n * Uses base58btc multibase encoding (z prefix) for string representation\n */\nexport class StoredKeyCodec {\n  /**\n   * Encode a StoredKey to a base58btc multibase string\n   * @param key The StoredKey to encode\n   * @returns base58btc encoded string with 'z' prefix\n   */\n  static encode(key: StoredKey): string {\n    const json = JSON.stringify(key);\n    const jsonBytes = stringToBytes(json);\n    return MultibaseCodec.encodeBase58btc(jsonBytes);\n  }\n\n  /**\n   * Decode a multibase string to a StoredKey with automatic key consistency validation\n   * @param serialized The multibase encoded string\n   * @returns The decoded and validated StoredKey\n   * @throws Error if decoding fails or key validation fails\n   */\n  static async decode(serialized: string): Promise<StoredKey> {\n    const jsonBytes = MultibaseCodec.decode(serialized);\n    const jsonStr = bytesToString(jsonBytes);\n    const key = JSON.parse(jsonStr) as StoredKey;\n\n    // Automatically validate key consistency for security\n    const isValid = await this.validateKeyConsistency(key);\n    if (!isValid) {\n      throw createValidationError(\n        IdentityKitErrorCode.KEY_VALIDATION_FAILED,\n        'StoredKey validation failed: private and public keys are inconsistent',\n        { keyId: key.keyId, keyType: key.keyType }\n      );\n    }\n\n    return key;\n  }\n\n  /**\n   * Validate the consistency between private key and public key in StoredKey\n   * @param key The StoredKey to validate\n   * @returns true if keys are consistent or validation can be skipped, false otherwise\n   */\n  private static async validateKeyConsistency(key: StoredKey): Promise<boolean> {\n    if (\n      !key.privateKeyMultibase ||\n      !key.publicKeyMultibase ||\n      key.privateKeyMultibase.trim() === '' ||\n      key.publicKeyMultibase.trim() === ''\n    ) {\n      // Skip validation if either key is missing or empty\n      return true;\n    }\n\n    try {\n      // Decode private and public keys\n      const privateKeyBytes = MultibaseCodec.decode(key.privateKeyMultibase);\n      const publicKeyBytes = MultibaseCodec.decode(key.publicKeyMultibase);\n\n      // Use the centralized validation method from CryptoUtils\n      return await CryptoUtils.validateKeyPairConsistency(\n        privateKeyBytes,\n        publicKeyBytes,\n        key.keyType\n      );\n    } catch (error) {\n      console.warn('Key consistency validation failed:', error);\n      return false;\n    }\n  }\n}\n","import { SignerInterface } from '../signers/types';\nimport { KeyType, roochSignatureSchemeToKeyType } from '../types/crypto';\nimport { CryptoUtils } from '../crypto';\nimport { KeyStore, StoredKey, MemoryKeyStore } from './KeyStore';\nimport { StoredKeyCodec } from './StoredKeyCodec';\nimport {\n  signWithKeyStore,\n  canSignWithKeyStore,\n  getKeyInfoFromKeyStore,\n} from '../signers/keyStoreUtils';\nimport { MultibaseCodec, KeyMultibaseCodec } from '../multibase';\nimport { decodeRoochSercetKey, Keypair } from '@roochnetwork/rooch-sdk';\nimport { getDidWithoutFragment } from '../utils/did';\nimport { IdentityKitErrorCode, createKeyManagementError, createValidationError } from '../errors';\n\n/**\n * Options for initializing a KeyManager\n */\nexport interface KeyManagerOptions {\n  /** The key store to use (defaults to MemoryKeyStore) */\n  store?: KeyStore;\n  /** Default key type to use when generating keys (defaults to Ed25519) */\n  defaultKeyType?: KeyType;\n  /** DID to associate with keys */\n  did?: string;\n}\n\n/**\n * KeyManager provides unified key lifecycle management\n * It implements SignerInterface and delegates to an underlying KeyStoreSigner\n */\nexport class KeyManager implements SignerInterface {\n  private store: KeyStore;\n  private defaultKeyType: KeyType;\n  private did?: string;\n\n  /**\n   * Create a new KeyManager\n   * @param options Configuration options\n   */\n  constructor(options?: KeyManagerOptions) {\n    this.store = options?.store || new MemoryKeyStore();\n    this.did = options?.did;\n    this.defaultKeyType = options?.defaultKeyType || KeyType.ED25519;\n  }\n\n  /**\n   * Generate a new key and store it\n   * @param fragment Optional fragment for the key ID (e.g., 'key-1')\n   * @param keyType Optional key type (defaults to the manager's defaultKeyType)\n   * @returns The stored key information\n   */\n  async generateKey(fragment?: string, keyType?: KeyType): Promise<StoredKey> {\n    if (!this.did) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.DID_NOT_SET,\n        'DID must be set before generating keys',\n        { operation: 'generateKey' }\n      );\n    }\n\n    const type = keyType || this.defaultKeyType;\n    const keyPair = await CryptoUtils.generateKeyPair(type);\n\n    // Create a key ID with the provided fragment or a timestamp\n    const keyFragment = fragment || `key-${Date.now()}`;\n    const keyId = `${this.did}#${keyFragment}`;\n\n    // Encode the keys\n    const publicKeyEncoded = MultibaseCodec.encodeBase58btc(keyPair.publicKey);\n    const privateKeyEncoded = MultibaseCodec.encodeBase58btc(keyPair.privateKey);\n\n    // Create the stored key\n    const storedKey: StoredKey = {\n      keyId,\n      keyType: type,\n      publicKeyMultibase: publicKeyEncoded,\n      privateKeyMultibase: privateKeyEncoded,\n    };\n\n    // Save to the store\n    await this.store.save(storedKey);\n\n    return storedKey;\n  }\n\n  /**\n   * Import an existing key into the store\n   * @param key The key to import\n   */\n  async importKey(key: StoredKey): Promise<void> {\n    const didFromKey = getDidWithoutFragment(key.keyId);\n\n    if (this.did && didFromKey !== this.did) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_DID_MISMATCH,\n        `Key belongs to a different DID: ${didFromKey}`,\n        { expectedDid: this.did, actualDid: didFromKey, keyId: key.keyId }\n      );\n    }\n\n    if (!this.did) {\n      this.did = didFromKey;\n    }\n\n    await this.store.save(key);\n  }\n\n  /**\n   * Delete a key from the store\n   * @param keyId ID of the key to delete\n   */\n  async deleteKey(keyId: string): Promise<void> {\n    await this.store.clear(keyId);\n  }\n\n  /**\n   * Clear all keys from the store\n   */\n  async clear(): Promise<void> {\n    await this.store.clear();\n  }\n\n  /**\n   * List all available key IDs\n   */\n  async listKeyIds(): Promise<string[]> {\n    return this.store.listKeyIds();\n  }\n\n  /**\n   * Get a stored key by its ID\n   * @param keyId ID of the key to retrieve\n   * @returns The stored key or null if not found\n   */\n  async getStoredKey(keyId: string): Promise<StoredKey | null> {\n    return this.store.load(keyId);\n  }\n\n  /**\n   * Set the DID for this manager\n   * @param did The DID to set\n   */\n  setDid(did: string): void {\n    this.did = did;\n  }\n\n  /**\n   * Get the DID\n   * @returns The DID\n   */\n  async getDid(): Promise<string> {\n    if (this.did) return this.did;\n\n    // Attempt to derive from stored keys\n    const keyIds = await this.listKeyIds();\n    if (keyIds.length > 0) {\n      this.did = getDidWithoutFragment(keyIds[0]);\n      return this.did;\n    }\n\n    // No DID found\n    throw createKeyManagementError(\n      IdentityKitErrorCode.DID_NOT_SET,\n      'DID not initialised. Call setDid() or import a key first.',\n      { operation: 'getDidAccountSigner' }\n    );\n  }\n\n  /**\n   * Sign data with a specific key\n   * @param data Data to sign\n   * @param keyId ID of the key to use\n   * @returns The signature\n   */\n  async signWithKeyId(data: Uint8Array, keyId: string): Promise<Uint8Array> {\n    return signWithKeyStore(this.store, data, keyId);\n  }\n\n  /**\n   * Check if a key is available for signing\n   * @param keyId ID of the key to check\n   * @returns True if the key exists and can be used for signing\n   */\n  async canSignWithKeyId(keyId: string): Promise<boolean> {\n    return canSignWithKeyStore(this.store, keyId);\n  }\n\n  /**\n   * Get information about a specific key\n   * @param keyId ID of the key to get information about\n   * @returns Key information or undefined if not found\n   */\n  async getKeyInfo(keyId: string): Promise<{ type: KeyType; publicKey: Uint8Array } | undefined> {\n    return getKeyInfoFromKeyStore(this.store, keyId);\n  }\n\n  /**\n   * Find the first key with a specific key type\n   * @param keyType The key type to search for\n   * @returns The key ID or undefined if not found\n   */\n  async findKeyByType(keyType: KeyType): Promise<string | undefined> {\n    const keyIds = await this.listKeyIds();\n\n    for (const keyId of keyIds) {\n      const key = await this.getStoredKey(keyId);\n      if (key && key.keyType === keyType) {\n        return keyId;\n      }\n    }\n\n    return undefined;\n  }\n\n  /**\n   * Get the underlying key store\n   * @returns The key store\n   */\n  getStore(): KeyStore {\n    return this.store;\n  }\n\n  /** Create an empty KeyManager instance and bind DID */\n  static createEmpty(did: string, store: KeyStore = new MemoryKeyStore()): KeyManager {\n    const km = new KeyManager({ store });\n    km.setDid(did);\n    return km;\n  }\n\n  /** Create KeyManager and immediately generate a key */\n  static async createWithNewKey(\n    did: string,\n    fragment = `key-${Date.now()}`,\n    type: KeyType = KeyType.ED25519,\n    store: KeyStore = new MemoryKeyStore()\n  ): Promise<{ keyManager: KeyManager; keyId: string }> {\n    const km = KeyManager.createEmpty(did, store);\n    const stored = await km.generateKey(fragment, type);\n    return { keyManager: km, keyId: stored.keyId };\n  }\n\n  /** Create KeyManager and import existing key pair */\n  static async createWithKeyPair(\n    did: string,\n    keyPair: { privateKey: Uint8Array; publicKey: Uint8Array },\n    fragment = 'account-key',\n    type: KeyType = KeyType.ED25519,\n    store: KeyStore = new MemoryKeyStore()\n  ): Promise<{ keyManager: KeyManager; keyId: string }> {\n    const km = KeyManager.createEmpty(did, store);\n    const keyId = await km.importKeyPair(fragment, keyPair, type);\n    return { keyManager: km, keyId };\n  }\n\n  /** Utility: generate did:key + master key */\n  static async createWithDidKey(): Promise<{ keyManager: KeyManager; keyId: string; did: string }> {\n    const { publicKey, privateKey } = await CryptoUtils.generateKeyPair(KeyType.ED25519);\n    const publicKeyMultibase = KeyMultibaseCodec.encodeWithType(publicKey, KeyType.ED25519);\n    const didKey = `did:key:${publicKeyMultibase}`;\n    const km = KeyManager.createEmpty(didKey);\n    const keyId = await km.importKeyPair('account-key', { privateKey, publicKey }, KeyType.ED25519);\n    return { keyManager: km, keyId, did: didKey };\n  }\n\n  /** Instance helper: import raw key pair (Uint8Array) */\n  async importKeyPair(\n    fragment: string,\n    keyPair: { privateKey: Uint8Array; publicKey: Uint8Array },\n    type: KeyType = KeyType.ED25519\n  ): Promise<string> {\n    const did = await this.getDid();\n    const keyId = `${did}#${fragment}`;\n\n    if (await this.getKeyInfo(keyId)) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_ALREADY_EXISTS,\n        `Key ID ${keyId} already exists in store`,\n        { keyId }\n      );\n    }\n\n    // Validate key pair consistency for security\n    const isConsistent = await CryptoUtils.validateKeyPairConsistency(\n      keyPair.privateKey,\n      keyPair.publicKey,\n      type\n    );\n    if (!isConsistent) {\n      throw createValidationError(\n        IdentityKitErrorCode.KEY_VALIDATION_FAILED,\n        'Key pair validation failed: private and public keys are inconsistent',\n        { keyId, keyType: type }\n      );\n    }\n\n    await this.importKey({\n      keyId,\n      keyType: type,\n      publicKeyMultibase: MultibaseCodec.encodeBase58btc(keyPair.publicKey),\n      privateKeyMultibase: MultibaseCodec.encodeBase58btc(keyPair.privateKey),\n    });\n\n    return keyId;\n  }\n\n  /** Instance helper: import Rooch Keypair */\n  async importRoochKeyPair(fragment: string, roochKeyPair: Keypair): Promise<string> {\n    const { secretKey, schema } = decodeRoochSercetKey(roochKeyPair.getSecretKey());\n    const keyType: KeyType = roochSignatureSchemeToKeyType(schema);\n    return this.importKeyPair(\n      fragment,\n      {\n        privateKey: secretKey,\n        publicKey: roochKeyPair.getPublicKey().toBytes(),\n      },\n      keyType\n    );\n  }\n\n  /**\n   * Export a stored key to a base58btc encoded string\n   * @param keyId The ID of the key to export\n   * @returns base58btc encoded string representation of the StoredKey\n   */\n  async exportKeyToString(keyId: string): Promise<string> {\n    const key = await this.getStoredKey(keyId);\n    if (!key) {\n      throw createKeyManagementError(IdentityKitErrorCode.KEY_NOT_FOUND, `Key ${keyId} not found`, {\n        keyId,\n      });\n    }\n    return StoredKeyCodec.encode(key);\n  }\n\n  /**\n   * Import a StoredKey from a base58btc encoded string into the current KeyManager\n   * @param serialized The base58btc encoded string representation of a StoredKey\n   * @returns The imported StoredKey\n   */\n  async importKeyFromString(serialized: string): Promise<StoredKey> {\n    const key = await StoredKeyCodec.decode(serialized);\n    await this.importKey(key);\n    return key;\n  }\n\n  /**\n   * Create a new KeyManager from a serialized StoredKey string\n   * @param serialized The base58btc encoded string representation of a StoredKey\n   * @param store Optional key store (defaults to MemoryKeyStore)\n   * @returns A new KeyManager instance with the imported key\n   */\n  static async fromSerializedKey(\n    serialized: string,\n    store: KeyStore = new MemoryKeyStore()\n  ): Promise<KeyManager> {\n    const key = await StoredKeyCodec.decode(serialized);\n    const km = KeyManager.createEmpty(getDidWithoutFragment(key.keyId), store);\n    await km.importKey(key);\n    return km;\n  }\n}\n","import { VDRRegistry, createVDR, VDRInterface } from './vdr';\nimport { KeyManager } from './keys/KeyManager';\nimport { MemoryKeyStore, KeyStore } from './keys/KeyStore';\nimport { IdentityKit } from './IdentityKit';\nimport { DIDDocument } from './types/did';\nimport { SignerInterface } from './signers/types';\nimport { DIDCreationRequest } from './vdr/types';\nimport { getDidWithoutFragment } from './utils/did';\n\n/**\n * IdentityEnv – runtime environment prepared by the Builder/bootstrap.\n * It wires together VDRRegistry + KeyManager, but **does not** automatically create a DID.\n */\nexport class IdentityEnv {\n  constructor(\n    public registry: VDRRegistry,\n    public keyManager: KeyManager\n  ) {}\n\n  /**\n   * Load an existing DID and return a ready IdentityKit instance\n   */\n  async loadDid(did: string, signer?: SignerInterface): Promise<IdentityKit> {\n    const s = signer || this.keyManager;\n    if (!signer) {\n      // Ensure keyManager knows DID (it may be needed for key generation later)\n      try {\n        this.keyManager.setDid(did);\n      } catch (_) {\n        /* ignore */\n      }\n    }\n    return IdentityKit.fromExistingDID(did, s);\n  }\n\n  /**\n   * Load from a known DID Document\n   */\n  async fromDocument(doc: DIDDocument, signer?: SignerInterface): Promise<IdentityKit> {\n    const s = signer || this.keyManager;\n    if (!signer) {\n      this.keyManager.setDid(getDidWithoutFragment(doc.id));\n    }\n    return IdentityKit.fromDIDDocument(doc, s);\n  }\n\n  /**\n   * Create a new DID via the underlying VDR\n   */\n  async createDid(\n    method: string,\n    request: DIDCreationRequest,\n    signer?: SignerInterface,\n    options?: Record<string, any>\n  ): Promise<IdentityKit> {\n    const s = signer || this.keyManager;\n    return IdentityKit.createNewDID(method, request, s, options);\n  }\n}\n\n/**\n * Builder for configuring IdentityEnv step-by-step\n */\nexport class IdentityEnvBuilder {\n  private vdrConfigs: { method: string; options?: any }[] = [];\n  private keyStore?: KeyStore;\n  private keyManager?: KeyManager;\n\n  /** Register (or ensure) a VDR for given DID method */\n  useVDR(method: string, options?: any): this {\n    this.vdrConfigs.push({ method, options });\n    return this;\n  }\n\n  /** Provide a custom KeyStore implementation */\n  useKeyStore(store: KeyStore): this {\n    this.keyStore = store;\n    return this;\n  }\n\n  /** Provide a pre-built KeyManager (advanced) */\n  useKeyManager(manager: KeyManager): this {\n    this.keyManager = manager;\n    return this;\n  }\n\n  /** Finalise and return the environment */\n  async init(): Promise<IdentityEnv> {\n    const registry = VDRRegistry.getInstance();\n\n    // 1. Ensure requested VDRs are registered\n    for (const { method, options } of this.vdrConfigs) {\n      if (!registry.getVDR(method)) {\n        const vdr = createVDR(method, options);\n        registry.registerVDR(vdr as VDRInterface);\n      }\n    }\n\n    // 2. Prepare KeyManager\n    let km: KeyManager;\n    if (this.keyManager) {\n      km = this.keyManager;\n    } else {\n      const store = this.keyStore || new MemoryKeyStore();\n      km = new KeyManager({ store });\n    }\n\n    return new IdentityEnv(registry, km);\n  }\n}\n\n/** Convenience helper similar to the old `init()` but **without** auto-creating DID */\nexport async function bootstrapIdentityEnv(\n  opts: {\n    method?: string;\n    keyStore?: KeyStore;\n    vdrOptions?: any;\n  } = {}\n): Promise<IdentityEnv> {\n  const builder = new IdentityEnvBuilder();\n  const method = opts.method || 'rooch';\n  builder.useVDR(method, opts.vdrOptions);\n  if (opts.keyStore) builder.useKeyStore(opts.keyStore);\n  return builder.init();\n}\n","import {\n  DIDDocument,\n  VerificationMethod,\n  VerificationRelationship,\n  ServiceInfo,\n  ServiceEndpoint,\n} from './types/did';\nimport { SignerInterface } from './signers/types';\nimport { OperationalKeyInfo } from './types/crypto';\nimport { VDRInterface, DIDCreationRequest } from './vdr/types';\nimport { VDRRegistry } from './vdr/VDRRegistry';\n// Key management & crypto utilities\nimport { KeyStore } from './keys/KeyStore';\nimport { MultibaseCodec } from './multibase';\nimport { extractMethod, parseDid } from './utils/did';\nimport { bootstrapIdentityEnv, IdentityEnv } from './IdentityEnv';\nimport { DebugLogger } from './utils/DebugLogger';\nimport {\n  IdentityKitError,\n  IdentityKitErrorCode,\n  createDIDError,\n  createVDRError,\n  createKeyManagementError,\n  wrapUnknownError,\n} from './errors';\n\n/**\n * Main SDK class for implementing NIP-1 Agent Single DID Multi-Key Model\n */\nexport class IdentityKit {\n  private didDocument: DIDDocument;\n  private vdr: VDRInterface;\n  private signer: SignerInterface;\n\n  // Private constructor, force use of factory methods\n  private constructor(didDocument: DIDDocument, vdr: VDRInterface, signer: SignerInterface) {\n    this.didDocument = didDocument;\n    this.vdr = vdr;\n    this.signer = signer;\n  }\n\n  // Factory methods\n  /**\n   * Create an instance from an existing DID (for managing existing DIDs)\n   */\n  static async fromExistingDID(did: string, signer: SignerInterface): Promise<IdentityKit> {\n    const registry = VDRRegistry.getInstance();\n    const method = extractMethod(did);\n    const vdr = registry.getVDR(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for DID method '${method}'`,\n        { method, did }\n      );\n    }\n\n    // Resolve DID to get DID Document\n    // We force refresh to ensure we get the latest DID Document from the VDR\n    // Maybe we should find a better way to clear the cache when we add a service or verification method\n    const didDocument = await registry.resolveDID(did, { forceRefresh: true });\n    if (!didDocument) {\n      throw createDIDError(\n        IdentityKitErrorCode.DID_RESOLUTION_FAILED,\n        `Failed to resolve DID: ${did}`,\n        { did, method }\n      );\n    }\n\n    return new IdentityKit(didDocument, vdr, signer);\n  }\n\n  /**\n   * Create an instance from a DID Document (for scenarios with known DID Document)\n   */\n  static fromDIDDocument(didDocument: DIDDocument, signer: SignerInterface): IdentityKit {\n    const { method } = parseDid(didDocument.id);\n    const vdr = VDRRegistry.getInstance().getVDR(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for DID method '${method}'`,\n        { method, did: didDocument.id }\n      );\n    }\n\n    return new IdentityKit(didDocument, vdr, signer);\n  }\n\n  /**\n   * Create and publish a new DID\n   */\n  static async createNewDID(\n    method: string,\n    creationRequest: DIDCreationRequest,\n    signer: SignerInterface,\n    options?: Record<string, any>\n  ): Promise<IdentityKit> {\n    const registry = VDRRegistry.getInstance();\n    const vdr = registry.getVDR(method);\n    if (!vdr) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_NOT_AVAILABLE,\n        `No VDR available for DID method '${method}'`,\n        { method }\n      );\n    }\n\n    const result = await registry.createDID(method, creationRequest, options);\n    if (!result.success || !result.didDocument) {\n      throw createDIDError(\n        IdentityKitErrorCode.DID_CREATION_FAILED,\n        `Failed to create DID: ${result.error || 'Unknown error'}`,\n        { method, creationRequest, result }\n      );\n    }\n\n    return new IdentityKit(result.didDocument, vdr, signer);\n  }\n\n  /**\n   * Lightweight environment bootstrap – prepares VDR(s) & KeyManager without touching DID.\n   * It is a thin wrapper around `bootstrapIdentityEnv()` so that callers can simply do:\n   * ```ts\n   * const env = await IdentityKit.bootstrap({ method: 'rooch' });\n   * const kit = await env.loadDid(did);\n   * ```\n   */\n  static async bootstrap(\n    opts: {\n      method?: string;\n      keyStore?: KeyStore;\n      vdrOptions?: any;\n    } = {}\n  ): Promise<IdentityEnv> {\n    return bootstrapIdentityEnv(opts);\n  }\n\n  // Verification Method Management\n  /**\n   * Find a key that has the specified verification relationship and is available for signing\n   * @param relationship The required verification relationship\n   * @returns The key ID if found, undefined otherwise\n   */\n  private async findKeyWithRelationship(\n    relationship: VerificationRelationship\n  ): Promise<string | undefined> {\n    return this.findKeysWithRelationship(relationship).then(keys => keys[0]);\n  }\n\n  /**\n   * Find all keys that have the specified verification relationship and are available for signing\n   * @param relationship The required verification relationship\n   * @returns Array of key IDs that match the criteria\n   */\n  private async findKeysWithRelationship(\n    relationship: VerificationRelationship\n  ): Promise<string[]> {\n    const availableKeyIds = await this.signer.listKeyIds();\n    if (!availableKeyIds.length) {\n      return [];\n    }\n\n    const relationships = this.didDocument[relationship] as (string | { id: string })[];\n    if (!relationships?.length) {\n      return [];\n    }\n\n    return relationships\n      .map(item => (typeof item === 'string' ? item : item.id))\n      .filter(keyId => availableKeyIds.includes(keyId));\n  }\n\n  async addVerificationMethod(\n    keyInfo: OperationalKeyInfo,\n    relationships: VerificationRelationship[],\n    options?: {\n      keyId?: string;\n      scopes?: string[];\n    }\n  ): Promise<string> {\n    // 1. Get signing key\n    const signingKeyId =\n      options?.keyId || (await this.findKeyWithRelationship('capabilityDelegation'));\n    if (!signingKeyId) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_PERMISSION_DENIED,\n        'No key with capabilityDelegation permission available',\n        {\n          did: this.didDocument.id,\n          requiredRelationship: 'capabilityDelegation',\n          availableKeys: await this.signer.listKeyIds(),\n        }\n      );\n    }\n\n    // 2. Create verification method entry\n    const keyIdFragment = keyInfo.idFragment || `key-${Date.now()}`;\n    const keyId = `${this.didDocument.id}#${keyIdFragment}`;\n    const verificationMethodEntry = {\n      id: keyId,\n      type: keyInfo.type,\n      controller: keyInfo.controller || this.didDocument.id,\n      publicKeyMultibase:\n        keyInfo.publicKeyMaterial instanceof Uint8Array\n          ? await MultibaseCodec.encodeBase58btc(keyInfo.publicKeyMaterial)\n          : undefined,\n      publicKeyJwk: !(keyInfo.publicKeyMaterial instanceof Uint8Array)\n        ? keyInfo.publicKeyMaterial\n        : undefined,\n    };\n\n    // 3. Call VDR interface\n    const published = await this.vdr.addVerificationMethod(\n      this.didDocument.id,\n      verificationMethodEntry,\n      relationships,\n      {\n        signer: this.signer,\n        keyId: signingKeyId,\n        scopes: options?.scopes,\n      }\n    );\n\n    if (!published) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_OPERATION_FAILED,\n        `Failed to publish verification method ${keyId}`,\n        {\n          did: this.didDocument.id,\n          keyId,\n          relationships,\n          verificationMethod: verificationMethodEntry,\n        }\n      );\n    }\n\n    // 4. Update local state\n    await this.updateLocalDIDDocument();\n\n    return keyId;\n  }\n\n  async removeVerificationMethod(\n    keyId: string,\n    options?: {\n      keyId?: string;\n    }\n  ): Promise<boolean> {\n    const signingKeyId =\n      options?.keyId || (await this.findKeyWithRelationship('capabilityDelegation'));\n    if (!signingKeyId) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_PERMISSION_DENIED,\n        'No key with capabilityDelegation permission available',\n        {\n          did: this.didDocument.id,\n          requiredRelationship: 'capabilityDelegation',\n          targetKeyId: keyId,\n          availableKeys: await this.signer.listKeyIds(),\n        }\n      );\n    }\n\n    const published = await this.vdr.removeVerificationMethod(this.didDocument.id, keyId, {\n      signer: this.signer,\n    });\n\n    if (published) {\n      // Update local state\n      if (this.didDocument.verificationMethod) {\n        this.didDocument.verificationMethod = this.didDocument.verificationMethod.filter(\n          vm => vm.id !== keyId\n        );\n      }\n\n      const relationships: VerificationRelationship[] = [\n        'authentication',\n        'assertionMethod',\n        'keyAgreement',\n        'capabilityInvocation',\n        'capabilityDelegation',\n      ];\n\n      relationships.forEach(rel => {\n        if (this.didDocument[rel]) {\n          this.didDocument[rel] = (this.didDocument[rel] as any[]).filter(item => {\n            if (typeof item === 'string') return item !== keyId;\n            if (typeof item === 'object' && item.id) return item.id !== keyId;\n            return true;\n          });\n        }\n      });\n\n      return true;\n    }\n\n    return false;\n  }\n\n  async updateVerificationMethodRelationships(\n    keyId: string,\n    addRelationships: VerificationRelationship[],\n    removeRelationships: VerificationRelationship[],\n    options: {\n      signer?: SignerInterface;\n    }\n  ): Promise<boolean> {\n    const published = await this.vdr.updateRelationships(\n      this.didDocument.id,\n      keyId,\n      addRelationships,\n      removeRelationships,\n      {\n        signer: options.signer,\n      }\n    );\n\n    if (published) {\n      // Update local state\n      addRelationships.forEach(rel => {\n        if (!this.didDocument[rel]) {\n          this.didDocument[rel] = [];\n        }\n        const relationshipArray = this.didDocument[rel] as (string | object)[];\n        if (\n          !relationshipArray.some(item => {\n            return typeof item === 'string' ? item === keyId : (item as any).id === keyId;\n          })\n        ) {\n          relationshipArray.push(keyId);\n        }\n      });\n\n      removeRelationships.forEach(rel => {\n        if (this.didDocument[rel]) {\n          this.didDocument[rel] = (this.didDocument[rel] as any[]).filter(item => {\n            if (typeof item === 'string') return item !== keyId;\n            if (typeof item === 'object' && item.id) return item.id !== keyId;\n            return true;\n          });\n        }\n      });\n\n      return true;\n    }\n\n    return false;\n  }\n\n  // Service Management\n  async addService(\n    serviceInfo: ServiceInfo,\n    options?: {\n      keyId?: string;\n    }\n  ): Promise<string> {\n    const signingKeyId =\n      options?.keyId || (await this.findKeyWithRelationship('capabilityInvocation'));\n    if (!signingKeyId) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_PERMISSION_DENIED,\n        'No key with capabilityInvocation permission available',\n        {\n          did: this.didDocument.id,\n          requiredRelationship: 'capabilityInvocation',\n          serviceInfo,\n          availableKeys: await this.signer.listKeyIds(),\n        }\n      );\n    }\n\n    const serviceId = `${this.didDocument.id}#${serviceInfo.idFragment}`;\n    const serviceEntry = {\n      id: serviceId,\n      type: serviceInfo.type,\n      serviceEndpoint: serviceInfo.serviceEndpoint,\n      ...(serviceInfo.additionalProperties || {}),\n    };\n\n    const published = await this.vdr.addService(this.didDocument.id, serviceEntry, {\n      signer: this.signer,\n      keyId: signingKeyId,\n    });\n\n    if (!published) {\n      throw createVDRError(\n        IdentityKitErrorCode.VDR_OPERATION_FAILED,\n        `Failed to publish service ${serviceId}`,\n        {\n          did: this.didDocument.id,\n          serviceId,\n          serviceInfo,\n          serviceEntry,\n        }\n      );\n    }\n    // Update local state\n    this.didDocument = (await this.vdr.resolve(this.didDocument.id)) as DIDDocument;\n    IdentityKit.logger.debug('After addService', this.didDocument);\n    return serviceId;\n  }\n\n  async removeService(\n    serviceId: string,\n    options?: {\n      keyId?: string;\n    }\n  ): Promise<boolean> {\n    const signingKeyId =\n      options?.keyId || (await this.findKeyWithRelationship('capabilityInvocation'));\n    if (!signingKeyId) {\n      throw createKeyManagementError(\n        IdentityKitErrorCode.KEY_PERMISSION_DENIED,\n        'No key with capabilityInvocation permission available',\n        {\n          did: this.didDocument.id,\n          requiredRelationship: 'capabilityInvocation',\n          serviceId,\n          availableKeys: await this.signer.listKeyIds(),\n        }\n      );\n    }\n\n    const published = await this.vdr.removeService(this.didDocument.id, serviceId, {\n      signer: this.signer,\n      keyId: signingKeyId,\n    });\n\n    if (published) {\n      // Update local state\n      if (this.didDocument.service) {\n        this.didDocument.service = this.didDocument.service.filter(s => s.id !== serviceId);\n      }\n      return true;\n    }\n\n    return false;\n  }\n\n  // Document Access\n  getDIDDocument(): DIDDocument {\n    return this.didDocument;\n  }\n\n  // Service Discovery\n  findServiceByType(serviceType: string): ServiceEndpoint | undefined {\n    return this.didDocument.service?.find(s => s.type === serviceType);\n  }\n\n  findVerificationMethodsByRelationship(\n    relationship: VerificationRelationship\n  ): VerificationMethod[] {\n    const relationships = this.didDocument[relationship] as (string | { id: string })[];\n    if (!relationships?.length) {\n      return [];\n    }\n\n    return relationships\n      .map(item => (typeof item === 'string' ? item : item.id))\n      .map(id =>\n        this.didDocument.verificationMethod?.find(vm => vm.id === id)\n      ) as VerificationMethod[];\n  }\n\n  // State Checks\n  async canSignWithKey(keyId: string): Promise<boolean> {\n    return this.signer.canSignWithKeyId(keyId);\n  }\n\n  private async updateLocalDIDDocument(): Promise<void> {\n    this.didDocument = (await this.vdr.resolve(this.didDocument.id)) as DIDDocument;\n    IdentityKit.logger.debug('After updateLocalDIDDocument', this.didDocument);\n  }\n\n  getSigner(): SignerInterface {\n    return this.signer;\n  }\n\n  /**\n   * Get all key IDs that are both present in DID document and available via Signer,\n   * grouped by verification relationship.\n   */\n  async getAvailableKeyIds(): Promise<{ [key in VerificationRelationship]?: string[] }> {\n    const relationships: VerificationRelationship[] = [\n      'authentication',\n      'assertionMethod',\n      'keyAgreement',\n      'capabilityInvocation',\n      'capabilityDelegation',\n    ];\n\n    const availableFromSigner = await this.signer.listKeyIds();\n    const result: { [key in VerificationRelationship]?: string[] } = {};\n\n    for (const rel of relationships) {\n      const relArray = this.didDocument[rel] as (string | { id: string })[] | undefined;\n      if (!relArray?.length) continue;\n\n      const ids = relArray\n        .map(item => (typeof item === 'string' ? item : item.id))\n        .filter(id => availableFromSigner.includes(id));\n\n      if (ids.length) result[rel] = ids;\n    }\n    return result;\n  }\n\n  // Logger instance for this class\n  private static readonly logger = DebugLogger.get('IdentityKit');\n}\n\nexport { IdentityKit as NuwaIdentityKit };\n","import { ServiceEndpoint, DIDDocument, ServiceInfo, VerificationRelationship } from './types/did';\nimport { SignerInterface } from './signers/types';\nimport {\n  CADOPCreationRequest,\n  CADOPControllerCreationRequest,\n  DIDCreationResult,\n  AUTH_PROVIDERS,\n  AuthProvider,\n} from './vdr/types';\nimport { VDRRegistry } from './vdr/VDRRegistry';\nimport { IdentityKit } from './IdentityKit';\nimport { DebugLogger } from './utils/DebugLogger';\nimport { IdentityKitErrorCode, createDIDError, createValidationError } from './errors';\n\n/**\n * CADOP service types\n */\nexport enum CadopServiceType {\n  CUSTODIAN = 'CadopCustodianService',\n  IDP = 'CadopIdPService',\n  WEB2_PROOF = 'CadopWeb2ProofService',\n}\n\n/**\n * CADOP service validation rules\n */\nexport interface CadopServiceValidationRule {\n  requiredProperties: string[];\n  optionalProperties: string[];\n  propertyValidators?: Record<string, (value: any) => boolean>;\n}\n\n/**\n * CadopIdentityKit class for managing CADOP-specific functionality\n */\nexport class CadopIdentityKit {\n  private static readonly SERVICE_VALIDATION_RULES: Record<\n    CadopServiceType,\n    CadopServiceValidationRule\n  > = {\n    [CadopServiceType.CUSTODIAN]: {\n      requiredProperties: ['id', 'type', 'serviceEndpoint'],\n      optionalProperties: ['description', 'fees', 'custodianPublicKey', 'custodianServiceVMType'],\n      propertyValidators: {\n        custodianPublicKey: (value: any) => typeof value === 'string' && value.length > 0,\n        custodianServiceVMType: (value: any) => typeof value === 'string' && value.length > 0,\n        fees: (value: any) => typeof value === 'object' && value !== null,\n      },\n    },\n    [CadopServiceType.IDP]: {\n      requiredProperties: ['id', 'type', 'serviceEndpoint'],\n      optionalProperties: ['supportedCredentials', 'description', 'fees', 'termsOfService'],\n      propertyValidators: {\n        supportedCredentials: (value: any) =>\n          typeof value === 'string' || (Array.isArray(value) && value.length > 0),\n        fees: (value: any) => typeof value === 'object' && value !== null,\n        termsOfService: (value: any) => typeof value === 'string' && value.length > 0,\n      },\n    },\n    [CadopServiceType.WEB2_PROOF]: {\n      requiredProperties: ['id', 'type', 'serviceEndpoint'],\n      optionalProperties: ['supportedPlatforms', 'description', 'fees'],\n      propertyValidators: {\n        supportedPlatforms: (value: any) =>\n          typeof value === 'string' || (Array.isArray(value) && value.length > 0),\n        fees: (value: any) => typeof value === 'object' && value !== null,\n      },\n    },\n  };\n\n  private nuwaKit: IdentityKit;\n\n  private constructor(nuwaKit: IdentityKit) {\n    this.nuwaKit = nuwaKit;\n  }\n\n  private extractCustodianInfo(): ServiceEndpoint {\n    const custodianServices = this.findServicesByType(CadopServiceType.CUSTODIAN);\n    if (custodianServices.length > 0) {\n      const custodianService = custodianServices[0];\n      const logger = DebugLogger.get('CadopIdentityKit');\n      logger.debug('extractCustodianInfo', custodianService);\n      return custodianService;\n    }\n    throw createDIDError(\n      IdentityKitErrorCode.DID_SERVICE_NOT_FOUND,\n      'Custodian service not found in service document',\n      { serviceDocument: this.nuwaKit.getDIDDocument(), serviceType: CadopServiceType.CUSTODIAN }\n    );\n  }\n\n  /**\n   * Initialize a CadopIdentityKit instance from an existing CADOP service DID\n   */\n  static async fromServiceDID(\n    serviceDid: string,\n    signer: SignerInterface\n  ): Promise<CadopIdentityKit> {\n    const nuwaKit = await IdentityKit.fromExistingDID(serviceDid, signer);\n    return new CadopIdentityKit(nuwaKit);\n  }\n\n  /**\n   * Create a new DID via CADOP protocol\n   */\n  async createDID(\n    method: string,\n    userDid: string,\n    options?: Record<string, any> & { customScopes?: string[] }\n  ): Promise<DIDCreationResult> {\n    const custodianInfo = this.extractCustodianInfo();\n\n    const authenticationMethods =\n      this.nuwaKit.findVerificationMethodsByRelationship('authentication');\n    if (authenticationMethods.length === 0) {\n      throw createDIDError(\n        IdentityKitErrorCode.DID_VERIFICATION_METHOD_NOT_FOUND,\n        'No authentication method found in service document',\n        { serviceDocument: this.nuwaKit.getDIDDocument(), relationship: 'authentication' }\n      );\n    }\n    const authenticationMethod = authenticationMethods[0];\n\n    //if the custodianPublicKey and custodianServiceVMType are not found in the service document, use the first authentication method\n    const { custodianPublicKey, custodianServiceVMType } =\n      custodianInfo.custodianPublicKey && custodianInfo.custodianServiceVMType\n        ? {\n            custodianPublicKey: custodianInfo.custodianPublicKey,\n            custodianServiceVMType: custodianInfo.custodianServiceVMType,\n          }\n        : {\n            custodianPublicKey: authenticationMethod.publicKeyMultibase,\n            custodianServiceVMType: authenticationMethod.type,\n          };\n\n    if (!custodianPublicKey || !custodianServiceVMType) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Custodian service configuration not found in service document',\n        { custodianPublicKey, custodianServiceVMType }\n      );\n    }\n\n    const creationRequest: CADOPCreationRequest = {\n      userDidKey: userDid,\n      custodianServicePublicKey: custodianPublicKey,\n      custodianServiceVMType: custodianServiceVMType,\n      customScopes: options?.customScopes,\n    };\n\n    return VDRRegistry.getInstance().createDIDViaCADOP(method, creationRequest, {\n      signer: this.nuwaKit.getSigner(),\n      ...options,\n    });\n  }\n\n  /**\n   * Create a new DID via CADOP protocol with controller\n   * Supports did:key (backward compatible), did:bitcoin, and other controller types\n   */\n  async createDIDWithController(\n    method: string,\n    controllerDid: string,\n    options?: {\n      controllerPublicKeyMultibase?: string;\n      controllerVMType?: string;\n      customScopes?: string[];\n    } & Record<string, any>\n  ): Promise<DIDCreationResult> {\n    const logger = DebugLogger.get('CadopIdentityKit');\n    logger.debug('createDIDWithController called', { method, controllerDid, options });\n\n    const custodianInfo = this.extractCustodianInfo();\n\n    const authenticationMethods =\n      this.nuwaKit.findVerificationMethodsByRelationship('authentication');\n    if (authenticationMethods.length === 0) {\n      throw createDIDError(\n        IdentityKitErrorCode.DID_VERIFICATION_METHOD_NOT_FOUND,\n        'No authentication method found in service document',\n        { serviceDocument: this.nuwaKit.getDIDDocument(), relationship: 'authentication' }\n      );\n    }\n    const authenticationMethod = authenticationMethods[0];\n\n    // Extract custodian service configuration\n    const { custodianPublicKey, custodianServiceVMType } =\n      custodianInfo.custodianPublicKey && custodianInfo.custodianServiceVMType\n        ? {\n            custodianPublicKey: custodianInfo.custodianPublicKey,\n            custodianServiceVMType: custodianInfo.custodianServiceVMType,\n          }\n        : {\n            custodianPublicKey: authenticationMethod.publicKeyMultibase,\n            custodianServiceVMType: authenticationMethod.type,\n          };\n\n    if (!custodianPublicKey || !custodianServiceVMType) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        'Custodian service configuration not found in service document',\n        { custodianPublicKey, custodianServiceVMType }\n      );\n    }\n\n    // Check if this is a did:key and we should use backward compatible path\n    if (controllerDid.startsWith('did:key:') && !options?.controllerPublicKeyMultibase) {\n      logger.debug('Using backward compatible did:key path');\n      // For did:key without explicit public key, use the legacy CADOP method\n      const creationRequest: CADOPCreationRequest = {\n        userDidKey: controllerDid,\n        custodianServicePublicKey: custodianPublicKey,\n        custodianServiceVMType: custodianServiceVMType,\n        customScopes: options?.customScopes,\n      };\n\n      return VDRRegistry.getInstance().createDIDViaCADOP(method, creationRequest, {\n        signer: this.nuwaKit.getSigner(),\n        ...options,\n      });\n    }\n\n    // Use the new controller-based path\n    logger.debug('Using controller-based CADOP path');\n    const creationRequest: CADOPControllerCreationRequest = {\n      controllerDid,\n      controllerPublicKeyMultibase: options?.controllerPublicKeyMultibase,\n      controllerVMType: options?.controllerVMType,\n      custodianServicePublicKey: custodianPublicKey,\n      custodianServiceVMType: custodianServiceVMType,\n      customScopes: options?.customScopes,\n    };\n\n    return VDRRegistry.getInstance().createDIDViaCADOPWithController(method, creationRequest, {\n      signer: this.nuwaKit.getSigner(),\n      ...options,\n    });\n  }\n\n  /**\n   * Add a new CADOP service to the service DID document\n   */\n  async addService(service: ServiceInfo): Promise<string> {\n    // Convert ServiceInfo to ServiceEndpoint format for validation\n    const serviceEndpoint: ServiceEndpoint = {\n      id: `${this.nuwaKit.getDIDDocument().id}#${service.idFragment}`,\n      type: service.type,\n      serviceEndpoint: service.serviceEndpoint,\n      ...(service.additionalProperties || {}),\n    };\n\n    if (!CadopIdentityKit.validateService(serviceEndpoint, service.type as CadopServiceType)) {\n      throw createValidationError(\n        IdentityKitErrorCode.VALIDATION_FAILED,\n        `Invalid CADOP service configuration for type: ${service.type}`,\n        { service, serviceType: service.type }\n      );\n    }\n    const result = await this.nuwaKit.addService(service);\n    return result;\n  }\n\n  /**\n   * Remove a CADOP service from the service DID document\n   */\n  async removeService(\n    serviceId: string,\n    options: {\n      keyId: string;\n      signer?: SignerInterface;\n    }\n  ): Promise<boolean> {\n    const result = await this.nuwaKit.removeService(serviceId, options);\n    return result;\n  }\n\n  /**\n   * Get the underlying IdentityKit instance\n   */\n  getNuwaIdentityKit(): IdentityKit {\n    return this.nuwaKit;\n  }\n\n  /**\n   * Find all custodian services in the service document\n   */\n  findCustodianServices(): ServiceEndpoint[] {\n    return this.findServicesByType(CadopServiceType.CUSTODIAN);\n  }\n\n  /**\n   * Find all IdP services in the service document\n   */\n  findIdPServices(): ServiceEndpoint[] {\n    return this.findServicesByType(CadopServiceType.IDP);\n  }\n\n  /**\n   * Find all Web2 proof services in the service document\n   */\n  findWeb2ProofServices(): ServiceEndpoint[] {\n    return this.findServicesByType(CadopServiceType.WEB2_PROOF);\n  }\n\n  /**\n   * Find services by type in the service document\n   */\n  private findServicesByType(type: CadopServiceType): ServiceEndpoint[] {\n    return (this.nuwaKit.getDIDDocument().service || [])\n      .filter(service => service.type === type)\n      .filter(service => CadopIdentityKit.validateService(service, type));\n  }\n\n  /**\n   * Validate a service against its type-specific validation rules\n   */\n  private static validateService(service: ServiceEndpoint, type: CadopServiceType): boolean {\n    const rules = CadopIdentityKit.SERVICE_VALIDATION_RULES[type];\n    if (!rules) {\n      return false;\n    }\n\n    // Check required properties\n    const hasAllRequired = rules.requiredProperties.every(\n      prop => prop in service && service[prop] !== undefined && service[prop] !== null\n    );\n    if (!hasAllRequired) {\n      return false;\n    }\n\n    // Check if there are any unknown properties\n    const allowedProperties = new Set([...rules.requiredProperties, ...rules.optionalProperties]);\n    const hasUnknownProps = Object.keys(service).some(prop => !allowedProperties.has(prop));\n    if (hasUnknownProps) {\n      return false;\n    }\n\n    // Run property-specific validators\n    if (rules.propertyValidators) {\n      return Object.entries(rules.propertyValidators).every(([prop, validator]) => {\n        if (prop in service) {\n          return validator(service[prop]);\n        }\n        return true; // Skip validation for optional properties that are not present\n      });\n    }\n\n    return true;\n  }\n}\n\n// Export additional types and constants for external use\nexport {\n  AUTH_PROVIDERS,\n  type AuthProvider,\n  type CADOPControllerCreationRequest,\n} from './vdr/types';\n","import { DIDDocument, DIDResolver } from '../../types';\nimport { SignerInterface } from '../../signers/types';\nimport { NIP1SignedObject, SignedData } from '../types';\nimport { canonicalize } from './utils';\nimport { CryptoUtils } from '../../crypto';\nimport { NonceStore, defaultNonceStore } from './nonceStore';\nimport { MultibaseCodec } from '../../multibase';\nimport { Bytes } from '../../utils/bytes';\nimport { IdentityKitErrorCode, createAuthenticationError } from '../../errors';\n\n// Authorization scheme identifier for HTTP headers\nconst AUTH_SCHEME = 'DIDAuthV1';\n// Prefix actually sent in the HTTP `Authorization` header, including trailing space\nconst HEADER_PREFIX = `${AUTH_SCHEME} `;\n// Default domain separator used in hash/signature calculations (spec §2.2)\nconst DEFAULT_DOMAIN_SEPARATOR = `${AUTH_SCHEME}:`;\n\n// Default maximum clock skew allowed for signature verification (spec §2.2)\nconst DEFAULT_MAX_CLOCK_SKEW = 300;\n\n// Error codes for authentication failures\nexport enum AuthErrorCode {\n  INVALID_HEADER = 'INVALID_HEADER',\n  INVALID_BASE64 = 'INVALID_BASE64',\n  INVALID_JSON = 'INVALID_JSON',\n  MISSING_SIGNATURE = 'MISSING_SIGNATURE',\n  TIMESTAMP_OUT_OF_WINDOW = 'TIMESTAMP_OUT_OF_WINDOW',\n  NONCE_REPLAYED = 'NONCE_REPLAYED',\n  SIGNATURE_VERIFICATION_FAILED = 'SIGNATURE_VERIFICATION_FAILED',\n  DID_DOCUMENT_NOT_FOUND = 'DID_DOCUMENT_NOT_FOUND',\n  VERIFICATION_METHOD_NOT_FOUND = 'VERIFICATION_METHOD_NOT_FOUND',\n  INVALID_PUBLIC_KEY = 'INVALID_PUBLIC_KEY',\n  DID_MISMATCH = 'DID_MISMATCH',\n}\n\ninterface VerifyOptions {\n  maxClockSkew?: number;\n}\n\ninterface VerifyHeaderOptions extends VerifyOptions {\n  nonceStore?: NonceStore;\n}\n\n// Detailed verification result with error codes\nexport type DetailedVerifyResult =\n  | {\n      ok: true;\n      signedObject: NIP1SignedObject;\n    }\n  | {\n      ok: false;\n      error: string;\n      errorCode: AuthErrorCode;\n      signedObject?: NIP1SignedObject;\n    };\n\n// New result type with error codes and optional signedObject\nexport type AuthVerifyResult = DetailedVerifyResult;\n\nexport async function createSignature(\n  payload: Omit<SignedData, 'nonce' | 'timestamp'>,\n  signer: SignerInterface,\n  keyId: string,\n  opts: {\n    didDocument?: DIDDocument;\n    nonce?: string;\n    timestamp?: number;\n    domainSeparator?: string;\n  } = {}\n): Promise<NIP1SignedObject> {\n  const signerDid = await signer.getDid();\n  if (opts.didDocument) {\n    if (opts.didDocument.id !== signerDid) {\n      throw createAuthenticationError(\n        IdentityKitErrorCode.AUTH_DID_MISMATCH,\n        `DID document ID ${opts.didDocument.id} does not match signer DID ${signerDid}`,\n        { didDocumentId: opts.didDocument.id, signerDid }\n      );\n    }\n    const verificationMethod = opts.didDocument.verificationMethod?.find(vm => vm.id === keyId);\n    if (!verificationMethod) {\n      throw createAuthenticationError(\n        IdentityKitErrorCode.AUTH_VERIFICATION_METHOD_NOT_FOUND,\n        `Verification method for keyId ${keyId} not found in DID document.`,\n        { keyId, didDocument: opts.didDocument }\n      );\n    }\n  }\n\n  const signedData: SignedData = {\n    ...payload,\n    nonce: opts.nonce ?? crypto.randomUUID(),\n    timestamp: opts.timestamp ?? Math.floor(Date.now() / 1000),\n  } as SignedData;\n\n  const canonicalData = canonicalize(signedData);\n  const domainSeparator = opts.domainSeparator ?? DEFAULT_DOMAIN_SEPARATOR;\n  const dataToSign = Bytes.stringToBytes(domainSeparator + canonicalData);\n\n  const signatureValue = await signer.signWithKeyId(dataToSign, keyId);\n\n  return {\n    signed_data: signedData,\n    signature: {\n      signer_did: signerDid,\n      key_id: keyId,\n      value: signatureValue,\n    },\n  };\n}\n\nexport function toAuthorizationHeader(obj: NIP1SignedObject): string {\n  // prepare serializable clone with base64url signature\n  const cloned = {\n    signed_data: obj.signed_data,\n    signature: {\n      ...obj.signature,\n      value: MultibaseCodec.encodeBase64url(obj.signature.value),\n    },\n  };\n  const json = JSON.stringify(cloned);\n  const b64url = MultibaseCodec.encodeBase64url(json);\n  return `${HEADER_PREFIX}${b64url}`;\n}\n\n// Internal detailed verification function\nasync function verifySignatureDetailed(\n  signedObject: NIP1SignedObject,\n  resolverOrDoc: DIDDocument | DIDResolver,\n  opts: VerifyOptions = {}\n): Promise<DetailedVerifyResult> {\n  const { signed_data, signature } = signedObject;\n\n  const attemptVerify = async (didDoc: DIDDocument): Promise<DetailedVerifyResult> => {\n    // timestamp window\n    const maxSkew = opts.maxClockSkew ?? DEFAULT_MAX_CLOCK_SKEW;\n    const now = Math.floor(Date.now() / 1000);\n    if (Math.abs(now - signed_data.timestamp) > maxSkew) {\n      return {\n        ok: false,\n        error: 'Timestamp out of window',\n        errorCode: AuthErrorCode.TIMESTAMP_OUT_OF_WINDOW,\n        signedObject,\n      };\n    }\n\n    if (didDoc.id !== signature.signer_did) {\n      return {\n        ok: false,\n        error: 'DID document ID does not match signer DID',\n        errorCode: AuthErrorCode.DID_MISMATCH,\n        signedObject,\n      };\n    }\n\n    const verificationMethod = didDoc.verificationMethod?.find(vm => vm.id === signature.key_id);\n    if (!verificationMethod) {\n      return {\n        ok: false,\n        error: 'Verification method not found in DID document',\n        errorCode: AuthErrorCode.VERIFICATION_METHOD_NOT_FOUND,\n        signedObject,\n      };\n    }\n\n    console.log('verificationMethod', verificationMethod);\n\n    let publicKeyMaterial: JsonWebKey | Uint8Array | null = null;\n    if (verificationMethod.publicKeyJwk) {\n      publicKeyMaterial = verificationMethod.publicKeyJwk;\n    } else if (verificationMethod.publicKeyMultibase) {\n      publicKeyMaterial = MultibaseCodec.decodeBase58btc(verificationMethod.publicKeyMultibase);\n    }\n    if (!publicKeyMaterial) {\n      return {\n        ok: false,\n        error: 'Invalid or missing public key material',\n        errorCode: AuthErrorCode.INVALID_PUBLIC_KEY,\n        signedObject,\n      };\n    }\n\n    const canonicalData = canonicalize(signed_data);\n    const dataToVerify = Bytes.stringToBytes(DEFAULT_DOMAIN_SEPARATOR + canonicalData);\n\n    const isValid = await CryptoUtils.verify(\n      dataToVerify,\n      signature.value,\n      publicKeyMaterial,\n      verificationMethod.type\n    );\n\n    if (isValid) {\n      return { ok: true, signedObject };\n    } else {\n      return {\n        ok: false,\n        error: 'Signature verification failed',\n        errorCode: AuthErrorCode.SIGNATURE_VERIFICATION_FAILED,\n        signedObject,\n      };\n    }\n  };\n\n  if (typeof (resolverOrDoc as any).resolveDID === 'function') {\n    const resolver = resolverOrDoc as DIDResolver;\n    let doc = await resolver.resolveDID(signature.signer_did);\n    if (doc) {\n      const result = await attemptVerify(doc);\n      if (result.ok) return result;\n    }\n\n    // fallback: force refresh once\n    doc = await resolver.resolveDID(signature.signer_did, { forceRefresh: true });\n    if (!doc) {\n      return {\n        ok: false,\n        error: 'DID document not found',\n        errorCode: AuthErrorCode.DID_DOCUMENT_NOT_FOUND,\n        signedObject,\n      };\n    }\n    return attemptVerify(doc);\n  } else {\n    return attemptVerify(resolverOrDoc as DIDDocument);\n  }\n}\n\n// Backward compatible simple verification function\nexport async function verifySignature(\n  signedObject: NIP1SignedObject,\n  resolverOrDoc: DIDDocument | DIDResolver,\n  opts: VerifyOptions = {}\n): Promise<boolean> {\n  const result = await verifySignatureDetailed(signedObject, resolverOrDoc, opts);\n  return result.ok;\n}\n\nexport async function verifyAuthHeader(\n  header: string,\n  resolver: DIDResolver,\n  opts: VerifyHeaderOptions = {}\n): Promise<AuthVerifyResult> {\n  if (!header || !header.startsWith(HEADER_PREFIX)) {\n    return {\n      ok: false,\n      error: 'Unsupported or missing Authorization header',\n      errorCode: AuthErrorCode.INVALID_HEADER,\n    };\n  }\n  const b64url = header.substring(HEADER_PREFIX.length).trim();\n  let payloadStr: string;\n  try {\n    payloadStr = Bytes.bytesToString(MultibaseCodec.decodeBase64url(b64url));\n  } catch (e) {\n    return {\n      ok: false,\n      error: 'Invalid base64 credentials',\n      errorCode: AuthErrorCode.INVALID_BASE64,\n    };\n  }\n\n  let parsed: any;\n  try {\n    parsed = JSON.parse(payloadStr);\n  } catch (e) {\n    return {\n      ok: false,\n      error: 'Invalid JSON in credentials',\n      errorCode: AuthErrorCode.INVALID_JSON,\n    };\n  }\n\n  // restore signature.value Uint8Array\n  if (!parsed?.signature?.value) {\n    return {\n      ok: false,\n      error: 'Missing signature value',\n      errorCode: AuthErrorCode.MISSING_SIGNATURE,\n    };\n  }\n  parsed.signature.value = MultibaseCodec.decodeBase64url(parsed.signature.value);\n  const signedObj = parsed as NIP1SignedObject;\n\n  // Use detailed verification function first (includes timestamp check)\n  const verifyResult = await verifySignatureDetailed(signedObj, resolver, {\n    maxClockSkew: opts.maxClockSkew,\n  });\n  if (!verifyResult.ok) {\n    return verifyResult; // Return the detailed error from signature verification\n  }\n\n  // Additional replay protection: nonce check (only if signature verification passed)\n  const store = opts.nonceStore ?? defaultNonceStore;\n  const maxSkew = opts.maxClockSkew ?? DEFAULT_MAX_CLOCK_SKEW;\n  const ttlSeconds = maxSkew; // allow same as window\n  const stored = await store.tryStoreNonce(\n    signedObj.signature.signer_did,\n    DEFAULT_DOMAIN_SEPARATOR,\n    signedObj.signed_data.nonce,\n    ttlSeconds\n  );\n  if (!stored) {\n    return {\n      ok: false,\n      error: 'Nonce replayed',\n      errorCode: AuthErrorCode.NONCE_REPLAYED,\n      signedObject: signedObj,\n    };\n  }\n\n  // All checks passed\n  return { ok: true, signedObject: signedObj };\n}\n\nexport default {\n  createSignature,\n  toAuthorizationHeader,\n  verifySignature,\n  verifyAuthHeader,\n  AuthErrorCode,\n};\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\n/**\n * Canonicalize a JSON object by sorting its keys.\n */\nexport function canonicalize(obj: any): string {\n  const keys = Object.keys(obj).sort();\n  return JSON.stringify(obj, keys);\n}\n","export interface NonceStore {\n  tryStoreNonce(\n    signerDid: string,\n    domainSeparator: string,\n    nonce: string,\n    ttlSeconds: number\n  ): Promise<boolean>;\n  sweep?(): Promise<void>;\n}\n\nexport interface InMemoryNonceStoreOptions {\n  capacity?: number;\n  sweepIntervalMs?: number;\n}\n\nexport class InMemoryNonceStore implements NonceStore {\n  private readonly capacity: number;\n  private readonly map: Map<string, number>; // key -> expiresAt\n  private readonly sweepInterval: NodeJS.Timeout;\n\n  constructor(options: InMemoryNonceStoreOptions = {}) {\n    this.capacity = options.capacity ?? 100_000;\n    this.map = new Map();\n    const interval = options.sweepIntervalMs ?? 60_000;\n    this.sweepInterval = setInterval(() => {\n      this.sweep?.();\n    }, interval);\n    this.sweepInterval.unref?.();\n  }\n\n  private compositeKey(signerDid: string, domainSeparator: string, nonce: string): string {\n    return `${signerDid}|${domainSeparator}|${nonce}`;\n  }\n\n  async tryStoreNonce(\n    signerDid: string,\n    domainSeparator: string,\n    nonce: string,\n    ttlSeconds: number\n  ): Promise<boolean> {\n    const key = this.compositeKey(signerDid, domainSeparator, nonce);\n    const now = Date.now();\n    const expiresAt = now + ttlSeconds * 1000;\n\n    const existing = this.map.get(key);\n    if (existing && existing > now) {\n      return false; // replay\n    }\n    // size control\n    if (this.map.size >= this.capacity) {\n      // remove oldest entry\n      const firstKey = this.map.keys().next().value as string | undefined;\n      if (firstKey) this.map.delete(firstKey);\n    }\n    this.map.set(key, expiresAt);\n    return true;\n  }\n\n  async sweep(): Promise<void> {\n    const now = Date.now();\n    for (const [key, expires] of this.map.entries()) {\n      if (expires <= now) {\n        this.map.delete(key);\n      }\n    }\n  }\n}\n\n// Default global instance\nexport const defaultNonceStore = new InMemoryNonceStore();\n","import * as v1 from './v1';\n\n/**\n * DIDAuth aggregation entry. Each version (v1, v2, …) lives in its own sub-module.\n */\nexport const DIDAuth = {\n  v1,\n} as const;\n\nexport * from './types';\n// Note: AuthErrorCode is now exported from './errors' for consistency\nexport default DIDAuth;\n","import { KeyStore, StoredKey } from '../../index';\nimport { IdentityKitErrorCode, createWebError } from '../../errors';\n\n/**\n * Browser LocalStorage implementation of KeyStore\n */\nexport class LocalStorageKeyStore implements KeyStore {\n  private readonly prefix: string;\n\n  constructor(options: { prefix?: string } = {}) {\n    // Runtime check for browser environment\n    if (typeof window === 'undefined' || typeof localStorage === 'undefined') {\n      throw createWebError(\n        IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED,\n        'LocalStorageKeyStore is only available in browser environments with localStorage support',\n        { environment: typeof window, localStorageAvailable: typeof localStorage !== 'undefined' }\n      );\n    }\n\n    this.prefix = options.prefix || 'nuwa_keystore_';\n  }\n\n  /**\n   * List all key IDs stored in this KeyStore\n   */\n  async listKeyIds(): Promise<string[]> {\n    const keys: string[] = [];\n    for (let i = 0; i < localStorage.length; i++) {\n      const key = localStorage.key(i);\n      if (key && key.startsWith(this.prefix)) {\n        keys.push(key.substring(this.prefix.length));\n      }\n    }\n    return keys;\n  }\n\n  /**\n   * Load a key by ID, or all keys if no ID is provided\n   */\n  async load(keyId?: string): Promise<StoredKey | null> {\n    if (!keyId) {\n      const keys = await this.listKeyIds();\n      if (keys.length === 0) {\n        return null;\n      }\n      return this.load(keys[0]);\n    }\n\n    const stored = localStorage.getItem(this.prefix + keyId);\n    if (!stored) {\n      return null;\n    }\n\n    try {\n      return JSON.parse(stored) as StoredKey;\n    } catch (e) {\n      console.error('Failed to parse stored key:', e);\n      return null;\n    }\n  }\n\n  /**\n   * Save a key to storage\n   */\n  async save(key: StoredKey): Promise<void> {\n    localStorage.setItem(this.prefix + key.keyId, JSON.stringify(key));\n  }\n\n  /**\n   * Clear a key from storage, or all keys if no ID is provided\n   */\n  async clear(keyId?: string): Promise<void> {\n    if (!keyId) {\n      const keys = await this.listKeyIds();\n      for (const key of keys) {\n        await this.clear(key);\n      }\n      return;\n    }\n\n    localStorage.removeItem(this.prefix + keyId);\n  }\n}\n","import { KeyStore, StoredKey } from '../../index';\nimport { IdentityKitErrorCode, createWebError, createStorageError } from '../../errors';\n\n/**\n * IndexedDB implementation of KeyStore\n * Supports storing CryptoKey objects and direct signing\n */\nexport class IndexedDBKeyStore implements KeyStore {\n  private readonly dbName: string;\n  private readonly storeName: string;\n  private db: IDBDatabase | null = null;\n\n  constructor(\n    options: {\n      dbName?: string;\n      storeName?: string;\n    } = {}\n  ) {\n    // Runtime check for browser environment with IndexedDB\n    if (typeof window === 'undefined' || typeof indexedDB === 'undefined') {\n      throw createWebError(\n        IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED,\n        'IndexedDBKeyStore is only available in browser environments with IndexedDB support',\n        { environment: typeof window, indexedDBAvailable: typeof indexedDB !== 'undefined' }\n      );\n    }\n\n    this.dbName = options.dbName || 'nuwa_keystore';\n    this.storeName = options.storeName || 'keys';\n  }\n\n  /**\n   * Initialize the database connection\n   */\n  private async initDB(): Promise<IDBDatabase> {\n    if (this.db) {\n      return this.db;\n    }\n\n    return new Promise((resolve, reject) => {\n      const request = indexedDB.open(this.dbName, 1);\n\n      request.onerror = () => {\n        reject(\n          createStorageError(\n            IdentityKitErrorCode.STORAGE_OPERATION_FAILED,\n            'Failed to open IndexedDB',\n            { dbName: this.dbName, operation: 'open' }\n          )\n        );\n      };\n\n      request.onsuccess = () => {\n        this.db = request.result;\n        resolve(this.db);\n      };\n\n      request.onupgradeneeded = event => {\n        const db = (event.target as IDBOpenDBRequest).result;\n        if (!db.objectStoreNames.contains(this.storeName)) {\n          db.createObjectStore(this.storeName, { keyPath: 'keyId' });\n        }\n      };\n    });\n  }\n\n  /**\n   * List all key IDs stored in this KeyStore\n   */\n  async listKeyIds(): Promise<string[]> {\n    const db = await this.initDB();\n\n    return new Promise((resolve, reject) => {\n      const transaction = db.transaction(this.storeName, 'readonly');\n      const store = transaction.objectStore(this.storeName);\n      const request = store.getAllKeys();\n\n      request.onsuccess = () => {\n        resolve(request.result.map(key => key.toString()));\n      };\n\n      request.onerror = () => {\n        reject(\n          createStorageError(IdentityKitErrorCode.STORAGE_OPERATION_FAILED, 'Failed to list keys', {\n            dbName: this.dbName,\n            storeName: this.storeName,\n            operation: 'listKeys',\n          })\n        );\n      };\n    });\n  }\n\n  /**\n   * Load a key by ID, or all keys if no ID is provided\n   */\n  async load(keyId?: string): Promise<StoredKey | null> {\n    const db = await this.initDB();\n\n    if (!keyId) {\n      const keys = await this.listKeyIds();\n      if (keys.length === 0) {\n        return null;\n      }\n      return this.load(keys[0]);\n    }\n\n    return new Promise((resolve, reject) => {\n      const transaction = db.transaction(this.storeName, 'readonly');\n      const store = transaction.objectStore(this.storeName);\n      const request = store.get(keyId);\n\n      request.onsuccess = () => {\n        resolve(request.result || null);\n      };\n\n      request.onerror = () => {\n        reject(\n          createStorageError(\n            IdentityKitErrorCode.STORAGE_OPERATION_FAILED,\n            `Failed to load key: ${keyId}`,\n            { keyId, dbName: this.dbName, storeName: this.storeName, operation: 'load' }\n          )\n        );\n      };\n    });\n  }\n\n  /**\n   * Save a key to storage\n   */\n  async save(key: StoredKey): Promise<void> {\n    const db = await this.initDB();\n\n    return new Promise((resolve, reject) => {\n      const transaction = db.transaction(this.storeName, 'readwrite');\n      const store = transaction.objectStore(this.storeName);\n      const request = store.put(key);\n\n      request.onsuccess = () => {\n        resolve();\n      };\n\n      request.onerror = () => {\n        reject(\n          createStorageError(\n            IdentityKitErrorCode.STORAGE_OPERATION_FAILED,\n            `Failed to save key: ${key.keyId}`,\n            { keyId: key.keyId, dbName: this.dbName, storeName: this.storeName, operation: 'save' }\n          )\n        );\n      };\n    });\n  }\n\n  /**\n   * Clear a key from storage, or all keys if no ID is provided\n   */\n  async clear(keyId?: string): Promise<void> {\n    const db = await this.initDB();\n\n    if (!keyId) {\n      const keys = await this.listKeyIds();\n      for (const key of keys) {\n        await this.clear(key);\n      }\n      return;\n    }\n\n    return new Promise((resolve, reject) => {\n      const transaction = db.transaction(this.storeName, 'readwrite');\n      const store = transaction.objectStore(this.storeName);\n      const request = store.delete(keyId);\n\n      request.onsuccess = () => {\n        resolve();\n      };\n\n      request.onerror = () => {\n        reject(\n          createStorageError(\n            IdentityKitErrorCode.STORAGE_OPERATION_FAILED,\n            `Failed to delete key: ${keyId}`,\n            { keyId, dbName: this.dbName, storeName: this.storeName, operation: 'delete' }\n          )\n        );\n      };\n    });\n  }\n}\n","import { MultibaseCodec } from '../multibase';\nimport type { KeyType } from '../types/crypto';\nimport type { AddKeyRequestPayloadV1 } from '../types/deeplink';\nimport type { VerificationRelationship } from '../types/did';\n\nexport interface BuildAddKeyPayloadInput {\n  keyType: KeyType;\n  publicKeyMultibase: string;\n  keyFragment: string;\n  relationships: VerificationRelationship[];\n  redirectUri: string;\n  state: string;\n  agentDid?: string;\n  scopes?: string[];\n}\n\nexport interface BuildAddKeyDeepLinkInput {\n  cadopDomain: string;\n  payload: AddKeyRequestPayloadV1;\n}\n\nconst LOCALHOST_PATTERN = /^(localhost|\\d+\\.\\d+\\.\\d+\\.\\d+)(:\\d+)?$/;\n\nexport function normalizeCadopDomain(cadopDomain: string): string {\n  const trimmed = cadopDomain.trim().replace(/\\/+$/, '');\n  if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {\n    return trimmed;\n  }\n  if (LOCALHOST_PATTERN.test(trimmed)) {\n    return `http://${trimmed}`;\n  }\n  return `https://${trimmed}`;\n}\n\nexport function buildAddKeyPayload(input: BuildAddKeyPayloadInput): AddKeyRequestPayloadV1 {\n  const payload: AddKeyRequestPayloadV1 = {\n    version: 1,\n    verificationMethod: {\n      type: input.keyType,\n      publicKeyMultibase: input.publicKeyMultibase,\n      idFragment: input.keyFragment,\n    },\n    verificationRelationships: input.relationships,\n    redirectUri: input.redirectUri,\n    state: input.state,\n  };\n\n  if (input.agentDid) {\n    payload.agentDid = input.agentDid;\n  }\n\n  if (input.scopes && input.scopes.length > 0) {\n    payload.scopes = input.scopes;\n  }\n\n  return payload;\n}\n\nexport function encodeAddKeyPayload(payload: AddKeyRequestPayloadV1): string {\n  return MultibaseCodec.encodeBase64url(JSON.stringify(payload));\n}\n\nexport function buildAddKeyDeepLink(input: BuildAddKeyDeepLinkInput): string {\n  const domain = normalizeCadopDomain(input.cadopDomain);\n  const encodedPayload = encodeAddKeyPayload(input.payload);\n  return `${domain}/add-key?payload=${encodedPayload}`;\n}\n","import type { KeyType, AddKeyRequestPayloadV1, VerificationRelationship } from '../../index';\nimport {\n  KeyManager,\n  CryptoUtils,\n  StoredKey,\n  MultibaseCodec,\n  KeyTypeInput,\n  toKeyType,\n  validateScopes,\n} from '../../index';\nimport { LocalStorageKeyStore } from '../keystore';\nimport { IdentityKitErrorCode, createWebError, createValidationError } from '../../errors';\nimport { buildAddKeyDeepLink, buildAddKeyPayload, normalizeCadopDomain } from '../../deeplink/shared';\n\nexport interface ConnectOptions {\n  cadopDomain?: string;\n  keyType?: KeyTypeInput; // Default: KeyType.ED25519\n  idFragment?: string;\n  relationships?: VerificationRelationship[]; // Default: ['authentication']\n  redirectPath?: string; // Default: '/callback'\n  agentDid?: string; // Target Agent DID, optional\n  /** Custom session key scopes (for authentication VM) */\n  scopes?: string[];\n}\n\nexport interface AuthResult {\n  success: boolean;\n  agentDid?: string;\n  keyId?: string;\n  error?: string;\n}\n\ninterface TempKey {\n  privateKeyMultibase: string;\n  publicKeyMultibase: string;\n  keyType: KeyType;\n  idFragment: string;\n}\n\n/**\n * Manages deep link authentication flow\n */\nexport class DeepLinkManager {\n  private keyManager: KeyManager;\n  private sessionStorage: Storage;\n\n  constructor(\n    options: {\n      keyManager?: KeyManager;\n      sessionStorage?: Storage;\n    } = {}\n  ) {\n    // Runtime check for browser environment\n    if (typeof window === 'undefined' || typeof sessionStorage === 'undefined') {\n      throw createWebError(\n        IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED,\n        'DeepLinkManager is only available in browser environments',\n        {\n          environment: typeof window,\n          sessionStorageAvailable: typeof sessionStorage !== 'undefined',\n        }\n      );\n    }\n\n    this.keyManager =\n      options.keyManager ||\n      new KeyManager({\n        store: new LocalStorageKeyStore(),\n      });\n    this.sessionStorage = options.sessionStorage || window.sessionStorage;\n  }\n\n  /**\n   * Build a deep link URL for adding a key to a DID\n   */\n  async buildAddKeyUrl(opts: ConnectOptions = {}): Promise<{\n    url: string;\n    state: string;\n    privateKeyMultibase: string;\n    publicKeyMultibase: string;\n  }> {\n    const cadopDomain = normalizeCadopDomain(opts.cadopDomain || 'id.nuwa.dev');\n    const keyType = toKeyType((opts.keyType ?? 'Ed25519VerificationKey2020') as KeyTypeInput);\n    const idFragment = opts.idFragment || `key-${Date.now()}`;\n    const relationships = opts.relationships || ['authentication'];\n    const redirectPath = opts.redirectPath || '/callback';\n\n    // Validate scopes if provided\n    if (opts.scopes && opts.scopes.length > 0) {\n      const scopeValidation = validateScopes(opts.scopes);\n      if (!scopeValidation.valid) {\n        throw createValidationError(\n          IdentityKitErrorCode.SCOPE_VALIDATION_FAILED,\n          `Invalid scope format: ${scopeValidation.invalidScopes.join(', ')}`,\n          { invalidScopes: scopeValidation.invalidScopes, allScopes: opts.scopes }\n        );\n      }\n    }\n\n    // Generate a random state to prevent CSRF\n    const state = this.generateRandomState();\n\n    // Generate a key pair\n    const { privateKey, publicKey } = await CryptoUtils.generateKeyPair(keyType);\n    const privateKeyMultibase = MultibaseCodec.encodeBase58btc(privateKey);\n    const publicKeyMultibase = MultibaseCodec.encodeBase58btc(publicKey);\n\n    // Store the private key temporarily in session storage\n    this.sessionStorage.setItem(\n      `nuwa_temp_key_${state}`,\n      JSON.stringify({\n        privateKeyMultibase: privateKeyMultibase,\n        publicKeyMultibase: publicKeyMultibase,\n        keyType,\n        idFragment,\n      })\n    );\n\n    // Build payload per spec (versioned JSON -> Base64URL)\n    const redirectUri = new URL(redirectPath, window.location.origin).toString();\n\n    const payload: AddKeyRequestPayloadV1 = buildAddKeyPayload({\n      keyType,\n      publicKeyMultibase,\n      keyFragment: idFragment,\n      relationships,\n      redirectUri,\n      state,\n      agentDid: opts.agentDid,\n      scopes: opts.scopes,\n    });\n\n    return {\n      url: buildAddKeyDeepLink({ cadopDomain, payload }),\n      state,\n      privateKeyMultibase,\n      publicKeyMultibase,\n    };\n  }\n\n  /**\n   * Handle the callback from the deep link\n   */\n  async handleCallback(search: string): Promise<AuthResult> {\n    const params = new URLSearchParams(search);\n    const state = params.get('state');\n    const agentDid = params.get('agentDid') || params.get('agent');\n    const keyId = params.get('key_id') || params.get('keyId');\n    const errorRaw = params.get('error');\n    const error = errorRaw ? decodeURIComponent(errorRaw) : undefined;\n\n    // Immediate failure if error param present and no success flag\n    if (error && !params.has('success')) {\n      return { success: false, error };\n    }\n\n    const successFlag = params.get('success');\n\n    if (successFlag === '0') {\n      return { success: false, error: error || 'Operation cancelled' };\n    }\n\n    if (!state || !agentDid || !keyId) {\n      return {\n        success: false,\n        error: 'Missing required parameters in callback',\n      };\n    }\n\n    // Retrieve the temporary key from session storage\n    const tempKeyJson = this.sessionStorage.getItem(`nuwa_temp_key_${state}`);\n    if (!tempKeyJson) {\n      return {\n        success: false,\n        error: `No matching key found for the provided state : ${state}`,\n      };\n    }\n\n    try {\n      const tempKey: TempKey = JSON.parse(tempKeyJson);\n\n      // Create a stored key object\n      const storedKey: StoredKey = {\n        keyId,\n        keyType: tempKey.keyType,\n        publicKeyMultibase: tempKey.publicKeyMultibase,\n        privateKeyMultibase: tempKey.privateKeyMultibase,\n      };\n\n      // Save the key to the key manager\n      await this.keyManager.importKey(storedKey);\n\n      // Clean up the temporary key\n      this.sessionStorage.removeItem(`nuwa_temp_key_${state}`);\n\n      return {\n        success: true,\n        agentDid,\n        keyId,\n      };\n    } catch (e) {\n      return {\n        success: false,\n        error: `Failed to process callback: ${e instanceof Error ? e.message : String(e)}`,\n      };\n    }\n  }\n\n  /**\n   * Generate a random state string\n   */\n  private generateRandomState(): string {\n    const array = new Uint8Array(16);\n    crypto.getRandomValues(array);\n    return Array.from(array)\n      .map(b => b.toString(16).padStart(2, '0'))\n      .join('');\n  }\n}\n","import {\n  KeyManager,\n  NIP1SignedObject,\n  DIDAuth,\n  VDRRegistry,\n  SignedData,\n  IdentityKit,\n  IdentityEnv,\n} from '../index';\nimport { LocalStorageKeyStore } from './keystore/LocalStorageKeyStore';\nimport { IndexedDBKeyStore } from './keystore/IndexedDBKeyStore';\nimport { DeepLinkManager } from './deeplink/DeepLinkManager';\nimport {\n  IdentityKitError,\n  IdentityKitErrorCode,\n  createWebError,\n  wrapUnknownError,\n} from '../errors';\n\nexport interface IdentityKitWebOptions {\n  /** Application name, used to build key id fragment; optional */\n  appName?: string;\n  cadopDomain?: string;\n  storage?: 'local' | 'indexeddb' | 'memory';\n  /** Optional explicit RPC endpoint for Rooch node */\n  roochRpcUrl?: string;\n}\n\n/**\n * IdentityKitWeb – High-level Web SDK for Nuwa Identity Kit\n * Provides a high-level API for web applications\n */\nexport class IdentityKitWeb {\n  private keyManager: KeyManager;\n  private deepLinkManager: DeepLinkManager;\n  private cadopDomain: string;\n  private appName?: string;\n  private identityEnv: IdentityEnv;\n\n  private constructor(\n    keyManager: KeyManager,\n    deepLinkManager: DeepLinkManager,\n    cadopDomain: string,\n    identityEnv: IdentityEnv,\n    appName?: string\n  ) {\n    this.keyManager = keyManager;\n    this.deepLinkManager = deepLinkManager;\n    this.cadopDomain = cadopDomain;\n    this.identityEnv = identityEnv;\n    this.appName = appName;\n  }\n\n  /**\n   * Initialize the IdentityKitWeb with automatic component initialization\n   */\n  static async init(options: IdentityKitWebOptions = {}): Promise<IdentityKitWeb> {\n    // Runtime check for browser environment\n    if (typeof window === 'undefined') {\n      throw createWebError(\n        IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED,\n        'IdentityKitWeb is only available in browser environments'\n      );\n    }\n    const { appName } = options;\n    const cadopDomain = options.cadopDomain || 'https://test-id.nuwa.dev';\n\n    // Resolve Rooch network and RPC URL\n    const network = resolveNetworkFromHost(cadopDomain);\n    const rpcUrl =\n      options.roochRpcUrl ||\n      (typeof window !== 'undefined' && (window as any).VITE_ROOCH_RPC_URL) ||\n      undefined;\n\n    // Determine KeyStore based on storage preference (defaults to LocalStorage)\n    let keyStore: any | undefined;\n    switch (options.storage) {\n      case 'indexeddb':\n        keyStore = new IndexedDBKeyStore();\n        break;\n      case 'memory':\n        keyStore = undefined; // let IdentityKit create an in-memory store\n        break;\n      case 'local':\n      default:\n        keyStore = new LocalStorageKeyStore();\n        break;\n    }\n\n    // Bootstrap IdentityEnv which internally registers VDRs and prepares KeyManager\n    const env = await IdentityKit.bootstrap({\n      method: 'rooch',\n      keyStore,\n      vdrOptions: { network, rpcUrl },\n    });\n\n    // Use KeyManager from the bootstrapped environment\n    const keyManager = env.keyManager;\n\n    // Create DeepLinkManager with the KeyManager\n    const deepLinkManager = new DeepLinkManager({\n      keyManager,\n    });\n\n    return new IdentityKitWeb(keyManager, deepLinkManager, cadopDomain, env, appName);\n  }\n\n  /**\n   * Advanced factory method for users who need to provide custom components\n   */\n  static async create(options: {\n    keyManager: KeyManager;\n    deepLinkManager?: DeepLinkManager;\n    identityEnv: IdentityEnv;\n    cadopDomain?: string;\n    appName?: string;\n  }): Promise<IdentityKitWeb> {\n    const { keyManager, identityEnv, appName } = options;\n    const cadopDomain = options.cadopDomain || 'https://test-id.nuwa.dev';\n\n    // Create DeepLinkManager if not provided\n    const deepLinkManager =\n      options.deepLinkManager ||\n      new DeepLinkManager({\n        keyManager,\n      });\n\n    return new IdentityKitWeb(keyManager, deepLinkManager, cadopDomain, identityEnv, appName);\n  }\n\n  /**\n   * Check if the user is connected\n   */\n  async isConnected(): Promise<boolean> {\n    const keyIds = await this.keyManager.listKeyIds();\n    return keyIds.length > 0;\n  }\n\n  /**\n   * Get the current DID\n   */\n  async getDid(): Promise<string> {\n    return await this.keyManager.getDid();\n  }\n\n  /**\n   * List all key IDs\n   */\n  async listKeyIds(): Promise<string[]> {\n    return this.keyManager.listKeyIds();\n  }\n\n  /**\n   * Connect to Cadop\n   * This will open a new window with the Cadop add-key page\n   */\n  async connect(options?: { scopes?: string[] }): Promise<void> {\n    const idFragment = this.generateIdFragment();\n\n    const { url } = await this.deepLinkManager.buildAddKeyUrl({\n      cadopDomain: this.cadopDomain,\n      idFragment,\n      scopes: options?.scopes,\n    });\n\n    // Open the URL in a new window/tab\n    window.open(url, '_blank');\n  }\n\n  /**\n   * Handle the callback from Cadop\n   */\n  async handleCallback(search: string): Promise<void> {\n    const result = await this.deepLinkManager.handleCallback(search);\n    if (!result.success) {\n      throw createWebError(\n        IdentityKitErrorCode.WEB_CALLBACK_FAILED,\n        result.error || 'Unknown error during callback',\n        { result }\n      );\n    }\n  }\n\n  /**\n   * Sign an operation payload using DIDAuth v1\n   * @param payload Object containing `operation` and `params` fields (other fields will be added automatically)\n   */\n  async sign(payload: Omit<SignedData, 'nonce' | 'timestamp'>): Promise<NIP1SignedObject> {\n    const keyIds = await this.keyManager.listKeyIds();\n    if (keyIds.length === 0) {\n      throw createWebError(IdentityKitErrorCode.KEY_NOT_FOUND, 'No keys available for signing', {\n        operation: 'sign',\n      });\n    }\n\n    const keyId = keyIds[0];\n\n    // Delegate signature creation to core DIDAuth util\n    return DIDAuth.v1.createSignature(payload, this.keyManager, keyId);\n  }\n\n  /**\n   * Verify a signature\n   */\n  async verify(sig: NIP1SignedObject, opts?: { maxClockSkew?: number }): Promise<boolean> {\n    const registry = VDRRegistry.getInstance();\n    return DIDAuth.v1.verifySignature(sig, registry, opts);\n  }\n\n  /**\n   * Logout (clear all keys)\n   */\n  async logout(): Promise<void> {\n    await this.keyManager.clear();\n  }\n\n  /**\n   * Generate a readable idFragment based on the application name.\n   * 1. Slugify the provided appName (keep a-z, 0-9, _ and -)\n   * 2. If slug becomes empty (e.g. non-Latin name), fall back to current hostname\n   * 3. If hostname slug is still empty (edge case), use default 'key'\n   * Always append timestamp to ensure uniqueness.\n   */\n  private generateIdFragment(): string {\n    const slugify = (input: string): string =>\n      input\n        .trim()\n        .toLowerCase()\n        .replace(/\\s+/g, '-')\n        .replace(/[^a-z0-9_-]/g, '');\n\n    let base = this.appName ? slugify(this.appName) : '';\n\n    if (!base) {\n      // Fallback to hostname (without port)\n      const host = typeof window !== 'undefined' ? window.location.hostname : '';\n      base = slugify(host);\n    }\n\n    if (!base) {\n      base = 'key';\n    }\n\n    return `${base}-${Date.now()}`;\n  }\n\n  /**\n   * Get the KeyManager instance\n   */\n  getKeyManager(): KeyManager {\n    return this.keyManager;\n  }\n\n  /**\n   * Get the IdentityEnv instance\n   */\n  getIdentityEnv(): IdentityEnv {\n    return this.identityEnv;\n  }\n\n  /**\n   * Get the DeepLinkManager instance\n   */\n  getDeepLinkManager(): DeepLinkManager {\n    return this.deepLinkManager;\n  }\n\n  /**\n   * Get the Cadop domain\n   */\n  getCadopDomain(): string {\n    return this.cadopDomain;\n  }\n\n  /**\n   * Get the app name\n   */\n  getAppName(): string | undefined {\n    return this.appName;\n  }\n\n  /**\n   * Expose the global VDRRegistry instance\n   */\n  static get registry(): VDRRegistry {\n    return VDRRegistry.getInstance();\n  }\n}\n\n/**\n * Resolve Rooch network from hostname – mimics logic from cadop-service registry.ts\n */\nfunction resolveNetworkFromHost(hostname: string): 'test' | 'main' {\n  let cleanHost = hostname.replace(/^https?:\\/\\//, '');\n  if (cleanHost.includes(':')) cleanHost = cleanHost.split(':')[0];\n  const h = cleanHost.toLowerCase();\n\n  if (h.startsWith('test-') || h === 'test-id.nuwa.dev') return 'test';\n  if (h === 'id.nuwa.dev' || h.endsWith('.id.nuwa.dev')) return 'main';\n  return 'test';\n}\n","import { IdentityKitWeb } from '..';\nimport { NIP1SignedObject } from '../../index';\nimport { IdentityKitErrorCode, createWebError } from '../../errors';\n\n// Import React hooks directly - the bundler will handle this as an external dependency\n// Since React is a peerDependency, the consuming application will provide it\nimport { useState, useEffect, useCallback } from 'react';\n\nexport interface IdentityKitState {\n  isConnected: boolean;\n  isConnecting: boolean;\n  agentDid: string | null;\n  keyId: string | null;\n  error: string | null;\n}\n\nexport interface IdentityKitHook {\n  state: IdentityKitState;\n  connect: (options?: { scopes?: string[] }) => Promise<void>;\n  sign: (payload: any) => Promise<NIP1SignedObject>;\n  verify: (sig: NIP1SignedObject) => Promise<boolean>;\n  logout: () => Promise<void>;\n  sdk: IdentityKitWeb | null;\n}\n\nexport interface UseIdentityKitOptions {\n  appName?: string;\n  cadopDomain?: string;\n  storage?: 'local' | 'indexeddb';\n  autoConnect?: boolean;\n  roochRpcUrl?: string;\n}\n\n/**\n * React hook for Nuwa Identity Kit (Web)\n */\nexport function useIdentityKit(options: UseIdentityKitOptions = {}): IdentityKitHook {\n  // Runtime checks for browser environment\n  if (typeof window === 'undefined') {\n    throw createWebError(\n      IdentityKitErrorCode.WEB_BROWSER_NOT_SUPPORTED,\n      'useIdentityKit is only available in browser environments'\n    );\n  }\n\n  const [sdk, setSdk] = useState<IdentityKitWeb | null>(null);\n  const [state, setState] = useState<IdentityKitState>({\n    isConnected: false,\n    isConnecting: false,\n    agentDid: null,\n    keyId: null,\n    error: null,\n  });\n\n  /**\n   * Helper – refresh connection state from SDK instance\n   */\n  async function refreshConnection(kit: IdentityKitWeb | null = sdk) {\n    if (!kit) return;\n    const isConnected = await kit.isConnected();\n    if (isConnected) {\n      const did = await kit.getDid();\n      const keyIds = await kit.listKeyIds();\n      setState({\n        isConnected: true,\n        isConnecting: false,\n        agentDid: did,\n        keyId: keyIds.length > 0 ? keyIds[0] : null,\n        error: null,\n      });\n    } else {\n      setState((prev: IdentityKitState) => ({\n        ...prev,\n        isConnected: false,\n        isConnecting: false,\n      }));\n    }\n  }\n\n  // Initialize SDK\n  useEffect(() => {\n    async function initSdk() {\n      try {\n        const newSdk = await IdentityKitWeb.init({\n          appName: options.appName,\n          cadopDomain: options.cadopDomain,\n          storage: options.storage,\n          roochRpcUrl: options.roochRpcUrl,\n        });\n        setSdk(newSdk);\n\n        // Check connection status\n        await refreshConnection(newSdk);\n      } catch (error) {\n        setState((prev: IdentityKitState) => ({\n          ...prev,\n          error: `Failed to initialize SDK: ${error instanceof Error ? error.message : String(error)}`,\n        }));\n      }\n    }\n\n    initSdk();\n  }, [options.appName, options.cadopDomain, options.storage]);\n\n  // Listen for postMessage from callback window\n  useEffect(() => {\n    function handleMessage(event: MessageEvent) {\n      if (event.data && event.data.type === 'nuwa-auth-success') {\n        // Re-check connection status when callback signals success\n        refreshConnection();\n      }\n    }\n    window.addEventListener('message', handleMessage);\n    return () => window.removeEventListener('message', handleMessage);\n  }, [sdk]);\n\n  // Connect action\n  const connect = useCallback(\n    async (options?: { scopes?: string[] }) => {\n      if (!sdk) {\n        setState((prev: IdentityKitState) => ({ ...prev, error: 'SDK not initialized' }));\n        return;\n      }\n\n      setState((prev: IdentityKitState) => ({ ...prev, isConnecting: true, error: null }));\n\n      try {\n        await sdk.connect(options);\n        // Actual connection result will be handled via postMessage in callback\n        setState((prev: IdentityKitState) => ({ ...prev, isConnecting: false }));\n      } catch (error) {\n        setState({\n          isConnected: false,\n          isConnecting: false,\n          agentDid: null,\n          keyId: null,\n          error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n        });\n      }\n    },\n    [sdk]\n  );\n\n  // Auto connect\n  useEffect(() => {\n    if (options.autoConnect && sdk && !state.isConnected && !state.isConnecting) {\n      connect();\n    }\n  }, [sdk, options.autoConnect, state.isConnected, state.isConnecting, connect]);\n\n  // Sign operation\n  const sign = useCallback(\n    async (payload: any): Promise<NIP1SignedObject> => {\n      if (!sdk)\n        throw createWebError(IdentityKitErrorCode.INITIALIZATION_FAILED, 'SDK not initialized', {\n          operation: 'sign',\n        });\n      if (!state.isConnected)\n        throw createWebError(IdentityKitErrorCode.WEB_NOT_CONNECTED, 'Not connected', {\n          operation: 'sign',\n          state,\n        });\n      return sdk.sign(payload);\n    },\n    [sdk, state.isConnected]\n  );\n\n  // Verify signature\n  const verify = useCallback(\n    async (sig: NIP1SignedObject): Promise<boolean> => {\n      if (!sdk)\n        throw createWebError(IdentityKitErrorCode.INITIALIZATION_FAILED, 'SDK not initialized', {\n          operation: 'verify',\n        });\n      return sdk.verify(sig);\n    },\n    [sdk]\n  );\n\n  // Logout\n  const logout = useCallback(async (): Promise<void> => {\n    if (!sdk)\n      throw createWebError(IdentityKitErrorCode.INITIALIZATION_FAILED, 'SDK not initialized', {\n        operation: 'logout',\n      });\n    await sdk.logout();\n    setState({\n      isConnected: false,\n      isConnecting: false,\n      agentDid: null,\n      keyId: null,\n      error: null,\n    });\n  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;AzC3JO,IAAM,WAAW,YAAY,YAAY;","names":["KeyType","base64url","base64","logger","logger","import_rooch_sdk","getCrypto","import_p256","import_rooch_sdk","import_rooch_sdk","address","module","address","sdkGetRoochNodeUrl","import_rooch_sdk","registry","registry","logger","creationRequest","AuthErrorCode","registry","options"]}