{"version":3,"sources":["../src/core/crypto.ts","../node_modules/abitype/src/version.ts","../node_modules/abitype/src/errors.ts","../node_modules/abitype/src/regex.ts","../node_modules/abitype/src/human-readable/formatAbiParameter.ts","../node_modules/abitype/src/human-readable/formatAbiParameters.ts","../node_modules/abitype/src/human-readable/formatAbiItem.ts","../node_modules/abitype/src/human-readable/runtime/signatures.ts","../node_modules/abitype/src/human-readable/errors/abiItem.ts","../node_modules/abitype/src/human-readable/errors/abiParameter.ts","../node_modules/abitype/src/human-readable/errors/signature.ts","../node_modules/abitype/src/human-readable/errors/struct.ts","../node_modules/abitype/src/human-readable/errors/splitParameters.ts","../node_modules/abitype/src/human-readable/runtime/cache.ts","../node_modules/abitype/src/human-readable/runtime/utils.ts","../node_modules/abitype/src/human-readable/runtime/structs.ts","../node_modules/abitype/src/human-readable/parseAbiItem.ts","../node_modules/abitype/src/exports/index.ts","../node_modules/viem/utils/abi/formatAbiItem.ts","../node_modules/viem/utils/data/isHex.ts","../node_modules/viem/utils/data/size.ts","../node_modules/viem/errors/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/data.ts","../node_modules/viem/utils/data/pad.ts","../node_modules/viem/errors/encoding.ts","../node_modules/viem/utils/data/trim.ts","../node_modules/viem/utils/encoding/fromHex.ts","../node_modules/viem/utils/encoding/toHex.ts","../node_modules/viem/utils/encoding/toBytes.ts","../node_modules/viem/utils/hash/keccak256.ts","../node_modules/viem/utils/hash/hashSignature.ts","../node_modules/viem/utils/hash/normalizeSignature.ts","../node_modules/viem/utils/hash/toSignature.ts","../node_modules/viem/utils/hash/toSignatureHash.ts","../node_modules/viem/utils/hash/toEventSelector.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/encoding/fromBytes.ts","../node_modules/viem/utils/abi/decodeAbiParameters.ts","../src/core/types.ts","../src/core/index.ts","../node_modules/viem/index.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/utils/hash/toEventHash.ts","../src/events/events.ts","../src/agent/agent-runner.ts","../src/registry/ipfs-fetcher.ts","../src/agent-loop/tool-builder.ts","../src/agent-loop/executor.ts","../src/agent-loop/context-compactor.ts","../src/agent-loop/fact-extractor.ts","../src/agent-loop/trace-emitter.ts","../src/agent-loop/loop.ts","../src/agent-loop/platform-tools/definitions.ts","../src/agent-loop/platform-tools/executor.ts","../src/agent-loop/a2a-daemon.ts","../src/llm/openai-provider.ts","../src/llm/gateway-provider.ts","../src/llm/factory.ts","../src/subscription/subscription.ts","../src/registry/agent-registry.ts","../src/registry/index.ts","../src/subscription/agent-x402.ts","../src/subscription/index.ts","../src/payment/payments.ts","../src/payment/tenant-plan.ts","../src/payment/index.ts","../src/payment/a2a-client.ts","../src/payment/period-client.ts","../src/payment/billing.ts","../src/payment/agent-wallet.ts","../src/a2a/a2a.ts","../src/a2a/index.ts","../src/mcp/connector.ts","../src/mcp/index.ts","../src/reputation/reputation.ts","../src/reputation/index.ts","../src/config/config.ts","../src/config/index.ts","../src/endpoint/multi-endpoint.ts","../src/configuration/configuration.ts","../src/ipfs/ipfs-uploader.ts","../src/traces/types.ts","../src/skills/browser.ts","../src/conversation/client.ts","../src/central/central-client.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// @agentx/sdk — Crypto Engine\n// ---------------------------------------------------------------------------\n// AES-256-GCM for content encryption (NIST standard wire format).\n// ECIES (secp256k1) for key wrapping.\n//\n// Wire format (AES-256-GCM):\n//   base64( IV[12] || ciphertext || authTag[16] )\n//\n// ECIES wire format (compatible with eciesjs):\n//   hex( ephemeralPub[33] || IV[16] || ciphertext || MAC[32] )\n//\n// Pure JS — works in browser, Node, edge. No native deps except @noble/*.\n// ---------------------------------------------------------------------------\n\nimport { gcm } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { hkdf } from '@noble/hashes/hkdf.js'\nimport { hmac } from '@noble/hashes/hmac.js'\nimport { bytesToHex, hexToBytes } from '@noble/ciphers/utils.js'\n\n// ── randomBytes implementation (cross-runtime: browser / Node) ────────────\n\nexport function randomBytes(length: number): Uint8Array {\n  // browser: crypto.getRandomValues\n  if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n    const buf = new Uint8Array(length)\n    crypto.getRandomValues(buf)\n    return buf\n  }\n  // Node: crypto.randomBytes\n  // eslint-disable-next-line @typescript-eslint/no-require-imports\n  const nodeCrypto = require('crypto')\n  return new Uint8Array(nodeCrypto.randomBytes(length))\n}\n\nimport type { EncryptedPayload, AgentPrivatePayload } from './types'\nimport type { PackResult } from './types'\n\n// ── Re-exports for convenience ─────────────────────────────────────────────\n\nexport { bytesToHex, hexToBytes }\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\nconst AES_KEY_SIZE = 32\nconst IV_SIZE = 12 // GCM recommended\nconst TAG_SIZE = 16 // GCM auth tag\n\n// ── Base64 helpers (cross-runtime) ─────────────────────────────────────────\n\nfunction toBase64(bytes: Uint8Array): string {\n  // Works in browser (btoa + binary) and Node (Buffer)\n  if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')\n  let binary = ''\n  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!)\n  return btoa(binary)\n}\n\nfunction fromBase64(b64: string): Uint8Array {\n  if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'))\n  const binary = atob(b64)\n  const bytes = new Uint8Array(binary.length)\n  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n  return bytes\n}\n\n// ── AES-256-GCM ────────────────────────────────────────────────────────────\n\n/**\n * Encrypt with AES-256-GCM.\n * Wire format: base64( IV[12] || ciphertext || authTag[16] )\n */\nexport function aesEncrypt(plaintext: string, keyHex: string): string {\n  const key = hexToBytes(keyHex)\n  const iv = randomBytes(IV_SIZE)\n  const plainBytes = new TextEncoder().encode(plaintext)\n\n  const cipher = gcm(key, iv)\n  const encrypted = cipher.encrypt(plainBytes)\n  // noble gcm.encrypt returns: ciphertext || authTag(16)\n  const ciphertext = encrypted.subarray(0, -TAG_SIZE)\n  const authTag = encrypted.subarray(-TAG_SIZE)\n\n  // Pack: IV || ciphertext || authTag\n  const combined = new Uint8Array(IV_SIZE + ciphertext.length + TAG_SIZE)\n  combined.set(iv, 0)\n  combined.set(ciphertext, IV_SIZE)\n  combined.set(authTag, IV_SIZE + ciphertext.length)\n\n  return toBase64(combined)\n}\n\n/**\n * Decrypt AES-256-GCM.\n */\nexport function aesDecrypt(encryptedBase64: string, keyHex: string): string {\n  const key = hexToBytes(keyHex)\n  const combined = fromBase64(encryptedBase64)\n\n  const iv = combined.subarray(0, IV_SIZE)\n  const ciphertext = combined.subarray(IV_SIZE, -TAG_SIZE)\n  const authTag = combined.subarray(-TAG_SIZE)\n\n  const cipher = gcm(key, iv)\n  // noble decrypt expects: ciphertext || authTag\n  const ciphertextWithTag = new Uint8Array(ciphertext.length + TAG_SIZE)\n  ciphertextWithTag.set(ciphertext, 0)\n  ciphertextWithTag.set(authTag, ciphertext.length)\n\n  const decrypted = cipher.decrypt(ciphertextWithTag)\n  return new TextDecoder().decode(decrypted)\n}\n\n/**\n * Encrypt with AES-256-GCM — master-key wire format.\n * Layout: base64( IV[12] || authTag[16] || ciphertext ).\n * Kept byte-for-byte compatible with the Gateway's legacy at-rest key\n * encryption (`gateway/src/lib/crypto.ts`) so existing stored rows decrypt\n * unchanged. New code should prefer `aesEncrypt`/`aesDecrypt` unless data\n * written in this layout must be read.\n */\nexport function encryptWithKey(plaintext: string, keyHex: string): string {\n  const key = hexToBytes(keyHex)\n  const iv = randomBytes(IV_SIZE)\n  const plainBytes = new TextEncoder().encode(plaintext)\n\n  const cipher = gcm(key, iv)\n  const encrypted = cipher.encrypt(plainBytes)\n  const ciphertext = encrypted.subarray(0, -TAG_SIZE)\n  const authTag = encrypted.subarray(-TAG_SIZE)\n\n  const combined = new Uint8Array(IV_SIZE + TAG_SIZE + ciphertext.length)\n  combined.set(iv, 0)\n  combined.set(authTag, IV_SIZE)\n  combined.set(ciphertext, IV_SIZE + TAG_SIZE)\n\n  return toBase64(combined)\n}\n\n/**\n * Decrypt AES-256-GCM — master-key wire format\n * (base64( IV[12] || authTag[16] || ciphertext )).\n */\nexport function decryptWithKey(encryptedBase64: string, keyHex: string): string {\n  const key = hexToBytes(keyHex)\n  const combined = fromBase64(encryptedBase64)\n\n  const iv = combined.subarray(0, IV_SIZE)\n  const authTag = combined.subarray(IV_SIZE, IV_SIZE + TAG_SIZE)\n  const ciphertext = combined.subarray(IV_SIZE + TAG_SIZE)\n\n  const cipher = gcm(key, iv)\n  const ciphertextWithTag = new Uint8Array(ciphertext.length + TAG_SIZE)\n  ciphertextWithTag.set(ciphertext, 0)\n  ciphertextWithTag.set(authTag, ciphertext.length)\n\n  const decrypted = cipher.decrypt(ciphertextWithTag)\n  return new TextDecoder().decode(decrypted)\n}\n\n/**\n * Generate a cryptographically random AES-256 key (hex, 64 chars).\n */\nexport function generateAesKey(): string {\n  return bytesToHex(randomBytes(AES_KEY_SIZE))\n}\n\n// ── ECIES (secp256k1) ──────────────────────────────────────────────────────\n//\n// eciesjs-compatible wire format:\n//   ephemeralPub(33B compressed) || IV(16B) || ciphertext || MAC(32B)\n//   Encoding: hex\n//\n// HKDF(SHA-256) derives AES key + HMAC key from ECDH shared secret.\n// ---------------------------------------------------------------------------\n\nfunction eciesEncode(\n  ephemeralPub: Uint8Array,\n  iv: Uint8Array,\n  ciphertext: Uint8Array,\n  mac: Uint8Array\n): string {\n  const out = new Uint8Array(33 + 16 + ciphertext.length + 32)\n  out.set(ephemeralPub, 0)\n  out.set(iv, 33)\n  out.set(ciphertext, 33 + 16)\n  out.set(mac, 33 + 16 + ciphertext.length)\n  return bytesToHex(out)\n}\n\nfunction eciesDecode(dataHex: string): {\n  ephemeralPub: Uint8Array\n  iv: Uint8Array\n  ciphertext: Uint8Array\n  mac: Uint8Array\n} {\n  const d = hexToBytes(dataHex)\n  return {\n    ephemeralPub: d.subarray(0, 33),\n    iv: d.subarray(33, 49),\n    ciphertext: d.subarray(49, -32),\n    mac: d.subarray(-32),\n  }\n}\n\n// Simple AES-256-CTR implementation on top of @noble/ciphers AES core\nfunction aesCtrEncrypt(key: Uint8Array, ctrBytes: Uint8Array, data: Uint8Array): Uint8Array {\n  const blockSize = 16\n  const cipher = gcm(key, ctrBytes) // GCM internally handles CTR\n  // Use noble's CTR approach: encrypt the plaintext directly with the derived stream\n  // noble uses AES-CTR internally for GCM; simpler: implement CTR with AES-ECB\n  const result = new Uint8Array(data.length)\n  const counter = new Uint8Array(blockSize)\n  counter.set(ctrBytes)\n  for (let i = 0; i < data.length; i += blockSize) {\n    const keystream = gcm(key, counter).encrypt(new Uint8Array(blockSize))\n    for (let j = 0; j < blockSize && i + j < data.length; j++) {\n      result[i + j] = keystream[j]! ^ data[i + j]!\n    }\n    // Increment counter (big-endian)\n    for (let j = blockSize - 1; j >= 0; j--) {\n      const val = counter[j]\n      if (val !== undefined) {\n        counter[j] = (val + 1) & 0xff\n        if (counter[j] !== 0) break\n      }\n    }\n  }\n  return result\n}\n\n/**\n * Encrypt data with recipient's secp256k1 public key (ECIES).\n *\n * @param dataHex    The data to encrypt (hex, e.g. AES key)\n * @param publicKey  Recipient's public key (hex, 04-prefixed uncompressed or 02/03 compressed)\n */\nexport function eciesEncrypt(dataHex: string, publicKey: string): string {\n  // 1. Ephemeral keypair\n  const ephPriv = randomBytes(32)\n  const ephPub = secp256k1.getPublicKey(ephPriv, true) // 33B compressed\n\n  // 2. Parse recipient public key\n  let recipientPub: Uint8Array\n  if (publicKey.startsWith('04') && publicKey.length === 130) {\n    recipientPub = hexToBytes(publicKey)\n  } else if (publicKey.startsWith('02') || publicKey.startsWith('03')) {\n    recipientPub = hexToBytes(publicKey)\n  } else {\n    throw new Error('Invalid public key format: expected hex with 02/03/04 prefix')\n  }\n\n  // 3. ECDH\n  const shared = secp256k1.getSharedSecret(ephPriv, recipientPub)\n  const sharedX = shared.subarray(1, 33) // x-coordinate only\n  const sharedKey = sha256(sharedX)\n\n  // 4. HKDF: encKey(32) || macKey(32)\n  const hkdfOut = hkdf(sha256, sharedKey, undefined, undefined, 64)\n  const encKey = hkdfOut.subarray(0, 32)\n  const macKey = hkdfOut.subarray(32, 64)\n\n  // 5. AES-256-CTR encrypt\n  const iv = randomBytes(16)\n  const plaintext = hexToBytes(dataHex)\n  const ciphertext = aesCtrEncrypt(encKey, iv, plaintext)\n\n  // 6. HMAC: MAC(ephemeralPub || IV || ciphertext)\n  const macInput = new Uint8Array(33 + 16 + ciphertext.length)\n  macInput.set(ephPub, 0)\n  macInput.set(iv, 33)\n  macInput.set(ciphertext, 33 + 16)\n  const mac = hmac(sha256, macKey, macInput)\n\n  return eciesEncode(ephPub, iv, ciphertext, mac)\n}\n\n/**\n * Decrypt ECIES ciphertext with recipient's secp256k1 private key.\n */\nexport function eciesDecrypt(dataHex: string, privateKey: string): string {\n  const { ephemeralPub, iv, ciphertext, mac } = eciesDecode(dataHex)\n\n  // 1. ECDH\n  const privBytes = hexToBytes(privateKey)\n  const shared = secp256k1.getSharedSecret(privBytes, ephemeralPub)\n  const sharedX = shared.subarray(1, 33)\n  const sharedKey = sha256(sharedX)\n\n  // 2. HKDF\n  const hkdfOut = hkdf(sha256, sharedKey, undefined, undefined, 64)\n  const encKey = hkdfOut.subarray(0, 32)\n  const macKey = hkdfOut.subarray(32, 64)\n\n  // 3. Verify MAC\n  const macInput = new Uint8Array(33 + 16 + ciphertext.length)\n  macInput.set(ephemeralPub, 0)\n  macInput.set(iv, 33)\n  macInput.set(ciphertext, 33 + 16)\n  const expectedMac = hmac(sha256, macKey, macInput)\n  if (!constantTimeEqual(mac, expectedMac)) {\n    throw new Error('ECIES decryption failed: MAC mismatch')\n  }\n\n  // 4. Decrypt\n  const plaintext = aesCtrEncrypt(encKey, iv, ciphertext) // CTR encrypt = decrypt\n  return bytesToHex(plaintext)\n}\n\nfunction constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false\n  let diff = 0\n  for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!\n  return diff === 0\n}\n\n// ── High-Level: Agent Pack / Unpack ────────────────────────────────────────\n\n/**\n * Encrypt an Agent's private payload with AES-256-GCM.\n */\nexport function encryptPayload(\n  payload: AgentPrivatePayload,\n  keyHex?: string\n): EncryptedPayload {\n  const key = keyHex ?? generateAesKey()\n  return {\n    encrypted: true,\n    algorithm: 'AES-256-GCM',\n    data: aesEncrypt(JSON.stringify(payload), key),\n  }\n}\n\n/**\n * Decrypt an EncryptedPayload.\n */\nexport function decryptPayload(\n  encrypted: EncryptedPayload,\n  keyHex: string\n): AgentPrivatePayload {\n  if (encrypted.algorithm !== 'AES-256-GCM') {\n    throw new Error(`Unsupported algorithm: ${encrypted.algorithm}`)\n  }\n  return JSON.parse(aesDecrypt(encrypted.data, keyHex)) as AgentPrivatePayload\n}\n\n/**\n * Pack an AgentPayload for publishing.\n *   1. Split public/private\n *   2. AES-256-GCM encrypt private part\n *   3. ECIES wrap AES key with creator's public key\n */\nexport function packAgentForPublish(\n  agent: import('./types').AgentPayload,\n  publicKey: string,\n  aesKeyHex?: string\n): PackResult {\n  const key = aesKeyHex ?? generateAesKey()\n\n  const eciesEncryptedKeyHex = eciesEncrypt(key, publicKey)\n\n  return {\n    encryptedCid: '', // filled after IPFS upload\n    publicCid: '',    // filled after IPFS upload\n    aesKeyHex: key,\n    eciesEncryptedKeyHex,\n  }\n}\n\n// ── Integrated Publish Pipeline ────────────────────────────────────────────\n\nimport type { IPFSUploader, IPFSUploadResult } from '../ipfs/ipfs-uploader'\n\nexport interface PublishAgentConfig {\n  /** Agent payload to publish */\n  agent: import('./types').AgentPayload\n  /** Creator's secp256k1 public key (hex) */\n  publicKey: string\n  /** IPFS uploader instance with Pinata JWT configured */\n  uploader: IPFSUploader\n  /** Optional AES key (auto-generated if not provided) */\n  aesKeyHex?: string\n  /** Agent name for IPFS metadata */\n  agentName?: string\n}\n\nexport interface PublishAgentResult {\n  /** AES encryption key (hex) */\n  aesKeyHex: string\n  /** ECIES-encrypted AES key for on-chain storage */\n  eciesEncryptedKeyHex: string\n  /** CID of the encrypted private payload on IPFS */\n  encryptedCid: string\n  /** Public IPFS gateway URL to the encrypted payload */\n  encryptedUrl: string\n  /** CID of the public metadata on IPFS */\n  publicCid: string\n  /** Public IPFS gateway URL to the public metadata */\n  publicUrl: string\n  /** Full PackResult (compatible with existing code) */\n  pack: PackResult\n  /** Raw IPFS upload results */\n  uploads: { encrypted: IPFSUploadResult; public: IPFSUploadResult }\n}\n\n/**\n * Full publish pipeline: encrypt + upload to IPFS.\n *\n * Usage:\n *   const uploader = new IPFSUploader({ pinataJwt: '...' })\n *   const result = await publishAgent({ agent, publicKey, uploader })\n *   // result.encryptedCid → IPFS CID to mint as on-chain tokenURI\n */\nexport async function publishAgent(config: PublishAgentConfig): Promise<PublishAgentResult> {\n  const { agent, publicKey, uploader, aesKeyHex, agentName } = config\n\n  if (!uploader.isConfigured()) {\n    throw new Error('IPFSUploader is not configured — set pinataJwt or customEndpoint')\n  }\n\n  const key = aesKeyHex ?? generateAesKey()\n  const eciesEncryptedKeyHex = eciesEncrypt(key, publicKey)\n\n  // Split into private (encrypted) and public payloads\n  const privatePayload: import('./types').AgentPrivatePayload = {\n    prompt: agent.prompt,\n    skills: agent.skills,\n    mcp: agent.mcp,\n  }\n  const encryptedPayload = encryptPayload(privatePayload, key)\n\n  // Upload both parts to IPFS in parallel\n  const [encrypted, publicMeta] = await Promise.all([\n    uploader.uploadEncryptedPayload(encryptedPayload, agentName),\n    uploader.uploadJSON({\n      name: agent.name,\n      description: agent.description,\n      version: agent.version,\n      tags: agent.tags,\n      capabilities: agent.capabilities,\n      category: agent.category,\n      eciesKey: eciesEncryptedKeyHex,\n    }),\n  ])\n\n  const pack: PackResult = {\n    encryptedCid: encrypted.cid,\n    publicCid: publicMeta.cid,\n    aesKeyHex: key,\n    eciesEncryptedKeyHex,\n  }\n\n  return {\n    aesKeyHex: key,\n    eciesEncryptedKeyHex,\n    encryptedCid: encrypted.cid,\n    encryptedUrl: encrypted.url,\n    publicCid: publicMeta.cid,\n    publicUrl: publicMeta.url,\n    pack,\n    uploads: { encrypted, public: publicMeta },\n  }\n}\n\n/**\n * Unpack an Agent:\n *   1. ECIES decrypt the AES key (private key)\n *   2. AES-256-GCM decrypt the payload\n */\nexport function unpackAgent(\n  encryptedPayload: EncryptedPayload,\n  eciesEncryptedKey: string,\n  privateKey: string\n): AgentPrivatePayload {\n  const aesKeyHex = eciesDecrypt(eciesEncryptedKey, privateKey)\n  return decryptPayload(encryptedPayload, aesKeyHex)\n}\n\n// ── Key Pair Utilities ─────────────────────────────────────────────────────\n\n/**\n * Generate a secp256k1 keypair compatible with Ethereum wallets.\n */\nexport function generateKeyPair(): { privateKey: string; publicKey: string } {\n  const priv = randomBytes(32)\n  const pub = secp256k1.getPublicKey(priv, false) // uncompressed 04-prefixed\n  return { privateKey: bytesToHex(priv), publicKey: bytesToHex(pub) }\n}\n\n/**\n * Derive public key from private key (hex).\n */\nexport function getPublicKey(privateKey: string): string {\n  return bytesToHex(secp256k1.getPublicKey(hexToBytes(privateKey), false))\n}\n","export const version = '1.2.3'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n  {\n    docsPath?: string | undefined\n    metaMessages?: string[] | undefined\n  } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n  details: string\n  docsPath?: string | undefined\n  metaMessages?: string[] | undefined\n  shortMessage: string\n\n  override name = 'AbiTypeError'\n\n  constructor(shortMessage: string, args: BaseErrorArgs = {}) {\n    const details =\n      args.cause instanceof BaseError\n        ? args.cause.details\n        : args.cause?.message\n          ? args.cause.message\n          : args.details!\n    const docsPath =\n      args.cause instanceof BaseError\n        ? args.cause.docsPath || args.docsPath\n        : args.docsPath\n    const message = [\n      shortMessage || 'An error occurred.',\n      '',\n      ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n      ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n      ...(details ? [`Details: ${details}`] : []),\n      `Version: abitype@${version}`,\n    ].join('\\n')\n\n    super(message)\n\n    if (args.cause) this.cause = args.cause\n    this.details = details\n    this.docsPath = docsPath\n    this.metaMessages = args.metaMessages\n    this.shortMessage = shortMessage\n  }\n}\n","// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.\n// https://twitter.com/GabrielVergnaud/status/1622906834343366657\nexport function execTyped<type>(regex: RegExp, string: string) {\n  const match = regex.exec(string)\n  return match?.groups as type | undefined\n}\n\n// `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n// https://regexr.com/6va55\nexport const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/\n\n// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex =\n  /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/\n\nexport const isTupleRegex = /^\\(.+?\\).*?$/\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport { execTyped } from '../regex.js'\nimport type { IsNarrowable, Join } from '../types.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param abiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * type Result = FormatAbiParameter<{ type: 'address'; name: 'from'; }>\n * //   ^? type Result = 'address from'\n */\nexport type FormatAbiParameter<\n  abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter extends {\n  name?: infer name extends string\n  type: `tuple${infer array}`\n  components: infer components extends readonly AbiParameter[]\n  indexed?: infer indexed extends boolean\n}\n  ? FormatAbiParameter<\n      {\n        type: `(${Join<\n          {\n            [key in keyof components]: FormatAbiParameter<\n              {\n                type: components[key]['type']\n              } & (IsNarrowable<components[key]['name'], string> extends true\n                ? { name: components[key]['name'] }\n                : unknown) &\n                (components[key] extends { components: readonly AbiParameter[] }\n                  ? { components: components[key]['components'] }\n                  : unknown)\n            >\n          },\n          ', '\n        >})${array}`\n      } & (IsNarrowable<name, string> extends true ? { name: name } : unknown) &\n        (IsNarrowable<indexed, boolean> extends true\n          ? { indexed: indexed }\n          : unknown)\n    >\n  : `${abiParameter['type']}${abiParameter extends { indexed: true }\n      ? ' indexed'\n      : ''}${abiParameter['name'] extends infer name extends string\n      ? name extends ''\n        ? ''\n        : ` ${AssertName<name>}`\n      : ''}`\n\n// https://regexr.com/7f7rv\nconst tupleRegex = /^tuple(?<array>(\\[(\\d*)\\])*)$/\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param abiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * const result = formatAbiParameter({ type: 'address', name: 'from' })\n * //    ^? const result: 'address from'\n */\nexport function formatAbiParameter<\n  const abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): FormatAbiParameter<abiParameter> {\n  type Result = FormatAbiParameter<abiParameter>\n\n  let type = abiParameter.type\n  if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {\n    type = '('\n    const length = abiParameter.components.length as number\n    for (let i = 0; i < length; i++) {\n      const component = abiParameter.components[i]!\n      type += formatAbiParameter(component)\n      if (i < length - 1) type += ', '\n    }\n    const result = execTyped<{ array?: string }>(tupleRegex, abiParameter.type)\n    type += `)${result?.array || ''}`\n    return formatAbiParameter({\n      ...abiParameter,\n      type,\n    }) as Result\n  }\n  // Add `indexed` to type if in `abiParameter`\n  if ('indexed' in abiParameter && abiParameter.indexed)\n    type = `${type} indexed`\n  // Return human-readable ABI parameter\n  if (abiParameter.name) return `${type} ${abiParameter.name}` as Result\n  return type as Result\n}\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport type { Join } from '../types.js'\nimport {\n  type FormatAbiParameter,\n  formatAbiParameter,\n} from './formatAbiParameter.js'\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameter.\n *\n * @param abiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * type Result = FormatAbiParameters<[\n *   // ^? type Result = 'address from, uint256 tokenId'\n *   { type: 'address'; name: 'from'; },\n *   { type: 'uint256'; name: 'tokenId'; },\n * ]>\n */\nexport type FormatAbiParameters<\n  abiParameters extends readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ],\n> = Join<\n  {\n    [key in keyof abiParameters]: FormatAbiParameter<abiParameters[key]>\n  },\n  ', '\n>\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameters.\n *\n * @param abiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * const result = formatAbiParameters([\n *   //  ^? const result: 'address from, uint256 tokenId'\n *   { type: 'address', name: 'from' },\n *   { type: 'uint256', name: 'tokenId' },\n * ])\n */\nexport function formatAbiParameters<\n  const abiParameters extends readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ],\n>(abiParameters: abiParameters): FormatAbiParameters<abiParameters> {\n  let params = ''\n  const length = abiParameters.length\n  for (let i = 0; i < length; i++) {\n    const abiParameter = abiParameters[i]!\n    params += formatAbiParameter(abiParameter)\n    if (i !== length - 1) params += ', '\n  }\n  return params as FormatAbiParameters<abiParameters>\n}\n","import type {\n  Abi,\n  AbiConstructor,\n  AbiError,\n  AbiEvent,\n  AbiEventParameter,\n  AbiFallback,\n  AbiFunction,\n  AbiParameter,\n  AbiReceive,\n  AbiStateMutability,\n} from '../abi.js'\nimport {\n  type FormatAbiParameters as FormatAbiParameters_,\n  formatAbiParameters,\n} from './formatAbiParameters.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem<abiItem extends Abi[number]> =\n  Abi[number] extends abiItem\n    ? string\n    :\n        | (abiItem extends AbiFunction\n            ? AbiFunction extends abiItem\n              ? string\n              : `function ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n                  abiItem['inputs']\n                >})${abiItem['stateMutability'] extends Exclude<\n                  AbiStateMutability,\n                  'nonpayable'\n                >\n                  ? ` ${abiItem['stateMutability']}`\n                  : ''}${abiItem['outputs']['length'] extends 0\n                  ? ''\n                  : ` returns (${FormatAbiParameters<abiItem['outputs']>})`}`\n            : never)\n        | (abiItem extends AbiEvent\n            ? AbiEvent extends abiItem\n              ? string\n              : `event ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n                  abiItem['inputs']\n                >})`\n            : never)\n        | (abiItem extends AbiError\n            ? AbiError extends abiItem\n              ? string\n              : `error ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n                  abiItem['inputs']\n                >})`\n            : never)\n        | (abiItem extends AbiConstructor\n            ? AbiConstructor extends abiItem\n              ? string\n              : `constructor(${FormatAbiParameters<\n                  abiItem['inputs']\n                >})${abiItem['stateMutability'] extends 'payable'\n                  ? ' payable'\n                  : ''}`\n            : never)\n        | (abiItem extends AbiFallback\n            ? AbiFallback extends abiItem\n              ? string\n              : `fallback() external${abiItem['stateMutability'] extends 'payable'\n                  ? ' payable'\n                  : ''}`\n            : never)\n        | (abiItem extends AbiReceive\n            ? AbiReceive extends abiItem\n              ? string\n              : 'receive() external payable'\n            : never)\n\ntype FormatAbiParameters<\n  abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n  ? ''\n  : FormatAbiParameters_<\n      abiParameters extends readonly [\n        AbiParameter | AbiEventParameter,\n        ...(readonly (AbiParameter | AbiEventParameter)[]),\n      ]\n        ? abiParameters\n        : never\n    >\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport function formatAbiItem<const abiItem extends Abi[number]>(\n  abiItem: abiItem,\n): FormatAbiItem<abiItem> {\n  type Result = FormatAbiItem<abiItem>\n  type Params = readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ]\n\n  if (abiItem.type === 'function')\n    return `function ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})${\n      abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'\n        ? ` ${abiItem.stateMutability}`\n        : ''\n    }${\n      abiItem.outputs?.length\n        ? ` returns (${formatAbiParameters(abiItem.outputs as Params)})`\n        : ''\n    }`\n  if (abiItem.type === 'event')\n    return `event ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})`\n  if (abiItem.type === 'error')\n    return `error ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})`\n  if (abiItem.type === 'constructor')\n    return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n      abiItem.stateMutability === 'payable' ? ' payable' : ''\n    }`\n  if (abiItem.type === 'fallback')\n    return `fallback() external${\n      abiItem.stateMutability === 'payable' ? ' payable' : ''\n    }` as Result\n  return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n  EventModifier,\n  FunctionModifier,\n  Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n  /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n  return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n  return execTyped<{ name: string; parameters: string }>(\n    errorSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n  /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/\nexport function isEventSignature(signature: string) {\n  return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n  return execTyped<{ name: string; parameters: string }>(\n    eventSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n  /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?<returns>.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n  return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n  return execTyped<{\n    name: string\n    parameters: string\n    stateMutability?: AbiStateMutability\n    returns?: string\n  }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n  /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?<properties>.*?)\\}$/\nexport function isStructSignature(signature: string) {\n  return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n  return execTyped<{ name: string; properties: string }>(\n    structSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n  /^constructor\\((?<parameters>.*?)\\)(?:\\s(?<stateMutability>payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n  return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n  return execTyped<{\n    parameters: string\n    stateMutability?: Extract<AbiStateMutability, 'payable'>\n  }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex =\n  /^fallback\\(\\) external(?:\\s(?<stateMutability>payable{1}))?$/\nexport function isFallbackSignature(signature: string) {\n  return fallbackSignatureRegex.test(signature)\n}\nexport function execFallbackSignature(signature: string) {\n  return execTyped<{\n    parameters: string\n    stateMutability?: Extract<AbiStateMutability, 'payable'>\n  }>(fallbackSignatureRegex, signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n  return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set<Modifier>([\n  'memory',\n  'indexed',\n  'storage',\n  'calldata',\n])\nexport const eventModifiers = new Set<EventModifier>(['indexed'])\nexport const functionModifiers = new Set<FunctionModifier>([\n  'calldata',\n  'memory',\n  'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n  override name = 'InvalidAbiItemError'\n\n  constructor({ signature }: { signature: string | object }) {\n    super('Failed to parse ABI item.', {\n      details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n      docsPath: '/api/human#parseabiitem-1',\n    })\n  }\n}\n\nexport class UnknownTypeError extends BaseError {\n  override name = 'UnknownTypeError'\n\n  constructor({ type }: { type: string }) {\n    super('Unknown type.', {\n      metaMessages: [\n        `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n      ],\n    })\n  }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n  override name = 'UnknownSolidityTypeError'\n\n  constructor({ type }: { type: string }) {\n    super('Unknown type.', {\n      metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n    })\n  }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n  override name = 'InvalidAbiParameterError'\n\n  constructor({ param }: { param: string | object }) {\n    super('Failed to parse ABI parameter.', {\n      details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n      docsPath: '/api/human#parseabiparameter-1',\n    })\n  }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n  override name = 'InvalidAbiParametersError'\n\n  constructor({ params }: { params: string | object }) {\n    super('Failed to parse ABI parameters.', {\n      details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n      docsPath: '/api/human#parseabiparameters-1',\n    })\n  }\n}\n\nexport class InvalidParameterError extends BaseError {\n  override name = 'InvalidParameterError'\n\n  constructor({ param }: { param: string }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n    })\n  }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n  override name = 'SolidityProtectedKeywordError'\n\n  constructor({ param, name }: { param: string; name: string }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n      ],\n    })\n  }\n}\n\nexport class InvalidModifierError extends BaseError {\n  override name = 'InvalidModifierError'\n\n  constructor({\n    param,\n    type,\n    modifier,\n  }: {\n    param: string\n    type?: AbiItemType | 'struct' | undefined\n    modifier: Modifier\n  }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `Modifier \"${modifier}\" not allowed${\n          type ? ` in \"${type}\" type` : ''\n        }.`,\n      ],\n    })\n  }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n  override name = 'InvalidFunctionModifierError'\n\n  constructor({\n    param,\n    type,\n    modifier,\n  }: {\n    param: string\n    type?: AbiItemType | 'struct' | undefined\n    modifier: Modifier\n  }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `Modifier \"${modifier}\" not allowed${\n          type ? ` in \"${type}\" type` : ''\n        }.`,\n        `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n      ],\n    })\n  }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n  override name = 'InvalidAbiTypeParameterError'\n\n  constructor({\n    abiParameter,\n  }: {\n    abiParameter: AbiParameter & { indexed?: boolean | undefined }\n  }) {\n    super('Invalid ABI parameter.', {\n      details: JSON.stringify(abiParameter, null, 2),\n      metaMessages: ['ABI parameter type is invalid.'],\n    })\n  }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n  override name = 'InvalidSignatureError'\n\n  constructor({\n    signature,\n    type,\n  }: {\n    signature: string\n    type: AbiItemType | 'struct'\n  }) {\n    super(`Invalid ${type} signature.`, {\n      details: signature,\n    })\n  }\n}\n\nexport class UnknownSignatureError extends BaseError {\n  override name = 'UnknownSignatureError'\n\n  constructor({ signature }: { signature: string }) {\n    super('Unknown signature.', {\n      details: signature,\n    })\n  }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n  override name = 'InvalidStructSignatureError'\n\n  constructor({ signature }: { signature: string }) {\n    super('Invalid struct signature.', {\n      details: signature,\n      metaMessages: ['No properties exist.'],\n    })\n  }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n  override name = 'CircularReferenceError'\n\n  constructor({ type }: { type: string }) {\n    super('Circular reference detected.', {\n      metaMessages: [`Struct \"${type}\" is a circular reference.`],\n    })\n  }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n  override name = 'InvalidParenthesisError'\n\n  constructor({ current, depth }: { current: string; depth: number }) {\n    super('Unbalanced parentheses.', {\n      metaMessages: [\n        `\"${current.trim()}\" has too many ${\n          depth > 0 ? 'opening' : 'closing'\n        } parentheses.`,\n      ],\n      details: `Depth \"${depth}\"`,\n    })\n  }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport type { StructLookup } from '../types/structs.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n  param: string,\n  type?: AbiItemType | 'struct',\n  structs?: StructLookup,\n) {\n  let structKey = ''\n  if (structs)\n    for (const struct of Object.entries(structs)) {\n      if (!struct) continue\n      let propertyKey = ''\n      for (const property of struct[1]) {\n        propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`\n      }\n      structKey += `(${struct[0]}{${propertyKey}})`\n    }\n  if (type) return `${type}:${param}${structKey}`\n  return `${param}${structKey}`\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n  string,\n  AbiParameter & { indexed?: boolean }\n>([\n  // Unnamed\n  ['address', { type: 'address' }],\n  ['bool', { type: 'bool' }],\n  ['bytes', { type: 'bytes' }],\n  ['bytes32', { type: 'bytes32' }],\n  ['int', { type: 'int256' }],\n  ['int256', { type: 'int256' }],\n  ['string', { type: 'string' }],\n  ['uint', { type: 'uint256' }],\n  ['uint8', { type: 'uint8' }],\n  ['uint16', { type: 'uint16' }],\n  ['uint24', { type: 'uint24' }],\n  ['uint32', { type: 'uint32' }],\n  ['uint64', { type: 'uint64' }],\n  ['uint96', { type: 'uint96' }],\n  ['uint112', { type: 'uint112' }],\n  ['uint160', { type: 'uint160' }],\n  ['uint192', { type: 'uint192' }],\n  ['uint256', { type: 'uint256' }],\n\n  // Named\n  ['address owner', { type: 'address', name: 'owner' }],\n  ['address to', { type: 'address', name: 'to' }],\n  ['bool approved', { type: 'bool', name: 'approved' }],\n  ['bytes _data', { type: 'bytes', name: '_data' }],\n  ['bytes data', { type: 'bytes', name: 'data' }],\n  ['bytes signature', { type: 'bytes', name: 'signature' }],\n  ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n  ['bytes32 r', { type: 'bytes32', name: 'r' }],\n  ['bytes32 root', { type: 'bytes32', name: 'root' }],\n  ['bytes32 s', { type: 'bytes32', name: 's' }],\n  ['string name', { type: 'string', name: 'name' }],\n  ['string symbol', { type: 'string', name: 'symbol' }],\n  ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n  ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n  ['uint8 v', { type: 'uint8', name: 'v' }],\n  ['uint256 balance', { type: 'uint256', name: 'balance' }],\n  ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n  ['uint256 value', { type: 'uint256', name: 'value' }],\n\n  // Indexed\n  [\n    'event:address indexed from',\n    { type: 'address', name: 'from', indexed: true },\n  ],\n  ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n  [\n    'event:uint indexed tokenId',\n    { type: 'uint256', name: 'tokenId', indexed: true },\n  ],\n  [\n    'event:uint256 indexed tokenId',\n    { type: 'uint256', name: 'tokenId', indexed: true },\n  ],\n])\n","import type {\n  AbiItemType,\n  AbiType,\n  SolidityArray,\n  SolidityBytes,\n  SolidityString,\n  SolidityTuple,\n} from '../../abi.js'\nimport {\n  bytesRegex,\n  execTyped,\n  integerRegex,\n  isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  InvalidParameterError,\n  SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n  InvalidSignatureError,\n  UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n  eventModifiers,\n  execConstructorSignature,\n  execErrorSignature,\n  execEventSignature,\n  execFallbackSignature,\n  execFunctionSignature,\n  functionModifiers,\n  isConstructorSignature,\n  isErrorSignature,\n  isEventSignature,\n  isFallbackSignature,\n  isFunctionSignature,\n  isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n  if (isFunctionSignature(signature))\n    return parseFunctionSignature(signature, structs)\n\n  if (isEventSignature(signature))\n    return parseEventSignature(signature, structs)\n\n  if (isErrorSignature(signature))\n    return parseErrorSignature(signature, structs)\n\n  if (isConstructorSignature(signature))\n    return parseConstructorSignature(signature, structs)\n\n  if (isFallbackSignature(signature)) return parseFallbackSignature(signature)\n\n  if (isReceiveSignature(signature))\n    return {\n      type: 'receive',\n      stateMutability: 'payable',\n    }\n\n  throw new UnknownSignatureError({ signature })\n}\n\nexport function parseFunctionSignature(\n  signature: string,\n  structs: StructLookup = {},\n) {\n  const match = execFunctionSignature(signature)\n  if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n  const inputParams = splitParameters(match.parameters)\n  const inputs = []\n  const inputLength = inputParams.length\n  for (let i = 0; i < inputLength; i++) {\n    inputs.push(\n      parseAbiParameter(inputParams[i]!, {\n        modifiers: functionModifiers,\n        structs,\n        type: 'function',\n      }),\n    )\n  }\n\n  const outputs = []\n  if (match.returns) {\n    const outputParams = splitParameters(match.returns)\n    const outputLength = outputParams.length\n    for (let i = 0; i < outputLength; i++) {\n      outputs.push(\n        parseAbiParameter(outputParams[i]!, {\n          modifiers: functionModifiers,\n          structs,\n          type: 'function',\n        }),\n      )\n    }\n  }\n\n  return {\n    name: match.name,\n    type: 'function',\n    stateMutability: match.stateMutability ?? 'nonpayable',\n    inputs,\n    outputs,\n  }\n}\n\nexport function parseEventSignature(\n  signature: string,\n  structs: StructLookup = {},\n) {\n  const match = execEventSignature(signature)\n  if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n  const params = splitParameters(match.parameters)\n  const abiParameters = []\n  const length = params.length\n  for (let i = 0; i < length; i++)\n    abiParameters.push(\n      parseAbiParameter(params[i]!, {\n        modifiers: eventModifiers,\n        structs,\n        type: 'event',\n      }),\n    )\n  return { name: match.name, type: 'event', inputs: abiParameters }\n}\n\nexport function parseErrorSignature(\n  signature: string,\n  structs: StructLookup = {},\n) {\n  const match = execErrorSignature(signature)\n  if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n  const params = splitParameters(match.parameters)\n  const abiParameters = []\n  const length = params.length\n  for (let i = 0; i < length; i++)\n    abiParameters.push(\n      parseAbiParameter(params[i]!, { structs, type: 'error' }),\n    )\n  return { name: match.name, type: 'error', inputs: abiParameters }\n}\n\nexport function parseConstructorSignature(\n  signature: string,\n  structs: StructLookup = {},\n) {\n  const match = execConstructorSignature(signature)\n  if (!match)\n    throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n  const params = splitParameters(match.parameters)\n  const abiParameters = []\n  const length = params.length\n  for (let i = 0; i < length; i++)\n    abiParameters.push(\n      parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n    )\n  return {\n    type: 'constructor',\n    stateMutability: match.stateMutability ?? 'nonpayable',\n    inputs: abiParameters,\n  }\n}\n\nexport function parseFallbackSignature(signature: string) {\n  const match = execFallbackSignature(signature)\n  if (!match) throw new InvalidSignatureError({ signature, type: 'fallback' })\n\n  return {\n    type: 'fallback',\n    stateMutability: match.stateMutability ?? 'nonpayable',\n  }\n}\n\nconst abiParameterWithoutTupleRegex =\n  /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\\spayable)?)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n  /^\\((?<type>.+?)\\)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n  modifiers?: Set<Modifier>\n  structs?: StructLookup\n  type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n  // optional namespace cache by `type`\n  const parameterCacheKey = getParameterCacheKey(\n    param,\n    options?.type,\n    options?.structs,\n  )\n  if (parameterCache.has(parameterCacheKey))\n    return parameterCache.get(parameterCacheKey)!\n\n  const isTuple = isTupleRegex.test(param)\n  const match = execTyped<{\n    array?: string\n    modifier?: Modifier\n    name?: string\n    type: string\n  }>(\n    isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n    param,\n  )\n  if (!match) throw new InvalidParameterError({ param })\n\n  if (match.name && isSolidityKeyword(match.name))\n    throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n  const name = match.name ? { name: match.name } : {}\n  const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n  const structs = options?.structs ?? {}\n  let type: string\n  let components = {}\n  if (isTuple) {\n    type = 'tuple'\n    const params = splitParameters(match.type)\n    const components_ = []\n    const length = params.length\n    for (let i = 0; i < length; i++) {\n      // remove `modifiers` from `options` to prevent from being added to tuple components\n      components_.push(parseAbiParameter(params[i]!, { structs }))\n    }\n    components = { components: components_ }\n  } else if (match.type in structs) {\n    type = 'tuple'\n    components = { components: structs[match.type] }\n  } else if (dynamicIntegerRegex.test(match.type)) {\n    type = `${match.type}256`\n  } else if (match.type === 'address payable') {\n    type = 'address'\n  } else {\n    type = match.type\n    if (!(options?.type === 'struct') && !isSolidityType(type))\n      throw new UnknownSolidityTypeError({ type })\n  }\n\n  if (match.modifier) {\n    // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n    if (!options?.modifiers?.has?.(match.modifier))\n      throw new InvalidModifierError({\n        param,\n        type: options?.type,\n        modifier: match.modifier,\n      })\n\n    // Check if resolved `type` is valid if there is a function modifier\n    if (\n      functionModifiers.has(match.modifier as FunctionModifier) &&\n      !isValidDataLocation(type, !!match.array)\n    )\n      throw new InvalidFunctionModifierError({\n        param,\n        type: options?.type,\n        modifier: match.modifier,\n      })\n  }\n\n  const abiParameter = {\n    type: `${type}${match.array ?? ''}`,\n    ...name,\n    ...indexed,\n    ...components,\n  }\n  parameterCache.set(parameterCacheKey, abiParameter)\n  return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n  params: string,\n  result: string[] = [],\n  current = '',\n  depth = 0,\n): readonly string[] {\n  const length = params.trim().length\n  // biome-ignore lint/correctness/noUnreachable: recursive\n  for (let i = 0; i < length; i++) {\n    const char = params[i]\n    const tail = params.slice(i + 1)\n    switch (char) {\n      case ',':\n        return depth === 0\n          ? splitParameters(tail, [...result, current.trim()])\n          : splitParameters(tail, result, `${current}${char}`, depth)\n      case '(':\n        return splitParameters(tail, result, `${current}${char}`, depth + 1)\n      case ')':\n        return splitParameters(tail, result, `${current}${char}`, depth - 1)\n      default:\n        return splitParameters(tail, result, `${current}${char}`, depth)\n    }\n  }\n\n  if (current === '') return result\n  if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n  result.push(current.trim())\n  return result\n}\n\nexport function isSolidityType(\n  type: string,\n): type is Exclude<AbiType, SolidityTuple | SolidityArray> {\n  return (\n    type === 'address' ||\n    type === 'bool' ||\n    type === 'function' ||\n    type === 'string' ||\n    bytesRegex.test(type) ||\n    integerRegex.test(type)\n  )\n}\n\nconst protectedKeywordsRegex =\n  /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\n/** @internal */\nexport function isSolidityKeyword(name: string) {\n  return (\n    name === 'address' ||\n    name === 'bool' ||\n    name === 'function' ||\n    name === 'string' ||\n    name === 'tuple' ||\n    bytesRegex.test(name) ||\n    integerRegex.test(name) ||\n    protectedKeywordsRegex.test(name)\n  )\n}\n\n/** @internal */\nexport function isValidDataLocation(\n  type: string,\n  isArray: boolean,\n): type is Exclude<\n  AbiType,\n  SolidityString | Extract<SolidityBytes, 'bytes'> | SolidityArray\n> {\n  return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n  InvalidSignatureError,\n  InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n  // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n  const shallowStructs: StructLookup = {}\n  const signaturesLength = signatures.length\n  for (let i = 0; i < signaturesLength; i++) {\n    const signature = signatures[i]!\n    if (!isStructSignature(signature)) continue\n\n    const match = execStructSignature(signature)\n    if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n    const properties = match.properties.split(';')\n\n    const components: AbiParameter[] = []\n    const propertiesLength = properties.length\n    for (let k = 0; k < propertiesLength; k++) {\n      const property = properties[k]!\n      const trimmed = property.trim()\n      if (!trimmed) continue\n      const abiParameter = parseAbiParameter(trimmed, {\n        type: 'struct',\n      })\n      components.push(abiParameter)\n    }\n\n    if (!components.length) throw new InvalidStructSignatureError({ signature })\n    shallowStructs[match.name] = components\n  }\n\n  // Resolve nested structs inside each parameter\n  const resolvedStructs: StructLookup = {}\n  const entries = Object.entries(shallowStructs)\n  const entriesLength = entries.length\n  for (let i = 0; i < entriesLength; i++) {\n    const [name, parameters] = entries[i]!\n    resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n  }\n\n  return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n  /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n  abiParameters: readonly (AbiParameter & { indexed?: true })[] = [],\n  structs: StructLookup = {},\n  ancestors = new Set<string>(),\n) {\n  const components: AbiParameter[] = []\n  const length = abiParameters.length\n  for (let i = 0; i < length; i++) {\n    const abiParameter = abiParameters[i]!\n    const isTuple = isTupleRegex.test(abiParameter.type)\n    if (isTuple) components.push(abiParameter)\n    else {\n      const match = execTyped<{ array?: string; type: string }>(\n        typeWithoutTupleRegex,\n        abiParameter.type,\n      )\n      if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n      const { array, type } = match\n      if (type in structs) {\n        if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n        components.push({\n          ...abiParameter,\n          type: `tuple${array ?? ''}`,\n          components: resolveStructs(\n            structs[type],\n            structs,\n            new Set([...ancestors, type]),\n          ),\n        })\n      } else {\n        if (isSolidityType(type)) components.push(abiParameter)\n        else throw new UnknownTypeError({ type })\n      }\n    }\n  }\n\n  return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Narrow } from '../narrow.js'\nimport type { Error, Filter } from '../types.js'\nimport { InvalidAbiItemError } from './errors/abiItem.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signature, Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * type Result = ParseAbiItem<'function balanceOf(address owner) view returns (uint256)'>\n * //   ^? type Result = { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * type Result = ParseAbiItem<\n *   // ^? type Result = { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n *   ['function foo(Baz bar) view returns (string)', 'struct Baz { string name; }']\n * >\n */\nexport type ParseAbiItem<\n  signature extends string | readonly string[] | readonly unknown[],\n> =\n  | (signature extends string\n      ? string extends signature\n        ? Abi[number]\n        : signature extends Signature<signature> // Validate signature\n          ? ParseSignature<signature>\n          : never\n      : never)\n  | (signature extends readonly string[]\n      ? string[] extends signature\n        ? Abi[number] // Return generic Abi item since type was no inferrable\n        : signature extends Signatures<signature> // Validate signature\n          ? ParseStructs<signature> extends infer structs\n            ? {\n                [key in keyof signature]: ParseSignature<\n                  signature[key] extends string ? signature[key] : never,\n                  structs\n                >\n              } extends infer mapped extends readonly unknown[]\n              ? // Filter out `never` since those are structs\n                Filter<mapped, never>[0] extends infer result\n                ? result extends undefined // convert `undefined` to `never` (e.g. `ParseAbiItem<['struct Foo { string name; }']>`)\n                  ? never\n                  : result\n                : never\n              : never\n            : never\n          : never\n      : never)\n\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * //    ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n *   //  ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n *   'function foo(Baz bar) view returns (string)',\n *   'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem<\n  signature extends string | readonly string[] | readonly unknown[],\n>(\n  signature: Narrow<signature> &\n    (\n      | (signature extends string\n          ? string extends signature\n            ? unknown\n            : Signature<signature>\n          : never)\n      | (signature extends readonly string[]\n          ? signature extends readonly [] // empty array\n            ? Error<'At least one signature required.'>\n            : string[] extends signature\n              ? unknown\n              : Signatures<signature>\n          : never)\n    ),\n): ParseAbiItem<signature> {\n  let abiItem: ParseAbiItem<signature> | undefined\n  if (typeof signature === 'string')\n    abiItem = parseSignature(signature) as ParseAbiItem<signature>\n  else {\n    const structs = parseStructs(signature as readonly string[])\n    const length = signature.length as number\n    for (let i = 0; i < length; i++) {\n      const signature_ = (signature as readonly string[])[i]!\n      if (isStructSignature(signature_)) continue\n      abiItem = parseSignature(signature_, structs) as ParseAbiItem<signature>\n      break\n    }\n  }\n\n  if (!abiItem) throw new InvalidAbiItemError({ signature })\n  return abiItem as ParseAbiItem<signature>\n}\n","export type {\n  Abi,\n  AbiConstructor,\n  AbiError,\n  AbiEvent,\n  AbiEventParameter,\n  AbiFallback,\n  AbiFunction,\n  AbiInternalType,\n  AbiItemType,\n  AbiParameter,\n  AbiParameterKind,\n  AbiReceive,\n  AbiStateMutability,\n  AbiType,\n  Address,\n  SolidityAddress,\n  SolidityArray,\n  SolidityArrayWithoutTuple,\n  SolidityArrayWithTuple,\n  SolidityBool,\n  SolidityBytes,\n  SolidityFixedArrayRange,\n  SolidityFixedArraySizeLookup,\n  SolidityFunction,\n  SolidityInt,\n  SolidityString,\n  SolidityTuple,\n  TypedData,\n  TypedDataDomain,\n  TypedDataParameter,\n  TypedDataType,\n} from '../abi.js'\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n  Register,\n  DefaultRegister,\n  ResolvedRegister,\n} from '../register.js'\n\nexport type {\n  AbiParameterToPrimitiveType,\n  AbiParametersToPrimitiveTypes,\n  AbiTypeToPrimitiveType,\n  ExtractAbiError,\n  ExtractAbiErrorNames,\n  ExtractAbiErrors,\n  ExtractAbiEvent,\n  ExtractAbiEventNames,\n  ExtractAbiEvents,\n  ExtractAbiFunction,\n  ExtractAbiFunctionNames,\n  ExtractAbiFunctions,\n  IsAbi,\n  IsTypedData,\n  TypedDataToPrimitiveTypes,\n} from '../utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n  formatAbi,\n  type FormatAbi,\n} from '../human-readable/formatAbi.js'\n\nexport {\n  formatAbiItem,\n  type FormatAbiItem,\n} from '../human-readable/formatAbiItem.js'\n\nexport {\n  formatAbiParameter,\n  type FormatAbiParameter,\n} from '../human-readable/formatAbiParameter.js'\n\nexport {\n  formatAbiParameters,\n  type FormatAbiParameters,\n} from '../human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from '../human-readable/parseAbi.js'\n\nexport {\n  parseAbiItem,\n  type ParseAbiItem,\n} from '../human-readable/parseAbiItem.js'\n\nexport {\n  parseAbiParameter,\n  type ParseAbiParameter,\n} from '../human-readable/parseAbiParameter.js'\n\nexport {\n  parseAbiParameters,\n  type ParseAbiParameters,\n} from '../human-readable/parseAbiParameters.js'\n\nexport {\n  UnknownTypeError,\n  InvalidAbiItemError,\n  UnknownSolidityTypeError,\n} from '../human-readable/errors/abiItem.js'\n\nexport {\n  InvalidAbiTypeParameterError,\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  SolidityProtectedKeywordError,\n  InvalidParameterError,\n  InvalidAbiParametersError,\n  InvalidAbiParameterError,\n} from '../human-readable/errors/abiParameter.js'\n\nexport {\n  InvalidStructSignatureError,\n  InvalidSignatureError,\n  UnknownSignatureError,\n} from '../human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from '../human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from '../human-readable/errors/struct.js'\n","import type { AbiParameter } from 'abitype'\n\nimport {\n  InvalidDefinitionTypeError,\n  type InvalidDefinitionTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\n\nexport type FormatAbiItemErrorType =\n  | FormatAbiParamsErrorType\n  | InvalidDefinitionTypeErrorType\n  | ErrorType\n\nexport function formatAbiItem(\n  abiItem: AbiItem,\n  { includeName = false }: { includeName?: boolean | undefined } = {},\n) {\n  if (\n    abiItem.type !== 'function' &&\n    abiItem.type !== 'event' &&\n    abiItem.type !== 'error'\n  )\n    throw new InvalidDefinitionTypeError(abiItem.type)\n\n  return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`\n}\n\nexport type FormatAbiParamsErrorType = ErrorType\n\nexport function formatAbiParams(\n  params: readonly AbiParameter[] | undefined,\n  { includeName = false }: { includeName?: boolean | undefined } = {},\n): string {\n  if (!params) return ''\n  return params\n    .map((param) => formatAbiParam(param, { includeName }))\n    .join(includeName ? ', ' : ',')\n}\n\nexport type FormatAbiParamErrorType = ErrorType\n\nfunction formatAbiParam(\n  param: AbiParameter,\n  { includeName }: { includeName: boolean },\n): string {\n  if (param.type.startsWith('tuple')) {\n    return `(${formatAbiParams(\n      (param as unknown as { components: AbiParameter[] }).components,\n      { includeName },\n    )})${param.type.slice('tuple'.length)}`\n  }\n  return param.type + (includeName && param.name ? ` ${param.name}` : '')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type IsHexErrorType = ErrorType\n\nexport function isHex(\n  value: unknown,\n  { strict = true }: { strict?: boolean | undefined } = {},\n): value is Hex {\n  if (!value) return false\n  if (typeof value !== 'string') return false\n  return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\n\nexport type SizeErrorType = IsHexErrorType | ErrorType\n\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value: Hex | ByteArray) {\n  if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2)\n  return value.length\n}\n","export const version = '2.55.2'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n  getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n  version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n  getDocsUrl: ({\n    docsBaseUrl,\n    docsPath = '',\n    docsSlug,\n  }: BaseErrorParameters) =>\n    docsPath\n      ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n          docsSlug ? `#${docsSlug}` : ''\n        }`\n      : undefined,\n  version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n  errorConfig = config\n}\n\ntype BaseErrorParameters = {\n  cause?: BaseError | Error | undefined\n  details?: string | undefined\n  docsBaseUrl?: string | undefined\n  docsPath?: string | undefined\n  docsSlug?: string | undefined\n  metaMessages?: string[] | undefined\n  name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n  details: string\n  docsPath?: string | undefined\n  metaMessages?: string[] | undefined\n  shortMessage: string\n  version: string\n\n  override name = 'BaseError'\n\n  constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n    const details = (() => {\n      if (args.cause instanceof BaseError) return args.cause.details\n      if (args.cause?.message) return args.cause.message\n      return args.details!\n    })()\n    const docsPath = (() => {\n      if (args.cause instanceof BaseError)\n        return args.cause.docsPath || args.docsPath\n      return args.docsPath\n    })()\n    const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n    const message = [\n      shortMessage || 'An error occurred.',\n      '',\n      ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n      ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n      ...(details ? [`Details: ${details}`] : []),\n      ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n    ].join('\\n')\n\n    super(message, args.cause ? { cause: args.cause } : undefined)\n\n    this.details = details\n    this.docsPath = docsPath\n    this.metaMessages = args.metaMessages\n    this.name = args.name ?? this.name\n    this.shortMessage = shortMessage\n    this.version = version\n  }\n\n  walk(): Error\n  walk(fn: (err: unknown) => boolean): Error | null\n  walk(fn?: any): any {\n    return walk(this, fn)\n  }\n}\n\nfunction walk(\n  err: unknown,\n  fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n  if (fn?.(err)) return err\n  if (\n    err &&\n    typeof err === 'object' &&\n    'cause' in err &&\n    err.cause !== undefined\n  )\n    return walk(err.cause, fn)\n  return fn ? null : err\n}\n","import type { Abi, AbiEvent, AbiParameter } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { formatAbiItem, formatAbiParams } from '../utils/abi/formatAbiItem.js'\nimport { size } from '../utils/data/size.js'\n\nimport { BaseError } from './base.js'\n\nexport type AbiConstructorNotFoundErrorType = AbiConstructorNotFoundError & {\n  name: 'AbiConstructorNotFoundError'\n}\nexport class AbiConstructorNotFoundError extends BaseError {\n  constructor({ docsPath }: { docsPath: string }) {\n    super(\n      [\n        'A constructor was not found on the ABI.',\n        'Make sure you are using the correct ABI and that the constructor exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiConstructorNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n  AbiConstructorParamsNotFoundError & {\n    name: 'AbiConstructorParamsNotFoundError'\n  }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\n  constructor({ docsPath }: { docsPath: string }) {\n    super(\n      [\n        'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',\n        'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiConstructorParamsNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n  AbiDecodingDataSizeInvalidError & {\n    name: 'AbiDecodingDataSizeInvalidError'\n  }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\n  constructor({ data, size }: { data: Hex; size: number }) {\n    super(\n      [\n        `Data size of ${size} bytes is invalid.`,\n        'Size must be in increments of 32 bytes (size % 32 === 0).',\n      ].join('\\n'),\n      {\n        metaMessages: [`Data: ${data} (${size} bytes)`],\n        name: 'AbiDecodingDataSizeInvalidError',\n      },\n    )\n  }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n  AbiDecodingDataSizeTooSmallError & {\n    name: 'AbiDecodingDataSizeTooSmallError'\n  }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\n  data: Hex\n  params: readonly AbiParameter[]\n  size: number\n\n  constructor({\n    data,\n    params,\n    size,\n  }: { data: Hex; params: readonly AbiParameter[]; size: number }) {\n    super(\n      [`Data size of ${size} bytes is too small for given parameters.`].join(\n        '\\n',\n      ),\n      {\n        metaMessages: [\n          `Params: (${formatAbiParams(params, { includeName: true })})`,\n          `Data:   ${data} (${size} bytes)`,\n        ],\n        name: 'AbiDecodingDataSizeTooSmallError',\n      },\n    )\n\n    this.data = data\n    this.params = params\n    this.size = size\n  }\n}\n\nexport type AbiDecodingZeroDataErrorType = AbiDecodingZeroDataError & {\n  name: 'AbiDecodingZeroDataError'\n}\nexport class AbiDecodingZeroDataError extends BaseError {\n  constructor({ cause }: { cause?: BaseError | Error | undefined } = {}) {\n    super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n      name: 'AbiDecodingZeroDataError',\n      cause,\n    })\n  }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n  AbiEncodingArrayLengthMismatchError & {\n    name: 'AbiEncodingArrayLengthMismatchError'\n  }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\n  constructor({\n    expectedLength,\n    givenLength,\n    type,\n  }: { expectedLength: number; givenLength: number; type: string }) {\n    super(\n      [\n        `ABI encoding array length mismatch for type ${type}.`,\n        `Expected length: ${expectedLength}`,\n        `Given length: ${givenLength}`,\n      ].join('\\n'),\n      { name: 'AbiEncodingArrayLengthMismatchError' },\n    )\n  }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n  AbiEncodingBytesSizeMismatchError & {\n    name: 'AbiEncodingBytesSizeMismatchError'\n  }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\n  constructor({ expectedSize, value }: { expectedSize: number; value: Hex }) {\n    super(\n      `Size of bytes \"${value}\" (bytes${size(\n        value,\n      )}) does not match expected size (bytes${expectedSize}).`,\n      { name: 'AbiEncodingBytesSizeMismatchError' },\n    )\n  }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n  AbiEncodingLengthMismatchError & {\n    name: 'AbiEncodingLengthMismatchError'\n  }\nexport class AbiEncodingLengthMismatchError extends BaseError {\n  constructor({\n    expectedLength,\n    givenLength,\n  }: { expectedLength: number; givenLength: number }) {\n    super(\n      [\n        'ABI encoding params/values length mismatch.',\n        `Expected length (params): ${expectedLength}`,\n        `Given length (values): ${givenLength}`,\n      ].join('\\n'),\n      { name: 'AbiEncodingLengthMismatchError' },\n    )\n  }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n  name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\n  constructor(errorName: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Arguments (\\`args\\`) were provided to \"${errorName}\", but \"${errorName}\" on the ABI does not contain any parameters (\\`inputs\\`).`,\n        'Cannot encode error result without knowing what the parameter types are.',\n        'Make sure you are using the correct ABI and that the inputs exist on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiErrorInputsNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n  name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n  constructor(\n    errorName?: string | undefined,\n    { docsPath }: { docsPath?: string | undefined } = {},\n  ) {\n    super(\n      [\n        `Error ${errorName ? `\"${errorName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the error exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiErrorNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n  AbiErrorSignatureNotFoundError & {\n    name: 'AbiErrorSignatureNotFoundError'\n  }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\n  signature: Hex\n\n  constructor(\n    signature: Hex,\n    {\n      docsPath,\n      cause,\n    }: { docsPath: string; cause?: BaseError | Error | undefined },\n  ) {\n    super(\n      [\n        `Encoded error signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the error exists on it.',\n        `You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiErrorSignatureNotFoundError',\n        cause,\n      },\n    )\n    this.signature = signature\n  }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n  AbiEventSignatureEmptyTopicsError & {\n    name: 'AbiEventSignatureEmptyTopicsError'\n  }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n  constructor({ docsPath }: { docsPath: string }) {\n    super('Cannot extract event signature from empty topics.', {\n      docsPath,\n      name: 'AbiEventSignatureEmptyTopicsError',\n    })\n  }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n  AbiEventSignatureNotFoundError & {\n    name: 'AbiEventSignatureNotFoundError'\n  }\nexport class AbiEventSignatureNotFoundError extends BaseError {\n  constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Encoded event signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the event exists on it.',\n        `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiEventSignatureNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n  name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n  constructor(\n    eventName?: string | undefined,\n    { docsPath }: { docsPath?: string | undefined } = {},\n  ) {\n    super(\n      [\n        `Event ${eventName ? `\"${eventName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the event exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiEventNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n  name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n  constructor(\n    functionName?: string | undefined,\n    { docsPath }: { docsPath?: string | undefined } = {},\n  ) {\n    super(\n      [\n        `Function ${functionName ? `\"${functionName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the function exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiFunctionNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n  AbiFunctionOutputsNotFoundError & {\n    name: 'AbiFunctionOutputsNotFoundError'\n  }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\n  constructor(functionName: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Function \"${functionName}\" does not contain any \\`outputs\\` on ABI.`,\n        'Cannot decode function result without knowing what the parameter types are.',\n        'Make sure you are using the correct ABI and that the function exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiFunctionOutputsNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n  AbiFunctionSignatureNotFoundError & {\n    name: 'AbiFunctionSignatureNotFoundError'\n  }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\n  constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Encoded function signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the function exists on it.',\n        `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n        name: 'AbiFunctionSignatureNotFoundError',\n      },\n    )\n  }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n  name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n  constructor(\n    x: { abiItem: Abi[number]; type: string },\n    y: { abiItem: Abi[number]; type: string },\n  ) {\n    super('Found ambiguous types in overloaded ABI items.', {\n      metaMessages: [\n        `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n        `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n        '',\n        'These types encode differently and cannot be distinguished at runtime.',\n        'Remove one of the ambiguous items in the ABI.',\n      ],\n      name: 'AbiItemAmbiguityError',\n    })\n  }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n  name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n  constructor({\n    expectedSize,\n    givenSize,\n  }: { expectedSize: number; givenSize: number }) {\n    super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n      name: 'BytesSizeMismatchError',\n    })\n  }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n  name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\n  abiItem: AbiEvent\n  data: Hex\n  params: readonly AbiParameter[]\n  size: number\n\n  constructor({\n    abiItem,\n    data,\n    params,\n    size,\n  }: {\n    abiItem: AbiEvent\n    data: Hex\n    params: readonly AbiParameter[]\n    size: number\n  }) {\n    super(\n      [\n        `Data size of ${size} bytes is too small for non-indexed event parameters.`,\n      ].join('\\n'),\n      {\n        metaMessages: [\n          `Params: (${formatAbiParams(params, { includeName: true })})`,\n          `Data:   ${data} (${size} bytes)`,\n        ],\n        name: 'DecodeLogDataMismatch',\n      },\n    )\n\n    this.abiItem = abiItem\n    this.data = data\n    this.params = params\n    this.size = size\n  }\n}\n\nexport type DecodeLogTopicsMismatchErrorType = DecodeLogTopicsMismatch & {\n  name: 'DecodeLogTopicsMismatch'\n}\nexport class DecodeLogTopicsMismatch extends BaseError {\n  abiItem: AbiEvent\n\n  constructor({\n    abiItem,\n    param,\n  }: {\n    abiItem: AbiEvent\n    param: AbiParameter & { indexed: boolean }\n  }) {\n    super(\n      [\n        `Expected a topic for indexed event parameter${\n          param.name ? ` \"${param.name}\"` : ''\n        } on event \"${formatAbiItem(abiItem, { includeName: true })}\".`,\n      ].join('\\n'),\n      { name: 'DecodeLogTopicsMismatch' },\n    )\n\n    this.abiItem = abiItem\n  }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n  name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\n  constructor(type: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Type \"${type}\" is not a valid encoding type.`,\n        'Please provide a valid ABI type.',\n      ].join('\\n'),\n      { docsPath, name: 'InvalidAbiEncodingType' },\n    )\n  }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n  name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\n  constructor(type: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Type \"${type}\" is not a valid decoding type.`,\n        'Please provide a valid ABI type.',\n      ].join('\\n'),\n      { docsPath, name: 'InvalidAbiDecodingType' },\n    )\n  }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n  name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n  constructor(value: unknown) {\n    super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n      name: 'InvalidArrayError',\n    })\n  }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n  name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\n  constructor(type: string) {\n    super(\n      [\n        `\"${type}\" is not a valid definition type.`,\n        'Valid types: \"function\", \"event\", \"error\"',\n      ].join('\\n'),\n      { name: 'InvalidDefinitionTypeError' },\n    )\n  }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n  name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n  constructor(type: unknown) {\n    super(`Type \"${type}\" is not supported for packed encoding.`, {\n      name: 'UnsupportedPackedAbiType',\n    })\n  }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n  name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n  constructor({\n    offset,\n    position,\n    size,\n  }: { offset: number; position: 'start' | 'end'; size: number }) {\n    super(\n      `Slice ${\n        position === 'start' ? 'starting' : 'ending'\n      } at offset \"${offset}\" is out-of-bounds (size: ${size}).`,\n      { name: 'SliceOffsetOutOfBoundsError' },\n    )\n  }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n  name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n  constructor({\n    size,\n    targetSize,\n    type,\n  }: {\n    size: number\n    targetSize: number\n    type: 'hex' | 'bytes'\n  }) {\n    super(\n      `${type.charAt(0).toUpperCase()}${type\n        .slice(1)\n        .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`,\n      { name: 'SizeExceedsPaddingSizeError' },\n    )\n  }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n  name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\n  constructor({\n    size,\n    targetSize,\n    type,\n  }: {\n    size: number\n    targetSize: number\n    type: 'hex' | 'bytes'\n  }) {\n    super(\n      `${type.charAt(0).toUpperCase()}${type\n        .slice(1)\n        .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n      { name: 'InvalidBytesLengthError' },\n    )\n  }\n}\n","import {\n  SizeExceedsPaddingSizeError,\n  type SizeExceedsPaddingSizeErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype PadOptions = {\n  dir?: 'left' | 'right' | undefined\n  size?: number | null | undefined\n}\nexport type PadReturnType<value extends ByteArray | Hex> = value extends Hex\n  ? Hex\n  : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad<value extends ByteArray | Hex>(\n  hexOrBytes: value,\n  { dir, size = 32 }: PadOptions = {},\n): PadReturnType<value> {\n  if (typeof hexOrBytes === 'string')\n    return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n  return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\n}\n\nexport type PadHexErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padHex(hex_: Hex, { dir, size = 32 }: PadOptions = {}) {\n  if (size === null) return hex_\n  const hex = hex_.replace('0x', '')\n  if (hex.length > size * 2)\n    throw new SizeExceedsPaddingSizeError({\n      size: Math.ceil(hex.length / 2),\n      targetSize: size,\n      type: 'hex',\n    })\n\n  return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](\n    size * 2,\n    '0',\n  )}` as Hex\n}\n\nexport type PadBytesErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padBytes(\n  bytes: ByteArray,\n  { dir, size = 32 }: PadOptions = {},\n) {\n  if (size === null) return bytes\n  if (bytes.length > size)\n    throw new SizeExceedsPaddingSizeError({\n      size: bytes.length,\n      targetSize: size,\n      type: 'bytes',\n    })\n  const paddedBytes = new Uint8Array(size)\n  for (let i = 0; i < size; i++) {\n    const padEnd = dir === 'right'\n    paddedBytes[padEnd ? i : size - i - 1] =\n      bytes[padEnd ? i : bytes.length - i - 1]\n  }\n  return paddedBytes\n}\n","import type { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n  name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n  constructor({\n    max,\n    min,\n    signed,\n    size,\n    value,\n  }: {\n    max?: string | undefined\n    min: string\n    signed?: boolean | undefined\n    size?: number | undefined\n    value: string\n  }) {\n    super(\n      `Number \"${value}\" is not in safe ${\n        size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''\n      }integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`,\n      { name: 'IntegerOutOfRangeError' },\n    )\n  }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n  name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\n  constructor(bytes: ByteArray) {\n    super(\n      `Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,\n      {\n        name: 'InvalidBytesBooleanError',\n      },\n    )\n  }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n  name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\n  constructor(hex: Hex) {\n    super(\n      `Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`,\n      { name: 'InvalidHexBooleanError' },\n    )\n  }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n  name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n  constructor(value: Hex) {\n    super(\n      `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n      { name: 'InvalidHexValueError' },\n    )\n  }\n}\n\nexport type RlpDepthLimitExceededErrorType = RlpDepthLimitExceededError & {\n  name: 'RlpDepthLimitExceededError'\n}\nexport class RlpDepthLimitExceededError extends BaseError {\n  constructor({ limit }: { limit: number }) {\n    super(`RLP depth limit of \\`${limit}\\` exceeded.`, {\n      name: 'RlpDepthLimitExceededError',\n    })\n  }\n}\n\nexport type RlpListBoundaryExceededErrorType = RlpListBoundaryExceededError & {\n  name: 'RlpListBoundaryExceededError'\n}\nexport class RlpListBoundaryExceededError extends BaseError {\n  constructor({ consumed, declared }: { consumed: number; declared: number }) {\n    super(\n      `RLP list items consumed \\`${consumed}\\` bytes but the list declared a length of \\`${declared}\\`.`,\n      { name: 'RlpListBoundaryExceededError' },\n    )\n  }\n}\n\nexport type RlpTrailingBytesErrorType = RlpTrailingBytesError & {\n  name: 'RlpTrailingBytesError'\n}\nexport class RlpTrailingBytesError extends BaseError {\n  constructor({ count }: { count: number }) {\n    super(\n      `RLP payload encodes a single item, but \\`${count}\\` trailing ${\n        count === 1 ? 'byte remains' : 'bytes remain'\n      }.`,\n      { name: 'RlpTrailingBytesError' },\n    )\n  }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n  name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n  constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n    super(\n      `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n      { name: 'SizeOverflowError' },\n    )\n  }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n  dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType<value extends ByteArray | Hex> = value extends Hex\n  ? Hex\n  : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim<value extends ByteArray | Hex>(\n  hexOrBytes: value,\n  { dir = 'left' }: TrimOptions = {},\n): TrimReturnType<value> {\n  let data: any =\n    typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes\n\n  let sliceLength = 0\n  for (let i = 0; i < data.length - 1; i++) {\n    if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n      sliceLength++\n    else break\n  }\n  data =\n    dir === 'left'\n      ? data.slice(sliceLength)\n      : data.slice(0, data.length - sliceLength)\n\n  if (typeof hexOrBytes === 'string') {\n    if (data.length === 1 && dir === 'right') data = `${data}0`\n    return `0x${\n      data.length % 2 === 1 ? `0${data}` : data\n    }` as TrimReturnType<value>\n  }\n  return data as TrimReturnType<value>\n}\n","import {\n  IntegerOutOfRangeError,\n  type IntegerOutOfRangeErrorType,\n  InvalidHexBooleanError,\n  type InvalidHexBooleanErrorType,\n  SizeOverflowError,\n  type SizeOverflowErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type SizeErrorType, size as size_ } from '../data/size.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\n\nexport type AssertSizeErrorType =\n  | SizeOverflowErrorType\n  | SizeErrorType\n  | ErrorType\n\nexport function assertSize(\n  hexOrBytes: Hex | ByteArray,\n  { size }: { size: number },\n): void {\n  if (size_(hexOrBytes) > size)\n    throw new SizeOverflowError({\n      givenSize: size_(hexOrBytes),\n      maxSize: size,\n    })\n}\n\nexport type FromHexParameters<\n  to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n  | to\n  | {\n      /** Size (in bytes) of the hex value. */\n      size?: number | undefined\n      /** Type to convert to. */\n      to: to\n    }\n\nexport type FromHexReturnType<to> = to extends 'string'\n  ? string\n  : to extends 'bigint'\n    ? bigint\n    : to extends 'number'\n      ? number\n      : to extends 'bytes'\n        ? ByteArray\n        : to extends 'boolean'\n          ? boolean\n          : never\n\nexport type FromHexErrorType =\n  | HexToNumberErrorType\n  | HexToBigIntErrorType\n  | HexToBoolErrorType\n  | HexToStringErrorType\n  | HexToBytesErrorType\n  | ErrorType\n\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n *   size: 32,\n *   to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex<\n  to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n>(hex: Hex, toOrOpts: FromHexParameters<to>): FromHexReturnType<to> {\n  const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n  const to = opts.to\n\n  if (to === 'number') return hexToNumber(hex, opts) as FromHexReturnType<to>\n  if (to === 'bigint') return hexToBigInt(hex, opts) as FromHexReturnType<to>\n  if (to === 'string') return hexToString(hex, opts) as FromHexReturnType<to>\n  if (to === 'boolean') return hexToBool(hex, opts) as FromHexReturnType<to>\n  return hexToBytes(hex, opts) as FromHexReturnType<to>\n}\n\nexport type HexToBigIntOpts = {\n  /** Whether or not the number of a signed representation. */\n  signed?: boolean | undefined\n  /** Size (in bytes) of the hex value. */\n  size?: number | undefined\n}\n\nexport type HexToBigIntErrorType = AssertSizeErrorType | ErrorType\n\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {\n  const { signed } = opts\n\n  if (opts.size) assertSize(hex, { size: opts.size })\n\n  const value = BigInt(hex)\n  if (!signed) return value\n\n  const size = (hex.length - 2) / 2\n  const max = (1n << (BigInt(size) * 8n - 1n)) - 1n\n  if (value <= max) return value\n\n  return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n\n}\n\nexport type HexToBoolOpts = {\n  /** Size (in bytes) of the hex value. */\n  size?: number | undefined\n}\n\nexport type HexToBoolErrorType =\n  | AssertSizeErrorType\n  | InvalidHexBooleanErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_: Hex, opts: HexToBoolOpts = {}): boolean {\n  let hex = hex_\n  if (opts.size) {\n    assertSize(hex, { size: opts.size })\n    hex = trim(hex)\n  }\n  if (trim(hex) === '0x00') return false\n  if (trim(hex) === '0x01') return true\n  throw new InvalidHexBooleanError(hex)\n}\n\nexport type HexToNumberOpts = HexToBigIntOpts\n\nexport type HexToNumberErrorType =\n  | HexToBigIntErrorType\n  | IntegerOutOfRangeErrorType\n  | ErrorType\n\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex: Hex, opts: HexToNumberOpts = {}): number {\n  const value = hexToBigInt(hex, opts)\n  const number = Number(value)\n  if (!Number.isSafeInteger(number))\n    throw new IntegerOutOfRangeError({\n      max: `${Number.MAX_SAFE_INTEGER}`,\n      min: `${Number.MIN_SAFE_INTEGER}`,\n      signed: opts.signed,\n      size: opts.size,\n      value: `${value}n`,\n    })\n  return number\n}\n\nexport type HexToStringOpts = {\n  /** Size (in bytes) of the hex value. */\n  size?: number | undefined\n}\n\nexport type HexToStringErrorType =\n  | AssertSizeErrorType\n  | HexToBytesErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n *  size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex: Hex, opts: HexToStringOpts = {}): string {\n  let bytes = hexToBytes(hex)\n  if (opts.size) {\n    assertSize(bytes, { size: opts.size })\n    bytes = trim(bytes, { dir: 'right' })\n  }\n  return new TextDecoder().decode(bytes)\n}\n","import {\n  IntegerOutOfRangeError,\n  type IntegerOutOfRangeErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n  i.toString(16).padStart(2, '0'),\n)\n\nexport type ToHexParameters = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number | undefined\n}\n\nexport type ToHexErrorType =\n  | BoolToHexErrorType\n  | BytesToHexErrorType\n  | NumberToHexErrorType\n  | StringToHexErrorType\n  | ErrorType\n\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(\n  value: string | number | bigint | boolean | ByteArray,\n  opts: ToHexParameters = {},\n): Hex {\n  if (typeof value === 'number' || typeof value === 'bigint')\n    return numberToHex(value, opts)\n  if (typeof value === 'string') {\n    return stringToHex(value, opts)\n  }\n  if (typeof value === 'boolean') return boolToHex(value, opts)\n  return bytesToHex(value, opts)\n}\n\nexport type BoolToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number | undefined\n}\n\nexport type BoolToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value: boolean, opts: BoolToHexOpts = {}): Hex {\n  const hex: Hex = `0x${Number(value)}`\n  if (typeof opts.size === 'number') {\n    assertSize(hex, { size: opts.size })\n    return pad(hex, { size: opts.size })\n  }\n  return hex\n}\n\nexport type BytesToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number | undefined\n}\n\nexport type BytesToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value: ByteArray, opts: BytesToHexOpts = {}): Hex {\n  let string = ''\n  for (let i = 0; i < value.length; i++) {\n    string += hexes[value[i]]\n  }\n  const hex = `0x${string}` as const\n\n  if (typeof opts.size === 'number') {\n    assertSize(hex, { size: opts.size })\n    return pad(hex, { dir: 'right', size: opts.size })\n  }\n  return hex\n}\n\nexport type NumberToHexOpts =\n  | {\n      /** Whether or not the number of a signed representation. */\n      signed?: boolean | undefined\n      /** The size (in bytes) of the output hex value. */\n      size: number\n    }\n  | {\n      signed?: undefined\n      /** The size (in bytes) of the output hex value. */\n      size?: number | undefined\n    }\n\nexport type NumberToHexErrorType =\n  | IntegerOutOfRangeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(\n  value_: number | bigint,\n  opts: NumberToHexOpts = {},\n): Hex {\n  const { signed, size } = opts\n\n  const value = BigInt(value_)\n\n  let maxValue: bigint | number | undefined\n  if (size) {\n    if (signed) maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n\n    else maxValue = 2n ** (BigInt(size) * 8n) - 1n\n  } else if (typeof value_ === 'number') {\n    maxValue = BigInt(Number.MAX_SAFE_INTEGER)\n  }\n\n  const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0\n\n  if ((maxValue && value > maxValue) || value < minValue) {\n    const suffix = typeof value_ === 'bigint' ? 'n' : ''\n    throw new IntegerOutOfRangeError({\n      max: maxValue ? `${maxValue}${suffix}` : undefined,\n      min: `${minValue}${suffix}`,\n      signed,\n      size,\n      value: `${value_}${suffix}`,\n    })\n  }\n\n  const hex = `0x${(\n    signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value\n  ).toString(16)}` as Hex\n  if (size) return pad(hex, { size }) as Hex\n  return hex\n}\n\nexport type StringToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number | undefined\n}\n\nexport type StringToHexErrorType = BytesToHexErrorType | ErrorType\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_: string, opts: StringToHexOpts = {}): Hex {\n  const value = encoder.encode(value_)\n  return bytesToHex(value, opts)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\nimport {\n  type NumberToHexErrorType,\n  type NumberToHexOpts,\n  numberToHex,\n} from './toHex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nexport type ToBytesParameters = {\n  /** Size of the output bytes. */\n  size?: number | undefined\n}\n\nexport type ToBytesErrorType =\n  | NumberToBytesErrorType\n  | BoolToBytesErrorType\n  | HexToBytesErrorType\n  | StringToBytesErrorType\n  | IsHexErrorType\n  | ErrorType\n\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(\n  value: string | bigint | number | boolean | Hex,\n  opts: ToBytesParameters = {},\n): ByteArray {\n  if (typeof value === 'number' || typeof value === 'bigint')\n    return numberToBytes(value, opts)\n  if (typeof value === 'boolean') return boolToBytes(value, opts)\n  if (isHex(value)) return hexToBytes(value, opts)\n  return stringToBytes(value, opts)\n}\n\nexport type BoolToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number | undefined\n}\n\nexport type BoolToBytesErrorType =\n  | AssertSizeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value: boolean, opts: BoolToBytesOpts = {}) {\n  const bytes = new Uint8Array(1)\n  bytes[0] = Number(value)\n  if (typeof opts.size === 'number') {\n    assertSize(bytes, { size: opts.size })\n    return pad(bytes, { size: opts.size })\n  }\n  return bytes\n}\n\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n  zero: 48,\n  nine: 57,\n  A: 65,\n  F: 70,\n  a: 97,\n  f: 102,\n} as const\n\nfunction charCodeToBase16(char: number) {\n  if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n    return char - charCodeMap.zero\n  if (char >= charCodeMap.A && char <= charCodeMap.F)\n    return char - (charCodeMap.A - 10)\n  if (char >= charCodeMap.a && char <= charCodeMap.f)\n    return char - (charCodeMap.a - 10)\n  return undefined\n}\n\nexport type HexToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number | undefined\n}\n\nexport type HexToBytesErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_: Hex, opts: HexToBytesOpts = {}): ByteArray {\n  let hex = hex_\n  if (opts.size) {\n    assertSize(hex, { size: opts.size })\n    hex = pad(hex, { dir: 'right', size: opts.size })\n  }\n\n  let hexString = hex.slice(2) as string\n  if (hexString.length % 2) hexString = `0${hexString}`\n\n  const length = hexString.length / 2\n  const bytes = new Uint8Array(length)\n  for (let index = 0, j = 0; index < length; index++) {\n    const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++))\n    const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++))\n    if (nibbleLeft === undefined || nibbleRight === undefined) {\n      throw new BaseError(\n        `Invalid byte sequence (\"${hexString[j - 2]}${\n          hexString[j - 1]\n        }\" in \"${hexString}\").`,\n      )\n    }\n    bytes[index] = nibbleLeft * 16 + nibbleRight\n  }\n  return bytes\n}\n\nexport type NumberToBytesErrorType =\n  | NumberToHexErrorType\n  | HexToBytesErrorType\n  | ErrorType\n\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(\n  value: bigint | number,\n  opts?: NumberToHexOpts | undefined,\n) {\n  const hex = numberToHex(value, opts)\n  return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number | undefined\n}\n\nexport type StringToBytesErrorType =\n  | AssertSizeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(\n  value: string,\n  opts: StringToBytesOpts = {},\n): ByteArray {\n  const bytes = encoder.encode(value)\n  if (typeof opts.size === 'number') {\n    assertSize(bytes, { size: opts.size })\n    return pad(bytes, { dir: 'right', size: opts.size })\n  }\n  return bytes\n}\n","import { keccak_256 } from '@noble/hashes/sha3'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Keccak256Hash<to extends To> =\n  | (to extends 'bytes' ? ByteArray : never)\n  | (to extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n  | IsHexErrorType\n  | ToBytesErrorType\n  | ToHexErrorType\n  | ErrorType\n\nexport function keccak256<to extends To = 'hex'>(\n  value: Hex | ByteArray,\n  to_?: to | undefined,\n): Keccak256Hash<to> {\n  const to = to_ || 'hex'\n  const bytes = keccak_256(\n    isHex(value, { strict: false }) ? toBytes(value) : value,\n  )\n  if (to === 'bytes') return bytes as Keccak256Hash<to>\n  return toHex(bytes) as Keccak256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n  | Keccak256ErrorType\n  | ToBytesErrorType\n  | ErrorType\n\nexport function hashSignature(sig: string) {\n  return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype NormalizeSignatureReturnType = string\nexport type NormalizeSignatureErrorType = ErrorType\n\nexport function normalizeSignature(\n  signature: NormalizeSignatureParameters,\n): NormalizeSignatureReturnType {\n  let active = true\n  let current = ''\n  let level = 0\n  let result = ''\n  let valid = false\n\n  for (let i = 0; i < signature.length; i++) {\n    const char = signature[i]\n\n    // If the character is a separator, we want to reactivate.\n    if (['(', ')', ','].includes(char)) active = true\n\n    // If the character is a \"level\" token, we want to increment/decrement.\n    if (char === '(') level++\n    if (char === ')') level--\n\n    // If we aren't active, we don't want to mutate the result.\n    if (!active) continue\n\n    // If level === 0, we are at the definition level.\n    if (level === 0) {\n      if (char === ' ' && ['event', 'function', ''].includes(result))\n        result = ''\n      else {\n        result += char\n\n        // If we are at the end of the definition, we must be finished.\n        if (char === ')') {\n          valid = true\n          break\n        }\n      }\n\n      continue\n    }\n\n    // Ignore spaces\n    if (char === ' ') {\n      // If the previous character is a separator, and the current section isn't empty, we want to deactivate.\n      if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {\n        current = ''\n        active = false\n      }\n      continue\n    }\n\n    result += char\n    current += char\n  }\n\n  if (!valid) throw new BaseError('Unable to normalize signature.')\n\n  return result\n}\n","import { type AbiEvent, type AbiFunction, formatAbiItem } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type NormalizeSignatureErrorType,\n  normalizeSignature,\n} from './normalizeSignature.js'\n\nexport type ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n *   name: 'ownerOf',\n *   type: 'function',\n *   inputs: [{ name: 'tokenId', type: 'uint256' }],\n *   outputs: [],\n *   stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n  const def_ = (() => {\n    if (typeof def === 'string') return def\n    return formatAbiItem(def)\n  })()\n  return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n  | HashSignatureErrorType\n  | ToSignatureErrorType\n  | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n  return hashSignature(toSignature(fn))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n  type ToSignatureHashErrorType,\n  toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n  maxSize: number\n\n  constructor(size: number) {\n    super()\n    this.maxSize = size\n  }\n\n  override get(key: string) {\n    const value = super.get(key)\n\n    if (super.has(key)) {\n      super.delete(key)\n      super.set(key, value as value)\n    }\n\n    return value\n  }\n\n  override set(key: string, value: value) {\n    if (super.has(key)) super.delete(key)\n    super.set(key, value)\n    if (this.maxSize && this.size > this.maxSize) {\n      const firstKey = super.keys().next().value\n      if (firstKey !== undefined) super.delete(firstKey)\n    }\n    return this\n  }\n}\n","import type { Address } from 'abitype'\n\nimport { InvalidAddressError } from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type StringToBytesErrorType,\n  stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap<Address>(8192)\n\nexport type ChecksumAddressErrorType =\n  | Keccak256ErrorType\n  | StringToBytesErrorType\n  | ErrorType\n\nexport function checksumAddress(\n  address_: Address,\n  /**\n   * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n   * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n   * that relies on EIP-55 checksum encoding (checksum without chainId).\n   *\n   * It is highly recommended to not use this feature unless you\n   * know what you are doing.\n   *\n   * See more: https://github.com/ethereum/EIPs/issues/1121\n   */\n  chainId?: number | undefined,\n): Address {\n  if (checksumAddressCache.has(`${address_}.${chainId}`))\n    return checksumAddressCache.get(`${address_}.${chainId}`)!\n\n  const hexAddress = chainId\n    ? `${chainId}${address_.toLowerCase()}`\n    : address_.substring(2).toLowerCase()\n  const hash = keccak256(stringToBytes(hexAddress), 'bytes')\n\n  const address = (\n    chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress\n  ).split('')\n  for (let i = 0; i < 40; i += 2) {\n    if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n      address[i] = address[i].toUpperCase()\n    }\n    if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n      address[i + 1] = address[i + 1].toUpperCase()\n    }\n  }\n\n  const result = `0x${address.join('')}` as const\n  checksumAddressCache.set(`${address_}.${chainId}`, result)\n  return result\n}\n\nexport type GetAddressErrorType =\n  | ChecksumAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\nexport function getAddress(\n  address: string,\n  /**\n   * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n   * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n   * that relies on EIP-55 checksum encoding (checksum without chainId).\n   *\n   * It is highly recommended to not use this feature unless you\n   * know what you are doing.\n   *\n   * See more: https://github.com/ethereum/EIPs/issues/1121\n   */\n  chainId?: number,\n): Address {\n  if (!isAddress(address, { strict: false }))\n    throw new InvalidAddressError({ address })\n  return checksumAddress(address, chainId)\n}\n","import {\n  SliceOffsetOutOfBoundsError,\n  type SliceOffsetOutOfBoundsErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\nimport { type SizeErrorType, size } from './size.js'\n\nexport type SliceReturnType<value extends ByteArray | Hex> = value extends Hex\n  ? Hex\n  : ByteArray\n\nexport type SliceErrorType =\n  | IsHexErrorType\n  | SliceBytesErrorType\n  | SliceHexErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice<value extends ByteArray | Hex>(\n  value: value,\n  start?: number | undefined,\n  end?: number | undefined,\n  { strict }: { strict?: boolean | undefined } = {},\n): SliceReturnType<value> {\n  if (isHex(value, { strict: false }))\n    return sliceHex(value as Hex, start, end, {\n      strict,\n    }) as SliceReturnType<value>\n  return sliceBytes(value as ByteArray, start, end, {\n    strict,\n  }) as SliceReturnType<value>\n}\n\nexport type AssertStartOffsetErrorType =\n  | SliceOffsetOutOfBoundsErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction assertStartOffset(value: Hex | ByteArray, start?: number | undefined) {\n  if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n    throw new SliceOffsetOutOfBoundsError({\n      offset: start,\n      position: 'start',\n      size: size(value),\n    })\n}\n\nexport type AssertEndOffsetErrorType =\n  | SliceOffsetOutOfBoundsErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction assertEndOffset(\n  value: Hex | ByteArray,\n  start?: number | undefined,\n  end?: number | undefined,\n) {\n  if (\n    typeof start === 'number' &&\n    typeof end === 'number' &&\n    size(value) !== end - start\n  ) {\n    throw new SliceOffsetOutOfBoundsError({\n      offset: end,\n      position: 'end',\n      size: size(value),\n    })\n  }\n}\n\nexport type SliceBytesErrorType =\n  | AssertStartOffsetErrorType\n  | AssertEndOffsetErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(\n  value_: ByteArray,\n  start?: number | undefined,\n  end?: number | undefined,\n  { strict }: { strict?: boolean | undefined } = {},\n): ByteArray {\n  assertStartOffset(value_, start)\n  const value = value_.slice(start, end)\n  if (strict) assertEndOffset(value, start, end)\n  return value\n}\n\nexport type SliceHexErrorType =\n  | AssertStartOffsetErrorType\n  | AssertEndOffsetErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(\n  value_: Hex,\n  start?: number | undefined,\n  end?: number | undefined,\n  { strict }: { strict?: boolean | undefined } = {},\n): Hex {\n  assertStartOffset(value_, start)\n  const value = `0x${value_\n    .replace('0x', '')\n    .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}` as const\n  if (strict) assertEndOffset(value, start, end)\n  return value\n}\n","import type {\n  AbiParameter,\n  AbiParameterKind,\n  AbiParametersToPrimitiveTypes,\n  AbiParameterToPrimitiveType,\n} from 'abitype'\n\nimport {\n  AbiEncodingArrayLengthMismatchError,\n  type AbiEncodingArrayLengthMismatchErrorType,\n  AbiEncodingBytesSizeMismatchError,\n  type AbiEncodingBytesSizeMismatchErrorType,\n  AbiEncodingLengthMismatchError,\n  type AbiEncodingLengthMismatchErrorType,\n  InvalidAbiEncodingTypeError,\n  type InvalidAbiEncodingTypeErrorType,\n  InvalidArrayError,\n  type InvalidArrayErrorType,\n} from '../../errors/abi.js'\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type PadHexErrorType, padHex } from '../data/pad.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n  type BoolToHexErrorType,\n  boolToHex,\n  type NumberToHexErrorType,\n  numberToHex,\n  type StringToHexErrorType,\n  stringToHex,\n} from '../encoding/toHex.js'\nimport { integerRegex } from '../regex.js'\n\nexport type EncodeAbiParametersReturnType = Hex\n\nexport type EncodeAbiParametersErrorType =\n  | AbiEncodingLengthMismatchErrorType\n  | PrepareParamsErrorType\n  | EncodeParamsErrorType\n  | ErrorType\n\n/**\n * @description Encodes a list of primitive values into an ABI-encoded hex value.\n *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n *   Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n *   [\n *     { name: 'x', type: 'string' },\n *     { name: 'y', type: 'uint' },\n *     { name: 'z', type: 'bool' }\n *   ],\n *   ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n *   parseAbiParameters('string x, uint y, bool z'),\n *   ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n  const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n  params: params,\n  values: params extends readonly AbiParameter[]\n    ? AbiParametersToPrimitiveTypes<params, AbiParameterKind, true>\n    : never,\n): EncodeAbiParametersReturnType {\n  if (params.length !== values.length)\n    throw new AbiEncodingLengthMismatchError({\n      expectedLength: params.length as number,\n      givenLength: values.length as any,\n    })\n  // Prepare the parameters to determine dynamic types to encode.\n  const preparedParams = prepareParams({\n    params: params as readonly AbiParameter[],\n    values: values as any,\n  })\n  return encodeParams(preparedParams)\n}\n\n/////////////////////////////////////////////////////////////////\n\ntype PreparedParam = { dynamic: boolean; encoded: Hex }\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\ntype Tuple = AbiParameterToPrimitiveType<TupleAbiParameter>\n\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams<const params extends readonly AbiParameter[]>({\n  params,\n  values,\n}: {\n  params: params\n  values: AbiParametersToPrimitiveTypes<params>\n}) {\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < params.length; i++) {\n    preparedParams.push(prepareParam({ param: params[i], value: values[i] }))\n  }\n  return preparedParams\n}\n\ntype PrepareParamErrorType =\n  | EncodeAddressErrorType\n  | EncodeArrayErrorType\n  | EncodeBytesErrorType\n  | EncodeBoolErrorType\n  | EncodeNumberErrorType\n  | EncodeStringErrorType\n  | EncodeTupleErrorType\n  | GetArrayComponentsErrorType\n  | InvalidAbiEncodingTypeErrorType\n  | ErrorType\n\nfunction prepareParam<const param extends AbiParameter>({\n  param,\n  value,\n}: {\n  param: param\n  value: AbiParameterToPrimitiveType<param>\n}): PreparedParam {\n  const arrayComponents = getArrayComponents(param.type)\n  if (arrayComponents) {\n    const [length, type] = arrayComponents\n    return encodeArray(value, { length, param: { ...param, type } })\n  }\n  if (param.type === 'tuple') {\n    return encodeTuple(value as unknown as Tuple, {\n      param: param as TupleAbiParameter,\n    })\n  }\n  if (param.type === 'address') {\n    return encodeAddress(value as unknown as Hex)\n  }\n  if (param.type === 'bool') {\n    return encodeBool(value as unknown as boolean)\n  }\n  if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n    const signed = param.type.startsWith('int')\n    const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n    return encodeNumber(value as unknown as number, {\n      signed,\n      size: Number(size),\n    })\n  }\n  if (param.type.startsWith('bytes')) {\n    return encodeBytes(value as unknown as Hex, { param })\n  }\n  if (param.type === 'string') {\n    return encodeString(value as unknown as string)\n  }\n  throw new InvalidAbiEncodingTypeError(param.type, {\n    docsPath: '/docs/contract/encodeAbiParameters',\n  })\n}\n\n/////////////////////////////////////////////////////////////////\n\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | ErrorType\n\nfunction encodeParams(preparedParams: PreparedParam[]): Hex {\n  // 1. Compute the size of the static part of the parameters.\n  let staticSize = 0\n  for (let i = 0; i < preparedParams.length; i++) {\n    const { dynamic, encoded } = preparedParams[i]\n    if (dynamic) staticSize += 32\n    else staticSize += size(encoded)\n  }\n\n  // 2. Split the parameters into static and dynamic parts.\n  const staticParams: Hex[] = []\n  const dynamicParams: Hex[] = []\n  let dynamicSize = 0\n  for (let i = 0; i < preparedParams.length; i++) {\n    const { dynamic, encoded } = preparedParams[i]\n    if (dynamic) {\n      staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }))\n      dynamicParams.push(encoded)\n      dynamicSize += size(encoded)\n    } else {\n      staticParams.push(encoded)\n    }\n  }\n\n  // 3. Concatenate static and dynamic parts.\n  // `concatHex` returns `'0x'` for empty input (zero-width parameters).\n  return concatHex([...staticParams, ...dynamicParams])\n}\n\n/////////////////////////////////////////////////////////////////\n\ntype EncodeAddressErrorType =\n  | InvalidAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\nfunction encodeAddress(value: Hex): PreparedParam {\n  if (!isAddress(value)) throw new InvalidAddressError({ address: value })\n  return { dynamic: false, encoded: padHex(value.toLowerCase() as Hex) }\n}\n\ntype EncodeArrayErrorType =\n  | AbiEncodingArrayLengthMismatchErrorType\n  | ConcatHexErrorType\n  | EncodeParamsErrorType\n  | InvalidArrayErrorType\n  | NumberToHexErrorType\n  // TODO: Add back once circular type reference is resolved\n  // | PrepareParamErrorType\n  | ErrorType\n\nfunction encodeArray<const param extends AbiParameter>(\n  value: AbiParameterToPrimitiveType<param>,\n  {\n    length,\n    param,\n  }: {\n    length: number | null\n    param: param\n  },\n): PreparedParam {\n  const dynamic = length === null\n\n  if (!Array.isArray(value)) throw new InvalidArrayError(value)\n  if (!dynamic && value.length !== length)\n    throw new AbiEncodingArrayLengthMismatchError({\n      expectedLength: length!,\n      givenLength: value.length,\n      type: `${param.type}[${length}]`,\n    })\n\n  // Zero-length fixed arrays of dynamic types (e.g. `string[0]`) are dynamic\n  // per the ABI spec, even though they have no elements to inspect.\n  let dynamicChild = value.length === 0 && isDynamicType(param)\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < value.length; i++) {\n    const preparedParam = prepareParam({ param, value: value[i] })\n    if (preparedParam.dynamic) dynamicChild = true\n    preparedParams.push(preparedParam)\n  }\n\n  if (dynamic || dynamicChild) {\n    const data = encodeParams(preparedParams)\n    if (dynamic) {\n      const length = numberToHex(preparedParams.length, { size: 32 })\n      return {\n        dynamic: true,\n        encoded: concatHex([length, data]),\n      }\n    }\n    if (dynamicChild) return { dynamic: true, encoded: data }\n  }\n  return {\n    dynamic: false,\n    encoded: concatHex(preparedParams.map(({ encoded }) => encoded)),\n  }\n}\n\ntype EncodeBytesErrorType =\n  | AbiEncodingBytesSizeMismatchErrorType\n  | ConcatHexErrorType\n  | PadHexErrorType\n  | NumberToHexErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction encodeBytes<const param extends AbiParameter>(\n  value: Hex,\n  { param }: { param: param },\n): PreparedParam {\n  const [, paramSize] = param.type.split('bytes')\n  const bytesSize = size(value)\n  if (!paramSize) {\n    let value_ = value\n    // If the size is not divisible by 32 bytes, pad the end\n    // with empty bytes to the ceiling 32 bytes.\n    if (bytesSize % 32 !== 0)\n      value_ = padHex(value_, {\n        dir: 'right',\n        size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n      })\n    return {\n      dynamic: true,\n      encoded: concatHex([\n        padHex(numberToHex(bytesSize, { size: 32 })),\n        value_,\n      ]),\n    }\n  }\n  if (bytesSize !== Number.parseInt(paramSize, 10))\n    throw new AbiEncodingBytesSizeMismatchError({\n      expectedSize: Number.parseInt(paramSize, 10),\n      value,\n    })\n  return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n  if (typeof value !== 'boolean')\n    throw new BaseError(\n      `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n    )\n  return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n  value: number,\n  { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n  if (typeof size === 'number') {\n    const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n    const min = signed ? -max - 1n : 0n\n    if (value > max || value < min)\n      throw new IntegerOutOfRangeError({\n        max: max.toString(),\n        min: min.toString(),\n        signed,\n        size: size / 8,\n        value: value.toString(),\n      })\n  }\n  return {\n    dynamic: false,\n    encoded: numberToHex(value, {\n      size: 32,\n      signed,\n    }),\n  }\n}\n\ntype EncodeStringErrorType =\n  | ConcatHexErrorType\n  | NumberToHexErrorType\n  | PadHexErrorType\n  | SizeErrorType\n  | SliceErrorType\n  | StringToHexErrorType\n  | ErrorType\n\nfunction encodeString(value: string): PreparedParam {\n  const hexValue = stringToHex(value)\n  const partsLength = Math.ceil(size(hexValue) / 32)\n  const parts: Hex[] = []\n  for (let i = 0; i < partsLength; i++) {\n    parts.push(\n      padHex(slice(hexValue, i * 32, (i + 1) * 32), {\n        dir: 'right',\n      }),\n    )\n  }\n  return {\n    dynamic: true,\n    encoded: concatHex([\n      padHex(numberToHex(size(hexValue), { size: 32 })),\n      ...parts,\n    ]),\n  }\n}\n\ntype EncodeTupleErrorType =\n  | ConcatHexErrorType\n  | EncodeParamsErrorType\n  // TODO: Add back once circular type reference is resolved\n  // | PrepareParamErrorType\n  | ErrorType\n\nfunction encodeTuple<\n  const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n  value: AbiParameterToPrimitiveType<param>,\n  { param }: { param: param },\n): PreparedParam {\n  let dynamic = false\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < param.components.length; i++) {\n    const param_ = param.components[i]\n    const index = Array.isArray(value) ? i : param_.name\n    const preparedParam = prepareParam({\n      param: param_,\n      value: (value as any)[index!] as readonly unknown[],\n    })\n    preparedParams.push(preparedParam)\n    if (preparedParam.dynamic) dynamic = true\n  }\n  return {\n    dynamic,\n    encoded: dynamic\n      ? encodeParams(preparedParams)\n      : concatHex(preparedParams.map(({ encoded }) => encoded)),\n  }\n}\n\ntype GetArrayComponentsErrorType = ErrorType\n\nexport function getArrayComponents(\n  type: string,\n): [length: number | null, innerType: string] | undefined {\n  const matches = type.match(/^(.*)\\[(\\d+)?\\]$/)\n  return matches\n    ? // Return `null` if the array is dynamic.\n      [matches[2] ? Number(matches[2]) : null, matches[1]]\n    : undefined\n}\n\nfunction isDynamicType(param: AbiParameter): boolean {\n  const { type } = param\n  if (type === 'string') return true\n  if (type === 'bytes') return true\n  if (type.endsWith('[]')) return true\n  if (type === 'tuple')\n    return (param as TupleAbiParameter).components.some(isDynamicType)\n  const arrayComponents = getArrayComponents(type)\n  if (arrayComponents)\n    return isDynamicType({ ...param, type: arrayComponents[1] })\n  return false\n}\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n  name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n  constructor({ offset }: { offset: number }) {\n    super(`Offset \\`${offset}\\` cannot be negative.`, {\n      name: 'NegativeOffsetError',\n    })\n  }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n  name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n  constructor({ length, position }: { length: number; position: number }) {\n    super(\n      `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n      { name: 'PositionOutOfBoundsError' },\n    )\n  }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n  RecursiveReadLimitExceededError & {\n    name: 'RecursiveReadLimitExceededError'\n  }\nexport class RecursiveReadLimitExceededError extends BaseError {\n  constructor({ count, limit }: { count: number; limit: number }) {\n    super(\n      `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n      { name: 'RecursiveReadLimitExceededError' },\n    )\n  }\n}\n","import {\n  NegativeOffsetError,\n  type NegativeOffsetErrorType,\n  PositionOutOfBoundsError,\n  type PositionOutOfBoundsErrorType,\n  RecursiveReadLimitExceededError,\n  type RecursiveReadLimitExceededErrorType,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n  bytes: ByteArray\n  dataView: DataView\n  position: number\n  positionReadCount: Map<number, number>\n  recursiveReadCount: number\n  recursiveReadLimit: number\n  remaining: number\n  assertReadLimit(position?: number): void\n  assertPosition(position: number): void\n  decrementPosition(offset: number): void\n  getReadCount(position?: number): number\n  incrementPosition(offset: number): void\n  inspectByte(position?: number): ByteArray[number]\n  inspectBytes(length: number, position?: number): ByteArray\n  inspectUint8(position?: number): number\n  inspectUint16(position?: number): number\n  inspectUint24(position?: number): number\n  inspectUint32(position?: number): number\n  pushByte(byte: ByteArray[number]): void\n  pushBytes(bytes: ByteArray): void\n  pushUint8(value: number): void\n  pushUint16(value: number): void\n  pushUint24(value: number): void\n  pushUint32(value: number): void\n  readByte(): ByteArray[number]\n  readBytes(length: number, size?: number): ByteArray\n  readUint8(): number\n  readUint16(): number\n  readUint24(): number\n  readUint32(): number\n  setPosition(position: number): () => void\n  _touch(): void\n}\n\ntype CursorErrorType =\n  | CursorAssertPositionErrorType\n  | CursorDecrementPositionErrorType\n  | CursorIncrementPositionErrorType\n  | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | ErrorType\n\ntype StaticCursorErrorType =\n  | NegativeOffsetErrorType\n  | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n  bytes: new Uint8Array(),\n  dataView: new DataView(new ArrayBuffer(0)),\n  position: 0,\n  positionReadCount: new Map(),\n  recursiveReadCount: 0,\n  recursiveReadLimit: Number.POSITIVE_INFINITY,\n  assertReadLimit() {\n    if (this.recursiveReadCount >= this.recursiveReadLimit)\n      throw new RecursiveReadLimitExceededError({\n        count: this.recursiveReadCount + 1,\n        limit: this.recursiveReadLimit,\n      })\n  },\n  assertPosition(position) {\n    if (position < 0 || position > this.bytes.length - 1)\n      throw new PositionOutOfBoundsError({\n        length: this.bytes.length,\n        position,\n      })\n  },\n  decrementPosition(offset) {\n    if (offset < 0) throw new NegativeOffsetError({ offset })\n    const position = this.position - offset\n    this.assertPosition(position)\n    this.position = position\n  },\n  getReadCount(position) {\n    return this.positionReadCount.get(position || this.position) || 0\n  },\n  incrementPosition(offset) {\n    if (offset < 0) throw new NegativeOffsetError({ offset })\n    const position = this.position + offset\n    this.assertPosition(position)\n    this.position = position\n  },\n  inspectByte(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position)\n    return this.bytes[position]\n  },\n  inspectBytes(length, position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + length - 1)\n    return this.bytes.subarray(position, position + length)\n  },\n  inspectUint8(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position)\n    return this.bytes[position]\n  },\n  inspectUint16(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 1)\n    return this.dataView.getUint16(position)\n  },\n  inspectUint24(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 2)\n    return (\n      (this.dataView.getUint16(position) << 8) +\n      this.dataView.getUint8(position + 2)\n    )\n  },\n  inspectUint32(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 3)\n    return this.dataView.getUint32(position)\n  },\n  pushByte(byte: ByteArray[number]) {\n    this.assertPosition(this.position)\n    this.bytes[this.position] = byte\n    this.position++\n  },\n  pushBytes(bytes: ByteArray) {\n    this.assertPosition(this.position + bytes.length - 1)\n    this.bytes.set(bytes, this.position)\n    this.position += bytes.length\n  },\n  pushUint8(value: number) {\n    this.assertPosition(this.position)\n    this.bytes[this.position] = value\n    this.position++\n  },\n  pushUint16(value: number) {\n    this.assertPosition(this.position + 1)\n    this.dataView.setUint16(this.position, value)\n    this.position += 2\n  },\n  pushUint24(value: number) {\n    this.assertPosition(this.position + 2)\n    this.dataView.setUint16(this.position, value >> 8)\n    this.dataView.setUint8(this.position + 2, value & ~4294967040)\n    this.position += 3\n  },\n  pushUint32(value: number) {\n    this.assertPosition(this.position + 3)\n    this.dataView.setUint32(this.position, value)\n    this.position += 4\n  },\n  readByte() {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectByte()\n    this.position++\n    return value\n  },\n  readBytes(length, size) {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectBytes(length)\n    this.position += size ?? length\n    return value\n  },\n  readUint8() {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectUint8()\n    this.position += 1\n    return value\n  },\n  readUint16() {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectUint16()\n    this.position += 2\n    return value\n  },\n  readUint24() {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectUint24()\n    this.position += 3\n    return value\n  },\n  readUint32() {\n    this.assertReadLimit()\n    this._touch()\n    const value = this.inspectUint32()\n    this.position += 4\n    return value\n  },\n  get remaining() {\n    return this.bytes.length - this.position\n  },\n  setPosition(position) {\n    const oldPosition = this.position\n    this.assertPosition(position)\n    this.position = position\n    return () => (this.position = oldPosition)\n  },\n  _touch() {\n    if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n    const count = this.getReadCount()\n    this.positionReadCount.set(this.position, count + 1)\n    if (count > 0) this.recursiveReadCount++\n  },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n  | CursorErrorType\n  | StaticCursorErrorType\n  | ErrorType\n\nexport function createCursor(\n  bytes: ByteArray,\n  { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n  const cursor: Cursor = Object.create(staticCursor)\n  cursor.bytes = bytes\n  cursor.dataView = new DataView(\n    bytes.buffer ?? bytes,\n    bytes.byteOffset,\n    bytes.byteLength,\n  )\n  cursor.positionReadCount = new Map()\n  cursor.recursiveReadLimit = recursiveReadLimit\n  return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n  type AssertSizeErrorType,\n  assertSize,\n  type HexToBigIntErrorType,\n  type HexToNumberErrorType,\n  hexToBigInt,\n  hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n  to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n  | to\n  | {\n      /** Size of the bytes. */\n      size?: number | undefined\n      /** Type to convert to. */\n      to: to\n    }\n\nexport type FromBytesReturnType<to> = to extends 'string'\n  ? string\n  : to extends 'hex'\n    ? Hex\n    : to extends 'bigint'\n      ? bigint\n      : to extends 'number'\n        ? number\n        : to extends 'boolean'\n          ? boolean\n          : never\n\nexport type FromBytesErrorType =\n  | BytesToHexErrorType\n  | BytesToBigIntErrorType\n  | BytesToBoolErrorType\n  | BytesToNumberErrorType\n  | BytesToStringErrorType\n  | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n *   new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n *   'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n  to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n  bytes: ByteArray,\n  toOrOpts: FromBytesParameters<to>,\n): FromBytesReturnType<to> {\n  const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n  const to = opts.to\n\n  if (to === 'number')\n    return bytesToNumber(bytes, opts) as FromBytesReturnType<to>\n  if (to === 'bigint')\n    return bytesToBigInt(bytes, opts) as FromBytesReturnType<to>\n  if (to === 'boolean')\n    return bytesToBool(bytes, opts) as FromBytesReturnType<to>\n  if (to === 'string')\n    return bytesToString(bytes, opts) as FromBytesReturnType<to>\n  return bytesToHex(bytes, opts) as FromBytesReturnType<to>\n}\n\nexport type BytesToBigIntOpts = {\n  /** Whether or not the number of a signed representation. */\n  signed?: boolean | undefined\n  /** Size of the bytes. */\n  size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n  | BytesToHexErrorType\n  | HexToBigIntErrorType\n  | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n  bytes: ByteArray,\n  opts: BytesToBigIntOpts = {},\n): bigint {\n  if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n  const hex = bytesToHex(bytes, opts)\n  return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n  /** Size of the bytes. */\n  size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n  | AssertSizeErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n  bytes_: ByteArray,\n  opts: BytesToBoolOpts = {},\n): boolean {\n  let bytes = bytes_\n  if (typeof opts.size !== 'undefined') {\n    assertSize(bytes, { size: opts.size })\n    bytes = trim(bytes)\n  }\n  if (bytes.length > 1 || bytes[0] > 1)\n    throw new InvalidBytesBooleanError(bytes)\n  return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n  | BytesToHexErrorType\n  | HexToNumberErrorType\n  | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n  bytes: ByteArray,\n  opts: BytesToNumberOpts = {},\n): number {\n  if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n  const hex = bytesToHex(bytes, opts)\n  return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n  /** Size of the bytes. */\n  size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n  | AssertSizeErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n  bytes_: ByteArray,\n  opts: BytesToStringOpts = {},\n): string {\n  let bytes = bytes_\n  if (typeof opts.size !== 'undefined') {\n    assertSize(bytes, { size: opts.size })\n    bytes = trim(bytes, { dir: 'right' })\n  }\n  return new TextDecoder().decode(bytes)\n}\n","import type {\n  AbiParameter,\n  AbiParameterKind,\n  AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n  AbiDecodingDataSizeTooSmallError,\n  AbiDecodingZeroDataError,\n  InvalidAbiDecodingTypeError,\n  type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n  type ChecksumAddressErrorType,\n  checksumAddress,\n} from '../address/getAddress.js'\nimport {\n  type CreateCursorErrorType,\n  type Cursor,\n  createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n  type BytesToBigIntErrorType,\n  type BytesToBoolErrorType,\n  type BytesToNumberErrorType,\n  type BytesToStringErrorType,\n  bytesToBigInt,\n  bytesToBool,\n  bytesToNumber,\n  bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n  params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n  params extends readonly AbiParameter[] ? params : AbiParameter[],\n  AbiParameterKind,\n  true\n>\n\nexport type DecodeAbiParametersErrorType =\n  | HexToBytesErrorType\n  | BytesToHexErrorType\n  | DecodeParameterErrorType\n  | SizeErrorType\n  | CreateCursorErrorType\n  | ErrorType\n\nexport function decodeAbiParameters<\n  const params extends readonly AbiParameter[],\n>(\n  params: params,\n  data: ByteArray | Hex,\n): DecodeAbiParametersReturnType<params> {\n  const bytes = typeof data === 'string' ? hexToBytes(data) : data\n  const cursor = createCursor(bytes)\n\n  if (size(bytes) === 0 && params.length > 0)\n    throw new AbiDecodingZeroDataError()\n  if (size(data) && size(data) < 32)\n    throw new AbiDecodingDataSizeTooSmallError({\n      data: typeof data === 'string' ? data : bytesToHex(data),\n      params: params as readonly AbiParameter[],\n      size: size(data),\n    })\n\n  let consumed = 0\n  const values = []\n  for (let i = 0; i < params.length; ++i) {\n    const param = params[i]\n    // Zero-width types (e.g. `uint256[0]`, empty tuples) at the end of the\n    // data consume no bytes, so the cursor may already be exhausted.\n    if (consumed < bytes.length) cursor.setPosition(consumed)\n    const [data, consumed_] = decodeParameter(cursor, param, {\n      staticPosition: 0,\n    })\n    consumed += consumed_\n    values.push(data)\n  }\n  return values as never\n}\n\ntype DecodeParameterErrorType =\n  | DecodeArrayErrorType\n  | DecodeTupleErrorType\n  | DecodeAddressErrorType\n  | DecodeBoolErrorType\n  | DecodeBytesErrorType\n  | DecodeNumberErrorType\n  | DecodeStringErrorType\n  | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n  cursor: Cursor,\n  param: AbiParameter,\n  { staticPosition }: { staticPosition: number },\n) {\n  const arrayComponents = getArrayComponents(param.type)\n  if (arrayComponents) {\n    const [length, type] = arrayComponents\n    return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n  }\n  if (param.type === 'tuple')\n    return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n  if (param.type === 'address') return decodeAddress(cursor)\n  if (param.type === 'bool') return decodeBool(cursor)\n  if (param.type.startsWith('bytes'))\n    return decodeBytes(cursor, param, { staticPosition })\n  if (param.type.startsWith('uint') || param.type.startsWith('int'))\n    return decodeNumber(cursor, param)\n  if (param.type === 'string') return decodeString(cursor, { staticPosition })\n  throw new InvalidAbiDecodingTypeError(param.type, {\n    docsPath: '/docs/contract/decodeAbiParameters',\n  })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n  | ChecksumAddressErrorType\n  | BytesToHexErrorType\n  | SliceBytesErrorType\n  | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n  const value = cursor.readBytes(32)\n  return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n  cursor: Cursor,\n  param: AbiParameter,\n  { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n  // If the length of the array is not known in advance (dynamic array),\n  // this means we will need to wonder off to the pointer and decode.\n  // Note: zero-length fixed arrays (`T[0]`) are not dynamic.\n  if (length === null) {\n    // Dealing with a dynamic type, so get the offset of the array data.\n    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n    // Start is the static position of current slot + offset.\n    const start = staticPosition + offset\n    const startOfData = start + sizeOfLength\n\n    // Get the length of the array from the offset.\n    cursor.setPosition(start)\n    const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n    // Check if the array has any dynamic children.\n    const dynamicChild = hasDynamicChild(param)\n\n    let consumed = 0\n    const value: unknown[] = []\n    for (let i = 0; i < length; ++i) {\n      // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n      // Otherwise, elements will be the size of their encoding (consumed bytes).\n      cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n      const [data, consumed_] = decodeParameter(cursor, param, {\n        staticPosition: startOfData,\n      })\n      consumed += consumed_\n      value.push(data)\n      // Charge zero-width elements against the read limit to bound work\n      // on huge lengths of zero-width types (e.g. `uint256[0][]`).\n      if (consumed_ === 0) {\n        cursor.assertReadLimit()\n        cursor._touch()\n      }\n    }\n\n    // As we have gone wondering, restore to the original position + next slot.\n    cursor.setPosition(staticPosition + 32)\n    return [value, 32]\n  }\n\n  // If the length of the array is known in advance,\n  // and the length of an element deeply nested in the array is not known,\n  // we need to decode the offset of the array data.\n  if (hasDynamicChild(param)) {\n    // Dealing with dynamic types, so get the offset of the array data.\n    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n    // Start is the static position of current slot + offset.\n    const start = staticPosition + offset\n\n    const value: unknown[] = []\n    for (let i = 0; i < length; ++i) {\n      // Move cursor along to the next slot (next offset pointer).\n      cursor.setPosition(start + i * 32)\n      const [data] = decodeParameter(cursor, param, {\n        staticPosition: start,\n      })\n      value.push(data)\n    }\n\n    // As we have gone wondering, restore to the original position + next slot.\n    cursor.setPosition(staticPosition + 32)\n    return [value, 32]\n  }\n\n  // If the length of the array is known in advance and the array is deeply static,\n  // then we can just decode each element in sequence.\n  let consumed = 0\n  const value: unknown[] = []\n  for (let i = 0; i < length; ++i) {\n    const [data, consumed_] = decodeParameter(cursor, param, {\n      staticPosition: staticPosition + consumed,\n    })\n    consumed += consumed_\n    value.push(data)\n    // Charge zero-width elements against the read limit to bound work\n    // on huge lengths of zero-width types (e.g. `uint256[0][4294967295]`).\n    if (consumed_ === 0) {\n      cursor.assertReadLimit()\n      cursor._touch()\n    }\n  }\n  return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n  return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n  | BytesToNumberErrorType\n  | BytesToHexErrorType\n  | ErrorType\n\nfunction decodeBytes(\n  cursor: Cursor,\n  param: AbiParameter,\n  { staticPosition }: { staticPosition: number },\n) {\n  const [_, size] = param.type.split('bytes')\n  if (!size) {\n    // Dealing with dynamic types, so get the offset of the bytes data.\n    const offset = bytesToNumber(cursor.readBytes(32))\n\n    // Set position of the cursor to start of bytes data.\n    cursor.setPosition(staticPosition + offset)\n\n    const length = bytesToNumber(cursor.readBytes(32))\n\n    // If there is no length, we have zero data.\n    if (length === 0) {\n      // As we have gone wondering, restore to the original position + next slot.\n      cursor.setPosition(staticPosition + 32)\n      return ['0x', 32]\n    }\n\n    const data = cursor.readBytes(length)\n\n    // As we have gone wondering, restore to the original position + next slot.\n    cursor.setPosition(staticPosition + 32)\n    return [bytesToHex(data), 32]\n  }\n\n  const value = bytesToHex(cursor.readBytes(Number.parseInt(size, 10), 32))\n  return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n  | BytesToNumberErrorType\n  | BytesToBigIntErrorType\n  | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n  const signed = param.type.startsWith('int')\n  const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n  const value = cursor.readBytes(32)\n  return [\n    size > 48\n      ? bytesToBigInt(value, { signed })\n      : bytesToNumber(value, { signed }),\n    32,\n  ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n  cursor: Cursor,\n  param: TupleAbiParameter,\n  { staticPosition }: { staticPosition: number },\n) {\n  // Tuples can have unnamed components (i.e. they are arrays), so we must\n  // determine whether the tuple is named or unnamed. In the case of a named\n  // tuple, the value will be an object where each property is the name of the\n  // component. In the case of an unnamed tuple, the value will be an array.\n  const hasUnnamedChild =\n    param.components.length === 0 || param.components.some(({ name }) => !name)\n\n  // Initialize the value to an object or an array, depending on whether the\n  // tuple is named or unnamed.\n  const value: any = hasUnnamedChild ? [] : {}\n  let consumed = 0\n\n  // If the tuple has a dynamic child, we must first decode the offset to the\n  // tuple data.\n  if (hasDynamicChild(param)) {\n    // Dealing with dynamic types, so get the offset of the tuple data.\n    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n    // Start is the static position of referencing slot + offset.\n    const start = staticPosition + offset\n\n    for (let i = 0; i < param.components.length; ++i) {\n      const component = param.components[i]\n      cursor.setPosition(start + consumed)\n      const [data, consumed_] = decodeParameter(cursor, component, {\n        staticPosition: start,\n      })\n      consumed += consumed_\n      value[hasUnnamedChild ? i : component?.name!] = data\n    }\n\n    // As we have gone wondering, restore to the original position + next slot.\n    cursor.setPosition(staticPosition + 32)\n    return [value, 32]\n  }\n\n  // If the tuple has static children, we can just decode each component\n  // in sequence.\n  for (let i = 0; i < param.components.length; ++i) {\n    const component = param.components[i]\n    const [data, consumed_] = decodeParameter(cursor, component, {\n      staticPosition,\n    })\n    value[hasUnnamedChild ? i : component?.name!] = data\n    consumed += consumed_\n  }\n  return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n  | BytesToNumberErrorType\n  | BytesToStringErrorType\n  | TrimErrorType\n  | ErrorType\n\nfunction decodeString(\n  cursor: Cursor,\n  { staticPosition }: { staticPosition: number },\n) {\n  // Get offset to start of string data.\n  const offset = bytesToNumber(cursor.readBytes(32))\n\n  // Start is the static position of current slot + offset.\n  const start = staticPosition + offset\n  cursor.setPosition(start)\n\n  const length = bytesToNumber(cursor.readBytes(32))\n\n  // If there is no length, we have zero data (empty string).\n  if (length === 0) {\n    cursor.setPosition(staticPosition + 32)\n    return ['', 32]\n  }\n\n  const data = cursor.readBytes(length, 32)\n  const value = bytesToString(trim(data))\n\n  // As we have gone wondering, restore to the original position + next slot.\n  cursor.setPosition(staticPosition + 32)\n\n  return [value, 32]\n}\n\nfunction hasDynamicChild(param: AbiParameter) {\n  const { type } = param\n  if (type === 'string') return true\n  if (type === 'bytes') return true\n  if (type.endsWith('[]')) return true\n\n  if (type === 'tuple') return (param as any).components?.some(hasDynamicChild)\n\n  const arrayComponents = getArrayComponents(param.type)\n  if (\n    arrayComponents &&\n    hasDynamicChild({ ...param, type: arrayComponents[1] } as AbiParameter)\n  )\n    return true\n\n  return false\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Core Type Definitions\n// ---------------------------------------------------------------------------\n// Agent = Prompt + Skills[] + MCP\n// All crypto-related \"wire\" fields (encryptedPayloadCid, eciesEncryptedKey)\n// live in IPFS metadata attributes → existing ERC8004 contracts are unchanged.\n// ---------------------------------------------------------------------------\n\n// ── JSON Schema (MCP standard subset) ──────────────────────────────────────\n\nexport interface JSONSchema {\n  type: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'integer' | 'null'\n  properties?: Record<string, JSONSchemaProperty>\n  required?: string[]\n  description?: string\n  items?: JSONSchema\n  enum?: (string | number | boolean | null)[]\n}\n\nexport interface JSONSchemaProperty {\n  type?: JSONSchema['type'] | JSONSchema['type'][]\n  description?: string\n  properties?: Record<string, JSONSchemaProperty>\n  required?: string[]\n  items?: JSONSchema\n  enum?: (string | number | boolean | null)[]\n  format?: string\n  default?: unknown\n}\n\n// ── Skill Definition ───────────────────────────────────────────────────────\n\n/**\n * A single skill module that an Agent exposes.\n * `inputSchema` and `outputSchema` follow MCP Tool JSON Schema conventions.\n */\nexport interface SkillDef {\n  /** Unique skill name (e.g. \"solidity_audit\") */\n  name: string\n  /** Human-readable description shown in the marketplace */\n  description: string\n  /** Semantic version of this skill */\n  version: string\n  /** JSON Schema for the tool's input parameters */\n  inputSchema: JSONSchema\n  /** JSON Schema for the tool's output return value */\n  outputSchema?: JSONSchema\n  /**\n   * Execution mode.\n   * - undefined / \"open\": Source is in the encrypted payload, runs locally.\n   * - { type: \"mcp\", toolName: \"...\" }: Source lives on the publisher's\n   *     MCP server.  Subscriber only gets Schema + remote execution endpoint.\n   *     MCP server verifies on-chain subscription on every call.\n   * - { type: \"a2a\", targetAgentId: 42 }: Delegates to another AgentX Agent.\n   *     The caller's AgentRunner loads + decrypts the target Agent, injects\n   *     its prompt into the LLM context, and exposes its skills as callable\n   *     tools.  This is the core Agent Composition primitive.\n   */\n  execution?: SkillExecutionRemote | A2ASkillExecution\n}\n\n/** Where the skill code actually runs. */\nexport type SkillExecutionMode = 'open' | 'mcp' | 'a2a'\n\nexport interface SkillExecutionRemote {\n  type: 'mcp'\n  /** MCP tool name on the publisher's server (e.g. \"run_strategy_abc123\") */\n  toolName: string\n  /** Optional: explicit MCP endpoint override */\n  endpoint?: string\n}\n\n/**\n * A2A Skill Execution — delegate to another AgentX Agent.\n *\n * Example: A \"trading\" Agent has a skill:\n *   execution: { type: \"a2a\", targetAgentId: 42 }\n * → When LLM calls this skill, AgentRunner loads Agent #42,\n *   decrypts its prompt+skills, and the sub-Agent runs in the\n *   same LLM conversation with its own system prompt.\n */\nexport interface A2ASkillExecution {\n  type: 'a2a'\n  /** On-chain Agent ID to delegate to */\n  targetAgentId: number\n  /** Optional: restrict which of the target Agent's skills are exposed */\n  skillFilter?: string[]\n  /** Optional: custom system prompt override for the sub-Agent */\n  promptOverride?: string\n}\n\n// ── MCP Connection ─────────────────────────────────────────────────────────\n\nexport type McpTransport = 'http' | 'sse' | 'stdio'\n\nexport interface McpConnection {\n  /** Transport type */\n  type: McpTransport\n  /** MCP server URL (required for http/sse) */\n  url?: string\n  /** Optional: limit which tools the Agent exposes to users */\n  toolFilter?: string[]\n  /** Optional: MCP server authentication header / key */\n  authHeader?: string\n}\n\n// ── Pricing ────────────────────────────────────────────────────────────────\n\nexport type PricingType = 'subscription' | 'pay_per_use' | 'free'\n\nexport interface AgentPricing {\n  type: PricingType\n  /** Amount in native unit (e.g. \"0.01\" for 0.01 ETH) */\n  amount: string\n  /** ERC20 token address, or empty for native currency */\n  currency: string\n  /** Billing period for subscriptions (e.g. \"month\", \"year\", \"day\") */\n  period?: string\n}\n\n// ── Agent Payload (the core data model) ────────────────────────────────────\n\n// ── Agent Category (application / use case) ─────────────────────────────────\n//\n// The application category of an agent. Marketplace and application launchers\n// (e.g. \"customer service\", \"airdrop tools\", \"quant strategies\") filter on this\n// field — agents without a category fall back to \"other\" for display purposes.\n// Publish flows MUST set it so the agent surfaces in the right application tab.\n\nexport const AGENT_CATEGORIES = [\n  'operations',          // 运营\n  'customer-service',    // 客服\n  'sales',               // 销售\n  'personal-assistant',  // 个人助理\n  'coding',              // 写代码 / 开发\n  'server-monitoring',   // 服务器监控\n  'airdrop',             // 空投\n  'quant-trading',       // 量化策略\n  'data-analysis',       // 数据分析\n  'content',             // 内容创作\n  'security',            // 安全\n  'finance',             // 金融\n  'other',               // 其他 / 未分类\n] as const\n\nexport type AgentCategory = (typeof AGENT_CATEGORIES)[number]\n\n/**\n * The complete Agent definition.\n *\n * - Fields above \"--- private payload ---\" are public (IPFS publicPayloadCid).\n * - Fields below are encrypted with AES-256-GCM and stored at encryptedPayloadCid.\n */\nexport interface AgentPayload {\n  // ── Public (visible in marketplace, stored at publicPayloadCid) ─────────\n  name: string\n  description: string\n  image?: string\n  version: string\n  tags: string[]\n  capabilities: string[]\n  supportedTasks: string[]\n  communicationProtocol: 'mcp' | 'a2a'\n  authenticationMethod: 'ecdsa'\n  pricing: AgentPricing\n  /**\n   * Application category / use case (see AGENT_CATEGORIES). Strongly\n   * recommended — marketplace and app launchers filter on it. Agents\n   * without a category are displayed under \"other\".\n   */\n  category?: AgentCategory\n\n  // ── Private (AES-256-GCM encrypted, stored at encryptedPayloadCid) ──────\n  prompt: string\n  skills: SkillDef[]\n  mcp: McpConnection\n}\n\n/** Subset of AgentPayload that is publicly visible */\nexport type AgentPublicPayload = Omit<\n  AgentPayload,\n  'prompt' | 'skills' | 'mcp'\n>\n\n/** Fields that must be encrypted before IPFS upload */\nexport type AgentPrivatePayload = Pick<\n  AgentPayload,\n  'prompt' | 'skills' | 'mcp'\n>\n\n// ── Encrypted Payload (IPFS wire format) ───────────────────────────────────\n\nexport interface EncryptedPayload {\n  encrypted: true\n  algorithm: 'AES-256-GCM'\n  /** base64(iv + ciphertext + authTag) */\n  data: string\n}\n\n// ── On-Chain Metadata (stored in ERC-721 tokenURI attributes) ─────────────\n\nexport interface OnChainAgentMetadata {\n  tokenURI: string\n  attributes: {\n    name: string\n    description: string\n    /** CID of the AES-256-GCM encrypted payload on IPFS */\n    encryptedPayloadCid: string\n    /** ECIES-encrypted AES key (secp256k1, hex string) */\n    eciesEncryptedKey: string\n    /** CID of the public metadata on IPFS */\n    publicPayloadCid: string\n    capabilities: string[]\n    skills: string[]\n    mcpEndpoint: string\n    version: string\n    tags: string[]\n    pricingType: PricingType\n    pricingAmount: string\n    /** Application category / use case (AGENT_CATEGORIES value). */\n    category?: string\n  }\n}\n\n// ── Agent Registry ─────────────────────────────────────────────────────────\n\nexport interface RegisteredAgent {\n  /** ERC-721 token ID (= agentId) */\n  agentId: number\n  /** Owner wallet address */\n  owner: string\n  /** Creator wallet address */\n  creator: string\n  /** Full on-chain metadata */\n  metadata: OnChainAgentMetadata\n  /** Block number where agent was registered */\n  registeredAt: number\n  /** IPFS CID of the full public payload (resolved from tokenURI) */\n  publicPayloadCid: string\n}\n\n// ── Agent Search ───────────────────────────────────────────────────────────\n\nexport interface AgentSearchQuery {\n  keyword?: string\n  capabilities?: string[]\n  tags?: string[]\n  pricingType?: PricingType\n  maxPrice?: string\n  owner?: string\n  sortBy?: 'latest' | 'reputation' | 'price_asc' | 'price_desc'\n  page?: number\n  pageSize?: number\n}\n\nexport interface AgentSearchResult {\n  agents: RegisteredAgent[]\n  total: number\n  page: number\n  pageSize: number\n}\n\n// ── Subscription ───────────────────────────────────────────────────────────\n\nexport type SubscriptionStatus = 'active' | 'expired' | 'cancelled' | 'pending'\n\nexport interface AgentSubscription {\n  subscriptionId: number\n  subscriber: string\n  agentId: number\n  status: SubscriptionStatus\n  startedAt: number\n  expiresAt: number\n  period: string\n}\n\n// ── A2A Protocol ───────────────────────────────────────────────────────────\n\nexport type A2ATaskStatus = 'created' | 'accepted' | 'in_progress' | 'completed' | 'failed'\n\nexport interface A2AAgentCard {\n  agentId: number\n  name: string\n  capabilities: string[]\n  supportedTasks: string[]\n  /** MCP endpoint URL for direct agent-to-agent communication */\n  endpoint: string\n  /** Public key for ECDSA authentication */\n  publicKey: string\n}\n\nexport interface A2ATask {\n  taskId: number\n  /** Agent that created the task */\n  creator: string\n  /** Target agent to execute the task */\n  targetAgentId: number\n  /** Task type (must be in target's supportedTasks) */\n  taskType: string\n  /** JSON input payload */\n  input: string\n  status: A2ATaskStatus\n  result?: string\n  createdAt: number\n  completedAt?: number\n}\n\n// ── Reputation ─────────────────────────────────────────────────────────────\n\nexport interface AgentReputation {\n  agentId: number\n  averageRating: number\n  totalRatings: number\n  reviews: AgentReview[]\n}\n\nexport interface AgentReview {\n  reviewer: string\n  rating: number // 1-5\n  comment: string\n  timestamp: number\n}\n\n// ── AgentX Client Configuration ────────────────────────────────────────────\n\nexport interface AgentXConfig {\n  /** Chain ID (e.g. 11155111 for Sepolia) */\n  chainId: number\n  /** RPC endpoint override (uses viem's default if omitted) */\n  rpcUrl?: string\n  /** Contract addresses for the current chain */\n  contracts: AgentXContracts\n  /** IPFS gateway URLs (ordered by priority) */\n  ipfsGateways: string[]\n  /** Default IPFS pinning service */\n  pinningService?: 'pinata'\n  pinataJwt?: string\n}\n\nexport interface AgentXContracts {\n  identityRegistry: `0x${string}`\n  subscriptionManager: `0x${string}`\n  a2aProtocolRegistry: `0x${string}`\n  reputationRegistry: `0x${string}`\n  configurationRegistry: `0x${string}`\n}\n\n// ── Agent Packing / Unpacking Result ───────────────────────────────────────\n\nexport interface PackResult {\n  /** CID of AES-256-GCM encrypted payload on IPFS */\n  encryptedCid: string\n  /** CID of public metadata on IPFS */\n  publicCid: string\n  /** Raw AES key (hex) — DO NOT share or upload this */\n  aesKeyHex: string\n  /** ECIES-encrypted AES key (hex), safe to store on-chain */\n  eciesEncryptedKeyHex: string\n}\n\nexport interface UnpackResult {\n  /** Decrypted AgentPayload */\n  agent: AgentPayload\n  /** CID where the encrypted payload was fetched from */\n  encryptedCid: string\n  /** CID of the public metadata */\n  publicCid: string\n}\n\n// ── Error Types ────────────────────────────────────────────────────────────\n\nexport enum AgentXErrorCode {\n  NOT_SUBSCRIBED = 'NOT_SUBSCRIBED',\n  SUBSCRIPTION_EXPIRED = 'SUBSCRIPTION_EXPIRED',\n  DECRYPTION_FAILED = 'DECRYPTION_FAILED',\n  IPFS_FETCH_FAILED = 'IPFS_FETCH_FAILED',\n  AGENT_NOT_FOUND = 'AGENT_NOT_FOUND',\n  INVALID_SCHEMA = 'INVALID_SCHEMA',\n  TX_FAILED = 'TX_FAILED',\n  WALLET_NOT_CONNECTED = 'WALLET_NOT_CONNECTED',\n}\n\nexport class AgentXError extends Error {\n  code: AgentXErrorCode\n  /** If NOT_SUBSCRIBED, carry enough info for wallet/X402 auto-payment */\n  paymentInfo?: SubscriptionRequired\n  constructor(code: AgentXErrorCode, message: string) {\n    super(message)\n    this.code = code\n    this.name = 'AgentXError'\n  }\n}\n\n/**\n * Structured info for wallet/X402 auto-subscription.\n * Thrown by AgentRunner.useAgent() when the user/Agent has no\n * active subscription.\n */\nexport interface SubscriptionRequired {\n  agentId: number\n  /** Plan IDs available for this Agent (on-chain query) */\n  plans?: { planId: number; price: bigint; period: string; payToken: string; trialDays: number }[]\n}\n","// @agentx/sdk — Core module\nexport * from './types'\nexport * from './crypto'\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n  type Abi,\n  type AbiEvent,\n  type AbiFunction,\n  type AbiParameter,\n  type AbiParameterKind,\n  type AbiParameterToPrimitiveType,\n  type AbiStateMutability,\n  type Address,\n  CircularReferenceError,\n  InvalidAbiItemError,\n  InvalidAbiParameterError,\n  InvalidAbiParametersError,\n  InvalidAbiTypeParameterError,\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  InvalidParameterError,\n  InvalidParenthesisError,\n  InvalidSignatureError,\n  InvalidStructSignatureError,\n  type Narrow,\n  type ParseAbi,\n  type ParseAbiItem,\n  type ParseAbiParameter,\n  type ParseAbiParameters,\n  parseAbi,\n  parseAbiItem,\n  parseAbiParameter,\n  parseAbiParameters,\n  SolidityProtectedKeywordError,\n  type TypedData,\n  type TypedDataDomain,\n  type TypedDataParameter,\n  UnknownSignatureError,\n  UnknownTypeError,\n} from 'abitype'\nexport type {\n  BlockOverrides,\n  Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n  RpcEstimateUserOperationGasReturnType,\n  RpcGetUserOperationByHashReturnType,\n  RpcUserOperation,\n  RpcUserOperationReceipt,\n  RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n  EstimateUserOperationGasReturnType,\n  GetUserOperationByHashReturnType,\n  PackedUserOperation,\n  UserOperation,\n  UserOperationReceipt,\n  UserOperationRequest,\n} from './account-abstraction/types/userOperation.js'\nexport type {\n  Account,\n  AccountSource,\n  CustomSource,\n  HDAccount,\n  HDOptions,\n  JsonRpcAccount,\n  LocalAccount,\n  PrivateKeyAccount,\n} from './accounts/types.js'\nexport type {\n  GetEnsAddressErrorType,\n  GetEnsAddressParameters,\n  GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n  GetEnsAvatarErrorType,\n  GetEnsAvatarParameters,\n  GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.js'\nexport type {\n  GetEnsNameErrorType,\n  GetEnsNameParameters,\n  GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n  GetEnsResolverErrorType,\n  GetEnsResolverParameters,\n  GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n  GetEnsTextErrorType,\n  GetEnsTextParameters,\n  GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n  type GetContractErrorType,\n  type GetContractParameters,\n  type GetContractReturnType,\n  getContract,\n} from './actions/getContract.js'\nexport type {\n  CallErrorType,\n  CallParameters,\n  CallReturnType,\n} from './actions/public/call.js'\nexport type {\n  CreateAccessListErrorType,\n  CreateAccessListParameters,\n  CreateAccessListReturnType,\n} from './actions/public/createAccessList.js'\nexport type {\n  CreateBlockFilterErrorType,\n  CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n  CreateContractEventFilterErrorType,\n  CreateContractEventFilterParameters,\n  CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n  CreateEventFilterErrorType,\n  CreateEventFilterParameters,\n  CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n  CreatePendingTransactionFilterErrorType,\n  CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n  EstimateContractGasErrorType,\n  EstimateContractGasParameters,\n  EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n  EstimateFeesPerGasErrorType,\n  EstimateFeesPerGasParameters,\n  EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n  EstimateGasErrorType,\n  EstimateGasParameters,\n  EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n  EstimateMaxPriorityFeePerGasErrorType,\n  EstimateMaxPriorityFeePerGasParameters,\n  EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n  FillTransactionErrorType,\n  FillTransactionParameters,\n  FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n  GetBalanceErrorType,\n  GetBalanceParameters,\n  GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n  GetBlobBaseFeeErrorType,\n  GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n  GetBlockErrorType,\n  GetBlockParameters,\n  GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n  GetBlockNumberErrorType,\n  GetBlockNumberParameters,\n  GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n  GetBlockReceiptsErrorType,\n  GetBlockReceiptsParameters,\n  GetBlockReceiptsReturnType,\n} from './actions/public/getBlockReceipts.js'\nexport type {\n  GetBlockTransactionCountErrorType,\n  GetBlockTransactionCountParameters,\n  GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n  GetChainIdErrorType,\n  GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n  /** @deprecated Use `GetCodeErrorType` instead */\n  GetCodeErrorType as GetBytecodeErrorType,\n  GetCodeErrorType,\n  /** @deprecated Use `GetCodeParameters` instead */\n  GetCodeParameters as GetBytecodeParameters,\n  GetCodeParameters,\n  /** @deprecated Use `GetCodeReturnType` instead  */\n  GetCodeReturnType as GetBytecodeReturnType,\n  GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n  GetContractEventsErrorType,\n  GetContractEventsParameters,\n  GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n  GetDelegationErrorType,\n  GetDelegationParameters,\n  GetDelegationReturnType,\n} from './actions/public/getDelegation.js'\nexport type {\n  GetEip712DomainErrorType,\n  GetEip712DomainParameters,\n  GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.js'\nexport type {\n  GetFeeHistoryErrorType,\n  GetFeeHistoryParameters,\n  GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n  GetFilterChangesErrorType,\n  GetFilterChangesParameters,\n  GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n  GetFilterLogsErrorType,\n  GetFilterLogsParameters,\n  GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n  GetGasPriceErrorType,\n  GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n  GetLogsErrorType,\n  GetLogsParameters,\n  GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n  GetProofErrorType,\n  GetProofParameters,\n  GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n  GetRawTransactionErrorType,\n  GetRawTransactionParameters,\n  GetRawTransactionReturnType,\n} from './actions/public/getRawTransaction.js'\nexport type {\n  GetStorageAtErrorType,\n  GetStorageAtParameters,\n  GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n  GetTransactionErrorType,\n  GetTransactionParameters,\n  GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n  GetTransactionConfirmationsErrorType,\n  GetTransactionConfirmationsParameters,\n  GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n  GetTransactionCountErrorType,\n  GetTransactionCountParameters,\n  GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n  GetTransactionReceiptErrorType,\n  GetTransactionReceiptParameters,\n  GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n  MulticallErrorType,\n  MulticallParameters,\n  MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n  ReadContractErrorType,\n  ReadContractParameters,\n  ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n  SimulateBlocksErrorType,\n  SimulateBlocksParameters,\n  SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n  SimulateCallsErrorType,\n  SimulateCallsParameters,\n  SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n  GetMutabilityAwareValue,\n  SimulateContractErrorType,\n  SimulateContractParameters,\n  SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n  UninstallFilterErrorType,\n  UninstallFilterParameters,\n  UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n  VerifyHashErrorType as VerifyHashActionErrorType,\n  VerifyHashParameters as VerifyHashActionParameters,\n  VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n  VerifyMessageErrorType as VerifyMessageActionErrorType,\n  VerifyMessageParameters as VerifyMessageActionParameters,\n  VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n  VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n  VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n  VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n  ReplacementReason,\n  ReplacementReturnType,\n  WaitForTransactionReceiptErrorType,\n  WaitForTransactionReceiptParameters,\n  WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n  OnBlockNumberFn,\n  OnBlockNumberParameter,\n  WatchBlockNumberErrorType,\n  WatchBlockNumberParameters,\n  WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n  OnBlock,\n  OnBlockParameter,\n  WatchBlocksErrorType,\n  WatchBlocksParameters,\n  WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n  WatchContractEventErrorType,\n  WatchContractEventOnLogsFn,\n  WatchContractEventOnLogsParameter,\n  WatchContractEventParameters,\n  WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n  WatchEventErrorType,\n  WatchEventOnLogsFn,\n  WatchEventOnLogsParameter,\n  WatchEventParameters,\n  WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n  OnTransactionsFn,\n  OnTransactionsParameter,\n  WatchPendingTransactionsErrorType,\n  WatchPendingTransactionsParameters,\n  WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n  DropTransactionErrorType,\n  DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n  DumpStateErrorType,\n  DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n  GetAutomineErrorType,\n  GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n  GetTxpoolContentErrorType,\n  GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n  GetTxpoolStatusErrorType,\n  GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n  ImpersonateAccountErrorType,\n  ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n  IncreaseTimeErrorType,\n  IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n  InspectTxpoolErrorType,\n  InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n  LoadStateErrorType,\n  LoadStateParameters,\n  LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n  RevertErrorType,\n  RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n  SendUnsignedTransactionErrorType,\n  SendUnsignedTransactionParameters,\n  SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.js'\nexport type {\n  SetBalanceErrorType,\n  SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n  SetBlockGasLimitErrorType,\n  SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n  SetBlockTimestampIntervalErrorType,\n  SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n  SetCodeErrorType,\n  SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n  SetCoinbaseErrorType,\n  SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n  SetIntervalMiningErrorType,\n  SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.js'\nexport type {\n  SetMinGasPriceErrorType,\n  SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n  SetNextBlockBaseFeePerGasErrorType,\n  SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n  SetNextBlockTimestampErrorType,\n  SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n  SetNonceErrorType,\n  SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n  SetStorageAtErrorType,\n  SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n  StopImpersonatingAccountErrorType,\n  StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n  AddChainErrorType,\n  AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n  DeployContractErrorType,\n  DeployContractParameters,\n  DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n  GetAddressesErrorType,\n  GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n  GetCallsStatusErrorType,\n  GetCallsStatusParameters,\n  GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n  GetCapabilitiesErrorType,\n  GetCapabilitiesParameters,\n  GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n  GetPermissionsErrorType,\n  GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n  PrepareAuthorizationErrorType,\n  PrepareAuthorizationParameters,\n  PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n  PrepareTransactionRequestErrorType,\n  PrepareTransactionRequestParameters,\n  PrepareTransactionRequestParameterType,\n  PrepareTransactionRequestRequest,\n  PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n  RequestAddressesErrorType,\n  RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n  RequestPermissionsErrorType,\n  RequestPermissionsParameters,\n  RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n  SendCallsErrorType,\n  SendCallsParameters,\n  SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n  SendCallsSyncErrorType,\n  SendCallsSyncParameters,\n  SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n  SendRawTransactionErrorType,\n  SendRawTransactionParameters,\n  SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n  SendRawTransactionSyncErrorType,\n  SendRawTransactionSyncParameters,\n  SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n  SendTransactionErrorType,\n  SendTransactionParameters,\n  SendTransactionRequest,\n  SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n  SendTransactionSyncErrorType,\n  SendTransactionSyncParameters,\n  SendTransactionSyncRequest,\n  SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n  ShowCallsStatusErrorType,\n  ShowCallsStatusParameters,\n  ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n  SignAuthorizationErrorType,\n  SignAuthorizationParameters,\n  SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n  SignMessageErrorType,\n  SignMessageParameters,\n  SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n  SignTransactionErrorType,\n  SignTransactionParameters,\n  SignTransactionRequest,\n  SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n  SignTypedDataErrorType,\n  SignTypedDataParameters,\n  SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n  SwitchChainErrorType,\n  SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n  WaitForCallsStatusErrorType,\n  WaitForCallsStatusParameters,\n  WaitForCallsStatusReturnType,\n  WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n  WatchAssetErrorType,\n  WatchAssetParameters,\n  WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n  WriteContractErrorType,\n  WriteContractParameters,\n  WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n  WriteContractSyncErrorType,\n  WriteContractSyncParameters,\n  WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n  type Client,\n  type ClientConfig,\n  type CreateClientErrorType,\n  createClient,\n  type MulticallBatchOptions,\n  rpcSchema,\n} from './clients/createClient.js'\nexport {\n  type CreatePublicClientErrorType,\n  createPublicClient,\n  type PublicClient,\n  type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n  type CreateTestClientErrorType,\n  createTestClient,\n  type TestClient,\n  type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n  type CreateWalletClientErrorType,\n  createWalletClient,\n  type WalletClient,\n  type WalletClientConfig,\n} from './clients/createWalletClient.js'\nexport {\n  type PublicActions,\n  publicActions,\n} from './clients/decorators/public.js'\nexport {\n  type TestActions,\n  testActions,\n} from './clients/decorators/test.js'\nexport {\n  type WalletActions,\n  walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n  type CreateTransportErrorType,\n  createTransport,\n  type Transport,\n  type TransportConfig,\n} from './clients/transports/createTransport.js'\nexport {\n  type CustomTransport,\n  type CustomTransportConfig,\n  type CustomTransportErrorType,\n  custom,\n} from './clients/transports/custom.js'\nexport {\n  type FallbackTransport,\n  type FallbackTransportConfig,\n  type FallbackTransportErrorType,\n  fallback,\n  shouldThrow,\n} from './clients/transports/fallback.js'\nexport {\n  type HttpTransport,\n  type HttpTransportConfig,\n  type HttpTransportErrorType,\n  http,\n} from './clients/transports/http.js'\nexport {\n  type WebSocketTransport,\n  type WebSocketTransportConfig,\n  type WebSocketTransportErrorType,\n  webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n  erc20Abi,\n  erc20Abi_bytes32,\n  erc721Abi,\n  erc1155Abi,\n  erc4626Abi,\n  erc6492SignatureValidatorAbi,\n  /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n  erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n  multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n  deploylessCallViaBytecodeBytecode,\n  deploylessCallViaFactoryBytecode,\n  erc6492SignatureValidatorByteCode,\n  /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n  erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.js'\nexport {\n  maxInt8,\n  maxInt16,\n  maxInt24,\n  maxInt32,\n  maxInt40,\n  maxInt48,\n  maxInt56,\n  maxInt64,\n  maxInt72,\n  maxInt80,\n  maxInt88,\n  maxInt96,\n  maxInt104,\n  maxInt112,\n  maxInt120,\n  maxInt128,\n  maxInt136,\n  maxInt144,\n  maxInt152,\n  maxInt160,\n  maxInt168,\n  maxInt176,\n  maxInt184,\n  maxInt192,\n  maxInt200,\n  maxInt208,\n  maxInt216,\n  maxInt224,\n  maxInt232,\n  maxInt240,\n  maxInt248,\n  maxInt256,\n  maxUint8,\n  maxUint16,\n  maxUint24,\n  maxUint32,\n  maxUint40,\n  maxUint48,\n  maxUint56,\n  maxUint64,\n  maxUint72,\n  maxUint80,\n  maxUint88,\n  maxUint96,\n  maxUint104,\n  maxUint112,\n  maxUint120,\n  maxUint128,\n  maxUint136,\n  maxUint144,\n  maxUint152,\n  maxUint160,\n  maxUint168,\n  maxUint176,\n  maxUint184,\n  maxUint192,\n  maxUint200,\n  maxUint208,\n  maxUint216,\n  maxUint224,\n  maxUint232,\n  maxUint240,\n  maxUint248,\n  maxUint256,\n  minInt8,\n  minInt16,\n  minInt24,\n  minInt32,\n  minInt40,\n  minInt48,\n  minInt56,\n  minInt64,\n  minInt72,\n  minInt80,\n  minInt88,\n  minInt96,\n  minInt104,\n  minInt112,\n  minInt120,\n  minInt128,\n  minInt136,\n  minInt144,\n  minInt152,\n  minInt160,\n  minInt168,\n  minInt176,\n  minInt184,\n  minInt192,\n  minInt200,\n  minInt208,\n  minInt216,\n  minInt224,\n  minInt232,\n  minInt240,\n  minInt248,\n  minInt256,\n} from './constants/number.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n  AbiConstructorNotFoundError,\n  type AbiConstructorNotFoundErrorType,\n  AbiConstructorParamsNotFoundError,\n  type AbiConstructorParamsNotFoundErrorType,\n  AbiDecodingDataSizeInvalidError,\n  type AbiDecodingDataSizeInvalidErrorType,\n  AbiDecodingDataSizeTooSmallError,\n  type AbiDecodingDataSizeTooSmallErrorType,\n  AbiDecodingZeroDataError,\n  type AbiDecodingZeroDataErrorType,\n  AbiEncodingArrayLengthMismatchError,\n  type AbiEncodingArrayLengthMismatchErrorType,\n  AbiEncodingBytesSizeMismatchError,\n  type AbiEncodingBytesSizeMismatchErrorType,\n  AbiEncodingLengthMismatchError,\n  type AbiEncodingLengthMismatchErrorType,\n  AbiErrorInputsNotFoundError,\n  type AbiErrorInputsNotFoundErrorType,\n  AbiErrorNotFoundError,\n  type AbiErrorNotFoundErrorType,\n  AbiErrorSignatureNotFoundError,\n  type AbiErrorSignatureNotFoundErrorType,\n  AbiEventNotFoundError,\n  type AbiEventNotFoundErrorType,\n  AbiEventSignatureEmptyTopicsError,\n  type AbiEventSignatureEmptyTopicsErrorType,\n  AbiEventSignatureNotFoundError,\n  type AbiEventSignatureNotFoundErrorType,\n  AbiFunctionNotFoundError,\n  type AbiFunctionNotFoundErrorType,\n  AbiFunctionOutputsNotFoundError,\n  type AbiFunctionOutputsNotFoundErrorType,\n  AbiFunctionSignatureNotFoundError,\n  type AbiFunctionSignatureNotFoundErrorType,\n  BytesSizeMismatchError,\n  type BytesSizeMismatchErrorType,\n  DecodeLogDataMismatch,\n  type DecodeLogDataMismatchErrorType,\n  DecodeLogTopicsMismatch,\n  type DecodeLogTopicsMismatchErrorType,\n  InvalidAbiDecodingTypeError,\n  type InvalidAbiDecodingTypeErrorType,\n  InvalidAbiEncodingTypeError,\n  type InvalidAbiEncodingTypeErrorType,\n  InvalidArrayError,\n  type InvalidArrayErrorType,\n  InvalidDefinitionTypeError,\n  type InvalidDefinitionTypeErrorType,\n  UnsupportedPackedAbiType,\n  type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n  BlockNotFoundError,\n  type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n  BundleFailedError,\n  type BundleFailedErrorType,\n} from './errors/calls.js'\nexport {\n  ChainDoesNotSupportContract,\n  type ChainDoesNotSupportContractErrorType,\n  ChainMismatchError,\n  type ChainMismatchErrorType,\n  ChainNotFoundError,\n  type ChainNotFoundErrorType,\n  ClientChainNotConfiguredError,\n  type ClientChainNotConfiguredErrorType,\n  InvalidChainIdError,\n  type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n  CallExecutionError,\n  type CallExecutionErrorType,\n  ContractFunctionExecutionError,\n  type ContractFunctionExecutionErrorType,\n  ContractFunctionRevertedError,\n  type ContractFunctionRevertedErrorType,\n  ContractFunctionZeroDataError,\n  type ContractFunctionZeroDataErrorType,\n  CounterfactualDeploymentFailedError,\n  type CounterfactualDeploymentFailedErrorType,\n  RawContractError,\n  type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n  SizeExceedsPaddingSizeError,\n  type SizeExceedsPaddingSizeErrorType,\n  SliceOffsetOutOfBoundsError,\n  type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n  IntegerOutOfRangeError,\n  type IntegerOutOfRangeErrorType,\n  InvalidBytesBooleanError,\n  type InvalidBytesBooleanErrorType,\n  InvalidHexBooleanError,\n  type InvalidHexBooleanErrorType,\n  InvalidHexValueError,\n  type InvalidHexValueErrorType,\n  RlpDepthLimitExceededError,\n  type RlpDepthLimitExceededErrorType,\n  RlpListBoundaryExceededError,\n  type RlpListBoundaryExceededErrorType,\n  RlpTrailingBytesError,\n  type RlpTrailingBytesErrorType,\n  SizeOverflowError,\n  type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n  type EnsAvatarInvalidMetadataError,\n  type EnsAvatarInvalidMetadataErrorType,\n  EnsAvatarInvalidNftUriError,\n  type EnsAvatarInvalidNftUriErrorType,\n  EnsAvatarUnsupportedNamespaceError,\n  type EnsAvatarUnsupportedNamespaceErrorType,\n  EnsAvatarUriResolutionError,\n  type EnsAvatarUriResolutionErrorType,\n  EnsInvalidChainIdError,\n  type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n  EstimateGasExecutionError,\n  type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n  BaseFeeScalarError,\n  type BaseFeeScalarErrorType,\n  Eip1559FeesNotSupportedError,\n  type Eip1559FeesNotSupportedErrorType,\n  MaxFeePerGasTooLowError,\n  type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n  FilterTypeNotSupportedError,\n  type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\n  ExecutionRevertedError,\n  type ExecutionRevertedErrorType,\n  FeeCapTooHighError,\n  type FeeCapTooHighErrorType,\n  FeeCapTooLowError,\n  type FeeCapTooLowErrorType,\n  InsufficientFundsError,\n  type InsufficientFundsErrorType,\n  IntrinsicGasTooHighError,\n  type IntrinsicGasTooHighErrorType,\n  IntrinsicGasTooLowError,\n  type IntrinsicGasTooLowErrorType,\n  NonceMaxValueError,\n  type NonceMaxValueErrorType,\n  NonceTooHighError,\n  type NonceTooHighErrorType,\n  NonceTooLowError,\n  type NonceTooLowErrorType,\n  TipAboveFeeCapError,\n  type TipAboveFeeCapErrorType,\n  TransactionTypeNotSupportedError,\n  type TransactionTypeNotSupportedErrorType,\n  UnknownNodeError,\n  type UnknownNodeErrorType,\n} from './errors/node.js'\nexport {\n  HttpRequestError,\n  type HttpRequestErrorType,\n  ResponseBodyTooLargeError,\n  type ResponseBodyTooLargeErrorType,\n  RpcRequestError,\n  type RpcRequestErrorType,\n  SocketClosedError,\n  type SocketClosedErrorType,\n  TimeoutError,\n  type TimeoutErrorType,\n  WebSocketRequestError,\n  type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n  AtomicityNotSupportedError,\n  type AtomicityNotSupportedErrorType,\n  AtomicReadyWalletRejectedUpgradeError,\n  type AtomicReadyWalletRejectedUpgradeErrorType,\n  BundleTooLargeError,\n  type BundleTooLargeErrorType,\n  ChainDisconnectedError,\n  type ChainDisconnectedErrorType,\n  DuplicateIdError,\n  type DuplicateIdErrorType,\n  InternalRpcError,\n  type InternalRpcErrorType,\n  InvalidInputRpcError,\n  type InvalidInputRpcErrorType,\n  InvalidParamsRpcError,\n  type InvalidParamsRpcErrorType,\n  InvalidRequestRpcError,\n  type InvalidRequestRpcErrorType,\n  JsonRpcVersionUnsupportedError,\n  type JsonRpcVersionUnsupportedErrorType,\n  LimitExceededRpcError,\n  type LimitExceededRpcErrorType,\n  MethodNotFoundRpcError,\n  type MethodNotFoundRpcErrorType,\n  MethodNotSupportedRpcError,\n  type MethodNotSupportedRpcErrorType,\n  ParseRpcError,\n  type ParseRpcErrorType,\n  ProviderDisconnectedError,\n  type ProviderDisconnectedErrorType,\n  ProviderRpcError,\n  type ProviderRpcErrorCode,\n  type ProviderRpcErrorType,\n  ResourceNotFoundRpcError,\n  type ResourceNotFoundRpcErrorType,\n  ResourceUnavailableRpcError,\n  type ResourceUnavailableRpcErrorType,\n  RpcError,\n  type RpcErrorCode,\n  type RpcErrorType,\n  SwitchChainError,\n  TransactionRejectedRpcError,\n  type TransactionRejectedRpcErrorType,\n  UnauthorizedProviderError,\n  type UnauthorizedProviderErrorType,\n  UnknownBundleIdError,\n  type UnknownBundleIdErrorType,\n  UnknownRpcError,\n  type UnknownRpcErrorType,\n  UnsupportedChainIdError,\n  type UnsupportedChainIdErrorType,\n  UnsupportedNonOptionalCapabilityError,\n  type UnsupportedNonOptionalCapabilityErrorType,\n  UnsupportedProviderMethodError,\n  type UnsupportedProviderMethodErrorType,\n  UserRejectedRequestError,\n  type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n  AccountStateConflictError,\n  type AccountStateConflictErrorType,\n  StateAssignmentConflictError,\n  type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.js'\nexport {\n  FeeConflictError,\n  type FeeConflictErrorType,\n  InvalidLegacyVError,\n  type InvalidLegacyVErrorType,\n  InvalidSerializableTransactionError,\n  type InvalidSerializableTransactionErrorType,\n  InvalidSerializedTransactionError,\n  type InvalidSerializedTransactionErrorType,\n  InvalidSerializedTransactionTypeError,\n  type InvalidSerializedTransactionTypeErrorType,\n  InvalidStorageKeySizeError,\n  type InvalidStorageKeySizeErrorType,\n  InvalidYParityError,\n  type InvalidYParityErrorType,\n  TransactionExecutionError,\n  type TransactionExecutionErrorType,\n  TransactionNotFoundError,\n  type TransactionNotFoundErrorType,\n  TransactionReceiptNotFoundError,\n  type TransactionReceiptNotFoundErrorType,\n  WaitForTransactionReceiptTimeoutError,\n  type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n  UrlRequiredError,\n  type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n  InvalidDomainError,\n  type InvalidDomainErrorType,\n  InvalidPrimaryTypeError,\n  type InvalidPrimaryTypeErrorType,\n  InvalidStructTypeError,\n  type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n  InvalidDecimalNumberError,\n  type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type { ResolvedToken, Tokens } from './tokens/defineToken.js'\nexport type {\n  DeriveAccount,\n  HDKey,\n  ParseAccount,\n} from './types/account.js'\nexport type {\n  Authorization,\n  AuthorizationList,\n  AuthorizationRequest,\n  SerializedAuthorization,\n  SerializedAuthorizationList,\n  SignedAuthorization,\n  SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n  Block,\n  BlockIdentifier,\n  BlockNumber,\n  BlockTag,\n  Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n  Capabilities,\n  /** @deprecated Use `Capabilities` instead. */\n  Capabilities as WalletCapabilities,\n  CapabilitiesSchema,\n  /** @deprecated Use `ChainIdToCapabilities` instead. */\n  ChainIdToCapabilities as WalletCapabilitiesRecord,\n  ChainIdToCapabilities,\n  ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n  Chain,\n  ChainConfig,\n  ChainContract,\n  ChainEstimateFeesPerGasFn,\n  ChainEstimateFeesPerGasFnParameters,\n  ChainFees,\n  ChainFeesFnParameters,\n  ChainFormatter,\n  ChainFormatters,\n  ChainMaxPriorityFeePerGasFn,\n  ChainSerializers,\n  DeriveChain,\n  ExtractChainFormatterExclude,\n  ExtractChainFormatterParameters,\n  ExtractChainFormatterReturnType,\n  GetChainParameter,\n} from './types/chain.js'\nexport type {\n  AbiEventParametersToPrimitiveTypes,\n  AbiEventParameterToPrimitiveType,\n  AbiEventTopicToPrimitiveType,\n  AbiItem,\n  AbiItemArgs,\n  AbiItemName,\n  ContractConstructorArgs,\n  ContractErrorArgs,\n  ContractErrorName,\n  ContractEventArgs,\n  ContractEventArgsFromTopics,\n  ContractEventName,\n  ContractFunctionArgs,\n  ContractFunctionName,\n  ContractFunctionParameters,\n  ContractFunctionReturnType,\n  EventDefinition,\n  ExtractAbiFunctionForArgs,\n  ExtractAbiItem,\n  ExtractAbiItemForArgs,\n  ExtractAbiItemNames,\n  GetEventArgs,\n  GetValue,\n  LogTopicType,\n  MaybeAbiEventName,\n  MaybeExtractEventArgsFromAbi,\n  UnionWiden,\n  Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n  AddEthereumChainParameter,\n  BundlerRpcSchema,\n  DebugBundlerRpcSchema,\n  EIP1193EventMap,\n  EIP1193Events,\n  EIP1193Parameters,\n  EIP1193Provider,\n  EIP1193RequestFn,\n  EIP1193RequestOptions,\n  EIP1474Methods,\n  NetworkSync,\n  PaymasterRpcSchema,\n  ProviderConnectInfo,\n  ProviderMessage,\n  ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n  PublicRpcSchema,\n  RpcSchema,\n  RpcSchemaOverride,\n  TestRpcSchema,\n  WalletCallReceipt,\n  WalletGetAssetsParameters,\n  WalletGetAssetsReturnType,\n  WalletGetCallsStatusReturnType,\n  WalletGrantPermissionsParameters,\n  WalletGrantPermissionsReturnType,\n  WalletPermission,\n  WalletPermissionCaveat,\n  WalletRpcSchema,\n  WalletSendCallsParameters,\n  WalletSendCallsReturnType,\n  WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n  FeeHistory,\n  FeeValues,\n  FeeValuesEIP1559,\n  FeeValuesEIP4844,\n  FeeValuesLegacy,\n  FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n  ByteArray,\n  CompactSignature,\n  Hash,\n  Hex,\n  LogTopic,\n  SignableMessage,\n  Signature,\n} from './types/misc.js'\nexport type {\n  MulticallContracts,\n  MulticallResponse,\n  MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n  Index,\n  Quantity,\n  RpcAccountStateOverride,\n  RpcAuthorization,\n  RpcAuthorizationList,\n  RpcBlock,\n  RpcBlockIdentifier,\n  RpcBlockNumber,\n  RpcFeeHistory,\n  RpcFeeValues,\n  RpcLog,\n  RpcProof,\n  RpcStateMapping,\n  RpcStateOverride,\n  RpcTransaction,\n  RpcTransactionReceipt,\n  RpcTransactionRequest,\n  RpcUncle,\n  Status,\n} from './types/rpc.js'\nexport type {\n  StateMapping,\n  StateOverride,\n} from './types/stateOverride.js'\nexport type {\n  AccessList,\n  Transaction,\n  TransactionBase,\n  TransactionEIP1559,\n  TransactionEIP2930,\n  TransactionEIP4844,\n  TransactionEIP7702,\n  TransactionLegacy,\n  TransactionReceipt,\n  TransactionRequest,\n  TransactionRequestBase,\n  TransactionRequestEIP1559,\n  TransactionRequestEIP2930,\n  TransactionRequestEIP4844,\n  TransactionRequestEIP7702,\n  TransactionRequestGeneric,\n  TransactionRequestLegacy,\n  TransactionSerializable,\n  TransactionSerializableBase,\n  TransactionSerializableEIP1559,\n  TransactionSerializableEIP2930,\n  TransactionSerializableEIP4844,\n  TransactionSerializableEIP7702,\n  TransactionSerializableGeneric,\n  TransactionSerializableLegacy,\n  TransactionSerialized,\n  TransactionSerializedEIP1559,\n  TransactionSerializedEIP2930,\n  TransactionSerializedEIP4844,\n  TransactionSerializedEIP7702,\n  TransactionSerializedGeneric,\n  TransactionSerializedLegacy,\n  TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n  EIP712DomainDefinition,\n  MessageDefinition,\n  TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n  Assign,\n  Branded,\n  Evaluate,\n  ExactPartial,\n  ExactRequired,\n  IsNarrowable,\n  IsNever,\n  IsUndefined,\n  IsUnion,\n  LooseOmit,\n  MaybePartial,\n  MaybePromise,\n  MaybeRequired,\n  Mutable,\n  NoInfer,\n  NoUndefined,\n  Omit,\n  OneOf,\n  Or,\n  PartialBy,\n  Prettify,\n  RequiredBy,\n  Some,\n  UnionEvaluate,\n  UnionLooseOmit,\n  UnionOmit,\n  UnionPartialBy,\n  UnionPick,\n  UnionRequiredBy,\n  UnionToTuple,\n  ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport {\n  type DecodeAbiParametersErrorType,\n  type DecodeAbiParametersReturnType,\n  decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n  type DecodeDeployDataErrorType,\n  type DecodeDeployDataParameters,\n  type DecodeDeployDataReturnType,\n  decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n  type DecodeErrorResultErrorType,\n  type DecodeErrorResultParameters,\n  type DecodeErrorResultReturnType,\n  decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n  type DecodeEventLogErrorType,\n  type DecodeEventLogParameters,\n  type DecodeEventLogReturnType,\n  decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n  type DecodeFunctionDataErrorType,\n  type DecodeFunctionDataParameters,\n  type DecodeFunctionDataReturnType,\n  decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n  type DecodeFunctionResultErrorType,\n  type DecodeFunctionResultParameters,\n  type DecodeFunctionResultReturnType,\n  decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n  type EncodeAbiParametersErrorType,\n  type EncodeAbiParametersReturnType,\n  encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n  type EncodeDeployDataErrorType,\n  type EncodeDeployDataParameters,\n  type EncodeDeployDataReturnType,\n  encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n  type EncodeErrorResultErrorType,\n  type EncodeErrorResultParameters,\n  type EncodeErrorResultReturnType,\n  encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n  type EncodeEventTopicsErrorType,\n  type EncodeEventTopicsParameters,\n  type EncodeEventTopicsReturnType,\n  encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  type EncodeFunctionDataReturnType,\n  encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n  type EncodeFunctionResultErrorType,\n  type EncodeFunctionResultParameters,\n  type EncodeFunctionResultReturnType,\n  encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n  type EncodePackedErrorType,\n  encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  type GetAbiItemReturnType,\n  getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n  type ParseEventLogsErrorType,\n  type ParseEventLogsParameters,\n  type ParseEventLogsReturnType,\n  parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n  type PrepareEncodeFunctionDataErrorType,\n  type PrepareEncodeFunctionDataParameters,\n  type PrepareEncodeFunctionDataReturnType,\n  prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n  type ChecksumAddressErrorType,\n  checksumAddress,\n  type GetAddressErrorType,\n  getAddress,\n} from './utils/address/getAddress.js'\nexport {\n  type GetContractAddressOptions,\n  type GetCreate2AddressErrorType,\n  type GetCreate2AddressOptions,\n  type GetCreateAddressErrorType,\n  type GetCreateAddressOptions,\n  getContractAddress,\n  getCreate2Address,\n  getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n  type IsAddressErrorType,\n  type IsAddressOptions,\n  isAddress,\n} from './utils/address/isAddress.js'\nexport {\n  type IsAddressEqualErrorType,\n  type IsAddressEqualReturnType,\n  isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n  type BlobsToCommitmentsErrorType,\n  type BlobsToCommitmentsParameters,\n  type BlobsToCommitmentsReturnType,\n  blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n  blobsToProofs,\n  type blobsToProofsErrorType,\n  type blobsToProofsParameters,\n  type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n  type CommitmentsToVersionedHashesErrorType,\n  type CommitmentsToVersionedHashesParameters,\n  type CommitmentsToVersionedHashesReturnType,\n  commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n  type CommitmentToVersionedHashErrorType,\n  type CommitmentToVersionedHashParameters,\n  type CommitmentToVersionedHashReturnType,\n  commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n  type FromBlobsErrorType,\n  type FromBlobsParameters,\n  type FromBlobsReturnType,\n  fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n  type SidecarsToVersionedHashesErrorType,\n  type SidecarsToVersionedHashesParameters,\n  type SidecarsToVersionedHashesReturnType,\n  sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n  type ToBlobSidecarsErrorType,\n  type ToBlobSidecarsParameters,\n  type ToBlobSidecarsReturnType,\n  toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n  type ToBlobsErrorType,\n  type ToBlobsParameters,\n  type ToBlobsReturnType,\n  toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n  type CcipRequestErrorType,\n  type CcipRequestParameters,\n  ccipRequest,\n  /** @deprecated Use `ccipRequest`. */\n  ccipRequest as ccipFetch,\n  type OffchainLookupErrorType,\n  offchainLookup,\n  offchainLookupAbiItem,\n  offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n  type CcipReadTunnelParameters,\n  ccipReadTunnel,\n} from './utils/ccipTunnel.js'\nexport {\n  type AssertCurrentChainErrorType,\n  type AssertCurrentChainParameters,\n  assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n  type DefineChainReturnType,\n  defineChain,\n  extendSchema,\n} from './utils/chain/defineChain.js'\nexport {\n  type ExtractChainErrorType,\n  type ExtractChainParameters,\n  type ExtractChainReturnType,\n  extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n  type ConcatBytesErrorType,\n  type ConcatErrorType,\n  type ConcatHexErrorType,\n  type ConcatReturnType,\n  concat,\n  concatBytes,\n  concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport {\n  type PadBytesErrorType,\n  type PadErrorType,\n  type PadHexErrorType,\n  type PadReturnType,\n  pad,\n  padBytes,\n  padHex,\n} from './utils/data/pad.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n  type SliceBytesErrorType,\n  type SliceErrorType,\n  type SliceHexErrorType,\n  slice,\n  sliceBytes,\n  sliceHex,\n} from './utils/data/slice.js'\nexport {\n  type TrimErrorType,\n  type TrimReturnType,\n  trim,\n} from './utils/data/trim.js'\nexport {\n  type BytesToBigIntErrorType,\n  type BytesToBigIntOpts,\n  type BytesToBoolErrorType,\n  type BytesToBoolOpts,\n  type BytesToNumberErrorType,\n  type BytesToNumberOpts,\n  type BytesToStringErrorType,\n  type BytesToStringOpts,\n  bytesToBigInt,\n  bytesToBool,\n  bytesToNumber,\n  bytesToString,\n  type FromBytesErrorType,\n  type FromBytesParameters,\n  fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n  type FromHexErrorType,\n  fromHex,\n  type HexToBigIntErrorType,\n  type HexToBoolErrorType,\n  type HexToNumberErrorType,\n  type HexToStringErrorType,\n  hexToBigInt,\n  hexToBool,\n  hexToNumber,\n  hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n  type FromRlpErrorType,\n  type FromRlpReturnType,\n  fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n  type BoolToBytesErrorType,\n  type BoolToBytesOpts,\n  boolToBytes,\n  type HexToBytesErrorType,\n  type HexToBytesOpts,\n  hexToBytes,\n  type NumberToBytesErrorType,\n  numberToBytes,\n  type StringToBytesErrorType,\n  type StringToBytesOpts,\n  stringToBytes,\n  type ToBytesErrorType,\n  type ToBytesParameters,\n  toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n  type BoolToHexErrorType,\n  type BoolToHexOpts,\n  type BytesToHexErrorType,\n  type BytesToHexOpts,\n  boolToHex,\n  bytesToHex,\n  type NumberToHexErrorType,\n  type NumberToHexOpts,\n  numberToHex,\n  type StringToHexErrorType,\n  type StringToHexOpts,\n  stringToHex,\n  type ToHexErrorType,\n  type ToHexParameters,\n  toHex,\n} from './utils/encoding/toHex.js'\nexport {\n  type BytesToRlpErrorType,\n  bytesToRlp,\n  type HexToRlpErrorType,\n  hexToRlp,\n  type ToRlpErrorType,\n  type ToRlpReturnType,\n  toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n  type ToCoinTypeError,\n  toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n  type DefineBlockErrorType,\n  defineBlock,\n  type FormatBlockErrorType,\n  type FormattedBlock,\n  formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n  type DefineTransactionErrorType,\n  defineTransaction,\n  type FormatTransactionErrorType,\n  type FormattedTransaction,\n  formatTransaction,\n  transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n  type DefineTransactionReceiptErrorType,\n  defineTransactionReceipt,\n  type FormatTransactionReceiptErrorType,\n  type FormattedTransactionReceipt,\n  formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n  type DefineTransactionRequestErrorType,\n  defineTransactionRequest,\n  type ExtractFormattedTransactionRequest,\n  type FormatTransactionRequestErrorType,\n  type FormattedTransactionRequest,\n  formatTransactionRequest,\n  rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n  type Keccak256ErrorType,\n  type Keccak256Hash,\n  keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n  type Ripemd160ErrorType,\n  type Ripemd160Hash,\n  ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n  type Sha256ErrorType,\n  type Sha256Hash,\n  sha256,\n} from './utils/hash/sha256.js'\nexport {\n  type ToEventHashErrorType,\n  toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n  type ToEventSelectorErrorType,\n  /** @deprecated use `ToEventSelectorErrorType`. */\n  type ToEventSelectorErrorType as GetEventSelectorErrorType,\n  toEventSelector,\n  /** @deprecated use `toEventSelector`. */\n  toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n  type ToEventSignatureErrorType,\n  /** @deprecated use `ToEventSignatureErrorType`. */\n  type ToEventSignatureErrorType as GetEventSignatureErrorType,\n  toEventSignature,\n  /** @deprecated use `toEventSignature`. */\n  toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n  type ToFunctionHashErrorType,\n  toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n  type ToFunctionSelectorErrorType,\n  /** @deprecated use `ToFunctionSelectorErrorType`. */\n  type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n  toFunctionSelector,\n  /** @deprecated use `toFunctionSelector`. */\n  toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n  type ToFunctionSignatureErrorType,\n  /** @deprecated use `ToFunctionSignatureErrorType`. */\n  type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n  toFunctionSignature,\n  /** @deprecated use `toFunctionSignature`. */\n  toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n  type DefineKzgErrorType,\n  type DefineKzgParameters,\n  type DefineKzgReturnType,\n  defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n  type SetupKzgErrorType,\n  type SetupKzgParameters,\n  type SetupKzgReturnType,\n  setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n  type CreateNonceManagerParameters,\n  createNonceManager,\n  type NonceManager,\n  type NonceManagerSource,\n  nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n  type WithRetryErrorType,\n  withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n  type WithTimeoutErrorType,\n  withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n  type CompactSignatureToSignatureErrorType,\n  compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n  type HashMessageErrorType,\n  hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n  type HashDomainErrorType,\n  type HashStructErrorType,\n  type HashTypedDataErrorType,\n  type HashTypedDataParameters,\n  type HashTypedDataReturnType,\n  hashDomain,\n  hashStruct,\n  hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n  type IsErc6492SignatureErrorType,\n  type IsErc6492SignatureParameters,\n  type IsErc6492SignatureReturnType,\n  isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n  type IsErc8010SignatureErrorType,\n  type IsErc8010SignatureParameters,\n  type IsErc8010SignatureReturnType,\n  isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n  /** @deprecated Use `ParseCompactSignatureErrorType`. */\n  type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n  type ParseCompactSignatureErrorType,\n  /** @deprecated Use `parseCompactSignature`. */\n  parseCompactSignature as hexToCompactSignature,\n  parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n  type ParseErc6492SignatureErrorType,\n  type ParseErc6492SignatureParameters,\n  type ParseErc6492SignatureReturnType,\n  parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n  type ParseErc8010SignatureErrorType,\n  type ParseErc8010SignatureParameters,\n  type ParseErc8010SignatureReturnType,\n  parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n  /** @deprecated Use `ParseSignatureErrorType`. */\n  type ParseSignatureErrorType as HexToSignatureErrorType,\n  type ParseSignatureErrorType,\n  /** @deprecated Use `parseSignature`. */\n  parseSignature as hexToSignature,\n  parseSignature,\n} from './utils/signature/parseSignature.js'\nexport {\n  type RecoverAddressErrorType,\n  type RecoverAddressParameters,\n  type RecoverAddressReturnType,\n  recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n  type RecoverMessageAddressErrorType,\n  type RecoverMessageAddressParameters,\n  type RecoverMessageAddressReturnType,\n  recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n  type RecoverPublicKeyErrorType,\n  type RecoverPublicKeyParameters,\n  type RecoverPublicKeyReturnType,\n  recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n  type RecoverTransactionAddressErrorType,\n  type RecoverTransactionAddressParameters,\n  type RecoverTransactionAddressReturnType,\n  recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n  type RecoverTypedDataAddressErrorType,\n  type RecoverTypedDataAddressParameters,\n  type RecoverTypedDataAddressReturnType,\n  recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n  /** @deprecated Use `SignatureToHexErrorType` instead. */\n  type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n  type SerializeCompactSignatureErrorType,\n  /** @deprecated Use `serializeCompactSignature` instead. */\n  serializeCompactSignature as compactSignatureToHex,\n  serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n  type SerializeErc6492SignatureErrorType,\n  type SerializeErc6492SignatureParameters,\n  type SerializeErc6492SignatureReturnType,\n  serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n  type SerializeErc8010SignatureErrorType,\n  type SerializeErc8010SignatureParameters,\n  type SerializeErc8010SignatureReturnType,\n  serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n  /** @deprecated Use `SignatureToHexErrorType` instead. */\n  type SerializeSignatureErrorType as SignatureToHexErrorType,\n  type SerializeSignatureErrorType,\n  type SerializeSignatureParameters,\n  type SerializeSignatureReturnType,\n  /** @deprecated Use `serializeSignature` instead. */\n  serializeSignature as signatureToHex,\n  serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n  type SignatureToCompactSignatureErrorType,\n  signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n  type ToPrefixedMessageErrorType,\n  toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n  type VerifyHashErrorType,\n  type VerifyHashParameters,\n  type VerifyHashReturnType,\n  verifyHash,\n} from './utils/signature/verifyHash.js'\nexport {\n  type VerifyMessageErrorType,\n  type VerifyMessageParameters,\n  type VerifyMessageReturnType,\n  verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n  type VerifyTypedDataErrorType,\n  type VerifyTypedDataParameters,\n  type VerifyTypedDataReturnType,\n  verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n  type AssertRequestErrorType,\n  assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n  type AssertTransactionEIP1559ErrorType,\n  type AssertTransactionEIP2930ErrorType,\n  type AssertTransactionLegacyErrorType,\n  assertTransactionEIP1559,\n  assertTransactionEIP2930,\n  assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n  type GetSerializedTransactionType,\n  type GetSerializedTransactionTypeErrorType,\n  getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n  type GetTransactionType,\n  type GetTransactionTypeErrorType,\n  getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n  type ParseTransactionErrorType,\n  type ParseTransactionReturnType,\n  parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n  type SerializeAccessListErrorType,\n  serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n  type SerializedTransactionReturnType,\n  type SerializeTransactionErrorType,\n  type SerializeTransactionFn,\n  serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n  type DomainSeparatorErrorType,\n  domainSeparator,\n  type GetTypesForEIP712DomainErrorType,\n  getTypesForEIP712Domain,\n  type SerializeTypedDataErrorType,\n  serializeTypedData,\n  type ValidateTypedDataErrorType,\n  validateTypedData,\n} from './utils/typedData.js'\nexport {\n  type FormatEtherErrorType,\n  formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n  type FormatGweiErrorType,\n  formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n  type FormatUnitsErrorType,\n  formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n  type ParseEtherErrorType,\n  parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n  type ParseUnitsErrorType,\n  parseUnits,\n} from './utils/unit/parseUnits.js'\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n  AbiDecodingDataSizeTooSmallError,\n  type AbiDecodingDataSizeTooSmallErrorType,\n  AbiEventSignatureEmptyTopicsError,\n  type AbiEventSignatureEmptyTopicsErrorType,\n  AbiEventSignatureNotFoundError,\n  type AbiEventSignatureNotFoundErrorType,\n  DecodeLogDataMismatch,\n  type DecodeLogDataMismatchErrorType,\n  DecodeLogTopicsMismatch,\n  type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n  ContractEventArgsFromTopics,\n  ContractEventName,\n  EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n  IsNarrowable,\n  Prettify,\n  UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n  type ToEventSelectorErrorType,\n  toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n  type DecodeAbiParametersErrorType,\n  decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n  abi extends Abi | readonly unknown[] = Abi,\n  eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n  topics extends Hex[] = Hex[],\n  data extends Hex | undefined = undefined,\n  strict extends boolean = true,\n> = {\n  abi: abi\n  data?: data | undefined\n  eventName?: eventName | ContractEventName<abi> | undefined\n  strict?: strict | boolean | undefined\n  topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n  abi extends Abi | readonly unknown[] = Abi,\n  eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n  topics extends Hex[] = Hex[],\n  data extends Hex | undefined = undefined,\n  strict extends boolean = true,\n  ///\n  allEventNames extends\n    ContractEventName<abi> = eventName extends ContractEventName<abi>\n    ? eventName\n    : ContractEventName<abi>,\n> = IsNarrowable<abi, Abi> extends true\n  ? {\n      [name in allEventNames]: Prettify<\n        {\n          eventName: name\n        } & UnionEvaluate<\n          ContractEventArgsFromTopics<abi, name, strict> extends infer allArgs\n            ? topics extends readonly []\n              ? data extends undefined\n                ? { args?: undefined }\n                : { args?: allArgs | undefined }\n              : { args: allArgs }\n            : never\n        >\n      >\n    }[allEventNames]\n  : {\n      eventName: eventName\n      args: readonly unknown[] | undefined\n    }\n\nexport type DecodeEventLogErrorType =\n  | AbiDecodingDataSizeTooSmallErrorType\n  | AbiEventSignatureEmptyTopicsErrorType\n  | AbiEventSignatureNotFoundErrorType\n  | DecodeAbiParametersErrorType\n  | DecodeLogTopicsMismatchErrorType\n  | DecodeLogDataMismatchErrorType\n  | FormatAbiItemErrorType\n  | ToEventSelectorErrorType\n  | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n  const abi extends Abi | readonly unknown[],\n  eventName extends ContractEventName<abi> | undefined = undefined,\n  topics extends Hex[] = Hex[],\n  data extends Hex | undefined = undefined,\n  strict extends boolean = true,\n>(\n  parameters: DecodeEventLogParameters<abi, eventName, topics, data, strict>,\n): DecodeEventLogReturnType<abi, eventName, topics, data, strict> {\n  const {\n    abi,\n    data,\n    strict: strict_,\n    topics,\n  } = parameters as DecodeEventLogParameters\n\n  const strict = strict_ ?? true\n  const [signature, ...argTopics] = topics\n  if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n  const abiItem = abi.find(\n    (x) =>\n      x.type === 'event' &&\n      signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n  )\n\n  if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n    throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n  const { name, inputs } = abiItem\n  const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n  const args: any = isUnnamed ? [] : {}\n\n  // Decode topics (indexed args).\n  const indexedInputs = inputs\n    .map((x, i) => [x, i] as const)\n    .filter(([x]) => 'indexed' in x && x.indexed)\n\n  const missingIndexedInputs: [AbiParameter, number][] = []\n\n  for (let i = 0; i < indexedInputs.length; i++) {\n    const [param, argIndex] = indexedInputs[i]\n    const topic = argTopics[i]\n    if (!topic) {\n      if (strict)\n        throw new DecodeLogTopicsMismatch({\n          abiItem,\n          param: param as AbiParameter & { indexed: boolean },\n        })\n      // Track missing indexed inputs to decode from data when strict is false\n      missingIndexedInputs.push([param, argIndex])\n      continue\n    }\n    args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n      param,\n      value: topic,\n    })\n  }\n\n  // Decode data (non-indexed args + missing indexed args when strict is false).\n  const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n  // When strict is false, missing indexed inputs should be decoded from data\n  const inputsToDecode = strict\n    ? nonIndexedInputs\n    : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n  if (inputsToDecode.length > 0) {\n    if (data && data !== '0x') {\n      try {\n        const decodedData = decodeAbiParameters(\n          inputsToDecode,\n          data,\n        ) as unknown[]\n        if (decodedData) {\n          let dataIndex = 0\n          // First, assign missing indexed parameters (when strict is false)\n          if (!strict) {\n            for (const [param, argIndex] of missingIndexedInputs) {\n              args[isUnnamed ? argIndex : param.name || argIndex] =\n                decodedData[dataIndex++]\n            }\n          }\n          // Then, assign non-indexed parameters\n          if (isUnnamed) {\n            for (let i = 0; i < inputs.length; i++)\n              if (args[i] === undefined && dataIndex < decodedData.length)\n                args[i] = decodedData[dataIndex++]\n          } else\n            for (let i = 0; i < nonIndexedInputs.length; i++)\n              args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n        }\n      } catch (err) {\n        if (strict) {\n          if (\n            err instanceof AbiDecodingDataSizeTooSmallError ||\n            err instanceof PositionOutOfBoundsError\n          )\n            throw new DecodeLogDataMismatch({\n              abiItem,\n              data: data,\n              params: inputsToDecode,\n              size: size(data),\n            })\n          throw err\n        }\n      }\n    } else if (strict) {\n      throw new DecodeLogDataMismatch({\n        abiItem,\n        data: '0x',\n        params: inputsToDecode,\n        size: 0,\n      })\n    }\n  }\n\n  return {\n    eventName: name,\n    args: Object.values(args).length > 0 ? args : undefined,\n  } as unknown as DecodeEventLogReturnType<abi, eventName, topics, data, strict>\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n  if (\n    param.type === 'string' ||\n    param.type === 'bytes' ||\n    param.type === 'tuple' ||\n    param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n  )\n    return value\n  const decodedArg = decodeAbiParameters([param], value) || []\n  return decodedArg[0]\n}\n","// biome-ignore lint/performance/noBarrelFile: intentional\nexport {\n  type ToSignatureHashErrorType as ToEventHashErrorType,\n  toSignatureHash as toEventHash,\n} from './toSignatureHash.js'\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — On-chain Event Listener\n// ---------------------------------------------------------------------------\n// Lightweight contract event subscription (Transfer / AgentRegistered on the\n// IdentityRegistry, PlanCreated / Subscribed on the SubscriptionManager).\n// Uses viem `watchContractEvent` in poll mode (works over any transport).\n// Replaces 2-minute polling loops with near-real-time event-driven sync.\n// ---------------------------------------------------------------------------\n\nimport { parseAbiItem } from 'viem'\nimport type { Address, Hash, PublicClient } from 'viem'\n\n// ── Event ABIs ─────────────────────────────────────────────────────────────\n\nconst TRANSFER_EVENT = parseAbiItem(\n  'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)'\n)\nconst AGENT_REGISTERED_EVENT = parseAbiItem(\n  'event AgentRegistered(uint256 indexed agentId, address indexed creator, string tokenURI)'\n)\nconst PLAN_CREATED_EVENT = parseAbiItem(\n  'event PlanCreated(uint256 indexed planId, uint256 indexed agentId, uint256 price, string period, address payToken, uint256 trialDays)'\n)\nconst SUBSCRIBED_EVENT = parseAbiItem(\n  'event Subscribed(uint256 indexed subscriptionId, address indexed subscriber, uint256 indexed agentId, uint256 expiresAt)'\n)\n\nconst EVENT_ABI = {\n  Transfer: TRANSFER_EVENT,\n  AgentRegistered: AGENT_REGISTERED_EVENT,\n  PlanCreated: PLAN_CREATED_EVENT,\n  Subscribed: SUBSCRIBED_EVENT,\n} as const\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type AgentXEventType = 'Transfer' | 'AgentRegistered' | 'PlanCreated' | 'Subscribed'\n\nexport interface AgentXChainEvent {\n  type: AgentXEventType\n  args: Record<string, unknown>\n  txHash: Hash\n}\n\nexport interface EventListenerOptions {\n  /** IdentityRegistry address (emits Transfer / AgentRegistered). */\n  identityRegistryAddress?: Address\n  /** SubscriptionManager address (emits PlanCreated / Subscribed). */\n  subscriptionManagerAddress?: Address\n  events: AgentXEventType[]\n  onEvent: (event: AgentXChainEvent) => void\n  /** Start listening from this block (default: latest). */\n  fromBlock?: number\n  /** Polling interval in ms (default: 4000). */\n  pollingInterval?: number\n}\n\n// Which events each contract can emit.\nconst CONTRACT_EVENTS: Record<'identityRegistryAddress' | 'subscriptionManagerAddress', readonly AgentXEventType[]> = {\n  identityRegistryAddress: ['Transfer', 'AgentRegistered'],\n  subscriptionManagerAddress: ['PlanCreated', 'Subscribed'],\n}\n\n// ── Listener ───────────────────────────────────────────────────────────────\n\n/**\n * Subscribe to AgentX contract events and receive a normalized callback.\n *\n * @returns A function that unsubscribes from all watched events.\n */\nexport function subscribeToEvents(\n  publicClient: PublicClient,\n  options: EventListenerOptions\n): Promise<() => void> {\n  const unwatchAll: (() => void)[] = []\n\n  const contracts = [\n    { address: options.identityRegistryAddress, events: CONTRACT_EVENTS.identityRegistryAddress },\n    { address: options.subscriptionManagerAddress, events: CONTRACT_EVENTS.subscriptionManagerAddress },\n  ]\n\n  for (const { address, events } of contracts) {\n    if (!address) continue\n    for (const eventName of events) {\n      if (!options.events.includes(eventName)) continue\n      unwatchAll.push(\n        publicClient.watchContractEvent({\n          address,\n          abi: [EVENT_ABI[eventName]],\n          eventName,\n          fromBlock: options.fromBlock !== undefined ? BigInt(options.fromBlock) : undefined,\n          pollingInterval: options.pollingInterval,\n          onLogs: (logs) => {\n            for (const log of logs) {\n              options.onEvent({\n                type: eventName,\n                args: log.args as Record<string, unknown>,\n                txHash: log.transactionHash,\n              })\n            }\n          },\n        })\n      )\n    }\n  }\n\n  return Promise.resolve(() => {\n    for (const unwatch of unwatchAll) unwatch()\n  })\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Agent Runner\n// ---------------------------------------------------------------------------\n// The unified entry point for \"using\" an Agent.\n//\n//   const runner = new AgentRunner({ reader, wallet })\n//   const ctx = await runner.useAgent(42)\n//   // ctx.prompt → system prompt for LLM\n//   // ctx.skills → [{ name, description, inputSchema, execute }]\n//   // ctx.mcp    → MCP connection info\n//\n//   对于 Open Skill：  直接本地执行（源码在解密后的 payload 里）\n//   对于 Closed Skill：通过 MCP 远程调用 → 发布者服务器执行 + 校验订阅\n// ---------------------------------------------------------------------------\n\nimport { eciesEncrypt, generateAesKey } from '../core/crypto'\nimport { unpackAgent } from '../core/crypto'\nimport { IPFSFetcher } from '../registry/ipfs-fetcher'\nimport type {\n  AgentPayload, AgentPrivatePayload,\n  EncryptedPayload, SkillDef,\n  PackResult, SubscriptionRequired,\n} from '../core/types'\nimport { AgentXError, AgentXErrorCode } from '../core/types'\n\n// ── Injected Dependencies (viem / wagmi integration) ───────────────────────\n\n/** Minimal on-chain reader interface — implement with viem. */\nexport interface OnChainReader {\n  /** Read tokenURI from IdentityRegistry by tokenId. */\n  getTokenURI(agentId: number): Promise<string>\n  /** Get agent metadata attributes (returned as key-value pairs). */\n  getAttributes(agentId: number): Promise<Record<string, string>>\n  /** Check if `address` has an active subscription for `agentId`. */\n  hasActiveSubscription(address: string, agentId: number): Promise<boolean>\n}\n\n/** Minimal wallet signer interface — implement with wagmi/viem. */\nexport interface WalletSigner {\n  /** Sign a message (for authentication to MCP servers). */\n  signMessage(message: string): Promise<string>\n  /** Get the current wallet address. */\n  getAddress(): Promise<string>\n  /** Get the wallet's ECDSA private key (required for ECIES decryption). */\n  getPrivateKey?(): Promise<string>\n}\n\n// ── Agent Runner Configuration ─────────────────────────────────────────────\n\nexport interface AgentRunnerConfig {\n  /** On-chain data reader (injected from viem/wagmi). */\n  reader: OnChainReader\n  /** Wallet signer (injected from wagmi). */\n  wallet: WalletSigner\n  /** IPFS fetcher instance (creates default if omitted). */\n  ipfsFetcher?: IPFSFetcher\n  /** IPFS gateway list (overrides IPFSFetcher defaults). */\n  ipfsGateways?: string[]\n}\n\n// ── Run Context (returned by useAgent) ─────────────────────────────────────\n\nexport interface AgentRunContext {\n  /** Agent NFT token ID */\n  agentId: number\n  /** System prompt — inject into LLM conversation */\n  prompt: string\n  /** All skills with execution metadata */\n  skills: RunnableSkill[]\n  /** MCP connection info */\n  mcp: {\n    type: string\n    url?: string\n    toolFilter?: string[]\n  }\n  /** Subscription expiry timestamp (0 = unknown) */\n  subscriptionExpiry: number\n}\n\nexport interface RunnableSkill {\n  name: string\n  description: string\n  inputSchema: Record<string, unknown>\n  outputSchema?: Record<string, unknown>\n  /** Execution mode */\n  mode: 'open' | 'mcp' | 'a2a'\n  /** If mode='a2a', the on-chain Agent ID being delegated to */\n  a2aTargetAgentId?: number\n  /**\n   * Execute this skill with the given input.\n   * - Open: runs locally (caller provides implementation)\n   * - MCP: POSTs to the publisher's MCP server\n   * - A2A: loads target Agent context (prompt+skills) via AgentRunner\n   */\n  execute(input: Record<string, unknown>): Promise<unknown>\n}\n\n// ── A2A Delegation Result ────────────────────────────────────────────────\n\n/**\n * Standard return type for A2A skill execution.\n * The calling LLM receives the sub-Agent's prompt and skills\n * and can inject them into the conversation.\n */\nexport interface A2ASkillResult {\n  /** On-chain Agent ID that was delegated to */\n  agentId: number\n  /** Sub-Agent's decrypted system prompt */\n  prompt: string\n  /** Sub-Agent's skills (name + description + schema only, no execute) */\n  skills: {\n    name: string\n    description: string\n    inputSchema: Record<string, unknown>\n  }[]\n  /** The original input passed by the caller */\n  callerInput: Record<string, unknown>\n}\n\n// ── Agent Runner ───────────────────────────────────────────────────────────\n\nexport class AgentRunner {\n  private reader: OnChainReader\n  private wallet: WalletSigner\n  private ipfs: IPFSFetcher\n\n  constructor(config: AgentRunnerConfig) {\n    this.reader = config.reader\n    this.wallet = config.wallet\n    this.ipfs = config.ipfsFetcher ?? new IPFSFetcher({\n      fallbackGateways: config.ipfsGateways ?? [\n        'gateway.pinata.cloud',\n        'dweb.link',\n        'cf-ipfs.com',\n      ],\n    })\n  }\n\n  // ── Primary API: useAgent ────────────────────────────────────────────────\n\n  /**\n   * Load and decrypt an Agent, returning a run context ready to inject\n   * into any LLM conversation.\n   *\n   * Steps:\n   *   1. Verify on-chain subscription (frontend check)\n   *   2. Fetch metadata → get encryptedPayloadCid + eciesEncryptedKey\n   *   3. IPFS fetch encrypted payload\n   *   4. ECIES decrypt AES key (using wallet private key)\n   *   5. AES-256-GCM decrypt payload → { prompt, skills, mcp }\n   *   6. Build RunnableSkill wrappers (Open: local stub, Closed: MCP remote)\n   */\n  async useAgent(agentId: number): Promise<AgentRunContext> {\n    // 1. Subscription check (frontend — MCP server also checks)\n    const address = await this.wallet.getAddress()\n    const isActive = await this.reader.hasActiveSubscription(address, agentId)\n    if (!isActive) {\n      const err = new AgentXError(\n        AgentXErrorCode.NOT_SUBSCRIBED,\n        `No active subscription for Agent #${agentId}. ` +\n        `Check error.paymentInfo for auto-subscribe via wallet/X402.`,\n      )\n      ;(err as AgentXError & { paymentInfo: SubscriptionRequired }).paymentInfo = {\n        agentId,\n      }\n      throw err\n    }\n\n    // 2. Read on-chain metadata\n    const attrs = await this.reader.getAttributes(agentId)\n    const encryptedPayloadCid = attrs.encryptedPayloadCid\n    const eciesEncryptedKey = attrs.eciesEncryptedKey\n\n    if (!encryptedPayloadCid || !eciesEncryptedKey) {\n      throw new AgentXError(\n        AgentXErrorCode.AGENT_NOT_FOUND,\n        `Agent #${agentId} metadata incomplete — missing encryptedPayloadCid or eciesEncryptedKey`\n      )\n    }\n\n    // 3. Fetch encrypted payload from IPFS\n    let encryptedPayload: EncryptedPayload\n    try {\n      encryptedPayload = await this.ipfs.fetchEncryptedPayload(encryptedPayloadCid)\n    } catch (e) {\n      throw new AgentXError(\n        AgentXErrorCode.IPFS_FETCH_FAILED,\n        `Failed to fetch encrypted payload for agent #${agentId}: ${e}`\n      )\n    }\n\n    // 4 + 5. ECIES + AES decrypt\n    let privatePayload: AgentPrivatePayload\n    try {\n      const privKey = await this._getPrivateKey()\n      privatePayload = unpackAgent(encryptedPayload, eciesEncryptedKey, privKey)\n    } catch (e) {\n      throw new AgentXError(\n        AgentXErrorCode.DECRYPTION_FAILED,\n        `Failed to decrypt agent #${agentId}: ${e}`\n      )\n    }\n\n    // 6. Build runnable skills\n    const skills = privatePayload.skills.map(s => this._wrapSkill(s))\n\n    return {\n      agentId,\n      prompt: privatePayload.prompt,\n      skills,\n      mcp: {\n        type: privatePayload.mcp.type,\n        url: privatePayload.mcp.url,\n        toolFilter: privatePayload.mcp.toolFilter,\n      },\n      subscriptionExpiry: 0,\n    }\n  }\n\n  // ── Publishing ───────────────────────────────────────────────────────────\n\n  /**\n   * Pack an AgentPayload for publishing (encryption only, no IPFS upload).\n   * Caller is responsible for IPFS upload and on-chain registration.\n   */\n  packForPublish(payload: AgentPayload, publicKey: string): PackResult {\n    const key = generateAesKey()\n    return {\n      encryptedCid: '',\n      publicCid: '',\n      aesKeyHex: key,\n      eciesEncryptedKeyHex: eciesEncrypt(key, publicKey),\n    }\n  }\n\n  // ── Internals ────────────────────────────────────────────────────────────\n\n  /** Wrap a SkillDef into a RunnableSkill with execute(). */\n  private _wrapSkill(skill: SkillDef): RunnableSkill {\n    let mode: RunnableSkill['mode'] = 'open'\n    let executeFn: (input: Record<string, unknown>) => Promise<unknown>\n\n    if (skill.execution) {\n      if (skill.execution.type === 'mcp') {\n        mode = 'mcp'\n        const endpoint = skill.execution.endpoint ?? ''\n        const toolName = skill.execution.toolName ?? skill.name\n        executeFn = async (input: Record<string, unknown>) => {\n          return this._executeMCPTool(endpoint, toolName, input)\n        }\n      } else if (skill.execution.type === 'a2a') {\n        mode = 'a2a'\n        executeFn = async (input: Record<string, unknown>) => {\n          return this._executeA2ASkill(skill, input)\n        }\n      } else {\n        throw new AgentXError(\n          AgentXErrorCode.INVALID_SCHEMA,\n          `Unknown execution type \"${(skill.execution as Record<string,string>).type}\" for skill \"${skill.name}\"`\n        )\n      }\n    } else {\n      executeFn = async () => {\n        throw new AgentXError(\n          AgentXErrorCode.INVALID_SCHEMA,\n          `Open skill \"${skill.name}\" has no local executor. ` +\n          `Implement execute() or switch to execution.type = \"mcp\" or \"a2a\".`\n        )\n      }\n    }\n\n    return {\n      name: skill.name,\n      description: skill.description,\n      inputSchema: skill.inputSchema as unknown as Record<string, unknown>,\n      outputSchema: skill.outputSchema as unknown as Record<string, unknown>,\n      mode,\n      execute: executeFn,\n      /** If A2A, carry delegation metadata so the LLM can see it */\n      a2aTargetAgentId: skill.execution?.type === 'a2a' ? (skill.execution as import('../core/types').A2ASkillExecution).targetAgentId : undefined,\n    }\n  }\n\n  /** Call a tool on the publisher's MCP server (Closed skill). */\n  private async _executeMCPTool(\n    endpoint: string,\n    toolName: string,\n    params: Record<string, unknown>\n  ): Promise<unknown> {\n    const address = await this.wallet.getAddress()\n\n    const timestamp = Math.floor(Date.now() / 1000)\n    const message = `agentx:mcp:${toolName}:${timestamp}`\n    const signature = await this.wallet.signMessage(message)\n\n    const res = await fetch(endpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        'X-Subscriber-Address': address,\n        'X-Signature': signature,\n        'X-Timestamp': String(timestamp),\n      },\n      body: JSON.stringify({\n        method: 'tools/call',\n        params: {\n          name: toolName,\n          arguments: params,\n        },\n      }),\n    })\n\n    if (!res.ok) {\n      const text = await res.text()\n      if (res.status === 403) {\n        throw new AgentXError(\n          AgentXErrorCode.SUBSCRIPTION_EXPIRED,\n          `MCP server rejected request: subscription may have expired. ${text}`\n        )\n      }\n      throw new AgentXError(\n        AgentXErrorCode.TX_FAILED,\n        `MCP tool \"${toolName}\" failed (HTTP ${res.status}): ${text}`\n      )\n    }\n\n    const data = await res.json() as { content?: { type: string; text?: string }[] }\n    const content = data.content?.[0]\n    if (content?.type === 'text' && content.text) {\n      try {\n        return JSON.parse(content.text)\n      } catch {\n        return content.text\n      }\n    }\n    return data\n  }\n\n  /**\n   * Execute an A2A skill — delegate to another AgentX Agent.\n   *\n   * Standard Interface:\n   *   Input:  { task, ...taskSpecificParams }\n   *   Output: { agentId, prompt, skills[] }\n   *\n   * The caller (LLM) receives the sub-Agent's prompt + skill list.\n   * The LLM then decides how to use the sub-Agent — typically by\n   * injecting the sub-Agent's system prompt and calling its skills.\n   */\n  private async _executeA2ASkill(\n    skill: SkillDef,\n    input: Record<string, unknown>\n  ): Promise<A2ASkillResult> {\n    const exec = skill.execution as import('../core/types').A2ASkillExecution\n    if (!exec || exec.type !== 'a2a') {\n      throw new AgentXError(\n        AgentXErrorCode.INVALID_SCHEMA,\n        `Skill \"${skill.name}\" is not an A2A delegation skill`\n      )\n    }\n\n    const targetAgentId = exec.targetAgentId\n\n    // Load the target Agent's full context\n    let subContext: AgentRunContext\n    try {\n      subContext = await this.useAgent(targetAgentId)\n    } catch (e) {\n      throw new AgentXError(\n        AgentXErrorCode.AGENT_NOT_FOUND,\n        `A2A delegation failed: cannot load Agent #${targetAgentId}. ${e}`\n      )\n    }\n\n    // Apply skill filter if specified\n    if (exec.skillFilter && exec.skillFilter.length > 0) {\n      const filterSet = new Set(exec.skillFilter)\n      subContext = {\n        ...subContext,\n        skills: subContext.skills.filter(s => filterSet.has(s.name)),\n      }\n    }\n\n    // Apply prompt override if specified\n    if (exec.promptOverride) {\n      subContext = { ...subContext, prompt: exec.promptOverride }\n    }\n\n    return {\n      agentId: targetAgentId,\n      prompt: subContext.prompt,\n      skills: subContext.skills.map(s => ({\n        name: s.name,\n        description: s.description,\n        inputSchema: s.inputSchema,\n      })),\n      // Pass the caller's input to the sub-agent's context\n      callerInput: input,\n    }\n  }\n\n  private async _getPrivateKey(): Promise<string> {\n    if (this.wallet.getPrivateKey) return this.wallet.getPrivateKey()\n    throw new AgentXError(\n      AgentXErrorCode.WALLET_NOT_CONNECTED,\n      'Wallet must support getPrivateKey() for ECIES decryption.'\n    )\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — IPFS Fetcher\n// ---------------------------------------------------------------------------\n// Multi-gateway IPFS fetcher with in-memory cache, deduplication, and\n// automatic fallback.  Compatible with the EncryptedPayload wire format.\n// ---------------------------------------------------------------------------\n\nimport type { EncryptedPayload } from '../core/types'\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface IPFSFetcherConfig {\n  /** Primary IPFS gateway (default: ipfs.io) */\n  gateway?: string\n  /** Fallback gateways in order of preference */\n  fallbackGateways?: string[]\n  /** Request timeout in ms (default: 10_000) */\n  timeoutMs?: number\n  /** Max cached entries (LRU-like eviction, default: 200) */\n  maxCache?: number\n}\n\ntype CacheEntry<T> = {\n  data: T\n  timestamp: number\n}\n\n// ── Implementation ─────────────────────────────────────────────────────────\n\nexport class IPFSFetcher {\n  private gateway: string\n  private fallbackGateways: string[]\n  private timeoutMs: number\n\n  private cache = new Map<string, CacheEntry<unknown>>()\n  private maxCache: number\n  private pending = new Map<string, Promise<unknown>>()\n  private failed = new Set<string>()\n\n  constructor(config: IPFSFetcherConfig = {}) {\n    this.gateway = config.gateway ?? 'ipfs.io'\n    this.fallbackGateways = config.fallbackGateways ?? [\n      'gateway.pinata.cloud',\n      'dweb.link',\n      'cf-ipfs.com',\n    ]\n    this.timeoutMs = config.timeoutMs ?? 10_000\n    this.maxCache = config.maxCache ?? 200\n  }\n\n  // ── Public API ──────────────────────────────────────────────────────────\n\n  /** Fetch JSON from a single IPFS CID. */\n  async fetchJSON<T = unknown>(cid: string): Promise<T> {\n    const cached = this.cache.get(cid)\n    if (cached) return cached.data as T\n\n    if (this.failed.has(cid)) throw new Error(`CID ${cid} previously failed`)\n\n    const pending = this.pending.get(cid)\n    if (pending) return pending as Promise<T>\n\n    const promise = this._doFetch<T>(cid)\n    this.pending.set(cid, promise)\n\n    try {\n      const data = await promise\n      this._cacheSet(cid, data)\n      return data\n    } catch (e) {\n      this.failed.add(cid)\n      throw e\n    } finally {\n      this.pending.delete(cid)\n    }\n  }\n\n  /** Fetch encrypted agent payload (validates algorithm). */\n  async fetchEncryptedPayload(cid: string): Promise<EncryptedPayload> {\n    const raw = await this.fetchJSON<Record<string, unknown>>(cid)\n    if (!raw.encrypted || raw.algorithm !== 'AES-256-GCM' || typeof raw.data !== 'string') {\n      throw new Error(`Invalid EncryptedPayload at CID ${cid}`)\n    }\n    return raw as unknown as EncryptedPayload\n  }\n\n  /** Batch fetch multiple CIDs with concurrency control. */\n  async fetchBatch<T = unknown>(cids: string[], concurrency = 5): Promise<Map<string, T>> {\n    const results = new Map<string, T>()\n    const unique = [...new Set(cids)].filter(c => this.isValidCID(c))\n\n    for (let i = 0; i < unique.length; i += concurrency) {\n      const batch = unique.slice(i, i + concurrency)\n      const settled = await Promise.allSettled(\n        batch.map(cid => this.fetchJSON<T>(cid))\n      )\n      settled.forEach((r, j) => {\n        if (r.status === 'fulfilled') results.set(batch[j]!, r.value)\n      })\n      if (i + concurrency < unique.length) {\n        await new Promise(r => setTimeout(r, 200))\n      }\n    }\n    return results\n  }\n\n  /** Check if a string looks like a valid IPFS CID. */\n  isValidCID(cid: string): boolean {\n    return /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[a-z2-7]{58,}|[A-Za-z0-9+/]{46,})$/.test(cid)\n  }\n\n  /** Clear cache (optionally for a specific CID). */\n  clearCache(cid?: string): void {\n    if (cid) {\n      this.cache.delete(cid)\n    } else {\n      this.cache.clear()\n    }\n    this.failed.clear()\n  }\n\n  /** Number of cached entries. */\n  get cacheSize(): number {\n    return this.cache.size\n  }\n\n  // ── Internal ─────────────────────────────────────────────────────────────\n\n  private async _doFetch<T>(cid: string): Promise<T> {\n    if (!this.isValidCID(cid)) throw new Error(`Invalid CID: ${cid}`)\n\n    // Try primary gateway\n    try {\n      return await this._fetchFrom(cid, this.gateway, this.timeoutMs)\n    } catch {\n      // fall through to alternatives\n    }\n\n    // Try fallback gateways\n    for (const gw of this.fallbackGateways) {\n      try {\n        return await this._fetchFrom(cid, gw, this.timeoutMs)\n      } catch {\n        // try next\n      }\n    }\n\n    throw new Error(`All IPFS gateways failed for CID ${cid}`)\n  }\n\n  private async _fetchFrom<T>(cid: string, gateway: string, timeoutMs: number): Promise<T> {\n    const url = `https://${gateway}/ipfs/${cid}`\n    const res = await fetch(url, {\n      headers: { Accept: 'application/json' },\n      signal: AbortSignal.timeout(timeoutMs),\n    })\n    if (!res.ok) throw new Error(`HTTP ${res.status}`)\n    return (await res.json()) as T\n  }\n\n  private _cacheSet(cid: string, data: unknown): void {\n    this.cache.set(cid, { data, timestamp: Date.now() })\n    // Simple LRU-like eviction\n    if (this.cache.size > this.maxCache) {\n      const oldest = [...this.cache.entries()].sort(\n        (a, b) => a[1].timestamp - b[1].timestamp\n      )[0]\n      if (oldest) this.cache.delete(oldest[0])\n    }\n  }\n}\n\n/** Singleton-friendly default instance. */\nexport const defaultIPFSFetcher = new IPFSFetcher()\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Tool Builder\n// ---------------------------------------------------------------------------\n// Converts AgentX RunnableSkill[] into OpenAI function-calling Tool JSON.\n//\n//   const tools = buildTools(ctx.skills)\n//   // → [{ type: \"function\", function: { name, description, parameters } }]\n// ---------------------------------------------------------------------------\n\nimport type { RunnableSkill } from '../agent/agent-runner'\nimport type { OpenAIToolDef } from './types'\n\nfunction toOpenAIParameters(schema: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = { type: (schema.type as string) ?? 'object' }\n\n  if (schema.properties) {\n    result.properties = convertProperties(schema.properties as Record<string, Record<string, unknown>>)\n  }\n  if (schema.required && Array.isArray(schema.required)) {\n    result.required = schema.required\n  }\n  if (schema.description) {\n    result.description = schema.description\n  }\n\n  return result\n}\n\nfunction convertProperties(properties: Record<string, Record<string, unknown>>): Record<string, Record<string, unknown>> {\n  const out: Record<string, Record<string, unknown>> = {}\n  for (const [key, prop] of Object.entries(properties)) {\n    const converted: Record<string, unknown> = {}\n\n    if (prop.type) converted.type = prop.type\n    if (prop.description) converted.description = prop.description\n    if (prop.items) converted.items = prop.items\n    if (prop.enum) converted.enum = prop.enum\n    if (prop.properties) {\n      converted.properties = convertProperties(prop.properties as Record<string, Record<string, unknown>>)\n    }\n    if (prop.required) converted.required = prop.required\n\n    out[key] = converted\n  }\n  return out\n}\n\nexport function buildTools(skills: RunnableSkill[]): OpenAIToolDef[] {\n  if (!skills || skills.length === 0) return []\n\n  return skills.map(skill => ({\n    type: 'function' as const,\n    function: {\n      name: skill.name,\n      description: skill.description || `Execute the \"${skill.name}\" skill`,\n      parameters: toOpenAIParameters(skill.inputSchema),\n    },\n  }))\n}\n\nexport function buildSystemPrompt(prompt: string, skills: RunnableSkill[]): string {\n  if (!skills || skills.length === 0) return prompt\n\n  const skillList = skills\n    .map(s => `- **${s.name}**: ${s.description}`)\n    .join('\\n')\n\n  return `${prompt}\\n\\n## Available Tools\\nYou have access to the following tools. Use them when appropriate:\\n${skillList}`\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Tool Executor\n// ---------------------------------------------------------------------------\n// Dispatches LLM tool calls to the correct RunnableSkill and executes.\n// Supports parallel execution of multiple tools in a single iteration.\n// ---------------------------------------------------------------------------\n\nimport type { RunnableSkill } from '../agent/agent-runner'\nimport type { ToolCallRecord } from './types'\n\nexport interface ExecuteOptions {\n  skills: RunnableSkill[]\n  timeoutMs?: number\n}\n\nexport class ToolExecutor {\n  private skills: Map<string, RunnableSkill>\n  private timeoutMs: number\n\n  constructor(opts: ExecuteOptions) {\n    this.skills = new Map()\n    for (const s of opts.skills) {\n      this.skills.set(s.name, s)\n    }\n    this.timeoutMs = opts.timeoutMs ?? 30_000\n  }\n\n  executeSingle(\n    name: string,\n    args: Record<string, unknown>,\n  ): Promise<ToolCallRecord> {\n    const startTime = Date.now()\n    const skill = this.skills.get(name)\n\n    if (!skill) {\n      return Promise.resolve({\n        callId: '',\n        name,\n        arguments: args,\n        result: null,\n        error: `Unknown tool: ${name}`,\n        durationMs: Date.now() - startTime,\n      })\n    }\n\n    const executePromise = skill.execute(args)\n\n    const timeoutPromise = new Promise<never>((_, reject) =>\n      setTimeout(() => reject(new Error(`Tool \"${name}\" timed out after ${this.timeoutMs}ms`)), this.timeoutMs),\n    )\n\n    return Promise.race([executePromise, timeoutPromise])\n      .then(result => ({\n        callId: '',\n        name,\n        arguments: args,\n        result: this.normalizeResult(result),\n        durationMs: Date.now() - startTime,\n      }))\n      .catch(err => ({\n        callId: '',\n        name,\n        arguments: args,\n        result: null,\n        error: err instanceof Error ? err.message : String(err),\n        durationMs: Date.now() - startTime,\n      }))\n  }\n\n  async executeBatch(\n    calls: { callId: string; name: string; arguments: Record<string, unknown> }[],\n  ): Promise<ToolCallRecord[]> {\n    const results = await Promise.all(\n      calls.map(async c => {\n        const record = await this.executeSingle(c.name, c.arguments)\n        record.callId = c.callId\n        return record\n      }),\n    )\n    return results\n  }\n\n  hasTool(name: string): boolean {\n    return this.skills.has(name)\n  }\n\n  getToolNames(): string[] {\n    return Array.from(this.skills.keys())\n  }\n\n  private normalizeResult(result: unknown): unknown {\n    if (result === undefined || result === null) return null\n    if (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') {\n      return result\n    }\n    if (result instanceof Error) return { error: result.message }\n    return result\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Context Compactor\n// ---------------------------------------------------------------------------\n// Token estimation + LLM-based message summarization.\n// Extracted from AgentLoop for decoupling.\n// ---------------------------------------------------------------------------\n\nimport type { LLMMessage, LLMProvider } from './types'\n\nexport class ContextCompactor {\n  constructor(\n    private readonly llmProvider: LLMProvider,\n    private readonly compactModel: string = 'gpt-4o-mini',\n  ) {}\n\n  /** Rough token estimation: 1 token ≈ 4 characters */\n  estimateTokens(messages: LLMMessage[]): number {\n    let total = 0\n    for (const msg of messages) {\n      total += JSON.stringify(msg).length\n    }\n    return Math.ceil(total / 4)\n  }\n\n  /**\n   * Compact messages: keep system prompt + last 2 turns, summarize the rest.\n   * Returns original array if not enough messages or compaction fails.\n   */\n  async compact(messages: LLMMessage[]): Promise<LLMMessage[]> {\n    if (messages.length <= 5) return messages\n\n    const system = messages.filter(m => m.role === 'system')\n    const nonSystem = messages.filter(m => m.role !== 'system')\n    const keepCount = Math.min(4, nonSystem.length)\n    const keepMessages = nonSystem.slice(-keepCount)\n    const compactTarget = nonSystem.slice(0, nonSystem.length - keepCount)\n\n    if (compactTarget.length === 0) return messages\n\n    try {\n      const stream = this.llmProvider.chatStream({\n        model: this.compactModel,\n        messages: [{\n          role: 'user',\n          content: `Summarize concisely (keep all facts/decisions):\\n${compactTarget.map(m => `${m.role}: ${m.content}`).join('\\n')}`,\n        }],\n        maxTokens: 500,\n        temperature: 0.3,\n      })\n\n      let summary = ''\n      for await (const event of stream) {\n        if (event.type === 'text_delta') summary += event.content\n      }\n\n      return [...system, { role: 'system', content: `[Summary]: ${summary}` }, ...keepMessages]\n    } catch {\n      return messages\n    }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Fact Extractor\n// ---------------------------------------------------------------------------\n// Extracts key facts from conversation for memory storage.\n// Uses a single cheap LLM call for summarization.\n// ---------------------------------------------------------------------------\n\nimport type { LLMProvider } from './types'\n\nexport class FactExtractor {\n  constructor(\n    private readonly llmProvider: LLMProvider,\n    private readonly factModel: string = 'gpt-4o-mini',\n  ) {}\n\n  /** Extract simple facts from the conversation for memory storage */\n  async extract(userMessage: string, assistantResponse: string): Promise<string[]> {\n    try {\n      const stream = this.llmProvider.chatStream({\n        model: this.factModel,\n        messages: [{\n          role: 'user',\n          content: `Extract 1-3 key facts/preferences. One per line, <100 chars each. No other text.\\nUser: ${userMessage}\\nAssistant: ${assistantResponse.slice(0, 500)}\\nFacts:`,\n        }],\n        maxTokens: 200,\n        temperature: 0.3,\n      })\n\n      let text = ''\n      for await (const event of stream) {\n        if (event.type === 'text_delta') text += event.content\n      }\n\n      return text.split('\\n').map(s => s.replace(/^[\\d\\-•. ]+/, '').trim()).filter(Boolean)\n    } catch {\n      return []\n    }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Loop Trace Emitter\n// ---------------------------------------------------------------------------\n// Fire-and-forget structured observability for AgentLoop.\n// Extracted from AgentLoop for decoupling.\n// ---------------------------------------------------------------------------\n\nimport type { TraceEvent, TraceConfig } from '../traces/types'\n\nexport class LoopTraceEmitter {\n  private readonly config: TraceConfig | undefined\n\n  constructor(config?: TraceConfig) {\n    this.config = config\n  }\n\n  emit(event: Omit<TraceEvent, 'timestamp'>): void {\n    if (!this.config?.enabled) return\n    try {\n      this.config.emitter.emit({ ...event, timestamp: Date.now() })\n    } catch {\n      // Trace emit should never throw — silently ignore\n    }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — AgentLoop\n// ---------------------------------------------------------------------------\n// ReAct-style agent loop engine.\n//\n//   const loop = new AgentLoop({ ctx, llmProvider, maxIterations: 5 })\n//   const result = await loop.run(userMessage, history)\n//\n// Flow:\n//   [Memory Recall] → User Input → LLM Thinks → [Context Check] → Tool Call → Execute → Result → LLM Thinks → ...\n//   Until: LLM stops calling tools, max iterations reached, or timeout.\n//   [Memory Store]\n// ---------------------------------------------------------------------------\n\nimport type {\n  AgentLoopConfig,\n  AgentLoopResult,\n  LLMMessage,\n  LLMToolCall,\n  ToolCallRecord,\n} from './types'\nimport { buildTools, buildSystemPrompt } from './tool-builder'\nimport { ToolExecutor } from './executor'\nimport { ContextCompactor } from './context-compactor'\nimport { FactExtractor } from './fact-extractor'\nimport { LoopTraceEmitter } from './trace-emitter'\n\nconst DEFAULT_MAX_ITERATIONS = 5\nconst DEFAULT_TIMEOUT_MS = 120_000\nconst DEFAULT_MODEL = 'gpt-4o'\n\nexport class AgentLoop {\n  private config: AgentLoopConfig\n  private executor: ToolExecutor\n  private tools: ReturnType<typeof buildTools>\n  private systemPrompt: string\n  private aborted = false\n  private abortController: AbortController | null = null\n  private sessionId = ''\n\n  private readonly compactor: ContextCompactor\n  private readonly factExtractor: FactExtractor\n  private readonly tracer: LoopTraceEmitter\n\n  constructor(config: AgentLoopConfig) {\n    this.config = {\n      ...config,\n      maxIterations: config.maxIterations ?? DEFAULT_MAX_ITERATIONS,\n      timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n    }\n\n    this.executor = new ToolExecutor({ skills: config.ctx.skills })\n    this.tools = buildTools(config.ctx.skills)\n    this.systemPrompt = buildSystemPrompt(config.ctx.prompt, config.ctx.skills)\n\n    // Extracted sub-engines — accept model overrides from config\n    this.compactor = new ContextCompactor(\n      config.llmProvider,\n      config.compactModel,\n    )\n    this.factExtractor = new FactExtractor(\n      config.llmProvider,\n      config.factExtractionModel,\n    )\n    this.tracer = new LoopTraceEmitter(config.trace)\n  }\n\n  abort(): void {\n    this.aborted = true\n    this.abortController?.abort()\n  }\n\n  async run(\n    userMessage: string,\n    history: { role: 'user' | 'assistant'; content: string }[] = [],\n  ): Promise<AgentLoopResult> {\n    const startTime = Date.now()\n    const toolCalls: ToolCallRecord[] = []\n    const totalUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }\n    let finalText = ''\n    let iterations = 0\n\n    let messages: LLMMessage[] = [\n      { role: 'system', content: this.systemPrompt },\n      ...history.map(m => ({\n        role: m.role as 'user' | 'assistant',\n        content: m.content,\n      })),\n      { role: 'user', content: userMessage },\n    ]\n\n    const sessionId = `sess_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`\n    this.sessionId = sessionId\n\n    // Memory recall\n    await this.recallMemory(messages, userMessage)\n\n    this.aborted = false\n    this.abortController = new AbortController()\n\n    try {\n      while (iterations < this.config.maxIterations!) {\n        if (this.aborted) {\n          if (this.config.onThinking) {\n            this.config.onThinking('Aborted by user')\n          }\n          break\n        }\n\n        iterations++\n\n        if (this.config.onThinking && iterations > 1) {\n          this.config.onThinking(`Thinking... (round ${iterations}/${this.config.maxIterations!})`)\n        }\n\n        // Context compaction\n        if (this.config.contextBudget && this.compactor.estimateTokens(messages) > this.config.contextBudget) {\n          messages = await this.compactor.compact(messages)\n        }\n\n        const iterationResult = await this.runIteration(messages)\n\n        finalText += iterationResult.text\n        toolCalls.push(...iterationResult.toolCallRecords)\n        totalUsage.promptTokens += iterationResult.usage.promptTokens\n        totalUsage.completionTokens += iterationResult.usage.completionTokens\n        totalUsage.totalTokens += iterationResult.usage.totalTokens\n\n        if (iterationResult.toolCalls.length === 0) {\n          break\n        }\n\n        const assistantMsg: LLMMessage = {\n          role: 'assistant',\n          content: iterationResult.text || null,\n          tool_calls: iterationResult.toolCalls,\n        }\n        messages.push(assistantMsg)\n\n        for (let i = 0; i < iterationResult.toolCalls.length; i++) {\n          const tc = iterationResult.toolCalls[i]!\n          const record = iterationResult.toolCallRecords[i]!\n          let toolContent: string\n\n          if (record.error) {\n            toolContent = `Error: ${record.error}`\n          } else {\n            toolContent = typeof record.result === 'string'\n              ? record.result\n              : JSON.stringify(record.result)\n          }\n\n          messages.push({\n            role: 'tool',\n            content: toolContent,\n            tool_call_id: tc.id,\n          })\n        }\n      }\n    } catch (err) {\n      const error = err instanceof Error ? err : new Error(String(err))\n      if (this.config.onError) {\n        this.config.onError(error)\n      }\n      if (finalText === '' && toolCalls.length === 0) {\n        finalText = `Agent loop error: ${error.message}`\n      }\n    } finally {\n      this.abortController = null\n    }\n\n    const result: AgentLoopResult = {\n      finalText: finalText || 'No response generated.',\n      toolCalls,\n      totalIterations: iterations,\n      totalDuration: Date.now() - startTime,\n      usage: totalUsage,\n    }\n\n    // Memory store on session end\n    await this.storeMemory(userMessage, result.finalText)\n\n    // Trace emit — session complete\n    this.tracer.emit({\n      tenantId: this.config.ctx.subscriberAddress || 'unknown',\n      agentId: this.config.ctx.agentId,\n      sessionId: this.sessionId,\n      type: 'session_complete',\n      data: {\n        totalIterations: iterations,\n        totalDuration: Date.now() - startTime,\n        totalTokens: totalUsage.totalTokens,\n        toolCallCount: toolCalls.length,\n      },\n    })\n\n    if (this.config.onComplete) {\n      this.config.onComplete(result)\n    }\n\n    return result\n  }\n\n  // ── Private: Memory ─────────────────────────────────────────────────────\n\n  private async recallMemory(messages: LLMMessage[], userMessage: string): Promise<void> {\n    if (!this.config.memory?.enabled || !this.config.ctx.subscriberAddress || !this.config.ctx.agentId) return\n\n    try {\n      const facts = await this.config.memory.provider.recall({\n        subscriberAddress: this.config.ctx.subscriberAddress,\n        agentId: this.config.ctx.agentId,\n        query: userMessage,\n        limit: this.config.memory.recallLimit ?? 5,\n      })\n      if (facts.length > 0 && messages[0]) {\n        const memoryContext = '\\n\\n## Relevant Memory\\n' + facts.map(f => `- ${f.fact}`).join('\\n')\n        messages[0].content = (messages[0].content || '') + memoryContext\n      }\n    } catch (err) {\n      console.warn('[AgentLoop] Memory recall failed:', (err as Error).message)\n    }\n  }\n\n  private async storeMemory(userMessage: string, assistantResponse: string): Promise<void> {\n    if (!this.config.memory?.enabled || this.config.memory.storeOnSessionEnd === false\n        || !this.config.ctx.subscriberAddress || !this.config.ctx.agentId) return\n\n    try {\n      const facts = await this.factExtractor.extract(userMessage, assistantResponse)\n      for (const fact of facts) {\n        await this.config.memory.provider.store({\n          subscriberAddress: this.config.ctx.subscriberAddress,\n          agentId: this.config.ctx.agentId,\n          fact,\n        })\n      }\n    } catch (err) {\n      console.warn('[AgentLoop] Memory store failed:', (err as Error).message)\n    }\n  }\n\n  // ── Private: Iteration ──────────────────────────────────────────────────\n\n  private async runIteration(\n    messages: LLMMessage[],\n  ): Promise<{\n    text: string\n    toolCalls: LLMToolCall[]\n    toolCallRecords: ToolCallRecord[]\n    usage: { promptTokens: number; completionTokens: number; totalTokens: number }\n  }> {\n    const model = this.config.ctx.model ?? this.config.llmProvider.model ?? DEFAULT_MODEL\n    const temperature = this.config.ctx.temperature ?? 0.7\n    const maxTokens = this.config.ctx.maxTokens ?? 4096\n\n    const stream = this.config.llmProvider.chatStream(\n      {\n        model,\n        messages,\n        tools: this.tools.length > 0 ? this.tools : undefined,\n        temperature,\n        maxTokens,\n      },\n      this.abortController?.signal,\n    )\n\n    let text = ''\n    const toolCallsAccum: Map<string, { name: string; arguments: string }> = new Map()\n    const usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }\n\n    for await (const event of stream) {\n      if (this.aborted) break\n\n      switch (event.type) {\n        case 'text_delta':\n          text += event.content\n          if (this.config.onTextDelta) {\n            this.config.onTextDelta(event.content)\n          }\n          break\n\n        case 'tool_call_start':\n          toolCallsAccum.set(event.callId, { name: event.name, arguments: '' })\n          break\n\n        case 'tool_call_delta': {\n          const existing = toolCallsAccum.get(event.callId)\n          if (existing) {\n            existing.arguments += event.arguments\n          }\n          break\n        }\n\n        case 'done':\n          usage.promptTokens = event.usage.promptTokens\n          usage.completionTokens = event.usage.completionTokens\n          usage.totalTokens = event.usage.totalTokens\n          break\n\n        case 'error':\n          throw event.error\n      }\n    }\n\n    const llmToolCalls: LLMToolCall[] = []\n    const parsedToolCalls: { callId: string; name: string; arguments: Record<string, unknown> }[] = []\n\n    for (const [callId, tc] of toolCallsAccum) {\n      let parsedArgs: Record<string, unknown> = {}\n      try {\n        parsedArgs = tc.arguments ? JSON.parse(tc.arguments) : {}\n      } catch {\n        parsedArgs = { raw: tc.arguments }\n      }\n\n      llmToolCalls.push({\n        id: callId,\n        type: 'function',\n        function: { name: tc.name, arguments: tc.arguments },\n      })\n\n      parsedToolCalls.push({ callId, name: tc.name, arguments: parsedArgs })\n    }\n\n    if (parsedToolCalls.length > 0) {\n      for (const ptc of parsedToolCalls) {\n        if (this.config.onToolCall) {\n          this.config.onToolCall({ callId: ptc.callId, name: ptc.name, arguments: ptc.arguments })\n        }\n        this.tracer.emit({\n          tenantId: this.config.ctx.subscriberAddress || 'unknown',\n          agentId: this.config.ctx.agentId,\n          sessionId: this.sessionId,\n          type: 'tool_call',\n          data: { callId: ptc.callId, name: ptc.name, arguments: ptc.arguments },\n        })\n      }\n    }\n\n    const toolCallRecords = await this.executor.executeBatch(parsedToolCalls)\n\n    for (const record of toolCallRecords) {\n      if (this.config.onToolResult) {\n        this.config.onToolResult({\n          callId: record.callId,\n          name: record.name,\n          result: record.result,\n          error: record.error,\n          durationMs: record.durationMs,\n        })\n      }\n      this.tracer.emit({\n        tenantId: this.config.ctx.subscriberAddress || 'unknown',\n        agentId: this.config.ctx.agentId,\n        sessionId: this.sessionId,\n        type: 'tool_result',\n        data: { callId: record.callId, name: record.name, error: record.error, durationMs: record.durationMs },\n      })\n    }\n\n    return { text, toolCalls: llmToolCalls, toolCallRecords, usage }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Platform Tools\n// ---------------------------------------------------------------------------\n// Exposes ALL AgentX platform capabilities as LLM-callable OpenAI function tools.\n//\n//   const tools = buildPlatformTools({ agentRunner, a2a, subscriptionManager, ... })\n//   // → [{ type: \"function\", function: { name, description, parameters } }]\n//\n// When AgentLoop calls a tool:\n//   platformExecutor(toolName, args, ctx) → result JSON\n//\n// Modules wrapped:\n//   1. IdentityRegistry  — register / get / list / exists / metadata\n//   2. SubscriptionManager — plans / subscribe / check / cancel / detail\n//   3. A2AProtocol        — createTask / getTask / completeTask / getUserTasks / card\n//   4. ReputationRegistry — rate / getRating / getReviews\n//   5. ConfigurationRegistry — getConfig / getAgentConfigs / setConfig\n//   6. MultiEndpointRegistry — getEndpoints / getBestEndpoint\n//   7. Gateway API         — chat / tenant / history\n// ---------------------------------------------------------------------------\n\nimport type { RunnableSkill } from '../../agent/agent-runner'\nimport type { AgentRunner } from '../../agent/agent-runner'\nimport type { A2AProtocol } from '../../a2a/a2a'\nimport type { SubscriptionManager } from '../../subscription/subscription'\nimport type { AgentRegistry } from '../../registry/agent-registry'\nimport type { IPFSUploader } from '../../ipfs/ipfs-uploader'\n\n// ── Tool Definition Types ──────────────────────────────────────────────────\n\nexport interface PlatformToolDef {\n  type: 'function'\n  function: {\n    name: string\n    description: string\n    parameters: Record<string, unknown>\n  }\n}\n\nexport interface PlatformToolContext {\n  agentRunner: AgentRunner\n  a2a: A2AProtocol\n  subscriptionManager: SubscriptionManager\n  agentRegistry: AgentRegistry\n  reputationRegistry?: {\n    rateAgent(agentId: number, rating: number, comment: string): Promise<unknown>\n    getRating(agentId: number): Promise<{ averageRating: number; totalRatings: number }>\n    getReviews(agentId: number): Promise<unknown[]>\n  }\n  configurationRegistry?: {\n    getConfig(agentId: number, key: string): Promise<{ value: string; dataType: string }>\n    getAgentConfigs(agentId: number): Promise<unknown[]>\n    setConfig(agentId: number, key: string, value: string, dataType: string): Promise<unknown>\n  }\n  multiEndpointRegistry?: {\n    getAgentEndpoints(agentId: number): Promise<unknown[]>\n    getActiveAgentEndpoints(agentId: number): Promise<unknown[]>\n    getBestMCPUrl(agentId: number): Promise<string>\n  }\n  gatewayUrl?: string\n  gatewayToken?: string\n  userAddress: string\n  ipfsUploader?: IPFSUploader\n}\n\n// ── Schema Helpers ─────────────────────────────────────────────────────────\n\nfunction required(keys: string[]): string[] { return keys }\n\nfunction object(props: Record<string, Record<string, unknown>>, req?: string[]): Record<string, unknown> {\n  const s: Record<string, unknown> = { type: 'object', properties: props }\n  if (req) s.required = req\n  return s\n}\n\nfunction str(desc: string, en?: string[]): Record<string, unknown> {\n  const s: Record<string, unknown> = { type: 'string', description: desc }\n  if (en) s.enum = en\n  return s\n}\n\nfunction num(desc: string): Record<string, unknown> {\n  return { type: 'number', description: desc }\n}\n\nfunction integer(desc: string): Record<string, unknown> {\n  return { type: 'integer', description: desc }\n}\n\nfunction boolean(desc: string): Record<string, unknown> {\n  return { type: 'boolean', description: desc }\n}\n\nfunction array(items: Record<string, unknown>, desc: string): Record<string, unknown> {\n  return { type: 'array', items, description: desc }\n}\n\n// ── 1. IdentityRegistry Tools ──────────────────────────────────────────────\n\nconst identityRegistryTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_identity_register',\n      description: 'Register a new AI Agent on the AgentX blockchain. Required before any agent can be published, subscribed to, or used.',\n      parameters: object({\n        tokenURI: str('IPFS URI of the agent public metadata (ipfs://...)'),\n        encryptedPayloadCid: str('IPFS CID of the encrypted agent payload'),\n        eciesEncryptedKey: str('Hex-encoded ECIES-encrypted AES key for the payload'),\n        aesKeyHex: str('Hex-encoded AES key (stored as metadata)'),\n      }, required(['tokenURI', 'encryptedPayloadCid', 'eciesEncryptedKey'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_identity_get',\n      description: 'Get detailed information about a registered Agent by its ID. Returns owner, metadata URI, active status, and on-chain metadata attributes.',\n      parameters: object({\n        agentId: integer('The numeric agent ID to query'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_identity_list',\n      description: 'List all Agent IDs owned by a specific wallet address.',\n      parameters: object({\n        ownerAddress: str('Ethereum wallet address to query'),\n      }),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_identity_exists',\n      description: 'Check if a specific Agent ID exists on the blockchain.',\n      parameters: object({\n        agentId: integer('The agent ID to check'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_identity_total_count',\n      description: 'Get the total number of agents registered in the IdentityRegistry.',\n      parameters: object({}),\n    },\n  },\n]\n\n// ── 2. SubscriptionManager Tools ───────────────────────────────────────────\n\nconst subscriptionTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_plans',\n      description: 'Get plan details for a specific subscription plan by its ID. Returns price, period, creator, pay token, trial days, and active status.',\n      parameters: object({\n        planId: integer('The plan ID to fetch'),\n      }, required(['planId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_check',\n      description: 'Check if a wallet address has an active subscription for a specific agent.',\n      parameters: object({\n        subscriberAddress: str('Wallet address to check'),\n        agentId: integer('The agent ID'),\n      }, required(['subscriberAddress', 'agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_detail',\n      description: 'Get full subscription details including trial info, payment token, amount paid, escrow status.',\n      parameters: object({\n        subscriptionId: integer('The subscription ID'),\n      }, required(['subscriptionId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_my_list',\n      description: 'List all subscription IDs belonging to the current user.',\n      parameters: object({}),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_subscribe',\n      description: 'Subscribe to a plan. For ETH plans this will send ETH. For ERC20 plans, the token must already be approved. This is a blockchain transaction — the user must approve it in their wallet.',\n      parameters: object({\n        planId: integer('The plan ID to subscribe to'),\n        valueWei: str('Amount of ETH in wei to send (for ETH plans). Example: \"1000000000000000000\" for 1 ETH'),\n      }, required(['planId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_cancel',\n      description: 'Cancel an existing subscription. If within trial period, funds may be refunded.',\n      parameters: object({\n        subscriptionId: integer('The subscription ID to cancel'),\n      }, required(['subscriptionId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_release',\n      description: 'Release escrowed subscription funds to the agent creator (after trial window). Only callable by the subscriber.',\n      parameters: object({\n        subscriptionId: integer('The subscription ID'),\n      }, required(['subscriptionId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_subscription_fee',\n      description: 'Get the current platform fee in basis points (e.g. 250 = 2.5%).',\n      parameters: object({}),\n    },\n  },\n]\n\n// ── 3. A2AProtocol Tools ───────────────────────────────────────────────────\n\nconst a2aTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_a2a_create_task',\n      description: 'Create an on-chain Agent-to-Agent task. This delegates work to another AgentX agent. The target agent will see this as a pending task they can complete.',\n      parameters: object({\n        targetAgentId: integer('The Agent ID to delegate work to'),\n        taskType: str('Type of task, e.g. \"audit\", \"analyze\", \"generate\", \"review\"'),\n        inputData: str('JSON string of the task input. Include all details the target agent needs.'),\n      }, required(['targetAgentId', 'taskType', 'inputData'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_a2a_get_task',\n      description: 'Get full details of an A2A task by its ID — status, input, output, creator, timestamps.',\n      parameters: object({\n        taskId: integer('The A2A task ID'),\n      }, required(['taskId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_a2a_complete_task',\n      description: 'Mark an A2A task as completed and submit the output data on-chain.',\n      parameters: object({\n        taskId: integer('The task ID to complete'),\n        outputData: str('JSON string of the task output/result'),\n      }, required(['taskId', 'outputData'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_a2a_my_tasks',\n      description: 'Get all A2A task IDs assigned to or created by the current user.',\n      parameters: object({}),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_a2a_agent_card',\n      description: 'Get an agent\\'s A2A card — name, capabilities, supported task types, protocol info.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n]\n\n// ── 4. ReputationRegistry Tools ────────────────────────────────────────────\n\nconst reputationTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_reputation_rate',\n      description: 'Rate an agent (1-5) and leave a comment on-chain.',\n      parameters: object({\n        agentId: integer('The agent ID to rate'),\n        rating: integer('Rating from 1 (worst) to 5 (best)'),\n        comment: str('Optional review comment'),\n      }, required(['agentId', 'rating'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_reputation_get',\n      description: 'Get the average rating and total number of ratings for an agent.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_reputation_reviews',\n      description: 'Get all reviews for an agent (reviewer address, rating, comment, timestamp).',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n]\n\n// ── 5. ConfigurationRegistry Tools ─────────────────────────────────────────\n\nconst configurationTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_config_get',\n      description: 'Read a single configuration value for an agent by key.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n        configKey: str('The configuration key name'),\n      }, required(['agentId', 'configKey'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_config_list',\n      description: 'List all configuration entries for an agent.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_config_set',\n      description: 'Set or update a configuration value for an agent on-chain. Only the agent owner can write.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n        key: str('Configuration key name'),\n        value: str('Configuration value'),\n        dataType: str('Data type: \"string\", \"number\", \"boolean\", \"json\"', ['string', 'number', 'boolean', 'json']),\n      }, required(['agentId', 'key', 'value'])),\n    },\n  },\n]\n\n// ── 6. MultiEndpointRegistry Tools ─────────────────────────────────────────\n\nconst endpointTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_endpoint_list',\n      description: 'Get all registered endpoints for an agent (MCP URLs, API endpoints, etc.).',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_endpoint_active',\n      description: 'Get only active endpoints for an agent. Useful for finding available MCP or API servers.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_endpoint_best_mcp',\n      description: 'Find the best available MCP endpoint URL for an agent. Automatically picks the healthiest active endpoint.',\n      parameters: object({\n        agentId: integer('The agent ID'),\n      }, required(['agentId'])),\n    },\n  },\n]\n\n// ── 7. Gateway API Tools ───────────────────────────────────────────────────\n\nconst gatewayTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_gateway_chat',\n      description: 'Call an LLM through the AgentX Gateway using platform quota or BYOK key. Supports OpenAI models via SSE streaming.',\n      parameters: object({\n        model: str('LLM model name, e.g. \"gpt-4o\", \"gpt-4o-mini\"'),\n        messages: array(\n          object({\n            role: str('Message role', ['system', 'user', 'assistant', 'tool']),\n            content: str('Message content text'),\n          }),\n          'Array of conversation messages'\n        ),\n        keySource: str('API key source', ['platform', 'tenant_owned']),\n        tenantKeyId: str('BYOK key UUID (required when key_source is \"tenant_owned\")'),\n        temperature: num('Sampling temperature 0-2'),\n        max_tokens: integer('Maximum tokens in the response'),\n      }, required(['model', 'messages'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_gateway_tenant_me',\n      description: 'Get the current tenant (user) profile: plan info, API keys, today\\'s usage quota.',\n      parameters: object({}),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_gateway_tenant_usage',\n      description: 'Get usage history for the current tenant: token consumption, tool calls by day.',\n      parameters: object({\n        days: integer('Number of days of history (default 30)'),\n      }),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_gateway_tenant_keys',\n      description: 'List all BYOK API keys registered for the current tenant.',\n      parameters: object({}),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_gateway_models',\n      description: 'List available LLM models: both platform-provided and tenant-owned models.',\n      parameters: object({}),\n    },\n  },\n]\n\n// ── 8. IPFS Tools ───────────────────────────────────────────────────────────\n\nconst ipfsTools: PlatformToolDef[] = [\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_ipfs_upload',\n      description: 'Upload JSON data to IPFS via Pinata (requires Pinata JWT configured). Returns the IPFS CID and gateway URL.',\n      parameters: object({\n        data: str('The JSON data to upload, as a JSON string'),\n        name: str('Optional name for the uploaded file'),\n      }, required(['data'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_ipfs_upload_encrypted',\n      description: 'Encrypt and upload an Agent payload to IPFS. Used in the Agent publish flow. Generates AES key, encrypts the payload, and uploads to IPFS in one step.',\n      parameters: object({\n        prompt: str('The private system prompt to encrypt and upload'),\n        skillsJson: str('JSON string of skills configuration'),\n        mcpJson: str('JSON string of MCP configuration'),\n        agentName: str('Name for the agent payload metadata'),\n      }, required(['prompt'])),\n    },\n  },\n  {\n    type: 'function',\n    function: {\n      name: 'agentx_ipfs_get_url',\n      description: 'Build a public IPFS gateway URL from a CID.',\n      parameters: object({\n        cid: str('The IPFS CID (Content Identifier)'),\n        gateway: str('Optional gateway URL (default: ipfs.io)'),\n      }, required(['cid'])),\n    },\n  },\n]\n\n// ── Build All Tools ─────────────────────────────────────────────────────────\n\nexport function buildPlatformTools(\n  available?: ('identity' | 'subscription' | 'a2a' | 'reputation' | 'configuration' | 'endpoint' | 'gateway' | 'ipfs')[]\n): PlatformToolDef[] {\n  const modules = available ?? ['identity', 'subscription', 'a2a', 'reputation', 'configuration', 'endpoint', 'gateway', 'ipfs']\n  const tools: PlatformToolDef[] = []\n\n  for (const mod of modules) {\n    switch (mod) {\n      case 'identity': tools.push(...identityRegistryTools); break\n      case 'subscription': tools.push(...subscriptionTools); break\n      case 'a2a': tools.push(...a2aTools); break\n      case 'reputation': tools.push(...reputationTools); break\n      case 'configuration': tools.push(...configurationTools); break\n      case 'endpoint': tools.push(...endpointTools); break\n      case 'gateway': tools.push(...gatewayTools); break\n      case 'ipfs': tools.push(...ipfsTools); break\n    }\n  }\n\n  return tools\n}\n\nexport function getAllPlatformToolNames(): string[] {\n  return buildPlatformTools().map(t => t.function.name)\n}\n\n","import type { PlatformToolDef, PlatformToolContext } from \"./definitions\"\nimport { buildPlatformTools } from \"./definitions\"\nimport type { RunnableSkill } from \"../../agent/agent-runner\"\n\n// ── Tool Executor ───────────────────────────────────────────────────────────\n\nexport async function executePlatformTool(\n  toolName: string,\n  args: Record<string, unknown>,\n  ctx: PlatformToolContext\n): Promise<unknown> {\n  try {\n    switch (toolName) {\n      // ── Identity ──────────────────────────────────\n      case 'agentx_identity_register': {\n        const { tokenURI, encryptedPayloadCid, eciesEncryptedKey, aesKeyHex } = args as any\n        const metadata = [\n          { key: 'encryptedPayloadCid', value: encryptedPayloadCid },\n          { key: 'eciesEncryptedKey', value: eciesEncryptedKey },\n        ]\n        if (aesKeyHex) metadata.push({ key: 'aesKeyHex', value: aesKeyHex })\n        return ctx.agentRegistry.register(tokenURI, metadata)\n      }\n      case 'agentx_identity_get':\n        return {\n          tokenURI: await ctx.agentRegistry.tokenURI(args.agentId as number),\n          attributes: await ctx.agentRegistry.getAttributes(args.agentId as number),\n          exists: await ctx.agentRegistry.agentExists(args.agentId as number),\n        }\n      case 'agentx_identity_list':\n        return ctx.agentRegistry.getAgentsByOwner((args.ownerAddress ?? ctx.userAddress) as `0x${string}`)\n      case 'agentx_identity_exists':\n        return ctx.agentRegistry.agentExists(args.agentId as number)\n      case 'agentx_identity_total_count':\n        return { totalAgents: await ctx.agentRegistry.getCurrentAgentId() }\n\n      // ── Subscription ──────────────────────────────\n      case 'agentx_subscription_plans':\n        return ctx.subscriptionManager.getPlan(args.planId as number)\n      case 'agentx_subscription_check':\n        return ctx.subscriptionManager.hasActiveSubscription(\n          (args.subscriberAddress ?? ctx.userAddress) as `0x${string}`,\n          args.agentId as number\n        )\n      case 'agentx_subscription_detail':\n        return ctx.subscriptionManager.getSubscriptionDetail(args.subscriptionId as number)\n      case 'agentx_subscription_my_list':\n        return ctx.subscriptionManager.getUserSubscriptions(ctx.userAddress as `0x${string}`)\n      case 'agentx_subscription_subscribe': {\n        const valueWei = args.valueWei ? BigInt(args.valueWei as string) : undefined\n        return ctx.subscriptionManager.subscribe(args.planId as number, { valueWei })\n      }\n      case 'agentx_subscription_cancel':\n        return ctx.subscriptionManager.cancel(args.subscriptionId as number)\n      case 'agentx_subscription_release':\n        return ctx.subscriptionManager.releaseFunds(args.subscriptionId as number)\n      case 'agentx_subscription_fee':\n        return { platformFeeBps: await ctx.subscriptionManager.getPlatformFeeBps() }\n\n      // ── A2A ───────────────────────────────────────\n      case 'agentx_a2a_create_task':\n        return ctx.a2a.createTask(\n          args.targetAgentId as number,\n          args.taskType as string,\n          typeof args.inputData === 'string' ? JSON.parse(args.inputData as string) : args.inputData as Record<string, unknown>\n        )\n      case 'agentx_a2a_get_task':\n        return ctx.a2a.getTask(args.taskId as number)\n      case 'agentx_a2a_complete_task':\n        return ctx.a2a.completeTask(args.taskId as number, args.outputData as string)\n      case 'agentx_a2a_my_tasks':\n        return ctx.a2a.getUserTasks(ctx.userAddress as `0x${string}`)\n      case 'agentx_a2a_agent_card':\n        return ctx.a2a.getAgentCard(args.agentId as number)\n\n      // ── Reputation ─────────────────────────────────\n      case 'agentx_reputation_rate':\n        if (!ctx.reputationRegistry) throw new Error('ReputationRegistry not configured')\n        return ctx.reputationRegistry.rateAgent(args.agentId as number, args.rating as number, (args.comment as string) ?? '')\n      case 'agentx_reputation_get':\n        if (!ctx.reputationRegistry) throw new Error('ReputationRegistry not configured')\n        return ctx.reputationRegistry.getRating(args.agentId as number)\n      case 'agentx_reputation_reviews':\n        if (!ctx.reputationRegistry) throw new Error('ReputationRegistry not configured')\n        return ctx.reputationRegistry.getReviews(args.agentId as number)\n\n      // ── Configuration ──────────────────────────────\n      case 'agentx_config_get':\n        if (!ctx.configurationRegistry) throw new Error('ConfigurationRegistry not configured')\n        return ctx.configurationRegistry.getConfig(args.agentId as number, args.configKey as string)\n      case 'agentx_config_list':\n        if (!ctx.configurationRegistry) throw new Error('ConfigurationRegistry not configured')\n        return ctx.configurationRegistry.getAgentConfigs(args.agentId as number)\n      case 'agentx_config_set':\n        if (!ctx.configurationRegistry) throw new Error('ConfigurationRegistry not configured')\n        return ctx.configurationRegistry.setConfig(\n          args.agentId as number, args.key as string,\n          args.value as string, (args.dataType as string) ?? 'string'\n        )\n\n      // ── MultiEndpoint ──────────────────────────────\n      case 'agentx_endpoint_list':\n        if (!ctx.multiEndpointRegistry) throw new Error('MultiEndpointRegistry not configured')\n        return ctx.multiEndpointRegistry.getAgentEndpoints(args.agentId as number)\n      case 'agentx_endpoint_active':\n        if (!ctx.multiEndpointRegistry) throw new Error('MultiEndpointRegistry not configured')\n        return ctx.multiEndpointRegistry.getActiveAgentEndpoints(args.agentId as number)\n      case 'agentx_endpoint_best_mcp':\n        if (!ctx.multiEndpointRegistry) throw new Error('MultiEndpointRegistry not configured')\n        return { mcpUrl: await ctx.multiEndpointRegistry.getBestMCPUrl(args.agentId as number) }\n\n      // ── Gateway ────────────────────────────────────\n      case 'agentx_gateway_chat': {\n        if (!ctx.gatewayUrl || !ctx.gatewayToken) throw new Error('Gateway not configured')\n        const body: Record<string, unknown> = {\n          model: args.model ?? 'gpt-4o',\n          messages: args.messages,\n          stream: false,\n          key_source: args.keySource ?? 'platform',\n        }\n        if (args.temperature !== undefined) body.temperature = args.temperature\n        if (args.max_tokens) body.max_tokens = args.max_tokens\n        if (args.tenantKeyId) body.tenant_key_id = args.tenantKeyId\n\n        const res = await fetch(`${ctx.gatewayUrl}/api/v1/chat/completions`, {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/json',\n            'Authorization': `Bearer ${ctx.gatewayToken}`,\n          },\n          body: JSON.stringify(body),\n        })\n        return res.json()\n      }\n      case 'agentx_gateway_tenant_me': {\n        if (!ctx.gatewayUrl || !ctx.gatewayToken) throw new Error('Gateway not configured')\n        const res = await fetch(`${ctx.gatewayUrl}/api/v1/tenant/me`, {\n          headers: { 'Authorization': `Bearer ${ctx.gatewayToken}` },\n        })\n        return res.json()\n      }\n      case 'agentx_gateway_tenant_usage': {\n        if (!ctx.gatewayUrl || !ctx.gatewayToken) throw new Error('Gateway not configured')\n        const res = await fetch(`${ctx.gatewayUrl}/api/v1/tenant/usage?days=${args.days ?? 30}`, {\n          headers: { 'Authorization': `Bearer ${ctx.gatewayToken}` },\n        })\n        return res.json()\n      }\n      case 'agentx_gateway_tenant_keys': {\n        if (!ctx.gatewayUrl || !ctx.gatewayToken) throw new Error('Gateway not configured')\n        const res = await fetch(`${ctx.gatewayUrl}/api/v1/tenant/keys`, {\n          headers: { 'Authorization': `Bearer ${ctx.gatewayToken}` },\n        })\n        return res.json()\n      }\n      case 'agentx_gateway_models': {\n        if (!ctx.gatewayUrl || !ctx.gatewayToken) throw new Error('Gateway not configured')\n        const res = await fetch(`${ctx.gatewayUrl}/api/v1/models`, {\n          headers: { 'Authorization': `Bearer ${ctx.gatewayToken}` },\n        })\n        return res.json()\n      }\n\n      // ── IPFS ───────────────────────────────────────\n      case 'agentx_ipfs_upload': {\n        if (!ctx.ipfsUploader) throw new Error('IPFSUploader not configured')\n        const data = typeof args.data === 'string' ? JSON.parse(args.data as string) : args.data\n        const result = await ctx.ipfsUploader.uploadJSON(data, { name: args.name as string })\n        return { cid: result.cid, url: result.url }\n      }\n      case 'agentx_ipfs_upload_encrypted': {\n        if (!ctx.ipfsUploader) throw new Error('IPFSUploader not configured')\n        const { generateAesKey, encryptPayload } = await import('../../core/crypto')\n        const privatePayload = {\n          prompt: args.prompt as string,\n          skills: args.skillsJson ? JSON.parse(args.skillsJson as string) : [],\n          mcp: args.mcpJson ? JSON.parse(args.mcpJson as string) : {},\n        }\n        const key = generateAesKey()\n        const encrypted = encryptPayload(privatePayload, key)\n        const result = await ctx.ipfsUploader.uploadEncryptedPayload(encrypted, args.agentName as string)\n        return { cid: result.cid, url: result.url, aesKeyHex: key }\n      }\n      case 'agentx_ipfs_get_url': {\n        const gateway = (args.gateway as string) ?? 'https://ipfs.io'\n        return { url: `${gateway}/ipfs/${args.cid}` }\n      }\n\n      default:\n        throw new Error(`Unknown platform tool: ${toolName}`)\n    }\n  } catch (err: unknown) {\n    const message = err instanceof Error ? err.message : String(err)\n    return { error: message, tool: toolName }\n  }\n}\n\n// ── Agent Loop Integration ──────────────────────────────────────────────────\n\n/**\n * Merge platform tools into an AgentLoop's skill list.\n * When AgentLoop calls execute(toolName, args), the platform executor handles it.\n */\nexport function wrapPlatformToolsAsSkills(\n  ctx: PlatformToolContext,\n  modules?: ('identity' | 'subscription' | 'a2a' | 'reputation' | 'configuration' | 'endpoint' | 'gateway' | 'ipfs')[]\n): RunnableSkill[] {\n  const toolDefs = buildPlatformTools(modules)\n\n  return toolDefs.map(def => ({\n    name: def.function.name,\n    description: def.function.description,\n    inputSchema: def.function.parameters as Record<string, unknown>,\n    mode: 'open' as const,\n    execute: async (input: Record<string, unknown>) => {\n      return executePlatformTool(def.function.name, input, ctx)\n    },\n  }))\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — A2A Task Daemon\n// ---------------------------------------------------------------------------\n// Runs alongside AgentLoop to automatically process incoming A2A tasks.\n//\n// How it works:\n//   1. Poll Gateway API for LLM-processed task results assigned to this agent\n//   2. (or) directly check contract for pending tasks via getAgentTasks()\n//   3. Call completeTask() on-chain with the agent owner's wallet\n//\n// This enables TRUE multi-agent interop:\n//   Agent A → createTask(Agent B) on-chain\n//   Gateway Worker → detects task → LLM processes → stores result in DB\n//   Agent B's A2A Daemon → polls Gateway → gets result → completeTask() on-chain\n//\n// Usage:\n//   const daemon = new A2ADaemon({\n//     agentId: 53,\n//     a2a: a2aProtocol,\n//     gatewayUrl: 'https://agentx.0xainet.top',\n//     pollIntervalMs: 15000,\n//   })\n//   daemon.start()\n//   daemon.on('taskCompleted', (task) => console.log('Done:', task.taskId))\n// ---------------------------------------------------------------------------\n\nimport type { A2AProtocol } from '../a2a/a2a'\nimport type { A2ATask } from '../core/types'\nimport { EventEmitter } from 'events'\n\n// ── Config ──────────────────────────────────────────────────────────────────\n\nexport interface A2ADaemonConfig {\n  /** Your agent's numeric ID */\n  agentId: number\n  /** Initialized A2AProtocol instance */\n  a2a: A2AProtocol\n  /** Gateway URL for fetching pre-computed LLM results */\n  gatewayUrl?: string\n  /** Poll interval in milliseconds (default: 15000) */\n  pollIntervalMs?: number\n  /** If true, daemon will auto-complete tasks (call completeTask on-chain) */\n  autoComplete?: boolean\n  /** Max tasks to process per poll (default: 3) */\n  maxPerPoll?: number\n}\n\nexport interface A2ATaskResult {\n  task: A2ATask\n  /** LLM-generated output from Gateway (if available) */\n  gatewayOutput?: string\n  /** If task was auto-completed on-chain */\n  completed: boolean\n  /** Transaction hash if completed */\n  txHash?: string\n  /** Error message if failed */\n  error?: string\n}\n\n// ── Daemon ──────────────────────────────────────────────────────────────────\n\nexport class A2ADaemon extends EventEmitter {\n  private config: Required<Omit<A2ADaemonConfig, 'gatewayUrl'>> & { gatewayUrl?: string }\n  private timer: ReturnType<typeof setInterval> | null = null\n  private isRunning = false\n  private processedTasks = new Set<number>()\n\n  constructor(config: A2ADaemonConfig) {\n    super()\n    this.config = {\n      agentId: config.agentId,\n      a2a: config.a2a,\n      gatewayUrl: config.gatewayUrl,\n      pollIntervalMs: config.pollIntervalMs ?? 15_000,\n      autoComplete: config.autoComplete ?? true,\n      maxPerPoll: config.maxPerPoll ?? 3,\n    }\n  }\n\n  // ── Lifecycle ────────────────────────────────────────────────────────────\n\n  start(): void {\n    if (this.timer) return\n    console.log(`[A2A Daemon] Starting for agent #${this.config.agentId}, poll: ${this.config.pollIntervalMs}ms`)\n    this.timer = setInterval(() => this.poll(), this.config.pollIntervalMs)\n    this.poll()\n  }\n\n  stop(): void {\n    if (this.timer) {\n      clearInterval(this.timer)\n      this.timer = null\n      console.log(`[A2A Daemon] Stopped for agent #${this.config.agentId}`)\n    }\n  }\n\n  get status(): { running: boolean; agentId: number; processedCount: number } {\n    return {\n      running: this.timer !== null,\n      agentId: this.config.agentId,\n      processedCount: this.processedTasks.size,\n    }\n  }\n\n  // ── Core Logic ───────────────────────────────────────────────────────────\n\n  private async poll(): Promise<void> {\n    if (this.isRunning) return\n    this.isRunning = true\n\n    try {\n      const pendingTasks = await this.getPendingTasks()\n      if (pendingTasks.length === 0) {\n        this.isRunning = false\n        return\n      }\n\n      console.log(`[A2A Daemon] Found ${pendingTasks.length} pending task(s) for agent #${this.config.agentId}`)\n\n      let processed = 0\n      for (const task of pendingTasks) {\n        if (processed >= this.config.maxPerPoll) break\n\n        try {\n          const result = await this.processPendingTask(task)\n          processed++\n\n          if (result.completed) {\n            this.processedTasks.add(task.taskId)\n            this.emit('taskCompleted', result)\n            console.log(`[A2A Daemon] Task #${task.taskId} completed, tx: ${result.txHash?.slice(0, 10)}...`)\n          } else if (result.error) {\n            this.emit('taskFailed', result)\n            console.warn(`[A2A Daemon] Task #${task.taskId} failed: ${result.error}`)\n          }\n        } catch (err: any) {\n          console.error(`[A2A Daemon] Error processing task #${task.taskId}:`, err.message)\n        }\n      }\n    } catch (err: any) {\n      console.error('[A2A Daemon] Poll error:', err.message)\n    } finally {\n      this.isRunning = false\n    }\n  }\n\n  /**\n   * Get pending tasks assigned to this agent using getAgentTasks() from the contract.\n   */\n  private async getPendingTasks(): Promise<A2ATask[]> {\n    try {\n      const allTasks = await this.config.a2a.getAgentTasks(this.config.agentId)\n      return allTasks.filter(\n        t => (t.status === 'created' || t.status === 'accepted') &&\n             !this.processedTasks.has(t.taskId)\n      )\n    } catch (err: any) {\n      console.warn('[A2A Daemon] Failed to fetch pending tasks:', err.message)\n      return []\n    }\n  }\n\n  /**\n   * Process a pending A2A task:\n   *   1. Try Gateway API for pre-computed LLM result\n   *   2. Call completeTask() on-chain with the owner's wallet\n   */\n  private async processPendingTask(task: A2ATask): Promise<A2ATaskResult> {\n    let gatewayOutput: string | undefined\n\n    // 1. Try Gateway API for pre-computed result\n    if (this.config.gatewayUrl) {\n      try {\n        const res = await fetch(\n          `${this.config.gatewayUrl}/api/v1/a2a/task-result/${task.taskId}`\n        )\n        if (res.ok) {\n          const data = await res.json() as any\n          if (data.status === 2 && data.output_data) {\n            gatewayOutput = data.output_data\n            console.log(`[A2A Daemon] Got result for task #${task.taskId} from Gateway`)\n          }\n        }\n      } catch (err: any) {\n        console.warn(`[A2A Daemon] Gateway unavailable for task #${task.taskId}:`, err.message)\n      }\n    }\n\n    // 2. Determine output content\n    const outputContent = gatewayOutput ||\n      `Task processed. Type: ${task.taskType}. Input: ${task.input}`\n\n    // 3. Auto-complete on-chain using owner's wallet\n    if (this.config.autoComplete) {\n      try {\n        // completeTask(taskId, output, status)\n        // status: 3=completed, 4=failed\n        const txHash = await this.config.a2a.completeTask(\n          task.taskId,\n          outputContent,\n          3  // completed\n        )\n\n        return { task, gatewayOutput, completed: true, txHash }\n      } catch (err: any) {\n        return { task, gatewayOutput, completed: false, error: err.message }\n      }\n    }\n\n    return { task, gatewayOutput, completed: false }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — OpenAI Provider\n// ---------------------------------------------------------------------------\n// Direct OpenAI-compatible chat completions with SSE streaming.\n// Supports: OpenAI, DeepSeek, and any /v1/chat/completions endpoint.\n// ---------------------------------------------------------------------------\n\nimport type { ChatRequest, ChatStreamEvent, LLMProvider } from '../agent-loop/types'\nimport type { OpenAIProviderConfig } from './types'\n\nconst DEFAULT_ENDPOINT = 'https://api.openai.com/v1'\n\ninterface SSEData {\n  choices?: {\n    index: number\n    delta?: {\n      content?: string\n      tool_calls?: {\n        index: number\n        id?: string\n        function?: { name?: string; arguments?: string }\n      }[]\n    }\n    finish_reason?: string | null\n  }[]\n  usage?: {\n    prompt_tokens: number\n    completion_tokens: number\n    total_tokens: number\n  }\n}\n\nexport class OpenAIProvider implements LLMProvider {\n  private config: Required<OpenAIProviderConfig>\n\n  /** Model the provider is configured with (used by AgentLoop when no explicit ctx.model) */\n  get model(): string | undefined {\n    return this.config.model\n  }\n\n  constructor(config: OpenAIProviderConfig) {\n    this.config = {\n      endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n      model: config.model,\n      apiKey: config.apiKey,\n      temperature: config.temperature ?? 0.7,\n      maxTokens: config.maxTokens ?? 4096,\n      timeoutMs: config.timeoutMs ?? 60_000,\n    }\n  }\n\n  async *chatStream(request: ChatRequest, signal?: AbortSignal): AsyncGenerator<ChatStreamEvent> {\n    const endpoint = `${this.config.endpoint}/chat/completions`\n\n    const body = JSON.stringify({\n      model: request.model || this.config.model,\n      messages: request.messages,\n      tools: request.tools,\n      temperature: request.temperature ?? this.config.temperature,\n      max_tokens: request.maxTokens ?? this.config.maxTokens,\n      stream: true,\n      stream_options: { include_usage: true },\n    })\n\n    let response: Response\n    try {\n      response = await fetch(endpoint, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          'Authorization': `Bearer ${this.config.apiKey}`,\n        },\n        body,\n        signal,\n      })\n    } catch (err) {\n      if ((err as Error).name === 'AbortError') {\n        yield { type: 'error', error: new Error('Request aborted') }\n      } else {\n        yield { type: 'error', error: err instanceof Error ? err : new Error(String(err)) }\n      }\n      return\n    }\n\n    if (!response.ok) {\n      let errorText = ''\n      try { errorText = await response.text() } catch { /* ignore */ }\n      yield { type: 'error', error: new Error(`HTTP ${response.status}: ${errorText}`) }\n      return\n    }\n\n    const reader = response.body?.getReader()\n    if (!reader) {\n      yield { type: 'error', error: new Error('No response body') }\n      return\n    }\n\n    const decoder = new TextDecoder()\n    let buffer = ''\n\n    // DeepSeek/OpenAI 流式 tool_calls: 首 chunk 带 id+name, 后续参数增量 chunk 只带 index。\n    // 维护 index→id 映射, 使 delta 能关联到 start 的真实 callId, 否则 arguments 会被丢弃。\n    const callIdsByIndex = new Map<number, string>()\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (done) break\n\n        buffer += decoder.decode(value, { stream: true })\n        const lines = buffer.split('\\n')\n        buffer = lines.pop() ?? ''\n\n        for (const line of lines) {\n          const trimmed = line.trim()\n          if (!trimmed || !trimmed.startsWith('data:')) continue\n\n          const dataStr = trimmed.slice(5).trim()\n          if (dataStr === '[DONE]') {\n            continue\n          }\n\n          let data: SSEData\n          try {\n            data = JSON.parse(dataStr)\n          } catch {\n            continue\n          }\n\n          if (data.usage) {\n            yield {\n              type: 'done',\n              usage: {\n                promptTokens: data.usage.prompt_tokens,\n                completionTokens: data.usage.completion_tokens,\n                totalTokens: data.usage.total_tokens,\n              },\n            }\n            continue\n          }\n\n          const choice = data.choices?.[0]\n          if (!choice) continue\n\n          if (choice.delta?.content) {\n            yield { type: 'text_delta', content: choice.delta.content }\n          }\n\n          if (choice.delta?.tool_calls) {\n            for (const tc of choice.delta.tool_calls) {\n              if (tc.id) callIdsByIndex.set(tc.index, tc.id)\n              if (tc.id && tc.function?.name) {\n                yield { type: 'tool_call_start', callId: tc.id, name: tc.function.name }\n              }\n              if (tc.function?.arguments) {\n                yield {\n                  type: 'tool_call_delta',\n                  callId: tc.id ?? callIdsByIndex.get(tc.index) ?? `call_${tc.index}`,\n                  arguments: tc.function.arguments,\n                }\n              }\n            }\n          }\n\n          if (choice.finish_reason === 'stop' && !data.usage) {\n            yield {\n              type: 'done',\n              usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0 },\n            }\n          }\n        }\n      }\n    } catch (err) {\n      if ((err as Error).name !== 'AbortError') {\n        yield { type: 'error', error: err instanceof Error ? err : new Error(String(err)) }\n      }\n    } finally {\n      reader.releaseLock()\n    }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Gateway Provider\n// ---------------------------------------------------------------------------\n// Routes LLM requests through AgentX Gateway for multi-tenant SaaS mode.\n// Gateway handles: auth, rate limiting, API key injection, usage tracking.\n// API Key never appears in the browser.\n// ---------------------------------------------------------------------------\n\nimport type { ChatRequest, ChatStreamEvent, LLMProvider } from '../agent-loop/types'\nimport type { GatewayProviderConfig } from './types'\n\ninterface GatewaySSEData {\n  choices?: {\n    index: number\n    delta?: {\n      content?: string\n      tool_calls?: {\n        index: number\n        id?: string\n        function?: { name?: string; arguments?: string }\n      }[]\n    }\n    finish_reason?: string | null\n  }[]\n  usage?: {\n    prompt_tokens: number\n    completion_tokens: number\n    total_tokens: number\n  }\n  error?: { message: string; code?: string }\n}\n\nexport class GatewayProvider implements LLMProvider {\n  private config: Required<Omit<GatewayProviderConfig, 'model' | 'tenantKeyId'>>\n    & Pick<GatewayProviderConfig, 'model' | 'tenantKeyId'>\n\n  /** Model the provider is configured with (used by AgentLoop when no explicit ctx.model) */\n  get model(): string | undefined {\n    return this.config.model\n  }\n\n  constructor(config: GatewayProviderConfig) {\n    this.config = {\n      gatewayUrl: config.gatewayUrl.replace(/\\/$/, ''),\n      accessToken: config.accessToken,\n      keySource: config.keySource ?? 'platform',\n      model: config.model,\n      tenantKeyId: config.tenantKeyId,\n      temperature: config.temperature ?? 0.7,\n      maxTokens: config.maxTokens ?? 4096,\n      timeoutMs: config.timeoutMs ?? 120_000,\n    }\n  }\n\n  async *chatStream(request: ChatRequest, signal?: AbortSignal): AsyncGenerator<ChatStreamEvent> {\n    const endpoint = `${this.config.gatewayUrl}/api/v1/chat/completions`\n\n    const body: Record<string, unknown> = {\n      model: request.model || this.config.model || 'gpt-4o',\n      messages: request.messages,\n      stream: true,\n      key_source: this.config.keySource,\n    }\n    if (request.tools && request.tools.length > 0) body.tools = request.tools\n    if (request.temperature !== undefined) body.temperature = request.temperature\n    if (request.maxTokens !== undefined) body.max_tokens = request.maxTokens\n    if (this.config.tenantKeyId) body.tenant_key_id = this.config.tenantKeyId\n\n    let response: Response\n    try {\n      response = await fetch(endpoint, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          'Authorization': `Bearer ${this.config.accessToken}`,\n        },\n        body: JSON.stringify(body),\n        signal,\n      })\n    } catch (err) {\n      if ((err as Error).name === 'AbortError') {\n        yield { type: 'error', error: new Error('Request aborted') }\n      } else {\n        yield { type: 'error', error: err instanceof Error ? err : new Error(String(err)) }\n      }\n      return\n    }\n\n    if (!response.ok) {\n      let errorMsg = `Gateway HTTP ${response.status}`\n      try {\n        const errBody = await response.json() as { error?: string; message?: string }\n        errorMsg = errBody.error || errBody.message || errorMsg\n      } catch { /* use default */ }\n\n      yield { type: 'error', error: new Error(errorMsg) }\n      return\n    }\n\n    const reader = response.body?.getReader()\n    if (!reader) {\n      yield { type: 'error', error: new Error('No response body from gateway') }\n      return\n    }\n\n    const decoder = new TextDecoder()\n    let buffer = ''\n\n    // DeepSeek/OpenAI 流式 tool_calls: 首 chunk 带 id+name, 后续参数增量 chunk 只带 index。\n    // 维护 index→id 映射, 使 delta 能关联到 start 的真实 callId, 否则 arguments 会被丢弃。\n    const callIdsByIndex = new Map<number, string>()\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (done) break\n\n        buffer += decoder.decode(value, { stream: true })\n        const lines = buffer.split('\\n')\n        buffer = lines.pop() ?? ''\n\n        for (const line of lines) {\n          const trimmed = line.trim()\n          if (!trimmed || !trimmed.startsWith('data:')) continue\n\n          const dataStr = trimmed.slice(5).trim()\n          if (dataStr === '[DONE]') continue\n\n          let data: GatewaySSEData\n          try { data = JSON.parse(dataStr) } catch { continue }\n\n          if (data.error) {\n            yield { type: 'error', error: new Error(data.error.message) }\n            return\n          }\n\n          if (data.usage) {\n            yield {\n              type: 'done',\n              usage: {\n                promptTokens: data.usage.prompt_tokens,\n                completionTokens: data.usage.completion_tokens,\n                totalTokens: data.usage.total_tokens,\n              },\n            }\n            continue\n          }\n\n          const choice = data.choices?.[0]\n          if (!choice) continue\n\n          if (choice.delta?.content) {\n            yield { type: 'text_delta', content: choice.delta.content }\n          }\n\n          if (choice.delta?.tool_calls) {\n            for (const tc of choice.delta.tool_calls) {\n              if (tc.id) callIdsByIndex.set(tc.index, tc.id)\n              if (tc.id && tc.function?.name) {\n                yield { type: 'tool_call_start', callId: tc.id, name: tc.function.name }\n              }\n              if (tc.function?.arguments) {\n                yield {\n                  type: 'tool_call_delta',\n                  callId: tc.id ?? callIdsByIndex.get(tc.index) ?? `call_${tc.index}`,\n                  arguments: tc.function.arguments,\n                }\n              }\n            }\n          }\n\n          if (choice.finish_reason === 'stop' && !data.usage) {\n            yield {\n              type: 'done',\n              usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0 },\n            }\n          }\n        }\n      }\n    } catch (err) {\n      if ((err as Error).name !== 'AbortError') {\n        yield { type: 'error', error: err instanceof Error ? err : new Error(String(err)) }\n      }\n    } finally {\n      reader.releaseLock()\n    }\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Provider Factory\n// ---------------------------------------------------------------------------\n// Creates the appropriate LLMProvider based on config.\n// ---------------------------------------------------------------------------\n\nimport type { LLMProvider } from '../agent-loop/types'\nimport type { ProviderFactoryConfig } from './types'\nimport { OpenAIProvider } from './openai-provider'\nimport { GatewayProvider } from './gateway-provider'\n\nexport function createLLMProvider(config: ProviderFactoryConfig): LLMProvider {\n  switch (config.type) {\n    case 'gateway':\n      if (!config.gatewayUrl || !config.accessToken) {\n        throw new Error('GatewayProvider requires gatewayUrl and accessToken')\n      }\n      return new GatewayProvider({\n        gatewayUrl: config.gatewayUrl,\n        accessToken: config.accessToken,\n        model: config.model,\n        keySource: config.keySource,\n        tenantKeyId: config.tenantKeyId,\n        temperature: config.temperature,\n        maxTokens: config.maxTokens,\n        timeoutMs: config.timeoutMs,\n      })\n\n    case 'openai':\n      if (!config.apiKey) {\n        throw new Error('OpenAIProvider requires apiKey')\n      }\n      return new OpenAIProvider({\n        apiKey: config.apiKey,\n        endpoint: config.endpoint,\n        model: config.model ?? 'gpt-4o',\n        temperature: config.temperature,\n        maxTokens: config.maxTokens,\n        timeoutMs: config.timeoutMs,\n      })\n\n    case 'direct':\n      if (!config.apiKey) {\n        throw new Error('Direct provider requires apiKey')\n      }\n      return new OpenAIProvider({\n        apiKey: config.apiKey,\n        endpoint: config.endpoint,\n        model: config.model ?? 'gpt-4o',\n        temperature: config.temperature,\n        maxTokens: config.maxTokens,\n        timeoutMs: config.timeoutMs,\n      })\n\n    default:\n      throw new Error(`Unknown provider type: ${(config as { type: string }).type}`)\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Subscription Manager v2\n// ---------------------------------------------------------------------------\n// Wraps SubscriptionManager v2 contract (escrow, platform fee, multi-currency).\n// Uses viem PublicClient / WalletClient (chain-agnostic).\n// ---------------------------------------------------------------------------\n\nimport { decodeEventLog, parseAbiItem, toEventHash } from 'viem'\nimport type { PublicClient, WalletClient, Account, Address, Hash, Hex } from 'viem'\nimport type { AgentSubscription } from '../core/types'\n\nexport const ZERO_ADDRESS: Address = '0x0000000000000000000000000000000000000000'\n\n// ── Event ABI (for receipt parsing) ────────────────────────────────────────\n\nconst PLAN_CREATED_EVENT = parseAbiItem(\n  'event PlanCreated(uint256 indexed planId, uint256 indexed agentId, uint256 price, string period, address payToken, uint256 trialDays)'\n)\nconst SUBSCRIBED_EVENT = parseAbiItem(\n  'event Subscribed(uint256 indexed subscriptionId, address indexed subscriber, uint256 indexed agentId, uint256 expiresAt)'\n)\nconst PLAN_CREATED_TOPIC = toEventHash(PLAN_CREATED_EVENT)\nconst SUBSCRIBED_TOPIC = toEventHash(SUBSCRIBED_EVENT)\n\n// ── ABI Fragments (v2) ─────────────────────────────────────────────────────\n\nconst SUBSCRIPTION_ABI_V2 = {\n  // Admin\n  platformFeeBps: {\n    inputs: [] as const, name: 'platformFeeBps' as const,\n    outputs: [{ name: '', type: 'uint256' }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  tokenWhitelist: {\n    inputs: [{ name: 'token', type: 'address' }] as const,\n    name: 'tokenWhitelist' as const,\n    outputs: [{ name: '', type: 'bool' }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  // Plans\n  createPlan: {\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'price', type: 'uint256' },\n      { name: 'period', type: 'string' },\n      { name: 'payToken', type: 'address' },\n      { name: 'trialDays', type: 'uint256' },\n    ] as const,\n    name: 'createPlan' as const,\n    outputs: [{ name: 'planId', type: 'uint256' }] as const,\n    stateMutability: 'nonpayable' as const, type: 'function' as const,\n  },\n  getPlan: {\n    inputs: [{ name: 'planId', type: 'uint256' }] as const,\n    name: 'getPlan' as const,\n    // Contract returns `SubscriptionPlan memory` (struct → dynamic tuple encoding).\n    outputs: [{\n      type: 'tuple' as const,\n      components: [\n        { name: 'planId', type: 'uint256' } as const,\n        { name: 'agentId', type: 'uint256' } as const,\n        { name: 'creator', type: 'address' } as const,\n        { name: 'price', type: 'uint256' } as const,\n        { name: 'period', type: 'string' } as const,\n        { name: 'active', type: 'bool' } as const,\n        { name: 'payToken', type: 'address' } as const,\n        { name: 'trialDays', type: 'uint256' } as const,\n      ],\n    }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  // Subscribe\n  subscribe: {\n    inputs: [{ name: 'planId', type: 'uint256' }] as const,\n    name: 'subscribe' as const,\n    outputs: [{ name: 'subscriptionId', type: 'uint256' }] as const,\n    stateMutability: 'payable' as const, type: 'function' as const,\n  },\n  // Trial / Release\n  releaseFunds: {\n    inputs: [{ name: 'subscriptionId', type: 'uint256' }] as const,\n    name: 'releaseFunds' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const, type: 'function' as const,\n  },\n  cancelSubscription: {\n    inputs: [{ name: 'subscriptionId', type: 'uint256' }] as const,\n    name: 'cancelSubscription' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const, type: 'function' as const,\n  },\n  // Queries\n  getSubscription: {\n    inputs: [\n      { name: 'subscriber', type: 'address' },\n      { name: 'agentId', type: 'uint256' },\n    ] as const,\n    name: 'getSubscription' as const,\n    outputs: [\n      { name: 'subscriptionId', type: 'uint256' },\n      { name: 'subscriber', type: 'address' },\n      { name: 'agentId', type: 'uint256' },\n      { name: 'status', type: 'uint8' },\n      { name: 'startedAt', type: 'uint256' },\n      { name: 'expiresAt', type: 'uint256' },\n      { name: 'period', type: 'string' },\n    ] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  hasActiveSubscription: {\n    inputs: [\n      { name: 'subscriber', type: 'address' },\n      { name: 'agentId', type: 'uint256' },\n    ] as const,\n    name: 'hasActiveSubscription' as const,\n    outputs: [{ name: '', type: 'bool' }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  getUserSubscriptions: {\n    inputs: [{ name: 'user', type: 'address' }] as const,\n    name: 'getUserSubscriptions' as const,\n    outputs: [{ name: '', type: 'uint256[]' }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n  getSubscriptionDetail: {\n    inputs: [{ name: 'subscriptionId', type: 'uint256' }] as const,\n    name: 'getSubscriptionDetail' as const,\n    outputs: [\n      { name: 'subscriptionId', type: 'uint256' },\n      { name: 'subscriber', type: 'address' },\n      { name: 'agentId', type: 'uint256' },\n      { name: 'status', type: 'uint8' },\n      { name: 'startedAt', type: 'uint256' },\n      { name: 'expiresAt', type: 'uint256' },\n      { name: 'period', type: 'string' },\n      { name: 'payToken', type: 'address' },\n      { name: 'amountPaid', type: 'uint256' },\n      { name: 'trialActive', type: 'bool' },\n      { name: 'trialEndsAt', type: 'uint256' },\n      { name: 'fundsReleased', type: 'bool' },\n    ] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n} as const\n\n// ── ERC20 ABI (approve) ────────────────────────────────────────────────────\n\nconst ERC20_ABI = {\n  approve: {\n    inputs: [\n      { name: 'spender', type: 'address' },\n      { name: 'amount', type: 'uint256' },\n    ] as const,\n    name: 'approve' as const,\n    outputs: [{ name: '', type: 'bool' }] as const,\n    stateMutability: 'nonpayable' as const, type: 'function' as const,\n  },\n  allowance: {\n    inputs: [\n      { name: 'owner', type: 'address' },\n      { name: 'spender', type: 'address' },\n    ] as const,\n    name: 'allowance' as const,\n    outputs: [{ name: '', type: 'uint256' }] as const,\n    stateMutability: 'view' as const, type: 'function' as const,\n  },\n} as const\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface SubscriptionConfig {\n  contractAddress: Address\n  publicClient: PublicClient\n  walletClient: WalletClient\n}\n\nexport interface PlanDetail {\n  planId: number\n  agentId: number\n  creator: Address\n  price: bigint\n  period: string\n  active: boolean\n  payToken: Address        // address(0) = ETH\n  trialDays: number\n}\n\nexport interface SubscriptionDetail {\n  subscriptionId: number\n  subscriber: Address\n  agentId: number\n  status: number            // 0=Inactive, 1=Active, 2=Expired, 3=Cancelled\n  startedAt: number\n  expiresAt: number\n  period: string\n  payToken: Address\n  amountPaid: bigint\n  trialActive: boolean\n  trialEndsAt: number\n  fundsReleased: boolean\n}\n\n// On-chain `SubscriptionStatus` enum (contracts/src/SubscriptionManager.sol):\n//   0=Inactive, 1=Active, 2=Expired, 3=Cancelled\n// Mapped to the typed SubscriptionStatus string; Inactive is surfaced as\n// 'pending' (SubscriptionStatus has no 'inactive' member).\nconst SUBSCRIPTION_STATUS_NAMES: Record<number, AgentSubscription['status']> = {\n  0: 'pending',\n  1: 'active',\n  2: 'expired',\n  3: 'cancelled',\n}\n\n// ── Period ─────────────────────────────────────────────────────────────────\n// On-chain `_periodToSeconds` only recognizes day/week/month/year; any other\n// string silently falls back to 30 days. Typed here so consumers cannot pass\n// e.g. 'monthly'/'yearly' and get a wrong expiry (silently falling back to 30 days).\n\nexport const SUBSCRIPTION_PERIODS = ['day', 'week', 'month', 'year'] as const\nexport type SubscriptionPeriod = (typeof SUBSCRIPTION_PERIODS)[number]\n\nexport interface CreatePlanParams {\n  agentId: number\n  /** Price in wei (native token) or token units for ERC20 plans. */\n  price: bigint\n  /** Must be one of: day | week | month | year (contract-valid enum). */\n  period: SubscriptionPeriod\n  /** ERC20 pay token; default zero address = native token. */\n  payToken?: Address\n  /** Trial days (0–30). Default 0 = no trial. */\n  trialDays?: number\n}\n\nexport interface CreatePlanResult {\n  planId: number\n  txHash: Hash\n}\n\nexport interface SubscribeResult {\n  subscriptionId: number\n  txHash: Hash\n  subscriber: Address\n  agentId: number\n  /** Unix timestamp (seconds) when the subscription expires. */\n  expiresAt: number\n}\n\n// ── Subscription Manager ───────────────────────────────────────────────────\n\nexport class SubscriptionManager {\n  private address: Address\n  private publicClient: PublicClient\n  private walletClient: WalletClient\n\n  constructor(config: SubscriptionConfig) {\n    this.address = config.contractAddress\n    this.publicClient = config.publicClient\n    this.walletClient = config.walletClient\n  }\n\n  /**\n   * Resolve the caller account for write operations.\n   *\n   * Prefers `walletClient.account` (a full viem Account object with signing\n   * capability) over `getAddresses()[0]` (a bare address string). Passing a\n   * bare string as `account` makes viem route `writeContract` through\n   * `eth_sendTransaction` (node-managed accounts only), which fails for local\n   * signers; the full object enables local signing via `eth_sendRawTransaction`.\n   * In browser wallets (e.g. MetaMask) `client.account` is a json-rpc account\n   * and the provider signs, so both paths keep working.\n   */\n  private async _resolveAccount(): Promise<Account | Address> {\n    const clientAccount = this.walletClient.account as Account | undefined\n    if (clientAccount) return clientAccount\n    const [address] = await this.walletClient.getAddresses()\n    if (!address) throw new Error('Wallet not connected')\n    return address\n  }\n\n  // ── Config Read ──────────────────────────────────────────────────────────\n\n  /** Get current platform fee in basis points (e.g. 250 = 2.5%). */\n  async getPlatformFeeBps(): Promise<number> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.platformFeeBps],\n      functionName: 'platformFeeBps',\n    })\n    return Number(result)\n  }\n\n  /** Check if a token is whitelisted for payments. */\n  async isTokenWhitelisted(token: Address): Promise<boolean> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.tokenWhitelist],\n      functionName: 'tokenWhitelist',\n      args: [token],\n    })\n    return result as boolean\n  }\n\n  // ── Plans ────────────────────────────────────────────────────────────────\n\n  /** Get full plan details with v2 fields. */\n  async getPlan(planId: number): Promise<PlanDetail> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.getPlan],\n      functionName: 'getPlan',\n      args: [BigInt(planId)],\n    })\n    // Contract returns a struct — viem decodes it to a named object\n    // (older viem versions returned a tuple; the object form is current).\n    const r = result as unknown as {\n      planId: bigint; agentId: bigint; creator: string; price: bigint;\n      period: string; active: boolean; payToken: string; trialDays: bigint\n    }\n    return {\n      planId: Number(r.planId), agentId: Number(r.agentId),\n      creator: r.creator as Address, price: r.price, period: r.period, active: r.active,\n      payToken: r.payToken as Address, trialDays: Number(r.trialDays),\n    }\n  }\n\n  // ── Plans ────────────────────────────────────────────────────────────────\n\n  /**\n   * Create a subscription plan for an agent.\n   *\n   * @param params.period  Must be 'day' | 'week' | 'month' | 'year' — the only\n   *                       values the contract maps to real durations. Anything\n   *                       else silently becomes 30 days on-chain.\n   * @returns              { planId, txHash } (planId parsed from PlanCreated event)\n   */\n  async createPlan(params: CreatePlanParams): Promise<CreatePlanResult> {\n    const { agentId, price, period, payToken = ZERO_ADDRESS, trialDays = 0 } = params\n\n    if (!SUBSCRIPTION_PERIODS.includes(period)) {\n      throw new Error(\n        `Invalid period \"${period}\". Must be one of: ${SUBSCRIPTION_PERIODS.join(', ')}`\n      )\n    }\n    if (trialDays < 0 || trialDays > 30) {\n      throw new Error('trialDays must be between 0 and 30')\n    }\n\n    const account = await this._resolveAccount()\n\n    const { request } = await this.publicClient.simulateContract({\n      account,\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.createPlan],\n      functionName: 'createPlan',\n      args: [BigInt(agentId), price, period, payToken, BigInt(trialDays)],\n    })\n    const hash = await this.walletClient.writeContract({ ...request, account })\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n\n    return { planId: this._parsePlanIdFromReceipt(receipt), txHash: hash }\n  }\n\n  /**\n   * Subscribe to a plan.\n   * For ETH plans: pass valueWei = plan.price.\n   * For ERC20 plans: auto-detects from plan.payToken, calls approve + subscribe.\n   *                    User must have approved this contract for plan.price tokens.\n   *\n   * @returns SubscribeResult — subscriptionId/expiresAt/subscriber parsed from\n   *          the Subscribed event (no longer hardcoded to 0).\n   */\n  async subscribe(\n    planId: number,\n    opts?: { valueWei?: bigint; approveTokenFirst?: boolean }\n  ): Promise<SubscribeResult> {\n    const account = await this._resolveAccount()\n\n    const plan = await this.getPlan(planId)\n    if (!plan.active) throw new Error('Plan not active')\n\n    if (plan.payToken === ZERO_ADDRESS) {\n      // ── ETH ──\n      const value = opts?.valueWei ?? plan.price\n\n      const { request } = await this.publicClient.simulateContract({\n        account,\n        address: this.address,\n        abi: [SUBSCRIPTION_ABI_V2.subscribe],\n        functionName: 'subscribe',\n        args: [BigInt(planId)],\n        value,\n      })\n      const hash = await this.walletClient.writeContract({ ...request, account })\n      const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n      return { txHash: hash, ...this._parseSubscribedFromReceipt(receipt) }\n    } else {\n      // ── ERC20 ──\n      const accountAddress = typeof account === 'string' ? account : account.address\n      // Optionally approve first\n      if (opts?.approveTokenFirst !== false) {\n        const allowance = await this.publicClient.readContract({\n          address: plan.payToken,\n          abi: [ERC20_ABI.allowance],\n          functionName: 'allowance',\n          args: [accountAddress, this.address],\n        })\n        if ((allowance as bigint) < plan.price) {\n          const { request: approveReq } = await this.publicClient.simulateContract({\n            account,\n            address: plan.payToken,\n            abi: [ERC20_ABI.approve],\n            functionName: 'approve',\n            args: [this.address, plan.price],\n          })\n          await this.walletClient.writeContract({ ...approveReq, account })\n        }\n      }\n\n      const { request } = await this.publicClient.simulateContract({\n        account,\n        address: this.address,\n        abi: [SUBSCRIPTION_ABI_V2.subscribe],\n        functionName: 'subscribe',\n        args: [BigInt(planId)],\n      })\n      const hash = await this.walletClient.writeContract({ ...request, account })\n      const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n      return { txHash: hash, ...this._parseSubscribedFromReceipt(receipt) }\n    }\n  }\n\n  /**\n   * One-step createPlan + subscribe (two transactions).\n   * Saves the caller one round of plan lookup when the plan does not exist yet.\n   */\n  async createPlanAndSubscribe(params: CreatePlanParams): Promise<CreatePlanResult & SubscribeResult> {\n    const { planId } = await this.createPlan(params)\n    const subscribed = await this.subscribe(planId)\n    return { planId, ...subscribed }\n  }\n\n  /** Release escrowed funds to creator after trial window ends. */\n  async releaseFunds(subscriptionId: number): Promise<Hash> {\n    const account = await this._resolveAccount()\n\n    const { request } = await this.publicClient.simulateContract({\n      account,\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.releaseFunds],\n      functionName: 'releaseFunds',\n      args: [BigInt(subscriptionId)],\n    })\n    return this.walletClient.writeContract({ ...request, account })\n  }\n\n  /** Cancel subscription (trial refund if within window). */\n  async cancel(subscriptionId: number): Promise<Hash> {\n    const account = await this._resolveAccount()\n\n    const { request } = await this.publicClient.simulateContract({\n      account,\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.cancelSubscription],\n      functionName: 'cancelSubscription',\n      args: [BigInt(subscriptionId)],\n    })\n    return this.walletClient.writeContract({ ...request, account })\n  }\n\n  // ── Read ─────────────────────────────────────────────────────────────────\n\n  async hasActiveSubscription(subscriber: Address, agentId: number): Promise<boolean> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.hasActiveSubscription],\n      functionName: 'hasActiveSubscription',\n      args: [subscriber, BigInt(agentId)],\n    })\n    return result as boolean\n  }\n\n  async getSubscription(subscriber: Address, agentId: number): Promise<AgentSubscription | null> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.getSubscription],\n      functionName: 'getSubscription',\n      args: [subscriber, BigInt(agentId)],\n    })\n    const [subId, sub, aId, status, started, expires, period] =\n      result as [bigint, string, bigint, number, bigint, bigint, string]\n    if (Number(subId) === 0) return null\n    return {\n      subscriptionId: Number(subId),\n      subscriber: sub as Address,\n      agentId: Number(aId),\n      status: SUBSCRIPTION_STATUS_NAMES[status] ?? 'pending',\n      startedAt: Number(started),\n      expiresAt: Number(expires),\n      period,\n    }\n  }\n\n  /** Get full subscription detail with v2 fields (trial, payToken, fundsReleased). */\n  async getSubscriptionDetail(subscriptionId: number): Promise<SubscriptionDetail> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.getSubscriptionDetail],\n      functionName: 'getSubscriptionDetail',\n      args: [BigInt(subscriptionId)],\n    })\n    const [sid, sub, aId, status, started, expires, period, payToken,\n           amountPaid, trialActive, trialEndsAt, fundsReleased] =\n      result as [bigint, string, bigint, number, bigint, bigint, string, string,\n                 bigint, boolean, bigint, boolean]\n    return {\n      subscriptionId: Number(sid), subscriber: sub as Address,\n      agentId: Number(aId), status, startedAt: Number(started),\n      expiresAt: Number(expires), period,\n      payToken: payToken as Address, amountPaid,\n      trialActive, trialEndsAt: Number(trialEndsAt), fundsReleased,\n    }\n  }\n\n  async getUserSubscriptions(user: Address): Promise<number[]> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [SUBSCRIPTION_ABI_V2.getUserSubscriptions],\n      functionName: 'getUserSubscriptions',\n      args: [user],\n    })\n    return (result as bigint[]).map(Number)\n  }\n\n  // ── Receipt parsing (event-driven, no hardcoded IDs) ─────────────────────\n\n  private _findEventLog(receipt: { logs: readonly unknown[] }, topic: Hex) {\n    return receipt.logs.find((l) => (l as { topics?: readonly unknown[] }).topics?.[0] === topic)\n  }\n\n  /** Parse planId from the PlanCreated event in a transaction receipt. */\n  private _parsePlanIdFromReceipt(receipt: { logs: readonly unknown[] }): number {\n    const log = this._findEventLog(receipt, PLAN_CREATED_TOPIC)\n    if (!log) {\n      throw new Error('PlanCreated event not found in transaction receipt')\n    }\n    const decoded = decodeEventLog({\n      abi: [PLAN_CREATED_EVENT],\n      data: (log as { data: Hex }).data,\n      topics: (log as { topics: [Hex, ...Hex[]] }).topics,\n    })\n    return Number(decoded.args.planId)\n  }\n\n  /** Parse subscriptionId/subscriber/agentId/expiresAt from the Subscribed event. */\n  private _parseSubscribedFromReceipt(receipt: { logs: readonly unknown[] }): Omit<SubscribeResult, 'txHash'> {\n    const log = this._findEventLog(receipt, SUBSCRIBED_TOPIC)\n    if (!log) {\n      throw new Error('Subscribed event not found in transaction receipt')\n    }\n    const decoded = decodeEventLog({\n      abi: [SUBSCRIBED_EVENT],\n      data: (log as { data: Hex }).data,\n      topics: (log as { topics: [Hex, ...Hex[]] }).topics,\n    })\n    return {\n      subscriptionId: Number(decoded.args.subscriptionId),\n      subscriber: decoded.args.subscriber as Address,\n      agentId: Number(decoded.args.agentId),\n      expiresAt: Number(decoded.args.expiresAt),\n    }\n  }\n}\n\n// ── Subscription Guard ─────────────────────────────────────────────────────\n\nexport async function guardSubscription(\n  manager: SubscriptionManager,\n  user: Address,\n  agentId: number\n): Promise<AgentSubscription> {\n  const active = await manager.hasActiveSubscription(user, agentId)\n  if (!active) {\n    throw new Error(\n      `No active subscription for agent #${agentId}. ` +\n      `Address ${user} must purchase a subscription first.`\n    )\n  }\n  const sub = await manager.getSubscription(user, agentId)\n  if (!sub) throw new Error(`Subscription not found for agent #${agentId}`)\n  return sub\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Agent Registry\n// ---------------------------------------------------------------------------\n// Wraps IdentityRegistry contract interactions (on-chain agent CRUD).\n//\n// Design:\n//   - Takes a viem PublicClient + WalletClient (chain-agnostic).\n//   - No wagmi dependency — works with any wallet provider that implements\n//     the WalletClient interface.\n//   - Methods match the existing ERC8004 IdentityRegistry ABI.\n// ---------------------------------------------------------------------------\n\nimport { encodeAbiParameters, parseAbiParameters, stringToHex, hexToString } from 'viem'\nimport type { PublicClient, WalletClient, Address, Hash } from 'viem'\nimport type { OnChainAgentMetadata } from '../core/types'\nimport { ZERO_ADDRESS } from '../subscription/subscription'\n\n// ── Minimal ABI Fragments ──────────────────────────────────────────────────\n\nconst IDENTITY_REGISTRY_ABI = {\n  // Register\n  register: {\n    inputs: [] as const,\n    name: 'register' as const,\n    outputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    stateMutability: 'payable' as const,\n    type: 'function' as const,\n  },\n  registerWithTokenURI: {\n    inputs: [{ name: 'tokenURI', type: 'string' }] as const,\n    name: 'register' as const,\n    outputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    stateMutability: 'payable' as const,\n    type: 'function' as const,\n  },\n  registerWithMetadata: {\n    inputs: [\n      { name: 'tokenURI', type: 'string' },\n      {\n        name: 'metadata',\n        type: 'tuple[]',\n        components: [\n          { name: 'key', type: 'string' },\n          { name: 'value', type: 'bytes' },\n        ],\n      },\n    ] as const,\n    name: 'registerWithMetadata' as const,\n    outputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    stateMutability: 'payable' as const,\n    type: 'function' as const,\n  },\n  // Queries\n  getAgentsByOwner: {\n    inputs: [{ name: 'owner', type: 'address' }] as const,\n    name: 'getAgentsByOwner' as const,\n    outputs: [{ name: '', type: 'uint256[]' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getCurrentAgentId: {\n    inputs: [] as const,\n    name: 'getCurrentAgentId' as const,\n    outputs: [{ name: '', type: 'uint256' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  agentExists: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'agentExists' as const,\n    outputs: [{ name: '', type: 'bool' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  tokenURI: {\n    inputs: [{ name: 'tokenId', type: 'uint256' }] as const,\n    name: 'tokenURI' as const,\n    outputs: [{ name: '', type: 'string' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getAgentMetadata: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getAgentMetadata' as const,\n    outputs: [{ name: '', type: 'tuple[]', components: [{ name: 'key', type: 'string' }, { name: 'value', type: 'bytes' }] }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  totalAgents: {\n    inputs: [] as const,\n    name: 'totalAgents' as const,\n    outputs: [{ name: '', type: 'uint256' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getAgentOwner: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getAgentOwner' as const,\n    outputs: [{ name: '', type: 'address' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n} as const\n\n// ── Registry Config ────────────────────────────────────────────────────────\n\nexport interface AgentRegistryConfig {\n  /** IdentityRegistry contract address */\n  contractAddress: Address\n  /** viem PublicClient for read calls */\n  publicClient: PublicClient\n  /** viem WalletClient for write calls */\n  walletClient: WalletClient\n}\n\n// ── Structured Metadata Types ───────────────────────────────────────────────\n\n/** Public, human-readable subset of on-chain agent metadata. */\nexport interface AgentSummaryMetadata {\n  name: string\n  description: string\n  capabilities: string[]\n  skills: string[]\n  /** Application category / use case (AGENT_CATEGORIES value; undefined = other). */\n  category?: string\n  /** Marketplace-visible availability; tokenURI JSON may override the default true. */\n  isActive: boolean\n}\n\n/** Lightweight agent record returned by getAllAgents(). */\nexport interface AgentSummary {\n  agentId: number\n  owner: string\n  tokenURI: string\n  metadata: AgentSummaryMetadata\n  /** Unix timestamp (seconds); 0 when the tokenURI metadata has no createdAt. */\n  createdAt: number\n}\n\nexport interface GetAllAgentsOptions {\n  /** First agent ID to scan (default: 1). */\n  fromId?: number\n  /** Last agent ID to scan (default: totalAgents()). */\n  toId?: number\n  /** Only return agents whose metadata.isActive === true (default: false). */\n  activeOnly?: boolean\n  /** Only return agents whose capabilities include ALL of these (AND). */\n  capabilities?: string[]\n  /** RPC batching size (default: 10). */\n  batchSize?: number\n}\n\n/** Full structured metadata for one agent (on-chain keys + tokenURI JSON). */\nexport interface StructuredAgentMetadata {\n  name: string\n  description: string\n  encryptedPayloadCid: string\n  eciesEncryptedKey: string\n  publicPayloadCid: string\n  capabilities: string[]\n  skills: string[]\n  /** Application category / use case (AGENT_CATEGORIES value; '' = other). */\n  category?: string\n  isActive: boolean\n}\n\n// ── tokenURI parsing helpers ────────────────────────────────────────────────\n\n/** Decode base64 in both Node and browser environments. */\nfunction decodeBase64(b64: string): string {\n  if (typeof Buffer !== 'undefined') {\n    return Buffer.from(b64, 'base64').toString('utf-8')\n  }\n  const bin = atob(b64)\n  const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0))\n  return new TextDecoder().decode(bytes)\n}\n\n/**\n * Parse base64 data-URI tokenURI → JSON metadata (null if not parseable).\n * Tolerant of contract bugs: trims trailing garbage after base64 padding,\n * repairs unterminated JSON (unclosed quotes/braces), and falls back to a\n * regex extraction of the name field.\n */\nexport function parseTokenURIJSON(tokenURI: string): Record<string, unknown> | null {\n  if (!tokenURI || tokenURI.startsWith('ipfs://')) return null\n  const match = tokenURI.match(/^data:application\\/json;base64,(.+)$/i)\n  if (!match) return null\n\n  // Clean up malformed base64: trim everything after the last \"==\" padding.\n  let b64 = match[1]!\n  const lastDoubleEq = b64.lastIndexOf('==')\n  if (lastDoubleEq > 0 && lastDoubleEq < b64.length - 2) {\n    b64 = b64.substring(0, lastDoubleEq + 2)\n  }\n\n  try {\n    const decoded = decodeBase64(b64)\n    // Try strict JSON parse first.\n    try {\n      return JSON.parse(decoded)\n    } catch {\n      // Unterminated JSON (contract bug): append missing closing quotes/braces.\n      let fixed = decoded\n      const quoteCount = (fixed.match(/\"/g) || []).length\n      if (quoteCount % 2 !== 0) fixed += '\"'\n      const openBraces = (fixed.match(/\\{/g) || []).length\n      const closeBraces = (fixed.match(/\\}/g) || []).length\n      for (let i = closeBraces; i < openBraces; i++) fixed += '}'\n      try { return JSON.parse(fixed) } catch { /* fall through */ }\n    }\n    // Regex fallback: extract the name field at least.\n    const nameM = decoded.match(/\"name\"\\s*:\\s*\"([^\"]*)/)\n    if (nameM) return { name: nameM[1] }\n    return null\n  } catch {\n    return null\n  }\n}\n\n/** Extract createdAt (unix seconds) from tokenURI JSON metadata. */\nfunction parseCreatedAt(parsed: Record<string, unknown> | null): number {\n  const v = parsed?.created_at ?? parsed?.createdAt\n  if (typeof v === 'number') return Math.floor(v)\n  if (typeof v === 'string') {\n    const t = Date.parse(v)\n    if (!Number.isNaN(t)) return Math.floor(t / 1000)\n  }\n  return 0\n}\n\n// ── Agent Registry ─────────────────────────────────────────────────────────\n\nexport class AgentRegistry {\n  private address: Address\n  private publicClient: PublicClient\n  private walletClient: WalletClient\n\n  constructor(config: AgentRegistryConfig) {\n    this.address = config.contractAddress\n    this.publicClient = config.publicClient\n    this.walletClient = config.walletClient\n  }\n\n  // ── Write: Register Agent ───────────────────────────────────────────────\n\n  /**\n   * Register a new Agent NFT on-chain.\n   *\n   * @param tokenURI    IPFS URI of the public metadata (ipfs://...)\n   * @param metadata    Key-value metadata (encryptedPayloadCid, eciesEncryptedKey, etc.)\n   * @param valueWei    Optional: native currency to send with registration\n   * @returns           { agentId: number, txHash: Hash }\n   */\n  async register(\n    tokenURI: string,\n    metadata: { key: string; value: string }[],\n    valueWei?: bigint\n  ): Promise<{ agentId: number; txHash: Hash }> {\n    const [account] = await this.walletClient.getAddresses()\n    if (!account) throw new Error('Wallet not connected')\n\n    const encodedMetadata = metadata.map(m => ({\n      key: m.key,\n      value: stringToHex(m.value),\n    }))\n\n    const { request } = await this.publicClient.simulateContract({\n      account,\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.registerWithMetadata],\n      functionName: 'registerWithMetadata',\n      args: [tokenURI, encodedMetadata],\n      value: valueWei,\n    })\n\n    const hash = await this.walletClient.writeContract(request)\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n\n    // Parse agentId from Transfer event (ERC-721)\n    const agentId = this._parseAgentIdFromReceipt(receipt)\n    return { agentId, txHash: hash }\n  }\n\n  /**\n   * Simple register — just a tokenURI, no extra metadata.\n   */\n  async registerSimple(tokenURI: string, valueWei?: bigint): Promise<{ agentId: number; txHash: Hash }> {\n    const [account] = await this.walletClient.getAddresses()\n    if (!account) throw new Error('Wallet not connected')\n\n    const abi = tokenURI\n      ? [IDENTITY_REGISTRY_ABI.registerWithTokenURI]\n      : [IDENTITY_REGISTRY_ABI.register]\n\n    const args = tokenURI ? [tokenURI] : []\n\n    const { request } = await this.publicClient.simulateContract({\n      account,\n      address: this.address,\n      abi: abi as any,\n      functionName: 'register',\n      args: args as any,\n      value: valueWei,\n    })\n\n    const hash = await this.walletClient.writeContract(request)\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n    const agentId = this._parseAgentIdFromReceipt(receipt)\n    return { agentId, txHash: hash }\n  }\n\n  // ── Read: Query ──────────────────────────────────────────────────────────\n\n  /** Get all agent IDs owned by an address. */\n  async getAgentsByOwner(owner: Address): Promise<number[]> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.getAgentsByOwner],\n      functionName: 'getAgentsByOwner',\n      args: [owner],\n    })\n    return (result as bigint[]).map(Number)\n  }\n\n  /** Get the current total agent count. */\n  async getCurrentAgentId(): Promise<number> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.getCurrentAgentId],\n      functionName: 'getCurrentAgentId',\n    })\n    return Number(result as bigint)\n  }\n\n  /** Check if an agent exists. */\n  async agentExists(agentId: number): Promise<boolean> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.agentExists],\n      functionName: 'agentExists',\n      args: [BigInt(agentId)],\n    })\n    return result as boolean\n  }\n\n  /** Get the tokenURI for an agent. */\n  async tokenURI(agentId: number): Promise<string> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.tokenURI],\n      functionName: 'tokenURI',\n      args: [BigInt(agentId)],\n    })\n    return result as string\n  }\n\n  /** Get all metadata attributes for an agent as key-value pairs. */\n  async getAttributes(agentId: number): Promise<Record<string, string>> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.getAgentMetadata],\n      functionName: 'getAgentMetadata',\n      args: [BigInt(agentId)],\n    })\n    const attrs: Record<string, string> = {}\n    for (const item of result as { key: string; value: string }[]) {\n      attrs[item.key] = hexToString(item.value as `0x${string}`)\n    }\n    return attrs\n  }\n\n  /** Total number of registered agents (monotonic max agent ID). */\n  async totalAgents(): Promise<number> {\n    const result = await this.publicClient.readContract({\n      address: this.address,\n      abi: [IDENTITY_REGISTRY_ABI.totalAgents],\n      functionName: 'totalAgents',\n    })\n    return Number(result as bigint)\n  }\n\n  /**\n   * Structured metadata for one agent.\n   * Combines on-chain attributes (encryptedPayloadCid / eciesEncryptedKey /\n   * publicPayloadCid) with the tokenURI JSON (name/description/capabilities/skills).\n   * `isActive` defaults to on-chain existence, overridable via tokenURI JSON.\n   */\n  async getAgentMetadata(agentId: number): Promise<StructuredAgentMetadata> {\n    const attrs = await this.getAttributes(agentId)\n    const parsed = parseTokenURIJSON(await this.tokenURI(agentId))\n\n    const str = (v: unknown) => (typeof v === 'string' ? v : '')\n    const arr = (v: unknown) => (Array.isArray(v) ? v.map(String) : [])\n    const caps = arr(parsed?.capabilities)\n    const skills = arr(parsed?.skills)\n\n    return {\n      name: str(parsed?.name) || str(attrs.name) || `Agent ${agentId}`,\n      description: str(parsed?.description) || str(attrs.description),\n      encryptedPayloadCid: str(attrs.encryptedPayloadCid),\n      eciesEncryptedKey: str(attrs.eciesEncryptedKey),\n      publicPayloadCid: str(attrs.publicPayloadCid),\n      capabilities: caps.length ? caps : arr(attrs.capabilities),\n      skills: skills.length ? skills : arr(attrs.skills),\n      category: str(parsed?.category) || str(attrs.category) || undefined,\n      isActive:\n        typeof parsed?.isActive === 'boolean'\n          ? parsed.isActive\n          : typeof parsed?.is_active === 'boolean'\n            ? parsed.is_active\n            : await this.agentExists(agentId),\n    }\n  }\n\n  /**\n   * Batch-read all agents in a contiguous ID range with optional filters.\n   * Replaces the manual binary-search + per-ID ownerOf loop used by chain-sync.\n   */\n  async getAllAgents(options: GetAllAgentsOptions = {}): Promise<AgentSummary[]> {\n    const { fromId = 1, batchSize = 10, activeOnly = false, capabilities } = options\n    const toId = options.toId ?? (await this.totalAgents())\n    if (toId < fromId || toId <= 0) return []\n\n    const agents: AgentSummary[] = []\n    for (let start = fromId; start <= toId; start += batchSize) {\n      const end = Math.min(start + batchSize - 1, toId)\n      const ids: number[] = []\n      for (let id = start; id <= end; id++) ids.push(id)\n\n      const results = await Promise.all(\n        ids.map(async (agentId) => {\n          try {\n            const [owner, tokenURI] = await Promise.all([\n              this.publicClient.readContract({\n                address: this.address,\n                abi: [IDENTITY_REGISTRY_ABI.getAgentOwner],\n                functionName: 'getAgentOwner',\n                args: [BigInt(agentId)],\n              }),\n              this.tokenURI(agentId),\n            ])\n            if (!owner || owner === ZERO_ADDRESS || !tokenURI) return null\n\n            const parsed = parseTokenURIJSON(tokenURI)\n            const metadata: AgentSummaryMetadata = {\n              name: (parsed?.name as string) || `Agent ${agentId}`,\n              description: (parsed?.description as string) || '',\n              capabilities: Array.isArray(parsed?.capabilities) ? parsed.capabilities.map(String) : [],\n              skills: Array.isArray(parsed?.skills) ? parsed.skills.map(String) : [],\n              category: typeof parsed?.category === 'string' && parsed.category ? parsed.category : undefined,\n              isActive:\n                typeof parsed?.isActive === 'boolean'\n                  ? parsed.isActive\n                  : typeof parsed?.is_active === 'boolean'\n                    ? parsed.is_active\n                    : true,\n            }\n\n            if (activeOnly && !metadata.isActive) return null\n            if (capabilities?.length && !capabilities.every((c) => metadata.capabilities.includes(c))) return null\n\n            return { agentId, owner: owner as string, tokenURI, metadata, createdAt: parseCreatedAt(parsed) }\n          } catch {\n            return null\n          }\n        })\n      )\n\n      for (const r of results) {\n        if (r) agents.push(r)\n      }\n    }\n    return agents\n  }\n\n  // ── Helpers ──────────────────────────────────────────────────────────────\n\n  /** Extract tokenId from the Transfer event in the receipt. */\n  private _parseAgentIdFromReceipt(receipt: { logs: { topics: string[]; data: string }[] }): number {\n    for (const log of receipt.logs) {\n      // ERC-721 Transfer event: keccak(\"Transfer(address,address,uint256)\")\n      const transferTopic = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n      if (log.topics[0] === transferTopic && log.topics.length >= 4) {\n        return Number(BigInt(log.topics[3]!))\n      }\n    }\n    throw new Error('Could not parse agentId from Transfer event in receipt')\n  }\n}\n\n// ── Utility ─────────────────────────────────────────────────────────────────\n\n/** Extract IPFS CID from an ipfs:// URI. */\nexport function cidFromURI(uri: string): string {\n  return uri.replace(/^ipfs:\\/\\//, '')\n}\n","// @agentx/sdk — Registry module\n// Agent registration, query, and IPFS fetching.\n\nexport { AgentRegistry, cidFromURI, parseTokenURIJSON } from './agent-registry'\nexport type {\n  AgentRegistryConfig,\n  AgentSummary,\n  AgentSummaryMetadata,\n  GetAllAgentsOptions,\n  StructuredAgentMetadata,\n} from './agent-registry'\n\nexport { IPFSFetcher, defaultIPFSFetcher } from './ipfs-fetcher'\nexport type { IPFSFetcherConfig } from './ipfs-fetcher'\n\n// Re-export types\nexport type {\n  RegisteredAgent,\n  AgentSearchQuery,\n  AgentSearchResult,\n  OnChainAgentMetadata,\n} from '../core/types'\n\nexport const REGISTRY_VERSION = '0.1.0'\n","// ---------------------------------------------------------------------------\n// agentx-protocol — AgentX402: Auto-Subscription Gate\n// ---------------------------------------------------------------------------\n// Standardized error handling for wallet/X402 integration.\n//\n// AgentX does NOT implement X402 or wallet logic.\n// Instead, it provides a clean subscription guard with structured\n// error metadata so external payment layers can react.\n//\n// Flow:\n//   App/Agent → AgentRunner.useAgent(id)\n//     → NOT_SUBSCRIBED error + { agentId }\n//     → X402 + AgentX402.requireSubscription() checks plans\n//     → Wallet/X402 layer: user/Agent approves + subscribes\n//     → App/Agent retries AgentRunner.useAgent(id)\n//     → ✅ success\n// ---------------------------------------------------------------------------\n\nimport type { PublicClient, WalletClient, Address } from 'viem'\nimport { AgentXError, AgentXErrorCode } from '../core/types'\nimport type { SubscriptionRequired } from '../core/types'\nimport { ZERO_ADDRESS } from './subscription'\n\n// ── ABI Fragments (v3 compatible) ──────────────────────────────────────────\n\nconst getPlanAbi = {\n  inputs: [{ name: 'planId', type: 'uint256' }] as const,\n  name: 'getPlan' as const,\n  outputs: [\n    { name: 'planId', type: 'uint256' },\n    { name: 'agentId', type: 'uint256' },\n    { name: 'creator', type: 'address' },\n    { name: 'price', type: 'uint256' },\n    { name: 'period', type: 'string' },\n    { name: 'active', type: 'bool' },\n    { name: 'payToken', type: 'address' },\n    { name: 'trialDays', type: 'uint256' },\n  ] as const,\n  stateMutability: 'view' as const,\n  type: 'function' as const,\n}\n\nconst subscribeAbi = {\n  inputs: [{ name: 'planId', type: 'uint256' }] as const,\n  name: 'subscribe' as const,\n  outputs: [{ name: 'subscriptionId', type: 'uint256' }] as const,\n  stateMutability: 'payable' as const,\n  type: 'function' as const,\n}\n\nconst hasActiveSubAbi = {\n  inputs: [\n    { name: 'subscriber', type: 'address' },\n    { name: 'agentId', type: 'uint256' },\n  ] as const,\n  name: 'hasActiveSubscription' as const,\n  outputs: [{ name: '', type: 'bool' }] as const,\n  stateMutability: 'view' as const,\n  type: 'function' as const,\n}\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface AgentX402Config {\n  subscriptionManagerAddress: Address\n  publicClient: PublicClient\n  walletClient: WalletClient\n}\n\n// ── AgentX402 ──────────────────────────────────────────────────────────────\n\nexport class AgentX402 {\n  constructor(private config: AgentX402Config) {}\n\n  /**\n   * Require active subscription — or throw with auto-pay info.\n   *\n   * Usage:\n   *   await x402.requireSubscription(agentId, address, { planIds: [1,2,3] })\n   *\n   * On success, returns silently.\n   * On failure, throws AgentXError with paymentInfo populated\n   * so the caller can auto-pay via wallet/X402.\n   */\n  async requireSubscription(\n    agentId: number,\n    address: Address,\n    opts?: { planIds?: number[] },\n  ): Promise<void> {\n    const { publicClient, subscriptionManagerAddress } = this.config\n\n    const isActive = (await publicClient.readContract({\n      address: subscriptionManagerAddress,\n      abi: [hasActiveSubAbi],\n      functionName: 'hasActiveSubscription',\n      args: [address, BigInt(agentId)],\n    })) as boolean\n\n    if (isActive) return // ✅ already subscribed\n\n    // ── Build payment info for X402 layer ──\n    const plans: NonNullable<SubscriptionRequired['plans']> = []\n\n    if (opts?.planIds && opts.planIds.length > 0) {\n      for (const planId of opts.planIds) {\n        try {\n          const plan = (await publicClient.readContract({\n            address: subscriptionManagerAddress,\n            abi: [getPlanAbi],\n            functionName: 'getPlan',\n            args: [BigInt(planId)],\n          })) as unknown as unknown[]\n\n          const planAgentId = Number(plan[1])\n          const planActive = plan[5] as boolean\n\n          if (planActive && planAgentId === agentId) {\n            plans.push({\n              planId: Number(plan[0]),\n              price: plan[3] as bigint,\n              period: plan[4] as string,\n              payToken: plan[6] as string,\n              trialDays: Number(plan[7]),\n            })\n          }\n        } catch {\n          // skip invalid plan IDs silently\n        }\n      }\n    }\n\n    const err = new AgentXError(\n      AgentXErrorCode.NOT_SUBSCRIBED,\n      `No active subscription for Agent #${agentId}. Use error.paymentInfo for auto-subscribe via X402/wallet.`,\n    )\n    ;(err as AgentXError & { paymentInfo: SubscriptionRequired }).paymentInfo = {\n      agentId,\n      plans: plans.length > 0 ? plans : undefined,\n    }\n    throw err\n  }\n\n  /**\n   * Subscribe to a plan + wait for receipt.\n   * Returns subscriptionId from the Subscribed event.\n   *\n   * NOTE: For ERC20 plans, the caller must approve token spending\n   * BEFORE calling this method. Use X402 SDK or wagmi's useWriteContract\n   * for the approve step.\n   */\n  async subscribeAndWait(\n    planId: number,\n    price: bigint,\n    payToken: Address,\n  ): Promise<number> {\n    const { publicClient, walletClient, subscriptionManagerAddress } = this.config\n    const isETH = payToken === ZERO_ADDRESS\n\n    const { request } = await publicClient.simulateContract({\n      address: subscriptionManagerAddress,\n      abi: [subscribeAbi],\n      functionName: 'subscribe',\n      args: [BigInt(planId)],\n      account: walletClient.account?.address as Address,\n      value: isETH ? price : 0n,\n    })\n\n    const hash = await walletClient.writeContract(request)\n    const receipt = await publicClient.waitForTransactionReceipt({ hash })\n\n    // Parse subscriptionId from Subscribed event (topic[1])\n    // event Subscribed(uint256 indexed subscriptionId, ...)\n    const subIdHex = receipt.logs[0]?.topics?.[1]\n    if (!subIdHex || subIdHex === '0x') {\n      throw new Error('Failed to parse subscriptionId from Subscribed event')\n    }\n    return Number(BigInt(subIdHex))\n  }\n}\n","// @agentx/sdk — Subscription module v2\nexport { SubscriptionManager, guardSubscription, ZERO_ADDRESS, SUBSCRIPTION_PERIODS } from './subscription'\nexport type {\n  SubscriptionConfig,\n  PlanDetail,\n  SubscriptionDetail,\n  SubscriptionPeriod,\n  CreatePlanParams,\n  CreatePlanResult,\n  SubscribeResult,\n} from './subscription'\nexport { AgentX402 } from './agent-x402'\nexport type { AgentX402Config } from './agent-x402'\nexport const SUBSCRIPTION_VERSION = '0.3.0'\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — SubscriptionPayments: unified three-rail subscription payment\n// ---------------------------------------------------------------------------\n// A single entry point for subscribing across all AgentX payment rails:\n//\n//   method: 'chain'  → on-chain SubscriptionManager (native / ERC20, escrow)\n//   method: 'fiat'   → unified payments endpoint (Stripe card, no wallet)\n//   method: 'x402'   → native-token period payment via the unified endpoint\n//\n// 0.9.0: the fiat / x402 / access rails now talk to the generic\n// `@0xinfrax/payments` engine through the Gateway's unified endpoint\n// (/api/v1/payments) via PaymentsClient. AgentX subscription semantics\n// (planId/agentId/subscription state) still live here — the generic module\n// never interprets them.\n// ---------------------------------------------------------------------------\n\nimport type { Address, Hash, WalletClient } from 'viem'\nimport { PaymentsClient } from '@0xinfrax/payments'\nimport type { ChainKey as PaymentsChainKey } from '@0xinfrax/payments'\nimport { SubscriptionManager } from '../subscription/subscription'\n\nexport type SubscriptionPaymentMethod = 'chain' | 'fiat' | 'x402'\nexport type SubscriptionPeriod = 'day' | 'week' | 'month' | 'year'\nexport type ChainKey = 'oxachain' | 'sepolia'\n\nexport interface SubscriptionPaymentsConfig {\n  /** AgentX Gateway base URL (required for fiat / x402 rails). */\n  gatewayUrl?: string\n  /** Optional gateway bearer token. */\n  accessToken?: string\n  /** Chain rail — required for `method: 'chain'` and for automatic x402 payment. */\n  subscriptionManager?: SubscriptionManager\n  /** Wallet used to automatically fund an x402 payment (if txHash is not supplied). */\n  walletClient?: WalletClient\n  /** Which chain to verify x402 payments on (default: oxachain). */\n  chain?: ChainKey\n}\n\nexport interface PaySubscriptionInput {\n  planId: number\n  agentId: number\n  method: SubscriptionPaymentMethod\n  /** Buyer wallet. Required for fiat / x402; chain resolves from the wallet client. */\n  subscriber?: Address\n  /** Chain rail: native value override (defaults to the plan price). */\n  valueWei?: bigint\n  /** Chain rail: approve the ERC20 token before subscribing. */\n  approveTokenFirst?: boolean\n  /** Fiat rail: amount in minor units (cents). Optional — the Gateway\n   *  auto-prices from the on-chain plan when planId is sent without it. */\n  amountCents?: number\n  /** Fiat rail: currency code (default 'usd'). */\n  currency?: string\n  /** Fiat rail: redirect targets after Stripe checkout. */\n  successUrl?: string\n  cancelUrl?: string\n  /** x402 rail: already-sent on-chain payment tx. When omitted and a wallet\n   *  client is configured, the payment is sent automatically. */\n  txHash?: string\n  /** x402 rail: plan price in wei. When set, the automatic x402 payment uses\n   *  this amount instead of reading the plan from the chain contract — needed\n   *  for centralized agents whose plans live off-chain (central_plans). */\n  priceWei?: bigint\n  /** Billing period (default 'month'). */\n  period?: SubscriptionPeriod\n}\n\nexport type PaySubscriptionResult =\n  | { method: 'chain'; subscriptionId: number; txHash: Hash }\n  | { method: 'fiat'; sessionUrl: string; sessionId: string; redirect: true }\n  | { method: 'x402'; subscriptionId: number; txHash: string; creditedWei?: string }\n\n/** x402 protocol discovery returned by the unified endpoint. */\nexport interface X402Info {\n  enabled: boolean\n  priceWei: string\n  payTo: string\n  network: string\n  chain: ChainKey\n}\n\nconst PERIODS: readonly SubscriptionPeriod[] = ['day', 'week', 'month', 'year']\n\nexport class SubscriptionPayments {\n  private client: PaymentsClient | null\n\n  constructor(private config: SubscriptionPaymentsConfig) {\n    this.client = config.gatewayUrl\n      ? new PaymentsClient({ baseUrl: config.gatewayUrl, accessToken: config.accessToken })\n      : null\n  }\n\n  // ── Public API ──────────────────────────────────────────────────────────\n\n  /** Pay for (or renew) a subscription using the chosen rail. */\n  async pay(input: PaySubscriptionInput): Promise<PaySubscriptionResult> {\n    switch (input.method) {\n      case 'chain':\n        return this._payChain(input)\n      case 'fiat':\n        return this._payFiat(input)\n      case 'x402':\n        return this._payX402(input)\n    }\n  }\n\n  /**\n   * Unified access check across all rails (chain OR fiat/x402) via the\n   * unified /api/v1/payments/access endpoint.\n   */\n  async hasAccess(agentId: number, subscriber: Address): Promise<boolean> {\n    if (!this.client) {\n      throw new Error('hasAccess() requires a gatewayUrl')\n    }\n    const res = await this.client.access(subscriber, agentId, this.config.chain ?? 'oxachain')\n    return res.active === true\n  }\n\n  /** x402 protocol discovery (price / pay-to wallet / network). */\n  async fetchX402Info(): Promise<X402Info> {\n    if (!this.client) {\n      throw new Error('fetchX402Info() requires a gatewayUrl')\n    }\n    const info = await this.client.info()\n    return {\n      enabled: Boolean(info.x402?.enabled),\n      priceWei: info.x402?.priceWei ?? '0',\n      payTo: info.x402?.payTo ?? '',\n      network: info.x402?.network ?? '',\n      chain: (info.x402?.chain ?? this.config.chain ?? 'oxachain') as ChainKey,\n    }\n  }\n\n  // ── Rails ───────────────────────────────────────────────────────────────\n\n  private async _payChain(input: PaySubscriptionInput): Promise<PaySubscriptionResult> {\n    const sm = this.config.subscriptionManager\n    if (!sm) throw new Error('method \"chain\" requires a SubscriptionManager in the config')\n    const result = await sm.subscribe(input.planId, {\n      valueWei: input.valueWei,\n      approveTokenFirst: input.approveTokenFirst,\n    })\n    return { method: 'chain', subscriptionId: result.subscriptionId, txHash: result.txHash }\n  }\n\n  private async _payFiat(input: PaySubscriptionInput): Promise<PaySubscriptionResult> {\n    if (!this.client) throw new Error('method \"fiat\" requires a gatewayUrl')\n    if (!input.subscriber) throw new Error('method \"fiat\" requires a subscriber address')\n    const data = await this.client.create({\n      method: 'fiat',\n      subscriber: input.subscriber,\n      period: input.period ?? 'month',\n      currency: input.currency ?? 'usd',\n      chain: (this.config.chain ?? 'oxachain') as PaymentsChainKey,\n      // amountCents is optional — the Gateway derives the USD amount from the\n      // on-chain plan price when omitted (FIAT_TOKEN_USD_PRICE on the Gateway).\n      amountCents: input.amountCents,\n      pricing: { planId: input.planId },\n      // AgentX business context rides in metadata (the unified endpoint reads\n      // it back out — the generic module never interprets it).\n      metadata: { agentId: input.agentId, planId: input.planId },\n      successUrl: input.successUrl,\n      cancelUrl: input.cancelUrl,\n    })\n    if (data.method !== 'fiat' || !data.sessionUrl) {\n      throw new Error('Fiat checkout returned no redirect URL')\n    }\n    return { method: 'fiat', sessionUrl: data.sessionUrl, sessionId: data.sessionId, redirect: true }\n  }\n\n  private async _payX402(input: PaySubscriptionInput): Promise<PaySubscriptionResult> {\n    if (!this.client) throw new Error('method \"x402\" requires a gatewayUrl')\n    if (!input.subscriber) throw new Error('method \"x402\" requires a subscriber address')\n    if (!PERIODS.includes(input.period ?? 'month')) {\n      throw new Error('period must be one of: day | week | month | year')\n    }\n\n    // Automatically fund the payment when no txHash is supplied.\n    let txHash = input.txHash\n    if (!txHash) {\n      txHash = await this._autoFundX402(input)\n    }\n\n    // The x402 subscription is AgentX business (planId/agentId/txHash), so it\n    // hits the unified endpoint with the full body — the generic client only\n    // models rails, not subscription semantics.\n    const data = await this._fetchJson<{ subscriptionId: number; creditedWei?: string }>('/api/v1/payments', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({\n        method: 'x402',\n        subscriber: input.subscriber,\n        agentId: input.agentId,\n        planId: input.planId,\n        period: input.period ?? 'month',\n        txHash,\n        chain: this.config.chain ?? 'oxachain',\n      }),\n    })\n    return {\n      method: 'x402',\n      subscriptionId: data.subscriptionId,\n      txHash,\n      creditedWei: data.creditedWei,\n    }\n  }\n\n  /** Send the on-chain native transfer to the platform wallet (x402 rail). */\n  private async _autoFundX402(input: PaySubscriptionInput): Promise<string> {\n    const { walletClient, subscriptionManager } = this.config\n    if (!walletClient || !subscriptionManager) {\n      throw new Error('x402 automatic payment needs a txHash, or a walletClient + subscriptionManager in the config')\n    }\n    const info = await this.fetchX402Info()\n    if (!info.enabled || !info.payTo) {\n      throw new Error('x402 is not enabled on the Gateway (X402_ENABLED / X402_PAY_TO missing)')\n    }\n    const priceWei = BigInt(info.priceWei || '0')\n    // Centralized agents have no on-chain plan — the caller supplies the plan\n    // price directly (central_plans); otherwise read it from the chain.\n    const amount = input.priceWei !== undefined\n      ? (input.priceWei > priceWei ? input.priceWei : priceWei)\n      : (async () => {\n          const plan = await subscriptionManager!.getPlan(input.planId)\n          return plan.price > priceWei ? plan.price : priceWei\n        })()\n    const resolvedAmount = typeof amount === 'bigint' ? amount : await amount\n    let account = (walletClient.account as { address?: Address } | undefined)?.address\n    if (!account) {\n      const [addr] = await walletClient.getAddresses()\n      account = addr\n    }\n    if (!account) throw new Error('Wallet not connected for x402 payment')\n    const hash = await walletClient.sendTransaction({\n      to: info.payTo as Address,\n      value: resolvedAmount,\n      chain: undefined,\n      account,\n    })\n    return hash\n  }\n\n  // ── HTTP helpers ────────────────────────────────────────────────────────\n\n  private async _fetchJson<T>(path: string, init?: RequestInit): Promise<T> {\n    const base = (this.config.gatewayUrl ?? '').replace(/\\/$/, '')\n    const headers: Record<string, string> = { ...(init?.headers as Record<string, string> | undefined) }\n    if (this.config.accessToken) headers.Authorization = `Bearer ${this.config.accessToken}`\n    const resp = await fetch(`${base}${path}`, { ...init, headers })\n    if (!resp.ok) {\n      let message = `Gateway request failed (${resp.status}): ${path}`\n      try {\n        const body = (await resp.json()) as { error?: string }\n        if (body.error) message = body.error\n      } catch { /* non-JSON error body */ }\n      throw new Error(message)\n    }\n    return (await resp.json()) as T\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — TenantPlanPayments: platform subscription-tier purchases (R19.3)\n// ---------------------------------------------------------------------------\n// R19.3 (D11): buying a *platform* subscription tier (the `plans` table on the\n// Gateway — quota_daily / rate limits) reuses the same @0xinfrax/payments\n// engine via the unified `/api/v1/payments` endpoint. Unlike\n// SubscriptionPayments (agent subscriptions, planId+agentId), a tenant plan\n// purchase binds onto the tenant: `purpose='tenant-plan'` + `tenantPlanId`.\n//\n//   method: 'chain' | 'x402' → verify the on-chain payment then bind the plan\n//   method: 'fiat'           → Stripe checkout (client_reference carries the\n//                              purpose); the webhook binds on completion\n// ---------------------------------------------------------------------------\n\nimport type { Address, Hash } from 'viem'\nimport type { ChainKey } from './payments'\n\nexport type TenantPlanPaymentMethod = 'chain' | 'fiat' | 'x402'\n\nexport interface TenantPlanPaymentsConfig {\n  /** AgentX Gateway base URL. */\n  gatewayUrl: string\n  /** Optional gateway bearer token (B-end wallet JWT). */\n  accessToken?: string\n  /** Which chain to verify on-chain payments on (default: oxachain). */\n  chain?: ChainKey\n}\n\nexport interface BuyTenantPlanInput {\n  /** Platform plan id (plans table UUID). */\n  tenantPlanId: string\n  /** Buying wallet address. */\n  subscriber: Address\n  method: TenantPlanPaymentMethod\n  /** chain | x402: already-sent on-chain payment tx. */\n  txHash?: Hash | string\n  /** fiat: redirect targets after Stripe checkout. */\n  successUrl?: string\n  cancelUrl?: string\n}\n\nexport type BuyTenantPlanResult =\n  | { method: 'chain' | 'x402'; tenantId: string; planId: string; planSlug: string; quotaDaily: string; txHash: string }\n  | { method: 'fiat'; sessionUrl: string; sessionId: string; redirect: true }\n\nexport class TenantPlanPayments {\n  constructor(private config: TenantPlanPaymentsConfig) {}\n\n  /** Buy a platform subscription tier on the chosen rail. */\n  async buy(input: BuyTenantPlanInput): Promise<BuyTenantPlanResult> {\n    if (!input.txHash && input.method !== 'fiat') {\n      throw new Error('txHash is required for the chain / x402 rails')\n    }\n    const body: Record<string, unknown> = {\n      method: input.method,\n      purpose: 'tenant-plan',\n      tenantPlanId: input.tenantPlanId,\n      subscriber: input.subscriber,\n      chain: this.config.chain ?? 'oxachain',\n      txHash: input.txHash,\n      successUrl: input.successUrl,\n      cancelUrl: input.cancelUrl,\n    }\n    const data = await this._fetchJson<Record<string, any>>('/api/v1/payments', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(body),\n    })\n    if (input.method === 'fiat') {\n      if (!data.sessionUrl) throw new Error('Fiat checkout returned no redirect URL')\n      return { method: 'fiat', sessionUrl: data.sessionUrl, sessionId: data.sessionId, redirect: true }\n    }\n    return {\n      method: input.method,\n      tenantId: String(data.tenantId ?? ''),\n      planId: String(data.planId ?? ''),\n      planSlug: String(data.planSlug ?? ''),\n      quotaDaily: String(data.quotaDaily ?? '0'),\n      txHash: String(input.txHash ?? ''),\n    }\n  }\n\n  // ── HTTP helpers ────────────────────────────────────────────────────────\n\n  private async _fetchJson<T>(path: string, init?: RequestInit): Promise<T> {\n    const base = (this.config.gatewayUrl ?? '').replace(/\\/$/, '')\n    const headers: Record<string, string> = { ...(init?.headers as Record<string, string> | undefined) }\n    if (this.config.accessToken) headers.Authorization = `Bearer ${this.config.accessToken}`\n    const resp = await fetch(`${base}${path}`, { ...init, headers })\n    if (!resp.ok) {\n      let message = `Gateway request failed (${resp.status}): ${path}`\n      try {\n        const body = (await resp.json()) as { error?: string }\n        if (body.error) message = body.error\n      } catch { /* non-JSON error body */ }\n      throw new Error(message)\n    }\n    return (await resp.json()) as T\n  }\n}\n","// @agentx/sdk — Payment module (three-rail subscription payments + generic clients)\nexport { SubscriptionPayments } from './payments'\nexport type {\n  SubscriptionPaymentMethod,\n  SubscriptionPaymentsConfig,\n  PaySubscriptionInput,\n  PaySubscriptionResult,\n  X402Info,\n} from './payments'\n\n// R19.3 (D11): platform subscription-tier purchases (tenant plans) share the\n// same unified payments endpoint; the business binding is `purpose='tenant-plan'`.\nexport { TenantPlanPayments } from './tenant-plan'\nexport type {\n  TenantPlanPaymentMethod,\n  TenantPlanPaymentsConfig,\n  BuyTenantPlanInput,\n  BuyTenantPlanResult,\n} from './tenant-plan'\n\n// v0.9.3: the generic engine (@0xinfrax/payments) adds MPP payment channels,\n// stablecoin (EIP-3009 / Permit2), period authorization and a2a-pay. AgentX\n// re-exports the protocol-level clients so integrators can drive those rails\n// directly; the business semantics stay in `@0xinfrax/payments` metadata.\n//\n// R17.5: @0xinfrax/payments@0.1.2 removed the a2a and period rails from the\n// generic engine, so AgentX self-hosted both (services/payments-a2a-period.ts).\n// R17.6: @0xinfrax/payments@0.1.3 restored both rails inside the engine. The\n// gateway now delegates to the module rails while keeping the HTTP contract\n// identical, so A2AClient / PeriodClient keep their public signatures and\n// B-side callers see zero change.\nexport { MPPClient, X402Client, PaymentsClient } from '@0xinfrax/payments'\nexport { A2AClient } from './a2a-client'\nexport { PeriodClient } from './period-client'\nexport type { ClientOptions } from '@0xinfrax/payments'\n\n// R19.7 companion (2026-08-16): B-end balance pre-check before pay-per-call\n// delegation — GET /api/v1/billing/balance (tenant / end-user wallet).\nexport { BillingClient } from './billing'\nexport type { BillingClientConfig, BalanceResult } from './billing'\n\n// t9 (2026-08-17): agent 自主钱包（InfraX MPC）管理客户端 — 绑定/解锁/查询。\n// A2A 委派自动代付由 gateway agent-payer 服务端完成。\nexport { AgentWalletConfig } from './agent-wallet'\nexport type {\n  AgentWalletConfigOptions,\n  AgentWalletInfo,\n  BindAgentWalletInput,\n  AuthorizePaymentSessionInput,\n  AuthorizePaymentSessionResult,\n  AgentWalletStatus,\n} from './agent-wallet'\n\nexport const PAYMENT_VERSION = '0.1.3'\n","// ---------------------------------------------------------------------------\n// @agentxv2/sdk — A2AClient (a2a rail, module-backed since R17.6)\n// ---------------------------------------------------------------------------\n// @0xinfrax/payments@0.1.2 removed the a2a rail; AgentX self-hosted it (R17.5)\n// while keeping the client contract byte-for-byte identical. Since 0.1.3 the\n// rail lives in the generic engine again and the gateway delegates to it, but\n// the public client contract is unchanged — B-side callers see zero change.\n// ---------------------------------------------------------------------------\n\nimport type { ChainKey, ClientOptions } from '@0xinfrax/payments'\n\n/** Minimal JSON request helper against an AgentX gateway (shared with period-client). */\nexport async function request(baseUrl: string, path: string, init?: RequestInit, accessToken?: string): Promise<any> {\n  const base = baseUrl.replace(/\\/$/, '')\n  const headers: Record<string, string> = {\n    ...((init?.headers as Record<string, string>) ?? {}),\n  }\n  if (accessToken) headers.Authorization = `Bearer ${accessToken}`\n  const resp = await fetch(`${base}${path}`, { ...init, headers })\n  if (!resp.ok) {\n    let message = `Payments request failed (${resp.status}): ${path}`\n    try {\n      const body = (await resp.json()) as { error?: string }\n      if (body.error) message = body.error\n    } catch { /* non-JSON */ }\n    throw new Error(message)\n  }\n  return resp.json()\n}\n\n/** a2a-pay client: paymentId two-phase (create → pay → settle). */\nexport class A2AClient {\n  constructor(private opts: ClientOptions) {}\n\n  /** Phase 1: create a payment intent. */\n  async create(input: { payer: string; amountWei: string; payee?: string; chain?: ChainKey; metadata?: Record<string, unknown> }): Promise<{ paymentId: string; amountWei: string; payee: string }> {\n    return request(\n      this.opts.baseUrl,\n      '/api/v1/payments/a2a',\n      { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) },\n      this.opts.accessToken\n    )\n  }\n\n  /** Phase 2: verify the payer's on-chain payment tx and credit it. */\n  async settle(input: { paymentId: string; txHash: string; chain?: ChainKey }): Promise<{ verified: boolean; paymentId: string; payer: string; creditedWei: string; balanceWei: string }> {\n    return request(\n      this.opts.baseUrl,\n      '/api/v1/payments/a2a/settle',\n      { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) },\n      this.opts.accessToken\n    )\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentxv2/sdk — PeriodClient (period rail, module-backed since R17.6)\n// ---------------------------------------------------------------------------\n// @0xinfrax/payments@0.1.2 removed the period-authorization rail; AgentX\n// self-hosted it (R17.5) while keeping the client contract identical. Since\n// 0.1.3 the rail lives in the generic engine again and the gateway delegates\n// to it (module PgAuthorizationStore seam), but the public client contract is\n// unchanged — B-side callers see zero change.\n// ---------------------------------------------------------------------------\n\nimport type { ClientOptions } from '@0xinfrax/payments'\nimport { request } from './a2a-client'\n\n/** Period-authorization client (P4): charge a period / read state. */\nexport class PeriodClient {\n  constructor(private opts: ClientOptions) {}\n\n  async charge(authorizationId: string): Promise<{ renewed: boolean; remainingWei: string }> {\n    return request(\n      this.opts.baseUrl,\n      '/api/v1/payments/period/charge',\n      { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ authorizationId }) },\n      this.opts.accessToken\n    )\n  }\n\n  async authorization(authorizationId: string): Promise<{ id: string; owner: string; remainingWei: string; periods: number; status: string }> {\n    return request(this.opts.baseUrl, `/api/v1/payments/period/authorization?authorizationId=${encodeURIComponent(authorizationId)}`, undefined, this.opts.accessToken)\n  }\n}\n","// ---------------------------------------------------------------------------\n// AgentX SDK — BillingClient (B-end balance query)\n// ---------------------------------------------------------------------------\n// Lets B-end (partner) integrators check the x402 ledger balance before\n// delegating to an unsubscribed agent (R19.7 pay-per-call), instead of\n// hitting HTTP 403 / 402 first.\n//   GET /api/v1/billing/balance\n//\n// Auth (either one is required, same as ConversationClient):\n//   - Tenant API Key:  X-Api-Key: agentx_xxx\n//   - Gateway JWT:     Authorization: Bearer <accessToken>\n// Dimension: tenant wallet by default; pass `endUserId` (0x wallet) to query\n// that end user's balance (same subject resolution as R19.7 access checks).\n// ---------------------------------------------------------------------------\n\nexport interface BillingClientConfig {\n  /** Gateway base URL, e.g. https://agentx.0xainet.top */\n  gatewayUrl: string\n  /** Tenant API Key (agentx_...) issued after registration (alternative to accessToken) */\n  apiKey?: string\n  /** Gateway JWT access token from wallet-signed login (alternative to apiKey) */\n  accessToken?: string\n  /** End-user wallet for balance queries within the tenant (optional) */\n  endUserId?: string\n}\n\nexport interface BalanceResult {\n  /** Balance in OXA as a high-precision decimal string, e.g. \"1.500000000000000000\". \"0\" when never funded. */\n  balance: string\n  /** Raw balance in wei (string) — use for exact programmatic comparison against priceWei. */\n  balanceWei: string\n  currency: 'OXA'\n  /** ISO timestamp of the last ledger update, or null when never funded. */\n  updatedAt: string | null\n  /** The wallet the balance was queried for (tenant or proxied end user). */\n  subject: string\n  /** Platform pay-to wallet for top-ups (present when x402 is enabled). */\n  payTo?: string\n  /** Per-request pay-per-call price in wei (present when x402 is enabled). */\n  priceWei?: string\n}\n\n/**\n * Balance query client for B-end integrations.\n * @example\n * const billing = new BillingClient({ gatewayUrl, apiKey: 'agentx_xxx' })\n * const { balanceWei, priceWei } = await billing.getBalance()\n * if (balanceWei && priceWei && BigInt(balanceWei) < BigInt(priceWei)) {\n *   // show top-up prompt: send native token to billing.payTo\n * }\n */\nexport class BillingClient {\n  private readonly baseUrl: string\n\n  constructor(private readonly config: BillingClientConfig) {\n    this.baseUrl = config.gatewayUrl.replace(/\\/$/, '')\n  }\n\n  private _headers(endUserId?: string): Record<string, string> {\n    const headers: Record<string, string> = {\n      'Content-Type': 'application/json',\n    }\n    if (this.config.apiKey) headers['X-Api-Key'] = this.config.apiKey\n    if (this.config.accessToken) headers['Authorization'] = `Bearer ${this.config.accessToken}`\n    if (!this.config.apiKey && !this.config.accessToken) {\n      throw new Error('BillingClient requires either apiKey or accessToken')\n    }\n    const uid = endUserId ?? this.config.endUserId\n    if (uid) headers['X-End-User-Id'] = uid\n    return headers\n  }\n\n  /**\n   * Query the x402 ledger balance for the tenant (default) or a proxied\n   * end-user wallet. Never throws on a zero balance — balance \"0\" is a normal\n   * response. Throws only on auth/transport errors.\n   * @param opts.endUserId 0x wallet to query instead of the tenant's own balance\n   */\n  async getBalance(opts: { endUserId?: string } = {}): Promise<BalanceResult> {\n    const res = await fetch(`${this.baseUrl}/api/v1/billing/balance`, {\n      method: 'GET',\n      headers: this._headers(opts.endUserId),\n    })\n    if (!res.ok) {\n      let detail = ''\n      try {\n        const body = await res.json()\n        detail = body?.error ?? ''\n      } catch {}\n      throw new Error(`Balance query failed (HTTP ${res.status}) ${detail}`.trim())\n    }\n    return res.json() as Promise<BalanceResult>\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentxv2/sdk — AgentWalletConfig (t9, P2)\n// ---------------------------------------------------------------------------\n// agent 自主钱包（InfraX MPC 钱包，Email 2-of-2 TSS）管理客户端。A2A 委派\n// 按次付费时，配置了自主钱包的 agent 由 gateway worker 自动代付（agent-payer\n// 服务），无需用户钱包弹窗/预充值。本模块封装 gateway 的 agent-payer 管理接口：\n//\n//   POST   /api/v1/admin/agent-payers                — 绑定 MPC 钱包\n//   POST   /api/v1/admin/agent-payers/:agentId/unlock— 邮箱验证码解锁会话\n//   GET    /api/v1/admin/agent-payers/:agentId       — 状态 + 链上余额\n//   GET    /api/v1/admin/agent-payers                — 列表\n//   DELETE /api/v1/admin/agent-payers/:agentId       — 解绑\n//\n// 鉴权双轨（agentPayerAuth）：\n//   - 平台侧：gateway ADMIN_KEY（Authorization: Bearer / X-Admin-Key），scope=admin 全量；\n//   - 租户侧：tenant API Key（X-Api-Key），scope=tenant，仅能操作自己名下的 agent。\n// 二者至少提供一个，同时提供时优先 ADMIN_KEY。\n// ---------------------------------------------------------------------------\n\n/** AgentWalletConfig 客户端配置。 */\nexport interface AgentWalletConfigOptions {\n  /** Gateway 地址（如 https://agentx.0xainet.top）。 */\n  baseUrl: string\n  /** Gateway ADMIN_KEY（admin 路由鉴权，平台全量）。与 apiKey 二选一。 */\n  adminKey?: string\n  /** 租户 API Key（agentx_...，租户作用域，仅限自有 agent）。与 adminKey 二选一。 */\n  apiKey?: string\n}\n\nexport interface AgentWalletInfo {\n  agentId: number\n  email: string\n  walletAddress: string\n  chain: string\n  sessionUnlocked: boolean\n  sessionExpiresAt: string | null\n}\n\nexport interface BindAgentWalletInput {\n  agentId: number\n  /** MPC 钱包注册邮箱（sendCode/register 所用）。 */\n  email: string\n  /** MPC 钱包地址。 */\n  walletAddress: string\n  /** 链名，默认 'oxachain'。 */\n  chain?: string\n}\n\nexport interface AuthorizePaymentSessionInput {\n  agentId: number\n  email: string\n  /** 邮箱收到的 6 位验证码（MPC session.unlock）。 */\n  code: string\n}\n\nexport interface AuthorizePaymentSessionResult {\n  address: string\n  expiresAt: string\n}\n\nexport interface AgentWalletStatus extends AgentWalletInfo {\n  chainBalanceWei: string | null\n}\n\nasync function adminRequest(opts: AgentWalletConfigOptions, path: string, init?: RequestInit): Promise<any> {\n  const base = opts.baseUrl.replace(/\\/$/, '')\n  const headers: Record<string, string> = {\n    ...(opts.adminKey ? { 'X-Admin-Key': opts.adminKey } : {}),\n    ...(opts.apiKey ? { 'X-Api-Key': opts.apiKey } : {}),\n    ...((init?.headers as Record<string, string>) ?? {}),\n  }\n  const resp = await fetch(`${base}${path}`, { ...init, headers })\n  if (!resp.ok) {\n    let message = `AgentWalletConfig request failed (${resp.status}): ${path}`\n    try {\n      const body = (await resp.json()) as { error?: string }\n      if (body.error) message = body.error\n    } catch { /* non-JSON */ }\n    throw new Error(message)\n  }\n  return resp.json()\n}\n\n/**\n * agent 自主钱包管理客户端：绑定 MPC 钱包 / 授权付款会话 / 查询状态。\n * 绑定 + 解锁完成后，A2A 委派由 gateway 服务端自动代付，SDK 侧无需再参与付款。\n */\nexport class AgentWalletConfig {\n  constructor(private opts: AgentWalletConfigOptions) {\n    if (!opts.adminKey && !opts.apiKey) {\n      throw new Error('AgentWalletConfig: adminKey or apiKey is required')\n    }\n  }\n\n  /** 绑定 agent 与 MPC 钱包（agent_id 唯一，重复绑定覆盖 email/地址/链）。 */\n  async bindWallet(input: BindAgentWalletInput): Promise<{ success: boolean }> {\n    return adminRequest(this.opts, '/api/v1/admin/agent-payers', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(input),\n    })\n  }\n\n  /** 邮箱验证码解锁 MPC 会话（令牌由 gateway 加密存储，服务端自动代付使用）。 */\n  async authorizePaymentSession(input: AuthorizePaymentSessionInput): Promise<AuthorizePaymentSessionResult> {\n    return adminRequest(\n      this.opts,\n      `/api/v1/admin/agent-payers/${input.agentId}/unlock`,\n      { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: input.code }) }\n    )\n  }\n\n  /** 查询单个 agent 自主钱包状态（含链上原生币余额）。 */\n  async status(agentId: number): Promise<AgentWalletStatus> {\n    return adminRequest(this.opts, `/api/v1/admin/agent-payers/${agentId}`)\n  }\n\n  /** 列出已绑定 agent 钱包（apiKey 模式下仅返回自有 agent）。 */\n  async list(): Promise<{ wallets: AgentWalletInfo[] }> {\n    return adminRequest(this.opts, '/api/v1/admin/agent-payers')\n  }\n\n  /** 解绑（清除钱包绑定与会话）。 */\n  async unbind(agentId: number): Promise<{ success: boolean }> {\n    return adminRequest(this.opts, `/api/v1/admin/agent-payers/${agentId}`, { method: 'DELETE' })\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — A2A Protocol\n// ---------------------------------------------------------------------------\n// Wraps A2AProtocolRegistry: Agent Cards, Skills, and Tasks.\n// viem PublicClient / WalletClient based.\n// ---------------------------------------------------------------------------\n\nimport { stringToHex, hexToString } from 'viem'\nimport type { PublicClient, WalletClient, Address, Hash } from 'viem'\nimport type { A2AAgentCard, A2ATask, A2ATaskStatus } from '../core/types'\n\n// ── ABI Fragments ──────────────────────────────────────────────────────────\n\nconst A2A_ABI = {\n  createAgentCard: {\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'name', type: 'string' },\n      { name: 'description', type: 'string' },\n      { name: 'version', type: 'string' },\n      { name: 'capabilities', type: 'string[]' },\n      { name: 'supportedTasks', type: 'string[]' },\n      { name: 'communicationProtocol', type: 'string' },\n      { name: 'authenticationMethod', type: 'string' },\n      { name: 'cardURI', type: 'string' },\n    ] as const,\n    name: 'createAgentCard' as const,\n    outputs: [{ name: 'cardId', type: 'uint256' }] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  getAgentCard: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getAgentCard' as const,\n    outputs: [\n      { name: 'cardId', type: 'uint256' },\n      { name: 'agentId', type: 'uint256' },\n      { name: 'name', type: 'string' },\n      { name: 'description', type: 'string' },\n      { name: 'version', type: 'string' },\n      { name: 'capabilities', type: 'string[]' },\n      { name: 'supportedTasks', type: 'string[]' },\n      { name: 'communicationProtocol', type: 'string' },\n      { name: 'authenticationMethod', type: 'string' },\n      { name: 'cardURI', type: 'string' },\n      { name: 'isActive', type: 'bool' },\n    ] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  registerSkill: {\n    inputs: [\n      { name: 'name', type: 'string' },\n      { name: 'description', type: 'string' },\n      { name: 'inputSchema', type: 'string' },\n      { name: 'outputSchema', type: 'string' },\n      { name: 'requiredCapabilities', type: 'string[]' },\n      { name: 'complexity', type: 'uint256' },\n    ] as const,\n    name: 'registerSkill' as const,\n    outputs: [{ name: 'skillId', type: 'uint256' }] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  addAgentSkill: {\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'skillId', type: 'uint256' },\n      { name: 'skillEndpoint', type: 'string' },\n      { name: 'version', type: 'string' },\n      { name: 'price', type: 'uint256' },\n      { name: 'priceToken', type: 'address' },\n    ] as const,\n    name: 'addAgentSkill' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  createTask: {\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'taskType', type: 'string' },\n      { name: 'inputData', type: 'string' },\n    ] as const,\n    name: 'createTask' as const,\n    outputs: [{ name: 'taskId', type: 'uint256' }] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  completeTask: {\n    inputs: [\n      { name: 'taskId', type: 'uint256' },\n      { name: 'outputData', type: 'string' },\n      { name: 'status', type: 'uint256' },\n    ] as const,\n    name: 'completeTask' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  getTask: {\n    inputs: [{ name: 'taskId', type: 'uint256' }] as const,\n    name: 'getTask' as const,\n    outputs: [\n      { name: 'taskId', type: 'uint256' },\n      { name: 'agentId', type: 'uint256' },\n      { name: 'taskType', type: 'string' },\n      { name: 'inputData', type: 'string' },\n      { name: 'outputData', type: 'string' },\n      { name: 'status', type: 'uint256' },\n      { name: 'clientAddress', type: 'address' },\n      { name: 'createdAt', type: 'uint256' },\n      { name: 'completedAt', type: 'uint256' },\n    ] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getUserTasks: {\n    inputs: [{ name: 'user', type: 'address' }] as const,\n    name: 'getUserTasks' as const,\n    outputs: [{ name: '', type: 'uint256[]' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getAgentTasks: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getAgentTasks' as const,\n    outputs: [\n      {\n        name: '', type: 'tuple[]',\n        components: [\n          { name: 'taskId', type: 'uint256' },\n          { name: 'agentId', type: 'uint256' },\n          { name: 'taskType', type: 'string' },\n          { name: 'inputData', type: 'string' },\n          { name: 'outputData', type: 'string' },\n          { name: 'status', type: 'uint256' },\n          { name: 'clientAddress', type: 'address' },\n          { name: 'createdAt', type: 'uint256' },\n          { name: 'completedAt', type: 'uint256' },\n          { name: 'taskHash', type: 'bytes32' },\n        ],\n      },\n    ] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n} as const\n\n// ── Config ─────────────────────────────────────────────────────────────────\n\nexport interface A2AConfig {\n  contractAddress: Address\n  publicClient: PublicClient\n  walletClient: WalletClient\n}\n\n// ── A2A Protocol ───────────────────────────────────────────────────────────\n\nexport class A2AProtocol {\n  private address: Address\n  private publicClient: PublicClient\n  private walletClient: WalletClient\n\n  constructor(config: A2AConfig) {\n    this.address = config.contractAddress\n    this.publicClient = config.publicClient\n    this.walletClient = config.walletClient\n  }\n\n  private get account(): Promise<Address> {\n    return this.walletClient.getAddresses().then(a => {\n      if (!a[0]) throw new Error('Wallet not connected')\n      return a[0]\n    })\n  }\n\n  // ── Agent Card ──────────────────────────────────────────────────────────\n\n  async createAgentCard(\n    agentId: number,\n    card: { name: string; description: string; version: string; capabilities: string[]; supportedTasks: string[]; commProtocol?: string; authMethod?: string; cardURI?: string }\n  ): Promise<{ cardId: number; txHash: Hash }> {\n    const acct = await this.account\n    const { request } = await this.publicClient.simulateContract({\n      account: acct,\n      address: this.address,\n      abi: [A2A_ABI.createAgentCard],\n      functionName: 'createAgentCard',\n      args: [\n        BigInt(agentId), card.name, card.description, card.version,\n        card.capabilities, card.supportedTasks,\n        card.commProtocol ?? 'a2a', card.authMethod ?? 'ecdsa',\n        card.cardURI ?? '',\n      ],\n    })\n    const hash = await this.walletClient.writeContract(request)\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n    const cardId = this._parseUintFromLog(receipt, 'AgentCardCreated')\n    return { cardId, txHash: hash }\n  }\n\n  async getAgentCard(agentId: number): Promise<A2AAgentCard | null> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [A2A_ABI.getAgentCard],\n      functionName: 'getAgentCard',\n      args: [BigInt(agentId)],\n    })\n    const [, aId, name, , , capabilities, supportedTasks, , , , isActive] = r as any\n    if (!isActive) return null\n    return {\n      agentId: Number(aId),\n      name: name as string,\n      capabilities: capabilities as string[],\n      supportedTasks: supportedTasks as string[],\n      endpoint: '',\n      publicKey: '',\n    }\n  }\n\n  // ── Task ────────────────────────────────────────────────────────────────\n\n  async createTask(agentId: number, taskType: string, input: string | Record<string, unknown>): Promise<{ taskId: number; txHash: Hash }> {\n    const acct = await this.account\n    const inputStr = typeof input === 'string' ? input : JSON.stringify(input)\n    const { request } = await this.publicClient.simulateContract({\n      account: acct,\n      address: this.address,\n      abi: [A2A_ABI.createTask],\n      functionName: 'createTask',\n      args: [BigInt(agentId), taskType, inputStr],\n    })\n    const hash = await this.walletClient.writeContract(request)\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash })\n    const taskId = this._parseUintFromLog(receipt, 'TaskCreated')\n    return { taskId, txHash: hash }\n  }\n\n  async completeTask(taskId: number, output: unknown, status: number = 3): Promise<Hash> {\n    const acct = await this.account\n    const outputStr = typeof output === 'string' ? output : JSON.stringify(output)\n    const { request } = await this.publicClient.simulateContract({\n      account: acct,\n      address: this.address,\n      abi: [A2A_ABI.completeTask],\n      functionName: 'completeTask',\n      args: [BigInt(taskId), outputStr, BigInt(status)],\n    })\n    return this.walletClient.writeContract(request)\n  }\n\n  async getTask(taskId: number): Promise<A2ATask | null> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [A2A_ABI.getTask],\n      functionName: 'getTask',\n      args: [BigInt(taskId)],\n    })\n    const [, aId, taskType, inputData, outputData, status, client, createdAt, completedAt] = r as any\n    const statusMap: A2ATaskStatus[] = ['created', 'accepted', 'in_progress', 'completed', 'failed']\n    return {\n      taskId: taskId,\n      creator: client as string,\n      targetAgentId: Number(aId),\n      taskType: taskType as string,\n      input: inputData as string,\n      status: statusMap[Number(status)] ?? 'created',\n      result: outputData as string | undefined,\n      createdAt: Number(createdAt),\n      completedAt: completedAt as bigint > 0n ? Number(completedAt) : undefined,\n    }\n  }\n\n  async getUserTasks(user: Address): Promise<number[]> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [A2A_ABI.getUserTasks],\n      functionName: 'getUserTasks',\n      args: [user],\n    })\n    return (r as bigint[]).map(Number)\n  }\n\n  async getAgentTasks(agentId: number): Promise<A2ATask[]> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [A2A_ABI.getAgentTasks],\n      functionName: 'getAgentTasks',\n      args: [BigInt(agentId)],\n    })\n    const statusMap: A2ATaskStatus[] = ['created', 'accepted', 'in_progress', 'completed', 'failed']\n    const tasks = r as any[]\n    return tasks.map((t: any) => ({\n      taskId: Number(t.taskId),\n      creator: t.clientAddress as string,\n      targetAgentId: Number(t.agentId),\n      taskType: t.taskType as string,\n      input: t.inputData as string,\n      status: statusMap[Number(t.status)] ?? 'created',\n      result: t.outputData as string | undefined,\n      createdAt: Number(t.createdAt),\n      completedAt: t.completedAt as bigint > 0n ? Number(t.completedAt) : undefined,\n    }))\n  }\n\n  async getAddress(): Promise<Address> {\n    return this.account\n  }\n\n  // ── Helpers ─────────────────────────────────────────────────────────────\n\n  private _parseUintFromLog(receipt: { logs: { topics: string[]; data?: string }[] }, _eventName: string): number {\n    for (const log of receipt.logs) {\n      if (log.topics.length >= 2) {\n        try { return Number(BigInt(log.topics[1]!)) } catch { /* */ }\n      }\n      if (log.data && log.data !== '0x') {\n        try { return Number(BigInt(log.data)) } catch { /* */ }\n      }\n    }\n    return 0\n  }\n}\n","// @agentx/sdk — A2A module\nexport { A2AProtocol } from './a2a'\nexport type { A2AConfig } from './a2a'\nexport const A2A_VERSION = '0.1.0'\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — MCP Connector\n// ---------------------------------------------------------------------------\n// Minimal MCP (Model Context Protocol) client for HTTP/SSE transports.\n// Used by AgentRunner for Closed Skill remote execution.\n// ---------------------------------------------------------------------------\n\nimport type { McpConnection } from '../core/types'\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface MCPTool {\n  name: string\n  description?: string\n  inputSchema: Record<string, unknown>\n}\n\nexport interface MCPCallResult {\n  content: { type: string; text?: string; data?: string }[]\n  isError?: boolean\n}\n\nexport interface MCPConnectorConfig {\n  /** MCP server base URL */\n  url: string\n  /** Transport type */\n  transport?: 'http' | 'sse'\n  /** Auth header value (e.g. \"Bearer xxx\") */\n  authHeader?: string\n  /** Request timeout in ms (default: 30_000) */\n  timeoutMs?: number\n  /** Optional: subscriber address for subscription-gated MCP servers */\n  subscriberAddress?: string\n  /** Optional: wallet signature for authentication */\n  signature?: string\n  timestamp?: number\n}\n\n// ── MCP Connector ──────────────────────────────────────────────────────────\n\nexport class MCPConnector {\n  private config: MCPConnectorConfig\n\n  constructor(config: MCPConnectorConfig) {\n    this.config = { timeoutMs: 30_000, transport: 'http', ...config }\n  }\n\n  /** Create from an Agent's McpConnection. */\n  static fromAgent(mcp: McpConnection, opts?: Partial<MCPConnectorConfig>): MCPConnector {\n    return new MCPConnector({\n      url: mcp.url ?? '',\n      transport: mcp.type === 'sse' ? 'sse' : 'http',\n      authHeader: mcp.authHeader,\n      ...opts,\n    })\n  }\n\n  // ── Tool Discovery ───────────────────────────────────────────────────────\n\n  /** List available tools from the MCP server. */\n  async listTools(): Promise<MCPTool[]> {\n    const res = await this._request('tools/list', {})\n    return (res.tools ?? []) as MCPTool[]\n  }\n\n  // ── Tool Execution ───────────────────────────────────────────────────────\n\n  /** Call a tool on the MCP server. */\n  async callTool(name: string, args: Record<string, unknown> = {}): Promise<MCPCallResult> {\n    return this._request('tools/call', { name, arguments: args }) as unknown as Promise<MCPCallResult>\n  }\n\n  // ── Resources (optional) ─────────────────────────────────────────────────\n\n  async listResources(): Promise<unknown[]> {\n    const res = await this._request('resources/list', {})\n    return (res.resources ?? []) as unknown[]\n  }\n\n  async readResource(uri: string): Promise<unknown> {\n    return this._request('resources/read', { uri })\n  }\n\n  // ── Internal ─────────────────────────────────────────────────────────────\n\n  private async _request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {\n    const headers: Record<string, string> = {\n      'Content-Type': 'application/json',\n    }\n    if (this.config.authHeader) {\n      headers['Authorization'] = this.config.authHeader\n    }\n    if (this.config.subscriberAddress) {\n      headers['X-Subscriber-Address'] = this.config.subscriberAddress\n    }\n    if (this.config.signature) {\n      headers['X-Signature'] = this.config.signature\n    }\n    if (this.config.timestamp) {\n      headers['X-Timestamp'] = String(this.config.timestamp)\n    }\n\n    const res = await fetch(this.config.url, {\n      method: 'POST',\n      headers,\n      body: JSON.stringify({\n        jsonrpc: '2.0',\n        id: Date.now(),\n        method,\n        params,\n      }),\n      signal: AbortSignal.timeout(this.config.timeoutMs ?? 30_000),\n    })\n\n    if (!res.ok) {\n      throw new Error(`MCP request failed: HTTP ${res.status}`)\n    }\n\n    const data = await res.json() as { result?: Record<string, unknown>; error?: { message: string } }\n    if (data.error) {\n      throw new Error(`MCP error: ${data.error.message}`)\n    }\n    return data.result ?? {}\n  }\n}\n","// @agentx/sdk — MCP module\nexport { MCPConnector } from './connector'\nexport type { MCPConnectorConfig, MCPTool, MCPCallResult } from './connector'\nexport const MCP_VERSION = '0.1.0'\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Reputation\n// ---------------------------------------------------------------------------\n// Wraps ReputationRegistry contract for agent ratings and reviews.\n// ---------------------------------------------------------------------------\n\nimport type { PublicClient, WalletClient, Address, Hash } from 'viem'\nimport type { AgentReputation, AgentReview } from '../core/types'\n\nconst REPUTATION_ABI = {\n  rateAgent: {\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'rating', type: 'uint8' },\n      { name: 'comment', type: 'string' },\n    ] as const,\n    name: 'rateAgent' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  getRating: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getRating' as const,\n    outputs: [\n      { name: 'averageRating', type: 'uint256' },\n      { name: 'totalRatings', type: 'uint256' },\n    ] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getReviews: {\n    inputs: [{ name: 'agentId', type: 'uint256' }] as const,\n    name: 'getReviews' as const,\n    outputs: [\n      {\n        name: '',\n        type: 'tuple[]',\n        components: [\n          { name: 'reviewer', type: 'address' },\n          { name: 'rating', type: 'uint8' },\n          { name: 'comment', type: 'string' },\n          { name: 'timestamp', type: 'uint256' },\n        ],\n      },\n    ] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n} as const\n\nexport interface ReputationConfig {\n  contractAddress: Address\n  publicClient: PublicClient\n  walletClient: WalletClient\n}\n\nexport class ReputationRegistry {\n  private address: Address\n  private publicClient: PublicClient\n  private walletClient: WalletClient\n\n  constructor(config: ReputationConfig) {\n    this.address = config.contractAddress\n    this.publicClient = config.publicClient\n    this.walletClient = config.walletClient\n  }\n\n  private get account(): Promise<Address> {\n    return this.walletClient.getAddresses().then(a => {\n      if (!a[0]) throw new Error('Wallet not connected')\n      return a[0]\n    })\n  }\n\n  /** Submit a rating (1-5) with optional comment. */\n  async rate(agentId: number, rating: number, comment = ''): Promise<Hash> {\n    if (rating < 1 || rating > 5) throw new Error('Rating must be 1-5')\n    const acct = await this.account\n    const { request } = await this.publicClient.simulateContract({\n      account: acct,\n      address: this.address,\n      abi: [REPUTATION_ABI.rateAgent],\n      functionName: 'rateAgent',\n      args: [BigInt(agentId), rating, comment],\n    })\n    return this.walletClient.writeContract(request)\n  }\n\n  /** Get average rating and total count. */\n  async getRating(agentId: number): Promise<{ averageRating: number; totalRatings: number }> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [REPUTATION_ABI.getRating],\n      functionName: 'getRating',\n      args: [BigInt(agentId)],\n    })\n    const [avg, total] = r as [bigint, bigint]\n    return { averageRating: Number(avg), totalRatings: Number(total) }\n  }\n\n  /** Get all reviews for an agent. */\n  async getReviews(agentId: number): Promise<AgentReview[]> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [REPUTATION_ABI.getReviews],\n      functionName: 'getReviews',\n      args: [BigInt(agentId)],\n    })\n    return (r as { reviewer: string; rating: number; comment: string; timestamp: bigint }[])\n      .map(x => ({\n        reviewer: x.reviewer as Address,\n        rating: x.rating,\n        comment: x.comment,\n        timestamp: Number(x.timestamp),\n      }))\n  }\n\n  /** Get full reputation summary. */\n  async getReputation(agentId: number): Promise<AgentReputation> {\n    const [rating, reviews] = await Promise.all([\n      this.getRating(agentId),\n      this.getReviews(agentId),\n    ])\n    return { agentId, ...rating, reviews }\n  }\n}\n","// @agentx/sdk — Reputation module\nexport { ReputationRegistry } from './reputation'\nexport type { ReputationConfig } from './reputation'\nexport const REPUTATION_VERSION = '0.1.0'\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — Configuration\n// ---------------------------------------------------------------------------\n// Wraps ConfigurationRegistry contract for key-value settings.\n// ---------------------------------------------------------------------------\n\nimport { stringToHex, hexToString } from 'viem'\nimport type { PublicClient, WalletClient, Address, Hash } from 'viem'\n\nconst CONFIG_ABI = {\n  setConfig: {\n    inputs: [{ name: 'key', type: 'string' }, { name: 'value', type: 'bytes' }] as const,\n    name: 'setConfig' as const,\n    outputs: [] as const,\n    stateMutability: 'nonpayable' as const,\n    type: 'function' as const,\n  },\n  getConfig: {\n    inputs: [{ name: 'key', type: 'string' }] as const,\n    name: 'getConfig' as const,\n    outputs: [{ name: '', type: 'bytes' }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n  getAllConfig: {\n    inputs: [] as const,\n    name: 'getAllConfig' as const,\n    outputs: [{ name: '', type: 'tuple[]', components: [{ name: 'key', type: 'string' }, { name: 'value', type: 'bytes' }] }] as const,\n    stateMutability: 'view' as const,\n    type: 'function' as const,\n  },\n} as const\n\n// ── Known chain configs ────────────────────────────────────────────────────\n\n// Moves these to a separate file when the list grows.\n\nexport interface ChainConfig {\n  chainId: number\n  contracts: {\n    identityRegistry: Address\n    subscriptionManager: Address\n    a2aProtocolRegistry: Address\n    reputationRegistry: Address\n    configurationRegistry: Address\n    multiEndpointRegistry: Address\n  }\n  ipfsGateways: string[]\n  rpcUrl?: string\n}\n\nexport const KNOWN_CHAINS: Record<number, ChainConfig> = {\n  // Sepolia Testnet\n  // v3 (deployed 2026-07-13): platformFee=250bps(2.5%), ReentrancyGuard, audit fixes\n  11155111: {\n    chainId: 11155111,\n    contracts: {\n      identityRegistry: '0xe94ad380d3F8d08a7590eda0C84f354a93F96e5F',\n      subscriptionManager: '0xC15fE80b9d800abb72121F353a6ae6d6E9077E63',\n      a2aProtocolRegistry: '0x309C7447d89f3087A9924BB686d88df020F7e9cB',\n      reputationRegistry: '0xeb6B410ea71b8d9dA0c96f6A91d35027CE143DC9',\n      configurationRegistry: '0x68DcE00e4C9077c94BC68016cD14B09557faEA6c',\n      multiEndpointRegistry: '0xEB5e866f186d4B73F97aa0d70B86f2C6e2e21Cb7',\n    },\n    ipfsGateways: ['ipfs.io', 'gateway.pinata.cloud', 'dweb.link', 'cf-ipfs.com'],\n  },\n\n  // OxaChain L1 Mainnet\n  // Chain ID 19505, Clique PoA, Shanghai+Cancun, gas token OXA\n  // Deployer: 0x8E869A0624fF9e766Df71b5B08897d00E4d260ba\n  // RPC: https://rpc-oxa.0xainet.top\n  // Explorer: https://explorer-oxa.0xainet.top\n  // All 6 core contracts deployed 2026-07-14\n  19505: {\n    chainId: 19505,\n    contracts: {\n      identityRegistry: '0xbf5F9db266c8c97E3334466C88597Eb758AfE212',\n      subscriptionManager: '0x019AC9d945467478Dd371CDbD70cb2f325800E6B',\n      a2aProtocolRegistry: '0x7F42a7dC4A0F3C107664C3750bE1B5B6fa6BEb86',\n      reputationRegistry: '0x6a18C2664E1b42063860d864b6448b824d7B843F',\n      configurationRegistry: '0x07280674ccc2898Fd038A9e3C22005CA83ffD2F8',\n      multiEndpointRegistry: '0xB361d04F49000013FC131D3C59C41c8486C64f8c',\n    },\n    ipfsGateways: ['ipfs.io', 'gateway.pinata.cloud', 'dweb.link', 'cf-ipfs.com'],\n    rpcUrl: 'https://rpc-oxa.0xainet.top',\n  },\n}\n\n// ── Config Registry ────────────────────────────────────────────────────────\n\nexport interface ConfigRegistryOpts {\n  contractAddress: Address\n  publicClient: PublicClient\n  walletClient: WalletClient\n}\n\nexport class ConfigurationRegistry {\n  private address: Address\n  private publicClient: PublicClient\n  private walletClient: WalletClient\n\n  constructor(opts: ConfigRegistryOpts) {\n    this.address = opts.contractAddress\n    this.publicClient = opts.publicClient\n    this.walletClient = opts.walletClient\n  }\n\n  private get account(): Promise<Address> {\n    return this.walletClient.getAddresses().then(a => {\n      if (!a[0]) throw new Error('Wallet not connected')\n      return a[0]\n    })\n  }\n\n  async set(key: string, value: string): Promise<Hash> {\n    const acct = await this.account\n    const { request } = await this.publicClient.simulateContract({\n      account: acct,\n      address: this.address,\n      abi: [CONFIG_ABI.setConfig],\n      functionName: 'setConfig',\n      args: [key, stringToHex(value)],\n    })\n    return this.walletClient.writeContract(request)\n  }\n\n  async get(key: string): Promise<string> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [CONFIG_ABI.getConfig],\n      functionName: 'getConfig',\n      args: [key],\n    })\n    return hexToString(r as `0x${string}`)\n  }\n\n  async getAll(): Promise<Record<string, string>> {\n    const r = await this.publicClient.readContract({\n      address: this.address,\n      abi: [CONFIG_ABI.getAllConfig],\n      functionName: 'getAllConfig',\n    })\n    const map: Record<string, string> = {}\n    for (const { key, value } of r as { key: string; value: string }[]) {\n      map[key] = hexToString(value as `0x${string}`)\n    }\n    return map\n  }\n}\n","// @agentx/sdk — Configuration module\nexport { ConfigurationRegistry, KNOWN_CHAINS } from './config'\nexport type { ConfigRegistryOpts, ChainConfig } from './config'\nexport const CONFIG_VERSION = '0.1.0'\n","/**\n * MultiEndpointRegistry SDK\n * OxaChain L1 + Sepolia — multi-endpoint management for AI Agents\n */\nimport { type PublicClient, type WalletClient, type Address, type Hash, type Chain } from 'viem'\n\nexport interface EndpointRecord {\n  endpointId: bigint\n  agentId: bigint\n  name: string\n  endpointType: string\n  protocol: string\n  url: string\n  description: string\n  isActive: boolean\n  createdAt: bigint\n  updatedAt: bigint\n  createdBy: Address\n}\n\nexport interface MultiEndpointConfig {\n  address: Address\n}\n\nconst ABI = [\n  {\n    name: 'getActiveAgentEndpoints',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{\n      type: 'tuple[]',\n      components: [\n        { name: 'endpointId', type: 'uint256' },\n        { name: 'agentId', type: 'uint256' },\n        { name: 'name', type: 'string' },\n        { name: 'endpointType', type: 'string' },\n        { name: 'protocol', type: 'string' },\n        { name: 'url', type: 'string' },\n        { name: 'description', type: 'string' },\n        { name: 'isActive', type: 'bool' },\n        { name: 'createdAt', type: 'uint256' },\n        { name: 'updatedAt', type: 'uint256' },\n        { name: 'createdBy', type: 'address' },\n      ]\n    }],\n  },\n  {\n    name: 'getAgentEndpoints',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{\n      type: 'tuple[]',\n      components: [\n        { name: 'endpointId', type: 'uint256' },\n        { name: 'agentId', type: 'uint256' },\n        { name: 'name', type: 'string' },\n        { name: 'endpointType', type: 'string' },\n        { name: 'protocol', type: 'string' },\n        { name: 'url', type: 'string' },\n        { name: 'description', type: 'string' },\n        { name: 'isActive', type: 'bool' },\n        { name: 'createdAt', type: 'uint256' },\n        { name: 'updatedAt', type: 'uint256' },\n        { name: 'createdBy', type: 'address' },\n      ]\n    }],\n  },\n  {\n    name: 'createEndpoint',\n    type: 'function',\n    stateMutability: 'nonpayable',\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'name', type: 'string' },\n      { name: 'endpointType', type: 'string' },\n      { name: 'protocol', type: 'string' },\n      { name: 'url', type: 'string' },\n      { name: 'description', type: 'string' },\n    ],\n    outputs: [{ name: 'endpointId', type: 'uint256' }],\n  },\n  {\n    name: 'getEndpoint',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'endpointId', type: 'uint256' }],\n    outputs: [{\n      type: 'tuple',\n      components: [\n        { name: 'endpointId', type: 'uint256' },\n        { name: 'agentId', type: 'uint256' },\n        { name: 'name', type: 'string' },\n        { name: 'endpointType', type: 'string' },\n        { name: 'protocol', type: 'string' },\n        { name: 'url', type: 'string' },\n        { name: 'description', type: 'string' },\n        { name: 'isActive', type: 'bool' },\n        { name: 'createdAt', type: 'uint256' },\n        { name: 'updatedAt', type: 'uint256' },\n        { name: 'createdBy', type: 'address' },\n      ]\n    }],\n  },\n  {\n    name: 'getSupportedProtocols',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [],\n    outputs: [{ type: 'string[]' }],\n  },\n  {\n    name: 'getAgentEndpointStats',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [\n      { name: 'totalEndpoints', type: 'uint256' },\n      { name: 'activeEndpoints', type: 'uint256' },\n      { name: 'httpEndpoints', type: 'uint256' },\n      { name: 'websocketEndpoints', type: 'uint256' },\n      { name: 'grpcEndpoints', type: 'uint256' },\n    ],\n  },\n] as const\n\nexport class MultiEndpointClient {\n  private address: Address\n  private publicClient: PublicClient | null\n\n  constructor(config: MultiEndpointConfig, publicClient?: PublicClient) {\n    this.address = config.address\n    this.publicClient = publicClient ?? null\n  }\n\n  setPublicClient(client: PublicClient) {\n    this.publicClient = client\n  }\n\n  async getActiveEndpoints(agentId: bigint): Promise<EndpointRecord[]> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getActiveAgentEndpoints',\n      args: [agentId],\n    })) as EndpointRecord[]\n  }\n\n  async getAllEndpoints(agentId: bigint): Promise<EndpointRecord[]> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getAgentEndpoints',\n      args: [agentId],\n    })) as EndpointRecord[]\n  }\n\n  async getEndpoint(endpointId: bigint): Promise<EndpointRecord> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getEndpoint',\n      args: [endpointId],\n    })) as EndpointRecord\n  }\n\n  async getStats(agentId: bigint) {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getAgentEndpointStats',\n      args: [agentId],\n    })) as [bigint, bigint, bigint, bigint, bigint]\n  }\n\n  /** Pick best active endpoint for the agent — prefer HTTP, take first active */\n  async pickBestEndpoint(agentId: bigint): Promise<EndpointRecord | null> {\n    const endpoints = await this.getActiveEndpoints(agentId)\n    if (endpoints.length === 0) return null\n    // prefer HTTP endpoints\n    const http = endpoints.find(e => e.protocol === 'HTTP')\n    return http ?? endpoints[0] ?? null\n  }\n\n  /** Pick any active endpoint URL — for MCP connector */\n  async getBestMCPUrl(agentId: bigint): Promise<string | null> {\n    const best = await this.pickBestEndpoint(agentId)\n    return best?.url ?? null\n  }\n}\n","/**\n * ConfigurationRegistry SDK\n * On-chain key-value config store for AI Agents\n */\nimport { type PublicClient, type WalletClient, type Address, type Hash } from 'viem'\n\nexport interface ConfigEntry {\n  agentId: bigint\n  key: string\n  value: string\n  dataType: string\n  updatedAt: bigint\n  updatedBy: Address\n}\n\nexport interface ConfigurationConfig {\n  address: Address\n}\n\nconst ABI = [\n  {\n    name: 'getConfig',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'configKey', type: 'string' },\n    ],\n    outputs: [{\n      type: 'tuple',\n      components: [\n        { name: 'agentId', type: 'uint256' },\n        { name: 'key', type: 'string' },\n        { name: 'value', type: 'string' },\n        { name: 'dataType', type: 'string' },\n        { name: 'updatedAt', type: 'uint256' },\n        { name: 'updatedBy', type: 'address' },\n      ],\n    }],\n  },\n  {\n    name: 'getAgentConfigs',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{\n      type: 'tuple[]',\n      components: [\n        { name: 'agentId', type: 'uint256' },\n        { name: 'key', type: 'string' },\n        { name: 'value', type: 'string' },\n        { name: 'dataType', type: 'string' },\n        { name: 'updatedAt', type: 'uint256' },\n        { name: 'updatedBy', type: 'address' },\n      ],\n    }],\n  },\n  {\n    name: 'getConfigKeys',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{ type: 'string[]' }],\n  },\n  {\n    name: 'getConfigCount',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{ type: 'uint256' }],\n  },\n  {\n    name: 'configExists',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'configKey', type: 'string' },\n    ],\n    outputs: [{ type: 'bool' }],\n  },\n] as const\n\nexport class ConfigurationClient {\n  private address: Address\n  private publicClient: PublicClient | null\n\n  constructor(config: ConfigurationConfig, publicClient?: PublicClient) {\n    this.address = config.address\n    this.publicClient = publicClient ?? null\n  }\n\n  setPublicClient(client: PublicClient) {\n    this.publicClient = client\n  }\n\n  async get(agentId: bigint, key: string): Promise<ConfigEntry | null> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    try {\n      return (await this.publicClient.readContract({\n        address: this.address,\n        abi: ABI,\n        functionName: 'getConfig',\n        args: [agentId, key],\n      })) as ConfigEntry\n    } catch {\n      return null\n    }\n  }\n\n  async getAll(agentId: bigint): Promise<ConfigEntry[]> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getAgentConfigs',\n      args: [agentId],\n    })) as ConfigEntry[]\n  }\n\n  async getKeys(agentId: bigint): Promise<string[]> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getConfigKeys',\n      args: [agentId],\n    })) as string[]\n  }\n\n  async getCount(agentId: bigint): Promise<bigint> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'getConfigCount',\n      args: [agentId],\n    })) as bigint\n  }\n\n  async exists(agentId: bigint, key: string): Promise<boolean> {\n    if (!this.publicClient) throw new Error('publicClient not set')\n    return (await this.publicClient.readContract({\n      address: this.address,\n      abi: ABI,\n      functionName: 'configExists',\n      args: [agentId, key],\n    })) as boolean\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentx/sdk — IPFS Uploader\n// ---------------------------------------------------------------------------\n// Lightweight IPFS upload via Pinata REST API (JWT auth) or custom endpoint.\n// Zero extra deps — works in browser, Node, edge with native fetch.\n// ---------------------------------------------------------------------------\n\nimport type { EncryptedPayload } from '../core/types'\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface IPFSUploaderConfig {\n  /** Pinata JWT token. Required for Pinata uploads. */\n  pinataJwt?: string\n  /** Custom IPFS API endpoint. Falls back to Pinata if not set. */\n  customEndpoint?: string\n  /** Custom API key for non-Pinata endpoints */\n  customApiKey?: string\n  /** Gateway URL for building access URLs (default: ipfs.io) */\n  gatewayUrl?: string\n  /** Request timeout in ms (default: 30_000) */\n  timeoutMs?: number\n  /** Pinata group ID for organizing pinned files */\n  pinataGroupId?: string\n  /** Metadata name prefix for pinned files */\n  namePrefix?: string\n}\n\nexport interface IPFSUploadResult {\n  /** IPFS CID (Content Identifier) */\n  cid: string\n  /** Full IPFS gateway URL */\n  url: string\n  /** Raw response from the upload endpoint */\n  raw: Record<string, unknown>\n}\n\n// ── Implementation ─────────────────────────────────────────────────────────\n\nexport class IPFSUploader {\n  private pinataJwt: string | null\n  private customEndpoint: string | null\n  private customApiKey: string | null\n  private gatewayUrl: string\n  private timeoutMs: number\n  private pinataGroupId: string | null\n  private namePrefix: string\n\n  private static readonly PINATA_JSON_API = 'https://api.pinata.cloud/pinning/pinJSONToIPFS'\n  private static readonly PINATA_FILE_API = 'https://api.pinata.cloud/pinning/pinFileToIPFS'\n\n  constructor(config: IPFSUploaderConfig = {}) {\n    this.pinataJwt = config.pinataJwt ?? null\n    this.customEndpoint = config.customEndpoint ?? null\n    this.customApiKey = config.customApiKey ?? null\n    this.gatewayUrl = config.gatewayUrl ?? 'https://ipfs.io'\n    this.timeoutMs = config.timeoutMs ?? 30_000\n    this.pinataGroupId = config.pinataGroupId ?? null\n    this.namePrefix = config.namePrefix ?? 'agentx-'\n  }\n\n  isConfigured(): boolean {\n    if (this.customEndpoint) return true\n    return !!this.pinataJwt\n  }\n\n  // ── JSON Upload ───────────────────────────────────────────────────────\n\n  /**\n   * Upload JSON-serializable data to IPFS.\n   *\n   * @param data       Any JSON-serializable value\n   * @param metadata   Optional name / keyvalues for Pinata metadata\n   */\n  async uploadJSON(\n    data: unknown,\n    metadata?: { name?: string; keyvalues?: Record<string, string> }\n  ): Promise<IPFSUploadResult> {\n    const endpoint = this.customEndpoint ?? IPFSUploader.PINATA_JSON_API\n\n    const body: Record<string, unknown> = {\n      pinataContent: data,\n      pinataMetadata: {\n        name: this.namePrefix + (metadata?.name ?? `json-${Date.now()}`),\n        keyvalues: metadata?.keyvalues ?? {},\n      },\n    }\n\n    if (this.pinataGroupId) {\n      ;(body.pinataMetadata as Record<string, unknown>).groupId = this.pinataGroupId\n    }\n\n    return this._doFetch(endpoint, body)\n  }\n\n  // ── File Upload ───────────────────────────────────────────────────────\n\n  /**\n   * Upload a file / Blob / Buffer / Uint8Array / string to IPFS.\n   */\n  async uploadFile(\n    content: Blob | Buffer | Uint8Array | string,\n    fileName?: string,\n    mimeType?: string\n  ): Promise<IPFSUploadResult> {\n    const endpoint = this.customEndpoint ?? IPFSUploader.PINATA_FILE_API\n\n    const formData = new FormData()\n\n    const blobPart = (\n      content instanceof Blob ? content\n      : typeof Buffer !== 'undefined' && Buffer.isBuffer(content) ? new Uint8Array(content)\n      : content instanceof Uint8Array ? content\n      : content // string\n    ) as BlobPart\n\n    const blob = new Blob([blobPart], { type: mimeType ?? 'application/octet-stream' })\n\n    formData.append('file', blob, fileName ?? `file-${Date.now()}`)\n\n    const metadata = JSON.stringify({\n      name: this.namePrefix + (fileName ?? `file-${Date.now()}`),\n      ...(this.pinataGroupId ? { groupId: this.pinataGroupId } : {}),\n    })\n    formData.append('pinataMetadata', metadata)\n\n    return this._doFetch(endpoint, formData)\n  }\n\n  // ── Encrypted Payload Upload (AgentX specific) ────────────────────────\n\n  /**\n   * Upload an encrypted agent payload to IPFS.\n   * This is the primary method used by Agent Studio publish flow.\n   */\n  async uploadEncryptedPayload(\n    payload: EncryptedPayload,\n    agentName?: string\n  ): Promise<IPFSUploadResult> {\n    return this.uploadJSON(payload, { name: agentName ?? 'agent-payload' })\n  }\n\n  // ── Convenience ──────────────────────────────────────────────────────────\n\n  async uploadString(content: string, name?: string): Promise<IPFSUploadResult> {\n    return this.uploadJSON({ content }, { name: name ?? 'string-data' })\n  }\n\n  /** Build a public access URL from a CID. */\n  getUrl(cid: string): string {\n    return `${this.gatewayUrl}/ipfs/${cid}`\n  }\n\n  // ── Internal ─────────────────────────────────────────────────────────────\n\n  private async _doFetch(\n    url: string,\n    body: BodyInit | Record<string, unknown>\n  ): Promise<IPFSUploadResult> {\n    const headers: Record<string, string> = {}\n\n    if (url === IPFSUploader.PINATA_JSON_API || url === IPFSUploader.PINATA_FILE_API) {\n      if (!this.pinataJwt) throw new Error('Pinata JWT is not configured')\n      headers['Authorization'] = `Bearer ${this.pinataJwt}`\n    } else if (this.customApiKey) {\n      headers['Authorization'] = `Bearer ${this.customApiKey}`\n    }\n\n    if (!(body instanceof FormData)) {\n      headers['Content-Type'] = 'application/json'\n      // eslint-disable-next-line no-param-reassign\n      body = JSON.stringify(body)\n    }\n\n    const res = await fetch(url, {\n      method: 'POST',\n      headers,\n      body: body as BodyInit,\n      signal: AbortSignal.timeout?.(this.timeoutMs),\n    })\n\n    if (!res.ok) {\n      const errText = await res.text().catch(() => '')\n      throw new Error(`IPFS upload failed: HTTP ${res.status} — ${errText.slice(0, 200)}`)\n    }\n\n    const raw = (await res.json()) as Record<string, unknown>\n\n    const cid = (raw.IpfsHash as string) || (raw.cid as string) || (raw.Hash as string)\n    if (!cid || typeof cid !== 'string') throw new Error('Upload succeeded but no CID returned')\n\n    return { cid, url: this.getUrl(cid), raw }\n  }\n}\n\n/** Shared default instance (unconfigured until pinataJwt is set). */\nexport const defaultIPFSUploader = new IPFSUploader()\n","// @agentx/sdk — Traces Module\n// Structured trace events for agent observability\n\nexport interface TraceEvent {\n  tenantId: string\n  agentId: number\n  sessionId: string\n  type: 'tool_call' | 'tool_result' | 'text_delta' | 'session_complete'\n  timestamp: number\n  data: Record<string, unknown>\n}\n\nexport interface TraceEmitter {\n  emit(event: TraceEvent): void\n}\n\n/** No-op emitter — zero overhead when tracing is not configured */\nexport class NoopTraceEmitter implements TraceEmitter {\n  emit(_event: TraceEvent): void {}\n}\n\n/** Batched HTTP trace emitter — sends events to a remote collector */\nexport class HttpTraceEmitter implements TraceEmitter {\n  private buffer: TraceEvent[] = []\n  private timer: ReturnType<typeof setTimeout> | null = null\n\n  constructor(\n    private readonly endpoint: string,\n    private readonly authToken?: string,\n    private readonly flushIntervalMs = 5000,\n    private readonly maxBufferSize = 100,\n  ) {}\n\n  emit(event: TraceEvent): void {\n    this.buffer.push(event)\n    if (this.buffer.length >= this.maxBufferSize) {\n      this.flush()\n      return\n    }\n    if (!this.timer) {\n      this.timer = setTimeout(() => this.flush(), this.flushIntervalMs)\n    }\n  }\n\n  private flush(): void {\n    if (this.buffer.length === 0) return\n    const batch = this.buffer.splice(0)\n    if (this.timer) { clearTimeout(this.timer); this.timer = null }\n\n    // Fire-and-forget — don't block AgentLoop\n    fetch(this.endpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        ...(this.authToken ? { 'Authorization': `Bearer ${this.authToken}` } : {}),\n      },\n      body: JSON.stringify({ events: batch }),\n    }).catch(() => {})\n  }\n}\n\nexport interface TraceConfig {\n  emitter: TraceEmitter\n  enabled: boolean\n}\n","// @agentx/sdk — Browser Control Skill\n// Text-based DOM manipulation for browser-side agent execution.\n// No external dependencies — uses native browser APIs only.\n//\n// Usage:\n//   import { executeBrowserAction, extractAccessibleDOM, sleep } from '@agentxv2/sdk/skills'\n//   const result = executeBrowserAction({ type: 'click', selector: '#submit' })\n//   await sleep(300)  // optional pacing between actions\n\nexport interface BrowserAction {\n  type:\n    | 'click' | 'type' | 'extract' | 'scroll' | 'navigate'\n    // v0.9.0 additions:\n    | 'hover' | 'press' | 'select' | 'back' | 'forward' | 'getInfo'\n  /** CSS selector or text content of the target element */\n  selector?: string\n  /** Value for 'type' / 'select' actions, URL for 'navigate', key for 'press', px for 'scroll' */\n  value?: string\n  /** Natural language description (fallback when no selector) */\n  description?: string\n}\n\nexport interface BrowserActionResult {\n  success: boolean\n  result?: string\n  error?: string\n}\n\n/** Wait for a delay (async pacing helper for agent loops). */\nexport function sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Extract a text-based DOM representation from the current page.\n * Returns a simplified DOM tree with only interactive and text-containing elements.\n */\nexport function extractAccessibleDOM(): string {\n  if (typeof document === 'undefined') {\n    return 'Browser DOM not available (not running in browser)'\n  }\n\n  const interactiveTags = new Set([\n    'A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'FORM',\n    'H1', 'H2', 'H3', 'H4', 'H5', 'H6',\n    'P', 'SPAN', 'DIV', 'LI', 'TD', 'TH', 'LABEL',\n  ])\n\n  const elements: string[] = []\n  const walker = document.createTreeWalker(\n    document.body,\n    NodeFilter.SHOW_ELEMENT,\n    {\n      acceptNode: (node) => {\n        if (!(node instanceof HTMLElement)) return NodeFilter.FILTER_REJECT\n        if (!interactiveTags.has(node.tagName)) return NodeFilter.FILTER_REJECT\n        // Skip hidden elements\n        if (node.offsetParent === null && node.tagName !== 'A') return NodeFilter.FILTER_REJECT\n        return NodeFilter.FILTER_ACCEPT\n      },\n    }\n  )\n\n  let node: Node | null\n  while ((node = walker.nextNode())) {\n    const el = node as HTMLElement\n    const tag = el.tagName.toLowerCase()\n    const text = (el.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 80)\n    const id = el.id ? `#${el.id}` : ''\n    const classes = el.className && typeof el.className === 'string'\n      ? '.' + el.className.trim().split(/\\s+/).slice(0, 2).join('.')\n      : ''\n    const href = el.getAttribute('href')\n    const placeholder = el.getAttribute('placeholder')\n    const type = el.getAttribute('type')\n    const name = el.getAttribute('name')\n    const role = el.getAttribute('role')\n    const ariaLabel = el.getAttribute('aria-label')\n\n    let desc = `<${tag}${id}${classes}`\n    if (href) desc += ` href=\"${href}\"`\n    if (placeholder) desc += ` placeholder=\"${placeholder}\"`\n    if (type) desc += ` type=\"${type}\"`\n    if (name) desc += ` name=\"${name}\"`\n    if (role) desc += ` role=\"${role}\"`\n    if (ariaLabel) desc += ` aria-label=\"${ariaLabel}\"`\n\n    // Form value / state — makes the snapshot actionable for the agent.\n    if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n      if (el.value) desc += ` value=\"${String(el.value).slice(0, 60)}\"`\n      if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) {\n        desc += ` checked=\"${el.checked}\"`\n      }\n    } else if (el instanceof HTMLSelectElement && el.value) {\n      desc += ` value=\"${el.value}\"`\n    } else if (el instanceof HTMLAnchorElement) {\n      desc += ` target=\"${el.target || '_self'}\"`\n    }\n\n    desc += '>'\n    if (text) desc += `${text}`\n    desc += `</${tag}>`\n\n    elements.push(desc)\n  }\n\n  return elements.join('\\n').slice(0, 8000)  // cap at ~8K chars\n}\n\n/**\n * Execute a single browser action directly in the DOM.\n */\nexport function executeBrowserAction(action: BrowserAction): BrowserActionResult {\n  if (typeof document === 'undefined') {\n    return { success: false, error: 'Not running in browser environment' }\n  }\n\n  try {\n    const el = findElement(action.selector, action.description)\n    const needsEl = !['navigate', 'extract', 'getInfo', 'back', 'forward', 'scroll'].includes(action.type)\n    if (!el && needsEl) {\n      return { success: false, error: `Element not found: ${action.selector || action.description}` }\n    }\n\n    switch (action.type) {\n      case 'click': {\n        (el as HTMLElement).click()\n        return { success: true, result: 'Clicked' }\n      }\n\n      case 'type': {\n        const input = el as HTMLInputElement | HTMLTextAreaElement\n        input.focus()\n        input.value = action.value || ''\n        input.dispatchEvent(new Event('input', { bubbles: true }))\n        input.dispatchEvent(new Event('change', { bubbles: true }))\n        return { success: true, result: `Typed: ${action.value}` }\n      }\n\n      case 'press': {\n        const key = action.value || action.selector || ''\n        if (!key) return { success: false, error: 'No key provided for press' }\n        const target = (el || document.activeElement || document.body) as Element\n        const opts = { bubbles: true, cancelable: true, key }\n        target.dispatchEvent(new KeyboardEvent('keydown', opts))\n        target.dispatchEvent(new KeyboardEvent('keyup', opts))\n        return { success: true, result: `Pressed: ${key}` }\n      }\n\n      case 'hover': {\n        const target = el as HTMLElement\n        target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }))\n        target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }))\n        target.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }))\n        return { success: true, result: `Hovered: ${action.selector || action.description || target.tagName}` }\n      }\n\n      case 'select': {\n        const value = action.value || ''\n        if (el instanceof HTMLSelectElement) {\n          el.value = value\n          el.dispatchEvent(new Event('change', { bubbles: true }))\n          return { success: true, result: `Selected: ${value}` }\n        }\n        if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) {\n          const checked = value === '' ? !el.checked : value.toLowerCase() === 'true' || value === '1'\n          el.checked = checked\n          el.dispatchEvent(new Event('change', { bubbles: true }))\n          return { success: true, result: `Checked: ${checked}` }\n        }\n        return { success: false, error: `Element is not a select/checkbox/radio: ${action.selector}` }\n      }\n\n      case 'extract': {\n        if (action.selector) {\n          const content = el?.textContent || ''\n          return { success: true, result: content.slice(0, 5000) }\n        }\n        // Extract full page accessible DOM\n        return { success: true, result: extractAccessibleDOM() }\n      }\n\n      case 'getInfo': {\n        return {\n          success: true,\n          result: JSON.stringify({\n            url: window.location.href,\n            title: document.title,\n            readyState: document.readyState,\n            viewport: { width: window.innerWidth, height: window.innerHeight },\n            scrollY: Math.round(window.scrollY),\n          }),\n        }\n      }\n\n      case 'scroll': {\n        if (el) {\n          el.scrollIntoView({ behavior: 'smooth', block: 'center' })\n        } else {\n          window.scrollBy({ top: action.value ? parseInt(action.value) || 500 : 500, behavior: 'smooth' })\n        }\n        return { success: true, result: 'Scrolled' }\n      }\n\n      case 'navigate': {\n        const url = action.value || action.selector\n        if (!url) return { success: false, error: 'No URL provided' }\n        window.location.href = url\n        return { success: true, result: `Navigating to ${url}` }\n      }\n\n      case 'back': {\n        window.history.back()\n        return { success: true, result: 'Navigated back' }\n      }\n\n      case 'forward': {\n        window.history.forward()\n        return { success: true, result: 'Navigated forward' }\n      }\n\n      default:\n        return { success: false, error: `Unknown action type: ${(action as any).type}` }\n    }\n  } catch (err) {\n    return { success: false, error: err instanceof Error ? err.message : String(err) }\n  }\n}\n\nfunction findElement(selector?: string, description?: string): Element | null {\n  // Try CSS selector first\n  if (selector) {\n    try {\n      const el = document.querySelector(selector)\n      if (el) return el\n    } catch { /* invalid selector */ }\n  }\n\n  // Fallback: text content search\n  const searchText = description || selector\n  if (!searchText) return null\n\n  const all = document.querySelectorAll('a, button, input, select, textarea, [role=\"button\"]')\n  const lower = searchText.toLowerCase()\n  for (const el of all) {\n    const text = (el.textContent || '').toLowerCase()\n    const placeholder = (el.getAttribute('placeholder') || '').toLowerCase()\n    const ariaLabel = (el.getAttribute('aria-label') || '').toLowerCase()\n    const name = (el.getAttribute('name') || '').toLowerCase()\n    if (text.includes(lower) || placeholder.includes(lower) || ariaLabel.includes(lower) || name.includes(lower)) {\n      return el\n    }\n  }\n\n  return null\n}\n","// ---------------------------------------------------------------------------\n// AgentX SDK — ConversationClient (remote conversation service client)\n// ---------------------------------------------------------------------------\n// Wraps the hosted Conversation Service via the Gateway:\n//   POST /api/v1/agent/runs  (SSE stream)\n//\n// Auth (either one is required):\n//   - Tenant API Key:  X-Api-Key: agentx_xxx  (issued after registration)\n//   - Gateway JWT:     Authorization: Bearer <accessToken>  (wallet-signed login)\n// Isolation: X-End-User-Id (per end-user memory isolation within a tenant)\n// ---------------------------------------------------------------------------\n\nexport interface ConversationClientConfig {\n  /** Gateway base URL, e.g. https://agentx.0xainet.top */\n  gatewayUrl: string\n  /** Tenant API Key (agentx_...) issued after registration (alternative to accessToken) */\n  apiKey?: string\n  /** Gateway JWT access token from wallet-signed login (alternative to apiKey) */\n  accessToken?: string\n  /** End-user ID for memory isolation within the tenant (optional) */\n  endUserId?: string\n  /** LLM API Key override — uses the caller's key instead of the tenant's (optional) */\n  llmApiKey?: string\n  /** LLM endpoint override for the caller's key, e.g. DeepSeek https://api.deepseek.com/v1 (optional) */\n  llmEndpoint?: string\n  /** LLM model override for the caller's key, e.g. deepseek-chat (optional; default gpt-4o) */\n  llmModel?: string\n  /** Abort timeout in ms for a single stream (default 120s) */\n  timeoutMs?: number\n}\n\nexport interface ConversationSkillDef {\n  name: string\n  description: string\n  inputSchema: Record<string, unknown>\n  execution?: {\n    type: 'mcp' | 'http' | 'a2a'\n    endpoint?: string\n    toolName?: string\n    targetAgentId?: number\n    skillFilter?: string[]\n    promptOverride?: string\n  }\n}\n\nexport interface ConversationChatParams {\n  /** AgentX agent id (omit when using inline prompt/skills mode) */\n  agentId?: number\n  message: string\n  /** Full conversation history — caller is responsible for per-end-user isolation */\n  history?: { role: 'user' | 'assistant'; content: string }[]\n  enableMemory?: boolean\n  contextBudget?: number\n  /**\n   * Per-request end-user id. For B-end (partner) callers, a `0x<wallet>` value\n   * triggers subscription proxying on the Gateway (access is authorized by that\n   * wallet's ownership/subscription). Any other value is used for memory\n   * isolation only. Overrides the constructor-level `endUserId`.\n   */\n  endUserId?: string\n  /** Inline mode: caller-supplied system prompt, bypasses Gateway agent lookup */\n  prompt?: string\n  /** Inline mode: caller-supplied tools (MCP/HTTP), injected into the run */\n  skills?: ConversationSkillDef[]\n  /** BYOK: id of a stored tenant-owned API key (resolved server-side by the Gateway) */\n  tenantKeyId?: string\n}\n\n/**\n * On-chain rail (2026-08-08): the user's own wallet must create the A2A task —\n * they pay the gas and become the on-chain client. Emitted by the Conversation\n * Service when a run requests an auditable / settled delegation.\n */\nexport interface OnChainApprovalRequest {\n  targetAgentId: number\n  taskType: string\n  inputData: string\n}\n\nexport interface ConversationSSEEvent {\n  type: 'text' | 'tool_call' | 'tool_result' | 'thinking' | 'done' | 'error' | 'clarification' | 'onchain_approval_required'\n  content?: string\n  /** Clarification question when the service decides the request needs disambiguation */\n  question?: string\n  toolName?: string\n  toolArgs?: Record<string, unknown>\n  toolResult?: unknown\n  /** Attached to tool_result when tool execution failed */\n  error?: string\n  /** On-chain rail: the agent requested an A2A delegation the user must approve in their wallet */\n  approval?: OnChainApprovalRequest\n  usage?: { promptTokens: number; completionTokens: number; totalTokens: number }\n  iterations?: number\n  /** Billing source of the LLM that produced this run (emitted on `done`).\n   *  'byok' → caller's own key (not metered); 'platform' → AgentX key (metered\n   *  against the tenant's plan quota). Observability only — metering is server-side. */\n  llmSource?: 'byok' | 'platform'\n}\n\nexport interface ConversationChatResult {\n  text: string\n  toolCalls: { name: string; arguments: Record<string, unknown>; result?: unknown }[]\n  /** When set, the service asked the user to clarify instead of running the run */\n  clarification?: string\n  usage?: { promptTokens: number; completionTokens: number; totalTokens: number }\n  iterations?: number\n}\n\n// ── Tasks (parallel runs, P8) ─────────────────────────────────────────────\n\nexport type ConversationTaskStatus = 'queued' | 'running' | 'done' | 'error' | 'cancelled'\n\nexport interface ConversationTask {\n  id: string\n  sessionId: string\n  tenant: string\n  agentId?: number | null\n  endUserId?: string | null\n  message: string\n  status: ConversationTaskStatus\n  enableMemory: boolean\n  history?: unknown\n  prompt?: string | null\n  skills?: unknown\n  result?: string | null\n  error?: string | null\n  usage?: unknown\n  iterations?: number | null\n  createdAt: string\n  startedAt?: string | null\n  finishedAt?: string | null\n}\n\nexport interface ConversationCreateTaskParams {\n  sessionId: string\n  /** AgentX agent id (omit when using inline prompt/skills mode) */\n  agentId?: number\n  message: string\n  enableMemory?: boolean\n  /** Full conversation history (optional) */\n  history?: { role: 'user' | 'assistant'; content: string }[]\n  /** Inline mode: caller-supplied system prompt */\n  prompt?: string\n  /** Inline mode: caller-supplied tools */\n  skills?: ConversationSkillDef[]\n  /** BYOK: id of a stored tenant-owned API key */\n  tenantKeyId?: string\n  /**\n   * Per-request end-user id. For B-end (partner) callers, a `0x<wallet>` value\n   * triggers subscription proxying on the Gateway (access is authorized by that\n   * wallet's ownership/subscription). Any other value is used for memory\n   * isolation only.\n   */\n  endUserId?: string\n}\n\nexport interface ConversationCreateSessionParams {\n  sessionId?: string\n  agentId?: number\n  endUserId?: string\n  title?: string\n}\n\n/**\n * Thrown by task APIs when the platform rejects the request.\n * `code === 'PARALLEL_TASKS_DISABLED'` (HTTP 403) means the integrator/tenant\n * is configured to disallow multi-task / sub-agent (P9).\n */\nexport class ConversationTaskError extends Error {\n  readonly status: number\n  readonly code?: string\n  constructor(status: number, message: string, code?: string) {\n    super(message)\n    this.name = 'ConversationTaskError'\n    this.status = status\n    this.code = code\n  }\n}\n\n// ── A2A delegated tasks & Session Key auto-pay (AItrader REQ-1/2/3) ────────\n\n/** `a2a_task_results.status` values (Gateway worker). */\nexport const A2A_STATUS = {\n  PROCESSING: 1,\n  DONE: 2,\n  ERROR: 3,\n  AWAITING_PAYMENT: 4,\n} as const\n\n/** A2A delegated-task row as stored in `a2a_task_results` (GET /api/v1/a2a/task-result/:id). */\nexport interface A2ADelegatedTaskResult {\n  task_id: number\n  status: number\n  agent_id?: number | null\n  output_data?: string | null\n  error_message?: string | null\n  payment_payer?: string | null\n  payment_pay_to?: string | null\n  payment_amount_wei?: string | null\n  payment_target_agent_id?: number | null\n  payment_ref?: string | null\n  payment_pending_since?: string | null\n  /** Payment options offered while `status === A2A_STATUS.AWAITING_PAYMENT` (REQ-2). */\n  payment_pay_options?: { prepay: boolean; sessionKey: boolean } | null\n  created_at?: string\n  updated_at?: string\n}\n\n/** Session Key engine capability info (GET /api/v1/a2a/session-key/info). */\nexport interface SessionKeyInfo {\n  enabled: boolean\n  chain: string\n  chainId: number\n  baseUrl: string\n}\n\n/** Session Key authorization status for an end-user wallet (REQ-3, from billing/balance). */\nexport interface SessionKeyAuthStatus {\n  enabled: boolean\n  authorized: boolean\n  sessionAddress?: string\n  maxPerTx?: string\n  maxTotal?: string\n  totalSpent?: string\n  validUntil?: string\n}\n\n/** x402 ledger balance (GET /api/v1/billing/balance). */\nexport interface BillingBalance {\n  balance: string\n  balanceWei: string\n  currency: string\n  updatedAt?: string | null\n  subject: string\n  payTo?: string\n  priceWei?: string\n  sessionKey?: SessionKeyAuthStatus\n}\n\nexport class ConversationClient {\n  private readonly baseUrl: string\n\n  constructor(private readonly config: ConversationClientConfig) {\n    this.baseUrl = config.gatewayUrl.replace(/\\/$/, '')\n  }\n\n  /** Common auth/tenant headers for all Gateway API calls. */\n  private _headers(): Record<string, string> {\n    const headers: Record<string, string> = {\n      'Content-Type': 'application/json',\n    }\n    if (this.config.apiKey) headers['X-Api-Key'] = this.config.apiKey\n    if (this.config.accessToken) headers['Authorization'] = `Bearer ${this.config.accessToken}`\n    if (!this.config.apiKey && !this.config.accessToken) {\n      throw new Error('ConversationClient requires either apiKey or accessToken')\n    }\n    if (this.config.endUserId) headers['X-End-User-Id'] = this.config.endUserId\n    if (this.config.llmApiKey) headers['X-Llm-Api-Key'] = this.config.llmApiKey\n    if (this.config.llmEndpoint) headers['X-Llm-Endpoint'] = this.config.llmEndpoint\n    if (this.config.llmModel) headers['X-Llm-Model'] = this.config.llmModel\n    return headers\n  }\n\n  /**\n   * Stream an agent conversation (SSE). Yields parsed events.\n   * @param opts.signal external AbortSignal — aborts the stream (e.g. user \"stop\")\n   */\n  async *stream(params: ConversationChatParams, opts?: { signal?: AbortSignal }): AsyncGenerator<ConversationSSEEvent> {\n    const headers = this._headers()\n    if (params.endUserId) headers['X-End-User-Id'] = params.endUserId\n\n    const controller = new AbortController()\n    const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 120_000)\n    const onExternalAbort = () => controller.abort()\n    opts?.signal?.addEventListener('abort', onExternalAbort, { once: true })\n\n    try {\n      const res = await fetch(`${this.baseUrl}/api/v1/agent/runs`, {\n        method: 'POST',\n        headers,\n        body: JSON.stringify(params),\n        signal: controller.signal,\n      })\n\n      if (!res.ok) {\n        let detail = ''\n        try {\n          const body = await res.json()\n          detail = body?.error ?? ''\n        } catch {}\n        throw new Error(`Conversation request failed (HTTP ${res.status}) ${detail}`.trim())\n      }\n\n      if (!res.body) {\n        throw new Error('Conversation stream unavailable')\n      }\n\n      const reader = res.body.getReader()\n      const decoder = new TextDecoder()\n      let buffer = ''\n\n      while (true) {\n        const { done, value } = await reader.read()\n        if (done) break\n\n        buffer += decoder.decode(value, { stream: true })\n        const chunks = buffer.split('\\n\\n')\n        buffer = chunks.pop() ?? ''\n\n        for (const chunk of chunks) {\n          for (const line of chunk.split('\\n')) {\n            if (!line.startsWith('data: ')) continue\n            try {\n              const event = JSON.parse(line.slice(6)) as ConversationSSEEvent\n              yield event\n              if (event.type === 'error') {\n                throw new Error(event.error || 'Conversation error')\n              }\n            } catch (err) {\n              if (err instanceof SyntaxError) continue\n              throw err\n            }\n          }\n        }\n      }\n    } finally {\n      clearTimeout(timeout)\n      opts?.signal?.removeEventListener('abort', onExternalAbort)\n    }\n  }\n\n  /**\n   * Run a conversation and collect the full result.\n   */\n  async chat(params: ConversationChatParams): Promise<ConversationChatResult> {\n    const result: ConversationChatResult = { text: '', toolCalls: [] }\n\n    for await (const event of this.stream(params)) {\n      switch (event.type) {\n        case 'text':\n          result.text += event.content ?? ''\n          break\n        case 'tool_call':\n          result.toolCalls.push({ name: event.toolName ?? '', arguments: event.toolArgs ?? {} })\n          break\n        case 'tool_result': {\n          const last = result.toolCalls[result.toolCalls.length - 1]\n          if (last) {\n            last.result = event.toolResult\n          }\n          break\n        }\n        case 'clarification':\n          result.clarification = event.question ?? ''\n          break\n        case 'done':\n          result.usage = event.usage\n          result.iterations = event.iterations\n          break\n      }\n    }\n\n    return result\n  }\n\n  // ── Sessions & Tasks (parallel runs) ────────────────────────────────────\n\n  /**\n   * Query the integrator's capability flags (P9). When `parallelTasks` is false,\n   * `createTask` will be rejected with HTTP 403 `PARALLEL_TASKS_DISABLED` —\n   * callers should degrade to single-turn `chat()` in that case.\n   */\n  async getCapabilities(): Promise<{ parallelTasks: boolean; parallelTasksOverride: boolean | null }> {\n    const res = await fetch(`${this.baseUrl}/api/v1/tenant/me`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(res.status, body?.error || `Capability lookup failed (HTTP ${res.status})`)\n    }\n    return {\n      parallelTasks: body?.capabilities?.parallel_tasks ?? true,\n      parallelTasksOverride: body?.capabilities?.parallel_tasks_override ?? null,\n    }\n  }\n\n  /**\n   * Create a session (dialog container that owns many tasks). Idempotent.\n   */\n  async createSession(params: ConversationCreateSessionParams): Promise<{ id: string; tenant: string; agentId?: number | null; endUserId?: string | null; title?: string | null }> {\n    const res = await fetch(`${this.baseUrl}/api/v1/sessions`, {\n      method: 'POST',\n      headers: this._headers(),\n      body: JSON.stringify(params),\n    })\n    if (!res.ok) {\n      throw new ConversationTaskError(res.status, `Session creation failed (HTTP ${res.status})`)\n    }\n    return res.json()\n  }\n\n  /**\n   * Create a task — returns immediately with the task row (`status: queued`);\n   * execution happens in the background. Throws `ConversationTaskError` with\n   * `code === 'PARALLEL_TASKS_DISABLED'` (HTTP 403) when the tenant/plan is\n   * configured to disallow multi-task / sub-agent.\n   */\n  async createTask(params: ConversationCreateTaskParams): Promise<ConversationTask> {\n    const headers = this._headers()\n    if (params.endUserId) headers['X-End-User-Id'] = params.endUserId\n    const res = await fetch(`${this.baseUrl}/api/v1/sessions/${params.sessionId}/tasks`, {\n      method: 'POST',\n      headers,\n      body: JSON.stringify(params),\n    })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(\n        res.status,\n        body?.error || `Task creation failed (HTTP ${res.status})`,\n        body?.code,\n      )\n    }\n    return body as ConversationTask\n  }\n\n  /** Fetch a single task by id. */\n  async getTask(taskId: string): Promise<ConversationTask> {\n    const res = await fetch(`${this.baseUrl}/api/v1/tasks/${taskId}`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(res.status, body?.error || `Task lookup failed (HTTP ${res.status})`, body?.code)\n    }\n    return body as ConversationTask\n  }\n\n  /** List tasks of a session. */\n  async listTasks(sessionId: string): Promise<ConversationTask[]> {\n    const res = await fetch(`${this.baseUrl}/api/v1/sessions/${sessionId}/tasks`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(res.status, body?.error || `Task list failed (HTTP ${res.status})`, body?.code)\n    }\n    return (body.tasks ?? []) as ConversationTask[]\n  }\n\n  /** Cancel a task (queued → cancelled directly, running → aborted). */\n  async cancelTask(taskId: string): Promise<ConversationTask> {\n    const res = await fetch(`${this.baseUrl}/api/v1/tasks/${taskId}`, {\n      method: 'DELETE',\n      headers: this._headers(),\n    })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(res.status, body?.error || `Task cancel failed (HTTP ${res.status})`, body?.code)\n    }\n    return body as ConversationTask\n  }\n\n  // ── A2A delegated tasks & Session Key auto-pay (AItrader REQ-1/2/3) ─────\n\n  /** Fetch an A2A delegated-task result row (`a2a_task_results`). */\n  async getA2ATaskResult(taskId: string | number): Promise<A2ADelegatedTaskResult> {\n    const res = await fetch(`${this.baseUrl}/api/v1/a2a/task-result/${taskId}`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(\n        res.status,\n        body?.error || `A2A task result lookup failed (HTTP ${res.status})`,\n        body?.code,\n      )\n    }\n    return body as A2ADelegatedTaskResult\n  }\n\n  /**\n   * Re-activate an `awaiting_payment` A2A task after the end user has\n   * authorized (and funded) a Session Key. Does NOT deduct from the ledger —\n   * the worker re-runs and auto-pays via the session-key branch. The client\n   * must be configured with `endUserId` = the task's `payment_payer` (or the\n   * caller holds an admin key).\n   */\n  async retryA2ATask(taskId: string | number): Promise<{ retried: boolean; taskId: number }> {\n    const res = await fetch(`${this.baseUrl}/api/v1/a2a/tasks/${taskId}/retry`, {\n      method: 'POST',\n      headers: this._headers(),\n    })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(\n        res.status,\n        body?.error || `A2A task retry failed (HTTP ${res.status})`,\n        body?.code,\n      )\n    }\n    return body as { retried: boolean; taskId: number }\n  }\n\n  /**\n   * Session Key engine capability info — used by an end-user frontend to reach\n   * the engine's public `nonce` / `createSession` endpoints directly\n   * (EIP-712-verified; the session private key never transits the Gateway).\n   */\n  async getSessionKeyInfo(): Promise<SessionKeyInfo> {\n    const res = await fetch(`${this.baseUrl}/api/v1/a2a/session-key/info`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(\n        res.status,\n        body?.error || `Session-key info lookup failed (HTTP ${res.status})`,\n        body?.code,\n      )\n    }\n    return body as SessionKeyInfo\n  }\n\n  /** x402 ledger balance + Session Key authorization status (REQ-3). */\n  async getBalance(): Promise<BillingBalance> {\n    const res = await fetch(`${this.baseUrl}/api/v1/billing/balance`, { headers: this._headers() })\n    const body = await res.json().catch(() => ({}))\n    if (!res.ok) {\n      throw new ConversationTaskError(\n        res.status,\n        body?.error || `Balance lookup failed (HTTP ${res.status})`,\n        body?.code,\n      )\n    }\n    return body as BillingBalance\n  }\n}\n","// ---------------------------------------------------------------------------\n// @agentxv2/sdk — CentralAgentClient (C-6 中心化 Agent 市场 · 2026-09-05)\n// ---------------------------------------------------------------------------\n// 中心化 Agent（agents.source='central'，负 ID）不发布在链上：\n//   - 订阅计划存于网关 DB（central_plans），付费复用同一 x402 通道\n//     （价格覆盖走 SubscriptionPayments.pay({ priceWei, period })）。\n//   - 查询 / 订阅状态 / 我的订阅均为网关公开 HTTP API，SDK 在此封装，\n//     第三方项目（如 AItrader）无需自行拼接网关 URL。\n// 发布（POST /api/v1/agents/central）需要 JWT 或租户 API Key，由调用方自持，\n// 本客户端只封装公开只读端点。\n// ---------------------------------------------------------------------------\n\nimport { request } from '../payment/a2a-client'\n\n/** 中心化 Agent 的订阅计划（与链上 subscriptionPlans 同一响应结构，订阅流程无感）。 */\nexport interface CentralPlan {\n  planId: number\n  /** wei，十进制字符串（避免 JS 精度丢失）。 */\n  price: string\n  /** 订阅周期：day | week | month | year。 */\n  period: string\n  payToken: 'native'\n  isActive: boolean\n  trialDays: number\n  creator: string\n}\n\n/** 中心化 Agent 摘要（列表 / 详情响应）。 */\nexport interface CentralAgentSummary {\n  id: number\n  owner: string\n  name: string\n  description: string\n  tags: string[]\n  capabilities: string[]\n  skills: string[]\n  category: string\n  isActive: boolean\n  source: 'central'\n  agentCreatedAt?: string\n  syncedAt?: string | null\n  createdAt?: string\n  updatedAt?: string\n  subscriptionPlans?: CentralPlan[]\n}\n\n/** 钱包的链下订阅记录（fiat_subscriptions，provider='x402'）。 */\nexport interface CentralSubscription {\n  id: number\n  agentId: number\n  planId: number | null\n  provider: string\n  providerSubId: string | null\n  status: string\n  currency: string | null\n  amountCents: number | null\n  period: string | null\n  startsAt: string | null\n  expiresAt: string | null\n  createdAt: string\n  updatedAt: string\n}\n\nexport interface CentralAgentClientOptions {\n  /** AgentX Gateway 基础 URL，例如 https://agentx.0xainet.top。 */\n  baseUrl: string\n  /** 可选：注册用户 JWT（Authorization: Bearer）——发布/管理中心化 Agent 时使用。 */\n  accessToken?: string\n  /** 可选：租户 API Key（X-Api-Key）——发布/管理中心化 Agent 时使用（owner=partner-<slug>）。 */\n  apiKey?: string\n}\n\nexport interface CentralAgentListFilters {\n  activeOnly?: boolean\n  category?: string\n  page?: number\n  pageSize?: number\n}\n\n/** 发布中心化 Agent 的输入（POST /api/v1/agents/central）。 */\nexport interface CreateCentralAgentInput {\n  name: string\n  description?: string\n  tags?: string[]\n  capabilities?: string[]\n  skills?: string[]\n  category?: string\n}\n\n/** 更新中心化 Agent 的输入（PATCH 语义：仅更新提供的字段）。 */\nexport type UpdateCentralAgentInput = Partial<CreateCentralAgentInput> & { isActive?: boolean }\n\n/** 添加中心化订阅计划（POST /api/v1/agents/central/:id/plans）。 */\nexport interface CreateCentralPlanInput {\n  /** wei 十进制字符串（正数）。 */\n  priceWei: string\n  /** 周期：day | week | month | year（默认 month）。 */\n  period?: string\n}\n\n/** 网关返回的计划行（central_plans）。 */\nexport interface CentralPlanRow {\n  id: number\n  agentId: number\n  priceWei: string\n  period: string\n  active: boolean\n}\n\n/** 中心化 Agent 客户端：公开只读（查询/订阅状态/我的订阅）+ 鉴权管理（发布/更新/下架/计划）。 */\nexport class CentralAgentClient {\n  constructor(private opts: CentralAgentClientOptions) {}\n\n  private get base(): string {\n    return this.opts.baseUrl.replace(/\\/$/, '')\n  }\n\n  /** 鉴权头：X-Api-Key（租户 Key）；JWT 由 request 助手按 accessToken 追加 Bearer。 */\n  private authHeaders(): Record<string, string> {\n    const headers: Record<string, string> = { 'Content-Type': 'application/json' }\n    if (this.opts.apiKey) headers['X-Api-Key'] = this.opts.apiKey\n    return headers\n  }\n\n  // ── 公开只读 ─────────────────────────────────────────────────────────────\n\n  /**\n   * 查询中心化 Agent 列表（公开）。固定 source='central'，\n   * 与链上 Agent 天然隔离；page/pageSize 分页（网关默认 pageSize=50，上限 100）。\n   */\n  async list(filters: CentralAgentListFilters = {}): Promise<{ agents: CentralAgentSummary[]; total: number; page: number; pageSize: number }> {\n    const params = new URLSearchParams({ source: 'central' })\n    if (filters.activeOnly !== undefined) params.set('activeOnly', String(filters.activeOnly))\n    if (filters.category) params.set('category', filters.category)\n    if (filters.page !== undefined) params.set('page', String(filters.page))\n    if (filters.pageSize !== undefined) params.set('pageSize', String(filters.pageSize))\n    return request(this.base, `/api/v1/agents?${params.toString()}`, undefined, this.opts.accessToken)\n  }\n\n  /**\n   * 查询单个中心化 Agent 详情（公开），含订阅计划（subscriptionPlans，\n   * 与链上同一结构，可直接喂给 SubscriptionPayments.pay({ planId, priceWei, period })）。\n   */\n  async get(agentId: number): Promise<CentralAgentSummary> {\n    return request(this.base, `/api/v1/agents/${agentId}`, undefined, this.opts.accessToken)\n  }\n\n  /**\n   * 订阅状态检查（公开）：resolveAccess 链下优先——中心化 Agent（负 ID）无链上\n   * 代币，访问记录在 fiat_subscriptions（x402 通道），由网关判定是否放行。\n   */\n  async checkSubscription(subscriber: string, agentId: number): Promise<{ chain: string; subscriber: string; agentId: number; active: boolean }> {\n    const params = new URLSearchParams({ subscriber, agentId: String(agentId) })\n    return request(this.base, `/api/v1/chain/check-subscription?${params.toString()}`, undefined, this.opts.accessToken)\n  }\n\n  /** 我的中心化订阅列表（公开，按钱包地址查询链下 fiat_subscriptions）。 */\n  async mySubscriptions(subscriber: string): Promise<{ subscriptions: CentralSubscription[] }> {\n    const params = new URLSearchParams({ subscriber })\n    return request(this.base, `/api/v1/fiat/subscriptions?${params.toString()}`, undefined, this.opts.accessToken)\n  }\n\n  // ── 鉴权管理（需 accessToken 或 apiKey）────────────────────────────────\n\n  /**\n   * 发布中心化 Agent（POST /api/v1/agents/central）。owner = 鉴权主体：\n   * JWT → 注册用户钱包；租户 Key → partner-<slug>（平台自身名下，适合「平台为市场建 Agent」）。\n   * 默认附带一个月度计划（作者可在管理页调整/停用）。\n   */\n  async create(input: CreateCentralAgentInput): Promise<{ agent: CentralAgentSummary }> {\n    return request(\n      this.base,\n      '/api/v1/agents/central',\n      { method: 'POST', headers: this.authHeaders(), body: JSON.stringify(input) },\n      this.opts.accessToken\n    )\n  }\n\n  /** 我的中心化 Agent 列表（GET /api/v1/agents/central/mine，含订阅计划）。 */\n  async listMine(): Promise<{ agents: CentralAgentSummary[] }> {\n    return request(this.base, '/api/v1/agents/central/mine', { headers: this.authHeaders() }, this.opts.accessToken)\n  }\n\n  /** 更新中心化 Agent（PATCH 语义：仅更新提供的字段）。 */\n  async update(agentId: number, input: UpdateCentralAgentInput): Promise<{ agent: CentralAgentSummary }> {\n    return request(\n      this.base,\n      `/api/v1/agents/central/${agentId}`,\n      { method: 'PATCH', headers: this.authHeaders(), body: JSON.stringify(input) },\n      this.opts.accessToken\n    )\n  }\n\n  /** 下架中心化 Agent（软删除 is_active=false，订阅访问随之失效）。 */\n  async deactivate(agentId: number): Promise<{ success: boolean }> {\n    return request(this.base, `/api/v1/agents/central/${agentId}`, { method: 'DELETE', headers: this.authHeaders() }, this.opts.accessToken)\n  }\n\n  /** 上架中心化 Agent（重新启用）。 */\n  async activate(agentId: number): Promise<{ agent: CentralAgentSummary }> {\n    return this.update(agentId, { isActive: true })\n  }\n\n  /** 添加订阅计划（priceWei 为 wei 十进制字符串）。 */\n  async createPlan(agentId: number, input: CreateCentralPlanInput): Promise<{ plan: CentralPlanRow }> {\n    return request(\n      this.base,\n      `/api/v1/agents/central/${agentId}/plans`,\n      { method: 'POST', headers: this.authHeaders(), body: JSON.stringify(input) },\n      this.opts.accessToken\n    )\n  }\n\n  /** 停用订阅计划（订阅访问随之失效）。 */\n  async deactivatePlan(agentId: number, planId: number): Promise<{ success: boolean }> {\n    return request(\n      this.base,\n      `/api/v1/agents/central/${agentId}/plans/${planId}`,\n      { method: 'DELETE', headers: this.authHeaders() },\n      this.opts.accessToken\n    )\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAK,YAAY,EAAE;AAAA,MAChD,KAAK,KAAK;AAAA,IACZ;AAAA,EACF;AACF;","names":["docsPath","array","formatAbiItem","init_formatAbiItem","version","init_version","BaseError","init_version","docsPath","version","init_formatAbiItem","BaseError","size","docsPath","formatAbiItem","BaseError","size","size","BaseError","size","size","hexToBytes","bytesToHex","size","hexToBytes","BaseError","encoder","BaseError","size","hash","BaseError","init_cursor","size","bytesToHex","hexToBytes","bytesToHex","data","length","consumed","value","size","init_cursor","AgentXErrorCode","init_formatAbiItem","formatAbiItem","generateAesKey","encryptPayload","request","request","PLAN_CREATED_EVENT","SUBSCRIBED_EVENT","request","hash","request","hash","str","request","hash","hash","PaymentsClient","request","hash","request","request","ABI","node"]}