@agentxv2/sdk 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/isHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/size.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/version.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/base.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/data.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/pad.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/encoding.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/trim.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/fromHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/toHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/toBytes.ts","../src/index.ts","../src/core/types.ts","../src/core/crypto.ts","../src/registry/ipfs-fetcher.ts","../src/agent/agent-runner.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/index.ts","../src/registry/agent-registry.ts","../src/registry/index.ts","../src/subscription/subscription.ts","../src/subscription/agent-x402.ts","../src/subscription/index.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/react/useAgentRunner.ts"],"sourcesContent":["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.0'\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 { 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","// ---------------------------------------------------------------------------\n// agentx-protocol — Main Entry\n// ---------------------------------------------------------------------------\n// AgentX: Decentralized AI Agent Platform SDK\n//\n// Agent = Prompt + Skills[] + MCP\n//\n// Quick start:\n// import { AgentRunner } from 'agentx-protocol'\n//\n// const runner = new AgentRunner({ reader, wallet })\n// const ctx = await runner.useAgent(42)\n// // ctx.prompt → inject as LLM system prompt\n// // ctx.skills → inject as LLM tools\n//\n// Modules:\n// agentx-protocol/core — Types, AES-256-GCM + ECIES crypto\n// agentx-protocol/registry — Agent registration & discovery\n// agentx-protocol/subscription — Subscription purchase + AgentX402 gate\n// agentx-protocol/a2a — Agent-to-Agent protocol\n// agentx-protocol/react — React hooks (useAgent, etc.)\n// ---------------------------------------------------------------------------\n\nexport * from './core'\nexport * from './agent'\nexport * from './registry'\nexport * from './subscription'\nexport * from './a2a'\nexport * from './mcp'\nexport * from './reputation'\nexport * from './config'\nexport * from './react'\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/**\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 // ── 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 }\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 paymentGateway: `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","// ---------------------------------------------------------------------------\n// @agentx/sdk — Crypto Engine\n// ---------------------------------------------------------------------------\n// AES-256-GCM for content encryption (NIST standard, same wire format as\n// aihunter-saas for interop). 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 (same as aihunter-saas): 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 (same wire format as aihunter-saas).\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 * 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/**\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","// ---------------------------------------------------------------------------\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 — 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","// 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","// ---------------------------------------------------------------------------\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'\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} 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// ── 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 // ── 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 } from './agent-registry'\nexport type { AgentRegistryConfig } 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/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 type { PublicClient, WalletClient, Address, Hash } from 'viem'\nimport type { AgentSubscription } from '../core/types'\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 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, 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// ── 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 // ── 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 const [pid, aid, creator, price, period, active, payToken, trialDays] =\n result as [bigint, bigint, string, bigint, string, boolean, string, bigint]\n return {\n planId: Number(pid), agentId: Number(aid),\n creator: creator as Address, price, period, active,\n payToken: payToken as Address, trialDays: Number(trialDays),\n }\n }\n\n // ── Subscribe ────────────────────────────────────────────────────────────\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 async subscribe(\n planId: number,\n opts?: { valueWei?: bigint; approveTokenFirst?: boolean }\n ): Promise<{ subscriptionId: number; txHash: Hash }> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\n\n const plan = await this.getPlan(planId)\n if (!plan.active) throw new Error('Plan not active')\n\n if (plan.payToken === '0x0000000000000000000000000000000000000000') {\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)\n return { subscriptionId: 0, txHash: hash }\n } else {\n // ── ERC20 ──\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: [account, 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)\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)\n return { subscriptionId: 0, txHash: hash }\n }\n }\n\n /** Release escrowed funds to creator after trial window ends. */\n async releaseFunds(subscriptionId: number): Promise<Hash> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\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)\n }\n\n /** Cancel subscription (trial refund if within window). */\n async cancel(subscriptionId: number): Promise<Hash> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\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)\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: ['active', 'expired', 'cancelled', 'pending'][status] as AgentSubscription['status'],\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\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-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'\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 === '0x0000000000000000000000000000000000000000'\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 } from './subscription'\nexport type { SubscriptionConfig, PlanDetail, SubscriptionDetail } from './subscription'\nexport { AgentX402 } from './agent-x402'\nexport type { AgentX402Config } from './agent-x402'\nexport const SUBSCRIPTION_VERSION = '0.2.0'\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 ] 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} 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: Record<string, unknown>): Promise<{ taskId: number; txHash: Hash }> {\n const acct = await this.account\n const inputStr = 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): 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],\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 // ── 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 paymentGateway: Address\n a2aProtocolRegistry: Address\n reputationRegistry: Address\n configurationRegistry: Address\n }\n ipfsGateways: string[]\n rpcUrl?: string\n}\n\nexport const KNOWN_CHAINS: Record<number, ChainConfig> = {\n // Sepolia\n // Sepolia v2 (deployed 2026-07-13): platformFee=500bps(5%), multi-currency, trial escrow\n 11155111: {\n chainId: 11155111,\n contracts: {\n identityRegistry: '0xe94ad380d3F8d08a7590eda0C84f354a93F96e5F',\n subscriptionManager: '0xC15fE80b9d800abb72121F353a6ae6d6E9077E63',\n paymentGateway: '0x0000000000000000000000000000000000000000',\n a2aProtocolRegistry: '0x0000000000000000000000000000000000000000',\n reputationRegistry: '0x0000000000000000000000000000000000000000',\n configurationRegistry: '0x0000000000000000000000000000000000000000',\n },\n ipfsGateways: ['ipfs.io', 'gateway.pinata.cloud', 'dweb.link', 'cf-ipfs.com'],\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// @agentx/sdk — useAgentRunner React Hook\n// ---------------------------------------------------------------------------\n// Wraps AgentRunner.useAgent() for React + wagmi integration.\n//\n// const { ctx, isLoading, error } = useAgentRunner(agentId)\n// // ctx.prompt → inject into LLM\n// // ctx.skills → RunnableSkill[] with execute()\n// // ctx.mcp → MCP connection info\n// ---------------------------------------------------------------------------\n\n'use client'\n\nimport { useState, useEffect, useRef } from 'react'\nimport { usePublicClient, useWalletClient } from 'wagmi'\nimport type { Address } from 'viem'\n\nimport { AgentRunner } from '../agent/agent-runner'\nimport type { AgentRunContext, OnChainReader } from '../agent/agent-runner'\nimport { IPFSFetcher } from '../registry/ipfs-fetcher'\nimport { KNOWN_CHAINS } from '../config/config'\nimport type { ChainConfig } from '../config/config'\n\n// ── IdentityRegistry ABI (minimal — only what useAgent needs) ──────────────\n\nconst IDENTITY_REGISTRY_ABI = [\n // getAgentMetadata returns MetadataEntry[] with key+value strings\n {\n name: 'getAgentMetadata',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'agentId', type: 'uint256' }],\n outputs: [\n {\n name: '',\n type: 'tuple[]',\n components: [\n { name: 'key', type: 'string' },\n { name: 'value', type: 'bytes' },\n ],\n },\n ],\n },\n] as const\n\n// ── SubscriptionManager ABI (minimal) ─────────────────────────────────────\n\nconst SUBSCRIPTION_MANAGER_ABI = [\n {\n name: 'hasActiveSubscription',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'subscriber', type: 'address' },\n { name: 'agentId', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n] as const\n\n// ── Hook Config ────────────────────────────────────────────────────────────\n\nexport interface UseAgentRunnerConfig {\n agentId: number\n chainConfig?: ChainConfig\n ipfsGateways?: string[]\n}\n\nexport interface UseAgentRunnerResult {\n ctx: AgentRunContext | null\n isLoading: boolean\n error: Error | null\n /** Re-trigger the load (e.g. after connecting wallet or subscribing) */\n refetch: () => void\n}\n\n// ── OnChainReader Implementation (viem) ────────────────────────────────────\n\nclass ViemOnChainReader implements OnChainReader {\n constructor(\n private publicClient: ReturnType<typeof usePublicClient>,\n private chainConfig: ChainConfig\n ) {}\n\n async getTokenURI(_agentId: number): Promise<string> {\n // tokenURI is standard ERC-721 metadata — not needed for our flow\n // Metadata is fetched via getAgentMetadata\n return ''\n }\n\n async getAttributes(agentId: number): Promise<Record<string, string>> {\n if (!this.publicClient) throw new Error('Public client not available')\n\n const entries = (await this.publicClient.readContract({\n address: this.chainConfig.contracts.identityRegistry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: 'getAgentMetadata',\n args: [BigInt(agentId)],\n })) as { key: string; value: string }[]\n\n const attrs: Record<string, string> = {}\n for (const entry of entries) {\n // value is bytes — convert to string\n const hexStr = entry.value\n if (hexStr && hexStr !== '0x') {\n attrs[entry.key] = hexToStringUTF8(hexStr)\n } else {\n attrs[entry.key] = ''\n }\n }\n return attrs\n }\n\n async hasActiveSubscription(address: string, agentId: number): Promise<boolean> {\n if (!this.publicClient) return false\n\n try {\n return (await this.publicClient.readContract({\n address: this.chainConfig.contracts.subscriptionManager,\n abi: SUBSCRIPTION_MANAGER_ABI,\n functionName: 'hasActiveSubscription',\n args: [address as Address, BigInt(agentId)],\n })) as boolean\n } catch {\n return false\n }\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction hexToStringUTF8(hex: string): string {\n if (!hex.startsWith('0x')) return hex\n const hexClean = hex.slice(2)\n if (hexClean.length === 0) return ''\n try {\n const bytes = new Uint8Array(hexClean.length / 2)\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hexClean.substring(i * 2, i * 2 + 2), 16)\n }\n return new TextDecoder().decode(bytes)\n } catch {\n return hex\n }\n}\n\n// ── Hook ───────────────────────────────────────────────────────────────────\n\nexport function useAgentRunner(config: UseAgentRunnerConfig): UseAgentRunnerResult {\n const { agentId, chainConfig: chainConfigOverride, ipfsGateways } = config\n\n const publicClient = usePublicClient()\n const { data: walletClient } = useWalletClient()\n\n const [ctx, setCtx] = useState<AgentRunContext | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | null>(null)\n const [refetchKey, setRefetchKey] = useState(0)\n\n const runnerRef = useRef<AgentRunner | null>(null)\n const mountedRef = useRef(true)\n\n useEffect(() => {\n mountedRef.current = true\n return () => {\n mountedRef.current = false\n }\n }, [])\n\n useEffect(() => {\n if (!publicClient || !walletClient) {\n setError(new Error('Wallet not connected'))\n return\n }\n\n const chainConfig =\n chainConfigOverride ?? (publicClient.chain?.id ? KNOWN_CHAINS[publicClient.chain.id] : undefined)\n\n if (!chainConfig) {\n setError(new Error(`Chain ${publicClient.chain?.id} not supported`))\n return\n }\n\n // Create OnChainReader\n const reader = new ViemOnChainReader(publicClient, chainConfig)\n\n // WalletSigner from wagmi\n const signer = {\n async signMessage(message: string): Promise<string> {\n if (!walletClient.account) throw new Error('Wallet not connected')\n return walletClient.signMessage({ account: walletClient.account, message })\n },\n async getAddress(): Promise<string> {\n if (!walletClient.account) throw new Error('Wallet not connected')\n return walletClient.account.address\n },\n async getPrivateKey(): Promise<string> {\n // wagmi walletClient doesn't expose private key\n // ECIES decryption requires private key — must be injected from wallet provider\n throw new Error(\n 'Private key not available via wagmi. ' +\n 'Use window.ethereum.request({ method: \"eth_private_key\" }) or inject getPrivateKey via custom WalletSigner.'\n )\n },\n }\n\n // IPFS Fetcher\n const ipfsFetcher = new IPFSFetcher({\n fallbackGateways: ipfsGateways ?? chainConfig.ipfsGateways ?? [\n 'gateway.pinata.cloud',\n 'dweb.link',\n 'cf-ipfs.com',\n ],\n })\n\n runnerRef.current = new AgentRunner({\n reader,\n wallet: signer,\n ipfsFetcher,\n })\n\n setIsLoading(true)\n setError(null)\n\n runnerRef.current\n .useAgent(agentId)\n .then(result => {\n if (mountedRef.current) {\n setCtx(result)\n setIsLoading(false)\n }\n })\n .catch(err => {\n if (mountedRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)))\n setIsLoading(false)\n }\n })\n\n return () => {\n mountedRef.current = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, publicClient?.chain?.id, publicClient, walletClient, refetchKey])\n\n const refetch = () => setRefetchKey(k => k + 1)\n\n return { ctx, isLoading, error, refetch }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKM,SAAU,MACd,OACA,EAAE,SAAS,KAAI,IAAuC,CAAA,GAAE;AAExD,MAAI,CAAC;AAAO,WAAO;AACnB,MAAI,OAAO,UAAU;AAAU,WAAO;AACtC,SAAO,SAAS,mBAAmB,KAAK,KAAK,IAAI,MAAM,WAAW,IAAI;AACxE;AAPA;;;;;;;ACQM,SAAU,KAAK,OAAsB;AACzC,MAAI,MAAM,OAAO,EAAE,QAAQ,MAAK,CAAE;AAAG,WAAO,KAAK,MAAM,MAAM,SAAS,KAAK,CAAC;AAC5E,SAAO,MAAM;AACf;AAbA;;;;;;;;ACHA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACoFvB,SAAS,KACP,KACA,IAA4C;AAE5C,MAAI,KAAK,GAAG;AAAG,WAAO;A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ytesToHex","hexToBytes","AgentXErrorCode","IDENTITY_REGISTRY_ABI"]}
1
+ {"version":3,"sources":["../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/isHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/size.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/version.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/base.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/data.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/pad.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/errors/encoding.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/data/trim.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/fromHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/toHex.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/utils/encoding/toBytes.ts","../src/index.ts","../src/core/types.ts","../src/core/crypto.ts","../src/registry/ipfs-fetcher.ts","../src/agent/agent-runner.ts","../node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/index.ts","../src/registry/agent-registry.ts","../src/registry/index.ts","../src/subscription/subscription.ts","../src/subscription/agent-x402.ts","../src/subscription/index.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/react/useAgentRunner.ts"],"sourcesContent":["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.0'\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 { 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","// ---------------------------------------------------------------------------\n// agentx-protocol — Main Entry\n// ---------------------------------------------------------------------------\n// AgentX: Decentralized AI Agent Platform SDK\n//\n// Agent = Prompt + Skills[] + MCP\n//\n// Quick start:\n// import { AgentRunner } from 'agentx-protocol'\n//\n// const runner = new AgentRunner({ reader, wallet })\n// const ctx = await runner.useAgent(42)\n// // ctx.prompt → inject as LLM system prompt\n// // ctx.skills → inject as LLM tools\n//\n// Modules:\n// agentx-protocol/core — Types, AES-256-GCM + ECIES crypto\n// agentx-protocol/registry — Agent registration & discovery\n// agentx-protocol/subscription — Subscription purchase + AgentX402 gate\n// agentx-protocol/a2a — Agent-to-Agent protocol\n// agentx-protocol/react — React hooks (useAgent, etc.)\n// ---------------------------------------------------------------------------\n\nexport * from './core'\nexport * from './agent'\nexport * from './registry'\nexport * from './subscription'\nexport * from './a2a'\nexport * from './mcp'\nexport * from './reputation'\nexport * from './config'\nexport * from './react'\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/**\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 // ── 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 }\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 paymentGateway: `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","// ---------------------------------------------------------------------------\n// @agentx/sdk — Crypto Engine\n// ---------------------------------------------------------------------------\n// AES-256-GCM for content encryption (NIST standard, same wire format as\n// aihunter-saas for interop). 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 (same as aihunter-saas): 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 (same wire format as aihunter-saas).\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 * 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/**\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","// ---------------------------------------------------------------------------\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 — 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","// 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","// ---------------------------------------------------------------------------\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'\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} 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// ── 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 // ── 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 } from './agent-registry'\nexport type { AgentRegistryConfig } 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/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 type { PublicClient, WalletClient, Address, Hash } from 'viem'\nimport type { AgentSubscription } from '../core/types'\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 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, 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// ── 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 // ── 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 const [pid, aid, creator, price, period, active, payToken, trialDays] =\n result as [bigint, bigint, string, bigint, string, boolean, string, bigint]\n return {\n planId: Number(pid), agentId: Number(aid),\n creator: creator as Address, price, period, active,\n payToken: payToken as Address, trialDays: Number(trialDays),\n }\n }\n\n // ── Subscribe ────────────────────────────────────────────────────────────\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 async subscribe(\n planId: number,\n opts?: { valueWei?: bigint; approveTokenFirst?: boolean }\n ): Promise<{ subscriptionId: number; txHash: Hash }> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\n\n const plan = await this.getPlan(planId)\n if (!plan.active) throw new Error('Plan not active')\n\n if (plan.payToken === '0x0000000000000000000000000000000000000000') {\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)\n return { subscriptionId: 0, txHash: hash }\n } else {\n // ── ERC20 ──\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: [account, 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)\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)\n return { subscriptionId: 0, txHash: hash }\n }\n }\n\n /** Release escrowed funds to creator after trial window ends. */\n async releaseFunds(subscriptionId: number): Promise<Hash> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\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)\n }\n\n /** Cancel subscription (trial refund if within window). */\n async cancel(subscriptionId: number): Promise<Hash> {\n const [account] = await this.walletClient.getAddresses()\n if (!account) throw new Error('Wallet not connected')\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)\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: ['active', 'expired', 'cancelled', 'pending'][status] as AgentSubscription['status'],\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\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-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'\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 === '0x0000000000000000000000000000000000000000'\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 } from './subscription'\nexport type { SubscriptionConfig, PlanDetail, SubscriptionDetail } from './subscription'\nexport { AgentX402 } from './agent-x402'\nexport type { AgentX402Config } from './agent-x402'\nexport const SUBSCRIPTION_VERSION = '0.2.0'\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 ] 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} 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: Record<string, unknown>): Promise<{ taskId: number; txHash: Hash }> {\n const acct = await this.account\n const inputStr = 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): 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],\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 // ── 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 paymentGateway: Address\n a2aProtocolRegistry: Address\n reputationRegistry: Address\n configurationRegistry: 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 paymentGateway: '0x59eA58c0089314C0fCc86A4ff646fb6dAE571C96',\n a2aProtocolRegistry: '0xEdb0022c250B38e281B3EF1418037889fC5C6092',\n reputationRegistry: '0xeb6B410ea71b8d9dA0c96f6A91d35027CE143DC9',\n configurationRegistry: '0x68DcE00e4C9077c94BC68016cD14B09557faEA6c',\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 T0x\n // Deployer: 0x8E869A0624fF9e766Df71b5B08897d00E4d260ba\n // RPC: http://43.156.99.215:18545\n // Explorer: http://43.156.99.215:18400\n // All 6 core contracts deployed 2026-07-14\n 19505: {\n chainId: 19505,\n contracts: {\n identityRegistry: '0xbf5F9db266c8c97E3334466C88597Eb758AfE212',\n subscriptionManager: '0x019AC9d945467478Dd371CDbD70cb2f325800E6B',\n paymentGateway: '0x0000000000000000000000000000000000000000',\n a2aProtocolRegistry: '0x61b7E7Eed21F013e35a90FC5de5c352780ec5169',\n reputationRegistry: '0x6a18C2664E1b42063860d864b6448b824d7B843F',\n configurationRegistry: '0x07280674ccc2898Fd038A9e3C22005CA83ffD2F8',\n },\n ipfsGateways: ['ipfs.io', 'gateway.pinata.cloud', 'dweb.link', 'cf-ipfs.com'],\n rpcUrl: 'http://43.156.99.215:18545',\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// @agentx/sdk — useAgentRunner React Hook\n// ---------------------------------------------------------------------------\n// Wraps AgentRunner.useAgent() for React + wagmi integration.\n//\n// const { ctx, isLoading, error } = useAgentRunner(agentId)\n// // ctx.prompt → inject into LLM\n// // ctx.skills → RunnableSkill[] with execute()\n// // ctx.mcp → MCP connection info\n// ---------------------------------------------------------------------------\n\n'use client'\n\nimport { useState, useEffect, useRef } from 'react'\nimport { usePublicClient, useWalletClient } from 'wagmi'\nimport type { Address } from 'viem'\n\nimport { AgentRunner } from '../agent/agent-runner'\nimport type { AgentRunContext, OnChainReader } from '../agent/agent-runner'\nimport { IPFSFetcher } from '../registry/ipfs-fetcher'\nimport { KNOWN_CHAINS } from '../config/config'\nimport type { ChainConfig } from '../config/config'\n\n// ── IdentityRegistry ABI (minimal — only what useAgent needs) ──────────────\n\nconst IDENTITY_REGISTRY_ABI = [\n // getAgentMetadata returns MetadataEntry[] with key+value strings\n {\n name: 'getAgentMetadata',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'agentId', type: 'uint256' }],\n outputs: [\n {\n name: '',\n type: 'tuple[]',\n components: [\n { name: 'key', type: 'string' },\n { name: 'value', type: 'bytes' },\n ],\n },\n ],\n },\n] as const\n\n// ── SubscriptionManager ABI (minimal) ─────────────────────────────────────\n\nconst SUBSCRIPTION_MANAGER_ABI = [\n {\n name: 'hasActiveSubscription',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'subscriber', type: 'address' },\n { name: 'agentId', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n] as const\n\n// ── Hook Config ────────────────────────────────────────────────────────────\n\nexport interface UseAgentRunnerConfig {\n agentId: number\n chainConfig?: ChainConfig\n ipfsGateways?: string[]\n}\n\nexport interface UseAgentRunnerResult {\n ctx: AgentRunContext | null\n isLoading: boolean\n error: Error | null\n /** Re-trigger the load (e.g. after connecting wallet or subscribing) */\n refetch: () => void\n}\n\n// ── OnChainReader Implementation (viem) ────────────────────────────────────\n\nclass ViemOnChainReader implements OnChainReader {\n constructor(\n private publicClient: ReturnType<typeof usePublicClient>,\n private chainConfig: ChainConfig\n ) {}\n\n async getTokenURI(_agentId: number): Promise<string> {\n // tokenURI is standard ERC-721 metadata — not needed for our flow\n // Metadata is fetched via getAgentMetadata\n return ''\n }\n\n async getAttributes(agentId: number): Promise<Record<string, string>> {\n if (!this.publicClient) throw new Error('Public client not available')\n\n const entries = (await this.publicClient.readContract({\n address: this.chainConfig.contracts.identityRegistry,\n abi: IDENTITY_REGISTRY_ABI,\n functionName: 'getAgentMetadata',\n args: [BigInt(agentId)],\n })) as { key: string; value: string }[]\n\n const attrs: Record<string, string> = {}\n for (const entry of entries) {\n // value is bytes — convert to string\n const hexStr = entry.value\n if (hexStr && hexStr !== '0x') {\n attrs[entry.key] = hexToStringUTF8(hexStr)\n } else {\n attrs[entry.key] = ''\n }\n }\n return attrs\n }\n\n async hasActiveSubscription(address: string, agentId: number): Promise<boolean> {\n if (!this.publicClient) return false\n\n try {\n return (await this.publicClient.readContract({\n address: this.chainConfig.contracts.subscriptionManager,\n abi: SUBSCRIPTION_MANAGER_ABI,\n functionName: 'hasActiveSubscription',\n args: [address as Address, BigInt(agentId)],\n })) as boolean\n } catch {\n return false\n }\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction hexToStringUTF8(hex: string): string {\n if (!hex.startsWith('0x')) return hex\n const hexClean = hex.slice(2)\n if (hexClean.length === 0) return ''\n try {\n const bytes = new Uint8Array(hexClean.length / 2)\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hexClean.substring(i * 2, i * 2 + 2), 16)\n }\n return new TextDecoder().decode(bytes)\n } catch {\n return hex\n }\n}\n\n// ── Hook ───────────────────────────────────────────────────────────────────\n\nexport function useAgentRunner(config: UseAgentRunnerConfig): UseAgentRunnerResult {\n const { agentId, chainConfig: chainConfigOverride, ipfsGateways } = config\n\n const publicClient = usePublicClient()\n const { data: walletClient } = useWalletClient()\n\n const [ctx, setCtx] = useState<AgentRunContext | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | null>(null)\n const [refetchKey, setRefetchKey] = useState(0)\n\n const runnerRef = useRef<AgentRunner | null>(null)\n const mountedRef = useRef(true)\n\n useEffect(() => {\n mountedRef.current = true\n return () => {\n mountedRef.current = false\n }\n }, [])\n\n useEffect(() => {\n if (!publicClient || !walletClient) {\n setError(new Error('Wallet not connected'))\n return\n }\n\n const chainConfig =\n chainConfigOverride ?? (publicClient.chain?.id ? KNOWN_CHAINS[publicClient.chain.id] : undefined)\n\n if (!chainConfig) {\n setError(new Error(`Chain ${publicClient.chain?.id} not supported`))\n return\n }\n\n // Create OnChainReader\n const reader = new ViemOnChainReader(publicClient, chainConfig)\n\n // WalletSigner from wagmi\n const signer = {\n async signMessage(message: string): Promise<string> {\n if (!walletClient.account) throw new Error('Wallet not connected')\n return walletClient.signMessage({ account: walletClient.account, message })\n },\n async getAddress(): Promise<string> {\n if (!walletClient.account) throw new Error('Wallet not connected')\n return walletClient.account.address\n },\n async getPrivateKey(): Promise<string> {\n // wagmi walletClient doesn't expose private key\n // ECIES decryption requires private key — must be injected from wallet provider\n throw new Error(\n 'Private key not available via wagmi. ' +\n 'Use window.ethereum.request({ method: \"eth_private_key\" }) or inject getPrivateKey via custom WalletSigner.'\n )\n },\n }\n\n // IPFS Fetcher\n const ipfsFetcher = new IPFSFetcher({\n fallbackGateways: ipfsGateways ?? chainConfig.ipfsGateways ?? [\n 'gateway.pinata.cloud',\n 'dweb.link',\n 'cf-ipfs.com',\n ],\n })\n\n runnerRef.current = new AgentRunner({\n reader,\n wallet: signer,\n ipfsFetcher,\n })\n\n setIsLoading(true)\n setError(null)\n\n runnerRef.current\n .useAgent(agentId)\n .then(result => {\n if (mountedRef.current) {\n setCtx(result)\n setIsLoading(false)\n }\n })\n .catch(err => {\n if (mountedRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)))\n setIsLoading(false)\n }\n })\n\n return () => {\n mountedRef.current = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, publicClient?.chain?.id, publicClient, walletClient, refetchKey])\n\n const refetch =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