{"version":3,"sources":["../src/types/schema.ts","../src/config/cache.ts","../src/config/thresholds.ts","../src/engine/cache.ts","../src/engine/enrichment/semantic.cache.ts","../src/engine/explorer/blockscout.repository.ts","../src/engine/errors.ts","../src/engine/explorer/normalizer.ts","../src/engine/compiler/extractors/role.extractor.ts","../src/engine/compiler/extractors/event.extractor.ts","../src/engine/compiler/extractors/function.extractor.ts","../src/engine/compiler/extractors/dependency.extractor.ts","../src/engine/compiler/integrity.scorer.ts","../src/engine/compiler/graph.assembler.ts","../src/engine/compiler/pipeline.ts","../src/chain/registry.ts","../src/engine/enrichment/enricher.ts","../src/sdk/client.ts","../src/engine/enrichment/llm.provider.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const MetadataSchema = z.object({\n  protocol_name: z.string(),\n  contract_address: z.string(),\n  is_proxy: z.boolean(),\n  implementation_address: z.string().optional(),\n  compiler_version: z.string(),\n  schema_version: z.string(),\n  enrichment_version: z.string(),\n  cache_status: z.enum([\"HIT\", \"MISS\"]),\n});\n\nexport const StatisticsSchema = z.object({\n  contracts: z.number(),\n  functions: z.number(),\n  events: z.number(),\n  dependencies: z.number(),\n  roles: z.number(),\n  proxy: z.boolean(),\n  compile_time_ms: z.number()\n});\n\nexport const RoleItemSchema = z.object({\n  name: z.string(),\n  source: z.string(),\n  confidence: z.number(),\n  evidence: z.string()\n});\n\nexport const DependencyItemSchema = z.object({\n  target: z.string(),\n  detected_from: z.string(),\n  evidence: z.string()\n});\n\nexport const EventItemSchema = z.object({\n  name: z.string(),\n  source: z.string()\n});\n\nexport const FunctionItemSchema = z.object({\n  name: z.string(),\n  classification: z.string(),\n  reason: z.string(),\n  visibility: z.string()\n});\n\nexport const StructuralSchema = z.object({\n  roles: z.array(RoleItemSchema),\n  dependencies: z.array(DependencyItemSchema),\n  events: z.array(EventItemSchema),\n});\n\nexport const DerivedStringSchema = z.object({\n  value: z.string(),\n  derived_from: z.array(z.string())\n});\n\nexport const DerivedArraySchema = z.array(DerivedStringSchema);\n\nexport const SemanticSchema = z.object({\n  intent: DerivedStringSchema.nullable(),\n  user_goal: DerivedStringSchema.nullable(),\n  semantic_status: z.enum([\"PENDING\", \"RUNNING\", \"COMPLETE\", \"FAILED\", \"SKIPPED\"]).default(\"PENDING\"),\n  prompt_version: z.string().optional(),\n  model: z.string().optional(),\n  generated_at: z.string().optional(),\n  enrichment_time_ms: z.number().optional(),\n  structural_integrity_score: z.number(),\n  verified: z.boolean(),\n});\n\nexport const SecuritySchema = z.object({\n  guardrails: DerivedArraySchema,\n  privileged_functions: z.array(FunctionItemSchema),\n  structural_integrity_score: z.number(),\n  verified: z.boolean(),\n});\n\nexport const DeveloperSchema = z.object({\n  integration_notes: DerivedArraySchema,\n  structural_integrity_score: z.number(),\n  verified: z.boolean(),\n});\n\nexport const RegistrySchema = z.object({\n  registered: z.boolean(),\n  verified: z.boolean(),\n  graphHash: z.string(),\n  metadataURI: z.string(),\n  registryAddress: z.string(),\n  deploymentNetwork: z.literal(\"HashKey Mainnet\"),\n}).optional();\n\nexport const HashGraphZodSchema = z.object({\n  metadata: MetadataSchema,\n  statistics: StatisticsSchema,\n  structural: StructuralSchema,\n  semantic: SemanticSchema,\n  security: SecuritySchema,\n  developer: DeveloperSchema,\n  registry: RegistrySchema,\n});\n\nexport type HashGraphSchema = z.infer<typeof HashGraphZodSchema>;\n","export const CACHE_CONFIG = {\n    VERIFIED_TTL: 86400, // seconds\n    LOW_EVIDENCE_TTL: 3600, // seconds\n    DB_NAME: \"hashgraph.db\",\n    DB_DIR: \"data\"\n};\n","export const EVIDENCE_THRESHOLD = {\n    VERIFIED: 0.85,\n    LOW: 0.50\n};\n","import { HashGraphSchema, HashGraphZodSchema } from \"../types/schema\";\nimport { CACHE_CONFIG } from \"../config/cache\";\nimport { EVIDENCE_THRESHOLD } from \"../config/thresholds\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport semver from \"semver\";\n\nexport const CURRENT_SCHEMA_VERSION = \"1.0.0\";\nexport const CURRENT_ENRICHMENT_VERSION = \"1.0.0\";\n\nexport interface CacheMetrics {\n  hits: number;\n  misses: number;\n  writes: number;\n  expired: number;\n  corrupted: number;\n}\n\ntype Stmt = {\n  get: (...args: any[]) => any;\n  run: (...args: any[]) => any;\n};\n\ntype DbLike = {\n  exec: (sql: string) => void;\n  prepare: (sql: string) => Stmt;\n};\n\n/** Minimal in-memory stand-in when better-sqlite3 native binding is unavailable. */\nclass MemoryDb implements DbLike {\n  private graphs = new Map<string, any>();\n\n  exec(_sql: string) {}\n\n  prepare(sql: string): Stmt {\n    const s = sql.replace(/\\s+/g, \" \").trim().toLowerCase();\n    if (s.startsWith(\"select\") && s.includes(\"from protocol_graphs\")) {\n      return {\n        get: (contractAddress: string) => this.graphs.get(String(contractAddress).toLowerCase()),\n        run: () => {},\n      };\n    }\n    if (s.startsWith(\"insert\") && s.includes(\"into protocol_graphs\")) {\n      return {\n        get: () => undefined,\n        run: (\n          contractAddress: string,\n          schema_version: string,\n          enrichment_version: string,\n          structural_integrity_score: number,\n          data: string,\n          created_at: number,\n          expires_at: number | null\n        ) => {\n          this.graphs.set(String(contractAddress).toLowerCase(), {\n            data,\n            schema_version,\n            enrichment_version,\n            structural_integrity_score,\n            created_at,\n            expires_at,\n          });\n        },\n      };\n    }\n    if (s.startsWith(\"delete\") && s.includes(\"from protocol_graphs\") && s.includes(\"where contract_address\")) {\n      return {\n        get: () => undefined,\n        run: (contractAddress: string) => {\n          this.graphs.delete(String(contractAddress).toLowerCase());\n        },\n      };\n    }\n    if (s.startsWith(\"delete\") && s.includes(\"expires_at\")) {\n      return {\n        get: () => undefined,\n        run: (now: number) => {\n          for (const [k, v] of this.graphs) {\n            if (v.expires_at !== null && v.expires_at < now) this.graphs.delete(k);\n          }\n        },\n      };\n    }\n    return { get: () => undefined, run: () => {} };\n  }\n}\n\nfunction openDatabase(dbPath: string): DbLike {\n  try {\n    // Lazy require so a missing native binding doesn't crash module load.\n    // eslint-disable-next-line @typescript-eslint/no-var-requires\n    const Database = require(\"better-sqlite3\");\n    return new Database(dbPath) as DbLike;\n  } catch (err: any) {\n    console.error(\n      \"[HashGraphCache] better-sqlite3 unavailable — using in-memory cache.\",\n      err?.message || err\n    );\n    console.error(\n      \"[HashGraphCache] Tip: run `npm rebuild better-sqlite3` if you want disk persistence.\"\n    );\n    return new MemoryDb();\n  }\n}\n\nexport class HashGraphCache {\n  private db: DbLike;\n  private metrics: CacheMetrics = {\n    hits: 0,\n    misses: 0,\n    writes: 0,\n    expired: 0,\n    corrupted: 0,\n  };\n\n  constructor(dbDir: string = CACHE_CONFIG.DB_DIR, dbName: string = CACHE_CONFIG.DB_NAME) {\n    let resolvedDbDir = dbDir;\n    if (process.env.VERCEL) {\n      resolvedDbDir = \"/tmp\";\n    }\n    const fullDir = path.isAbsolute(resolvedDbDir) ? resolvedDbDir : path.resolve(process.cwd(), resolvedDbDir);\n    if (!fs.existsSync(fullDir)) {\n      fs.mkdirSync(fullDir, { recursive: true });\n    }\n\n    const dbPath = path.join(fullDir, dbName);\n    this.db = openDatabase(dbPath);\n    this.initDatabase();\n  }\n\n  private initDatabase() {\n    this.db.exec(`\n      CREATE TABLE IF NOT EXISTS protocol_graphs (\n        contract_address TEXT PRIMARY KEY,\n        schema_version TEXT NOT NULL,\n        enrichment_version TEXT NOT NULL,\n        structural_integrity_score REAL NOT NULL,\n        data TEXT NOT NULL,\n        created_at INTEGER NOT NULL,\n        expires_at INTEGER\n      )\n    `);\n  }\n\n  public getMetrics(): CacheMetrics {\n    return { ...this.metrics };\n  }\n\n  public get(contractAddress: string): HashGraphSchema | null {\n    const stmt = this.db.prepare(`\n      SELECT data, schema_version, enrichment_version, expires_at\n      FROM protocol_graphs\n      WHERE contract_address = ?\n    `);\n\n    const row = stmt.get(contractAddress) as {\n      data: string;\n      schema_version: string;\n      enrichment_version: string;\n      expires_at: number | null;\n    } | undefined;\n\n    if (!row) {\n      this.metrics.misses++;\n      return null;\n    }\n\n    // Schema version migration guard (exact major version match required)\n    if (!semver.satisfies(row.schema_version, `^${semver.major(CURRENT_SCHEMA_VERSION)}.0.0`)) {\n      this.metrics.expired++; // treat as expired/invalid\n      this.delete(contractAddress);\n      this.metrics.misses++;\n      return null;\n    }\n\n    // Enrichment version exact match\n    if (row.enrichment_version !== CURRENT_ENRICHMENT_VERSION) {\n      this.metrics.expired++;\n      this.delete(contractAddress);\n      this.metrics.misses++;\n      return null;\n    }\n\n    // TTL check\n    if (row.expires_at !== null && Date.now() > row.expires_at) {\n      this.metrics.expired++;\n      this.delete(contractAddress);\n      this.metrics.misses++;\n      return null;\n    }\n\n    try {\n      const parsedData = JSON.parse(row.data);\n      const validGraph = HashGraphZodSchema.parse(parsedData);\n\n      validGraph.metadata.cache_status = \"HIT\";\n      this.metrics.hits++;\n      return validGraph;\n    } catch (error) {\n      this.metrics.corrupted++;\n      this.delete(contractAddress);\n      this.metrics.misses++;\n      return null;\n    }\n  }\n\n  public set(contractAddress: string, graph: HashGraphSchema): void {\n    const evidenceScore =\n      (graph.semantic.structural_integrity_score +\n        graph.security.structural_integrity_score +\n        graph.developer.structural_integrity_score) /\n      3;\n\n    let ttlSeconds = CACHE_CONFIG.VERIFIED_TTL;\n    if (evidenceScore < EVIDENCE_THRESHOLD.LOW) {\n      ttlSeconds = CACHE_CONFIG.LOW_EVIDENCE_TTL;\n    }\n\n    const expiresAt = Date.now() + ttlSeconds * 1000;\n\n    const stmt = this.db.prepare(`\n      INSERT INTO protocol_graphs (\n        contract_address,\n        schema_version,\n        enrichment_version,\n        structural_integrity_score,\n        data,\n        created_at,\n        expires_at\n      ) VALUES (?, ?, ?, ?, ?, ?, ?)\n      ON CONFLICT(contract_address) DO UPDATE SET\n        schema_version = excluded.schema_version,\n        enrichment_version = excluded.enrichment_version,\n        structural_integrity_score = excluded.structural_integrity_score,\n        data = excluded.data,\n        created_at = excluded.created_at,\n        expires_at = excluded.expires_at\n    `);\n\n    graph.metadata.schema_version = CURRENT_SCHEMA_VERSION;\n    graph.metadata.enrichment_version = CURRENT_ENRICHMENT_VERSION;\n\n    // Explicitly reset cache_status to MISS before saving so if fetched outside, it's correct\n    graph.metadata.cache_status = \"MISS\";\n\n    stmt.run(\n      contractAddress,\n      CURRENT_SCHEMA_VERSION,\n      CURRENT_ENRICHMENT_VERSION,\n      evidenceScore,\n      JSON.stringify(graph),\n      Date.now(),\n      expiresAt\n    );\n\n    this.metrics.writes++;\n  }\n\n  public delete(contractAddress: string): void {\n    this.db.prepare(\"DELETE FROM protocol_graphs WHERE contract_address = ?\").run(contractAddress);\n  }\n\n  public cleanupExpiredEntries(): void {\n    const stmt = this.db.prepare(\n      \"DELETE FROM protocol_graphs WHERE expires_at IS NOT NULL AND expires_at < ?\"\n    );\n    stmt.run(Date.now());\n  }\n\n  public _getDbForTesting(): DbLike {\n    return this.db;\n  }\n}\n","import { CACHE_CONFIG } from \"../../config/cache\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nexport interface SemanticCacheData {\n  semantic: any;\n  security: any;\n  developer: any;\n}\n\ntype Stmt = {\n  get: (...args: any[]) => any;\n  run: (...args: any[]) => any;\n};\n\ntype DbLike = {\n  exec: (sql: string) => void;\n  prepare: (sql: string) => Stmt;\n};\n\nclass MemoryDb implements DbLike {\n  private rows = new Map<string, any>();\n\n  exec(_sql: string) {}\n\n  prepare(sql: string): Stmt {\n    const s = sql.replace(/\\s+/g, \" \").trim().toLowerCase();\n    if (s.startsWith(\"select\") && s.includes(\"from semantic_annotations\")) {\n      return {\n        get: (contractAddress: string) => this.rows.get(String(contractAddress).toLowerCase()),\n        run: () => {},\n      };\n    }\n    if (s.startsWith(\"insert\") && s.includes(\"into semantic_annotations\")) {\n      return {\n        get: () => undefined,\n        run: (\n          contractAddress: string,\n          prompt_version: string,\n          data: string,\n          created_at: number\n        ) => {\n          this.rows.set(String(contractAddress).toLowerCase(), {\n            data,\n            prompt_version,\n            created_at,\n          });\n        },\n      };\n    }\n    if (s.startsWith(\"delete\")) {\n      return {\n        get: () => undefined,\n        run: (contractAddress: string) => {\n          this.rows.delete(String(contractAddress).toLowerCase());\n        },\n      };\n    }\n    return { get: () => undefined, run: () => {} };\n  }\n}\n\nfunction openDatabase(dbPath: string): DbLike {\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-var-requires\n    const Database = require(\"better-sqlite3\");\n    return new Database(dbPath) as DbLike;\n  } catch (err: any) {\n    console.error(\n      \"[SemanticCache] better-sqlite3 unavailable — using in-memory cache.\",\n      err?.message || err\n    );\n    return new MemoryDb();\n  }\n}\n\nexport class SemanticCache {\n  private db: DbLike;\n\n  constructor(dbDir: string = CACHE_CONFIG.DB_DIR, dbName: string = \"semantic_hashgraph.db\") {\n    let resolvedDbDir = dbDir;\n    if (process.env.VERCEL) {\n      resolvedDbDir = \"/tmp\";\n    }\n    const fullDir = path.isAbsolute(resolvedDbDir) ? resolvedDbDir : path.resolve(process.cwd(), resolvedDbDir);\n    if (!fs.existsSync(fullDir)) {\n      fs.mkdirSync(fullDir, { recursive: true });\n    }\n\n    const dbPath = path.join(fullDir, dbName);\n    this.db = openDatabase(dbPath);\n    this.initDatabase();\n  }\n\n  private initDatabase() {\n    this.db.exec(`\n      CREATE TABLE IF NOT EXISTS semantic_annotations (\n        contract_address TEXT PRIMARY KEY,\n        prompt_version TEXT NOT NULL,\n        data TEXT NOT NULL,\n        created_at INTEGER NOT NULL\n      )\n    `);\n  }\n\n  public get(contractAddress: string, requiredPromptVersion: string): SemanticCacheData | null {\n    const stmt = this.db.prepare(`\n      SELECT data, prompt_version\n      FROM semantic_annotations\n      WHERE contract_address = ?\n    `);\n\n    const row = stmt.get(contractAddress) as { data: string; prompt_version: string } | undefined;\n\n    if (!row) return null;\n\n    if (row.prompt_version !== requiredPromptVersion) {\n      this.delete(contractAddress);\n      return null;\n    }\n\n    try {\n      return JSON.parse(row.data) as SemanticCacheData;\n    } catch {\n      this.delete(contractAddress);\n      return null;\n    }\n  }\n\n  public set(contractAddress: string, promptVersion: string, data: SemanticCacheData): void {\n    const stmt = this.db.prepare(`\n      INSERT INTO semantic_annotations (\n        contract_address,\n        prompt_version,\n        data,\n        created_at\n      ) VALUES (?, ?, ?, ?)\n      ON CONFLICT(contract_address) DO UPDATE SET\n        prompt_version = excluded.prompt_version,\n        data = excluded.data,\n        created_at = excluded.created_at\n    `);\n\n    stmt.run(contractAddress, promptVersion, JSON.stringify(data), Date.now());\n  }\n\n  public delete(contractAddress: string): void {\n    this.db.prepare(\"DELETE FROM semantic_annotations WHERE contract_address = ?\").run(contractAddress);\n  }\n}\n","import Bottleneck from \"bottleneck\";\nimport { z } from \"zod\";\nimport { IExplorerRepository } from \"./repository.interface\";\nimport { \n  ExplorerAPIError, \n  ExplorerDataError, \n  ExplorerRateLimitError, \n  ExplorerTimeoutError \n} from \"../errors\";\n\n// Blockscout returns generic responses matching this shape\nconst BlockscoutResponseSchema = z.object({\n  status: z.string(),\n  message: z.string(),\n  result: z.any()\n});\n\nexport class BlockscoutRepository implements IExplorerRepository {\n  private baseUrl: string;\n  private limiter: Bottleneck;\n\n  constructor(baseUrl: string = \"https://hsk.blockscout.com/api\") {\n    this.baseUrl = baseUrl;\n    \n    // Bottleneck handles concurrency and rate limiting\n    // Setting to max 5 requests per second to avoid hitting 429 limits\n    this.limiter = new Bottleneck({\n      minTime: 200,\n      maxConcurrent: 5\n    });\n  }\n\n  /**\n   * Internal method wrapping fetch with rate limiter and exponential backoff.\n   */\n  private async fetchWithRetry(url: string, retries = 3): Promise<any> {\n    for (let i = 0; i < retries; i++) {\n      try {\n        return await this.limiter.schedule(() => this.makeRequest(url));\n      } catch (error) {\n        // Only retry on rate limits or 5xx server errors\n        if (error instanceof ExplorerRateLimitError || \n           (error instanceof ExplorerAPIError && error.statusCode && error.statusCode >= 500)) {\n          if (i === retries - 1) throw error;\n          const backoff = 1000 * Math.pow(2, i);\n          await new Promise(resolve => setTimeout(resolve, backoff));\n        } else {\n          // Immediately throw on 400s or data errors\n          throw error;\n        }\n      }\n    }\n  }\n\n  private async makeRequest(url: string): Promise<any> {\n    const controller = new AbortController();\n    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout\n\n    try {\n      const response = await fetch(url, { signal: controller.signal });\n      clearTimeout(timeoutId);\n\n      if (response.status === 429) {\n        throw new ExplorerRateLimitError();\n      }\n\n      if (!response.ok) {\n        throw new ExplorerAPIError(`HTTP Error: ${response.statusText}`, response.status);\n      }\n\n      const rawData = await response.json();\n      \n      // Strict Zod validation on the boundary\n      const parsedData = BlockscoutResponseSchema.safeParse(rawData);\n      if (!parsedData.success) {\n        throw new ExplorerDataError(\"Invalid response schema from Blockscout\");\n      }\n\n      return parsedData.data;\n    } catch (error: any) {\n      clearTimeout(timeoutId);\n      if (error.name === 'AbortError') {\n        throw new ExplorerTimeoutError();\n      }\n      throw error;\n    }\n  }\n\n  public async fetchContractAbi(address: string): Promise<string | null> {\n    try {\n      const url = `${this.baseUrl}?module=contract&action=getabi&address=${address}`;\n      const data = await this.fetchWithRetry(url);\n      \n      // Status \"1\" means success/verified. Status \"0\" usually means unverified.\n      if (data.status === \"1\" && typeof data.result === \"string\") {\n        return data.result;\n      }\n    } catch (e) {\n      console.warn(`[Blockscout] Failed to fetch ABI for ${address}, trying local fallback...`);\n    }\n\n    // Local Fallbacks for demo contracts\n    if (address.toLowerCase() === \"0xb210d2120d57b758ee163cffb43e73728c471cf1\".toLowerCase()) {\n      return '[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]';\n    }\n    if (address.toLowerCase() === \"0x4200000000000000000000000000000000000015\".toLowerCase()) {\n      return '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_admin\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previousAdmin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"AdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"implementation\",\"type\":\"address\"}],\"name\":\"Upgraded\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]';\n    }\n    if (address.toLowerCase() === \"0x4200000000000000000000000000000000000016\".toLowerCase()) {\n      return '[{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]';\n    }\n\n    return null;\n  }\n\n  public async fetchContractSource(address: string): Promise<string | null> {\n    const url = `${this.baseUrl}?module=contract&action=getsourcecode&address=${address}`;\n    const data = await this.fetchWithRetry(url);\n    \n    if (data.status === \"1\" && Array.isArray(data.result) && data.result.length > 0) {\n      if (data.result[0].SourceCode) {\n         return data.result[0].SourceCode;\n      }\n    }\n    return null;\n  }\n\n  public async resolveProxyImplementation(address: string): Promise<string | null> {\n    const url = `${this.baseUrl}?module=contract&action=getsourcecode&address=${address}`;\n    const data = await this.fetchWithRetry(url);\n    \n    if (data.status === \"1\" && Array.isArray(data.result) && data.result.length > 0) {\n      const contract = data.result[0];\n      // Blockscout / Etherscan format for proxy tracking\n      if (contract.Proxy === \"1\" && contract.Implementation) {\n        return contract.Implementation;\n      }\n    }\n    return null;\n  }\n}\n","export class ExplorerRateLimitError extends Error {\n  constructor(message: string = \"Explorer API rate limit exceeded\") {\n    super(message);\n    this.name = \"ExplorerRateLimitError\";\n  }\n}\n\nexport class ExplorerTimeoutError extends Error {\n  constructor(message: string = \"Explorer API request timed out\") {\n    super(message);\n    this.name = \"ExplorerTimeoutError\";\n  }\n}\n\nexport class ExplorerAPIError extends Error {\n  constructor(message: string, public statusCode?: number) {\n    super(message);\n    this.name = \"ExplorerAPIError\";\n  }\n}\n\nexport class ExplorerDataError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"ExplorerDataError\";\n  }\n}\n","import { IExplorerRepository } from \"./repository.interface\";\nimport { createPublicClient, http, Address, parseAbi } from \"viem\";\n\nexport interface NormalizedContractData {\n  address: string;\n  isProxy: boolean;\n  implementationAddress: string | null;\n  abi: string | null;\n  sourceCode: string | null;\n}\n\n// Proxy slot reads must hit the same chain as Blockscout (HashKey Mainnet).\nconst HASHKEY_CHAIN = {\n  id: 177,\n  name: \"HashKey Mainnet\",\n  nativeCurrency: { name: \"HSK\", symbol: \"HSK\", decimals: 18 },\n  rpcUrls: { default: { http: [process.env.HASHKEY_RPC_URL ?? process.env.RPC_URL ?? \"https://mainnet.hsk.xyz\"] } },\n} as const;\n\nexport class DataNormalizer {\n  private repository: IExplorerRepository;\n  private client = createPublicClient({ chain: HASHKEY_CHAIN, transport: http() });\n\n  // Dependency Inversion: Compiler doesn't know about Blockscout\n  constructor(repository: IExplorerRepository) {\n    this.repository = repository;\n  }\n\n  /**\n   * Normalizes explorer data for the compiler.\n   * Resolves standard proxy implementations and Diamond proxies automatically.\n   */\n  public async normalize(address: string): Promise<NormalizedContractData> {\n    // 1. Try standard proxy resolution from explorer\n    let implementationAddress = await this.repository.resolveProxyImplementation(address);\n    let isProxy = !!implementationAddress;\n    \n    // 1.5 Try raw EIP-1967 storage slot read if explorer failed\n    if (!isProxy) {\n        try {\n            // EIP-1967 Implementation Slot: bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)\n            const EIP1967_SLOT = \"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\";\n            const slotData = await this.client.getStorageAt({\n                address: address as Address,\n                slot: EIP1967_SLOT\n            });\n            // The slot returns a 32-byte hex. An address is the last 20 bytes (40 hex chars).\n            if (slotData && slotData !== \"0x\" && slotData !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n                const extractedAddress = \"0x\" + slotData.slice(26); // slice off the '0x' + 24 zeros\n                isProxy = true;\n                implementationAddress = extractedAddress;\n                console.log(`[Normalizer] EIP-1967 Proxy detected via raw storage slot! Implementation: ${extractedAddress}`);\n            } else {\n                // Try Beacon Slot: bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)\n                const BEACON_SLOT = \"0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50\";\n                const beaconSlotData = await this.client.getStorageAt({\n                    address: address as Address,\n                    slot: BEACON_SLOT\n                });\n                if (beaconSlotData && beaconSlotData !== \"0x\" && beaconSlotData !== \"0x0000000000000000000000000000000000000000000000000000000000000000\") {\n                    const beaconAddress = \"0x\" + beaconSlotData.slice(26);\n                    // Now ask the beacon for the implementation\n                    const implData = await this.client.readContract({\n                        address: beaconAddress as Address,\n                        abi: parseAbi([\"function implementation() external view returns (address)\"]),\n                        functionName: 'implementation'\n                    });\n                    isProxy = true;\n                    implementationAddress = implData as string;\n                    console.log(`[Normalizer] EIP-1967 Beacon Proxy detected! Beacon: ${beaconAddress}, Implementation: ${implementationAddress}`);\n                }\n            }\n        } catch (e) {\n            // Ignore storage read failures\n        }\n    }\n    \n    // 1.75 Try EIP-1167 Minimal Proxy clone detection\n    if (!isProxy) {\n        try {\n            const bytecode = await this.client.getBytecode({ address: address as Address });\n            if (bytecode && bytecode.startsWith(\"0x363d3d373d3d3d363d73\")) {\n                // EIP-1167 minimal proxy bytecode pattern:\n                // 363d3d373d3d3d363d73 <20 bytes> 5af43d82803e903d91602b57fd5bf3\n                const extractedAddress = \"0x\" + bytecode.slice(22, 62);\n                isProxy = true;\n                implementationAddress = extractedAddress;\n                console.log(`[Normalizer] EIP-1167 Minimal Clone detected! Implementation: ${extractedAddress}`);\n            }\n        } catch (e) {\n            // Ignore bytecode read failures\n        }\n    }\n    \n    // 2. Try Diamond Proxy resolution if no standard implementation was found\n    let combinedAbi = \"\";\n    let combinedSource = \"\";\n    \n    if (!isProxy) {\n        try {\n            // EIP-2535 Loupe function\n            const facets = await this.client.readContract({\n                address: address as Address,\n                abi: parseAbi([\"function facets() external view returns (tuple(address facetAddress, bytes4[] functionSelectors)[])\"]),\n                functionName: 'facets'\n            });\n            \n            const facetsArray = facets as any[];\n            if (facetsArray && facetsArray.length > 0) {\n                isProxy = true;\n                implementationAddress = \"DiamondProxy\";\n                console.log(`[Normalizer] Detected Diamond Proxy with ${facetsArray.length} facets.`);\n                \n                // Fetch ABIs for all facets in parallel\n                const facetData = await Promise.all(\n                    facetsArray.map((f: any) => this.repository.fetchContractAbi(f.facetAddress))\n                );\n                \n                const abis = facetData.filter(Boolean).map((a: any) => JSON.parse(a as string));\n                const flatAbi = abis.flat();\n                \n                // Deduplicate ABI items by name/type\n                const uniqueAbi = Array.from(new Map(flatAbi.map((item: any) => \n                    [item.name + item.type, item]\n                )).values());\n                \n                combinedAbi = JSON.stringify(uniqueAbi);\n                combinedSource = \"// Diamond Proxy Facets Combined Source\";\n                \n                return {\n                    address,\n                    isProxy,\n                    implementationAddress,\n                    abi: combinedAbi,\n                    sourceCode: combinedSource\n                };\n            }\n        } catch (e) {\n            // Not a diamond proxy\n        }\n    }\n\n    const targetAddress = implementationAddress && implementationAddress !== \"DiamondProxy\" ? implementationAddress : address;\n\n    let [abi, sourceCode] = await Promise.all([\n      this.repository.fetchContractAbi(targetAddress),\n      this.repository.fetchContractSource(targetAddress)\n    ]);\n\n    // Fix 2: Unflatten JSON source code (Blockscout specific quirk)\n    if (sourceCode && sourceCode.startsWith(\"{\") && sourceCode.endsWith(\"}\")) {\n        try {\n            // Sometimes it is wrapped in double curly braces {{ ... }}\n            let cleanJson = sourceCode;\n            if (cleanJson.startsWith(\"{{\") && cleanJson.endsWith(\"}}\")) {\n                cleanJson = cleanJson.slice(1, -1);\n            }\n            const parsed = JSON.parse(cleanJson);\n            \n            // If it's a Standard JSON input format, extract all sources and combine them\n            if (parsed.sources) {\n                let combined = \"\";\n                for (const [path, content] of Object.entries(parsed.sources) as any) {\n                    combined += `// File: ${path}\\n${content.content}\\n\\n`;\n                }\n                sourceCode = combined;\n                console.log(`[Normalizer] Successfully unflattened ${Object.keys(parsed.sources).length} files from JSON source.`);\n            }\n        } catch (e) {\n            // Not valid JSON, keep as is\n            console.log(`[Normalizer] JSON parsing failed for source code, keeping as text.`);\n        }\n    }\n\n    // Fallback for unverified contracts (Fix 1: Decompilation Pipeline)\n    if (!abi || abi === \"[]\") {\n        console.log(`[Normalizer] Contract unverified. Falling back to bytecode decompilation...`);\n        const { BytecodeDecompiler } = await import(\"./bytecode.js\");\n        const decompiler = new BytecodeDecompiler();\n        const pseudoAbi = await decompiler.generatePseudoAbi(targetAddress);\n        if (pseudoAbi) {\n            abi = pseudoAbi;\n            sourceCode = \"// Unverified Contract: Pseudo-ABI generated from bytecode selectors\";\n        }\n    }\n\n    return {\n      address,\n      isProxy,\n      implementationAddress,\n      abi,\n      sourceCode\n    };\n  }\n}\n\n","import { CompilerInput, GraphExtractor, RoleResult, RoleItem } from \"../interfaces\";\n\nexport class RoleExtractor implements GraphExtractor<RoleResult> {\n    public name = \"RoleExtractor\";\n\n    public async extract(input: CompilerInput): Promise<RoleResult> {\n        const rolesMap = new Map<string, RoleItem>();\n\n        if (input.abi) {\n            for (const item of input.abi) {\n                if (item && item.type === \"function\") {\n                    if (item.name === \"owner\" || item.name === \"transferOwnership\") {\n                        // ADR-014: confidence = 1.0 ← derived from verified ABI function signature for ownership\n                        rolesMap.set(\"Owner\", { name: \"Owner\", source: \"ABI\", confidence: 1.0, evidence: `${item.name}()` });\n                    }\n                    if (item.name === \"hasRole\") {\n                        // ADR-014: confidence = 1.0 ← derived from OpenZeppelin AccessControl signature hasRole\n                        rolesMap.set(\"AccessControl\", { name: \"AccessControl\", source: \"ABI\", confidence: 1.0, evidence: \"hasRole(bytes32,address)\" });\n                    }\n                    if (item.name === \"MINTER_ROLE\") {\n                        // ADR-014: confidence = 1.0 ← derived from explicit MINTER_ROLE declaration in ABI\n                        rolesMap.set(\"Minter\", { name: \"Minter\", source: \"ABI\", confidence: 1.0, evidence: \"MINTER_ROLE()\" });\n                    }\n                }\n            }\n        }\n\n        if (input.source) {\n            if (input.source.includes(\"contract Ownable\") || input.source.includes(\"is Ownable\")) {\n                if (!rolesMap.has(\"Owner\")) {\n                    // ADR-014: confidence = 0.9 ← derived from source code pattern matching of Ownable contract inheritance (less certain than ABI function check)\n                    rolesMap.set(\"Owner\", { name: \"Owner\", source: \"Source\", confidence: 0.9, evidence: \"Inherits Ownable\" });\n                }\n            }\n        }\n\n        return { roles: Array.from(rolesMap.values()) };\n    }\n}\n","import { CompilerInput, GraphExtractor, EventResult, EventItem } from \"../interfaces\";\n\nexport class EventExtractor implements GraphExtractor<EventResult> {\n    public name = \"EventExtractor\";\n\n    public async extract(input: CompilerInput): Promise<EventResult> {\n        const events: EventItem[] = [];\n\n        if (input.abi) {\n            for (const item of input.abi) {\n                if (item && (item.type === \"event\" || item.type === \"error\") && item.name) {\n                    // ADR-014: source = \"ABI\" ← events/errors extracted directly from verified ABI specifications\n                    events.push({\n                        name: item.type === \"error\" ? `[Error] ${item.name}` : item.name,\n                        source: \"ABI\"\n                    });\n                }\n            }\n        }\n\n        return { events };\n    }\n}\n","import { CompilerInput, GraphExtractor, FunctionResult, FunctionItem } from \"../interfaces\";\n\nexport class FunctionExtractor implements GraphExtractor<FunctionResult> {\n    public name = \"FunctionExtractor\";\n\n    public async extract(input: CompilerInput): Promise<FunctionResult> {\n        const privileged: FunctionItem[] = [];\n        const publicFuncs: FunctionItem[] = [];\n\n        if (input.abi) {\n            for (const item of input.abi) {\n                if (item && item.type === \"function\") {\n                    const isViewOrPure = item.stateMutability === \"view\" || item.stateMutability === \"pure\";\n                    \n                    const isPrivileged = !isViewOrPure && typeof item.name === \"string\" && (\n                        item.name.startsWith(\"set\") ||\n                        item.name.startsWith(\"update\") ||\n                        item.name === \"pause\" ||\n                        item.name === \"unpause\" ||\n                        item.name === \"mint\" ||\n                        item.name === \"burn\" ||\n                        item.name === \"transferOwnership\" ||\n                        item.name === \"upgradeTo\"\n                    );\n\n                    const visibility = (item.stateMutability === \"private\" || item.stateMutability === \"internal\") \n                        ? item.stateMutability : \"external\";\n\n                    if (isPrivileged) {\n                        // ADR-014: classification = \"privileged\" ← determined by state mutation heuristics (prefixes like set/update/mint/burn/pause/upgrade)\n                        privileged.push({\n                            name: item.name || \"\",\n                            classification: \"privileged\",\n                            reason: \"state mutation heuristic\",\n                            visibility\n                        });\n                    } else if (visibility !== \"private\" && visibility !== \"internal\") {\n                        // ADR-014: classification = \"read-only\" or \"public mutator\" ← derived from stateMutability (pure/view means read-only, nonpayable/payable means mutator)\n                        publicFuncs.push({\n                            name: item.name || \"\",\n                            classification: isViewOrPure ? \"read-only\" : \"public mutator\",\n                            reason: isViewOrPure ? \"no state mutation\" : \"standard state mutation\",\n                            visibility\n                        });\n                    }\n                }\n            }\n        }\n\n        return { \n            privileged_functions: privileged, \n            public_functions: publicFuncs \n        };\n    }\n}\n","import { CompilerInput, GraphExtractor, DependencyResult, DependencyItem } from \"../interfaces\";\n\nexport class DependencyExtractor implements GraphExtractor<DependencyResult> {\n    public name = \"DependencyExtractor\";\n\n    public async extract(input: CompilerInput): Promise<DependencyResult> {\n        if (input.depth >= input.maxDepth || input.visited.has(input.address)) {\n            return { dependencies: [] };\n        }\n        input.visited.add(input.address);\n\n        const depsMap = new Map<string, DependencyItem>();\n\n        if (input.abi) {\n            for (const item of input.abi) {\n                if (item && item.inputs) {\n                    for (const inputParam of item.inputs) {\n                        if (inputParam.internalType && inputParam.internalType.startsWith(\"contract I\")) {\n                            // ADR-014: detected_from = \"constructor\" or \"function\" ← inferred from parameters pointing to custom contracts starting with I (e.g. contract IPriceOracle)\n                            const target = inputParam.internalType.replace(\"contract \", \"\").replace(\"[]\", \"\");\n                            depsMap.set(target, {\n                                target,\n                                detected_from: item.type === \"constructor\" ? \"constructor\" : `function ${item.name}`,\n                                evidence: `${item.type === \"constructor\" ? \"constructor\" : item.name}(${inputParam.internalType} ${inputParam.name})`\n                            });\n                        }\n                    }\n                }\n            }\n        }\n\n        if (input.source) {\n            if (input.source.includes(\"@openzeppelin/contracts/token/ERC20\")) {\n                // ADR-014: detected_from = \"source imports\" ← dependency inferred from openzeppelin token import path\n                if (!depsMap.has(\"IERC20\")) depsMap.set(\"IERC20\", { target: \"IERC20\", detected_from: \"source imports\", evidence: \"import @openzeppelin...ERC20\" });\n            }\n            if (input.source.includes(\"@openzeppelin/contracts/token/ERC721\")) {\n                // ADR-014: detected_from = \"source imports\" ← dependency inferred from openzeppelin token import path\n                if (!depsMap.has(\"IERC721\")) depsMap.set(\"IERC721\", { target: \"IERC721\", detected_from: \"source imports\", evidence: \"import @openzeppelin...ERC721\" });\n            }\n        }\n\n        return { dependencies: Array.from(depsMap.values()) };\n    }\n}\n","import { IntegrityEvidence, CompilerInput } from \"./interfaces\";\n\nexport class IntegrityScorer {\n    public score(evidence: IntegrityEvidence): number {\n        let score = 0;\n        \n        // ADR-014: +50 points ← verified source code available (highest confidence source)\n        if (evidence.verifiedSource) score += 50;\n        // ADR-014: +30 points ← verified ABI available (fallback when no source code)\n        else if (evidence.verifiedABI) score += 30;\n\n        // ADR-014: +15 points ← standard openzeppelin imports found, showing standard/secure base libraries\n        if (evidence.openzeppelin) score += 15;\n        // ADR-014: +20 points ← proxy address resolved successfully, verifying implementation legitimacy\n        if (evidence.proxyResolved) score += 20;\n        // ADR-014: +5 points ← dependency links found, enriching graph coverage\n        if (evidence.dependencyCoverage > 0) score += 5;\n        // ADR-014: +10 points ← events/errors successfully extracted\n        if (evidence.eventCoverage > 0) score += 10;\n\n        return Math.min(100, score);\n    }\n}\n\nexport class IntegrityBuilder {\n    public build(input: CompilerInput, extractedDeps: number, extractedEvents: number): IntegrityEvidence {\n        return {\n            verifiedABI: !!(input.abi && input.abi.length > 0),\n            verifiedSource: !!input.source,\n            openzeppelin: !!(input.source && input.source.includes(\"@openzeppelin\")),\n            proxyResolved: input.isProxy && !!input.implementation,\n            dependencyCoverage: extractedDeps > 0 ? 1.0 : 0.0,\n            eventCoverage: extractedEvents > 0 ? 1.0 : 0.0,\n        };\n    }\n}\n","import { HashGraphSchema } from \"../../types/schema\";\nimport { \n  CompilerInput, \n  RoleResult, \n  EventResult, \n  FunctionResult, \n  DependencyResult \n} from \"./interfaces\";\n\nexport class GraphAssembler {\n    public assemble(\n        input: CompilerInput,\n        roles: RoleResult,\n        events: EventResult,\n        functions: FunctionResult,\n        deps: DependencyResult,\n        integrityScore: number,\n        extractionTimeMs: number\n    ): HashGraphSchema {\n        \n        const isVerified = integrityScore >= 85;\n\n        return {\n            metadata: {\n                protocol_name: input.metadata.protocolName,\n                contract_address: input.address,\n                is_proxy: input.isProxy,\n                implementation_address: input.implementation || undefined,\n                compiler_version: input.metadata.compilerVersion,\n                schema_version: \"1.0.0\",\n                enrichment_version: \"1.0.0\",\n                cache_status: \"MISS\"\n            },\n            statistics: {\n                contracts: 1 + (input.isProxy && input.implementation ? 1 : 0),\n                functions: functions.privileged_functions.length + functions.public_functions.length,\n                events: events.events.length,\n                dependencies: deps.dependencies.length,\n                roles: roles.roles.length,\n                proxy: input.isProxy,\n                compile_time_ms: Math.round(extractionTimeMs)\n            },\n            structural: {\n                roles: roles.roles,\n                dependencies: deps.dependencies,\n                events: events.events\n            },\n            semantic: {\n                intent: null,\n                user_goal: null,\n                semantic_status: \"PENDING\",\n                structural_integrity_score: integrityScore,\n                verified: isVerified\n            },\n            security: {\n                guardrails: [],\n                privileged_functions: functions.privileged_functions,\n                structural_integrity_score: integrityScore,\n                verified: isVerified\n            },\n            developer: {\n                integration_notes: [],\n                structural_integrity_score: integrityScore,\n                verified: isVerified\n            }\n        };\n    }\n}\n","/**\n * @file pipeline.ts\n * @description Orchestrates the deterministic compiling pipeline for HashGraph.\n * Wires together pure extractor stages, integrity builders, scorers, and assemblers.\n *\n * Adheres to:\n * - ADR-013: Compiler Stages Are Pure. Operates as a pure orchestrator, collecting\n *   deterministic facts without network requests, LLM interactions, or mutating shared state.\n */\n\nimport { \n    CompilerInput, \n    CompilerDiagnostics, \n    RoleResult, \n    EventResult, \n    FunctionResult, \n    DependencyResult \n} from \"./interfaces\";\nimport { RoleExtractor } from \"./extractors/role.extractor\";\nimport { EventExtractor } from \"./extractors/event.extractor\";\nimport { FunctionExtractor } from \"./extractors/function.extractor\";\nimport { DependencyExtractor } from \"./extractors/dependency.extractor\";\nimport { IntegrityBuilder, IntegrityScorer } from \"./integrity.scorer\";\nimport { GraphAssembler } from \"./graph.assembler\";\nimport { HashGraphSchema } from \"../../types/schema\";\nimport crypto from \"crypto\";\nimport { lookupGraph } from \"../../chain/registry\";\n\n\nexport class CompilerPipeline {\n    private roleExtractor = new RoleExtractor();\n    private eventExtractor = new EventExtractor();\n    private functionExtractor = new FunctionExtractor();\n    private dependencyExtractor = new DependencyExtractor();\n    \n    private integrityBuilder = new IntegrityBuilder();\n    private integrityScorer = new IntegrityScorer();\n    private assembler = new GraphAssembler();\n\n    private static compileCounter = 0;\n\n    public async compile(input: CompilerInput): Promise<{ graph: HashGraphSchema, diagnostics: CompilerDiagnostics }> {\n        CompilerPipeline.compileCounter++;\n        const compileId = CompilerPipeline.compileCounter;\n        \n        const diagnostics: CompilerDiagnostics = {\n            warnings: [],\n            skipped: [],\n            unsupported: [],\n            extraction_time_ms: 0,\n            stage_times: {},\n            parser_version: \"1.0.0\",\n            trace: \"\"\n        };\n        \n        const totalStart = performance.now();\n\n        // 1. Role Extraction\n        const roleStart = performance.now();\n        const roles: RoleResult = await this.roleExtractor.extract(input);\n        diagnostics.stage_times[this.roleExtractor.name] = performance.now() - roleStart;\n\n        // 2. Event Extraction\n        const eventStart = performance.now();\n        const events: EventResult = await this.eventExtractor.extract(input);\n        diagnostics.stage_times[this.eventExtractor.name] = performance.now() - eventStart;\n\n        // 3. Function Extraction\n        const funcStart = performance.now();\n        const functions: FunctionResult = await this.functionExtractor.extract(input);\n        diagnostics.stage_times[this.functionExtractor.name] = performance.now() - funcStart;\n\n        // 4. Dependency Extraction\n        const depStart = performance.now();\n        const deps: DependencyResult = await this.dependencyExtractor.extract(input);\n        diagnostics.stage_times[this.dependencyExtractor.name] = performance.now() - depStart;\n\n        // 5. Integrity Scoring\n        const evidenceStart = performance.now();\n        const evidence = this.integrityBuilder.build(input, deps.dependencies.length, events.events.length);\n        const score = this.integrityScorer.score(evidence);\n        diagnostics.stage_times['IntegrityScorer'] = performance.now() - evidenceStart;\n\n        const extractionTimeMs = performance.now() - totalStart;\n        diagnostics.extraction_time_ms = extractionTimeMs;\n\n        // 6. Graph Assembly\n        const assembleStart = performance.now();\n        const graph = this.assembler.assemble(input, roles, events, functions, deps, score, extractionTimeMs);\n        diagnostics.stage_times['GraphAssembler'] = performance.now() - assembleStart;\n\n        // 7. Hash & Registry Lookup\n        const registryStart = performance.now();\n        // Create a deterministic hash string (sort keys to be safe, but JSON.stringify on structured data is usually deterministic here since order is defined by Schema)\n        const hashInput = JSON.stringify({\n            address: input.address.toLowerCase(),\n            roles: graph.structural.roles,\n            events: graph.structural.events,\n            dependencies: graph.structural.dependencies,\n            functions: graph.security.privileged_functions\n        });\n        const graphHash = \"0x\" + crypto.createHash(\"sha256\").update(hashInput).digest(\"hex\");\n        \n        const attestation = await lookupGraph(input.address);\n        const ZERO =\n          \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n        const hasAttestation = !!(\n          attestation &&\n          attestation.verified &&\n          attestation.graphHash &&\n          attestation.graphHash !== ZERO\n        );\n\n        graph.registry = {\n            registered: hasAttestation,\n            verified: hasAttestation && attestation!.graphHash === graphHash,\n            graphHash: graphHash,\n            metadataURI: hasAttestation ? attestation!.metadataURI : \"\",\n            registryAddress:\n              process.env.REGISTRY_ADDRESS ||\n              process.env.NEXT_PUBLIC_REGISTRY_ADDRESS ||\n              \"0x3776Cc9AEe3AFb005F9465e6B78079FCf4d16DA6\",\n            deploymentNetwork: \"HashKey Mainnet\"\n        };\n        diagnostics.stage_times['RegistryLookup'] = performance.now() - registryStart;\n\n        // Trace Generation\n        diagnostics.trace = this.generateTrace(compileId, evidence, score, extractionTimeMs);\n\n        if (input.source && input.source.includes(\"assembly {\")) {\n            diagnostics.unsupported.push(\"Inline Assembly detected - structural graph may be incomplete\");\n        }\n\n        return { graph, diagnostics };\n    }\n\n    private generateTrace(id: number, evidence: any, score: number, timeMs: number): string {\n        const check = (condition: boolean) => condition ? \"✓\" : \"✗\";\n        \n        return [\n            `Compile #${id}`,\n            \"\",\n            `ABI Loaded ${check(evidence.verifiedABI)}`,\n            `Source Verified ${check(evidence.verifiedSource)}`,\n            `Proxy Resolved ${check(evidence.proxyResolved)}`,\n            `Role Extraction ✓`,\n            `Event Extraction ✓`,\n            `Dependency Extraction ✓`,\n            \"\",\n            `Integrity Score ${score}`,\n            \"\",\n            `Completed in ${Math.round(timeMs)} ms`\n        ].join(\"\\\\n\");\n    }\n}\n","import { createPublicClient, createWalletClient, http, custom, Address } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\nconst REGISTRY_ABI = [\n  {\n    name: \"getAttestation\",\n    type: \"function\",\n    stateMutability: \"view\",\n    inputs: [{ name: \"protocol\", type: \"address\" }],\n    outputs: [\n      { name: \"graphHash\",    type: \"bytes32\" },\n      { name: \"metadataURI\",  type: \"string\"  },\n      { name: \"attester\",     type: \"address\" },\n      { name: \"timestamp\",    type: \"uint256\" },\n      { name: \"verified\",     type: \"bool\"    },\n    ],\n  },\n  {\n    name: \"attest\",\n    type: \"function\",\n    stateMutability: \"nonpayable\",\n    inputs: [\n      { name: \"protocol\",     type: \"address\" },\n      { name: \"graphHash\",    type: \"bytes32\" },\n      { name: \"metadataURI\",  type: \"string\"  },\n    ],\n    outputs: [],\n  },\n] as const;\n\n// HashGraphRegistry on HashKey Mainnet (see deployments/mainnet.json).\n// Override with REGISTRY_CHAIN_ID / REGISTRY_RPC_URL for testnet or custom RPCs.\nconst DEFAULT_REGISTRY_ADDRESS =\n  \"0x3776Cc9AEe3AFb005F9465e6B78079FCf4d16DA6\" as const;\n\nconst HASHKEY_CHAIN = {\n  id: Number(process.env.REGISTRY_CHAIN_ID ?? 177),\n  name: process.env.REGISTRY_CHAIN_NAME ?? \"HashKey Mainnet\",\n  nativeCurrency: { name: \"HSK\", symbol: \"HSK\", decimals: 18 },\n  rpcUrls: {\n    default: {\n      http: [\n        process.env.REGISTRY_RPC_URL ??\n          process.env.HASHKEY_RPC_URL ??\n          process.env.RPC_URL ??\n          \"https://mainnet.hsk.xyz\",\n      ],\n    },\n  },\n} as const;\n\nexport interface RegistryAttestation {\n  graphHash: string;\n  metadataURI: string;\n  attester: string;\n  timestamp: number;\n  verified: boolean;\n}\n\nfunction getPublicClient() {\n  return createPublicClient({\n    chain: HASHKEY_CHAIN,\n    transport: http()\n  });\n}\n\nfunction getRegistryAddress(): Address {\n  const addr =\n    process.env.REGISTRY_ADDRESS ||\n    process.env.NEXT_PUBLIC_REGISTRY_ADDRESS ||\n    DEFAULT_REGISTRY_ADDRESS;\n  return addr as Address;\n}\n\nexport async function lookupGraph(protocolAddress: string): Promise<RegistryAttestation | null> {\n  const publicClient = getPublicClient();\n  const registryAddress = getRegistryAddress();\n  \n  if (registryAddress === '0x0000000000000000000000000000000000000000') return null;\n\n  try {\n    const data = await publicClient.readContract({\n      address: registryAddress,\n      abi: REGISTRY_ABI,\n      functionName: 'getAttestation',\n      args: [protocolAddress as Address],\n    });\n\n    return {\n      graphHash: data[0],\n      metadataURI: data[1],\n      attester: data[2],\n      timestamp: Number(data[3]),\n      verified: data[4],\n    };\n  } catch (err) {\n    console.error(`[Registry] Failed to lookup graph for ${protocolAddress}`, err);\n    return null;\n  }\n}\n\nexport async function registerGraph(protocolAddress: string, graphHash: string, metadataURI: string): Promise<string | null> {\n  const pk = process.env.DEPLOYER_PRIVATE_KEY;\n  if (!pk) {\n      console.error(\"[Registry] Missing DEPLOYER_PRIVATE_KEY in .env\");\n      return null;\n  }\n\n  const account = privateKeyToAccount(pk as `0x${string}`);\n  const walletClient = createWalletClient({\n    account,\n    chain: HASHKEY_CHAIN,\n    transport: http()\n  });\n  const publicClient = getPublicClient();\n  \n  try {\n    const { request } = await publicClient.simulateContract({\n      account,\n      address: getRegistryAddress(),\n      abi: REGISTRY_ABI,\n      functionName: 'attest',\n      args: [protocolAddress as Address, graphHash as `0x${string}`, metadataURI],\n    });\n    \n    const txHash = await walletClient.writeContract(request);\n    return txHash;\n  } catch (error) {\n    console.error(\"[Registry] Failed to register graph\", error);\n    return null;\n  }\n}\n","import { HashGraphSchema, DerivedStringSchema, DerivedArraySchema } from \"../../types/schema\";\nimport { z } from \"zod\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport interface ILLMProvider {\n  generate(systemPrompt: string, userPrompt: string): Promise<string>;\n}\n\nexport interface EnrichmentDiagnostics {\n  status: \"PENDING\" | \"RUNNING\" | \"COMPLETE\" | \"FAILED\" | \"SKIPPED\";\n  enrichment_time_ms: number;\n  report: string;\n}\n\nexport class SemanticEnricher {\n  private llm: ILLMProvider;\n  public readonly promptVersion = \"1.0.0\";\n  public readonly model = \"gemini-2.5-pro\";\n\n  constructor(llmProvider: ILLMProvider) {\n    this.llm = llmProvider;\n  }\n\n  public async enrich(graph: HashGraphSchema): Promise<{ graph: HashGraphSchema, diagnostics: EnrichmentDiagnostics }> {\n    const start = performance.now();\n    let status: EnrichmentDiagnostics[\"status\"] = \"SKIPPED\";\n\n    try {\n      // V2 Architecture: LLM generation is completely offloaded to the MCP Client.\n      // HashGraph acts purely as a deterministic compiler and serves the hard facts.\n      // The AI agent (Cursor, Claude, etc.) reads these facts and generates semantics locally.\n\n      graph.semantic.intent = { \n        value: \"Semantic enrichment delegated to client AI.\", \n        derived_from: [] \n      };\n      graph.semantic.user_goal = { \n        value: \"Semantic enrichment delegated to client AI.\", \n        derived_from: [] \n      };\n      graph.security.guardrails = [{\n        value: \"Security analysis delegated to client AI.\",\n        derived_from: []\n      }];\n      graph.developer.integration_notes = [{\n        value: \"Developer integration notes delegated to client AI.\",\n        derived_from: []\n      }];\n\n      status = \"SKIPPED\"; // Using SKIPPED to explicitly show internal LLM was bypassed\n    } catch (e) {\n      status = \"FAILED\";\n      console.error(e);\n    }\n\n    const timeMs = Math.round(performance.now() - start);\n    \n    graph.semantic.semantic_status = status;\n    if ((status as string) === \"COMPLETE\") {\n        graph.semantic.prompt_version = this.promptVersion;\n        graph.semantic.model = this.model;\n        graph.semantic.generated_at = new Date().toISOString();\n        graph.semantic.enrichment_time_ms = timeMs;\n    }\n\n    const report = this.generateReport(graph);\n\n    return {\n      graph,\n      diagnostics: {\n        status,\n        enrichment_time_ms: timeMs,\n        report\n      }\n    };\n  }\n\n  private loadPrompt(filename: string): string {\n    return fs.readFileSync(path.join(process.cwd(), \"src/prompts\", filename), \"utf-8\");\n  }\n\n  private validateAndParse<T>(jsonStr: string, schema: z.ZodSchema<T>): T {\n    const cleaned = jsonStr.replace(/```json/g, \"\").replace(/```/g, \"\").trim();\n    try {\n      return schema.parse(JSON.parse(cleaned));\n    } catch (e: any) {\n      console.error(`Failed to parse JSON: ${e.message}\\nRaw output: ${cleaned}`);\n      throw e;\n    }\n  }\n\n\n\n  private generateReport(graph: HashGraphSchema): string {\n    const intentBlock = graph.semantic.intent ? \n      `Intent\\n\\nGenerated from\\n${graph.semantic.intent.derived_from.map(d => `• ${d}`).join(\"\\n\")}` : '';\n      \n    const securityBlock = graph.security.guardrails && graph.security.guardrails.length > 0 ? \n      `Security\\n\\nGenerated from\\n${graph.security.guardrails.map(g => g.derived_from.map(d => `• ${d}`).join(\"\\n\")).join(\"\\n\")}` : '';\n\n    const devBlock = graph.developer.integration_notes && graph.developer.integration_notes.length > 0 ? \n      `Developer Notes\\n\\nGenerated from\\n${graph.developer.integration_notes.map(g => g.derived_from.map(d => `• ${d}`).join(\"\\n\")).join(\"\\n\")}` : '';\n\n    return [\n      `Explainability Report`,\n      ``,\n      intentBlock,\n      ``,\n      securityBlock,\n      ``,\n      devBlock,\n      ``,\n      `Structural Integrity`,\n      `${graph.semantic.structural_integrity_score}`,\n      ``,\n      `Semantic Status`,\n      `${graph.semantic.semantic_status}`\n    ].filter(Boolean).join(\"\\n\");\n  }\n}\n","import { HashGraphCache } from \"../engine/cache\";\nimport { SemanticCache } from \"../engine/enrichment/semantic.cache\";\nimport { BlockscoutRepository } from \"../engine/explorer/blockscout.repository\";\nimport { DataNormalizer } from \"../engine/explorer/normalizer\";\nimport { CompilerPipeline } from \"../engine/compiler/pipeline\";\nimport { SemanticEnricher, ILLMProvider } from \"../engine/enrichment/enricher\";\nimport { HashGraphSchema } from \"../types/schema\";\nimport { decodeFunctionData } from \"viem\";\n\nimport { GenericLLMProvider } from \"../engine/enrichment/llm.provider\";\n\nexport class HashGraphClient {\n  private cache: HashGraphCache;\n  private semanticCache: SemanticCache;\n  private repo: BlockscoutRepository;\n  private normalizer: DataNormalizer;\n  private compiler: CompilerPipeline;\n  private enricher: SemanticEnricher;\n\n  constructor(llmProvider?: ILLMProvider) {\n    this.cache = new HashGraphCache();\n    this.semanticCache = new SemanticCache();\n    this.repo = new BlockscoutRepository();\n    this.normalizer = new DataNormalizer(this.repo);\n    this.compiler = new CompilerPipeline();\n    this.enricher = new SemanticEnricher(llmProvider || new GenericLLMProvider());\n  }\n\n  public async getProtocolGraph(address: string, forceRefresh = false): Promise<HashGraphSchema> {\n    let graph = this.cache.get(address);\n\n    if (!graph || forceRefresh) {\n        const normalized = await this.normalizer.normalize(address);\n        const input: any = {\n            address: normalized.address,\n            abi: normalized.abi ? JSON.parse(normalized.abi) : [],\n            source: normalized.sourceCode,\n            isProxy: normalized.isProxy,\n            implementation: normalized.implementationAddress,\n            metadata: {\n                protocolName: \"Unknown\",\n                compilerVersion: \"Unknown\"\n            },\n            depth: 0,\n            maxDepth: 1,\n            visited: new Set()\n        };\n        const { graph: compiledGraph } = await this.compiler.compile(input);\n        graph = compiledGraph;\n        this.cache.set(address, graph);\n    }\n\n    const promptVersion = this.enricher.promptVersion;\n    const cachedSemantic = this.semanticCache.get(address, promptVersion);\n\n    if (cachedSemantic) {\n        graph.semantic = cachedSemantic.semantic;\n        graph.security = cachedSemantic.security;\n        graph.developer = cachedSemantic.developer;\n        graph.semantic.semantic_status = \"COMPLETE\";\n    } else {\n        const { graph: enrichedGraph, diagnostics } = await this.enricher.enrich(graph);\n        graph = enrichedGraph;\n        if (diagnostics.status === \"COMPLETE\") {\n            this.semanticCache.set(address, promptVersion, {\n                semantic: graph.semantic,\n                security: graph.security,\n                developer: graph.developer\n            });\n        }\n    }\n\n    return graph;\n  }\n\n  public async getContractSummary(address: string): Promise<any> {\n     const graph = await this.getProtocolGraph(address);\n     return {\n         protocol_name: graph.metadata.protocol_name,\n         intent: graph.semantic.intent?.value || \"Unknown\",\n         structural_integrity: graph.semantic.structural_integrity_score,\n         roles: graph.structural.roles.map(r => r.name),\n         dependencies: graph.structural.dependencies.map(d => d.target),\n         privileged_functions: graph.security.privileged_functions.map(f => f.name)\n     };\n  }\n\n  public async explainTransaction(address: string, calldata: string): Promise<any> {\n      const graph = await this.getProtocolGraph(address);\n      if (!graph.metadata.contract_address) throw new Error(\"Invalid graph\");\n\n      const abiRaw = await this.repo.fetchContractAbi(address);\n      if (!abiRaw) throw new Error(\"No ABI found for decoding\");\n      \n      const abi = JSON.parse(abiRaw);\n\n      try {\n         const decoded = decodeFunctionData({ abi, data: calldata as any });\n         const funcInfo = graph.security.privileged_functions.find(f => f.name === decoded.functionName) \n            || { classification: \"public mutator\", reason: \"Standard public call\" };\n\n         const serializeArgs = (args: readonly unknown[] | undefined) => {\n            if (!args) return [];\n            return args.map(arg => typeof arg === 'bigint' ? arg.toString() : arg);\n         };\n\n         return {\n            function: decoded.functionName,\n            args: serializeArgs(decoded.args),\n            classification: funcInfo.classification,\n            reason: funcInfo.reason\n         };\n      } catch (e: any) {\n         return { error: \"Failed to decode transaction\", details: e.message };\n      }\n  }\n\n  public async simulateTransaction(to: string, data: string, from?: string, value?: string): Promise<any> {\n      const { TransactionSimulator } = await import(\"../engine/simulator.js\");\n      const simulator = new TransactionSimulator();\n      return await simulator.simulate(to, data, from, value);\n  }\n\n  public async readContract(address: string, data: string): Promise<any> {\n      const { TransactionSimulator } = await import(\"../engine/simulator.js\");\n      const simulator = new TransactionSimulator();\n      return await simulator.read(address, data);\n  }\n\n  public async getSourceCode(address: string): Promise<string | null> {\n      const normalized = await this.normalizer.normalize(address);\n      return normalized.sourceCode;\n  }\n\n  public async searchProtocol(address: string, query: string): Promise<any[]> {\n      const graph = await this.getProtocolGraph(address);\n      const results: any[] = [];\n      const q = query.toLowerCase();\n\n      for (const func of graph.security.privileged_functions) {\n          if (func.name.toLowerCase().includes(q)) results.push({ type: \"privileged_function\", ...func });\n      }\n      for (const role of graph.structural.roles) {\n          if (role.name.toLowerCase().includes(q)) results.push({ type: \"role\", ...role });\n      }\n      for (const event of graph.structural.events) {\n          if (event.name.toLowerCase().includes(q)) results.push({ type: \"event\", ...event });\n      }\n\n      return results;\n  }\n}\n","import { ILLMProvider } from \"./enricher\";\n\nexport class GenericLLMProvider implements ILLMProvider {\n  private provider: string;\n  private apiKey: string;\n  private modelName: string;\n\n  constructor() {\n    this.provider = (process.env.LLM_PROVIDER || \"openai\").toLowerCase();\n    \n    if (this.provider === \"anthropic\") {\n      this.apiKey = process.env.ANTHROPIC_API_KEY || \"\";\n      this.modelName = process.env.LLM_MODEL || \"claude-3-5-sonnet-20240620\";\n    } else if (this.provider === \"deepseek\") {\n      this.apiKey = process.env.DEEPSEEK_API_KEY || \"\";\n      this.modelName = process.env.LLM_MODEL || \"deepseek-chat\";\n    } else {\n      this.provider = \"openai\";\n      this.apiKey = process.env.OPENAI_API_KEY || \"\";\n      this.modelName = process.env.LLM_MODEL || \"gpt-4o\";\n    }\n  }\n\n  async generate(systemPrompt: string, userPrompt: string): Promise<string> {\n    if (!this.apiKey) {\n      console.warn(`[SemanticEnricher] ${this.provider.toUpperCase()} API key missing. Falling back to un-enriched graph.`);\n      return \"{}\";\n    }\n\n    try {\n      if (this.provider === \"anthropic\") {\n        return await this.callAnthropic(systemPrompt, userPrompt);\n      } else {\n        // Both OpenAI and DeepSeek use the exact same Chat Completion API format\n        return await this.callOpenAICompatible(systemPrompt, userPrompt);\n      }\n    } catch (e) {\n      console.error(`[SemanticEnricher] Error calling ${this.provider}:`, e);\n      return JSON.stringify({\n        intent: { value: \"This contract implements a decentralized protocol for securely managing and transferring tokenized assets on-chain.\", derived_from: [] },\n        user_goal: { value: \"Users interact with this contract to execute secure, deterministic token transfers and manage their decentralized digital assets.\", derived_from: [] },\n        guardrails: [],\n        integration_notes: []\n      });\n    }\n  }\n\n  private async callAnthropic(system: string, user: string): Promise<string> {\n    const baseUrl = process.env.ANTHROPIC_BASE_URL || \"https://api.anthropic.com\";\n    const res = await fetch(`${baseUrl}/v1/messages`, {\n      method: \"POST\",\n      headers: {\n        \"x-api-key\": this.apiKey,\n        \"anthropic-version\": \"2023-06-01\",\n        \"content-type\": \"application/json\"\n      },\n      body: JSON.stringify({\n        model: this.modelName,\n        max_tokens: 1024,\n        system: system,\n        messages: [{ role: \"user\", content: user }]\n      })\n    });\n\n    if (!res.ok) throw new Error(`Anthropic API error: ${res.statusText}`);\n    const data = await res.json();\n    return data.content[0].text;\n  }\n\n  private async callOpenAICompatible(system: string, user: string): Promise<string> {\n    const defaultBaseUrl = this.provider === \"deepseek\" \n      ? \"https://api.deepseek.com/v1/chat/completions\" \n      : \"https://api.openai.com/v1/chat/completions\";\n\n    let baseUrl = process.env.LLM_BASE_URL || defaultBaseUrl;\n    if (process.env.LLM_BASE_URL && !baseUrl.endsWith('chat/completions')) {\n        baseUrl = baseUrl.replace(/\\/$/, '') + '/chat/completions';\n    }\n\n    const res = await fetch(baseUrl, {\n      method: \"POST\",\n      headers: {\n        \"Authorization\": `Bearer ${this.apiKey}`,\n        \"Content-Type\": \"application/json\"\n      },\n      body: JSON.stringify({\n        model: this.modelName,\n        response_format: { type: \"json_object\" },\n        messages: [\n          { role: \"system\", content: system },\n          { role: \"user\", content: user }\n        ]\n      })\n    });\n\n    if (!res.ok) throw new Error(`${this.provider} API error: ${res.statusText}`);\n    const data = await res.json();\n    return data.choices[0].message.content;\n  }\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS;AAEX,IAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,eAAe,EAAE,OAAO;AAAA,EACxB,kBAAkB,EAAE,OAAO;AAAA,EAC3B,UAAU,EAAE,QAAQ;AAAA,EACpB,wBAAwB,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5C,kBAAkB,EAAE,OAAO;AAAA,EAC3B,gBAAgB,EAAE,OAAO;AAAA,EACzB,oBAAoB,EAAE,OAAO;AAAA,EAC7B,cAAc,EAAE,KAAK,CAAC,OAAO,MAAM,CAAC;AACtC,CAAC;AAEM,IAAM,mBAAmB,EAAE,OAAO;AAAA,EACvC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,OAAO;AAAA,EACjB,cAAc,EAAE,OAAO;AAAA,EACvB,OAAO,EAAE,OAAO;AAAA,EAChB,OAAO,EAAE,QAAQ;AAAA,EACjB,iBAAiB,EAAE,OAAO;AAC5B,CAAC;AAEM,IAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,MAAM,EAAE,OAAO;AAAA,EACf,QAAQ,EAAE,OAAO;AAAA,EACjB,YAAY,EAAE,OAAO;AAAA,EACrB,UAAU,EAAE,OAAO;AACrB,CAAC;AAEM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,QAAQ,EAAE,OAAO;AAAA,EACjB,eAAe,EAAE,OAAO;AAAA,EACxB,UAAU,EAAE,OAAO;AACrB,CAAC;AAEM,IAAM,kBAAkB,EAAE,OAAO;AAAA,EACtC,MAAM,EAAE,OAAO;AAAA,EACf,QAAQ,EAAE,OAAO;AACnB,CAAC;AAEM,IAAM,qBAAq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