@monolythium/core-sdk 0.2.0 → 0.2.2
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/crypto/index.cjs.map +1 -1
- package/dist/crypto/index.d.cts +3 -3
- package/dist/crypto/index.d.ts +3 -3
- package/dist/crypto/index.js.map +1 -1
- package/dist/ethers/index.cjs +58 -5
- package/dist/ethers/index.cjs.map +1 -1
- package/dist/ethers/index.d.cts +1 -1
- package/dist/ethers/index.d.ts +1 -1
- package/dist/ethers/index.js +58 -5
- package/dist/ethers/index.js.map +1 -1
- package/dist/index.cjs +183 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -22
- package/dist/index.d.ts +40 -22
- package/dist/index.js +181 -33
- package/dist/index.js.map +1 -1
- package/dist/{native-events-BEkkGoak.d.cts → native-events-CA0yrnj-.d.cts} +33 -16
- package/dist/{native-events-BEkkGoak.d.ts → native-events-CA0yrnj-.d.ts} +33 -16
- package/dist/{submission-BrsftNSl.d.cts → submission-AOqfeSIS.d.cts} +1 -1
- package/dist/{submission-CelGfDRQ.d.ts → submission-msoZzFIa.d.ts} +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/address.ts","../../src/error.ts","../../src/native-events.ts","../../src/node-registry.ts","../../src/crypto/ml-dsa.ts","../../src/crypto/envelope.ts","../../src/mrv.ts","../../src/registry.ts","../../src/types.ts","../../src/client.ts","../../src/ethers/network.ts","../../src/ethers/provider.ts","../../src/ethers/signer.ts","../../src/ethers/tx-translate.ts"],"names":["JsonRpcApiProvider","Network","AbstractSigner"],"mappings":";;;;;;;;;;;;;AAQO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,IAAA,EAAM,MAAA;AAAA,EACN,YAAA,EAAc,OAAA;AAAA,EACd,QAAA,EAAU,OAAA;AAAA,EACV,OAAA,EAAS,OAAA;AAAA,EACT,QAAA,EAAU,OAAA;AAAA,EACV,Y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CAAmB,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IACpD,UAAU,CAAA,EAAA,EAAK,MAAA,CAAO,kBAAA,CAAmB,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IACrD,WAAW,MAAA,CAAO,UAAA;AAAA,IAClB,KAAA,EAAO,4CAAA;AAAA,IACP,UAAA,EAAY,KAAA;AAAA,IACZ,KAAA,EAAO,oBAAA;AAAA,IACP,aAAA,EAAe,IAAA;AAAA,IACf,SAAA,EAAW,IAAA;AAAA,IACX,OAAA,EAAS,oEAAA;AAAA,IACT,cAAc,EAAC;AAAA,IACf,gBAAA,EAAkB,oEAAA;AAAA,IAClB,YAAA,EAAc,oEAAA;AAAA,IACd,SAAA,EAAW,CAAA,EAAA,EAAK,GAAA,CAAI,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA;AAAA,IAC/B,UAAA,EAAY,oEAAA;AAAA,IACZ,QAAQ,EAAC;AAAA,IACT,IAAA,EAAM;AAAA,GACR;AACF","file":"index.cjs","sourcesContent":["/**\n * Address display helpers.\n *\n * Monolythium keeps 20-byte account identifiers on the wire, but\n * user-facing surfaces display them as `mono1...` bech32m strings.\n */\n\nexport const ADDRESS_HRP = \"mono\" as const;\nexport const ADDRESS_KIND_HRPS = {\n user: \"mono\",\n smartAccount: \"monos\",\n contract: \"monoc\",\n cluster: \"monok\",\n multisig: \"monom\",\n systemModule: \"monox\",\n} as const;\nexport const RESERVED_ADDRESS_HRPS = [\"monor\", \"monop\", \"monoi\", \"monoa\"] as const;\n\nexport type AddressKind = keyof typeof ADDRESS_KIND_HRPS;\n\nexport interface TypedAddress {\n kind: AddressKind;\n address: string;\n bytes: Uint8Array;\n hex: string;\n}\n\nconst CHARSET = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\nconst CHARSET_MAP = new Map([...CHARSET].map((c, i) => [c, i]));\nconst BECH32M_CONST = 0x2bc830a3;\nconst HEX_20_BYTE_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport class AddressError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AddressError\";\n }\n}\n\nexport function hexToAddressBytes(address: string): Uint8Array {\n if (!HEX_20_BYTE_RE.test(address)) {\n throw new AddressError(\"expected 0x-prefixed 20-byte hex address\");\n }\n const out = new Uint8Array(20);\n const body = address.slice(2);\n for (let i = 0; i < 20; i++) {\n out[i] = Number.parseInt(body.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nexport function addressBytesToHex(address: Uint8Array | readonly number[]): string {\n const bytes = expectLength(address, 20, \"address\");\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nexport function addressToBech32(address: string | Uint8Array | readonly number[]): string {\n return addressToTypedBech32(\"user\", address);\n}\n\nexport function addressToTypedBech32(\n kind: AddressKind,\n address: string | Uint8Array | readonly number[],\n): string {\n const bytes = typeof address === \"string\" ? hexToAddressBytes(address) : expectLength(address, 20, \"address\");\n return encodeBech32m(ADDRESS_KIND_HRPS[kind], bytes);\n}\n\nfunction encodeBech32m(hrp: string, bytes: Uint8Array): string {\n const words = convertBits([...bytes], 8, 5, true);\n const checksum = createChecksum(hrp, words);\n return `${hrp}1${[...words, ...checksum].map((v) => CHARSET[v]).join(\"\")}`;\n}\n\nexport function bech32ToAddressBytes(address: string): Uint8Array {\n return typedBech32ToAddress(address, \"user\").bytes;\n}\n\nexport function bech32ToAddress(address: string): string {\n return addressBytesToHex(bech32ToAddressBytes(address));\n}\n\nexport function typedBech32ToAddress(address: string, expectedKind?: AddressKind): TypedAddress {\n const parsed = decodeBech32m(address);\n if ((RESERVED_ADDRESS_HRPS as readonly string[]).includes(parsed.hrp)) {\n throw new AddressError(`reserved address hrp '${parsed.hrp}'`);\n }\n const kind = addressKindFromHrp(parsed.hrp);\n if (kind === undefined) {\n throw new AddressError(`unknown address hrp '${parsed.hrp}'`);\n }\n if (expectedKind !== undefined && kind !== expectedKind) {\n throw new AddressError(`unexpected hrp '${parsed.hrp}', expected '${ADDRESS_KIND_HRPS[expectedKind]}'`);\n }\n const bytes = convertBits(parsed.data, 5, 8, false);\n if (bytes.length !== 20) {\n throw new AddressError(`expected 20-byte payload, got ${bytes.length} bytes`);\n }\n const out = Uint8Array.from(bytes);\n return { kind, address: address.toLowerCase(), bytes: out, hex: addressBytesToHex(out) };\n}\n\nexport function requireTypedAddress(\n address: string,\n expectedKind: AddressKind,\n label = \"address\",\n): string {\n if (address.startsWith(\"0x\") || address.startsWith(\"0X\")) {\n throw new AddressError(\n `${label} raw 0x addresses are retired; use typed ${ADDRESS_KIND_HRPS[expectedKind]} bech32m addresses`,\n );\n }\n try {\n return typedBech32ToAddress(address, expectedKind).address;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new AddressError(\n `${label} must be typed ${ADDRESS_KIND_HRPS[expectedKind]} bech32m address: ${message}`,\n );\n }\n}\n\nexport function parseAddress(address: string): Uint8Array {\n if (address.startsWith(\"0x\") || address.startsWith(\"0X\")) {\n return hexToAddressBytes(address);\n }\n return bech32ToAddressBytes(address);\n}\n\nexport function normalizeAddressHex(address: string): string {\n return addressBytesToHex(parseAddress(address));\n}\n\nfunction decodeBech32m(input: string): { hrp: string; data: number[] } {\n if (input.length < 8) {\n throw new AddressError(\"bech32m address is too short\");\n }\n const hasLower = input !== input.toUpperCase();\n const hasUpper = input !== input.toLowerCase();\n if (hasLower && hasUpper) {\n throw new AddressError(\"bech32m address cannot mix upper and lower case\");\n }\n const s = input.toLowerCase();\n const sep = s.lastIndexOf(\"1\");\n if (sep <= 0 || sep + 7 > s.length) {\n throw new AddressError(\"bech32m separator/checksum shape is invalid\");\n }\n const hrp = s.slice(0, sep);\n const values: number[] = [];\n for (const c of s.slice(sep + 1)) {\n const v = CHARSET_MAP.get(c);\n if (v === undefined) {\n throw new AddressError(`invalid bech32m character '${c}'`);\n }\n values.push(v);\n }\n if (!verifyChecksum(hrp, values)) {\n throw new AddressError(\"bech32m checksum mismatch\");\n }\n return { hrp, data: values.slice(0, -6) };\n}\n\nfunction addressKindFromHrp(hrp: string): AddressKind | undefined {\n for (const [kind, kindHrp] of Object.entries(ADDRESS_KIND_HRPS) as Array<[AddressKind, string]>) {\n if (kindHrp === hrp) return kind;\n }\n return undefined;\n}\n\nfunction hrpExpand(hrp: string): number[] {\n const high = [...hrp].map((c) => c.charCodeAt(0) >> 5);\n const low = [...hrp].map((c) => c.charCodeAt(0) & 31);\n return [...high, 0, ...low];\n}\n\nfunction polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if (((top >> i) & 1) === 1) {\n chk ^= generators[i];\n }\n }\n }\n return chk >>> 0;\n}\n\nfunction createChecksum(hrp: string, data: number[]): number[] {\n const values = [...hrpExpand(hrp), ...data, 0, 0, 0, 0, 0, 0];\n const mod = polymod(values) ^ BECH32M_CONST;\n const out: number[] = [];\n for (let p = 0; p < 6; p++) {\n out.push((mod >> (5 * (5 - p))) & 31);\n }\n return out;\n}\n\nfunction verifyChecksum(hrp: string, values: number[]): boolean {\n return polymod([...hrpExpand(hrp), ...values]) === BECH32M_CONST;\n}\n\nfunction convertBits(data: readonly number[], fromBits: number, toBits: number, pad: boolean): number[] {\n let acc = 0;\n let bits = 0;\n const ret: number[] = [];\n const maxv = (1 << toBits) - 1;\n const maxAcc = (1 << (fromBits + toBits - 1)) - 1;\n for (const value of data) {\n if (value < 0 || value >> fromBits !== 0) {\n throw new AddressError(\"invalid address payload value\");\n }\n acc = ((acc << fromBits) | value) & maxAcc;\n bits += fromBits;\n while (bits >= toBits) {\n bits -= toBits;\n ret.push((acc >> bits) & maxv);\n }\n }\n if (pad) {\n if (bits > 0) {\n ret.push((acc << (toBits - bits)) & maxv);\n }\n } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) !== 0) {\n throw new AddressError(\"invalid bech32m padding\");\n }\n return ret;\n}\n\nfunction expectLength(value: Uint8Array | readonly number[], len: number, name: string): Uint8Array {\n if (value.length !== len) {\n throw new AddressError(`${name} must be ${len} bytes`);\n }\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n","/**\n * Error surfaced by `RpcClient`. Distinguishes transport failures\n * (HTTP errors, network), protocol errors (JSON-RPC `error` envelopes),\n * and shape mismatches.\n */\nexport class SdkError extends Error {\n public readonly kind: \"transport\" | \"rpc\" | \"malformed\" | \"endpoint\";\n public readonly code?: number;\n public readonly data?: unknown;\n\n constructor(\n kind: \"transport\" | \"rpc\" | \"malformed\" | \"endpoint\",\n message: string,\n opts?: { code?: number; data?: unknown; cause?: unknown },\n ) {\n super(message, opts?.cause ? { cause: opts.cause } : undefined);\n this.name = \"SdkError\";\n this.kind = kind;\n this.code = opts?.code;\n this.data = opts?.data;\n }\n\n static transport(message: string, cause?: unknown): SdkError {\n return new SdkError(\"transport\", message, { cause });\n }\n static rpc(code: number, message: string, data?: unknown): SdkError {\n return new SdkError(\"rpc\", `rpc error ${code}: ${message}`, { code, data });\n }\n static malformed(message: string): SdkError {\n return new SdkError(\"malformed\", message);\n }\n static endpoint(message: string): SdkError {\n return new SdkError(\"endpoint\", message);\n }\n}\n","import { SdkError } from \"./error.js\";\nimport type {\n NativeEventsResponse,\n NativeReceiptEvent,\n NativeReceiptResponse,\n} from \"./client.js\";\n\n/** Common typed payload envelope emitted by the native event projector. */\nexport interface NativeDecodedEvent {\n block_height: number;\n tx_index: number;\n sequence: number;\n family: string;\n event_name: string;\n nonce?: number | null;\n market_surface?: string | null;\n marketSurface?: string | null;\n market_asset_id?: string | null;\n marketAssetId?: string | null;\n market_related_asset_id?: string | null;\n marketRelatedAssetId?: string | null;\n market_order_id?: string | null;\n marketOrderId?: string | null;\n market_related_order_id?: string | null;\n marketRelatedOrderId?: string | null;\n price?: string | null;\n quantity?: string | null;\n remaining?: string | null;\n side?: string | null;\n status?: string | null;\n nft_standard?: string | null;\n nftStandard?: string | null;\n policy?: NativeMrcPolicyProjection | null;\n royalty_bps?: number | null;\n royaltyBps?: number | null;\n listing_kind?: unknown;\n listingKind?: unknown;\n expires_at_block?: number | null;\n expiresAtBlock?: number | null;\n tick_size?: string | null;\n tickSize?: string | null;\n lot_size?: string | null;\n lotSize?: string | null;\n min_quantity?: string | null;\n minQuantity?: string | null;\n min_notional?: string | null;\n minNotional?: string | null;\n payload_hash: string;\n [field: string]: unknown;\n}\n\n/** Canonical policy body projected from native MRC policy-account events. */\nexport interface NativeMrcPolicyProjection {\n enabled: boolean;\n per_action_limit: string | number;\n window_limit: string | number;\n allowed_assets: Array<string | Array<number>>;\n}\n\nexport type NativeEventProjection = NativeDecodedEvent;\n\nexport const NATIVE_MARKET_EVENT_FAMILY = \"market\" as const;\n\n/** Optional filters applied to native receipt event rows. */\nexport interface NativeEventFilter {\n address?: string;\n eventTopic?: string;\n family?: string;\n eventName?: string;\n}\n\nexport function nativeMarketEventFilter(filter: NativeEventFilter = {}): NativeEventFilter {\n return { ...filter, family: NATIVE_MARKET_EVENT_FAMILY };\n}\n\nexport type TypedNativeReceiptEvent<TDecoded extends NativeDecodedEvent = NativeDecodedEvent> =\n NativeReceiptEvent<TDecoded>;\n\nexport type NativeEventConsumer<TDecoded extends NativeDecodedEvent = NativeDecodedEvent> = (\n event: TypedNativeReceiptEvent<TDecoded>,\n) => void | Promise<void>;\n\nexport function isNativeDecodedEvent(value: unknown): value is NativeDecodedEvent {\n const row = asRecord(value);\n return (\n row !== null &&\n typeof row[\"block_height\"] === \"number\" &&\n typeof row[\"tx_index\"] === \"number\" &&\n typeof row[\"sequence\"] === \"number\" &&\n typeof row[\"family\"] === \"string\" &&\n typeof row[\"event_name\"] === \"string\" &&\n typeof row[\"payload_hash\"] === \"string\"\n );\n}\n\nexport function parseNativeDecodedEvent<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n event: Pick<NativeReceiptEvent<unknown>, \"decoded\" | \"decodedJson\" | \"eventTopic\" | \"logIndex\">,\n): TDecoded {\n if (isNativeDecodedEvent(event.decoded)) {\n return event.decoded as TDecoded;\n }\n\n try {\n const parsed = JSON.parse(event.decodedJson) as unknown;\n if (isNativeDecodedEvent(parsed)) {\n return parsed as TDecoded;\n }\n } catch {\n // Fall through to the shape error below.\n }\n\n throw SdkError.malformed(\n `native event ${event.eventTopic} at logIndex ${event.logIndex} is missing a typed decoded payload`,\n );\n}\n\nexport function nativeEventMatches(\n event: NativeReceiptEvent<unknown>,\n filter: NativeEventFilter = {},\n): boolean {\n if (filter.address !== undefined && event.address !== filter.address) return false;\n if (filter.eventTopic !== undefined && event.eventTopic !== filter.eventTopic) return false;\n\n if (filter.family === undefined && filter.eventName === undefined) return true;\n\n let decoded: NativeDecodedEvent;\n try {\n decoded = parseNativeDecodedEvent(event);\n } catch {\n return false;\n }\n if (filter.family !== undefined && decoded.family !== filter.family) return false;\n if (filter.eventName !== undefined && decoded.event_name !== filter.eventName) return false;\n return true;\n}\n\nexport function nativeEventsFromReceipt<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n filter: NativeEventFilter = {},\n): Array<TypedNativeReceiptEvent<TDecoded>> {\n return receipt.events\n .filter((event) => nativeEventMatches(event, filter))\n .map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n }));\n}\n\nexport function nativeMarketEventsFromReceipt<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n filter: NativeEventFilter = {},\n): Array<TypedNativeReceiptEvent<TDecoded>> {\n return nativeEventsFromReceipt<TDecoded>(receipt, nativeMarketEventFilter(filter));\n}\n\nexport function nativeEventsFromHistory<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(response: NativeEventsResponse<unknown>): NativeEventsResponse<TDecoded> {\n return {\n ...response,\n events: response.events.map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n })),\n };\n}\n\nexport function nativeMarketEventsFromHistory<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(response: NativeEventsResponse<unknown>): NativeEventsResponse<TDecoded> {\n return {\n ...response,\n filters: { ...response.filters, family: NATIVE_MARKET_EVENT_FAMILY },\n events: response.events\n .filter((event) => nativeEventMatches(event, { family: NATIVE_MARKET_EVENT_FAMILY }))\n .map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n })),\n };\n}\n\nexport async function consumeNativeEvents<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n consumer: NativeEventConsumer<TDecoded>,\n filter: NativeEventFilter = {},\n): Promise<number> {\n const events = nativeEventsFromReceipt<TDecoded>(receipt, filter);\n for (const event of events) {\n await consumer(event);\n }\n return events.length;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n}\n","/**\n * Node-registry precompile ABI helpers and service capability constants.\n *\n * These constants mirror `protocore-node-registry::capabilities` and\n * `protocore-node-registry::abi`. They are exported for wallets,\n * service probers, faucets, and operator dashboards that need to build\n * canonical registry transactions without retyping low-level values.\n */\n\nimport { PRECOMPILE_ADDRESSES } from \"./consts.js\";\n\nexport const NODE_REGISTRY_CAPABILITIES = {\n SERVES_RPC: 0x0000_0001,\n SERVES_INDEXER: 0x0000_0002,\n SERVES_BROADCASTER: 0x0000_0004,\n SERVES_ARCHIVE: 0x0000_0008,\n SERVES_WEBSOCKET: 0x0000_0010,\n SERVES_LIGHT_CLIENT: 0x0000_0020,\n SERVES_ORACLE_WRITER: 0x0000_0040,\n SERVES_BRIDGE_RELAY: 0x0000_0080,\n SERVES_PUBLIC_API: 0x0000_0100,\n} as const;\n\nexport const NODE_REGISTRY_CAPABILITY_MASK = 0x0000_ffff;\n\nexport const NODE_REGISTRY_PUBLIC_SERVICE_MASK =\n NODE_REGISTRY_CAPABILITIES.SERVES_RPC |\n NODE_REGISTRY_CAPABILITIES.SERVES_INDEXER |\n NODE_REGISTRY_CAPABILITIES.SERVES_ARCHIVE |\n NODE_REGISTRY_CAPABILITIES.SERVES_WEBSOCKET |\n NODE_REGISTRY_CAPABILITIES.SERVES_PUBLIC_API;\n\nexport const SERVICE_PROBE_STATUS = {\n UNKNOWN: 0,\n REACHABLE: 1,\n DEGRADED: 2,\n UNREACHABLE: 3,\n} as const;\n\nexport const NODE_REGISTRY_SELECTORS = {\n reportServiceProbe: \"0xeee31bba\",\n getServiceProbe: \"0x1fcbfbce\",\n} as const;\n\nexport interface ReportServiceProbeCalldataArgs {\n peerId: string | Uint8Array | readonly number[];\n serviceMask: number;\n status: number;\n latencyMs: number;\n probeDigest: string | Uint8Array | readonly number[];\n}\n\nexport class NodeRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NodeRegistryError\";\n }\n}\n\nexport function nodeRegistryAddressHex(): string {\n return PRECOMPILE_ADDRESSES.NODE_REGISTRY.toLowerCase();\n}\n\nexport function isValidNodeRegistryCapabilities(flags: number): boolean {\n return Number.isInteger(flags) && flags >= 0 && (flags & ~NODE_REGISTRY_CAPABILITY_MASK) === 0;\n}\n\nexport function isValidPublicServiceProbeMask(mask: number): boolean {\n return (\n Number.isInteger(mask) &&\n mask > 0 &&\n (mask & ~NODE_REGISTRY_PUBLIC_SERVICE_MASK) === 0\n );\n}\n\nexport function isSinglePublicServiceProbeMask(mask: number): boolean {\n return isValidPublicServiceProbeMask(mask) && bitCount(mask) === 1;\n}\n\nexport function isConcreteServiceProbeStatus(status: number): boolean {\n return (\n status === SERVICE_PROBE_STATUS.REACHABLE ||\n status === SERVICE_PROBE_STATUS.DEGRADED ||\n status === SERVICE_PROBE_STATUS.UNREACHABLE\n );\n}\n\nexport function serviceProbeStatusLabel(status: number): string {\n switch (status) {\n case SERVICE_PROBE_STATUS.REACHABLE:\n return \"reachable\";\n case SERVICE_PROBE_STATUS.DEGRADED:\n return \"degraded\";\n case SERVICE_PROBE_STATUS.UNREACHABLE:\n return \"unreachable\";\n default:\n return \"unknown\";\n }\n}\n\nexport function encodeReportServiceProbeCalldata(args: ReportServiceProbeCalldataArgs): string {\n if (!isValidPublicServiceProbeMask(args.serviceMask)) {\n throw new NodeRegistryError(\n `serviceMask 0x${args.serviceMask.toString(16).padStart(8, \"0\")} is not a valid public-service mask`,\n );\n }\n if (!isConcreteServiceProbeStatus(args.status)) {\n throw new NodeRegistryError(`status ${args.status} is not a concrete service-probe outcome`);\n }\n const latencyMs = expectUint32(args.latencyMs, \"latencyMs\");\n return bytesToHex(\n concatBytes(\n hexToBytes(NODE_REGISTRY_SELECTORS.reportServiceProbe),\n expectLength(toBytes(args.peerId), 32, \"peerId\"),\n uint32Word(args.serviceMask),\n uint8Word(args.status),\n uint32Word(latencyMs),\n expectLength(toBytes(args.probeDigest), 32, \"probeDigest\"),\n ),\n );\n}\n\nfunction bitCount(value: number): number {\n let n = value >>> 0;\n let count = 0;\n while (n !== 0) {\n count += n & 1;\n n >>>= 1;\n }\n return count;\n}\n\nfunction expectUint32(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw new NodeRegistryError(`${name} must be a uint32`);\n }\n return value;\n}\n\nfunction uint32Word(value: number): Uint8Array {\n const out = new Uint8Array(32);\n const n = expectUint32(value, \"uint32\");\n out[28] = (n >>> 24) & 0xff;\n out[29] = (n >>> 16) & 0xff;\n out[30] = (n >>> 8) & 0xff;\n out[31] = n & 0xff;\n return out;\n}\n\nfunction uint8Word(value: number): Uint8Array {\n if (!Number.isInteger(value) || value < 0 || value > 0xff) {\n throw new NodeRegistryError(\"uint8 value out of range\");\n }\n const out = new Uint8Array(32);\n out[31] = value;\n return out;\n}\n\nfunction toBytes(value: string | Uint8Array | readonly number[]): Uint8Array {\n if (typeof value === \"string\") {\n return hexToBytes(value);\n }\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {\n throw new NodeRegistryError(\"invalid hex bytes\");\n }\n const out = new Uint8Array(body.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = Number.parseInt(body.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction expectLength(value: Uint8Array, len: number, name: string): Uint8Array {\n if (value.length !== len) {\n throw new NodeRegistryError(`${name} must be ${len} bytes, got ${value.length}`);\n }\n return value;\n}\n","import { ml_dsa65 } from \"@noble/post-quantum/ml-dsa.js\";\nimport { blake3 } from \"@noble/hashes/blake3.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bigintToBeBytes, bytesToHex, concatBytes, expectBytes } from \"./bytes.js\";\nimport { bincodeSignedTransaction, encodeTransactionForHash, type NativeEvmTxFields } from \"./tx.js\";\n\nexport const ML_DSA_65_SEED_LEN = 32;\nexport const ML_DSA_65_SIGNING_KEY_LEN = 4032;\nexport const ML_DSA_65_PUBLIC_KEY_LEN = 1952;\nexport const ML_DSA_65_SIGNATURE_LEN = 3309;\nexport const STANDARD_ALGO_NUMBER_ML_DSA_65 = 1001;\nexport const ENUM_VARIANT_INDEX_ML_DSA_65 = 5;\nexport const ADDRESS_DERIVATION_DOMAIN = \"MONO_ADDRESS_BLAKE3_20_V1\";\n\nconst ADDRESS_DERIVATION_DOMAIN_BYTES = new TextEncoder().encode(ADDRESS_DERIVATION_DOMAIN);\n\nexport class MlDsa65Backend {\n readonly #secretKey: Uint8Array;\n readonly #publicKey: Uint8Array;\n readonly #addressBytes: Uint8Array;\n\n private constructor(secretKey: Uint8Array, publicKey: Uint8Array) {\n this.#secretKey = expectBytes(secretKey, ML_DSA_65_SIGNING_KEY_LEN, \"ML-DSA-65 secret key\").slice();\n this.#publicKey = expectBytes(publicKey, ML_DSA_65_PUBLIC_KEY_LEN, \"ML-DSA-65 public key\").slice();\n this.#addressBytes = mlDsa65AddressBytes(this.#publicKey);\n }\n\n static fromSeed(seed: Uint8Array | readonly number[]): MlDsa65Backend {\n const kp = ml_dsa65.keygen(expectBytes(seed, ML_DSA_65_SEED_LEN, \"ML-DSA-65 seed\"));\n return new MlDsa65Backend(kp.secretKey, kp.publicKey);\n }\n\n publicKey(): Uint8Array {\n return this.#publicKey.slice();\n }\n\n addressBytes(): Uint8Array {\n return this.#addressBytes.slice();\n }\n\n getAddress(): string {\n return bytesToHex(this.#addressBytes);\n }\n\n sign(message: Uint8Array): Uint8Array {\n return ml_dsa65.sign(message, this.#secretKey, { extraEntropy: false });\n }\n\n signPrehash(digest: Uint8Array): Uint8Array {\n return this.sign(expectBytes(digest, 32, \"prehash\"));\n }\n\n verify(message: Uint8Array, signature: Uint8Array): boolean {\n return ml_dsa65.verify(\n expectBytes(signature, ML_DSA_65_SIGNATURE_LEN, \"ML-DSA-65 signature\"),\n message,\n this.#publicKey,\n );\n }\n\n signEvmTx(fields: NativeEvmTxFields): {\n wireHex: string;\n wireBytes: Uint8Array;\n sighash: Uint8Array;\n txHash: Uint8Array;\n } {\n const txHashPreimage = encodeTransactionForHash(fields, 0x01);\n const sighash = keccak_256(txHashPreimage);\n const signature = this.sign(sighash);\n const wireBytes = bincodeSignedTransaction(fields, signature, this.#publicKey);\n const txHash = keccak_256(\n concatBytes(\n encodeTransactionForHash(fields, 0x02),\n signature,\n this.#publicKey,\n ),\n );\n return {\n wireHex: bytesToHex(wireBytes).slice(2),\n wireBytes,\n sighash,\n txHash,\n };\n }\n}\n\nexport function mlDsa65AddressFromPublicKey(publicKey: Uint8Array | readonly number[]): string {\n return bytesToHex(mlDsa65AddressBytes(publicKey));\n}\n\nexport function mlDsa65AddressBytes(publicKey: Uint8Array | readonly number[]): Uint8Array {\n const bytes = expectBytes(publicKey, ML_DSA_65_PUBLIC_KEY_LEN, \"ML-DSA-65 public key\");\n return blake3(concatBytes(\n ADDRESS_DERIVATION_DOMAIN_BYTES,\n bigintToBeBytes(BigInt(STANDARD_ALGO_NUMBER_ML_DSA_65), 2, \"ML-DSA-65 algo id\"),\n bytes,\n )).slice(0, 20);\n}\n\nexport function encodeMlDsa65Opaque(raw: Uint8Array | readonly number[]): Uint8Array {\n const bytes = raw instanceof Uint8Array ? raw : Uint8Array.from(raw);\n const len = bytes.length === ML_DSA_65_PUBLIC_KEY_LEN ? ML_DSA_65_PUBLIC_KEY_LEN : ML_DSA_65_SIGNATURE_LEN;\n expectBytes(bytes, len, \"ML-DSA-65 opaque bytes\");\n const out = new Uint8Array(4 + 2 + 8 + bytes.length);\n const dv = new DataView(out.buffer);\n dv.setUint32(0, ENUM_VARIANT_INDEX_ML_DSA_65, true);\n dv.setUint16(4, STANDARD_ALGO_NUMBER_ML_DSA_65, true);\n dv.setBigUint64(6, BigInt(bytes.length), true);\n out.set(bytes, 14);\n return out;\n}\n\nexport function uint256Bytes(value: bigint | number | string, label: string): Uint8Array {\n const v = typeof value === \"bigint\" ? value : typeof value === \"number\" ? BigInt(value) : BigInt(value);\n return bigintToBeBytes(v, 32, label);\n}\n","import { ml_kem768 } from \"@noble/post-quantum/ml-kem.js\";\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { BincodeWriter } from \"./bincode.js\";\nimport { bytesToHex, concatBytes, expectBytes } from \"./bytes.js\";\nimport {\n ENUM_VARIANT_INDEX_ML_DSA_65,\n ML_DSA_65_PUBLIC_KEY_LEN,\n ML_DSA_65_SIGNATURE_LEN,\n STANDARD_ALGO_NUMBER_ML_DSA_65,\n} from \"./ml-dsa.js\";\n\nconst DKG_AEAD_DOMAIN_TAG = new TextEncoder().encode(\"protocore/v2/mempool/dkg-mlkem768/1\");\n\nexport const ML_KEM_768_CIPHERTEXT_LEN = 1088;\nexport const ML_KEM_768_ENCAPSULATION_KEY_LEN = 1184;\nexport const ML_KEM_768_SHARED_SECRET_LEN = 32;\nexport const DKG_NONCE_LEN = 12;\nexport const DKG_AEAD_TAG_LEN = 16;\n\nexport const MempoolClass = {\n Transfer: 0,\n ContractCall: 1,\n PrivacyOp: 2,\n CLOBOp: 3,\n AgentOp: 4,\n FoundationOp: 5,\n /** @deprecated Use FoundationOp. */\n GovernanceOp: 5,\n RWAOp: 6,\n} as const;\nexport type MempoolClass = (typeof MempoolClass)[keyof typeof MempoolClass];\n\nexport interface NonceAad {\n sender: Uint8Array;\n nonce: bigint;\n chainId: bigint;\n class: MempoolClass;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n gasLimit: bigint;\n}\n\nexport interface DecryptHint {\n epoch: bigint;\n scheme: number;\n}\n\nexport interface EncryptedEnvelope {\n nonceAad: NonceAad;\n ciphertext: Uint8Array;\n decryptionHint: DecryptHint;\n senderPubkey: Uint8Array;\n outerSignature: Uint8Array;\n sender: Uint8Array;\n}\n\nexport function bincodeNonceAad(aad: NonceAad): Uint8Array {\n const w = new BincodeWriter();\n w.bytes(expectBytes(aad.sender, 20, \"NonceAad.sender\"));\n w.u64(aad.nonce);\n w.u64(aad.chainId);\n w.enumVariant(aad.class);\n w.u128(aad.maxFeePerGas);\n w.u128(aad.maxPriorityFeePerGas);\n w.u64(aad.gasLimit);\n return w.toBytes();\n}\n\nexport function bincodeDecryptHint(hint: DecryptHint): Uint8Array {\n const w = new BincodeWriter();\n w.u64(hint.epoch);\n w.u16(hint.scheme);\n return w.toBytes();\n}\n\nexport function bincodeEncryptedEnvelope(env: EncryptedEnvelope): Uint8Array {\n const w = new BincodeWriter();\n w.rawBytes(bincodeNonceAad(env.nonceAad));\n w.bytes(env.ciphertext);\n w.rawBytes(bincodeDecryptHint(env.decryptionHint));\n bincodeMlDsa65OpaqueInto(w, expectBytes(env.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\"));\n bincodeMlDsa65OpaqueInto(w, expectBytes(env.outerSignature, ML_DSA_65_SIGNATURE_LEN, \"outerSignature\"));\n w.bytes(expectBytes(env.sender, 20, \"sender\"));\n return w.toBytes();\n}\n\nexport function encryptInnerTx(\n signedInnerTxBincode: Uint8Array,\n nonceAad: NonceAad,\n kemEncapsulationKey: Uint8Array,\n): Uint8Array {\n expectBytes(kemEncapsulationKey, ML_KEM_768_ENCAPSULATION_KEY_LEN, \"kemEncapsulationKey\");\n const { cipherText: kemCt, sharedSecret } = ml_kem768.encapsulate(kemEncapsulationKey);\n const nonce = randomBytes(DKG_NONCE_LEN);\n const cipher = chacha20poly1305(sharedSecret, nonce, aadFor(nonceAad));\n const aeadCt = cipher.encrypt(signedInnerTxBincode);\n sharedSecret.fill(0);\n return concatBytes(kemCt, nonce, aeadCt);\n}\n\nexport function outerSigDigest(\n nonceAad: NonceAad,\n ciphertext: Uint8Array,\n decryptionHint: DecryptHint,\n senderPubkey: Uint8Array,\n): Uint8Array {\n const aad = bincodeNonceAad(nonceAad);\n const hint = bincodeDecryptHint(decryptionHint);\n return keccak_256(concatBytes(aad, ciphertext, hint, expectBytes(senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\")));\n}\n\nexport async function buildEncryptedEnvelope(args: {\n signedInnerTxBincode: Uint8Array;\n nonceAad: NonceAad;\n decryptionHint: DecryptHint;\n kemEncapsulationKey: Uint8Array;\n senderAddress: Uint8Array;\n senderPubkey: Uint8Array;\n signOuterDigest: (digest: Uint8Array) => Promise<Uint8Array> | Uint8Array;\n}): Promise<{ envelope: EncryptedEnvelope; wireBytes: Uint8Array; wireHex: string }> {\n const ciphertext = encryptInnerTx(args.signedInnerTxBincode, args.nonceAad, args.kemEncapsulationKey);\n const digest = outerSigDigest(args.nonceAad, ciphertext, args.decryptionHint, args.senderPubkey);\n const outerSignature = await args.signOuterDigest(digest);\n const envelope: EncryptedEnvelope = {\n nonceAad: args.nonceAad,\n ciphertext,\n decryptionHint: args.decryptionHint,\n senderPubkey: expectBytes(args.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\"),\n outerSignature: expectBytes(outerSignature, ML_DSA_65_SIGNATURE_LEN, \"outerSignature\"),\n sender: expectBytes(args.senderAddress, 20, \"senderAddress\"),\n };\n const wireBytes = bincodeEncryptedEnvelope(envelope);\n return { envelope, wireBytes, wireHex: bytesToHex(wireBytes) };\n}\n\nfunction aadFor(aad: NonceAad): Uint8Array {\n return concatBytes(DKG_AEAD_DOMAIN_TAG, bincodeNonceAad(aad));\n}\n\nfunction bincodeMlDsa65OpaqueInto(w: BincodeWriter, raw: Uint8Array): void {\n w.enumVariant(ENUM_VARIANT_INDEX_ML_DSA_65);\n w.u16(STANDARD_ALGO_NUMBER_ML_DSA_65);\n w.bytes(raw);\n}\n","import { blake3 } from \"@noble/hashes/blake3.js\";\nimport { ADDRESS_KIND_HRPS, addressToTypedBech32, typedBech32ToAddress } from \"./address.js\";\nimport {\n buildEncryptedSubmission,\n fetchEncryptionKey,\n submitEncryptedEnvelope,\n type EncryptionKey,\n} from \"./crypto/submission.js\";\nimport { BincodeWriter } from \"./crypto/bincode.js\";\n\nexport type { MrvAbiManifest } from \"./bindings/MrvAbiManifest.js\";\nexport type { MrvAbiParam } from \"./bindings/MrvAbiParam.js\";\nexport type { MrvAbiSymbol } from \"./bindings/MrvAbiSymbol.js\";\nexport type { MrvAbiSymbolKind } from \"./bindings/MrvAbiSymbolKind.js\";\nexport type { MrvAbiType } from \"./bindings/MrvAbiType.js\";\nexport type { MrvAddressKind } from \"./bindings/MrvAddressKind.js\";\nexport type { MrvArtifactMetadata } from \"./bindings/MrvArtifactMetadata.js\";\nexport type { MrvBuildMetadata } from \"./bindings/MrvBuildMetadata.js\";\nexport type { MrvCallRequest } from \"./bindings/MrvCallRequest.js\";\nexport type { MrvCallResponse } from \"./bindings/MrvCallResponse.js\";\nexport type { MrvCallStatus } from \"./bindings/MrvCallStatus.js\";\nexport type { MrvDeployPayload } from \"./bindings/MrvDeployPayload.js\";\nexport type { MrvDeployRequest } from \"./bindings/MrvDeployRequest.js\";\nexport type { MrvDeployResponse } from \"./bindings/MrvDeployResponse.js\";\nexport type { MrvEventRecord } from \"./bindings/MrvEventRecord.js\";\nexport type { MrvExecutionReceipt } from \"./bindings/MrvExecutionReceipt.js\";\nexport type { MrvMemoryLimits } from \"./bindings/MrvMemoryLimits.js\";\nexport type { MrvMeterCounters } from \"./bindings/MrvMeterCounters.js\";\nexport type { MrvNativeStateDelta } from \"./bindings/MrvNativeStateDelta.js\";\nexport type { MrvResolvedSyscall } from \"./bindings/MrvResolvedSyscall.js\";\nexport type { MrvRevertPayload } from \"./bindings/MrvRevertPayload.js\";\nexport type { MrvRiscvProfile } from \"./bindings/MrvRiscvProfile.js\";\nexport type { MrvStorageNamespace } from \"./bindings/MrvStorageNamespace.js\";\nexport type { MrvSyscallImport } from \"./bindings/MrvSyscallImport.js\";\nexport type { MrvTransactionExtension } from \"./bindings/MrvTransactionExtension.js\";\nexport type { MrvTypedAddress } from \"./bindings/MrvTypedAddress.js\";\nexport type { MrvValidatedArtifactMetadata } from \"./bindings/MrvValidatedArtifactMetadata.js\";\n\nimport type { AddressKind } from \"./address.js\";\nimport type { MrvAbiManifest } from \"./bindings/MrvAbiManifest.js\";\nimport type { MrvAbiType } from \"./bindings/MrvAbiType.js\";\nimport type { MrvAddressKind } from \"./bindings/MrvAddressKind.js\";\nimport type { MrvArtifactMetadata } from \"./bindings/MrvArtifactMetadata.js\";\nimport type { MrvCallRequest } from \"./bindings/MrvCallRequest.js\";\nimport type { MrvDeployRequest } from \"./bindings/MrvDeployRequest.js\";\nimport type { MrvResolvedSyscall } from \"./bindings/MrvResolvedSyscall.js\";\nimport type { MrvTransactionExtension } from \"./bindings/MrvTransactionExtension.js\";\nimport type { MrvValidatedArtifactMetadata } from \"./bindings/MrvValidatedArtifactMetadata.js\";\nimport type { RpcClient } from \"./client.js\";\nimport type { MempoolClass } from \"./crypto/envelope.js\";\nimport type { MlDsa65Backend } from \"./crypto/ml-dsa.js\";\nimport type { NativeEvmTxFields, NativeTxExtensionLike } from \"./crypto/tx.js\";\nimport type { NativeReceiptFee } from \"./client.js\";\n\nexport type MrvBytesLike = string | Uint8Array | readonly number[];\nexport type MrvDecimalLike = string | number | bigint;\n\nexport interface MrvRequestBuildOptions {\n from?: string;\n valueLythoshi?: MrvDecimalLike;\n executionUnitLimit?: number | bigint;\n maxExecutionFeeLythoshi?: MrvDecimalLike;\n priorityTipLythoshi?: MrvDecimalLike;\n nonce?: number | bigint;\n}\n\nexport interface MrvDeployPlanOptions extends MrvRequestBuildOptions {\n artifactHash?: string;\n}\n\nexport interface MrvDeployPayloadRequestOptions extends MrvRequestBuildOptions {\n constructorInput?: MrvBytesLike | null;\n}\n\nexport interface MrvDeployPayloadPlanOptions extends MrvDeployPayloadRequestOptions {\n artifactHash?: string;\n}\n\nexport interface MrvDeployPlan {\n request: MrvDeployRequest;\n extension: MrvTransactionExtension;\n expectedContractAddress?: string;\n}\n\nexport interface MrvCallPlan {\n request: MrvCallRequest;\n extension: MrvTransactionExtension;\n}\n\nexport type MrvDeployNativeTxOptions = Omit<\n MrvDeployPlanOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport type MrvDeployPayloadNativeTxOptions = Omit<\n MrvDeployPayloadPlanOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport type MrvCallNativeTxOptions = Omit<\n MrvRequestBuildOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport interface MrvNativeTxFacade {\n chainId: bigint;\n nonce: bigint;\n valueLythoshi: string;\n executionUnitLimit: bigint;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n}\n\nexport interface MrvNativeFeePreview {\n totalLythoshi: string;\n totalLyth: string;\n cyclesUsed: bigint;\n executionUnitLimit: bigint;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n}\n\nexport interface MrvDeployNativeTxPlan extends MrvDeployPlan {\n nativeTx: MrvNativeTxFacade;\n feePreview: MrvNativeFeePreview;\n tx: NativeEvmTxFields;\n}\n\nexport interface MrvCallNativeTxPlan extends MrvCallPlan {\n nativeTx: MrvNativeTxFacade;\n feePreview: MrvNativeFeePreview;\n tx: NativeEvmTxFields;\n}\n\nexport interface MrvEncryptedSubmissionResult {\n envelopeWireHex: string;\n innerSighashHex: string;\n innerTxHashHex: string;\n innerWireBytes: number;\n txHash: string;\n}\n\nexport type MrvDeploySubmitOptions = MrvDeployNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvDeployPayloadSubmitOptions = MrvDeployPayloadNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvCallSubmitOptions = MrvCallNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvDeploySubmission = MrvDeployNativeTxPlan & MrvEncryptedSubmissionResult;\nexport type MrvDeployPayloadSubmission = MrvDeployNativeTxPlan & MrvEncryptedSubmissionResult;\nexport type MrvCallSubmission = MrvCallNativeTxPlan & MrvEncryptedSubmissionResult;\n\nexport const MRV_FORMAT_VERSION = 1 as const;\nexport const MRV_DEPLOY_PAYLOAD_VERSION = 1 as const;\nexport const MRV_PROFILE_MONO_RV32IM_V1 = \"mono_rv32im_v1\" as const;\nexport const MRV_MEMORY_PAGE_BYTES = 65_536 as const;\nexport const MRV_MAX_CODE_BYTES = 16 * 1024 * 1024;\nexport const MRV_MAX_DEBUG_BYTES = 16 * 1024 * 1024;\nexport const MRV_MAX_MEMORY_PAGES = 1024 as const;\nexport const MRV_MAX_ABI_SYMBOLS = 1024 as const;\nexport const MRV_MAX_STORAGE_NAMESPACE_BYTES = 64 as const;\nexport const LYTH_DECIMALS = 8 as const;\nexport const NATIVE_LYTH_DECIMALS = LYTH_DECIMALS;\nexport const LYTHOSHI_PER_LYTH = 100_000_000n;\nexport const MRV_TX_EXTENSION_KIND = 0x30 as const;\nexport const MRV_TX_EXTENSION_V1 = 0x01 as const;\n\nconst MRV_CODE_HASH_DOMAIN = new TextEncoder().encode(\"MONO_MRV_CODE_V1\");\nconst MRV_CONTRACT_ADDRESS_DOMAIN = new TextEncoder().encode(\"mono:riscv:contract-address:v1\");\nconst MONO_SYSCALL_MODULE = \"mono\";\n\nconst SYSCALLS = [\n [0x0101, \"storage_read\"],\n [0x0102, \"storage_write\"],\n [0x0103, \"storage_delete\"],\n [0x0201, \"caller\"],\n [0x0202, \"contract_address\"],\n [0x0203, \"block_height\"],\n [0x0204, \"block_hash\"],\n [0x0301, \"call_contract\"],\n [0x0302, \"emit_event\"],\n [0x0303, \"transfer_native\"],\n [0x0401, \"verify_signature\"],\n [0x0402, \"hash\"],\n [0x0501, \"revert\"],\n] as const;\n\nconst SYSCALL_NAME_BY_ID = new Map<number, string>(SYSCALLS);\nconst SYSCALL_ID_BY_NAME = new Map<string, number>(SYSCALLS.map(([id, name]) => [name, id]));\n\nexport class MrvValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MrvValidationError\";\n }\n}\n\nexport interface LythFormatOptions {\n includeUnit?: boolean;\n}\n\nexport const MRV_STRUCTURED_FEE_FIELDS = [\n \"total_lythoshi\",\n \"cycles_used\",\n \"base_price_per_cycle_lythoshi\",\n \"state_io_units\",\n \"state_io_price_per_unit_lythoshi\",\n \"priority_tip_lythoshi\",\n] as const;\n\nexport interface MrvFeeDisplayConformanceInput {\n expectedTotalLythoshi: MrvDecimalLike;\n defaultFeeText: string;\n detailTexts?: readonly string[];\n structuredFee?: unknown;\n customFeeInputVisible?: boolean;\n speedUpCancelVisible?: boolean;\n}\n\nexport interface MrvFeeDisplayConformanceReport {\n passed: boolean;\n failures: string[];\n expectedDefaultFeeText: string;\n}\n\nexport interface MrvStructuredFeeConformanceOptions {\n expectedTotalLythoshi?: MrvDecimalLike;\n label?: string;\n}\n\nexport interface MrvStructuredFeeConformanceReport {\n passed: boolean;\n failures: string[];\n}\n\nexport interface NativeReceiptFeeDisplay {\n defaultFeeText: string;\n detailTexts: string[];\n totalLythoshi: string;\n totalLyth: string;\n}\n\nexport function formatLyth(lythoshi: MrvDecimalLike, options: LythFormatOptions = {}): string {\n const amount = BigInt(normalizeDecimalLike(\"lythoshi\", lythoshi));\n const whole = amount / LYTHOSHI_PER_LYTH;\n const fraction = amount % LYTHOSHI_PER_LYTH;\n let formatted = formatWholeWithCommas(whole);\n if (fraction !== 0n) {\n formatted += `.${fraction.toString().padStart(NATIVE_LYTH_DECIMALS, \"0\").replace(/0+$/, \"\")}`;\n }\n if (options.includeUnit !== false) {\n formatted += \" LYTH\";\n }\n return formatted;\n}\n\nexport function formatLythoshi(lythoshi: MrvDecimalLike, options: LythFormatOptions = {}): string {\n return formatLyth(lythoshi, options);\n}\n\nexport function parseLythToLythoshi(input: string): bigint {\n const numeric = stripLythUnit(input);\n const parts = numeric.split(\".\");\n if (parts.length > 2) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n const [wholeRaw, fractionRaw = \"\"] = parts;\n if (!isCanonicalWholeLyth(wholeRaw)) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n if (numeric.includes(\".\") && fractionRaw.length === 0) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n if (fractionRaw.length > NATIVE_LYTH_DECIMALS || !/^[0-9]*$/.test(fractionRaw)) {\n throw new MrvValidationError(\"lyth amount supports at most 8 decimal places\");\n }\n const whole = BigInt(wholeRaw.replaceAll(\",\", \"\"));\n const fraction = fractionRaw === \"\" ? 0n : BigInt(fractionRaw.padEnd(NATIVE_LYTH_DECIMALS, \"0\"));\n return whole * LYTHOSHI_PER_LYTH + fraction;\n}\n\nexport function checkMrvFeeDisplayConformance(\n input: MrvFeeDisplayConformanceInput,\n): MrvFeeDisplayConformanceReport {\n const expectedTotalLythoshi = normalizeDecimalLike(\"expectedTotalLythoshi\", input.expectedTotalLythoshi);\n const expectedDefaultFeeText = formatLyth(expectedTotalLythoshi);\n const failures: string[] = [];\n const amountCandidates = extractLythAmountCandidates(input.defaultFeeText);\n\n if (amountCandidates.length !== 1) {\n failures.push(\"defaultFeeText must contain exactly one LYTH-denominated fee amount\");\n } else {\n const renderedCandidate = `${amountCandidates[0]} LYTH`;\n if (renderedCandidate !== expectedDefaultFeeText) {\n failures.push(`defaultFeeText fee must be ${expectedDefaultFeeText}`);\n }\n try {\n const parsed = parseLythToLythoshi(renderedCandidate);\n if (parsed.toString() !== expectedTotalLythoshi) {\n failures.push(`defaultFeeText fee must total ${expectedTotalLythoshi} lythoshi`);\n }\n } catch {\n failures.push(\"defaultFeeText fee must be a canonical 8-decimal LYTH amount\");\n }\n }\n\n const defaultForbidden = firstForbiddenDefaultFeeTerm(input.defaultFeeText);\n if (defaultForbidden !== undefined) {\n failures.push(`defaultFeeText exposes detail-only fee term '${defaultForbidden}'`);\n }\n\n for (const [index, detailText] of (input.detailTexts ?? []).entries()) {\n const detailForbidden = firstForbiddenDetailFeeTerm(detailText);\n if (detailForbidden !== undefined) {\n failures.push(`detailTexts[${index}] exposes inherited fee term '${detailForbidden}'`);\n }\n }\n\n if (input.structuredFee !== undefined) {\n checkStructuredFeeObject(input.structuredFee, expectedTotalLythoshi, failures);\n }\n\n if (input.customFeeInputVisible === true) {\n failures.push(\"default surface must not expose custom fee inputs\");\n }\n if (input.speedUpCancelVisible === true) {\n failures.push(\"default surface must not expose speed-up or cancel controls\");\n }\n\n return {\n passed: failures.length === 0,\n failures,\n expectedDefaultFeeText,\n };\n}\n\nexport function checkMrvStructuredFeeConformance(\n value: unknown,\n options: MrvStructuredFeeConformanceOptions = {},\n): MrvStructuredFeeConformanceReport {\n const failures: string[] = [];\n const expectedTotalLythoshi =\n options.expectedTotalLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"expectedTotalLythoshi\", options.expectedTotalLythoshi);\n checkStructuredFeeObject(\n value,\n expectedTotalLythoshi,\n failures,\n options.label ?? \"structuredFee\",\n );\n return {\n passed: failures.length === 0,\n failures,\n };\n}\n\nexport function assertMrvStructuredFeeConformance(\n value: unknown,\n options: MrvStructuredFeeConformanceOptions = {},\n): asserts value is NativeReceiptFee {\n const report = checkMrvStructuredFeeConformance(value, options);\n if (!report.passed) {\n throw new MrvValidationError(`structured fee conformance failed: ${report.failures.join(\"; \")}`);\n }\n}\n\nexport function assertMrvFeeDisplayConformance(input: MrvFeeDisplayConformanceInput): void {\n const report = checkMrvFeeDisplayConformance(input);\n if (!report.passed) {\n throw new MrvValidationError(`fee display conformance failed: ${report.failures.join(\"; \")}`);\n }\n}\n\nexport function formatNativeReceiptFeeDisplay(\n fee: Pick<\n NativeReceiptFee,\n | \"total_lythoshi\"\n | \"cycles_used\"\n | \"state_io_units\"\n | \"base_price_per_cycle_lythoshi\"\n | \"state_io_price_per_unit_lythoshi\"\n | \"priority_tip_lythoshi\"\n >,\n): NativeReceiptFeeDisplay {\n const totalLythoshi = normalizeDecimalLike(\"fee.total_lythoshi\", fee.total_lythoshi);\n const totalLyth = formatLyth(totalLythoshi, { includeUnit: false });\n return {\n defaultFeeText: `Network fee: ${totalLyth} LYTH`,\n detailTexts: [\n `cycles ${fee.cycles_used}, state I/O ${fee.state_io_units}, total ${totalLythoshi} lythoshi`,\n `cycle price ${fee.base_price_per_cycle_lythoshi} lythoshi, state I/O price ${fee.state_io_price_per_unit_lythoshi} lythoshi, priority tip ${fee.priority_tip_lythoshi} lythoshi`,\n ],\n totalLythoshi,\n totalLyth,\n };\n}\n\nexport function mrvCodeHashHex(code: MrvBytesLike): string {\n const codeBytes = bytesFrom(code, \"code\");\n const len = new Uint8Array(8);\n new DataView(len.buffer).setBigUint64(0, BigInt(codeBytes.length), false);\n return bytesToHex(blake3(concatBytes(MRV_CODE_HASH_DOMAIN, len, codeBytes)));\n}\n\nexport function mrvV1TransactionExtension(): MrvTransactionExtension {\n return { kind: MRV_TX_EXTENSION_KIND, bodyHex: \"0x01\" };\n}\n\nexport function encodeMrvDeployPayload(\n artifactBytes: MrvBytesLike,\n constructorInput?: MrvBytesLike | null,\n): string {\n const artifact = bytesFrom(artifactBytes, \"artifactBytes\");\n const w = new BincodeWriter();\n w.u16(MRV_DEPLOY_PAYLOAD_VERSION);\n w.bytes(artifact);\n if (constructorInput === undefined || constructorInput === null) {\n w.u8(0);\n } else {\n const constructor = bytesFrom(constructorInput, \"constructorInput\");\n w.u8(1);\n w.bytes(constructor);\n }\n return bytesToHex(w.toBytes());\n}\n\nexport function mrvAddressToBech32(kind: MrvAddressKind, bytes: MrvBytesLike): string {\n return addressToTypedBech32(kind as AddressKind, bytesFrom(bytes, \"address\"));\n}\n\nexport function mrvBech32ToAddress(address: string, expectedKind?: MrvAddressKind) {\n return typedBech32ToAddress(address, expectedKind as AddressKind | undefined);\n}\n\nexport function deriveMrvContractAddress(\n deployerAddress: string,\n deployerNonce: number | bigint,\n artifactHashHex: string,\n): string {\n const deployer = typedBech32ToAddress(deployerAddress);\n const artifactHash = hexToBytes(artifactHashHex, \"artifactHash\");\n if (artifactHash.length !== 32) throw new MrvValidationError(\"artifactHash must be 32 bytes\");\n const nonceValue = normalizeU64(deployerNonce, \"deployerNonce\");\n const nonce = new Uint8Array(8);\n new DataView(nonce.buffer).setBigUint64(0, nonceValue, false);\n const digest = blake3(\n concatBytes(\n MRV_CONTRACT_ADDRESS_DOMAIN,\n new TextEncoder().encode(ADDRESS_KIND_HRPS[deployer.kind]),\n Uint8Array.of(0),\n hexToBytes(deployer.hex, \"deployerAddress\"),\n nonce,\n artifactHash,\n ),\n );\n return addressToTypedBech32(\"contract\", digest.slice(0, 20));\n}\n\nexport function validateMrvArtifactMetadata(\n metadata: MrvArtifactMetadata,\n code: MrvBytesLike,\n): MrvValidatedArtifactMetadata {\n const codeBytes = bytesFrom(code, \"code\");\n if (metadata.formatVersion !== MRV_FORMAT_VERSION) {\n throw new MrvValidationError(\n `unsupported MRV format version ${metadata.formatVersion}, expected ${MRV_FORMAT_VERSION}`,\n );\n }\n if (metadata.profile !== MRV_PROFILE_MONO_RV32IM_V1) {\n throw new MrvValidationError(`unsupported MRV profile ${metadata.profile}`);\n }\n if (codeBytes.length === 0) {\n throw new MrvValidationError(\"MRV code is empty\");\n }\n if (codeBytes.length > MRV_MAX_CODE_BYTES) {\n throw new MrvValidationError(`MRV code has ${codeBytes.length} bytes, max ${MRV_MAX_CODE_BYTES}`);\n }\n if (metadata.codeBytes !== BigInt(codeBytes.length)) {\n throw new MrvValidationError(\n `metadata codeBytes ${metadata.codeBytes.toString()} does not match supplied code length ${codeBytes.length}`,\n );\n }\n if (metadata.debugBytes > BigInt(MRV_MAX_DEBUG_BYTES)) {\n throw new MrvValidationError(`MRV debug section has ${metadata.debugBytes.toString()} bytes`);\n }\n validateHexLength(\"codeHash\", metadata.codeHash, 32);\n validateHexLength(\"sourceDigest\", metadata.build.sourceDigest, 32);\n validateMemory(metadata.memory.initialPages, metadata.memory.maxPages, metadata.memory.stackBytes);\n validateStorageNamespace(metadata.storageNamespace.name, metadata.storageNamespace.version);\n validateAbi(metadata.abi);\n const syscalls = validateImports(metadata.imports);\n const computed = mrvCodeHashHex(codeBytes);\n if (metadata.codeHash.toLowerCase() !== computed) {\n throw new MrvValidationError(`MRV code hash mismatch: declared ${metadata.codeHash}, computed ${computed}`);\n }\n return {\n codeHash: computed,\n profile: metadata.profile,\n memory: metadata.memory,\n storageNamespace: metadata.storageNamespace,\n syscalls,\n abiSymbolCount: BigInt(metadata.abi.symbols.length),\n codeBytes: BigInt(codeBytes.length),\n };\n}\n\nexport function validateMrvDeployRequest(request: MrvDeployRequest): void {\n if (request.from !== undefined) typedBech32ToAddress(request.from, \"user\");\n hexToBytes(request.artifactBytes, \"artifactBytes\");\n validateDecimal(\"valueLythoshi\", request.valueLythoshi);\n validateOptionalDecimal(\"maxExecutionFeeLythoshi\", request.maxExecutionFeeLythoshi);\n validateOptionalDecimal(\"priorityTipLythoshi\", request.priorityTipLythoshi);\n validateExecutionUnitLimit(\"executionUnitLimit\", request.executionUnitLimit);\n}\n\nexport function validateMrvCallRequest(request: MrvCallRequest): void {\n if (request.from !== undefined) typedBech32ToAddress(request.from, \"user\");\n typedBech32ToAddress(request.contractAddress, \"contract\");\n hexToBytes(request.input, \"input\");\n validateDecimal(\"valueLythoshi\", request.valueLythoshi);\n validateOptionalDecimal(\"maxExecutionFeeLythoshi\", request.maxExecutionFeeLythoshi);\n validateOptionalDecimal(\"priorityTipLythoshi\", request.priorityTipLythoshi);\n validateExecutionUnitLimit(\"executionUnitLimit\", request.executionUnitLimit);\n}\n\nexport function buildMrvDeployRequest(\n artifactBytes: MrvBytesLike,\n options: MrvRequestBuildOptions = {},\n): MrvDeployRequest {\n const request: MrvDeployRequest = {\n artifactBytes: normalizeBytesHex(artifactBytes, \"artifactBytes\"),\n valueLythoshi: normalizeDecimalLike(\"valueLythoshi\", options.valueLythoshi, \"0\"),\n };\n applyRequestOptions(request, options);\n validateMrvDeployRequest(request);\n return request;\n}\n\nexport function buildMrvDeployPayloadRequest(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadRequestOptions = {},\n): MrvDeployRequest {\n const request = buildMrvDeployRequest(\n encodeMrvDeployPayload(artifactBytes, options.constructorInput),\n options,\n );\n return request;\n}\n\nexport function buildMrvCallRequest(\n contractAddress: string,\n input: MrvBytesLike = \"0x\",\n options: MrvRequestBuildOptions = {},\n): MrvCallRequest {\n const request: MrvCallRequest = {\n contractAddress,\n input: normalizeBytesHex(input, \"input\"),\n valueLythoshi: normalizeDecimalLike(\"valueLythoshi\", options.valueLythoshi, \"0\"),\n };\n applyRequestOptions(request, options);\n validateMrvCallRequest(request);\n return request;\n}\n\nexport function buildMrvDeployPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPlanOptions = {},\n): MrvDeployPlan {\n const request = buildMrvDeployRequest(artifactBytes, options);\n const plan: MrvDeployPlan = {\n request,\n extension: mrvV1TransactionExtension(),\n };\n if (options.artifactHash !== undefined && request.from !== undefined && request.nonce !== undefined) {\n plan.expectedContractAddress = deriveMrvContractAddress(request.from, request.nonce, options.artifactHash);\n } else if (options.artifactHash !== undefined) {\n validateHexLength(\"artifactHash\", options.artifactHash, 32);\n }\n return plan;\n}\n\nexport function buildMrvDeployPayloadPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadPlanOptions = {},\n): MrvDeployPlan {\n const request = buildMrvDeployPayloadRequest(artifactBytes, options);\n const plan: MrvDeployPlan = {\n request,\n extension: mrvV1TransactionExtension(),\n };\n if (options.artifactHash !== undefined && request.from !== undefined && request.nonce !== undefined) {\n plan.expectedContractAddress = deriveMrvContractAddress(request.from, request.nonce, options.artifactHash);\n } else if (options.artifactHash !== undefined) {\n validateHexLength(\"artifactHash\", options.artifactHash, 32);\n }\n return plan;\n}\n\nexport function buildMrvCallPlan(\n contractAddress: string,\n input: MrvBytesLike = \"0x\",\n options: MrvRequestBuildOptions = {},\n): MrvCallPlan {\n return {\n request: buildMrvCallRequest(contractAddress, input, options),\n extension: mrvV1TransactionExtension(),\n };\n}\n\nexport function buildMrvDeployNativeTxPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployNativeTxOptions,\n): MrvDeployNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvDeployPlan(artifactBytes, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: null,\n value: plan.request.valueLythoshi,\n input: plan.request.artifactBytes,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function buildMrvDeployPayloadNativeTxPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadNativeTxOptions,\n): MrvDeployNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvDeployPayloadPlan(artifactBytes, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: null,\n value: plan.request.valueLythoshi,\n input: plan.request.artifactBytes,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function buildMrvCallNativeTxPlan(\n contractAddress: string,\n input: MrvBytesLike,\n options: MrvCallNativeTxOptions,\n): MrvCallNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvCallPlan(contractAddress, input, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: typedBech32ToAddress(plan.request.contractAddress, \"contract\").hex,\n value: plan.request.valueLythoshi,\n input: plan.request.input,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function assertMrvDeployNativeSubmissionPlan(plan: MrvDeployNativeTxPlan): void {\n assertMrvNativeSubmissionEnvelope(plan);\n if (plan.tx.to !== null) {\n throw new MrvValidationError(\"MRV deploy submission tx.to must be null\");\n }\n const txInput = normalizeBytesHex(plan.tx.input ?? \"0x\", \"tx.input\");\n if (txInput !== plan.request.artifactBytes) {\n throw new MrvValidationError(\"MRV deploy submission tx.input must match artifactBytes\");\n }\n}\n\nexport function assertMrvCallNativeSubmissionPlan(plan: MrvCallNativeTxPlan): void {\n assertMrvNativeSubmissionEnvelope(plan);\n const actualTo = normalizeNativeTxToHex(plan.tx.to, \"tx.to\");\n if (actualTo === null) {\n throw new MrvValidationError(\"MRV call submission tx.to must be a 20-byte contract address\");\n }\n const expectedTo = typedBech32ToAddress(plan.request.contractAddress, \"contract\").hex.toLowerCase();\n if (actualTo !== expectedTo) {\n throw new MrvValidationError(\"MRV call submission tx.to must match contractAddress\");\n }\n const txInput = normalizeBytesHex(plan.tx.input ?? \"0x\", \"tx.input\");\n if (txInput !== plan.request.input) {\n throw new MrvValidationError(\"MRV call submission tx.input must match request input\");\n }\n}\n\nfunction buildMrvNativeFeePreview(\n executionUnitLimit: bigint,\n maxExecutionFeeLythoshi: string,\n priorityTipLythoshi: string,\n): MrvNativeFeePreview {\n const totalLythoshi = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", maxExecutionFeeLythoshi);\n return {\n totalLythoshi,\n totalLyth: formatLyth(totalLythoshi, { includeUnit: false }),\n cyclesUsed: executionUnitLimit,\n executionUnitLimit,\n maxExecutionFeeLythoshi: totalLythoshi,\n priorityTipLythoshi: normalizeDecimalLike(\"priorityTipLythoshi\", priorityTipLythoshi),\n };\n}\n\nexport async function submitMrvDeployNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n artifactBytes: MrvBytesLike,\n options: MrvDeploySubmitOptions,\n): Promise<MrvDeploySubmission> {\n const plan = buildMrvDeployNativeTxPlan(artifactBytes, options);\n assertMrvDeployNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nexport async function submitMrvDeployPayloadNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadSubmitOptions,\n): Promise<MrvDeployPayloadSubmission> {\n const plan = buildMrvDeployPayloadNativeTxPlan(artifactBytes, options);\n assertMrvDeployNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nexport async function submitMrvCallNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n contractAddress: string,\n input: MrvBytesLike,\n options: MrvCallSubmitOptions,\n): Promise<MrvCallSubmission> {\n const plan = buildMrvCallNativeTxPlan(contractAddress, input, options);\n assertMrvCallNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nfunction assertMrvNativeSubmissionEnvelope(plan: MrvDeployNativeTxPlan | MrvCallNativeTxPlan): void {\n const extensions = plan.tx.extensions ?? [];\n if (extensions.length !== 1) {\n throw new MrvValidationError(\"MRV native submission must carry exactly one transaction extension\");\n }\n assertMrvV1Extension(plan.extension, \"extension\");\n assertMrvV1Extension(extensions[0], \"tx.extensions[0]\");\n assertSameBigint(\"tx.chainId\", plan.tx.chainId, plan.nativeTx.chainId);\n assertSameBigint(\"tx.nonce\", plan.tx.nonce, plan.nativeTx.nonce);\n assertSameBigint(\"tx.gasLimit\", plan.tx.gasLimit, plan.nativeTx.executionUnitLimit);\n assertSameDecimal(\"tx.value\", plan.tx.value, plan.nativeTx.valueLythoshi);\n assertSameDecimal(\"tx.maxFeePerGas\", plan.tx.maxFeePerGas, plan.nativeTx.maxExecutionFeeLythoshi);\n assertSameDecimal(\"tx.maxPriorityFeePerGas\", plan.tx.maxPriorityFeePerGas, plan.nativeTx.priorityTipLythoshi);\n assertU128Lythoshi(\"maxExecutionFeeLythoshi\", plan.nativeTx.maxExecutionFeeLythoshi);\n assertU128Lythoshi(\"priorityTipLythoshi\", plan.nativeTx.priorityTipLythoshi);\n}\n\nfunction assertMrvV1Extension(extension: NativeTxExtensionLike, field: string): void {\n if (extension.kind !== MRV_TX_EXTENSION_KIND) {\n throw new MrvValidationError(`${field}.kind must be MRV v1 extension kind`);\n }\n const bodyHex = normalizeBytesHex(\"bodyHex\" in extension ? extension.bodyHex : extension.body, `${field}.body`);\n if (bodyHex !== \"0x01\") {\n throw new MrvValidationError(`${field}.body must be MRV v1 extension body`);\n }\n}\n\nfunction assertSameBigint(field: string, actual: bigint | number | string, expected: bigint): void {\n if (normalizeU64Like(actual, field) !== expected) {\n throw new MrvValidationError(`${field} must match nativeTx`);\n }\n}\n\nfunction assertSameDecimal(field: string, actual: MrvDecimalLike, expected: string): void {\n if (normalizeDecimalLike(field, actual) !== expected) {\n throw new MrvValidationError(`${field} must match nativeTx`);\n }\n}\n\nfunction assertU128Lythoshi(field: string, value: MrvDecimalLike): void {\n const normalized = BigInt(normalizeDecimalLike(field, value));\n if (normalized > (1n << 128n) - 1n) {\n throw new MrvValidationError(`${field} must fit in u128 for encrypted submission`);\n }\n}\n\nfunction normalizeNativeTxToHex(value: NativeEvmTxFields[\"to\"], field: string): string | null {\n if (value === null) return null;\n const bytes = bytesFrom(value, field);\n if (bytes.length !== 20) {\n throw new MrvValidationError(`${field} must be a 20-byte address`);\n }\n return bytesToHex(bytes).toLowerCase();\n}\n\nfunction normalizeU64Like(value: bigint | number | string, field: string): bigint {\n if (typeof value === \"string\") {\n return normalizeU64(BigInt(normalizeDecimalLike(field, value)), field);\n }\n return normalizeU64(value, field);\n}\n\nfunction validateMemory(initialPages: number, maxPages: number, stackBytes: number): void {\n if (initialPages === 0) throw new MrvValidationError(\"initialPages is zero\");\n if (maxPages === 0) throw new MrvValidationError(\"maxPages is zero\");\n if (initialPages > maxPages) throw new MrvValidationError(\"initialPages exceeds maxPages\");\n if (maxPages > MRV_MAX_MEMORY_PAGES) throw new MrvValidationError(\"maxPages exceeds bound\");\n if (stackBytes === 0) throw new MrvValidationError(\"stackBytes is zero\");\n const maxBytes = maxPages * MRV_MEMORY_PAGE_BYTES;\n if (stackBytes > maxBytes) throw new MrvValidationError(\"stackBytes exceeds max memory\");\n if (stackBytes % 16 !== 0) throw new MrvValidationError(\"stackBytes must be 16-byte aligned\");\n}\n\nfunction validateStorageNamespace(name: string, version: number): void {\n if (version === 0) throw new MrvValidationError(\"storage namespace version must be non-zero\");\n if (name.length > MRV_MAX_STORAGE_NAMESPACE_BYTES) throw new MrvValidationError(\"storage namespace is too long\");\n if (!isIdentifier(name)) throw new MrvValidationError(\"storage namespace is not canonical\");\n}\n\nfunction validateAbi(abi: MrvAbiManifest): void {\n if (abi.symbols.length === 0) throw new MrvValidationError(\"MRV ABI must declare at least one symbol\");\n if (abi.symbols.length > MRV_MAX_ABI_SYMBOLS) {\n throw new MrvValidationError(`MRV ABI has ${abi.symbols.length} symbols, max ${MRV_MAX_ABI_SYMBOLS}`);\n }\n const seen = new Set<string>();\n for (const symbol of abi.symbols) {\n if (!isIdentifier(symbol.name)) throw new MrvValidationError(`invalid MRV ABI symbol '${symbol.name}'`);\n if (seen.has(symbol.name)) throw new MrvValidationError(`duplicate MRV ABI symbol '${symbol.name}'`);\n seen.add(symbol.name);\n for (const param of [...symbol.inputs, ...symbol.outputs]) {\n if (!isIdentifier(param.name)) throw new MrvValidationError(`invalid MRV ABI parameter '${param.name}'`);\n validateAbiType(param.ty);\n }\n }\n}\n\nfunction validateAbiType(ty: MrvAbiType): void {\n if (ty.kind === \"fixedBytes\" && ty.len === 0) {\n throw new MrvValidationError(\"fixed bytes length is zero\");\n }\n}\n\nfunction validateImports(imports: MrvArtifactMetadata[\"imports\"]): MrvResolvedSyscall[] {\n const seen = new Set<number>();\n const resolved: MrvResolvedSyscall[] = [];\n for (const imp of imports) {\n if (imp.module !== MONO_SYSCALL_MODULE) {\n throw new MrvValidationError(`forbidden host import ${imp.module}.${imp.name}`);\n }\n const expectedName = SYSCALL_NAME_BY_ID.get(imp.id);\n if (expectedName === undefined) throw new MrvValidationError(`unknown MRV syscall id ${imp.id}`);\n const expectedId = SYSCALL_ID_BY_NAME.get(imp.name);\n if (expectedId === undefined) throw new MrvValidationError(`unknown MRV syscall name '${imp.name}'`);\n if (expectedId !== imp.id) {\n throw new MrvValidationError(`MRV syscall name/id mismatch for ${imp.name}: declared ${imp.id}`);\n }\n if (seen.has(imp.id)) throw new MrvValidationError(`duplicate MRV syscall '${expectedName}'`);\n seen.add(imp.id);\n resolved.push({ id: imp.id, name: expectedName });\n }\n return resolved;\n}\n\nfunction validateOptionalDecimal(field: string, value: string | undefined): void {\n if (value !== undefined) validateDecimal(field, value);\n}\n\nfunction applyRequestOptions(request: MrvDeployRequest | MrvCallRequest, options: MrvRequestBuildOptions): void {\n if (options.from !== undefined) request.from = options.from;\n const executionUnitLimit = normalizeOptionalU64(\"executionUnitLimit\", options.executionUnitLimit);\n if (executionUnitLimit !== undefined) request.executionUnitLimit = executionUnitLimit;\n const maxExecutionFee = normalizeOptionalDecimalLike(\n \"maxExecutionFeeLythoshi\",\n options.maxExecutionFeeLythoshi,\n );\n if (maxExecutionFee !== undefined) request.maxExecutionFeeLythoshi = maxExecutionFee;\n const priorityTip = normalizeOptionalDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n if (priorityTip !== undefined) request.priorityTipLythoshi = priorityTip;\n const nonce = normalizeOptionalU64(\"nonce\", options.nonce);\n if (nonce !== undefined) request.nonce = nonce;\n}\n\nfunction normalizeBytesHex(value: MrvBytesLike, field: string): string {\n return bytesToHex(bytesFrom(value, field));\n}\n\nfunction normalizeOptionalDecimalLike(field: string, value: MrvDecimalLike | undefined): string | undefined {\n return value === undefined ? undefined : normalizeDecimalLike(field, value);\n}\n\nfunction formatWholeWithCommas(value: bigint): string {\n const digits = value.toString();\n const firstGroupLen = digits.length % 3;\n const groups: string[] = [];\n let index = 0;\n if (firstGroupLen !== 0) {\n groups.push(digits.slice(0, firstGroupLen));\n index = firstGroupLen;\n }\n while (index < digits.length) {\n groups.push(digits.slice(index, index + 3));\n index += 3;\n }\n return groups.join(\",\");\n}\n\nfunction stripLythUnit(input: string): string {\n const trimmed = input.trim();\n const withoutUnit = trimmed.replace(/\\s+LYTH$/i, \"\").trim();\n if (withoutUnit.length === 0) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n return withoutUnit;\n}\n\nfunction isCanonicalWholeLyth(value: string): boolean {\n if (/^(0|[1-9][0-9]*)$/.test(value)) {\n return true;\n }\n return /^[1-9][0-9]{0,2}(,[0-9]{3})+$/.test(value);\n}\n\nfunction extractLythAmountCandidates(text: string): string[] {\n return [...text.matchAll(/(?:^|[^A-Za-z0-9_])([0-9][0-9,]*(?:\\.[0-9]+)?)\\s+LYTH\\b/g)].map(\n (match) => match[1],\n );\n}\n\nfunction firstForbiddenDefaultFeeTerm(text: string): string | undefined {\n const tokens = feeTermTokens(text);\n for (const forbidden of [\"gas\", \"gwei\", \"wei\", \"cycle\", \"cycles\", \"lythoshi\"]) {\n if (tokens.includes(forbidden)) return forbidden;\n }\n if (hasAdjacentTerms(tokens, \"state\", \"io\") || hasStateIOTerms(tokens)) return \"state I/O\";\n return undefined;\n}\n\nfunction firstForbiddenDetailFeeTerm(text: string): string | undefined {\n const tokens = feeTermTokens(text);\n for (const forbidden of [\"gas\", \"gwei\", \"wei\"]) {\n if (tokens.includes(forbidden)) return forbidden;\n }\n return undefined;\n}\n\nfunction feeTermTokens(text: string): string[] {\n return text.toLowerCase().match(/[a-z]+/g) ?? [];\n}\n\nfunction hasAdjacentTerms(tokens: readonly string[], first: string, second: string): boolean {\n return tokens.some((token, index) => token === first && tokens[index + 1] === second);\n}\n\nfunction hasStateIOTerms(tokens: readonly string[]): boolean {\n return tokens.some((token, index) => token === \"state\" && tokens[index + 1] === \"i\" && tokens[index + 2] === \"o\");\n}\n\nfunction checkStructuredFeeObject(\n value: unknown,\n expectedTotalLythoshi: string | undefined,\n failures: string[],\n label = \"structuredFee\",\n): void {\n if (!isRecord(value)) {\n failures.push(`${label} must be an object`);\n return;\n }\n const expectedFields = new Set<string>([...MRV_STRUCTURED_FEE_FIELDS, \"total_lyth\"]);\n const actualFields = Object.keys(value);\n for (const field of MRV_STRUCTURED_FEE_FIELDS) {\n if (!(field in value)) failures.push(`${label} is missing '${field}'`);\n }\n for (const field of actualFields) {\n if (!expectedFields.has(field)) failures.push(`${label} has unexpected field '${field}'`);\n }\n\n const totalLythoshi = stringField(value, \"total_lythoshi\", failures, label);\n const expectedTotal = expectedTotalLythoshi ?? totalLythoshi;\n if (\n totalLythoshi !== undefined &&\n expectedTotalLythoshi !== undefined &&\n totalLythoshi !== expectedTotalLythoshi\n ) {\n failures.push(`${label}.total_lythoshi must be ${expectedTotalLythoshi}`);\n }\n const totalLyth =\n \"total_lyth\" in value ? lythDecimalField(value, \"total_lyth\", failures, label) : undefined;\n if (totalLyth !== undefined && expectedTotal !== undefined) {\n const expectedTotalLyth = formatLyth(expectedTotal, { includeUnit: false });\n if (totalLyth !== expectedTotalLyth) {\n failures.push(`${label}.total_lyth must be ${expectedTotalLyth}`);\n }\n }\n for (const field of [\n \"base_price_per_cycle_lythoshi\",\n \"state_io_price_per_unit_lythoshi\",\n \"priority_tip_lythoshi\",\n ]) {\n stringField(value, field, failures, label);\n }\n for (const field of [\"cycles_used\", \"state_io_units\"]) {\n integerField(value, field, failures, label);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): string | undefined {\n const fieldValue = value[field];\n if (typeof fieldValue !== \"string\" || !isCanonicalUnsignedDecimalString(fieldValue)) {\n failures.push(`${label}.${field} must be a canonical unsigned decimal string`);\n return undefined;\n }\n return fieldValue;\n}\n\nfunction lythDecimalField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): string | undefined {\n const fieldValue = value[field];\n if (typeof fieldValue !== \"string\") {\n failures.push(`${label}.${field} must be a canonical LYTH decimal string`);\n return undefined;\n }\n try {\n parseLythToLythoshi(`${fieldValue} LYTH`);\n } catch {\n failures.push(`${label}.${field} must be a canonical LYTH decimal string`);\n return undefined;\n }\n return fieldValue;\n}\n\nfunction integerField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): void {\n const fieldValue = value[field];\n if (\n typeof fieldValue !== \"number\" ||\n !Number.isSafeInteger(fieldValue) ||\n fieldValue < 0\n ) {\n failures.push(`${label}.${field} must be a non-negative safe integer`);\n }\n}\n\nfunction isCanonicalUnsignedDecimalString(value: string): boolean {\n if (!/^(0|[1-9][0-9]*)$/.test(value)) return false;\n try {\n BigInt(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalizeDecimalLike(field: string, value: MrvDecimalLike | undefined, defaultValue?: string): string {\n if (value === undefined) {\n if (defaultValue === undefined) throw new MrvValidationError(`${field} is required`);\n return defaultValue;\n }\n if (typeof value === \"string\") {\n validateDecimal(field, value);\n return value;\n }\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n throw new MrvValidationError(`${field} must be a safe unsigned integer`);\n }\n const out = BigInt(value);\n if (out < 0n) throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n return out.toString();\n}\n\nfunction normalizeOptionalU64(field: string, value: number | bigint | undefined): bigint | undefined {\n return value === undefined ? undefined : normalizeU64(value, field);\n}\n\nfunction validateDecimal(field: string, value: string): void {\n if (!/^(0|[1-9][0-9]*)$/.test(value)) {\n throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n }\n try {\n BigInt(value);\n } catch {\n throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n }\n}\n\nfunction validateExecutionUnitLimit(field: string, value: number | bigint | undefined): void {\n if (value !== undefined && BigInt(value) === 0n) {\n throw new MrvValidationError(`${field} must be greater than zero`);\n }\n}\n\nfunction normalizeU64(value: number | bigint, field: string): bigint {\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n throw new MrvValidationError(`${field} must be a safe unsigned integer`);\n }\n const out = BigInt(value);\n if (out < 0n || out > 0xffff_ffff_ffff_ffffn) {\n throw new MrvValidationError(`${field} must fit in u64`);\n }\n return out;\n}\n\nfunction validateHexLength(field: string, value: string, expected: number): void {\n const bytes = hexToBytes(value, field);\n if (bytes.length !== expected) throw new MrvValidationError(`${field} must be ${expected} bytes`);\n}\n\nfunction bytesFrom(value: MrvBytesLike, field: string): Uint8Array {\n if (typeof value === \"string\") return hexToBytes(value, field);\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n\nfunction hexToBytes(value: string, field: string): Uint8Array {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new MrvValidationError(`${field} must be 0x-prefixed even-length hex`);\n }\n const out = new Uint8Array((value.length - 2) / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = Number.parseInt(value.slice(2 + i * 2, 4 + i * 2), 16);\n }\n return out;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const len = parts.reduce((sum, item) => sum + item.length, 0);\n const out = new Uint8Array(len);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction isIdentifier(value: string): boolean {\n return /^[a-z][a-z0-9_]*$/.test(value);\n}\n","/**\n * Chain-registry snapshot and helpers.\n *\n * Source of truth:\n * https://github.com/monolythium/chain-registry\n *\n * The SDK vendors a release-time snapshot so callers can bootstrap without\n * network access to GitHub. Callers that want the newest registry state can\n * opt into `fetchChainRegistryLatest()`.\n */\n\nimport { ML_DSA_65_PUBLIC_KEY_LEN } from \"./crypto/ml-dsa.js\";\nimport { hexToBytes } from \"./crypto/bytes.js\";\nimport type { NoEvmReceiptTrustPolicy } from \"./receipt-proof.js\";\n\nexport type NetworkSlug = \"testnet-69420\";\n\nconst BLS_PUBLIC_KEY_BYTE_LENGTH = 48;\n\nexport interface RpcEndpoint {\n url: string;\n provider: string;\n region?: string;\n tier: \"official\" | \"community\";\n archive?: boolean;\n ws_url?: string;\n notes?: string;\n}\n\nexport interface P2pSeed {\n multiaddr: string;\n region?: string;\n}\n\nexport interface ExplorerEndpoint {\n url: string;\n name: string;\n kind?: \"monoscan\" | \"etherscan-fork\" | \"custom\";\n}\n\nexport interface ReceiptProofTrustArchiveSigner {\n public_key: string;\n signer_id?: string;\n valid_from_height?: number;\n valid_to_height?: number;\n notes?: string;\n}\n\nexport interface ReceiptProofTrustArchivePolicy {\n signature_threshold: number;\n valid_from_height?: number;\n valid_to_height?: number;\n signers: ReceiptProofTrustArchiveSigner[];\n}\n\nexport interface ReceiptProofTrustFinalitySigner {\n authority_index: number;\n public_key: string;\n valid_from_round?: number;\n valid_to_round?: number;\n notes?: string;\n}\n\nexport interface ReceiptProofTrustFinalityPolicy {\n mode: \"cluster\" | \"multisig\";\n chain_id?: number;\n threshold: number;\n committee_size?: number;\n cluster_public_key?: string;\n valid_from_round?: number;\n valid_to_round?: number;\n signers?: ReceiptProofTrustFinalitySigner[];\n}\n\nexport interface ReceiptProofTrustPolicy {\n archive?: ReceiptProofTrustArchivePolicy;\n finality?: ReceiptProofTrustFinalityPolicy;\n}\n\nexport interface ChainInfo {\n chain_id: number;\n network: NetworkSlug | string;\n display_name?: string;\n description?: string;\n genesis_hash: string;\n binary_sha: string;\n rpc: RpcEndpoint[];\n p2p: P2pSeed[];\n explorer?: ExplorerEndpoint[];\n receipt_proof_trust?: ReceiptProofTrustPolicy;\n}\n\nexport type ChainRegistry = Record<NetworkSlug | string, ChainInfo>;\n\nexport const TESTNET_69420: ChainInfo = {\n chain_id: 69420,\n network: \"testnet-69420\",\n display_name: \"Monolythium Testnet\",\n description:\n \"Public Monolythium testnet. Testnet state may reset without notice; do not store value on this network.\",\n genesis_hash:\n \"0x325057e476b7be3730a22c92b9289f4a14a3414a2a081bd279b43eeba36b0075\",\n binary_sha: \"44a9ec4\",\n rpc: [\n {\n url: \"https://rpc.monolythium.com\",\n provider: \"monolythium\",\n tier: \"official\",\n },\n ],\n p2p: [],\n};\n\nexport const CHAIN_REGISTRY: ChainRegistry = {\n \"testnet-69420\": TESTNET_69420,\n};\n\nexport const CHAIN_REGISTRY_RAW_BASE =\n \"https://raw.githubusercontent.com/monolythium/chain-registry/master/chains\" as const;\n\nexport function getChainInfo(network: NetworkSlug | string): ChainInfo {\n const info = CHAIN_REGISTRY[network];\n if (!info) {\n throw new Error(`unknown Monolythium network: ${network}`);\n }\n return info;\n}\n\nexport function getRpcEndpoints(network: NetworkSlug | string): readonly RpcEndpoint[] {\n return getChainInfo(network).rpc;\n}\n\nexport function getP2pSeeds(network: NetworkSlug | string): readonly P2pSeed[] {\n return getChainInfo(network).p2p;\n}\n\nexport function getNoEvmReceiptTrustPolicy(\n network: NetworkSlug | string,\n registry: ChainRegistry = CHAIN_REGISTRY,\n): NoEvmReceiptTrustPolicy | null {\n const info = registry[network];\n if (!info) {\n throw new Error(`unknown Monolythium network: ${network}`);\n }\n return noEvmReceiptTrustPolicyFromChainInfo(info);\n}\n\nexport function noEvmReceiptTrustPolicyFromChainInfo(\n info: ChainInfo,\n): NoEvmReceiptTrustPolicy | null {\n const trust = info.receipt_proof_trust;\n if (trust == null || (trust.archive == null && trust.finality == null)) return null;\n\n const policy: NoEvmReceiptTrustPolicy = { chainId: info.chain_id };\n if (trust.archive != null) {\n policy.archive = {\n threshold: assertSafeIntegerAtLeast(\n trust.archive.signature_threshold,\n 1,\n \"receipt_proof_trust.archive.signature_threshold\",\n ),\n validFromHeight: trust.archive.valid_from_height,\n validToHeight: trust.archive.valid_to_height,\n trustedSigners: trust.archive.signers.map((signer, index) => ({\n publicKey: decodeFixedHex(\n signer.public_key,\n ML_DSA_65_PUBLIC_KEY_LEN,\n `receipt_proof_trust.archive.signers[${index}].public_key`,\n ),\n signerId: signer.signer_id,\n validFromHeight: signer.valid_from_height,\n validToHeight: signer.valid_to_height,\n })),\n };\n }\n if (trust.finality != null) {\n const threshold = assertSafeIntegerAtLeast(\n trust.finality.threshold,\n 1,\n \"receipt_proof_trust.finality.threshold\",\n );\n const chainId = trust.finality.chain_id ?? info.chain_id;\n if (trust.finality.mode === \"cluster\") {\n if (trust.finality.cluster_public_key == null) {\n throw new Error(\n \"receipt_proof_trust.finality.cluster_public_key is required for cluster mode\",\n );\n }\n policy.finality = {\n mode: \"cluster\",\n chainId,\n threshold,\n validFromRound: trust.finality.valid_from_round,\n validToRound: trust.finality.valid_to_round,\n committeeSize: assertSafeIntegerAtLeast(\n trust.finality.committee_size,\n 1,\n \"receipt_proof_trust.finality.committee_size\",\n ),\n clusterPublicKey: decodeFixedHex(\n trust.finality.cluster_public_key,\n BLS_PUBLIC_KEY_BYTE_LENGTH,\n \"receipt_proof_trust.finality.cluster_public_key\",\n ),\n };\n } else if (trust.finality.mode === \"multisig\") {\n const signers = trust.finality.signers ?? [];\n policy.finality = {\n mode: \"multisig\",\n chainId,\n threshold,\n validFromRound: trust.finality.valid_from_round,\n validToRound: trust.finality.valid_to_round,\n trustedSigners: signers.map((signer, index) => ({\n authorityIndex: assertSafeIntegerAtLeast(\n signer.authority_index,\n 0,\n `receipt_proof_trust.finality.signers[${index}].authority_index`,\n ),\n publicKey: decodeFixedHex(\n signer.public_key,\n BLS_PUBLIC_KEY_BYTE_LENGTH,\n `receipt_proof_trust.finality.signers[${index}].public_key`,\n ),\n validFromRound: signer.valid_from_round,\n validToRound: signer.valid_to_round,\n })),\n };\n } else {\n throw new Error(\n `unsupported receipt_proof_trust.finality.mode: ${String(trust.finality.mode)}`,\n );\n }\n }\n\n return policy;\n}\n\nexport interface FetchChainRegistryOptions {\n fetch?: typeof fetch;\n rawBaseUrl?: string;\n}\n\nexport async function fetchChainInfoLatest(\n network: NetworkSlug | string,\n options: FetchChainRegistryOptions = {},\n): Promise<ChainInfo> {\n const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n const rawBaseUrl = options.rawBaseUrl ?? CHAIN_REGISTRY_RAW_BASE;\n const resp = await fetchImpl(`${rawBaseUrl}/${network}.toml`);\n if (!resp.ok) {\n throw new Error(`failed to fetch chain registry ${network}: HTTP ${resp.status}`);\n }\n return parseChainRegistryToml(await resp.text());\n}\n\nexport async function fetchChainRegistryLatest(\n networks: readonly (NetworkSlug | string)[] = [\"testnet-69420\"],\n options: FetchChainRegistryOptions = {},\n): Promise<ChainRegistry> {\n const entries = await Promise.all(\n networks.map(async (network) => [network, await fetchChainInfoLatest(network, options)] as const),\n );\n return Object.fromEntries(entries);\n}\n\nexport function parseChainRegistryToml(input: string): ChainInfo {\n const info: Partial<ChainInfo> & {\n rpc: RpcEndpoint[];\n p2p: P2pSeed[];\n explorer: ExplorerEndpoint[];\n receipt_proof_trust?: ReceiptProofTrustPolicy;\n } = {\n rpc: [],\n p2p: [],\n explorer: [],\n };\n let section:\n | \"root\"\n | \"rpc\"\n | \"p2p\"\n | \"explorer\"\n | \"receipt_proof_trust.archive\"\n | \"receipt_proof_trust.archive.signers\"\n | \"receipt_proof_trust.finality\"\n | \"receipt_proof_trust.finality.signers\" = \"root\";\n for (const rawLine of input.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\s+#.*$/, \"\").trim();\n if (!line || line.startsWith(\"#\")) continue;\n if (line === \"[[rpc]]\") {\n section = \"rpc\";\n info.rpc.push({ url: \"\", provider: \"\", tier: \"community\" });\n continue;\n }\n if (line === \"[[p2p]]\") {\n section = \"p2p\";\n info.p2p.push({ multiaddr: \"\" });\n continue;\n }\n if (line === \"[[explorer]]\") {\n section = \"explorer\";\n info.explorer.push({ url: \"\", name: \"\" });\n continue;\n }\n if (line === \"[receipt_proof_trust.archive]\") {\n section = \"receipt_proof_trust.archive\";\n ensureReceiptProofTrust(info).archive ??= { signature_threshold: 0, signers: [] };\n continue;\n }\n if (line === \"[[receipt_proof_trust.archive.signers]]\") {\n section = \"receipt_proof_trust.archive.signers\";\n const trust = ensureReceiptProofTrust(info);\n trust.archive ??= { signature_threshold: 0, signers: [] };\n trust.archive.signers.push({ public_key: \"\" });\n continue;\n }\n if (line === \"[receipt_proof_trust.finality]\") {\n section = \"receipt_proof_trust.finality\";\n ensureReceiptProofTrust(info).finality ??= {\n mode: \"cluster\",\n threshold: 0,\n };\n continue;\n }\n if (line === \"[[receipt_proof_trust.finality.signers]]\") {\n section = \"receipt_proof_trust.finality.signers\";\n const trust = ensureReceiptProofTrust(info);\n trust.finality ??= {\n mode: \"multisig\",\n threshold: 0,\n signers: [],\n };\n trust.finality.signers ??= [];\n trust.finality.signers.push({ authority_index: 0, public_key: \"\" });\n continue;\n }\n const match = /^([A-Za-z0-9_]+)\\s*=\\s*(.+)$/.exec(line);\n if (!match) continue;\n const [, key, rawValue] = match;\n const value = parseTomlScalar(rawValue);\n if (section === \"root\") {\n (info as Record<string, unknown>)[key] = value;\n } else if (section === \"rpc\" || section === \"p2p\" || section === \"explorer\") {\n const list = info[section];\n const target = list[list.length - 1] as unknown as Record<string, unknown>;\n target[key] = value;\n } else if (section === \"receipt_proof_trust.archive\") {\n const trust = ensureReceiptProofTrust(info);\n trust.archive ??= { signature_threshold: 0, signers: [] };\n (trust.archive as unknown as Record<string, unknown>)[key] = value;\n } else if (section === \"receipt_proof_trust.archive.signers\") {\n const archive = ensureReceiptProofTrust(info).archive ??= {\n signature_threshold: 0,\n signers: [],\n };\n const target = archive.signers[archive.signers.length - 1] as unknown as Record<\n string,\n unknown\n >;\n target[key] = value;\n } else if (section === \"receipt_proof_trust.finality\") {\n const trust = ensureReceiptProofTrust(info);\n trust.finality ??= { mode: \"cluster\", threshold: 0 };\n (trust.finality as unknown as Record<string, unknown>)[key] = value;\n } else {\n const finality = ensureReceiptProofTrust(info).finality ??= {\n mode: \"multisig\",\n threshold: 0,\n signers: [],\n };\n finality.signers ??= [];\n const target = finality.signers[finality.signers.length - 1] as unknown as Record<\n string,\n unknown\n >;\n target[key] = value;\n }\n }\n if (!info.network || !info.chain_id || !info.genesis_hash || !info.binary_sha) {\n throw new Error(\"chain registry TOML is missing required top-level fields\");\n }\n if (info.rpc.length === 0 || info.rpc.some((r) => !r.url || !r.provider || !r.tier)) {\n throw new Error(\"chain registry TOML must include at least one complete rpc endpoint\");\n }\n if (info.p2p.length === 0 || info.p2p.some((p) => !p.multiaddr)) {\n throw new Error(\"chain registry TOML must include at least one p2p seed\");\n }\n const out: ChainInfo = {\n chain_id: Number(info.chain_id),\n network: String(info.network),\n display_name: info.display_name ? String(info.display_name) : undefined,\n description: info.description ? String(info.description) : undefined,\n genesis_hash: String(info.genesis_hash),\n binary_sha: String(info.binary_sha),\n rpc: info.rpc,\n p2p: info.p2p,\n };\n if (info.explorer.length > 0) out.explorer = info.explorer;\n if (info.receipt_proof_trust) {\n out.receipt_proof_trust = normalizeReceiptProofTrust(info.receipt_proof_trust);\n }\n return out;\n}\n\nfunction parseTomlScalar(raw: string): string | number | boolean {\n const value = raw.trim();\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n }\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (/^-?\\d+$/.test(value)) return Number(value);\n return value;\n}\n\nfunction ensureReceiptProofTrust(\n info: Partial<ChainInfo> & { receipt_proof_trust?: ReceiptProofTrustPolicy },\n): ReceiptProofTrustPolicy {\n info.receipt_proof_trust ??= {};\n return info.receipt_proof_trust;\n}\n\nfunction normalizeReceiptProofTrust(trust: ReceiptProofTrustPolicy): ReceiptProofTrustPolicy {\n const out: ReceiptProofTrustPolicy = {};\n if (trust.archive == null || trust.finality == null) {\n throw new Error(\"receipt_proof_trust must include both archive and finality policies\");\n }\n if (trust.archive != null) {\n const threshold = assertSafeIntegerAtLeast(\n trust.archive.signature_threshold,\n 1,\n \"receipt_proof_trust.archive.signature_threshold\",\n );\n if (trust.archive.signers.length === 0 || trust.archive.signers.some((s) => !s.public_key)) {\n throw new Error(\"receipt_proof_trust.archive.signers must contain complete signer rows\");\n }\n if (threshold > trust.archive.signers.length) {\n throw new Error(\"receipt_proof_trust.archive.signature_threshold exceeds signer count\");\n }\n assertOptionalRange(\n trust.archive.valid_from_height,\n trust.archive.valid_to_height,\n \"receipt_proof_trust.archive\",\n );\n assertUniqueStrings(\n trust.archive.signers.map((signer) => signer.public_key),\n \"receipt_proof_trust.archive.signers.public_key\",\n );\n assertUniqueStrings(\n trust.archive.signers.flatMap((signer) => (signer.signer_id ? [signer.signer_id] : [])),\n \"receipt_proof_trust.archive.signers.signer_id\",\n );\n out.archive = {\n signature_threshold: threshold,\n valid_from_height: optionalSafeInteger(trust.archive.valid_from_height),\n valid_to_height: optionalSafeInteger(trust.archive.valid_to_height),\n signers: trust.archive.signers.map((signer) => {\n assertOptionalRange(\n signer.valid_from_height,\n signer.valid_to_height,\n \"receipt_proof_trust.archive.signers\",\n );\n return {\n public_key: assertString(\n signer.public_key,\n \"receipt_proof_trust.archive.signers.public_key\",\n ),\n signer_id: optionalString(signer.signer_id),\n valid_from_height: optionalSafeInteger(signer.valid_from_height),\n valid_to_height: optionalSafeInteger(signer.valid_to_height),\n notes: optionalString(signer.notes),\n };\n }),\n };\n }\n if (trust.finality != null) {\n const mode = trust.finality.mode;\n if (mode !== \"cluster\" && mode !== \"multisig\") {\n throw new Error(`unsupported receipt_proof_trust.finality.mode: ${String(mode)}`);\n }\n const finality: ReceiptProofTrustFinalityPolicy = {\n mode,\n chain_id: optionalSafeInteger(trust.finality.chain_id),\n threshold: assertSafeIntegerAtLeast(\n trust.finality.threshold,\n 1,\n \"receipt_proof_trust.finality.threshold\",\n ),\n valid_from_round: optionalSafeInteger(trust.finality.valid_from_round),\n valid_to_round: optionalSafeInteger(trust.finality.valid_to_round),\n };\n assertOptionalRange(\n trust.finality.valid_from_round,\n trust.finality.valid_to_round,\n \"receipt_proof_trust.finality\",\n );\n if (mode === \"cluster\") {\n finality.committee_size = assertSafeIntegerAtLeast(\n trust.finality.committee_size,\n 1,\n \"receipt_proof_trust.finality.committee_size\",\n );\n if (finality.threshold > finality.committee_size) {\n throw new Error(\"receipt_proof_trust.finality.threshold exceeds committee_size\");\n }\n finality.cluster_public_key = assertString(\n trust.finality.cluster_public_key,\n \"receipt_proof_trust.finality.cluster_public_key\",\n );\n if ((trust.finality.signers ?? []).length > 0) {\n throw new Error(\"receipt_proof_trust.finality.signers are invalid in cluster mode\");\n }\n } else {\n const signers = trust.finality.signers ?? [];\n if (signers.length === 0 || signers.some((s) => !s.public_key)) {\n throw new Error(\"receipt_proof_trust.finality.signers must contain complete signer rows\");\n }\n if (finality.threshold > signers.length) {\n throw new Error(\"receipt_proof_trust.finality.threshold exceeds signer count\");\n }\n if (trust.finality.committee_size != null || trust.finality.cluster_public_key != null) {\n throw new Error(\"receipt_proof_trust.finality cluster fields are invalid in multisig mode\");\n }\n assertUniqueNumbers(\n signers.map((signer) => signer.authority_index),\n \"receipt_proof_trust.finality.signers.authority_index\",\n );\n assertUniqueStrings(\n signers.map((signer) => signer.public_key),\n \"receipt_proof_trust.finality.signers.public_key\",\n );\n finality.signers = signers.map((signer) => {\n assertOptionalRange(\n signer.valid_from_round,\n signer.valid_to_round,\n \"receipt_proof_trust.finality.signers\",\n );\n return {\n authority_index: assertSafeIntegerAtLeast(\n signer.authority_index,\n 0,\n \"receipt_proof_trust.finality.signers.authority_index\",\n ),\n public_key: assertString(\n signer.public_key,\n \"receipt_proof_trust.finality.signers.public_key\",\n ),\n valid_from_round: optionalSafeInteger(signer.valid_from_round),\n valid_to_round: optionalSafeInteger(signer.valid_to_round),\n notes: optionalString(signer.notes),\n };\n });\n }\n out.finality = finality;\n }\n return out;\n}\n\nfunction decodeFixedHex(value: string, expectedLength: number, field: string): Uint8Array {\n const bytes = hexToBytes(assertString(value, field), field);\n if (bytes.length !== expectedLength) {\n throw new Error(`${field} must be ${expectedLength} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\nfunction assertString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`${field} must be a non-empty string`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return value === undefined ? undefined : assertString(value, \"optional string field\");\n}\n\nfunction optionalSafeInteger(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || Number(value) < 0) {\n throw new Error(\"optional integer field must be a non-negative safe integer\");\n }\n return Number(value);\n}\n\nfunction assertSafeIntegerAtLeast(value: unknown, min: number, field: string): number {\n if (!Number.isSafeInteger(value) || Number(value) < min) {\n throw new Error(`${field} must be a safe integer >= ${min}`);\n }\n return Number(value);\n}\n\nfunction assertOptionalRange(from: unknown, to: unknown, field: string): void {\n const start = optionalSafeInteger(from);\n const end = optionalSafeInteger(to);\n if (start != null && end != null && end < start) {\n throw new Error(`${field} valid_to must be >= valid_from`);\n }\n}\n\nfunction assertUniqueStrings(values: readonly string[], field: string): void {\n const seen = new Set<string>();\n for (const value of values) {\n const normalized = assertString(value, field).toLowerCase();\n if (seen.has(normalized)) {\n throw new Error(`${field} values must be unique`);\n }\n seen.add(normalized);\n }\n}\n\nfunction assertUniqueNumbers(values: readonly number[], field: string): void {\n const seen = new Set<number>();\n for (const value of values) {\n const normalized = assertSafeIntegerAtLeast(value, 0, field);\n if (seen.has(normalized)) {\n throw new Error(`${field} values must be unique`);\n }\n seen.add(normalized);\n }\n}\n","/**\n * Wire-shape types served by a `mono-core` node.\n *\n * Re-exports the `ts-rs`-generated definitions in `./bindings/`. Those\n * files are the authoritative source — they are written from Rust by\n * `cargo test --features ts-bindings` and copied into this package via\n * `pnpm run build:bindings` / `bash scripts/sync-bindings.sh`.\n *\n * Quantities (`u64` etc.) surface as `bigint` to preserve full\n * precision against the chain's 256-bit world. Hashes / addresses /\n * `0x`-hex byte vectors surface as `string`.\n */\n\nexport type * from \"./bindings/index.js\";\n\n/** `0x`-prefixed hex byte vector. */\nexport type Hex = string;\n\n/** `0x`-prefixed hex 20-byte address. */\nexport type Address = string;\n\n/** `0x`-prefixed hex 32-byte hash. */\nexport type Hash = string;\n\n/** `0x`-prefixed hex unsigned quantity. */\nexport type Quantity = string;\n\nimport type { BlockTag } from \"./bindings/BlockTag.js\";\nexport type { BlockTag };\n\n/**\n * Block selector for `eth_getBlock*`, `eth_call`, etc. — accepts a tag,\n * a numeric height (encoded by the client as `0x`-hex), a `bigint`, or\n * a 32-byte hash where the spec allows it.\n */\nexport type BlockSelector = BlockTag | number | bigint | Hash;\n\n/** Encode a `BlockSelector` for a JSON-RPC params array. */\nexport function encodeBlockSelector(b: BlockSelector): string {\n if (typeof b === \"number\") return `0x${b.toString(16)}`;\n if (typeof b === \"bigint\") return `0x${b.toString(16)}`;\n return b;\n}\n","/**\n * Typed JSON-RPC client for a `mono-core` node.\n *\n * Mirrors the Rust SDK's `RpcClient` — every public method maps 1:1 to\n * a method on the Rust client, returns the same wire-shape value, and\n * sends the same `lyth_*` / `eth_*` / `debug_*` JSON-RPC method strings\n * (Law §13.2).\n */\n\nimport {\n requireTypedAddress,\n type AddressKind,\n} from \"./address.js\";\nimport { SdkError } from \"./error.js\";\nimport type { BridgeRouteDisclosure, BridgeRoutesRequest, BridgeRoutesResponse } from \"./bridge.js\";\nimport {\n nativeEventsFromHistory,\n nativeEventsFromReceipt,\n nativeMarketEventsFromHistory,\n nativeMarketEventsFromReceipt,\n} from \"./native-events.js\";\nimport {\n isConcreteServiceProbeStatus,\n isSinglePublicServiceProbeMask,\n isValidPublicServiceProbeMask,\n} from \"./node-registry.js\";\nimport { assertMrvStructuredFeeConformance } from \"./mrv.js\";\nimport { getChainInfo, type ChainInfo, type ChainRegistry, type NetworkSlug } from \"./registry.js\";\nimport type {\n AccountPolicy,\n AccountProofResponse,\n AddressActivityEntry,\n AddressActivityKindResponse,\n AddressLabelRecord,\n AssetPolicy,\n BlsCertificateResponse,\n BlockHeader,\n CallRequest,\n CapabilitiesResponse,\n CheckpointRecord,\n ClobMarketResponse,\n ClusterDelegatorsResponse,\n ClusterEntityResponse,\n ClusterResignationsResponse,\n DagParentsResponse,\n DagSyncStatus,\n DecodeTxResponse,\n DelegationCapResponse,\n DelegationHistoryRecord,\n DelegationsResponse,\n EncryptionKeyResponse,\n EntityRatchetResponse,\n FeeHistoryResponse,\n GapRecordsResponse,\n IndexerStatus,\n MempoolSnapshot,\n MeshDecodedTx,\n MeshSignedTxResponse,\n MeshTxIntent,\n MeshUnsignedTxResponse,\n MrcAccountRequest,\n MrcAccountResponse,\n MrcHoldersRequest,\n MrcHoldersResponse,\n MrcMetadataResponse,\n PeerSummary,\n PendingRewardsResponse,\n PendingTxSummary,\n PrecompileDescriptor,\n RedemptionQueueResponse,\n RegistryRecord,\n RichListResponse,\n RoundInfo,\n StorageProofBatch,\n SyncStatus,\n TpmAttestationResponse,\n TransactionReceipt,\n TransactionView,\n TokenBalanceMrcIdentity,\n TokenBalanceRecord,\n} from \"./bindings/index.js\";\nimport type { BlockSelector } from \"./types.js\";\nimport { encodeBlockSelector } from \"./types.js\";\nimport type { ApiStreamTopic } from \"./streams.js\";\nimport type {\n NativeDecodedEvent,\n NativeEventFilter,\n TypedNativeReceiptEvent,\n} from \"./native-events.js\";\n\n/** Optional per-client configuration. */\nexport interface RpcClientOptions {\n /** Override `fetch`. Useful for tests or non-Node environments. */\n fetch?: typeof fetch;\n /** Extra headers to attach to every request. */\n headers?: Record<string, string>;\n}\n\nexport interface NetworkClientOptions extends RpcClientOptions {\n /** Registry snapshot to use instead of the SDK-bundled snapshot. */\n registry?: ChainRegistry;\n /** Probe all known endpoints and choose the first one that answers. */\n probe?: boolean;\n}\n\n/** Typed ADR-0038 user address (`mono1...`) accepted at public SDK boundaries. */\nexport type UserAddressInput = string;\n\nexport interface TxFeedReceipt {\n status: number;\n executionUnitsUsed: number;\n logsCount: number;\n}\n\nexport interface TxFeedTransaction {\n txHash: string;\n blockHash: string;\n blockNumber: number;\n blockTimestamp: number | null;\n txIndex: number;\n from: string;\n to: string | null;\n nonce: number;\n /** Native value in lythoshi. The tx-feed wire key is still `value`. */\n value: string;\n executionUnitLimit: number;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n fee: NativeReceiptFee;\n input: string;\n receipt: TxFeedReceipt | null;\n}\n\nexport interface TxFeedResponse {\n schemaVersion: number;\n latestHeight: number;\n limit: number;\n nextCursor: string | null;\n transactions: TxFeedTransaction[];\n}\n\nexport const MAX_NATIVE_RECEIPT_EVENTS = 1_000;\n\nexport interface NativeReceiptCounters {\n cycles: number;\n syscallUnits: number;\n stateIoUnits: number;\n}\n\nexport interface NativeReceiptFee {\n total_lythoshi: string;\n total_lyth?: string;\n cycles_used: number;\n base_price_per_cycle_lythoshi: string;\n state_io_units: number;\n state_io_price_per_unit_lythoshi: string;\n priority_tip_lythoshi: string;\n}\n\nexport interface NativeReceiptEvent<TDecoded = unknown> {\n blockHeight: number;\n txIndex: number;\n logIndex: number;\n address: string;\n eventTopic: string;\n decoded: TDecoded;\n decodedJson: string;\n}\n\nexport interface NativeReceiptSource {\n chainProvider: string;\n indexerProvider: string;\n metadataLogIndex: number;\n}\n\nexport interface NoEvmCompactInclusionProof {\n schema: \"mono.no_evm_receipt_compact_inclusion.v1\";\n treeAlgorithm: \"binary-keccak-receipt-tree\";\n root: string;\n leafHash: string;\n siblingHashes: string[];\n pathSides: boolean[];\n}\n\nexport interface NoEvmArchiveProof {\n schema: \"mono.no_evm_receipt_archive_binding.v1\";\n source: \"indexerReceiptArchiveContentDigest\" | string;\n manifestHash: string;\n contentHash: string;\n signatureDigest?: string | null;\n signatures: string[];\n coveringSnapshot?: NoEvmArchiveCoveringSnapshot | null;\n}\n\nexport interface NoEvmArchiveCoveringSnapshot {\n snapshotHeight: number;\n manifestHash: string;\n signatureDigest: string;\n contentHash: string;\n checkpointContentHash: string;\n checkpointFrom: number;\n checkpointTo: number;\n signatures: string[];\n}\n\nexport interface NoEvmFinalityCertificate {\n round: number;\n signature: string;\n signersBitmap: string;\n signerIndices: number[];\n signerCount: number;\n}\n\nexport interface NoEvmFinalityBlockReference {\n round: number;\n authority: number;\n digest: string;\n}\n\nexport interface NoEvmFinalityEvidence {\n schema: \"mono.no_evm_receipt_finality.v1\";\n source: \"blsRoundCertificate\" | string;\n round: number;\n certificate: NoEvmFinalityCertificate;\n blockReference?: NoEvmFinalityBlockReference | null;\n leaderCertificate?: NoEvmFinalityCertificate | null;\n dacCertificate?: NoEvmFinalityCertificate | null;\n}\n\ninterface NoEvmReceiptProofBase {\n schema: \"mono.no_evm_receipt_proof.v1\";\n rootAlgorithm: string;\n receiptCodec: \"bincode(protocore_evm::Receipt)\";\n blockHash: string;\n txHash: string;\n receiptsRoot: string;\n targetReceiptHash: string;\n blockHeight: number;\n txIndex: number;\n receiptCount: number;\n finalityEvidence?: NoEvmFinalityEvidence | null;\n}\n\nexport interface NoEvmBoundedReceiptProof extends NoEvmReceiptProofBase {\n proofKind?: \"boundedCacheTranscript\";\n proofType: \"canonicalReceiptsTranscript\";\n historySource?: \"legacyUnspecified\" | \"liveBlockCache\";\n compactInclusionProof?: null;\n archiveProof?: null;\n missingProofMaterial?: string[];\n receiptTranscript: string[];\n}\n\nexport interface NoEvmCompactReceiptProof extends NoEvmReceiptProofBase {\n proofKind: \"compactInclusion\";\n proofType: \"canonicalReceiptInclusion\";\n historySource: \"liveBlockCache\" | \"indexerReceiptArchive\";\n compactInclusionProof: NoEvmCompactInclusionProof;\n archiveProof?: NoEvmArchiveProof | null;\n missingProofMaterial?: string[];\n targetReceiptBytes: string;\n receiptTranscript?: string[];\n}\n\nexport type NoEvmReceiptProof = NoEvmBoundedReceiptProof | NoEvmCompactReceiptProof;\n\nexport interface NativeReceiptResponse<TDecoded = unknown> {\n txHash: string;\n blockHash: string;\n blockHeight: number;\n txIndex: number;\n schema: string;\n artifactHash: string;\n receiptCommitment: string;\n /** Current nodes may return `null`; older nodes may omit the field. */\n noEvmProof?: NoEvmReceiptProof | null;\n counters: NativeReceiptCounters;\n fee: NativeReceiptFee;\n reverted: boolean;\n nativeDeltaCount: number;\n eventCount: number;\n events: Array<NativeReceiptEvent<TDecoded>>;\n source: NativeReceiptSource;\n}\n\n/** Filter object passed to `lyth_nativeEvents` and `/api/v1/native-events`. */\nexport interface NativeEventsFilter {\n fromBlock: number | bigint | string;\n toBlock: number | bigint | string;\n limit?: number | bigint | string | null;\n txIndex?: number | bigint | string | null;\n logIndex?: number | bigint | string | null;\n address?: string | null;\n eventTopic?: string | null;\n family?: string | null;\n eventName?: string | null;\n primaryId?: string | null;\n relatedId?: string | null;\n tokenId?: string | null;\n account?: string | null;\n counterparty?: string | null;\n}\n\nexport interface NativeEventsResponseFilters {\n txIndex?: number | null;\n logIndex?: number | null;\n address?: string | null;\n eventTopic?: string | null;\n family?: string | null;\n eventName?: string | null;\n primaryId?: string | null;\n relatedId?: string | null;\n tokenId?: string | null;\n account?: string | null;\n counterparty?: string | null;\n}\n\nexport interface NativeEventsSource {\n indexerProvider: string;\n}\n\nexport interface NativeEventsResponse<TDecoded = unknown> {\n schemaVersion: number;\n fromBlock: number;\n toBlock: number;\n limit: number;\n filters: NativeEventsResponseFilters;\n events: Array<NativeReceiptEvent<TDecoded>>;\n source: NativeEventsSource;\n}\n\n/** Filter object passed to `lyth_nativeAgentState` and `/api/v1/native-agent-state`. */\nexport interface NativeAgentStateFilter {\n policyId?: string | null;\n escrowId?: string | null;\n account?: string | null;\n includePolicySpends?: boolean | null;\n limit?: number | bigint | string | null;\n}\n\nexport interface NativeAgentStateResponseFilters {\n policyId?: string | null;\n escrowId?: string | null;\n account?: string | null;\n includePolicySpends: boolean;\n}\n\nexport interface NativeAgentStateSource {\n indexerProvider: string;\n projection: string;\n}\n\nexport interface NativeAgentPolicyStateRecord {\n policyId: string;\n owner: string;\n controller: string;\n assetId: string;\n /** Owner/controller-local policy nonce; omitted by older nodes. */\n nonce?: number | null;\n enabled: boolean;\n perActionLimit: string;\n windowLimit: string;\n windowSecs: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentPolicySpendStateRecord {\n policyId: string;\n controller: string;\n assetId: string;\n window: number;\n amount: string;\n spent: string;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentEscrowStateRecord {\n escrowId: string;\n buyer: string;\n provider: string;\n arbiter: string;\n assetId: string;\n /** Buyer-local escrow nonce; omitted by older nodes. */\n nonce?: number | null;\n amount: string;\n termsHash: string;\n round: number;\n buyerAccepted: boolean;\n providerAccepted: boolean;\n submittedPayloadHash?: string | null;\n status: string;\n resolution?: string | null;\n lastActor?: string | null;\n createdAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentIssuerStateRecord {\n issuerId: string;\n issuer: string;\n /** Issuer-local nonce; omitted by older nodes. */\n nonce?: number | null;\n metadataHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentAttestationStateRecord {\n attestationId: string;\n /** Issuer-local attestation nonce; omitted by older nodes. */\n nonce?: number | null;\n issuerId?: string | null;\n issuer?: string | null;\n subject: string;\n schemaHash?: string | null;\n payloadHash?: string | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentConsentStateRecord {\n consentId: string;\n subject: string;\n grantee: string;\n /** Subject-local consent nonce; omitted by older nodes. */\n nonce?: number | null;\n scopeHash?: string | null;\n expiresAt?: number | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentServiceStateRecord {\n serviceId: string;\n provider: string;\n /** Provider-local service nonce; omitted by older nodes. */\n nonce?: number | null;\n categoryHash?: string | null;\n metadataHash?: string | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentAvailabilityStateRecord {\n provider: string;\n maxConcurrent: number;\n openRequests: number;\n paused: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentArbiterStateRecord {\n arbiterId: string;\n arbiter: string;\n /** Arbiter-local registration nonce; omitted by older nodes. */\n nonce?: number | null;\n tier?: number | null;\n metadataHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentReputationReviewStateRecord {\n reviewId: string;\n reviewer: string;\n subject: string;\n categoryId: number;\n speedScore: number;\n qualityScore: number;\n communicationScore: number;\n accuracyScore: number;\n payloadHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentStateResponse {\n schemaVersion: number;\n limit: number;\n filters: NativeAgentStateResponseFilters;\n issuers: NativeAgentIssuerStateRecord[];\n attestations: NativeAgentAttestationStateRecord[];\n consents: NativeAgentConsentStateRecord[];\n services: NativeAgentServiceStateRecord[];\n availability: NativeAgentAvailabilityStateRecord[];\n arbiters: NativeAgentArbiterStateRecord[];\n reputationReviews: NativeAgentReputationReviewStateRecord[];\n spendingPolicies: NativeAgentPolicyStateRecord[];\n policySpends: NativeAgentPolicySpendStateRecord[];\n escrows: NativeAgentEscrowStateRecord[];\n source: NativeAgentStateSource;\n}\n\nexport type NativeAgentStateFilterParamValue = string | number | boolean;\n\n/** Filter object passed to `lyth_nativeMarketState` and `/api/v1/native-market-state`. */\nexport interface NativeMarketStateFilter {\n marketId?: string | null;\n orderId?: string | null;\n listingId?: string | null;\n collectionId?: string | null;\n account?: string | null;\n includeSpotOrders?: boolean | null;\n limit?: number | bigint | string | null;\n}\n\nexport interface NativeMarketStateResponseFilters {\n marketId?: string | null;\n orderId?: string | null;\n listingId?: string | null;\n collectionId?: string | null;\n account?: string | null;\n includeSpotOrders: boolean;\n}\n\nexport interface NativeMarketStateSource {\n indexerProvider: string;\n projection: string;\n}\n\nexport interface NativeSpotMarketStateRecord {\n marketId: string;\n owner: string;\n baseAssetId: string;\n quoteAssetId: string;\n tickSize: string;\n lotSize: string;\n minQuantity: string;\n minNotional: string;\n tradeCount: string;\n totalVolumeBase: string;\n lastPrice: string | null;\n lastBlockHeight: number | null;\n createdAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeSpotOrderStateRecord {\n orderId: string;\n marketId: string;\n owner: string;\n /** Owner-local spot order nonce; omitted by older nodes. */\n nonce?: number | null;\n side: string;\n price: string;\n quantity: string;\n remaining: string;\n status: string;\n expiresAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeNftListingStateRecord {\n listingId: string;\n seller: string;\n /** Seller-local NFT listing nonce; omitted by older nodes. */\n nonce?: number | null;\n standard: string;\n collectionId: string;\n tokenId: string;\n quantity: string;\n paymentAssetId: string;\n price: string;\n listingKind: unknown;\n status: string;\n expiresAtBlock: number;\n highestBidder: string | null;\n highestBid: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeCollectionRoyaltyStateRecord {\n collectionId: string;\n creator: string | null;\n recipient: string;\n bps: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeMarketStateResponse {\n schemaVersion: number;\n limit: number;\n filters: NativeMarketStateResponseFilters;\n spotMarkets: NativeSpotMarketStateRecord[];\n spotOrders: NativeSpotOrderStateRecord[];\n nftListings: NativeNftListingStateRecord[];\n collectionRoyalties: NativeCollectionRoyaltyStateRecord[];\n source: NativeMarketStateSource;\n}\n\nexport type NativeMarketStateFilterParamValue = string | number | boolean;\n\nexport type AgentReputationCategoryScope = \"global\" | \"category\";\n\nexport interface AgentReputationRecord {\n provider: string;\n categoryId: number;\n blockHeight: number;\n speedSumX10: number;\n qualitySumX10: number;\n communicationSumX10: number;\n accuracySumX10: number;\n sampleCount: number;\n avgSpeedX10: number;\n avgQualityX10: number;\n avgCommunicationX10: number;\n avgAccuracyX10: number;\n}\n\nexport interface AgentReputationResponse {\n schemaVersion: 1;\n provider: string;\n categoryId: number;\n categoryScope: AgentReputationCategoryScope;\n record: AgentReputationRecord | null;\n}\n\nexport interface AddressProfileResponse {\n schemaVersion: number;\n address: string;\n account: {\n nativeBalance: string;\n nonce: number;\n codeHash: string;\n isContract: boolean;\n };\n label: {\n category: string;\n displayName: string | null;\n updatedAtBlock: number;\n } | null;\n activity: {\n kind: string;\n retention: unknown | null;\n latest: unknown | null;\n };\n tokenBalances: Array<{\n tokenId: string;\n balance: string;\n updatedAtBlock: number;\n mrc?: TokenBalanceMrcIdentity | null;\n }>;\n bridgeRouteDisclosures?: BridgeRouteDisclosure[] | null;\n}\n\nexport interface AddressFlowResponse {\n schemaVersion: number;\n address: string;\n sampleSize: number;\n limit: number;\n totals: {\n inbound: string;\n outbound: string;\n swapVolume: string;\n stake: string;\n unstake: string;\n };\n topCounterparties: Array<{\n address: string;\n eventCount: number;\n inbound: string;\n outbound: string;\n }>;\n}\n\nexport interface SearchHit {\n type: string;\n id: string;\n route: string;\n label: string;\n score: number;\n meta?: unknown;\n}\n\nexport interface SearchResponse {\n schemaVersion: number;\n query: string;\n hits: SearchHit[];\n nextCursor: string | null;\n}\n\nexport interface ChainStatsResponse {\n schemaVersion: number;\n chainId: number;\n genesisHash: string | null;\n latestHeight: number;\n latestBlockHash: string | null;\n latestTimestamp: number | null;\n peerCount: number;\n mempool: {\n ready: number;\n pending: number;\n mailboxDepth: number;\n };\n indexer: unknown | null;\n clusters: {\n total: number;\n pageSize: number;\n };\n}\n\nexport interface ClobMarketSummary {\n marketId: string;\n tradeCount: number;\n totalVolumeBase: string;\n lastPrice: string;\n lastBlockHeight: number;\n}\n\nexport interface ClobMarketsResponse {\n schemaVersion: number;\n limit: number;\n markets: ClobMarketSummary[];\n source: string;\n}\n\nexport interface ClobTrade {\n blockHeight: number;\n txIndex: number;\n logIndex: number;\n marketId: string;\n takerOrder: string;\n makerOrder: string;\n price: string;\n amount: string;\n taker: string;\n maker: string;\n}\n\nexport interface ClobTradesResponse {\n schemaVersion: number;\n marketId: string;\n limit: number;\n nextCursor: string | null;\n trades: ClobTrade[];\n}\n\nexport interface ClobOhlcResponse {\n schemaVersion: number;\n marketId: string;\n fromBlock: number;\n toBlock: number;\n bucketBlocks: number;\n candles: Array<{\n startBlock: number;\n endBlock: number;\n open: string;\n high: string;\n low: string;\n close: string;\n volumeBase: string;\n tradeCount: number;\n }>;\n}\n\nexport interface ClobOrderBookResponse {\n schemaVersion: number;\n marketId: string;\n levels?: number;\n bids: Array<{ price: string; size: string }>;\n asks: Array<{ price: string; size: string }>;\n}\n\n/** Public-safe aggregate returned by `lyth_peerSummary`. */\nexport interface PeerSummaryAggregate {\n peerCount: number;\n inboundCount: number | null;\n outboundCount: number | null;\n latencyBands: {\n lt_50ms: number;\n lt_200ms: number;\n lt_1s: number;\n ge_1s: number;\n } | null;\n versionDistribution: Record<string, number>;\n healthSummary: {\n synced: number;\n lagging: number;\n stale: number;\n };\n asOfBlock: number;\n}\n\n/** Live `lyth_listActivePrecompiles` response envelope. */\nexport interface PrecompileCatalogueResponse {\n /** Block height sampled by the node. */\n blockNumber: bigint;\n /** Precompile descriptors active or known at the sampled block. */\n precompiles: PrecompileDescriptor[];\n}\n\nexport interface OperatorInfoResponse {\n operatorId: string;\n moniker: string | null;\n alias: string | null;\n chainAddress: string;\n bonded: boolean;\n commissionBps: number | null;\n delegationCount: number | null;\n bondedAmount: string;\n activeClusterIds: number[];\n operatorKeyFingerprint: string | null;\n blsKeyFingerprint: string | null;\n lifecycleState: string;\n capability: Record<string, unknown>;\n}\n\nexport interface ClusterMemberResponse {\n operatorId: string;\n blsPubkey: string;\n state: string;\n}\n\nexport interface ClusterStatusResponse {\n clusterId: number;\n threshold: number;\n size: number;\n live: number;\n lagging: number;\n offline: number;\n maintenance: number;\n members: ClusterMemberResponse[];\n epoch: bigint | null;\n round: bigint | null;\n quorum: string;\n reputationScore: number | null;\n livenessScore: number | null;\n lastUpdateHeight: bigint;\n}\n\nexport interface ClusterDirectoryEntryResponse {\n clusterId: number;\n size: number;\n threshold: number;\n aggregateHealth: string;\n regionDiversity: string[] | null;\n active: boolean;\n}\n\nexport interface ClusterDirectoryPageResponse {\n page: number;\n limit: number;\n totalClusters: number;\n clusters: ClusterDirectoryEntryResponse[];\n}\n\nexport type OperatorSurfaceStatus =\n | \"available\"\n | \"disabled\"\n | \"not_implemented\"\n | \"not_retained\"\n | \"ws_only\"\n | string;\n\nexport interface OperatorSurfaceCapability {\n status: OperatorSurfaceStatus;\n tracking?: string;\n}\n\nexport interface OperatorCapabilitiesResponse {\n schemaVersion: number;\n surfaces: Record<string, OperatorSurfaceCapability>;\n}\n\nexport interface OperatorAuthorityResponse {\n schemaVersion: number;\n operatorId: string;\n authorityIndex: number;\n blsPubkey: string;\n active: boolean;\n}\n\nexport type SigningEntryStatus = \"signed\" | \"missed\" | \"no_cert\" | string;\n\nexport interface OperatorSigningEntry {\n round: bigint;\n status: SigningEntryStatus;\n}\n\nexport interface OperatorSigningActivityResponse {\n schemaVersion: number;\n authorityIndex: number;\n currentRound: bigint;\n limit: number;\n entries: OperatorSigningEntry[];\n}\n\nexport interface AttestationWindow {\n startRound: bigint;\n endRound: bigint;\n kind: string;\n}\n\nexport interface DutyAbsence {\n reason: string;\n}\n\nexport type KeyRotationWindow =\n | { nextRound: bigint; epochLengthRounds: bigint }\n | DutyAbsence;\n\nexport interface UpcomingDutyMap {\n attestation: AttestationWindow;\n blockProduction: DutyAbsence;\n sync: DutyAbsence;\n keyRotation: KeyRotationWindow;\n}\n\nexport interface UpcomingDutiesResponse {\n schemaVersion: number;\n authorityIndex: number;\n currentRound: bigint;\n horizonRounds: number;\n duties: UpcomingDutyMap;\n}\n\nexport type JailStatusWindow =\n | {\n jailed: boolean;\n tombstoned: boolean;\n jailedUntilHeight: bigint;\n unjailCount: bigint;\n }\n | DutyAbsence;\n\nexport interface OperatorRiskResponse {\n schemaVersion: number;\n authorityIndex: number;\n dataHeight: bigint;\n windowRounds: number;\n missedRounds: number;\n observedRounds: number;\n missRateBps: number;\n thresholdBps: number;\n remainingHeadroomBps: number;\n jailStatus: JailStatusWindow;\n reasons: string[];\n}\n\nexport interface LythUpgradePlanStatus {\n upgradeId: string;\n activationHeight: number;\n activationRound: number | null;\n requiredBinaryVersion: string;\n expectedBinaryDigest: string;\n p2pProtocolVersion: number;\n requiredFeatures: string[];\n milestoneFileDigest: string | null;\n stateMigrationId: string | null;\n stateMigrationHash: string | null;\n expectedPreStateRoot: string | null;\n expectedPostStateRoot: string | null;\n}\n\nexport interface LythUpgradeStatusResponse {\n chainId: number;\n blockNumber: number;\n configured: boolean;\n planCount: number;\n state: \"active\" | \"none\" | \"pending\" | string;\n active: LythUpgradePlanStatus | null;\n pendingCount: number;\n pending: LythUpgradePlanStatus[];\n}\n\nexport interface RuntimeBuildProvenance {\n clientName: string;\n version: string;\n gitCommit: string;\n gitDirty: boolean;\n buildTimestampUtc: number;\n rustc: string;\n target: string;\n profile: string;\n features: string;\n p2pProtocolVersion: number;\n binarySha256: string | null;\n stateMigrations: string[];\n}\n\nexport interface RuntimeUpgradeStatus {\n blockNumber: number;\n configured: boolean;\n planCount: number;\n state: \"active\" | \"none\" | \"pending\" | string;\n active: LythUpgradePlanStatus | null;\n pending: LythUpgradePlanStatus[];\n}\n\nexport interface RuntimeProvenanceResponse {\n schemaVersion: number;\n chainId: number;\n genesisHash: string | null;\n latestHeight: number;\n runtime: RuntimeBuildProvenance;\n upgrade: RuntimeUpgradeStatus | null;\n}\n\nexport type ServiceProbeStatusLabel =\n | \"unknown\"\n | \"reachable\"\n | \"degraded\"\n | \"unreachable\"\n | string;\n\nexport interface ServiceProbeResponse {\n serviceMask: number;\n status: ServiceProbeStatusLabel;\n statusCode: number;\n lastProbeBlock: number;\n latencyMs: number;\n probeDigest: string;\n reporter: string;\n}\n\nexport interface ReportServiceProbeRequest {\n peerId: string;\n serviceMask: number;\n status: number;\n latencyMs: number;\n probeDigest: string;\n signedRawTx: string;\n}\n\nexport interface ReportServiceProbeResponse {\n txHash: string;\n peerId: string;\n serviceMask: number;\n statusCode: number;\n}\n\nexport type TxStatusResponse = TxStatusFoundResponse | TxStatusNotFoundResponse;\n\nexport interface TxStatusFoundResponse {\n status: \"found\";\n txHash: string;\n blockHash: string;\n blockNumber: number;\n txIndex: number;\n}\n\nexport interface TxStatusNotFoundResponse {\n status: \"not_found\";\n txHash: string;\n latestHeight: number;\n indexerEnabled: boolean;\n providerKind: string;\n}\n\nexport interface VertexAtRound {\n vertexHash: string;\n author: number;\n}\n\nexport interface VerticesAtRoundResponse {\n schemaVersion: number;\n round: number;\n vertices: VertexAtRound[] | null;\n}\n\nexport type MetricsRangeStatus = \"available\" | \"not_retained\" | \"unknown\" | string;\n\nexport interface MetricsRangeSample {\n blockNumber: number;\n value: number;\n}\n\nexport interface MetricsRangeSeries {\n selector: string;\n status: MetricsRangeStatus;\n unit: string | null;\n samples: MetricsRangeSample[] | null;\n}\n\nexport interface MetricsRangeResponse {\n schemaVersion: number;\n range: [number, number] | null;\n tracking: string;\n series: MetricsRangeSeries[];\n}\n\nexport type AddressActivityKind =\n | \"found\"\n | \"not_found\"\n | \"indexer_disabled\"\n | \"pruned\"\n | \"private\"\n | string;\n\ninterface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id: number;\n method: string;\n params: unknown;\n}\n\ninterface JsonRpcResponse {\n jsonrpc?: \"2.0\";\n id?: number;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst SDK_VERSION = \"0.1.0\";\nconst ETH_COMPAT_RPC_PREFIX = \"eth_\";\nconst ethCompatMethod = (name: string): string => `${ETH_COMPAT_RPC_PREFIX}${name}`;\n\nfunction resolveChainInfo(network: NetworkSlug | string, registry?: ChainRegistry): ChainInfo {\n if (registry) {\n const info = registry[network];\n if (!info) {\n throw SdkError.endpoint(`unknown Monolythium network: ${network}`);\n }\n return info;\n }\n try {\n return getChainInfo(network);\n } catch (err) {\n throw SdkError.endpoint((err as Error)?.message ?? String(err));\n }\n}\n\nexport class RpcClient {\n readonly endpoint: string;\n readonly #fetch: typeof fetch;\n readonly #headers: Record<string, string>;\n #nextId: number;\n\n constructor(endpoint: string, options: RpcClientOptions = {}) {\n if (!endpoint || endpoint.length === 0) {\n throw SdkError.endpoint(\"endpoint cannot be empty\");\n }\n this.endpoint = endpoint;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#headers = {\n \"content-type\": \"application/json\",\n \"user-agent\": `monolythium-core-sdk/${SDK_VERSION}`,\n ...(options.headers ?? {}),\n };\n this.#nextId = 1;\n }\n\n /**\n * Construct a client from the chain-registry network slug.\n *\n * Defaults to the SDK-bundled registry snapshot from\n * `monolythium/chain-registry`. Set `probe: true` to walk the\n * registry endpoints in order and return the first endpoint whose\n * `eth_chainId` matches the registry chain id.\n */\n static async forNetwork(\n network: NetworkSlug | string = \"testnet-69420\",\n options: NetworkClientOptions = {},\n ): Promise<RpcClient> {\n const info = resolveChainInfo(network, options.registry);\n if (info.rpc.length === 0) {\n throw SdkError.endpoint(`network ${network} has no RPC endpoints`);\n }\n if (options.probe) {\n return this.fromFirstReachable(info, options);\n }\n return new RpcClient(info.rpc[0].url, options);\n }\n\n /**\n * Walk a chain-registry entry in order and return the first endpoint\n * whose `eth_chainId` matches the registry `chain_id`.\n */\n static async fromFirstReachable(\n chain: ChainInfo,\n options: RpcClientOptions = {},\n ): Promise<RpcClient> {\n const errors: string[] = [];\n for (const endpoint of chain.rpc) {\n const client = new RpcClient(endpoint.url, options);\n try {\n const chainId = await client.ethChainId();\n if (chainId === BigInt(chain.chain_id)) {\n return client;\n }\n errors.push(`${endpoint.url}: chain id ${chainId} != ${chain.chain_id}`);\n } catch (err) {\n errors.push(`${endpoint.url}: ${(err as Error)?.message ?? err}`);\n }\n }\n throw SdkError.endpoint(\n `no reachable RPC endpoint for ${chain.network}; tried ${errors.join(\"; \")}`,\n );\n }\n\n /**\n * Send an arbitrary JSON-RPC method. Most callers should prefer the\n * typed wrappers below; this is the escape hatch for methods the\n * SDK does not yet wrap.\n */\n async call<T>(method: string, params: unknown = []): Promise<T> {\n const id = this.#nextId++;\n const body: JsonRpcRequest = { jsonrpc: \"2.0\", id, method, params };\n let resp: Response;\n try {\n resp = await this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: this.#headers,\n body: JSON.stringify(body),\n });\n } catch (cause) {\n throw SdkError.transport(\n `transport failure calling ${method}: ${(cause as Error)?.message ?? cause}`,\n cause,\n );\n }\n let parsed: JsonRpcResponse;\n try {\n parsed = (await resp.json()) as JsonRpcResponse;\n } catch (cause) {\n throw SdkError.malformed(\n `non-JSON response (HTTP ${resp.status}): ${(cause as Error)?.message ?? cause}`,\n );\n }\n if (parsed.error) {\n throw SdkError.rpc(parsed.error.code, parsed.error.message, parsed.error.data);\n }\n if (!(\"result\" in parsed) || parsed.result === undefined) {\n if (!resp.ok) {\n throw SdkError.malformed(`HTTP ${resp.status} with no JSON-RPC result`);\n }\n throw SdkError.malformed(\"response is missing both `result` and `error`\");\n }\n return parsed.result as T;\n }\n\n // ---- eth_* / net_* / web3_* ---------------------------------------\n\n /** `eth_chainId` — configured chain id. */\n async ethChainId(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"eth_chainId\", []));\n }\n\n /** Compatibility block-height read. */\n async ethBlockNumber(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(ethCompatMethod(\"blockNumber\"), []));\n }\n\n /** `eth_getBalance` — balance + Merkle proof envelope. */\n async ethGetBalance(\n address: string,\n block: BlockSelector = \"latest\",\n ): Promise<AccountProofResponse> {\n return this.call(\"eth_getBalance\", [address, encodeBlockSelector(block)]);\n }\n\n /** `eth_getStorageAt` — storage word + Merkle proof. */\n async ethGetStorageAt(\n address: string,\n slot: string,\n block: BlockSelector = \"latest\",\n ): Promise<AccountProofResponse> {\n return this.call(\"eth_getStorageAt\", [\n address,\n slot,\n encodeBlockSelector(block),\n ]);\n }\n\n /** `eth_getTransactionCount` — sender nonce. */\n async ethGetTransactionCount(\n address: string,\n block: BlockSelector = \"latest\",\n ): Promise<bigint> {\n return parseQuantityBig(\n await this.call<string>(\"eth_getTransactionCount\", [\n address,\n encodeBlockSelector(block),\n ]),\n );\n }\n\n /** `eth_getCode` — deployed bytecode (`0x` for an EOA, `0xfe` for a precompile). */\n async ethGetCode(address: string, block: BlockSelector = \"latest\"): Promise<string> {\n return this.call(\"eth_getCode\", [address, encodeBlockSelector(block)]);\n }\n\n /** Compatibility block-header read by height/tag. */\n async ethGetBlockByNumber(\n block: BlockSelector = \"latest\",\n ): Promise<BlockHeader | null> {\n return normalizeBlockHeader(await this.call(ethCompatMethod(\"getBlockByNumber\"), [encodeBlockSelector(block)]));\n }\n\n /** Compatibility block-header read by hash. */\n async ethGetBlockByHash(hash: string): Promise<BlockHeader | null> {\n return normalizeBlockHeader(await this.call(ethCompatMethod(\"getBlockByHash\"), [hash]));\n }\n\n /** `eth_getTransactionByHash` — fetch an included transaction by hash. */\n async ethGetTransactionByHash(txHash: string): Promise<TransactionView | null> {\n return this.call(\"eth_getTransactionByHash\", [txHash]);\n }\n\n /** `eth_getTransactionReceipt` — receipt for a confirmed tx. */\n async ethGetTransactionReceipt(txHash: string): Promise<TransactionReceipt | null> {\n return normalizeTransactionReceipt(await this.call(\"eth_getTransactionReceipt\", [txHash]));\n }\n\n /** `eth_sendRawTransaction` — submit a signed raw tx. */\n async ethSendRawTransaction(rawTx: string): Promise<string> {\n return this.call(\"eth_sendRawTransaction\", [rawTx]);\n }\n\n /** `eth_call` — dry-run a transaction. */\n async ethCall(request: CallRequest, block: BlockSelector = \"latest\"): Promise<string> {\n return this.call(\"eth_call\", [request, encodeBlockSelector(block)]);\n }\n\n /** `eth_estimateGas` — gas estimate for a dry-run. */\n async ethEstimateGas(\n request: CallRequest,\n block: BlockSelector = \"latest\",\n ): Promise<bigint> {\n return parseQuantityBig(\n await this.call<string>(\"eth_estimateGas\", [request, encodeBlockSelector(block)]),\n );\n }\n\n /**\n * `eth_gasPrice` — legacy compatibility fee quote for ethers/viem shims.\n * Native v4.1 surfaces should use execution-unit and lythoshi fee fields.\n */\n async ethGasPrice(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"eth_gasPrice\", []));\n }\n\n /** `eth_feeHistory` — base-fee + gas-used history. */\n async ethFeeHistory(\n blockCount: number,\n newestBlock: BlockSelector = \"latest\",\n rewardPercentiles: number[] = [],\n ): Promise<FeeHistoryResponse> {\n return this.call(\"eth_feeHistory\", [\n `0x${blockCount.toString(16)}`,\n encodeBlockSelector(newestBlock),\n rewardPercentiles,\n ]);\n }\n\n /** `eth_syncing` — `null` when caught up. */\n async ethSyncing(): Promise<SyncStatus | null> {\n const v = await this.call<unknown>(\"eth_syncing\", []);\n if (v === false || v === null || v === undefined) return null;\n return v as SyncStatus;\n }\n\n /** `net_version` — chain id as a decimal string. */\n async netVersion(): Promise<string> {\n return this.call(\"net_version\", []);\n }\n\n /** `net_peerCount` — number of connected peers. */\n async netPeerCount(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"net_peerCount\", []));\n }\n\n /** `net_listening` — whether the node accepts inbound peers. */\n async netListening(): Promise<boolean> {\n return this.call(\"net_listening\", []);\n }\n\n /** `web3_clientVersion` — server's client-version string. */\n async web3ClientVersion(): Promise<string> {\n return this.call(\"web3_clientVersion\", []);\n }\n\n /** `web3_sha3` — Keccak-256 of `data`. */\n async web3Sha3(data: string): Promise<string> {\n return this.call(\"web3_sha3\", [data]);\n }\n\n // ---- lyth_* (Law §13.2 native namespace) --------------------------\n\n /** `lyth_listProviders` — paged registry enumeration. */\n async lythListProviders(\n capabilityMask: number,\n cursor: string | null = null,\n limit = 100,\n ): Promise<RegistryRecord[]> {\n return this.call(\"lyth_listProviders\", [capabilityMask, cursor, limit]);\n }\n\n /** `lyth_getRegistration` — single registry lookup. */\n async lythGetRegistration(peerId: string): Promise<RegistryRecord | null> {\n return this.call(\"lyth_getRegistration\", [peerId]);\n }\n\n /** `lyth_registryStateProof` — Merkle proof for a registry entry. */\n async lythRegistryStateProof(peerId: string): Promise<AccountProofResponse> {\n return this.call(\"lyth_registryStateProof\", [peerId]);\n }\n\n /** `lyth_getAccountPolicy` — privacy posture for an account. */\n async lythGetAccountPolicy(address: string): Promise<AccountPolicy> {\n return this.call(\"lyth_getAccountPolicy\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_getAssetPolicy` — privacy posture for an asset. */\n async lythGetAssetPolicy(tokenId: string): Promise<AssetPolicy> {\n return this.call(\"lyth_getAssetPolicy\", [tokenId]);\n }\n\n /** `lyth_getTokenBalances` — indexed per-asset balances for one address. */\n async lythGetTokenBalances(address: string): Promise<TokenBalanceRecord[]> {\n return this.call(\"lyth_getTokenBalances\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_bridgeRoutes` — read-only bridge route-selection/readiness. */\n async lythBridgeRoutes(request: BridgeRoutesRequest): Promise<BridgeRoutesResponse> {\n return this.call(\"lyth_bridgeRoutes\", [request]);\n }\n\n /** `lyth_mrcMetadata` — exact current-state native MRC metadata lookup. */\n async lythMrcMetadata(\n assetId: string,\n tokenId?: string | null,\n ): Promise<MrcMetadataResponse> {\n const params = tokenId == null ? [assetId] : [assetId, tokenId];\n return this.call(\"lyth_mrcMetadata\", params);\n }\n\n /** `lyth_mrcAccount` — exact current-state native MRC account lookup. */\n async lythMrcAccount(\n account: string,\n spendLimit?: number | null,\n ): Promise<MrcAccountResponse> {\n const request: MrcAccountRequest = {\n account: sdkTypedAddress(account, \"smartAccount\", \"account\"),\n };\n if (spendLimit != null) request.spendLimit = spendLimit;\n const params =\n request.spendLimit == null\n ? [request.account]\n : [request.account, request.spendLimit];\n return this.call(\"lyth_mrcAccount\", params);\n }\n\n /** `lyth_mrcHolders` — top holders for a native MRC asset/token key. */\n async lythMrcHolders(\n standard: string,\n assetId: string,\n tokenId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcHoldersScoped(standard, assetId, tokenId, limit);\n }\n\n /**\n * `lyth_mrcHolders` — top holders for a native MRC asset/vault key.\n *\n * This is the asset-scoped form used by MRC-4626 vault share balances.\n */\n async lythMrcAssetHolders(\n standard: string,\n assetId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcHoldersScoped(standard, assetId, null, limit);\n }\n\n /** `lyth_mrcHolders` — top holders for MRC-4626 vault shares. */\n async lythMrc4626Holders(\n vaultId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcAssetHolders(\"mrc4626\", vaultId, limit);\n }\n\n private async lythMrcHoldersScoped(\n standard: string,\n assetId: string,\n tokenId: string | null,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n const request: MrcHoldersRequest = {\n standard,\n assetId,\n tokenId,\n };\n if (limit != null) request.limit = limit;\n const params =\n request.limit == null\n ? [request.standard, request.assetId, request.tokenId]\n : [request.standard, request.assetId, request.tokenId, request.limit];\n return this.call(\"lyth_mrcHolders\", params);\n }\n\n /** `lyth_getAddressLabel` — indexed display/category label for one address. */\n async lythGetAddressLabel(address: string): Promise<AddressLabelRecord | null> {\n const v = await this.call<unknown>(\"lyth_getAddressLabel\", [\n sdkTypedAddress(address, \"user\", \"address\"),\n ]);\n if (v === null || v === undefined) return null;\n return v as AddressLabelRecord;\n }\n\n /** `lyth_getAddressActivity` — indexed per-address activity timeline. */\n async lythGetAddressActivity(\n address: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<AddressActivityEntry[]> {\n const userAddress = sdkTypedAddress(address, \"user\", \"address\");\n const params = cursor === undefined ? [userAddress, limit] : [userAddress, limit, cursor];\n return this.call(\"lyth_getAddressActivity\", params);\n }\n\n /** `lyth_addressActivityKind` — activity index coverage for one address. */\n async lythAddressActivityKind(address: string): Promise<AddressActivityKindResponse> {\n return this.call(\"lyth_addressActivityKind\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_agentReputation` — reputation accumulators for an agent provider. */\n async lythAgentReputation(\n provider: UserAddressInput,\n categoryId = 0,\n ): Promise<AgentReputationResponse> {\n return this.call(\"lyth_agentReputation\", [\n sdkTypedAddress(provider, \"user\", \"provider address\"),\n categoryId,\n ]);\n }\n\n /** `lyth_decodeTx` — explorer-grade decoded transaction envelope. */\n async lythDecodeTx(txHash: string): Promise<DecodeTxResponse> {\n return this.call(\"lyth_decodeTx\", [txHash]);\n }\n\n /** `lyth_nativeReceipt` — native RISC-V receipt metadata and typed native event rows. */\n async lythNativeReceipt<TDecoded = unknown>(\n txHash: string,\n ): Promise<NativeReceiptResponse<TDecoded>> {\n return decodeNativeReceiptResponse<TDecoded>(\n await this.call<unknown>(\"lyth_nativeReceipt\", [txHash]),\n );\n }\n\n /**\n * Typed native event rows from `lyth_nativeReceipt`.\n *\n * This helper intentionally consumes the existing receipt RPC surface;\n * it does not require a separate `lyth_nativeEvents` node method.\n */\n async lythNativeReceiptEvents<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n txHash: string,\n filter: NativeEventFilter = {},\n ): Promise<Array<TypedNativeReceiptEvent<TDecoded>>> {\n const receipt = await this.lythNativeReceipt(txHash);\n return nativeEventsFromReceipt<TDecoded>(receipt, filter);\n }\n\n /** Typed native market event rows from `lyth_nativeReceipt`. */\n async lythNativeReceiptMarketEvents<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n txHash: string,\n filter: NativeEventFilter = {},\n ): Promise<Array<TypedNativeReceiptEvent<TDecoded>>> {\n const receipt = await this.lythNativeReceipt(txHash);\n return nativeMarketEventsFromReceipt<TDecoded>(receipt, filter);\n }\n\n /** `lyth_nativeEvents` — historical indexed native event rows. */\n async lythNativeEvents<TDecoded = unknown>(\n filter: NativeEventsFilter,\n ): Promise<NativeEventsResponse<TDecoded>> {\n return this.call(\"lyth_nativeEvents\", [nativeEventsFilterParams(filter)]);\n }\n\n /** `lyth_nativeEvents` with decoded rows converted into a caller-selected type. */\n async lythNativeEventsTyped<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n >(filter: NativeEventsFilter): Promise<NativeEventsResponse<TDecoded>> {\n const response = await this.lythNativeEvents(filter);\n return nativeEventsFromHistory<TDecoded>(response);\n }\n\n /** `lyth_nativeEvents` restricted to native marketplace event rows. */\n async lythNativeMarketEvents<TDecoded = unknown>(\n filter: NativeEventsFilter,\n ): Promise<NativeEventsResponse<TDecoded>> {\n return this.lythNativeEvents<TDecoded>({\n ...filter,\n family: \"market\",\n });\n }\n\n /** `lyth_nativeEvents` market rows with decoded rows converted into a caller-selected type. */\n async lythNativeMarketEventsTyped<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n >(filter: NativeEventsFilter): Promise<NativeEventsResponse<TDecoded>> {\n const response = await this.lythNativeEvents({\n ...filter,\n family: \"market\",\n });\n return nativeMarketEventsFromHistory<TDecoded>(response);\n }\n\n /** `lyth_nativeAgentState` — current-state native agent policy and escrow rows. */\n async lythNativeAgentState(\n filter: NativeAgentStateFilter = {},\n ): Promise<NativeAgentStateResponse> {\n const response = await this.call(\"lyth_nativeAgentState\", [\n nativeAgentStateFilterParams(filter),\n ]);\n return decodeNativeAgentStateResponse(response);\n }\n\n /** `lyth_nativeMarketState` — current-state native spot and NFT market rows. */\n async lythNativeMarketState(\n filter: NativeMarketStateFilter = {},\n ): Promise<NativeMarketStateResponse> {\n return this.call(\"lyth_nativeMarketState\", [nativeMarketStateFilterParams(filter)]);\n }\n\n /** `lyth_gapRecords` — retained ingestion/indexing gaps for a block range. */\n async lythGapRecords(\n fromBlock: number | bigint | string,\n toBlock: number | bigint | string,\n ): Promise<GapRecordsResponse> {\n return this.call(\"lyth_gapRecords\", [\n encodeRpcU64Number(fromBlock, \"fromBlock\"),\n encodeRpcU64Number(toBlock, \"toBlock\"),\n ]);\n }\n\n /** `lyth_dagParents` — parent vertices for a DAG round. */\n async lythDagParents(round: number | bigint | string): Promise<DagParentsResponse> {\n return this.call(\"lyth_dagParents\", [encodeRpcU64Number(round, \"round\")]);\n }\n\n /** `lyth_richList` — top holders for a token id. */\n async lythRichList(tokenId: string, limit?: number | null): Promise<RichListResponse> {\n const params = limit == null ? [tokenId] : [tokenId, limit];\n return this.call(\"lyth_richList\", params);\n }\n\n /** `lyth_clobMarket` — live CLOB market metadata for a market id. */\n async lythClobMarket(marketId: string): Promise<ClobMarketResponse> {\n return this.call(\"lyth_clobMarket\", [marketId]);\n }\n\n /** `lyth_clobMarkets` — CLOB markets observed through indexed trades. */\n async lythClobMarkets(limit?: number | null): Promise<ClobMarketsResponse> {\n const params = limit == null ? [] : [limit];\n return this.call(\"lyth_clobMarkets\", params);\n }\n\n /** `lyth_clobTrades` — CLOB fills for one market. */\n async lythClobTrades(\n marketId: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<ClobTradesResponse> {\n const params = cursor === undefined ? [marketId, limit] : [marketId, limit, cursor];\n return this.call(\"lyth_clobTrades\", params);\n }\n\n /** `lyth_clobOhlc` — CLOB OHLC candles for a market over a block range. */\n async lythClobOhlc(\n marketId: string,\n fromBlock?: number | bigint | string | null,\n toBlock?: number | bigint | string | null,\n bucketBlocks?: number | bigint | string | null,\n ): Promise<ClobOhlcResponse> {\n const params =\n fromBlock == null && toBlock == null && bucketBlocks == null\n ? [marketId]\n : [\n marketId,\n fromBlock == null ? null : encodeRpcU64Number(fromBlock, \"fromBlock\"),\n toBlock == null ? null : encodeRpcU64Number(toBlock, \"toBlock\"),\n bucketBlocks == null ? null : encodeRpcU64Number(bucketBlocks, \"bucketBlocks\"),\n ];\n return this.call(\"lyth_clobOhlc\", params);\n }\n\n /** `lyth_clobOrderBook` — live CLOB depth from canonical state. */\n async lythClobOrderBook(\n marketId: string,\n levels?: number | null,\n ): Promise<ClobOrderBookResponse> {\n const params = levels == null ? [marketId] : [marketId, levels];\n return this.call(\"lyth_clobOrderBook\", params);\n }\n\n /** `lyth_txFeed` — paged global transaction feed. */\n async lythTxFeed(limit = 50, cursor?: string | null): Promise<TxFeedResponse> {\n const params = cursor === undefined ? [limit] : [limit, cursor];\n return decodeTxFeedResponse(await this.call<unknown>(\"lyth_txFeed\", params));\n }\n\n /** `lyth_addressProfile` — live account + label + activity aggregate. */\n async lythAddressProfile(address: string): Promise<AddressProfileResponse> {\n return this.call(\"lyth_addressProfile\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_addressFlow` — recent indexed address-flow aggregate. */\n async lythAddressFlow(address: string, limit = 250): Promise<AddressFlowResponse> {\n return this.call(\"lyth_addressFlow\", [sdkTypedAddress(address, \"user\", \"address\"), limit]);\n }\n\n /** `lyth_search` — exact live resolver for hashes, addresses, blocks, and clusters. */\n async lythSearch(query: string, limit = 10): Promise<SearchResponse> {\n return this.call(\"lyth_search\", [query, limit]);\n }\n\n /** `lyth_chainStats` — compact live chain/indexer/mempool summary. */\n async lythChainStats(): Promise<ChainStatsResponse> {\n return this.call(\"lyth_chainStats\", []);\n }\n\n /** `lyth_mempoolStatus` — aggregate mempool snapshot. */\n async lythMempoolStatus(): Promise<MempoolSnapshot> {\n return normalizeMempoolSnapshot(await this.call(\"lyth_mempoolStatus\", []));\n }\n\n /** `lyth_mempoolPending` — pending txs for a sender. */\n async lythMempoolPending(sender: string): Promise<PendingTxSummary[]> {\n return this.call(\"lyth_mempoolPending\", [sdkTypedAddress(sender, \"user\", \"sender\")]);\n }\n\n /** `lyth_currentRound` — latest committed height. */\n async lythCurrentRound(): Promise<RoundInfo> {\n return normalizeRoundInfo(await this.call(\"lyth_currentRound\", []));\n }\n\n /** `lyth_peerSummary` — public-safe aggregate peer-network diagnostics. */\n async lythPeerSummary(): Promise<PeerSummaryAggregate> {\n return this.call(\"lyth_peerSummary\", []);\n }\n\n /**\n * `lyth_listActivePrecompiles` — milestone-gated precompile catalogue\n * (OI-0170 / ADR-0015 §5).\n */\n async lythListActivePrecompiles(\n block: BlockSelector = \"latest\",\n ): Promise<PrecompileCatalogueResponse> {\n return this.call(\"lyth_listActivePrecompiles\", [encodeBlockSelector(block)]);\n }\n\n /** `lyth_capabilities` — address-keyed precompile capability map. */\n async lythCapabilities(block?: BlockSelector): Promise<CapabilitiesResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return normalizeCapabilitiesResponse(\n await this.call<CapabilitiesResponse>(\"lyth_capabilities\", params),\n );\n }\n\n /**\n * `lyth_operatorCapabilities` — node-level availability for operator UI\n * and explorer surfaces.\n */\n async lythOperatorCapabilities(): Promise<OperatorCapabilitiesResponse> {\n return this.call(\"lyth_operatorCapabilities\", []);\n }\n\n /** `lyth_indexerStatus` — indexer status; `null` when disabled. */\n async lythIndexerStatus(): Promise<IndexerStatus | null> {\n const v = await this.call<unknown>(\"lyth_indexerStatus\", []);\n if (v === null || v === undefined) return null;\n return v as IndexerStatus;\n }\n\n /** `lyth_getStorageProof` — batched Merkle proofs. */\n async lythGetStorageProof(\n address: string,\n slots: string[],\n ): Promise<StorageProofBatch> {\n return this.call(\"lyth_getStorageProof\", [address, slots]);\n }\n\n /** `lyth_getDelegations` — wallet delegation rows at a block. */\n async lythGetDelegations(\n wallet: string,\n block?: BlockSelector,\n ): Promise<DelegationsResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_getDelegations\", params);\n }\n\n /** `lyth_pendingRewards` — wallet pending rewards at a block. */\n async lythPendingRewards(\n wallet: string,\n block?: BlockSelector,\n ): Promise<PendingRewardsResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_pendingRewards\", params);\n }\n\n /** `lyth_redemptionQueue` — wallet redemption tickets at a block. */\n async lythRedemptionQueue(\n wallet: string,\n block?: BlockSelector,\n ): Promise<RedemptionQueueResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_redemptionQueue\", params);\n }\n\n /** `lyth_getDelegationHistory` — indexed per-wallet delegation event timeline. */\n async lythGetDelegationHistory(\n wallet: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<DelegationHistoryRecord[]> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params = cursor === undefined ? [userWallet, limit] : [userWallet, limit, cursor];\n return this.call(\"lyth_getDelegationHistory\", params);\n }\n\n /** `lyth_getClusterDelegators` — delegator addresses for a cluster. */\n async lythGetClusterDelegators(\n cluster: number,\n block?: BlockSelector,\n ): Promise<ClusterDelegatorsResponse> {\n const params =\n block === undefined ? [cluster] : [cluster, encodeBlockSelector(block)];\n return this.call(\"lyth_getClusterDelegators\", params);\n }\n\n /** `lyth_getDelegationCap` — active per-cluster cap at a block. */\n async lythGetDelegationCap(\n block?: BlockSelector,\n ): Promise<DelegationCapResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_getDelegationCap\", params);\n }\n\n /** `lyth_getTpmAttestation` — TPM quote digest + EK id for a peer. */\n async lythGetTpmAttestation(\n peerId: string,\n block?: BlockSelector,\n ): Promise<TpmAttestationResponse> {\n const params =\n block === undefined ? [peerId] : [peerId, encodeBlockSelector(block)];\n return this.call(\"lyth_getTpmAttestation\", params);\n }\n\n /** `lyth_getClusterEntity` — entity flag for a cluster. */\n async lythGetClusterEntity(\n cluster: number,\n block?: BlockSelector,\n ): Promise<ClusterEntityResponse> {\n const params =\n block === undefined ? [cluster] : [cluster, encodeBlockSelector(block)];\n return this.call(\"lyth_getClusterEntity\", params);\n }\n\n /** `lyth_getEntityRatchet` — entity-ratchet snapshot at a block. */\n async lythGetEntityRatchet(\n block?: BlockSelector,\n ): Promise<EntityRatchetResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_getEntityRatchet\", params);\n }\n\n /** `lyth_operatorInfo` — canonical operator identity envelope. */\n async lythOperatorInfo(operatorId: string): Promise<OperatorInfoResponse> {\n return normalizeOperatorInfo(await this.call(\"lyth_operatorInfo\", [operatorId]));\n }\n\n /** `lyth_getServiceProbe` — latest external reachability report for one public service. */\n async lythGetServiceProbe(\n peerId: string,\n serviceMask: number,\n ): Promise<ServiceProbeResponse | null> {\n assertHexBytes(peerId, 32, \"peerId\");\n if (!isSinglePublicServiceProbeMask(serviceMask)) {\n throw SdkError.malformed(\"serviceMask must contain exactly one public-service bit\");\n }\n const value = await this.call<unknown>(\"lyth_getServiceProbe\", [peerId, serviceMask]);\n if (value === null || value === undefined) return null;\n return normalizeServiceProbe(value);\n }\n\n /** `lyth_reportServiceProbe` — submit a pre-signed public-service probe report. */\n async lythReportServiceProbe(\n req: ReportServiceProbeRequest,\n ): Promise<ReportServiceProbeResponse> {\n assertHexBytes(req.peerId, 32, \"peerId\");\n if (!isValidPublicServiceProbeMask(req.serviceMask)) {\n throw SdkError.malformed(\"serviceMask must name one or more public-service bits\");\n }\n if (!isConcreteServiceProbeStatus(req.status)) {\n throw SdkError.malformed(\"status must be reachable, degraded, or unreachable\");\n }\n assertSafeUint32(req.latencyMs, \"latencyMs\");\n assertHexBytes(req.probeDigest, 32, \"probeDigest\");\n assertNonEmptyHex(req.signedRawTx, \"signedRawTx\");\n return this.call(\"lyth_reportServiceProbe\", [req]);\n }\n\n /** `lyth_clusterStatus` — canonical cluster status envelope. */\n async lythClusterStatus(clusterId: number): Promise<ClusterStatusResponse> {\n return normalizeClusterStatus(await this.call(\"lyth_clusterStatus\", [clusterId]));\n }\n\n /** `lyth_clusterDirectory` — paged public cluster directory. */\n async lythClusterDirectory(page = 0, limit = 25): Promise<ClusterDirectoryPageResponse> {\n return normalizeClusterDirectoryPage(\n await this.call(\"lyth_clusterDirectory\", [page, limit]),\n );\n }\n\n /** `lyth_clusters` — alias for `lyth_clusterDirectory`. */\n async lythClusters(page = 0, limit = 25): Promise<ClusterDirectoryPageResponse> {\n return normalizeClusterDirectoryPage(await this.call(\"lyth_clusters\", [page, limit]));\n }\n\n /**\n * `lyth_submitPendingChange` — operator-onboarding transport for the\n * pending-change ledger. Server validates the envelope shape.\n */\n async lythSubmitPendingChange(envelope: unknown): Promise<unknown> {\n return this.call(\"lyth_submitPendingChange\", [envelope]);\n }\n\n /** `lyth_submitEncrypted` — submit a bincode-encoded encrypted envelope hex. */\n async lythSubmitEncrypted(envelopeHex: string): Promise<string> {\n return this.call(\"lyth_submitEncrypted\", [envelopeHex]);\n }\n\n /** `lyth_getEncryptionKey` — cluster ML-KEM encapsulation key. */\n async lythGetEncryptionKey(): Promise<EncryptionKeyResponse> {\n return this.call(\"lyth_getEncryptionKey\", []);\n }\n\n /** `lyth_syncStatus` — DAG-sync driver snapshot. */\n async lythSyncStatus(): Promise<DagSyncStatus | null> {\n const v = await this.call<unknown>(\"lyth_syncStatus\", []);\n if (v === null || v === undefined) return null;\n return v as DagSyncStatus;\n }\n\n /** `lyth_resolveOperatorAuthority` — operator id to authority index. */\n async lythResolveOperatorAuthority(operatorId: string): Promise<OperatorAuthorityResponse> {\n return normalizeOperatorAuthority(\n await this.call(\"lyth_resolveOperatorAuthority\", [operatorId]),\n );\n }\n\n /** `lyth_signingActivity` — recent per-round signing participation. */\n async lythSigningActivity(\n authorityIndex: number,\n limit?: number | null,\n ): Promise<OperatorSigningActivityResponse> {\n const params = limit == null ? [authorityIndex] : [authorityIndex, limit];\n return normalizeSigningActivity(await this.call(\"lyth_signingActivity\", params));\n }\n\n /** `lyth_upcomingDuties` — deterministic upcoming duty windows. */\n async lythUpcomingDuties(\n authorityIndex: number,\n horizonRounds?: number | null,\n ): Promise<UpcomingDutiesResponse> {\n const params =\n horizonRounds == null ? [authorityIndex] : [authorityIndex, horizonRounds];\n return normalizeUpcomingDuties(await this.call(\"lyth_upcomingDuties\", params));\n }\n\n /** `lyth_operatorRisk` — miss-rate and jail-status window. */\n async lythOperatorRisk(\n authorityIndex: number,\n windowRounds?: number | null,\n ): Promise<OperatorRiskResponse> {\n const params =\n windowRounds == null ? [authorityIndex] : [authorityIndex, windowRounds];\n return normalizeOperatorRisk(await this.call(\"lyth_operatorRisk\", params));\n }\n\n /** `lyth_upgradeStatus` — signed network-upgrade readiness at a height. */\n async lythUpgradeStatus(block?: BlockSelector): Promise<LythUpgradeStatusResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_upgradeStatus\", params);\n }\n\n /** `lyth_runtimeProvenance` — public-safe build/runtime provenance. */\n async lythRuntimeProvenance(): Promise<RuntimeProvenanceResponse> {\n return this.call(\"lyth_runtimeProvenance\", []);\n }\n\n /** `lyth_txStatus` — discriminated transaction lookup outcome. */\n async lythTxStatus(txHash: string): Promise<TxStatusResponse> {\n return this.call(\"lyth_txStatus\", [txHash]);\n }\n\n /** `lyth_verticesAtRound` — per-vertex authorship observed at a DAG round. */\n async lythVerticesAtRound(\n round: number | bigint | string,\n ): Promise<VerticesAtRoundResponse> {\n return this.call(\"lyth_verticesAtRound\", [\n encodeRpcU64Number(round, \"round\"),\n ]);\n }\n\n /** `lyth_metricsRange` — retained telemetry series when the node has them. */\n async lythMetricsRange(\n selectors: string[],\n range?: readonly [number | bigint | string, number | bigint | string] | null,\n ): Promise<MetricsRangeResponse> {\n const params =\n range === undefined\n ? [selectors]\n : [\n selectors,\n range === null\n ? null\n : [\n encodeRpcU64Number(range[0], \"fromBlock\"),\n encodeRpcU64Number(range[1], \"toBlock\"),\n ],\n ];\n return this.call(\"lyth_metricsRange\", params);\n }\n\n /** `lyth_getLatestCheckpoint` — latest PQ-finality checkpoint rows. */\n async lythGetLatestCheckpoint(belowHeight?: number | bigint | string | null): Promise<CheckpointRecord[]> {\n const params = belowHeight === undefined ? [] : [encodeOptionalHeight(belowHeight)];\n return this.call(\"lyth_getLatestCheckpoint\", params);\n }\n\n /** `lyth_getClusterResignations` — in-flight + applied operator resignations. */\n async lythGetClusterResignations(\n operator?: string | null,\n status?: \"pending\" | \"applied\" | \"all\" | string | null,\n ): Promise<ClusterResignationsResponse> {\n const params =\n status === undefined\n ? operator == null\n ? []\n : [operator]\n : [operator ?? null, status];\n return this.call(\"lyth_getClusterResignations\", params);\n }\n\n /** `lyth_getBlsRoundCertificate` — round-advancement BLS aggregate. */\n async lythGetBlsRoundCertificate(round: number | bigint | string): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getBlsRoundCertificate\", [encodeRpcInteger(round)]);\n }\n\n /** `lyth_getLeaderCertificate` — leader-vote BLS aggregate for a block ref. */\n async lythGetLeaderCertificate(\n round: number | bigint | string,\n authority: number,\n digest: string,\n ): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getLeaderCertificate\", [encodeRpcInteger(round), authority, digest]);\n }\n\n /** `lyth_getDacCertificate` — data-availability certificate for a block ref. */\n async lythGetDacCertificate(\n round: number | bigint | string,\n authority: number,\n digest: string,\n ): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getDacCertificate\", [encodeRpcInteger(round), authority, digest]);\n }\n\n /** `lyth_subscribe` — WebSocket-only; returns an RPC error over HTTP. */\n async lythSubscribe(channel: ApiStreamTopic | (string & {})): Promise<unknown> {\n return this.call(\"lyth_subscribe\", [channel]);\n }\n\n /** `lyth_unsubscribe` — counterpart to `lythSubscribe`. */\n async lythUnsubscribe(subId: string): Promise<unknown> {\n return this.call(\"lyth_unsubscribe\", [subId]);\n }\n\n // ---- debug_* ------------------------------------------------------\n // Server-side gated by `RpcConfig::debug_enabled`. When the namespace\n // is disabled, every call surfaces as `SdkError.rpc`.\n\n /** `debug_traceTransaction` — legacy compatibility trace for a confirmed tx. */\n async debugTraceTransaction(txHash: string): Promise<unknown> {\n return this.call(\"debug_traceTransaction\", [txHash]);\n }\n\n /** `debug_traceCall` — legacy compatibility trace for a dry-run. */\n async debugTraceCall(\n request: CallRequest,\n block: BlockSelector = \"latest\",\n ): Promise<unknown> {\n return this.call(\"debug_traceCall\", [request, encodeBlockSelector(block)]);\n }\n\n /** `debug_traceBlockByNumber` — legacy compatibility traces for an entire block. */\n async debugTraceBlockByNumber(block: BlockSelector): Promise<unknown> {\n return this.call(\"debug_traceBlockByNumber\", [encodeBlockSelector(block)]);\n }\n\n /** `debug_mempoolDump` — full mempool snapshot. */\n async debugMempoolDump(): Promise<MempoolSnapshot> {\n return normalizeMempoolSnapshot(await this.call(\"debug_mempoolDump\", []));\n }\n\n /** `debug_p2pPeers` — connected libp2p peer list. */\n async debugP2pPeers(): Promise<PeerSummary[]> {\n return this.call(\"debug_p2pPeers\", []);\n }\n\n /** `debug_stateDiff` — state-diff for a block range. */\n async debugStateDiff(params: unknown): Promise<unknown> {\n return this.call(\"debug_stateDiff\", params);\n }\n\n /** `debug_chainReorg` — testnet-only reorg trigger. */\n async debugChainReorg(params: unknown): Promise<unknown> {\n return this.call(\"debug_chainReorg\", params);\n }\n\n // ---- mesh_* -------------------------------------------------------\n\n /** `mesh_buildUnsignedTx` — build an unsigned transaction envelope. */\n async meshBuildUnsignedTx(intent: MeshTxIntent): Promise<MeshUnsignedTxResponse> {\n return this.call(\"mesh_buildUnsignedTx\", [intent]);\n }\n\n /** `mesh_combineTx` — combine an unsigned envelope with a wallet signature. */\n async meshCombineTx(\n unsignedTx: string,\n signatureHex: string,\n algo?: \"secp256k1\" | \"ml_dsa_65\" | string,\n pubkeyHex?: string,\n ): Promise<MeshSignedTxResponse> {\n const params =\n algo === undefined\n ? [unsignedTx, signatureHex]\n : pubkeyHex === undefined\n ? [unsignedTx, signatureHex, algo]\n : [unsignedTx, signatureHex, algo, pubkeyHex];\n return this.call(\"mesh_combineTx\", params);\n }\n\n /** `mesh_decodeTx` — decode a signed or unsigned mesh envelope. */\n async meshDecodeTx(envelopeHex: string, signed = false): Promise<MeshDecodedTx> {\n return this.call(\"mesh_decodeTx\", [envelopeHex, signed]);\n }\n\n /** `mesh_submitTx` — submit a signed mesh envelope. */\n async meshSubmitTx(signedTx: string): Promise<string> {\n return this.call(\"mesh_submitTx\", [signedTx]);\n }\n}\n\n/** Decode a `0x`-prefixed hex quantity to a `bigint`. */\nexport function parseQuantityBig(hex: string): bigint {\n if (!hex) return 0n;\n const rest = hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n if (rest.length === 0) return 0n;\n if (!/^[0-9a-fA-F]+$/.test(rest)) {\n throw SdkError.malformed(`invalid hex quantity: ${hex}`);\n }\n return BigInt(`0x${rest}`);\n}\n\n/**\n * Decode a `0x`-prefixed hex quantity to a JS `number`. Convenience for\n * small quantities (chain id, block height, gas estimate). Throws if the\n * value exceeds `Number.MAX_SAFE_INTEGER`.\n */\nexport function parseQuantity(hex: string): number {\n const big = parseQuantityBig(hex);\n if (big > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw SdkError.malformed(`hex quantity exceeds safe integer: ${hex}`);\n }\n return Number(big);\n}\n\nfunction encodeRpcInteger(v: number | bigint | string): number | string {\n if (typeof v === \"bigint\") return `0x${v.toString(16)}`;\n return v;\n}\n\nfunction encodeOptionalHeight(v: number | bigint | string | null): number | string | null {\n if (v === null) return null;\n return encodeRpcInteger(v);\n}\n\nfunction encodeRpcU64Number(v: number | bigint | string, label: string): number {\n return parseRpcNumber(v, label);\n}\n\nexport function nativeEventsFilterParams(filter: NativeEventsFilter): Record<string, unknown> {\n return {\n fromBlock: encodeRpcU64Number(filter.fromBlock, \"fromBlock\"),\n toBlock: encodeRpcU64Number(filter.toBlock, \"toBlock\"),\n ...optionalRpcNumber(\"limit\", filter.limit),\n ...optionalRpcNumber(\"txIndex\", filter.txIndex),\n ...optionalRpcNumber(\"logIndex\", filter.logIndex),\n ...optionalString(\"address\", filter.address),\n ...optionalString(\"eventTopic\", filter.eventTopic),\n ...optionalString(\"family\", filter.family),\n ...optionalString(\"eventName\", filter.eventName),\n ...optionalString(\"primaryId\", filter.primaryId),\n ...optionalString(\"relatedId\", filter.relatedId),\n ...optionalString(\"tokenId\", filter.tokenId),\n ...optionalString(\"account\", filter.account),\n ...optionalString(\"counterparty\", filter.counterparty),\n };\n}\n\nfunction optionalRpcNumber(\n key: string,\n value: number | bigint | string | null | undefined,\n): Record<string, number> {\n return value == null ? {} : { [key]: encodeRpcU64Number(value, key) };\n}\n\nfunction optionalString(key: string, value: string | null | undefined): Record<string, string> {\n return value == null ? {} : { [key]: value };\n}\n\nfunction parseRpcBigint(value: unknown, label: string): bigint {\n if (typeof value === \"bigint\") {\n if (value < 0n) {\n throw SdkError.malformed(`${label} must be a non-negative quantity`);\n }\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw SdkError.malformed(`${label} must be a non-negative safe integer`);\n }\n return BigInt(value);\n }\n if (typeof value === \"string\") {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) return parseQuantityBig(value);\n if (/^\\d+$/.test(value)) return BigInt(value);\n }\n throw SdkError.malformed(`${label} must be a bigint-compatible quantity`);\n}\n\nfunction parseRpcNumber(value: unknown, label: string): number {\n const big = parseRpcBigint(value, label);\n if (big > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw SdkError.malformed(`${label} exceeds safe integer range`);\n }\n return Number(big);\n}\n\nfunction parseRpcNumberNullable(value: unknown, label: string): number | null {\n return value === null || value === undefined ? null : parseRpcNumber(value, label);\n}\n\nfunction parseRpcBigintNullable(value: unknown, label: string): bigint | null {\n return value === null || value === undefined ? null : parseRpcBigint(value, label);\n}\n\nfunction parseStringNullable(value: unknown): string | null {\n return value === null || value === undefined ? null : String(value);\n}\n\nfunction parseStringField(value: unknown, label: string): string {\n if (value === null || value === undefined) {\n throw SdkError.malformed(`${label} is missing`);\n }\n return String(value);\n}\n\nfunction parseBooleanField(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") {\n throw SdkError.malformed(`${label} must be a boolean`);\n }\n return value;\n}\n\nfunction parseRpcUint(value: unknown, label: string, max: number, typeName: string): number {\n const parsed = parseRpcNumber(value, label);\n if (parsed > max) {\n throw SdkError.malformed(`${label} must be a ${typeName}`);\n }\n return parsed;\n}\n\nfunction parseRpcUintNullable(\n value: unknown,\n label: string,\n max: number,\n typeName: string,\n): number | null {\n return value === null || value === undefined ? null : parseRpcUint(value, label, max, typeName);\n}\n\nfunction decodeNativeAgentStateArray<T>(\n row: Record<string, unknown>,\n key: string,\n decode: (value: unknown, label: string) => T,\n defaultMissing: boolean,\n): T[] {\n const value = row[key];\n if (value === undefined && defaultMissing) return [];\n if (!Array.isArray(value)) {\n throw SdkError.malformed(`native agent state ${key} must be an array`);\n }\n return value.map((item, index) => decode(item, `native agent state ${key}[${index}]`));\n}\n\nfunction decodeNativeAgentExistingStateRecord<T>(value: unknown, label: string): T {\n return expectObject(value, label) as unknown as T;\n}\n\nfunction decodeNativeAgentIssuerStateRecord(\n value: unknown,\n label: string,\n): NativeAgentIssuerStateRecord {\n const row = expectObject(value, label);\n return {\n issuerId: parseStringField(row[\"issuerId\"], `${label}.issuerId`),\n issuer: parseStringField(row[\"issuer\"], `${label}.issuer`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentAttestationStateRecord(\n value: unknown,\n label: string,\n): NativeAgentAttestationStateRecord {\n const row = expectObject(value, label);\n return {\n attestationId: parseStringField(row[\"attestationId\"], `${label}.attestationId`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n issuerId: parseStringNullable(row[\"issuerId\"]),\n issuer: parseStringNullable(row[\"issuer\"]),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n schemaHash: parseStringNullable(row[\"schemaHash\"]),\n payloadHash: parseStringNullable(row[\"payloadHash\"]),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentConsentStateRecord(\n value: unknown,\n label: string,\n): NativeAgentConsentStateRecord {\n const row = expectObject(value, label);\n return {\n consentId: parseStringField(row[\"consentId\"], `${label}.consentId`),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n grantee: parseStringField(row[\"grantee\"], `${label}.grantee`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n scopeHash: parseStringNullable(row[\"scopeHash\"]),\n expiresAt: parseRpcNumberNullable(row[\"expiresAt\"], `${label}.expiresAt`),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentServiceStateRecord(\n value: unknown,\n label: string,\n): NativeAgentServiceStateRecord {\n const row = expectObject(value, label);\n return {\n serviceId: parseStringField(row[\"serviceId\"], `${label}.serviceId`),\n provider: parseStringField(row[\"provider\"], `${label}.provider`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n categoryHash: parseStringNullable(row[\"categoryHash\"]),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentAvailabilityStateRecord(\n value: unknown,\n label: string,\n): NativeAgentAvailabilityStateRecord {\n const row = expectObject(value, label);\n return {\n provider: parseStringField(row[\"provider\"], `${label}.provider`),\n maxConcurrent: parseRpcUint(row[\"maxConcurrent\"], `${label}.maxConcurrent`, 0xffffffff, \"uint32\"),\n openRequests: parseRpcUint(row[\"openRequests\"], `${label}.openRequests`, 0xffffffff, \"uint32\"),\n paused: parseBooleanField(row[\"paused\"], `${label}.paused`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentArbiterStateRecord(\n value: unknown,\n label: string,\n): NativeAgentArbiterStateRecord {\n const row = expectObject(value, label);\n return {\n arbiterId: parseStringField(row[\"arbiterId\"], `${label}.arbiterId`),\n arbiter: parseStringField(row[\"arbiter\"], `${label}.arbiter`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n tier: parseRpcUintNullable(row[\"tier\"], `${label}.tier`, 0xffff, \"uint16\"),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentReputationReviewStateRecord(\n value: unknown,\n label: string,\n): NativeAgentReputationReviewStateRecord {\n const row = expectObject(value, label);\n return {\n reviewId: parseStringField(row[\"reviewId\"], `${label}.reviewId`),\n reviewer: parseStringField(row[\"reviewer\"], `${label}.reviewer`),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n categoryId: parseRpcUint(row[\"categoryId\"], `${label}.categoryId`, 0xffffffff, \"uint32\"),\n speedScore: parseRpcUint(row[\"speedScore\"], `${label}.speedScore`, 0xff, \"uint8\"),\n qualityScore: parseRpcUint(row[\"qualityScore\"], `${label}.qualityScore`, 0xff, \"uint8\"),\n communicationScore: parseRpcUint(\n row[\"communicationScore\"],\n `${label}.communicationScore`,\n 0xff,\n \"uint8\",\n ),\n accuracyScore: parseRpcUint(row[\"accuracyScore\"], `${label}.accuracyScore`, 0xff, \"uint8\"),\n payloadHash: parseStringNullable(row[\"payloadHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction expectObject(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw SdkError.malformed(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nexport function decodeNativeReceiptResponse<TDecoded = unknown>(\n value: unknown,\n): NativeReceiptResponse<TDecoded> {\n const row = expectObject(value, \"native receipt response\");\n assertNativeReceiptFee(row[\"fee\"], \"native receipt response.fee\");\n return value as NativeReceiptResponse<TDecoded>;\n}\n\nexport function decodeTxFeedResponse(value: unknown): TxFeedResponse {\n const row = expectObject(value, \"tx feed response\");\n const transactions = row[\"transactions\"];\n if (!Array.isArray(transactions)) {\n throw SdkError.malformed(\"tx feed response.transactions must be an array\");\n }\n transactions.forEach((transaction, index) => {\n const tx = expectObject(transaction, `tx feed response.transactions[${index}]`);\n assertNativeReceiptFee(tx[\"fee\"], `tx feed response.transactions[${index}].fee`);\n });\n return value as TxFeedResponse;\n}\n\nfunction assertNativeReceiptFee(value: unknown, label: string): asserts value is NativeReceiptFee {\n try {\n assertMrvStructuredFeeConformance(value, { label });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw SdkError.malformed(`structured native fee violation: ${message}`);\n }\n}\n\nfunction firstField(row: Record<string, unknown>, keys: readonly string[], label: string): unknown {\n for (const key of keys) {\n if (row[key] !== undefined) return row[key];\n }\n throw SdkError.malformed(`${label} is missing (${keys.join(\" | \")})`);\n}\n\nfunction normalizeServiceProbe(value: unknown): ServiceProbeResponse {\n const row = expectObject(value, \"service probe response\");\n return {\n serviceMask: parseRpcNumber(row[\"serviceMask\"], \"service probe serviceMask\"),\n status: String(row[\"status\"]),\n statusCode: parseRpcNumber(row[\"statusCode\"], \"service probe statusCode\"),\n lastProbeBlock: parseRpcNumber(row[\"lastProbeBlock\"], \"service probe lastProbeBlock\"),\n latencyMs: parseRpcNumber(row[\"latencyMs\"], \"service probe latencyMs\"),\n probeDigest: String(row[\"probeDigest\"]),\n reporter: String(row[\"reporter\"]),\n };\n}\n\nfunction assertSafeUint32(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw SdkError.malformed(`${label} must be a uint32`);\n }\n}\n\nfunction assertHexBytes(value: string, expectedLen: number, label: string): void {\n const body = hexBody(value, label);\n if (body.length !== expectedLen * 2) {\n throw SdkError.malformed(`${label} must be ${expectedLen} bytes`);\n }\n}\n\nfunction assertNonEmptyHex(value: string, label: string): void {\n const body = hexBody(value, label);\n if (body.length === 0) {\n throw SdkError.malformed(`${label} must be non-empty`);\n }\n}\n\nfunction hexBody(value: string, label: string): string {\n const body = value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {\n throw SdkError.malformed(`${label} must be hex bytes`);\n }\n return body;\n}\n\nfunction normalizeOperatorInfo(value: unknown): OperatorInfoResponse {\n const row = expectObject(value, \"operator info response\");\n const activeClusterIds = row[\"activeClusterIds\"];\n if (!Array.isArray(activeClusterIds)) {\n throw SdkError.malformed(\"operator info activeClusterIds must be an array\");\n }\n const capability = row[\"capability\"];\n return {\n operatorId: String(row[\"operatorId\"]),\n moniker: parseStringNullable(row[\"moniker\"]),\n alias: parseStringNullable(row[\"alias\"]),\n chainAddress: String(row[\"chainAddress\"]),\n bonded: Boolean(row[\"bonded\"]),\n commissionBps: parseRpcNumberNullable(row[\"commissionBps\"], \"operator info commissionBps\"),\n delegationCount: parseRpcNumberNullable(\n row[\"delegationCount\"],\n \"operator info delegationCount\",\n ),\n bondedAmount: String(row[\"bondedAmount\"]),\n activeClusterIds: activeClusterIds.map((v, i) =>\n parseRpcNumber(v, `operator info activeClusterIds[${i}]`),\n ),\n operatorKeyFingerprint: parseStringNullable(row[\"operatorKeyFingerprint\"]),\n blsKeyFingerprint: parseStringNullable(row[\"blsKeyFingerprint\"]),\n lifecycleState: String(row[\"lifecycleState\"]),\n capability:\n capability && typeof capability === \"object\" && !Array.isArray(capability)\n ? (capability as Record<string, unknown>)\n : {},\n };\n}\n\nfunction normalizeClusterMember(value: unknown, label: string): ClusterMemberResponse {\n const row = expectObject(value, label);\n return {\n operatorId: String(row[\"operatorId\"]),\n blsPubkey: String(row[\"blsPubkey\"]),\n state: String(row[\"state\"]),\n };\n}\n\nfunction normalizeClusterStatus(value: unknown): ClusterStatusResponse {\n const row = expectObject(value, \"cluster status response\");\n const members = row[\"members\"];\n if (!Array.isArray(members)) {\n throw SdkError.malformed(\"cluster status members must be an array\");\n }\n return {\n clusterId: parseRpcNumber(row[\"clusterId\"], \"cluster status clusterId\"),\n threshold: parseRpcNumber(row[\"threshold\"], \"cluster status threshold\"),\n size: parseRpcNumber(row[\"size\"], \"cluster status size\"),\n live: parseRpcNumber(row[\"live\"], \"cluster status live\"),\n lagging: parseRpcNumber(row[\"lagging\"], \"cluster status lagging\"),\n offline: parseRpcNumber(row[\"offline\"], \"cluster status offline\"),\n maintenance: parseRpcNumber(row[\"maintenance\"], \"cluster status maintenance\"),\n members: members.map((member, i) => normalizeClusterMember(member, `cluster status members[${i}]`)),\n epoch: parseRpcBigintNullable(row[\"epoch\"], \"cluster status epoch\"),\n round: parseRpcBigintNullable(row[\"round\"], \"cluster status round\"),\n quorum: String(row[\"quorum\"]),\n reputationScore: parseRpcNumberNullable(\n row[\"reputationScore\"],\n \"cluster status reputationScore\",\n ),\n livenessScore: parseRpcNumberNullable(row[\"livenessScore\"], \"cluster status livenessScore\"),\n lastUpdateHeight: parseRpcBigint(row[\"lastUpdateHeight\"], \"cluster status lastUpdateHeight\"),\n };\n}\n\nfunction normalizeClusterDirectoryEntry(value: unknown, label: string): ClusterDirectoryEntryResponse {\n const row = expectObject(value, label);\n const regionDiversity = row[\"regionDiversity\"];\n if (regionDiversity !== null && regionDiversity !== undefined && !Array.isArray(regionDiversity)) {\n throw SdkError.malformed(`${label}.regionDiversity must be an array or null`);\n }\n return {\n clusterId: parseRpcNumber(row[\"clusterId\"], `${label}.clusterId`),\n size: parseRpcNumber(row[\"size\"], `${label}.size`),\n threshold: parseRpcNumber(row[\"threshold\"], `${label}.threshold`),\n aggregateHealth: String(row[\"aggregateHealth\"]),\n regionDiversity: Array.isArray(regionDiversity) ? regionDiversity.map(String) : null,\n active: Boolean(row[\"active\"]),\n };\n}\n\nfunction normalizeClusterDirectoryPage(value: unknown): ClusterDirectoryPageResponse {\n const row = expectObject(value, \"cluster directory response\");\n const clusters = row[\"clusters\"];\n if (!Array.isArray(clusters)) {\n throw SdkError.malformed(\"cluster directory clusters must be an array\");\n }\n return {\n page: parseRpcNumber(row[\"page\"], \"cluster directory page\"),\n limit: parseRpcNumber(row[\"limit\"], \"cluster directory limit\"),\n totalClusters: parseRpcNumber(row[\"totalClusters\"], \"cluster directory totalClusters\"),\n clusters: clusters.map((cluster, i) =>\n normalizeClusterDirectoryEntry(cluster, `cluster directory clusters[${i}]`),\n ),\n };\n}\n\nfunction normalizeOperatorAuthority(value: unknown): OperatorAuthorityResponse {\n const row = expectObject(value, \"operator authority response\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"operator authority schemaVersion\"),\n operatorId: String(row[\"operatorId\"]),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"operator authority authorityIndex\"),\n blsPubkey: String(row[\"blsPubkey\"]),\n active: Boolean(row[\"active\"]),\n };\n}\n\nfunction normalizeSigningActivity(value: unknown): OperatorSigningActivityResponse {\n const row = expectObject(value, \"signing activity response\");\n const entries = row[\"entries\"];\n if (!Array.isArray(entries)) {\n throw SdkError.malformed(\"signing activity entries must be an array\");\n }\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"signing activity schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"signing activity authorityIndex\"),\n currentRound: parseRpcBigint(row[\"currentRound\"], \"signing activity currentRound\"),\n limit: parseRpcNumber(row[\"limit\"], \"signing activity limit\"),\n entries: entries.map((entry, i) => {\n const e = expectObject(entry, `signing activity entries[${i}]`);\n return {\n round: parseRpcBigint(e[\"round\"], `signing activity entries[${i}].round`),\n status: String(e[\"status\"]),\n };\n }),\n };\n}\n\nfunction normalizeDutyAbsence(value: unknown, label: string): DutyAbsence {\n const row = expectObject(value, label);\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeKeyRotationWindow(value: unknown): KeyRotationWindow {\n const row = expectObject(value, \"upcoming duties keyRotation\");\n if (\"nextRound\" in row) {\n return {\n nextRound: parseRpcBigint(row[\"nextRound\"], \"upcoming duties keyRotation.nextRound\"),\n epochLengthRounds: parseRpcBigint(\n row[\"epochLengthRounds\"],\n \"upcoming duties keyRotation.epochLengthRounds\",\n ),\n };\n }\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeUpcomingDuties(value: unknown): UpcomingDutiesResponse {\n const row = expectObject(value, \"upcoming duties response\");\n const duties = expectObject(row[\"duties\"], \"upcoming duties duties\");\n const attestation = expectObject(duties[\"attestation\"], \"upcoming duties attestation\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"upcoming duties schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"upcoming duties authorityIndex\"),\n currentRound: parseRpcBigint(row[\"currentRound\"], \"upcoming duties currentRound\"),\n horizonRounds: parseRpcNumber(row[\"horizonRounds\"], \"upcoming duties horizonRounds\"),\n duties: {\n attestation: {\n startRound: parseRpcBigint(attestation[\"startRound\"], \"upcoming duties attestation.startRound\"),\n endRound: parseRpcBigint(attestation[\"endRound\"], \"upcoming duties attestation.endRound\"),\n kind: String(attestation[\"kind\"]),\n },\n blockProduction: normalizeDutyAbsence(\n duties[\"blockProduction\"],\n \"upcoming duties blockProduction\",\n ),\n sync: normalizeDutyAbsence(duties[\"sync\"], \"upcoming duties sync\"),\n keyRotation: normalizeKeyRotationWindow(duties[\"keyRotation\"]),\n },\n };\n}\n\nfunction normalizeJailStatus(value: unknown): JailStatusWindow {\n const row = expectObject(value, \"operator risk jailStatus\");\n if (\"jailed\" in row || \"tombstoned\" in row) {\n return {\n jailed: Boolean(row[\"jailed\"]),\n tombstoned: Boolean(row[\"tombstoned\"]),\n jailedUntilHeight: parseRpcBigint(\n row[\"jailedUntilHeight\"],\n \"operator risk jailStatus.jailedUntilHeight\",\n ),\n unjailCount: parseRpcBigint(row[\"unjailCount\"], \"operator risk jailStatus.unjailCount\"),\n };\n }\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeOperatorRisk(value: unknown): OperatorRiskResponse {\n const row = expectObject(value, \"operator risk response\");\n const reasons = row[\"reasons\"];\n if (!Array.isArray(reasons)) {\n throw SdkError.malformed(\"operator risk reasons must be an array\");\n }\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"operator risk schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"operator risk authorityIndex\"),\n dataHeight: parseRpcBigint(row[\"dataHeight\"], \"operator risk dataHeight\"),\n windowRounds: parseRpcNumber(row[\"windowRounds\"], \"operator risk windowRounds\"),\n missedRounds: parseRpcNumber(row[\"missedRounds\"], \"operator risk missedRounds\"),\n observedRounds: parseRpcNumber(row[\"observedRounds\"], \"operator risk observedRounds\"),\n missRateBps: parseRpcNumber(row[\"missRateBps\"], \"operator risk missRateBps\"),\n thresholdBps: parseRpcNumber(row[\"thresholdBps\"], \"operator risk thresholdBps\"),\n remainingHeadroomBps: parseRpcNumber(\n row[\"remainingHeadroomBps\"],\n \"operator risk remainingHeadroomBps\",\n ),\n jailStatus: normalizeJailStatus(row[\"jailStatus\"]),\n reasons: reasons.map(String),\n };\n}\n\nexport function nativeAgentStateFilterParams(\n filter: NativeAgentStateFilter,\n): Record<string, NativeAgentStateFilterParamValue> {\n const out: Record<string, NativeAgentStateFilterParamValue> = {};\n if (filter.policyId != null) out.policyId = filter.policyId;\n if (filter.escrowId != null) out.escrowId = filter.escrowId;\n if (filter.account != null) out.account = filter.account;\n if (filter.includePolicySpends != null) out.includePolicySpends = filter.includePolicySpends;\n if (filter.limit != null) out.limit = encodeRpcU64Number(filter.limit, \"limit\");\n return out;\n}\n\nexport function decodeNativeAgentStateResponse(value: unknown): NativeAgentStateResponse {\n const row = expectObject(value, \"native agent state response\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"native agent state schemaVersion\"),\n limit: parseRpcNumber(row[\"limit\"], \"native agent state limit\"),\n filters: expectObject(\n row[\"filters\"],\n \"native agent state filters\",\n ) as unknown as NativeAgentStateResponseFilters,\n issuers: decodeNativeAgentStateArray(\n row,\n \"issuers\",\n decodeNativeAgentIssuerStateRecord,\n true,\n ),\n attestations: decodeNativeAgentStateArray(\n row,\n \"attestations\",\n decodeNativeAgentAttestationStateRecord,\n true,\n ),\n consents: decodeNativeAgentStateArray(\n row,\n \"consents\",\n decodeNativeAgentConsentStateRecord,\n true,\n ),\n services: decodeNativeAgentStateArray(\n row,\n \"services\",\n decodeNativeAgentServiceStateRecord,\n true,\n ),\n availability: decodeNativeAgentStateArray(\n row,\n \"availability\",\n decodeNativeAgentAvailabilityStateRecord,\n true,\n ),\n arbiters: decodeNativeAgentStateArray(\n row,\n \"arbiters\",\n decodeNativeAgentArbiterStateRecord,\n true,\n ),\n reputationReviews: decodeNativeAgentStateArray(\n row,\n \"reputationReviews\",\n decodeNativeAgentReputationReviewStateRecord,\n true,\n ),\n spendingPolicies: decodeNativeAgentStateArray(\n row,\n \"spendingPolicies\",\n decodeNativeAgentExistingStateRecord<NativeAgentPolicyStateRecord>,\n false,\n ),\n policySpends: decodeNativeAgentStateArray(\n row,\n \"policySpends\",\n decodeNativeAgentExistingStateRecord<NativeAgentPolicySpendStateRecord>,\n false,\n ),\n escrows: decodeNativeAgentStateArray(\n row,\n \"escrows\",\n decodeNativeAgentExistingStateRecord<NativeAgentEscrowStateRecord>,\n false,\n ),\n source: expectObject(\n row[\"source\"],\n \"native agent state source\",\n ) as unknown as NativeAgentStateSource,\n };\n}\n\nexport function nativeMarketStateFilterParams(\n filter: NativeMarketStateFilter,\n): Record<string, NativeMarketStateFilterParamValue> {\n const out: Record<string, NativeMarketStateFilterParamValue> = {};\n if (filter.marketId != null) out.marketId = filter.marketId;\n if (filter.orderId != null) out.orderId = filter.orderId;\n if (filter.listingId != null) out.listingId = filter.listingId;\n if (filter.collectionId != null) out.collectionId = filter.collectionId;\n if (filter.account != null) out.account = filter.account;\n if (filter.includeSpotOrders != null) out.includeSpotOrders = filter.includeSpotOrders;\n if (filter.limit != null) out.limit = encodeRpcU64Number(filter.limit, \"limit\");\n return out;\n}\n\nfunction normalizeBlockHeader(value: unknown): BlockHeader | null {\n if (value === null || value === undefined) return null;\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"block header must be an object or null\");\n }\n const h = value as Record<string, unknown>;\n return {\n number: parseRpcBigint(h[\"number\"], \"block header number\"),\n hash: String(h[\"hash\"]),\n parent_hash: String(firstField(h, [\"parent_hash\", \"parentHash\"], \"block header parent hash\")),\n state_root: String(firstField(h, [\"state_root\", \"stateRoot\"], \"block header state root\")),\n timestamp: parseRpcBigint(h[\"timestamp\"], \"block header timestamp\"),\n executionUnitsUsed: parseRpcBigint(\n firstField(\n h,\n [\"executionUnitsUsed\", \"execution_units_used\", \"gas_used\", \"gasUsed\"],\n \"block header execution units used\",\n ),\n \"block header execution units used\",\n ),\n executionUnitLimit: parseRpcBigint(\n firstField(\n h,\n [\"executionUnitLimit\", \"execution_unit_limit\", \"gas_limit\", \"gasLimit\"],\n \"block header execution unit limit\",\n ),\n \"block header execution unit limit\",\n ),\n };\n}\n\nfunction normalizeTransactionReceipt(value: unknown): TransactionReceipt | null {\n if (value === null || value === undefined) return null;\n const r = expectObject(value, \"transaction receipt\");\n return {\n tx_hash: String(\n firstField(r, [\"tx_hash\", \"txHash\", \"transactionHash\"], \"transaction receipt tx hash\"),\n ),\n block_hash: String(\n firstField(r, [\"block_hash\", \"blockHash\"], \"transaction receipt block hash\"),\n ),\n block_number: parseRpcBigint(\n firstField(r, [\"block_number\", \"blockNumber\"], \"transaction receipt block number\"),\n \"transaction receipt block number\",\n ),\n tx_index: parseRpcNumber(\n firstField(r, [\"tx_index\", \"txIndex\", \"transactionIndex\"], \"transaction receipt tx index\"),\n \"transaction receipt tx index\",\n ),\n status: parseRpcNumber(firstField(r, [\"status\"], \"transaction receipt status\"), \"transaction receipt status\"),\n executionUnitsUsed: parseRpcBigint(\n firstField(\n r,\n [\"executionUnitsUsed\", \"execution_units_used\", \"gas_used\", \"gasUsed\"],\n \"transaction receipt execution units used\",\n ),\n \"transaction receipt execution units used\",\n ),\n };\n}\n\nfunction sdkTypedAddress(address: string, kind: AddressKind, label: string): string {\n try {\n return requireTypedAddress(address, kind, label);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw SdkError.malformed(message);\n }\n}\n\nfunction normalizeRoundInfo(value: unknown): RoundInfo {\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"round info must be an object\");\n }\n const row = value as Record<string, unknown>;\n return {\n height: parseRpcBigint(row[\"height\"], \"round height\"),\n };\n}\n\nfunction normalizeMempoolSnapshot(value: unknown): MempoolSnapshot {\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"mempool snapshot must be an object\");\n }\n const row = value as Record<string, unknown>;\n const bytesByClass = row[\"bytes_by_class\"];\n if (!Array.isArray(bytesByClass) || bytesByClass.length !== 7) {\n throw SdkError.malformed(\"mempool bytes_by_class must contain 7 entries\");\n }\n return {\n count_ready: parseRpcBigint(row[\"count_ready\"], \"mempool count_ready\"),\n count_pending: parseRpcBigint(row[\"count_pending\"], \"mempool count_pending\"),\n mailbox_depth: parseRpcBigint(row[\"mailbox_depth\"], \"mempool mailbox_depth\"),\n bytes_by_class: bytesByClass.map((v, i) => parseRpcBigint(v, `mempool bytes_by_class[${i}]`)) as MempoolSnapshot[\"bytes_by_class\"],\n };\n}\n\nfunction normalizeCapabilitiesResponse(value: CapabilitiesResponse): CapabilitiesResponse {\n return {\n ...value,\n nativeModuleForwarders: value.nativeModuleForwarders ?? {},\n };\n}\n","/**\n * Network identity for the ethers.js compat shim.\n *\n * Monolythium testnet `chain_id` is **`69420`**.\n * Mainnet chain id is reserved for the genesis ceremony and not yet\n * exported.\n */\n\n/** Monolythium v4.1 testnet chain id. */\nexport const MONOLYTHIUM_TESTNET_CHAIN_ID = 69420n;\n\n/** Network name surfaced to ethers `Network` instances. */\nexport const MONOLYTHIUM_TESTNET_NETWORK_NAME = \"monolythium-testnet\";\n\n/**\n * Built-in network presets for the ethers shim. Callers that point at a\n * different chain id (e.g. a local dev node) construct `MonolythiumProvider`\n * with an explicit `network` option instead.\n */\nexport const MONOLYTHIUM_NETWORKS = {\n testnet: {\n chainId: MONOLYTHIUM_TESTNET_CHAIN_ID,\n name: MONOLYTHIUM_TESTNET_NETWORK_NAME,\n },\n} as const;\n\n/** Configuration object accepted by the ethers shim factory functions. */\nexport interface MonolythiumNetworkConfig {\n /** Numeric chain id (e.g. `69420n`). */\n chainId: bigint;\n /** Human-readable network name. */\n name: string;\n}\n","/**\n * `MonolythiumProvider` — ethers v6 `JsonRpcApiProvider` that routes\n * every call through the native `RpcClient`.\n *\n * `JsonRpcApiProvider` already knows how to translate the rich\n * `_perform(req)` surface into the standard `eth_*` JSON-RPC calls,\n * so we only need to override `_send`: instead of opening its own\n * fetch transport, we reuse the SDK's transport and `lyth_*`-aware\n * error handling.\n *\n * That keeps a single transport in the process — no double-counted\n * connection pools, no duplicated retry/backoff logic, and any\n * future SDK-side feature (auth headers, ws upgrade, registry-based\n * routing) lights up for ethers callers automatically.\n *\n * **SDK-only compat.** This shim never alters the chain's wire. It wraps\n * compatibility JSON-RPC methods in ethers' interface for migration scripts;\n * current v4.1 app paths should use native MRV/RISC-V builders and `lyth_*`\n * read surfaces.\n */\n\nimport {\n type JsonRpcPayload,\n type JsonRpcResult,\n type JsonRpcError,\n JsonRpcApiProvider,\n Network,\n} from \"ethers\";\nimport { RpcClient, type RpcClientOptions } from \"../client.js\";\nimport { SdkError } from \"../error.js\";\nimport {\n MONOLYTHIUM_TESTNET_CHAIN_ID,\n MONOLYTHIUM_TESTNET_NETWORK_NAME,\n type MonolythiumNetworkConfig,\n} from \"./network.js\";\n\n/** Optional configuration for `MonolythiumProvider`. */\nexport interface MonolythiumProviderOptions extends RpcClientOptions {\n /**\n * Override the chain id / network name surfaced to ethers. Defaults\n * to the Monolythium v4.1 testnet preset (`chain_id` `69420`, name\n * `monolythium-testnet`).\n */\n network?: MonolythiumNetworkConfig;\n}\n\n/**\n * `MonolythiumProvider` adapts `mono-core`'s JSON-RPC surface to\n * ethers v6.\n *\n * Use it the same way you'd use any ethers provider:\n *\n * ```ts\n * import { MonolythiumProvider } from \"@monolythium/core-sdk/ethers\";\n *\n * const provider = new MonolythiumProvider(\"https://rpc.testnet.monolythium.com\");\n * const block = await provider.getBlockNumber();\n * ```\n *\n * Legacy ethers actions such as `getBlockNumber`, `getBalance`,\n * `getTransactionReceipt`, `call`, `estimateGas`, and\n * `broadcastTransaction` flow through `RpcClient.call`, so no-EVM profiles\n * may reject unsupported compatibility methods server-side.\n */\nexport class MonolythiumProvider extends JsonRpcApiProvider {\n /** Underlying SDK client. Exposed for callers that want native types. */\n readonly rpcClient: RpcClient;\n\n constructor(\n endpointOrClient: string | RpcClient,\n options: MonolythiumProviderOptions = {},\n ) {\n const network = options.network ?? {\n chainId: MONOLYTHIUM_TESTNET_CHAIN_ID,\n name: MONOLYTHIUM_TESTNET_NETWORK_NAME,\n };\n // `Network`'s constructor takes `BigNumberish` for `chainId`, which\n // accepts a `bigint` directly — `Networkish` (the literal-shape\n // alternative) restricts to `number`, which would clip our `69420n`\n // testnet id when callers point at a chain id past `Number.MAX_SAFE_INTEGER`.\n //\n // We register the name with ethers' global registry on first\n // construction so any later `Network.from(name)` resolves cleanly,\n // but swallow the error when the same name is registered twice\n // (re-instantiation in tests, multiple shim consumers in one\n // process — both legitimate).\n try {\n Network.register(\n network.name,\n () => new Network(network.name, network.chainId),\n );\n } catch (_e) {\n // already registered — fine, fall through.\n }\n super(new Network(network.name, network.chainId));\n\n this.rpcClient =\n typeof endpointOrClient === \"string\"\n ? new RpcClient(endpointOrClient, {\n fetch: options.fetch,\n headers: options.headers,\n })\n : endpointOrClient;\n }\n\n /**\n * Forward a single JSON-RPC method through the SDK transport. Ethers'\n * `_perform` calls this and ethers callers can also call `provider.send`\n * directly to access methods the rich provider interface does not wrap\n * (e.g. `lyth_*`).\n */\n override async _send(\n payload: JsonRpcPayload | Array<JsonRpcPayload>,\n ): Promise<Array<JsonRpcResult | JsonRpcError>> {\n const calls = Array.isArray(payload) ? payload : [payload];\n return Promise.all(calls.map((p) => this.#sendOne(p)));\n }\n\n async #sendOne(p: JsonRpcPayload): Promise<JsonRpcResult | JsonRpcError> {\n try {\n const params = Array.isArray(p.params)\n ? p.params\n : p.params === undefined\n ? []\n : (p.params as unknown[]);\n const result = await this.rpcClient.call<unknown>(p.method, params);\n return { id: p.id, result };\n } catch (e) {\n if (e instanceof SdkError && e.kind === \"rpc\") {\n return {\n id: p.id,\n error: {\n code: e.code ?? -32603,\n message: e.message,\n data: e.data,\n },\n };\n }\n // Transport / malformed / endpoint errors don't have a JSON-RPC\n // shape — surface them as a generic internal error so ethers'\n // own error wrapper can pick them up cleanly.\n const msg = (e as Error)?.message ?? String(e);\n return {\n id: p.id,\n error: { code: -32603, message: `${msg}` },\n };\n }\n }\n}\n","/**\n * `MonolythiumSigner` — ethers v6 `AbstractSigner` adapter.\n *\n * Two backend strategies are supported, both via the same external\n * surface — `getAddress`, `signTransaction`, `signMessage`,\n * `signTypedData`:\n *\n * 1. **`fromEthersWallet`** — wraps a normal `ethers.Wallet`\n * (secp256k1). Useful for tests, scripts, and any path where the\n * user already has an Ethereum-style key. The SDK does not store\n * the key — the wallet does.\n *\n * 2. **`MonolythiumSignerBackend`** — generic interface a non-ethers\n * backend (keychain, hardware wallet, future ML-DSA-65 signer)\n * implements to plug into ethers without forcing the SDK to take\n * a hard ethers dependency on either the chain side or the\n * consumer side.\n *\n * Native Mono address derivation is ADR-0038:\n * `BLAKE3(\"MONO_ADDRESS_BLAKE3_20_V1\" || algo_id_be_u16 ||\n * canonical_pubkey_bytes)[0..20]`. `fromEthersWallet` preserves the\n * wrapped ethers address only for the compatibility signer path; native\n * ML-DSA-65 callers should use the crypto helpers directly.\n *\n * **What the shim is not.** This is SDK-level compat (per\n * `feedback_no_ethereum_wire_retrofit.md`). The chain's protocol-native\n * signing path is ML-DSA-65 (Law §2.1); ethers cannot produce ML-DSA\n * signatures, and the chain accepts secp256k1 only via the\n * crypto-agile `SignedTransaction` envelope. Use\n * `MonolythiumSignerBackend` to plug a native ML-DSA path in.\n */\n\nimport {\n AbstractSigner,\n type BaseWallet,\n type Provider,\n type Signer as EthersSigner,\n type TransactionRequest,\n type TypedDataDomain,\n type TypedDataField,\n} from \"ethers\";\n\n/**\n * Backend the `MonolythiumSigner` delegates signing to.\n *\n * The intent is to let consumers wire up any signing source — local\n * keystore, OS keychain, hardware wallet, or a future ML-DSA-65\n * adapter — without the shim forcing a particular implementation.\n *\n * Every method's return shape mirrors what ethers'\n * `AbstractSigner` callers expect, so the backend can compose with\n * any tooling built on ethers.\n */\nexport interface MonolythiumSignerBackend {\n /** Resolves to the 20-byte 0x-hex address (Law §2.6 derivation). */\n getAddress(): Promise<string>;\n\n /**\n * Resolves to a fully-encoded raw signed transaction (a 0x-hex\n * string). For secp256k1 this is the canonical EIP-1559 RLP that\n * `eth_sendRawTransaction` expects.\n */\n signTransaction(tx: TransactionRequest): Promise<string>;\n\n /**\n * Resolves to an EIP-191 personal-sign signature (`0x` + 65 bytes\n * for secp256k1 / variable for non-recoverable algorithms).\n */\n signMessage(message: string | Uint8Array): Promise<string>;\n\n /** Resolves to an EIP-712 typed-data signature. */\n signTypedData(\n domain: TypedDataDomain,\n types: Record<string, Array<TypedDataField>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n}\n\n/**\n * `MonolythiumSigner` — ethers v6 `Signer` for the Monolythium chain.\n *\n * Construct one of three ways:\n *\n * 1. `MonolythiumSigner.fromEthersWallet(wallet, provider)` — the\n * fastest path; wraps a normal `ethers.Wallet`.\n * 2. `new MonolythiumSigner(backend, provider)` — supply any object\n * implementing `MonolythiumSignerBackend`.\n *\n * The signer is compatible with ethers v6 migration flows: it can be passed\n * anywhere a `Signer` is accepted and supports legacy contract deploy/call\n * helpers plus `provider.broadcastTransaction(signed)`. New v4.1 app paths\n * should use native MRV/RISC-V builders instead.\n */\nexport class MonolythiumSigner extends AbstractSigner<Provider | null> {\n readonly #backend: MonolythiumSignerBackend;\n\n constructor(backend: MonolythiumSignerBackend, provider?: Provider | null) {\n super(provider ?? null);\n this.#backend = backend;\n }\n\n /**\n * Wrap any ethers v6 `BaseWallet` (the parent class of `Wallet`,\n * `HDNodeWallet`, and friends) so callers don't have to write a\n * `MonolythiumSignerBackend` for the common test / dev path.\n *\n * Both `new Wallet(privateKey)` and `Wallet.createRandom()` /\n * `HDNodeWallet.fromMnemonic(...)` are accepted.\n */\n static fromEthersWallet(\n wallet: BaseWallet,\n provider?: Provider | null,\n ): MonolythiumSigner {\n const backend: MonolythiumSignerBackend = {\n getAddress: async () => wallet.address,\n signTransaction: (tx) => wallet.signTransaction(tx),\n signMessage: (message) => wallet.signMessage(message),\n signTypedData: (domain, types, value) =>\n wallet.signTypedData(domain, types, value),\n };\n return new MonolythiumSigner(backend, provider);\n }\n\n override async getAddress(): Promise<string> {\n return this.#backend.getAddress();\n }\n\n override connect(provider: Provider | null): EthersSigner {\n return new MonolythiumSigner(this.#backend, provider);\n }\n\n override async signTransaction(tx: TransactionRequest): Promise<string> {\n return this.#backend.signTransaction(tx);\n }\n\n override async signMessage(message: string | Uint8Array): Promise<string> {\n return this.#backend.signMessage(message);\n }\n\n override async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, Array<TypedDataField>>,\n value: Record<string, unknown>,\n ): Promise<string> {\n return this.#backend.signTypedData(domain, types, value);\n }\n}\n","/**\n * Tx wire translation between ethers.js and `mono-core`.\n *\n * The chain natively accepts EIP-1559-shape EVM transactions on the\n * `Tx::Evm` (kind tag `0x01`) wire path — a `SignedTransaction` payload\n * carries the legacy EIP-1559 envelope plus the secp256k1 signature.\n * That makes the round-trip simple: ethers produces the canonical\n * EIP-1559 RLP, the client posts it via `eth_sendRawTransaction`, the\n * chain decodes it, and the receipt comes back through the same\n * `eth_getTransactionReceipt` shape ethers expects.\n *\n * Two notes for any future maintainer:\n *\n * 1. **No chain-level Ethereum retrofit.** This shim is SDK-only — see\n * `feedback_no_ethereum_wire_retrofit.md`. The chain keeps its\n * custom envelope and native tx hash for the protocol-native path\n * (ML-DSA-65 signing, native tx kinds beyond EVM). The shim only\n * spans the **EIP-1559 EVM subset** of the chain's tx surface.\n * 2. **Fields ethers does not see.** Monolythium-specific extension\n * fields (privacy flags, native tx kinds, ML-DSA-65 signatures) are\n * intentionally dropped by these helpers. Callers that need those\n * surfaces use the native SDK signer trait, not the ethers shim.\n */\n\nimport type { CallRequest } from \"../bindings/CallRequest.js\";\nimport type { TransactionReceipt as MonoTransactionReceipt } from \"../bindings/TransactionReceipt.js\";\n\n/**\n * The EIP-1559 subset of fields ethers' `TransactionRequest` carries\n * across the shim. We don't import ethers' type here so the shim can be\n * compiled (and its types re-exported) even when ethers isn't installed\n * — ethers is a peerDependency, not a hard dependency.\n */\nexport interface EthersTxRequestSubset {\n to?: string | null;\n from?: string | null;\n nonce?: number | bigint | null;\n gasLimit?: bigint | string | null;\n gasPrice?: bigint | string | null;\n maxFeePerGas?: bigint | string | null;\n maxPriorityFeePerGas?: bigint | string | null;\n value?: bigint | string | null;\n data?: string | null;\n chainId?: bigint | number | null;\n type?: number | null;\n}\n\n/** `0x`-prefixed hex helpers — kept local so this module has no import surface. */\nfunction toHexQuantity(v: bigint | number | string | null | undefined): string | undefined {\n if (v === null || v === undefined) return undefined;\n if (typeof v === \"string\") {\n if (v.startsWith(\"0x\") || v.startsWith(\"0X\")) return v;\n // Ethers occasionally hands us decimal strings — be lenient.\n return `0x${BigInt(v).toString(16)}`;\n }\n if (typeof v === \"number\") return `0x${v.toString(16)}`;\n return `0x${v.toString(16)}`;\n}\n\n/**\n * Translate ethers' `TransactionRequest` into the wire shape the\n * `mono-core` JSON-RPC accepts for `eth_call` / `eth_estimateGas`.\n *\n * Returns the SDK's `CallRequest` shape (which mirrors the chain's\n * accepted `eth_call` argument). Round-trips losslessly for the\n * EIP-1559 EVM subset; Monolythium-specific extension fields are\n * intentionally not surfaced here.\n */\nexport function translateTxIn(req: EthersTxRequestSubset): CallRequest {\n const out: CallRequest = {};\n if (req.from !== undefined && req.from !== null) out.from = req.from;\n if (req.to !== undefined && req.to !== null) out.to = req.to;\n const gas = toHexQuantity(req.gasLimit);\n if (gas !== undefined) out.gas = gas;\n // Use `gasPrice` for legacy / non-EIP-1559 paths. EIP-1559 priority +\n // fee fields are not part of the v0.0.x server's `eth_call` shape; the\n // chain ignores them on dry-runs.\n const gasPrice = toHexQuantity(req.gasPrice);\n if (gasPrice !== undefined) out.gasPrice = gasPrice;\n const value = toHexQuantity(req.value);\n if (value !== undefined) out.value = value;\n if (req.data !== undefined && req.data !== null) out.data = req.data;\n return out;\n}\n\n/**\n * The ethers v6 wire shape for `eth_getTransactionReceipt`. We hand-roll\n * this rather than importing ethers' internal types because the shim\n * has to compile without ethers installed (peerDependency).\n *\n * Field naming and casing match what `JsonRpcApiProvider._perform` expects\n * back — the provider then normalises into ethers' rich\n * `TransactionReceipt` for callers.\n */\nexport interface EthersReceiptShape {\n transactionHash: string;\n blockHash: string;\n blockNumber: string; // 0x-hex\n transactionIndex: string; // 0x-hex\n status: string; // \"0x0\" | \"0x1\"\n gasUsed: string; // 0x-hex\n cumulativeGasUsed: string; // 0x-hex\n effectiveGasPrice: string; // 0x-hex\n contractAddress: string | null;\n from: string;\n to: string | null;\n type: string; // 0x-hex\n logsBloom: string; // 0x-hex 256 bytes\n logs: unknown[];\n}\n\n/**\n * Translate `mono-core`'s native `TransactionReceipt` into the wire\n * shape ethers expects. Required for `eth_getTransactionReceipt` to\n * surface a usable `TransactionResponse` to ethers callers.\n *\n * The chain's receipt today is intentionally narrow — log emission,\n * cumulative execution-unit aggregation, and effective-fee disclosure are\n * tracked OI items. This translator fills in zero-equivalent values for\n * those gaps; callers that need the full native surface consume the SDK\n * receipt shape directly.\n */\nexport function translateReceiptOut(\n monoReceipt: MonoTransactionReceipt,\n fromAddress: string | null,\n toAddress: string | null,\n): EthersReceiptShape {\n return {\n transactionHash: monoReceipt.tx_hash,\n blockHash: monoReceipt.block_hash,\n blockNumber: `0x${BigInt(monoReceipt.block_number).toString(16)}`,\n transactionIndex: `0x${monoReceipt.tx_index.toString(16)}`,\n status: monoReceipt.status === 1 ? \"0x1\" : \"0x0\",\n gasUsed: `0x${BigInt(monoReceipt.executionUnitsUsed).toString(16)}`,\n cumulativeGasUsed: `0x${BigInt(monoReceipt.executionUnitsUsed).toString(16)}`,\n effectiveGasPrice: \"0x0\",\n contractAddress: null,\n from: fromAddress ?? \"0x0000000000000000000000000000000000000000\",\n to: toAddress,\n type: \"0x2\",\n logsBloom: `0x${\"0\".repeat(512)}`,\n logs: [],\n };\n}\n\n/**\n * Translate `mono-core`'s `BlockHeader` into the ethers v6 wire shape\n * for `eth_getBlockByNumber` / `eth_getBlockByHash`.\n *\n * The chain's block header is intentionally narrower than Ethereum's\n * — it omits fields that don't exist in Monolythium (uncles, mix hash,\n * difficulty, nonce, sha3Uncles). This translator emits zero-valued\n * stand-ins so ethers' normaliser does not throw. Callers needing the\n * authoritative shape import the native `BlockHeader` from the SDK.\n */\nexport interface EthersBlockShape {\n number: string;\n hash: string;\n parentHash: string;\n timestamp: string;\n gasUsed: string;\n gasLimit: string;\n stateRoot: string;\n miner: string;\n difficulty: string;\n nonce: string;\n baseFeePerGas: string | null;\n extraData: string;\n mixHash: string;\n transactions: string[];\n transactionsRoot: string;\n receiptsRoot: string;\n logsBloom: string;\n sha3Uncles: string;\n uncles: string[];\n size: string;\n}\n\n/**\n * Translate `mono-core`'s `BlockHeader` to the ethers wire shape.\n * `transactions` defaults to an empty list — the SDK's\n * `eth_getBlockByNumber` does not yet return tx hashes; once Stage 1+\n * surfaces them, callers update this translator.\n */\nexport function translateBlockOut(header: {\n number: bigint;\n hash: string;\n parent_hash: string;\n state_root: string;\n timestamp: bigint;\n executionUnitsUsed: bigint;\n executionUnitLimit: bigint;\n}): EthersBlockShape {\n return {\n number: `0x${header.number.toString(16)}`,\n hash: header.hash,\n parentHash: header.parent_hash,\n timestamp: `0x${header.timestamp.toString(16)}`,\n gasUsed: `0x${header.executionUnitsUsed.toString(16)}`,\n gasLimit: `0x${header.executionUnitLimit.toString(16)}`,\n stateRoot: header.state_root,\n miner: \"0x0000000000000000000000000000000000000000\",\n difficulty: \"0x0\",\n nonce: \"0x0000000000000000\",\n baseFeePerGas: null,\n extraData: \"0x\",\n mixHash: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n transactions: [],\n transactionsRoot: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n receiptsRoot: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n logsBloom: `0x${\"0\".repeat(512)}`,\n sha3Uncles: \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n uncles: [],\n size: \"0x0\",\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/address.ts","../../src/error.ts","../../src/native-events.ts","../../src/node-registry.ts","../../src/crypto/ml-dsa.ts","../../src/crypto/envelope.ts","../../src/mrv.ts","../../src/registry.ts","../../src/types.ts","../../src/client.ts","../../src/ethers/network.ts","../../src/ethers/provider.ts","../../src/ethers/signer.ts","../../src/ethers/tx-translate.ts"],"names":["JsonRpcApiProvider","Network","AbstractSigner"],"mappings":";;;;;;;;;;;;;AAQO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,IAAA,EAAM,MAAA;AAAA,EACN,YAAA,EAAc,OAAA;AAAA,EACd,QAAA,EAAU,OAAA;AAAA,EACV,OAAA,EAAS,OAAA;AAAA,EACT,QAAA,EAAU,OAAA;AAAA,EACV,YAAA,EAAc;AAChB,CAAA;AACO,IAAM,qBAAA,GAAwB,CAAC,OAAA,EAAS,OAAA,EAAS,SAAS,OAAO,CAAA;AAWxE,IAAM,OAAA,GAAU,kCAAA;AAChB,IAAM,WAA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AAI,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA;AAAA,IAC/B,MAAM;AAAC,GACT;AACF;AAyCO,SAAS,kBAAkB,MAAA,EAQb;AACnB,EAAA,OAAO;AAAA,IACL,QAAQ,CAAA,EAAA,EAAK,MAAA,CAAO,MAAA,CAAO,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IACvC,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,YAAY,MAAA,CAAO,WAAA;AAAA,IACnB,WAAW,CAAA,EAAA,EAAK,MAAA,CAAO,SAAA,CAAU,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IAC7C,SAAS,CAAA,EAAA,EAAK,MAAA,CAAO,kBAAA,CAAmB,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IACpD,UAAU,CAAA,EAAA,EAAK,MAAA,CAAO,kBAAA,CAAmB,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAAA,IACrD,WAAW,MAAA,CAAO,UAAA;AAAA,IAClB,KAAA,EAAO,4CAAA;AAAA,IACP,UAAA,EAAY,KAAA;AAAA,IACZ,KAAA,EAAO,oBAAA;AAAA,IACP,aAAA,EAAe,IAAA;AAAA,IACf,SAAA,EAAW,IAAA;AAAA,IACX,OAAA,EAAS,oEAAA;AAAA,IACT,cAAc,EAAC;AAAA,IACf,gBAAA,EAAkB,oEAAA;AAAA,IAClB,YAAA,EAAc,oEAAA;AAAA,IACd,SAAA,EAAW,CAAA,EAAA,EAAK,GAAA,CAAI,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA;AAAA,IAC/B,UAAA,EAAY,oEAAA;AAAA,IACZ,QAAQ,EAAC;AAAA,IACT,IAAA,EAAM;AAAA,GACR;AACF","file":"index.cjs","sourcesContent":["/**\n * Address display helpers.\n *\n * Monolythium keeps 20-byte account identifiers on the wire, but\n * user-facing surfaces display them as `mono1...` bech32m strings.\n */\n\nexport const ADDRESS_HRP = \"mono\" as const;\nexport const ADDRESS_KIND_HRPS = {\n user: \"mono\",\n smartAccount: \"monos\",\n contract: \"monoc\",\n cluster: \"monok\",\n multisig: \"monom\",\n systemModule: \"monox\",\n} as const;\nexport const RESERVED_ADDRESS_HRPS = [\"monor\", \"monop\", \"monoi\", \"monoa\"] as const;\n\nexport type AddressKind = keyof typeof ADDRESS_KIND_HRPS;\n\nexport interface TypedAddress {\n kind: AddressKind;\n address: string;\n bytes: Uint8Array;\n hex: string;\n}\n\nconst CHARSET = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\nconst CHARSET_MAP = new Map([...CHARSET].map((c, i) => [c, i]));\nconst BECH32M_CONST = 0x2bc830a3;\nconst HEX_20_BYTE_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport class AddressError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AddressError\";\n }\n}\n\nexport function hexToAddressBytes(address: string): Uint8Array {\n if (!HEX_20_BYTE_RE.test(address)) {\n throw new AddressError(\"expected 0x-prefixed 20-byte hex address\");\n }\n const out = new Uint8Array(20);\n const body = address.slice(2);\n for (let i = 0; i < 20; i++) {\n out[i] = Number.parseInt(body.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nexport function addressBytesToHex(address: Uint8Array | readonly number[]): string {\n const bytes = expectLength(address, 20, \"address\");\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nexport function addressToBech32(address: string | Uint8Array | readonly number[]): string {\n return addressToTypedBech32(\"user\", address);\n}\n\nexport function addressToTypedBech32(\n kind: AddressKind,\n address: string | Uint8Array | readonly number[],\n): string {\n const bytes = typeof address === \"string\" ? hexToAddressBytes(address) : expectLength(address, 20, \"address\");\n return encodeBech32m(ADDRESS_KIND_HRPS[kind], bytes);\n}\n\nfunction encodeBech32m(hrp: string, bytes: Uint8Array): string {\n const words = convertBits([...bytes], 8, 5, true);\n const checksum = createChecksum(hrp, words);\n return `${hrp}1${[...words, ...checksum].map((v) => CHARSET[v]).join(\"\")}`;\n}\n\nexport function bech32ToAddressBytes(address: string): Uint8Array {\n return typedBech32ToAddress(address, \"user\").bytes;\n}\n\nexport function bech32ToAddress(address: string): string {\n return addressBytesToHex(bech32ToAddressBytes(address));\n}\n\nexport function typedBech32ToAddress(address: string, expectedKind?: AddressKind): TypedAddress {\n const parsed = decodeBech32m(address);\n if ((RESERVED_ADDRESS_HRPS as readonly string[]).includes(parsed.hrp)) {\n throw new AddressError(`reserved address hrp '${parsed.hrp}'`);\n }\n const kind = addressKindFromHrp(parsed.hrp);\n if (kind === undefined) {\n throw new AddressError(`unknown address hrp '${parsed.hrp}'`);\n }\n if (expectedKind !== undefined && kind !== expectedKind) {\n throw new AddressError(`unexpected hrp '${parsed.hrp}', expected '${ADDRESS_KIND_HRPS[expectedKind]}'`);\n }\n const bytes = convertBits(parsed.data, 5, 8, false);\n if (bytes.length !== 20) {\n throw new AddressError(`expected 20-byte payload, got ${bytes.length} bytes`);\n }\n const out = Uint8Array.from(bytes);\n return { kind, address: address.toLowerCase(), bytes: out, hex: addressBytesToHex(out) };\n}\n\nexport function requireTypedAddress(\n address: string,\n expectedKind: AddressKind,\n label = \"address\",\n): string {\n if (address.startsWith(\"0x\") || address.startsWith(\"0X\")) {\n throw new AddressError(\n `${label} raw 0x addresses are retired; use typed ${ADDRESS_KIND_HRPS[expectedKind]} bech32m addresses`,\n );\n }\n try {\n return typedBech32ToAddress(address, expectedKind).address;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new AddressError(\n `${label} must be typed ${ADDRESS_KIND_HRPS[expectedKind]} bech32m address: ${message}`,\n );\n }\n}\n\nexport function parseAddress(address: string): Uint8Array {\n if (address.startsWith(\"0x\") || address.startsWith(\"0X\")) {\n return hexToAddressBytes(address);\n }\n return bech32ToAddressBytes(address);\n}\n\n/** Address-validation result for non-throwing callers (UI forms, search). */\nexport type AddressValidation =\n | {\n valid: true;\n /** Lower-case bech32m representation; matches what the wire format expects. */\n normalized: string;\n /** Bech32m kind when the input is a typed bech32m address, otherwise null. */\n kind: AddressKind | null;\n /** Which surface the input came from. */\n format: \"hex\" | \"bech32m\";\n /** Raw 20-byte payload, useful for client-side bytes-derived lookups. */\n bytes: Uint8Array;\n }\n | { valid: false; reason: string };\n\n/**\n * Validate an address string without throwing. Accepts both raw hex and\n * typed bech32m. On success returns the canonical bech32m form along with\n * the kind/format/bytes; on failure returns a short reason string.\n */\nexport function validateAddress(address: string): AddressValidation {\n if (typeof address !== \"string\" || address.length === 0) {\n return { valid: false, reason: \"address cannot be empty\" };\n }\n const trimmed = address.trim();\n if (trimmed.length === 0) {\n return { valid: false, reason: \"address cannot be empty\" };\n }\n if (trimmed.startsWith(\"0x\") || trimmed.startsWith(\"0X\")) {\n try {\n const bytes = hexToAddressBytes(trimmed);\n return {\n valid: true,\n normalized: addressToBech32(bytes),\n kind: null,\n format: \"hex\",\n bytes,\n };\n } catch (err) {\n return { valid: false, reason: err instanceof Error ? err.message : String(err) };\n }\n }\n try {\n const typed = typedBech32ToAddress(trimmed);\n return {\n valid: true,\n normalized: typed.address,\n kind: typed.kind,\n format: \"bech32m\",\n bytes: typed.bytes,\n };\n } catch (err) {\n return { valid: false, reason: err instanceof Error ? err.message : String(err) };\n }\n}\n\nexport function normalizeAddressHex(address: string): string {\n return addressBytesToHex(parseAddress(address));\n}\n\nfunction decodeBech32m(input: string): { hrp: string; data: number[] } {\n if (input.length < 8) {\n throw new AddressError(\"bech32m address is too short\");\n }\n const hasLower = input !== input.toUpperCase();\n const hasUpper = input !== input.toLowerCase();\n if (hasLower && hasUpper) {\n throw new AddressError(\"bech32m address cannot mix upper and lower case\");\n }\n const s = input.toLowerCase();\n const sep = s.lastIndexOf(\"1\");\n if (sep <= 0 || sep + 7 > s.length) {\n throw new AddressError(\"bech32m separator/checksum shape is invalid\");\n }\n const hrp = s.slice(0, sep);\n const values: number[] = [];\n for (const c of s.slice(sep + 1)) {\n const v = CHARSET_MAP.get(c);\n if (v === undefined) {\n throw new AddressError(`invalid bech32m character '${c}'`);\n }\n values.push(v);\n }\n if (!verifyChecksum(hrp, values)) {\n throw new AddressError(\"bech32m checksum mismatch\");\n }\n return { hrp, data: values.slice(0, -6) };\n}\n\nfunction addressKindFromHrp(hrp: string): AddressKind | undefined {\n for (const [kind, kindHrp] of Object.entries(ADDRESS_KIND_HRPS) as Array<[AddressKind, string]>) {\n if (kindHrp === hrp) return kind;\n }\n return undefined;\n}\n\nfunction hrpExpand(hrp: string): number[] {\n const high = [...hrp].map((c) => c.charCodeAt(0) >> 5);\n const low = [...hrp].map((c) => c.charCodeAt(0) & 31);\n return [...high, 0, ...low];\n}\n\nfunction polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if (((top >> i) & 1) === 1) {\n chk ^= generators[i];\n }\n }\n }\n return chk >>> 0;\n}\n\nfunction createChecksum(hrp: string, data: number[]): number[] {\n const values = [...hrpExpand(hrp), ...data, 0, 0, 0, 0, 0, 0];\n const mod = polymod(values) ^ BECH32M_CONST;\n const out: number[] = [];\n for (let p = 0; p < 6; p++) {\n out.push((mod >> (5 * (5 - p))) & 31);\n }\n return out;\n}\n\nfunction verifyChecksum(hrp: string, values: number[]): boolean {\n return polymod([...hrpExpand(hrp), ...values]) === BECH32M_CONST;\n}\n\nfunction convertBits(data: readonly number[], fromBits: number, toBits: number, pad: boolean): number[] {\n let acc = 0;\n let bits = 0;\n const ret: number[] = [];\n const maxv = (1 << toBits) - 1;\n const maxAcc = (1 << (fromBits + toBits - 1)) - 1;\n for (const value of data) {\n if (value < 0 || value >> fromBits !== 0) {\n throw new AddressError(\"invalid address payload value\");\n }\n acc = ((acc << fromBits) | value) & maxAcc;\n bits += fromBits;\n while (bits >= toBits) {\n bits -= toBits;\n ret.push((acc >> bits) & maxv);\n }\n }\n if (pad) {\n if (bits > 0) {\n ret.push((acc << (toBits - bits)) & maxv);\n }\n } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) !== 0) {\n throw new AddressError(\"invalid bech32m padding\");\n }\n return ret;\n}\n\nfunction expectLength(value: Uint8Array | readonly number[], len: number, name: string): Uint8Array {\n if (value.length !== len) {\n throw new AddressError(`${name} must be ${len} bytes`);\n }\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n","/**\n * Error surfaced by `RpcClient`. Distinguishes transport failures\n * (HTTP errors, network), protocol errors (JSON-RPC `error` envelopes),\n * and shape mismatches.\n */\nexport class SdkError extends Error {\n public readonly kind: \"transport\" | \"rpc\" | \"malformed\" | \"endpoint\";\n public readonly code?: number;\n public readonly data?: unknown;\n\n constructor(\n kind: \"transport\" | \"rpc\" | \"malformed\" | \"endpoint\",\n message: string,\n opts?: { code?: number; data?: unknown; cause?: unknown },\n ) {\n super(message, opts?.cause ? { cause: opts.cause } : undefined);\n this.name = \"SdkError\";\n this.kind = kind;\n this.code = opts?.code;\n this.data = opts?.data;\n }\n\n static transport(message: string, cause?: unknown): SdkError {\n return new SdkError(\"transport\", message, { cause });\n }\n static rpc(code: number, message: string, data?: unknown): SdkError {\n return new SdkError(\"rpc\", `rpc error ${code}: ${message}`, { code, data });\n }\n static malformed(message: string): SdkError {\n return new SdkError(\"malformed\", message);\n }\n static endpoint(message: string): SdkError {\n return new SdkError(\"endpoint\", message);\n }\n}\n","import { SdkError } from \"./error.js\";\nimport type {\n NativeEventsResponse,\n NativeReceiptEvent,\n NativeReceiptResponse,\n} from \"./client.js\";\n\n/** Common typed payload envelope emitted by the native event projector. */\nexport interface NativeDecodedEvent {\n block_height: number;\n tx_index: number;\n sequence: number;\n family: string;\n event_name: string;\n nonce?: number | null;\n market_surface?: string | null;\n marketSurface?: string | null;\n market_asset_id?: string | null;\n marketAssetId?: string | null;\n market_related_asset_id?: string | null;\n marketRelatedAssetId?: string | null;\n market_order_id?: string | null;\n marketOrderId?: string | null;\n market_related_order_id?: string | null;\n marketRelatedOrderId?: string | null;\n price?: string | null;\n quantity?: string | null;\n remaining?: string | null;\n side?: string | null;\n status?: string | null;\n nft_standard?: string | null;\n nftStandard?: string | null;\n policy?: NativeMrcPolicyProjection | null;\n royalty_bps?: number | null;\n royaltyBps?: number | null;\n listing_kind?: unknown;\n listingKind?: unknown;\n expires_at_block?: number | null;\n expiresAtBlock?: number | null;\n tick_size?: string | null;\n tickSize?: string | null;\n lot_size?: string | null;\n lotSize?: string | null;\n min_quantity?: string | null;\n minQuantity?: string | null;\n min_notional?: string | null;\n minNotional?: string | null;\n payload_hash: string;\n [field: string]: unknown;\n}\n\n/** Canonical policy body projected from native MRC policy-account events. */\nexport interface NativeMrcPolicyProjection {\n enabled: boolean;\n per_action_limit: string | number;\n window_limit: string | number;\n allowed_assets: Array<string | Array<number>>;\n}\n\nexport type NativeEventProjection = NativeDecodedEvent;\n\nexport const NATIVE_MARKET_EVENT_FAMILY = \"market\" as const;\n\n/** Optional filters applied to native receipt event rows. */\nexport interface NativeEventFilter {\n address?: string;\n eventTopic?: string;\n family?: string;\n eventName?: string;\n}\n\nexport function nativeMarketEventFilter(filter: NativeEventFilter = {}): NativeEventFilter {\n return { ...filter, family: NATIVE_MARKET_EVENT_FAMILY };\n}\n\nexport type TypedNativeReceiptEvent<TDecoded extends NativeDecodedEvent = NativeDecodedEvent> =\n NativeReceiptEvent<TDecoded>;\n\nexport type NativeEventConsumer<TDecoded extends NativeDecodedEvent = NativeDecodedEvent> = (\n event: TypedNativeReceiptEvent<TDecoded>,\n) => void | Promise<void>;\n\nexport function isNativeDecodedEvent(value: unknown): value is NativeDecodedEvent {\n const row = asRecord(value);\n return (\n row !== null &&\n typeof row[\"block_height\"] === \"number\" &&\n typeof row[\"tx_index\"] === \"number\" &&\n typeof row[\"sequence\"] === \"number\" &&\n typeof row[\"family\"] === \"string\" &&\n typeof row[\"event_name\"] === \"string\" &&\n typeof row[\"payload_hash\"] === \"string\"\n );\n}\n\nexport function parseNativeDecodedEvent<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n event: Pick<NativeReceiptEvent<unknown>, \"decoded\" | \"decodedJson\" | \"eventTopic\" | \"logIndex\">,\n): TDecoded {\n if (isNativeDecodedEvent(event.decoded)) {\n return event.decoded as TDecoded;\n }\n\n try {\n const parsed = JSON.parse(event.decodedJson) as unknown;\n if (isNativeDecodedEvent(parsed)) {\n return parsed as TDecoded;\n }\n } catch {\n // Fall through to the shape error below.\n }\n\n throw SdkError.malformed(\n `native event ${event.eventTopic} at logIndex ${event.logIndex} is missing a typed decoded payload`,\n );\n}\n\nexport function nativeEventMatches(\n event: NativeReceiptEvent<unknown>,\n filter: NativeEventFilter = {},\n): boolean {\n if (filter.address !== undefined && event.address !== filter.address) return false;\n if (filter.eventTopic !== undefined && event.eventTopic !== filter.eventTopic) return false;\n\n if (filter.family === undefined && filter.eventName === undefined) return true;\n\n let decoded: NativeDecodedEvent;\n try {\n decoded = parseNativeDecodedEvent(event);\n } catch {\n return false;\n }\n if (filter.family !== undefined && decoded.family !== filter.family) return false;\n if (filter.eventName !== undefined && decoded.event_name !== filter.eventName) return false;\n return true;\n}\n\nexport function nativeEventsFromReceipt<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n filter: NativeEventFilter = {},\n): Array<TypedNativeReceiptEvent<TDecoded>> {\n return receipt.events\n .filter((event) => nativeEventMatches(event, filter))\n .map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n }));\n}\n\nexport function nativeMarketEventsFromReceipt<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n filter: NativeEventFilter = {},\n): Array<TypedNativeReceiptEvent<TDecoded>> {\n return nativeEventsFromReceipt<TDecoded>(receipt, nativeMarketEventFilter(filter));\n}\n\nexport function nativeEventsFromHistory<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(response: NativeEventsResponse<unknown>): NativeEventsResponse<TDecoded> {\n return {\n ...response,\n events: response.events.map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n })),\n };\n}\n\nexport function nativeMarketEventsFromHistory<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(response: NativeEventsResponse<unknown>): NativeEventsResponse<TDecoded> {\n return {\n ...response,\n filters: { ...response.filters, family: NATIVE_MARKET_EVENT_FAMILY },\n events: response.events\n .filter((event) => nativeEventMatches(event, { family: NATIVE_MARKET_EVENT_FAMILY }))\n .map((event) => ({\n ...event,\n decoded: parseNativeDecodedEvent<TDecoded>(event),\n })),\n };\n}\n\nexport async function consumeNativeEvents<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n>(\n receipt: NativeReceiptResponse<unknown>,\n consumer: NativeEventConsumer<TDecoded>,\n filter: NativeEventFilter = {},\n): Promise<number> {\n const events = nativeEventsFromReceipt<TDecoded>(receipt, filter);\n for (const event of events) {\n await consumer(event);\n }\n return events.length;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n}\n","/**\n * Node-registry precompile ABI helpers and service capability constants.\n *\n * These constants mirror `protocore-node-registry::capabilities` and\n * `protocore-node-registry::abi`. They are exported for wallets,\n * service probers, faucets, and operator dashboards that need to build\n * canonical registry transactions without retyping low-level values.\n */\n\nimport { PRECOMPILE_ADDRESSES } from \"./consts.js\";\n\nexport const NODE_REGISTRY_CAPABILITIES = {\n SERVES_RPC: 0x0000_0001,\n SERVES_INDEXER: 0x0000_0002,\n SERVES_BROADCASTER: 0x0000_0004,\n SERVES_ARCHIVE: 0x0000_0008,\n SERVES_WEBSOCKET: 0x0000_0010,\n SERVES_LIGHT_CLIENT: 0x0000_0020,\n SERVES_ORACLE_WRITER: 0x0000_0040,\n SERVES_BRIDGE_RELAY: 0x0000_0080,\n SERVES_PUBLIC_API: 0x0000_0100,\n} as const;\n\nexport const NODE_REGISTRY_CAPABILITY_MASK = 0x0000_ffff;\n\nexport const NODE_REGISTRY_PUBLIC_SERVICE_MASK =\n NODE_REGISTRY_CAPABILITIES.SERVES_RPC |\n NODE_REGISTRY_CAPABILITIES.SERVES_INDEXER |\n NODE_REGISTRY_CAPABILITIES.SERVES_ARCHIVE |\n NODE_REGISTRY_CAPABILITIES.SERVES_WEBSOCKET |\n NODE_REGISTRY_CAPABILITIES.SERVES_PUBLIC_API;\n\nexport const SERVICE_PROBE_STATUS = {\n UNKNOWN: 0,\n REACHABLE: 1,\n DEGRADED: 2,\n UNREACHABLE: 3,\n} as const;\n\nexport const NODE_REGISTRY_SELECTORS = {\n reportServiceProbe: \"0xeee31bba\",\n getServiceProbe: \"0x1fcbfbce\",\n} as const;\n\nexport interface ReportServiceProbeCalldataArgs {\n peerId: string | Uint8Array | readonly number[];\n serviceMask: number;\n status: number;\n latencyMs: number;\n probeDigest: string | Uint8Array | readonly number[];\n}\n\nexport class NodeRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NodeRegistryError\";\n }\n}\n\nexport function nodeRegistryAddressHex(): string {\n return PRECOMPILE_ADDRESSES.NODE_REGISTRY.toLowerCase();\n}\n\nexport function isValidNodeRegistryCapabilities(flags: number): boolean {\n return Number.isInteger(flags) && flags >= 0 && (flags & ~NODE_REGISTRY_CAPABILITY_MASK) === 0;\n}\n\nexport function isValidPublicServiceProbeMask(mask: number): boolean {\n return (\n Number.isInteger(mask) &&\n mask > 0 &&\n (mask & ~NODE_REGISTRY_PUBLIC_SERVICE_MASK) === 0\n );\n}\n\nexport function isSinglePublicServiceProbeMask(mask: number): boolean {\n return isValidPublicServiceProbeMask(mask) && bitCount(mask) === 1;\n}\n\nexport function isConcreteServiceProbeStatus(status: number): boolean {\n return (\n status === SERVICE_PROBE_STATUS.REACHABLE ||\n status === SERVICE_PROBE_STATUS.DEGRADED ||\n status === SERVICE_PROBE_STATUS.UNREACHABLE\n );\n}\n\nexport function serviceProbeStatusLabel(status: number): string {\n switch (status) {\n case SERVICE_PROBE_STATUS.REACHABLE:\n return \"reachable\";\n case SERVICE_PROBE_STATUS.DEGRADED:\n return \"degraded\";\n case SERVICE_PROBE_STATUS.UNREACHABLE:\n return \"unreachable\";\n default:\n return \"unknown\";\n }\n}\n\nexport function encodeReportServiceProbeCalldata(args: ReportServiceProbeCalldataArgs): string {\n if (!isValidPublicServiceProbeMask(args.serviceMask)) {\n throw new NodeRegistryError(\n `serviceMask 0x${args.serviceMask.toString(16).padStart(8, \"0\")} is not a valid public-service mask`,\n );\n }\n if (!isConcreteServiceProbeStatus(args.status)) {\n throw new NodeRegistryError(`status ${args.status} is not a concrete service-probe outcome`);\n }\n const latencyMs = expectUint32(args.latencyMs, \"latencyMs\");\n return bytesToHex(\n concatBytes(\n hexToBytes(NODE_REGISTRY_SELECTORS.reportServiceProbe),\n expectLength(toBytes(args.peerId), 32, \"peerId\"),\n uint32Word(args.serviceMask),\n uint8Word(args.status),\n uint32Word(latencyMs),\n expectLength(toBytes(args.probeDigest), 32, \"probeDigest\"),\n ),\n );\n}\n\nfunction bitCount(value: number): number {\n let n = value >>> 0;\n let count = 0;\n while (n !== 0) {\n count += n & 1;\n n >>>= 1;\n }\n return count;\n}\n\nfunction expectUint32(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw new NodeRegistryError(`${name} must be a uint32`);\n }\n return value;\n}\n\nfunction uint32Word(value: number): Uint8Array {\n const out = new Uint8Array(32);\n const n = expectUint32(value, \"uint32\");\n out[28] = (n >>> 24) & 0xff;\n out[29] = (n >>> 16) & 0xff;\n out[30] = (n >>> 8) & 0xff;\n out[31] = n & 0xff;\n return out;\n}\n\nfunction uint8Word(value: number): Uint8Array {\n if (!Number.isInteger(value) || value < 0 || value > 0xff) {\n throw new NodeRegistryError(\"uint8 value out of range\");\n }\n const out = new Uint8Array(32);\n out[31] = value;\n return out;\n}\n\nfunction toBytes(value: string | Uint8Array | readonly number[]): Uint8Array {\n if (typeof value === \"string\") {\n return hexToBytes(value);\n }\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {\n throw new NodeRegistryError(\"invalid hex bytes\");\n }\n const out = new Uint8Array(body.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = Number.parseInt(body.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction expectLength(value: Uint8Array, len: number, name: string): Uint8Array {\n if (value.length !== len) {\n throw new NodeRegistryError(`${name} must be ${len} bytes, got ${value.length}`);\n }\n return value;\n}\n","import { ml_dsa65 } from \"@noble/post-quantum/ml-dsa.js\";\nimport { blake3 } from \"@noble/hashes/blake3.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { bigintToBeBytes, bytesToHex, concatBytes, expectBytes } from \"./bytes.js\";\nimport { bincodeSignedTransaction, encodeTransactionForHash, type NativeEvmTxFields } from \"./tx.js\";\n\nexport const ML_DSA_65_SEED_LEN = 32;\nexport const ML_DSA_65_SIGNING_KEY_LEN = 4032;\nexport const ML_DSA_65_PUBLIC_KEY_LEN = 1952;\nexport const ML_DSA_65_SIGNATURE_LEN = 3309;\nexport const STANDARD_ALGO_NUMBER_ML_DSA_65 = 1001;\nexport const ENUM_VARIANT_INDEX_ML_DSA_65 = 5;\nexport const ADDRESS_DERIVATION_DOMAIN = \"MONO_ADDRESS_BLAKE3_20_V1\";\n\nconst ADDRESS_DERIVATION_DOMAIN_BYTES = new TextEncoder().encode(ADDRESS_DERIVATION_DOMAIN);\n\nexport class MlDsa65Backend {\n readonly #secretKey: Uint8Array;\n readonly #publicKey: Uint8Array;\n readonly #addressBytes: Uint8Array;\n\n private constructor(secretKey: Uint8Array, publicKey: Uint8Array) {\n this.#secretKey = expectBytes(secretKey, ML_DSA_65_SIGNING_KEY_LEN, \"ML-DSA-65 secret key\").slice();\n this.#publicKey = expectBytes(publicKey, ML_DSA_65_PUBLIC_KEY_LEN, \"ML-DSA-65 public key\").slice();\n this.#addressBytes = mlDsa65AddressBytes(this.#publicKey);\n }\n\n static fromSeed(seed: Uint8Array | readonly number[]): MlDsa65Backend {\n const kp = ml_dsa65.keygen(expectBytes(seed, ML_DSA_65_SEED_LEN, \"ML-DSA-65 seed\"));\n return new MlDsa65Backend(kp.secretKey, kp.publicKey);\n }\n\n publicKey(): Uint8Array {\n return this.#publicKey.slice();\n }\n\n addressBytes(): Uint8Array {\n return this.#addressBytes.slice();\n }\n\n getAddress(): string {\n return bytesToHex(this.#addressBytes);\n }\n\n sign(message: Uint8Array): Uint8Array {\n return ml_dsa65.sign(message, this.#secretKey, { extraEntropy: false });\n }\n\n signPrehash(digest: Uint8Array): Uint8Array {\n return this.sign(expectBytes(digest, 32, \"prehash\"));\n }\n\n verify(message: Uint8Array, signature: Uint8Array): boolean {\n return ml_dsa65.verify(\n expectBytes(signature, ML_DSA_65_SIGNATURE_LEN, \"ML-DSA-65 signature\"),\n message,\n this.#publicKey,\n );\n }\n\n signEvmTx(fields: NativeEvmTxFields): {\n wireHex: string;\n wireBytes: Uint8Array;\n sighash: Uint8Array;\n txHash: Uint8Array;\n } {\n const txHashPreimage = encodeTransactionForHash(fields, 0x01);\n const sighash = keccak_256(txHashPreimage);\n const signature = this.sign(sighash);\n const wireBytes = bincodeSignedTransaction(fields, signature, this.#publicKey);\n const txHash = keccak_256(\n concatBytes(\n encodeTransactionForHash(fields, 0x02),\n signature,\n this.#publicKey,\n ),\n );\n return {\n wireHex: bytesToHex(wireBytes).slice(2),\n wireBytes,\n sighash,\n txHash,\n };\n }\n}\n\nexport function mlDsa65AddressFromPublicKey(publicKey: Uint8Array | readonly number[]): string {\n return bytesToHex(mlDsa65AddressBytes(publicKey));\n}\n\nexport function mlDsa65AddressBytes(publicKey: Uint8Array | readonly number[]): Uint8Array {\n const bytes = expectBytes(publicKey, ML_DSA_65_PUBLIC_KEY_LEN, \"ML-DSA-65 public key\");\n return blake3(concatBytes(\n ADDRESS_DERIVATION_DOMAIN_BYTES,\n bigintToBeBytes(BigInt(STANDARD_ALGO_NUMBER_ML_DSA_65), 2, \"ML-DSA-65 algo id\"),\n bytes,\n )).slice(0, 20);\n}\n\nexport function encodeMlDsa65Opaque(raw: Uint8Array | readonly number[]): Uint8Array {\n const bytes = raw instanceof Uint8Array ? raw : Uint8Array.from(raw);\n const len = bytes.length === ML_DSA_65_PUBLIC_KEY_LEN ? ML_DSA_65_PUBLIC_KEY_LEN : ML_DSA_65_SIGNATURE_LEN;\n expectBytes(bytes, len, \"ML-DSA-65 opaque bytes\");\n const out = new Uint8Array(4 + 2 + 8 + bytes.length);\n const dv = new DataView(out.buffer);\n dv.setUint32(0, ENUM_VARIANT_INDEX_ML_DSA_65, true);\n dv.setUint16(4, STANDARD_ALGO_NUMBER_ML_DSA_65, true);\n dv.setBigUint64(6, BigInt(bytes.length), true);\n out.set(bytes, 14);\n return out;\n}\n\nexport function uint256Bytes(value: bigint | number | string, label: string): Uint8Array {\n const v = typeof value === \"bigint\" ? value : typeof value === \"number\" ? BigInt(value) : BigInt(value);\n return bigintToBeBytes(v, 32, label);\n}\n","import { ml_kem768 } from \"@noble/post-quantum/ml-kem.js\";\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { BincodeWriter } from \"./bincode.js\";\nimport { bytesToHex, concatBytes, expectBytes } from \"./bytes.js\";\nimport {\n ENUM_VARIANT_INDEX_ML_DSA_65,\n ML_DSA_65_PUBLIC_KEY_LEN,\n ML_DSA_65_SIGNATURE_LEN,\n STANDARD_ALGO_NUMBER_ML_DSA_65,\n} from \"./ml-dsa.js\";\n\nconst DKG_AEAD_DOMAIN_TAG = new TextEncoder().encode(\"protocore/v2/mempool/dkg-mlkem768/1\");\n\nexport const ML_KEM_768_CIPHERTEXT_LEN = 1088;\nexport const ML_KEM_768_ENCAPSULATION_KEY_LEN = 1184;\nexport const ML_KEM_768_SHARED_SECRET_LEN = 32;\nexport const DKG_NONCE_LEN = 12;\nexport const DKG_AEAD_TAG_LEN = 16;\n\nexport const MempoolClass = {\n Transfer: 0,\n ContractCall: 1,\n PrivacyOp: 2,\n CLOBOp: 3,\n AgentOp: 4,\n FoundationOp: 5,\n /** @deprecated Use FoundationOp. */\n GovernanceOp: 5,\n RWAOp: 6,\n} as const;\nexport type MempoolClass = (typeof MempoolClass)[keyof typeof MempoolClass];\n\nexport interface NonceAad {\n sender: Uint8Array;\n nonce: bigint;\n chainId: bigint;\n class: MempoolClass;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n gasLimit: bigint;\n}\n\nexport interface DecryptHint {\n epoch: bigint;\n scheme: number;\n}\n\nexport interface EncryptedEnvelope {\n nonceAad: NonceAad;\n ciphertext: Uint8Array;\n decryptionHint: DecryptHint;\n senderPubkey: Uint8Array;\n outerSignature: Uint8Array;\n sender: Uint8Array;\n}\n\nexport function bincodeNonceAad(aad: NonceAad): Uint8Array {\n const w = new BincodeWriter();\n w.bytes(expectBytes(aad.sender, 20, \"NonceAad.sender\"));\n w.u64(aad.nonce);\n w.u64(aad.chainId);\n w.enumVariant(aad.class);\n w.u128(aad.maxFeePerGas);\n w.u128(aad.maxPriorityFeePerGas);\n w.u64(aad.gasLimit);\n return w.toBytes();\n}\n\nexport function bincodeDecryptHint(hint: DecryptHint): Uint8Array {\n const w = new BincodeWriter();\n w.u64(hint.epoch);\n w.u16(hint.scheme);\n return w.toBytes();\n}\n\nexport function bincodeEncryptedEnvelope(env: EncryptedEnvelope): Uint8Array {\n const w = new BincodeWriter();\n w.rawBytes(bincodeNonceAad(env.nonceAad));\n w.bytes(env.ciphertext);\n w.rawBytes(bincodeDecryptHint(env.decryptionHint));\n bincodeMlDsa65OpaqueInto(w, expectBytes(env.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\"));\n bincodeMlDsa65OpaqueInto(w, expectBytes(env.outerSignature, ML_DSA_65_SIGNATURE_LEN, \"outerSignature\"));\n w.bytes(expectBytes(env.sender, 20, \"sender\"));\n return w.toBytes();\n}\n\nexport function encryptInnerTx(\n signedInnerTxBincode: Uint8Array,\n nonceAad: NonceAad,\n kemEncapsulationKey: Uint8Array,\n): Uint8Array {\n expectBytes(kemEncapsulationKey, ML_KEM_768_ENCAPSULATION_KEY_LEN, \"kemEncapsulationKey\");\n const { cipherText: kemCt, sharedSecret } = ml_kem768.encapsulate(kemEncapsulationKey);\n const nonce = randomBytes(DKG_NONCE_LEN);\n const cipher = chacha20poly1305(sharedSecret, nonce, aadFor(nonceAad));\n const aeadCt = cipher.encrypt(signedInnerTxBincode);\n sharedSecret.fill(0);\n return concatBytes(kemCt, nonce, aeadCt);\n}\n\nexport function outerSigDigest(\n nonceAad: NonceAad,\n ciphertext: Uint8Array,\n decryptionHint: DecryptHint,\n senderPubkey: Uint8Array,\n): Uint8Array {\n const aad = bincodeNonceAad(nonceAad);\n const hint = bincodeDecryptHint(decryptionHint);\n return keccak_256(concatBytes(aad, ciphertext, hint, expectBytes(senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\")));\n}\n\nexport async function buildEncryptedEnvelope(args: {\n signedInnerTxBincode: Uint8Array;\n nonceAad: NonceAad;\n decryptionHint: DecryptHint;\n kemEncapsulationKey: Uint8Array;\n senderAddress: Uint8Array;\n senderPubkey: Uint8Array;\n signOuterDigest: (digest: Uint8Array) => Promise<Uint8Array> | Uint8Array;\n}): Promise<{ envelope: EncryptedEnvelope; wireBytes: Uint8Array; wireHex: string }> {\n const ciphertext = encryptInnerTx(args.signedInnerTxBincode, args.nonceAad, args.kemEncapsulationKey);\n const digest = outerSigDigest(args.nonceAad, ciphertext, args.decryptionHint, args.senderPubkey);\n const outerSignature = await args.signOuterDigest(digest);\n const envelope: EncryptedEnvelope = {\n nonceAad: args.nonceAad,\n ciphertext,\n decryptionHint: args.decryptionHint,\n senderPubkey: expectBytes(args.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, \"senderPubkey\"),\n outerSignature: expectBytes(outerSignature, ML_DSA_65_SIGNATURE_LEN, \"outerSignature\"),\n sender: expectBytes(args.senderAddress, 20, \"senderAddress\"),\n };\n const wireBytes = bincodeEncryptedEnvelope(envelope);\n return { envelope, wireBytes, wireHex: bytesToHex(wireBytes) };\n}\n\nfunction aadFor(aad: NonceAad): Uint8Array {\n return concatBytes(DKG_AEAD_DOMAIN_TAG, bincodeNonceAad(aad));\n}\n\nfunction bincodeMlDsa65OpaqueInto(w: BincodeWriter, raw: Uint8Array): void {\n w.enumVariant(ENUM_VARIANT_INDEX_ML_DSA_65);\n w.u16(STANDARD_ALGO_NUMBER_ML_DSA_65);\n w.bytes(raw);\n}\n","import { blake3 } from \"@noble/hashes/blake3.js\";\nimport { ADDRESS_KIND_HRPS, addressToTypedBech32, typedBech32ToAddress } from \"./address.js\";\nimport {\n buildEncryptedSubmission,\n fetchEncryptionKey,\n submitEncryptedEnvelope,\n type EncryptionKey,\n} from \"./crypto/submission.js\";\nimport { BincodeWriter } from \"./crypto/bincode.js\";\n\nexport type { MrvAbiManifest } from \"./bindings/MrvAbiManifest.js\";\nexport type { MrvAbiParam } from \"./bindings/MrvAbiParam.js\";\nexport type { MrvAbiSymbol } from \"./bindings/MrvAbiSymbol.js\";\nexport type { MrvAbiSymbolKind } from \"./bindings/MrvAbiSymbolKind.js\";\nexport type { MrvAbiType } from \"./bindings/MrvAbiType.js\";\nexport type { MrvAddressKind } from \"./bindings/MrvAddressKind.js\";\nexport type { MrvArtifactMetadata } from \"./bindings/MrvArtifactMetadata.js\";\nexport type { MrvBuildMetadata } from \"./bindings/MrvBuildMetadata.js\";\nexport type { MrvCallRequest } from \"./bindings/MrvCallRequest.js\";\nexport type { MrvCallResponse } from \"./bindings/MrvCallResponse.js\";\nexport type { MrvCallStatus } from \"./bindings/MrvCallStatus.js\";\nexport type { MrvDeployPayload } from \"./bindings/MrvDeployPayload.js\";\nexport type { MrvDeployRequest } from \"./bindings/MrvDeployRequest.js\";\nexport type { MrvDeployResponse } from \"./bindings/MrvDeployResponse.js\";\nexport type { MrvEventRecord } from \"./bindings/MrvEventRecord.js\";\nexport type { MrvExecutionReceipt } from \"./bindings/MrvExecutionReceipt.js\";\nexport type { MrvMemoryLimits } from \"./bindings/MrvMemoryLimits.js\";\nexport type { MrvMeterCounters } from \"./bindings/MrvMeterCounters.js\";\nexport type { MrvNativeStateDelta } from \"./bindings/MrvNativeStateDelta.js\";\nexport type { MrvResolvedSyscall } from \"./bindings/MrvResolvedSyscall.js\";\nexport type { MrvRevertPayload } from \"./bindings/MrvRevertPayload.js\";\nexport type { MrvRiscvProfile } from \"./bindings/MrvRiscvProfile.js\";\nexport type { MrvStorageNamespace } from \"./bindings/MrvStorageNamespace.js\";\nexport type { MrvSyscallImport } from \"./bindings/MrvSyscallImport.js\";\nexport type { MrvTransactionExtension } from \"./bindings/MrvTransactionExtension.js\";\nexport type { MrvTypedAddress } from \"./bindings/MrvTypedAddress.js\";\nexport type { MrvValidatedArtifactMetadata } from \"./bindings/MrvValidatedArtifactMetadata.js\";\n\nimport type { AddressKind } from \"./address.js\";\nimport type { MrvAbiManifest } from \"./bindings/MrvAbiManifest.js\";\nimport type { MrvAbiType } from \"./bindings/MrvAbiType.js\";\nimport type { MrvAddressKind } from \"./bindings/MrvAddressKind.js\";\nimport type { MrvArtifactMetadata } from \"./bindings/MrvArtifactMetadata.js\";\nimport type { MrvCallRequest } from \"./bindings/MrvCallRequest.js\";\nimport type { MrvDeployRequest } from \"./bindings/MrvDeployRequest.js\";\nimport type { MrvResolvedSyscall } from \"./bindings/MrvResolvedSyscall.js\";\nimport type { MrvTransactionExtension } from \"./bindings/MrvTransactionExtension.js\";\nimport type { MrvValidatedArtifactMetadata } from \"./bindings/MrvValidatedArtifactMetadata.js\";\nimport type { RpcClient } from \"./client.js\";\nimport type { MempoolClass } from \"./crypto/envelope.js\";\nimport type { MlDsa65Backend } from \"./crypto/ml-dsa.js\";\nimport type { NativeEvmTxFields, NativeTxExtensionLike } from \"./crypto/tx.js\";\nimport type { NativeReceiptFee } from \"./client.js\";\n\nexport type MrvBytesLike = string | Uint8Array | readonly number[];\nexport type MrvDecimalLike = string | number | bigint;\n\nexport interface MrvRequestBuildOptions {\n from?: string;\n valueLythoshi?: MrvDecimalLike;\n executionUnitLimit?: number | bigint;\n maxExecutionFeeLythoshi?: MrvDecimalLike;\n priorityTipLythoshi?: MrvDecimalLike;\n nonce?: number | bigint;\n}\n\nexport interface MrvDeployPlanOptions extends MrvRequestBuildOptions {\n artifactHash?: string;\n}\n\nexport interface MrvDeployPayloadRequestOptions extends MrvRequestBuildOptions {\n constructorInput?: MrvBytesLike | null;\n}\n\nexport interface MrvDeployPayloadPlanOptions extends MrvDeployPayloadRequestOptions {\n artifactHash?: string;\n}\n\nexport interface MrvDeployPlan {\n request: MrvDeployRequest;\n extension: MrvTransactionExtension;\n expectedContractAddress?: string;\n}\n\nexport interface MrvCallPlan {\n request: MrvCallRequest;\n extension: MrvTransactionExtension;\n}\n\nexport type MrvDeployNativeTxOptions = Omit<\n MrvDeployPlanOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport type MrvDeployPayloadNativeTxOptions = Omit<\n MrvDeployPayloadPlanOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport type MrvCallNativeTxOptions = Omit<\n MrvRequestBuildOptions,\n \"executionUnitLimit\" | \"maxExecutionFeeLythoshi\" | \"nonce\"\n> & {\n chainId: number | bigint;\n nonce: number | bigint;\n executionUnitLimit: number | bigint;\n maxExecutionFeeLythoshi: MrvDecimalLike;\n};\n\nexport interface MrvNativeTxFacade {\n chainId: bigint;\n nonce: bigint;\n valueLythoshi: string;\n executionUnitLimit: bigint;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n}\n\nexport interface MrvNativeFeePreview {\n totalLythoshi: string;\n totalLyth: string;\n cyclesUsed: bigint;\n executionUnitLimit: bigint;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n}\n\nexport interface MrvDeployNativeTxPlan extends MrvDeployPlan {\n nativeTx: MrvNativeTxFacade;\n feePreview: MrvNativeFeePreview;\n tx: NativeEvmTxFields;\n}\n\nexport interface MrvCallNativeTxPlan extends MrvCallPlan {\n nativeTx: MrvNativeTxFacade;\n feePreview: MrvNativeFeePreview;\n tx: NativeEvmTxFields;\n}\n\nexport interface MrvEncryptedSubmissionResult {\n envelopeWireHex: string;\n innerSighashHex: string;\n innerTxHashHex: string;\n innerWireBytes: number;\n txHash: string;\n}\n\nexport type MrvDeploySubmitOptions = MrvDeployNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvDeployPayloadSubmitOptions = MrvDeployPayloadNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvCallSubmitOptions = MrvCallNativeTxOptions & {\n encryptionKey?: EncryptionKey;\n class?: MempoolClass;\n};\n\nexport type MrvDeploySubmission = MrvDeployNativeTxPlan & MrvEncryptedSubmissionResult;\nexport type MrvDeployPayloadSubmission = MrvDeployNativeTxPlan & MrvEncryptedSubmissionResult;\nexport type MrvCallSubmission = MrvCallNativeTxPlan & MrvEncryptedSubmissionResult;\n\nexport const MRV_FORMAT_VERSION = 1 as const;\nexport const MRV_DEPLOY_PAYLOAD_VERSION = 1 as const;\nexport const MRV_PROFILE_MONO_RV32IM_V1 = \"mono_rv32im_v1\" as const;\nexport const MRV_MEMORY_PAGE_BYTES = 65_536 as const;\nexport const MRV_MAX_CODE_BYTES = 16 * 1024 * 1024;\nexport const MRV_MAX_DEBUG_BYTES = 16 * 1024 * 1024;\nexport const MRV_MAX_MEMORY_PAGES = 1024 as const;\nexport const MRV_MAX_ABI_SYMBOLS = 1024 as const;\nexport const MRV_MAX_STORAGE_NAMESPACE_BYTES = 64 as const;\nexport const LYTH_DECIMALS = 8 as const;\nexport const NATIVE_LYTH_DECIMALS = LYTH_DECIMALS;\nexport const LYTHOSHI_PER_LYTH = 100_000_000n;\nexport const MRV_TX_EXTENSION_KIND = 0x30 as const;\nexport const MRV_TX_EXTENSION_V1 = 0x01 as const;\n\nconst MRV_CODE_HASH_DOMAIN = new TextEncoder().encode(\"MONO_MRV_CODE_V1\");\nconst MRV_CONTRACT_ADDRESS_DOMAIN = new TextEncoder().encode(\"mono:riscv:contract-address:v1\");\nconst MONO_SYSCALL_MODULE = \"mono\";\n\nconst SYSCALLS = [\n [0x0101, \"storage_read\"],\n [0x0102, \"storage_write\"],\n [0x0103, \"storage_delete\"],\n [0x0201, \"caller\"],\n [0x0202, \"contract_address\"],\n [0x0203, \"block_height\"],\n [0x0204, \"block_hash\"],\n [0x0301, \"call_contract\"],\n [0x0302, \"emit_event\"],\n [0x0303, \"transfer_native\"],\n [0x0401, \"verify_signature\"],\n [0x0402, \"hash\"],\n [0x0501, \"revert\"],\n] as const;\n\nconst SYSCALL_NAME_BY_ID = new Map<number, string>(SYSCALLS);\nconst SYSCALL_ID_BY_NAME = new Map<string, number>(SYSCALLS.map(([id, name]) => [name, id]));\n\nexport class MrvValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MrvValidationError\";\n }\n}\n\nexport interface LythFormatOptions {\n includeUnit?: boolean;\n}\n\nexport const MRV_STRUCTURED_FEE_FIELDS = [\n \"total_lythoshi\",\n \"cycles_used\",\n \"base_price_per_cycle_lythoshi\",\n \"state_io_units\",\n \"state_io_price_per_unit_lythoshi\",\n \"priority_tip_lythoshi\",\n] as const;\n\nexport interface MrvFeeDisplayConformanceInput {\n expectedTotalLythoshi: MrvDecimalLike;\n defaultFeeText: string;\n detailTexts?: readonly string[];\n structuredFee?: unknown;\n customFeeInputVisible?: boolean;\n speedUpCancelVisible?: boolean;\n}\n\nexport interface MrvFeeDisplayConformanceReport {\n passed: boolean;\n failures: string[];\n expectedDefaultFeeText: string;\n}\n\nexport interface MrvStructuredFeeConformanceOptions {\n expectedTotalLythoshi?: MrvDecimalLike;\n label?: string;\n}\n\nexport interface MrvStructuredFeeConformanceReport {\n passed: boolean;\n failures: string[];\n}\n\nexport interface NativeReceiptFeeDisplay {\n defaultFeeText: string;\n detailTexts: string[];\n totalLythoshi: string;\n totalLyth: string;\n}\n\nexport function formatLyth(lythoshi: MrvDecimalLike, options: LythFormatOptions = {}): string {\n const amount = BigInt(normalizeDecimalLike(\"lythoshi\", lythoshi));\n const whole = amount / LYTHOSHI_PER_LYTH;\n const fraction = amount % LYTHOSHI_PER_LYTH;\n let formatted = formatWholeWithCommas(whole);\n if (fraction !== 0n) {\n formatted += `.${fraction.toString().padStart(NATIVE_LYTH_DECIMALS, \"0\").replace(/0+$/, \"\")}`;\n }\n if (options.includeUnit !== false) {\n formatted += \" LYTH\";\n }\n return formatted;\n}\n\nexport function formatLythoshi(lythoshi: MrvDecimalLike, options: LythFormatOptions = {}): string {\n return formatLyth(lythoshi, options);\n}\n\nexport function parseLythToLythoshi(input: string): bigint {\n const numeric = stripLythUnit(input);\n const parts = numeric.split(\".\");\n if (parts.length > 2) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n const [wholeRaw, fractionRaw = \"\"] = parts;\n if (!isCanonicalWholeLyth(wholeRaw)) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n if (numeric.includes(\".\") && fractionRaw.length === 0) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n if (fractionRaw.length > NATIVE_LYTH_DECIMALS || !/^[0-9]*$/.test(fractionRaw)) {\n throw new MrvValidationError(\"lyth amount supports at most 8 decimal places\");\n }\n const whole = BigInt(wholeRaw.replaceAll(\",\", \"\"));\n const fraction = fractionRaw === \"\" ? 0n : BigInt(fractionRaw.padEnd(NATIVE_LYTH_DECIMALS, \"0\"));\n return whole * LYTHOSHI_PER_LYTH + fraction;\n}\n\nexport function checkMrvFeeDisplayConformance(\n input: MrvFeeDisplayConformanceInput,\n): MrvFeeDisplayConformanceReport {\n const expectedTotalLythoshi = normalizeDecimalLike(\"expectedTotalLythoshi\", input.expectedTotalLythoshi);\n const expectedDefaultFeeText = formatLyth(expectedTotalLythoshi);\n const failures: string[] = [];\n const amountCandidates = extractLythAmountCandidates(input.defaultFeeText);\n\n if (amountCandidates.length !== 1) {\n failures.push(\"defaultFeeText must contain exactly one LYTH-denominated fee amount\");\n } else {\n const renderedCandidate = `${amountCandidates[0]} LYTH`;\n if (renderedCandidate !== expectedDefaultFeeText) {\n failures.push(`defaultFeeText fee must be ${expectedDefaultFeeText}`);\n }\n try {\n const parsed = parseLythToLythoshi(renderedCandidate);\n if (parsed.toString() !== expectedTotalLythoshi) {\n failures.push(`defaultFeeText fee must total ${expectedTotalLythoshi} lythoshi`);\n }\n } catch {\n failures.push(\"defaultFeeText fee must be a canonical 8-decimal LYTH amount\");\n }\n }\n\n const defaultForbidden = firstForbiddenDefaultFeeTerm(input.defaultFeeText);\n if (defaultForbidden !== undefined) {\n failures.push(`defaultFeeText exposes detail-only fee term '${defaultForbidden}'`);\n }\n\n for (const [index, detailText] of (input.detailTexts ?? []).entries()) {\n const detailForbidden = firstForbiddenDetailFeeTerm(detailText);\n if (detailForbidden !== undefined) {\n failures.push(`detailTexts[${index}] exposes inherited fee term '${detailForbidden}'`);\n }\n }\n\n if (input.structuredFee !== undefined) {\n checkStructuredFeeObject(input.structuredFee, expectedTotalLythoshi, failures);\n }\n\n if (input.customFeeInputVisible === true) {\n failures.push(\"default surface must not expose custom fee inputs\");\n }\n if (input.speedUpCancelVisible === true) {\n failures.push(\"default surface must not expose speed-up or cancel controls\");\n }\n\n return {\n passed: failures.length === 0,\n failures,\n expectedDefaultFeeText,\n };\n}\n\nexport function checkMrvStructuredFeeConformance(\n value: unknown,\n options: MrvStructuredFeeConformanceOptions = {},\n): MrvStructuredFeeConformanceReport {\n const failures: string[] = [];\n const expectedTotalLythoshi =\n options.expectedTotalLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"expectedTotalLythoshi\", options.expectedTotalLythoshi);\n checkStructuredFeeObject(\n value,\n expectedTotalLythoshi,\n failures,\n options.label ?? \"structuredFee\",\n );\n return {\n passed: failures.length === 0,\n failures,\n };\n}\n\nexport function assertMrvStructuredFeeConformance(\n value: unknown,\n options: MrvStructuredFeeConformanceOptions = {},\n): asserts value is NativeReceiptFee {\n const report = checkMrvStructuredFeeConformance(value, options);\n if (!report.passed) {\n throw new MrvValidationError(`structured fee conformance failed: ${report.failures.join(\"; \")}`);\n }\n}\n\nexport function assertMrvFeeDisplayConformance(input: MrvFeeDisplayConformanceInput): void {\n const report = checkMrvFeeDisplayConformance(input);\n if (!report.passed) {\n throw new MrvValidationError(`fee display conformance failed: ${report.failures.join(\"; \")}`);\n }\n}\n\nexport function formatNativeReceiptFeeDisplay(\n fee: Pick<\n NativeReceiptFee,\n | \"total_lythoshi\"\n | \"cycles_used\"\n | \"state_io_units\"\n | \"base_price_per_cycle_lythoshi\"\n | \"state_io_price_per_unit_lythoshi\"\n | \"priority_tip_lythoshi\"\n >,\n): NativeReceiptFeeDisplay {\n const totalLythoshi = normalizeDecimalLike(\"fee.total_lythoshi\", fee.total_lythoshi);\n const totalLyth = formatLyth(totalLythoshi, { includeUnit: false });\n return {\n defaultFeeText: `Network fee: ${totalLyth} LYTH`,\n detailTexts: [\n `cycles ${fee.cycles_used}, state I/O ${fee.state_io_units}, total ${totalLythoshi} lythoshi`,\n `cycle price ${fee.base_price_per_cycle_lythoshi} lythoshi, state I/O price ${fee.state_io_price_per_unit_lythoshi} lythoshi, priority tip ${fee.priority_tip_lythoshi} lythoshi`,\n ],\n totalLythoshi,\n totalLyth,\n };\n}\n\nexport function mrvCodeHashHex(code: MrvBytesLike): string {\n const codeBytes = bytesFrom(code, \"code\");\n const len = new Uint8Array(8);\n new DataView(len.buffer).setBigUint64(0, BigInt(codeBytes.length), false);\n return bytesToHex(blake3(concatBytes(MRV_CODE_HASH_DOMAIN, len, codeBytes)));\n}\n\nexport function mrvV1TransactionExtension(): MrvTransactionExtension {\n return { kind: MRV_TX_EXTENSION_KIND, bodyHex: \"0x01\" };\n}\n\nexport function encodeMrvDeployPayload(\n artifactBytes: MrvBytesLike,\n constructorInput?: MrvBytesLike | null,\n): string {\n const artifact = bytesFrom(artifactBytes, \"artifactBytes\");\n const w = new BincodeWriter();\n w.u16(MRV_DEPLOY_PAYLOAD_VERSION);\n w.bytes(artifact);\n if (constructorInput === undefined || constructorInput === null) {\n w.u8(0);\n } else {\n const constructor = bytesFrom(constructorInput, \"constructorInput\");\n w.u8(1);\n w.bytes(constructor);\n }\n return bytesToHex(w.toBytes());\n}\n\nexport function mrvAddressToBech32(kind: MrvAddressKind, bytes: MrvBytesLike): string {\n return addressToTypedBech32(kind as AddressKind, bytesFrom(bytes, \"address\"));\n}\n\nexport function mrvBech32ToAddress(address: string, expectedKind?: MrvAddressKind) {\n return typedBech32ToAddress(address, expectedKind as AddressKind | undefined);\n}\n\nexport function deriveMrvContractAddress(\n deployerAddress: string,\n deployerNonce: number | bigint,\n artifactHashHex: string,\n): string {\n const deployer = typedBech32ToAddress(deployerAddress);\n const artifactHash = hexToBytes(artifactHashHex, \"artifactHash\");\n if (artifactHash.length !== 32) throw new MrvValidationError(\"artifactHash must be 32 bytes\");\n const nonceValue = normalizeU64(deployerNonce, \"deployerNonce\");\n const nonce = new Uint8Array(8);\n new DataView(nonce.buffer).setBigUint64(0, nonceValue, false);\n const digest = blake3(\n concatBytes(\n MRV_CONTRACT_ADDRESS_DOMAIN,\n new TextEncoder().encode(ADDRESS_KIND_HRPS[deployer.kind]),\n Uint8Array.of(0),\n hexToBytes(deployer.hex, \"deployerAddress\"),\n nonce,\n artifactHash,\n ),\n );\n return addressToTypedBech32(\"contract\", digest.slice(0, 20));\n}\n\nexport function validateMrvArtifactMetadata(\n metadata: MrvArtifactMetadata,\n code: MrvBytesLike,\n): MrvValidatedArtifactMetadata {\n const codeBytes = bytesFrom(code, \"code\");\n if (metadata.formatVersion !== MRV_FORMAT_VERSION) {\n throw new MrvValidationError(\n `unsupported MRV format version ${metadata.formatVersion}, expected ${MRV_FORMAT_VERSION}`,\n );\n }\n if (metadata.profile !== MRV_PROFILE_MONO_RV32IM_V1) {\n throw new MrvValidationError(`unsupported MRV profile ${metadata.profile}`);\n }\n if (codeBytes.length === 0) {\n throw new MrvValidationError(\"MRV code is empty\");\n }\n if (codeBytes.length > MRV_MAX_CODE_BYTES) {\n throw new MrvValidationError(`MRV code has ${codeBytes.length} bytes, max ${MRV_MAX_CODE_BYTES}`);\n }\n if (metadata.codeBytes !== BigInt(codeBytes.length)) {\n throw new MrvValidationError(\n `metadata codeBytes ${metadata.codeBytes.toString()} does not match supplied code length ${codeBytes.length}`,\n );\n }\n if (metadata.debugBytes > BigInt(MRV_MAX_DEBUG_BYTES)) {\n throw new MrvValidationError(`MRV debug section has ${metadata.debugBytes.toString()} bytes`);\n }\n validateHexLength(\"codeHash\", metadata.codeHash, 32);\n validateHexLength(\"sourceDigest\", metadata.build.sourceDigest, 32);\n validateMemory(metadata.memory.initialPages, metadata.memory.maxPages, metadata.memory.stackBytes);\n validateStorageNamespace(metadata.storageNamespace.name, metadata.storageNamespace.version);\n validateAbi(metadata.abi);\n const syscalls = validateImports(metadata.imports);\n const computed = mrvCodeHashHex(codeBytes);\n if (metadata.codeHash.toLowerCase() !== computed) {\n throw new MrvValidationError(`MRV code hash mismatch: declared ${metadata.codeHash}, computed ${computed}`);\n }\n return {\n codeHash: computed,\n profile: metadata.profile,\n memory: metadata.memory,\n storageNamespace: metadata.storageNamespace,\n syscalls,\n abiSymbolCount: BigInt(metadata.abi.symbols.length),\n codeBytes: BigInt(codeBytes.length),\n };\n}\n\nexport function validateMrvDeployRequest(request: MrvDeployRequest): void {\n if (request.from !== undefined) typedBech32ToAddress(request.from, \"user\");\n hexToBytes(request.artifactBytes, \"artifactBytes\");\n validateDecimal(\"valueLythoshi\", request.valueLythoshi);\n validateOptionalDecimal(\"maxExecutionFeeLythoshi\", request.maxExecutionFeeLythoshi);\n validateOptionalDecimal(\"priorityTipLythoshi\", request.priorityTipLythoshi);\n validateExecutionUnitLimit(\"executionUnitLimit\", request.executionUnitLimit);\n}\n\nexport function validateMrvCallRequest(request: MrvCallRequest): void {\n if (request.from !== undefined) typedBech32ToAddress(request.from, \"user\");\n typedBech32ToAddress(request.contractAddress, \"contract\");\n hexToBytes(request.input, \"input\");\n validateDecimal(\"valueLythoshi\", request.valueLythoshi);\n validateOptionalDecimal(\"maxExecutionFeeLythoshi\", request.maxExecutionFeeLythoshi);\n validateOptionalDecimal(\"priorityTipLythoshi\", request.priorityTipLythoshi);\n validateExecutionUnitLimit(\"executionUnitLimit\", request.executionUnitLimit);\n}\n\nexport function buildMrvDeployRequest(\n artifactBytes: MrvBytesLike,\n options: MrvRequestBuildOptions = {},\n): MrvDeployRequest {\n const request: MrvDeployRequest = {\n artifactBytes: normalizeBytesHex(artifactBytes, \"artifactBytes\"),\n valueLythoshi: normalizeDecimalLike(\"valueLythoshi\", options.valueLythoshi, \"0\"),\n };\n applyRequestOptions(request, options);\n validateMrvDeployRequest(request);\n return request;\n}\n\nexport function buildMrvDeployPayloadRequest(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadRequestOptions = {},\n): MrvDeployRequest {\n const request = buildMrvDeployRequest(\n encodeMrvDeployPayload(artifactBytes, options.constructorInput),\n options,\n );\n return request;\n}\n\nexport function buildMrvCallRequest(\n contractAddress: string,\n input: MrvBytesLike = \"0x\",\n options: MrvRequestBuildOptions = {},\n): MrvCallRequest {\n const request: MrvCallRequest = {\n contractAddress,\n input: normalizeBytesHex(input, \"input\"),\n valueLythoshi: normalizeDecimalLike(\"valueLythoshi\", options.valueLythoshi, \"0\"),\n };\n applyRequestOptions(request, options);\n validateMrvCallRequest(request);\n return request;\n}\n\nexport function buildMrvDeployPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPlanOptions = {},\n): MrvDeployPlan {\n const request = buildMrvDeployRequest(artifactBytes, options);\n const plan: MrvDeployPlan = {\n request,\n extension: mrvV1TransactionExtension(),\n };\n if (options.artifactHash !== undefined && request.from !== undefined && request.nonce !== undefined) {\n plan.expectedContractAddress = deriveMrvContractAddress(request.from, request.nonce, options.artifactHash);\n } else if (options.artifactHash !== undefined) {\n validateHexLength(\"artifactHash\", options.artifactHash, 32);\n }\n return plan;\n}\n\nexport function buildMrvDeployPayloadPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadPlanOptions = {},\n): MrvDeployPlan {\n const request = buildMrvDeployPayloadRequest(artifactBytes, options);\n const plan: MrvDeployPlan = {\n request,\n extension: mrvV1TransactionExtension(),\n };\n if (options.artifactHash !== undefined && request.from !== undefined && request.nonce !== undefined) {\n plan.expectedContractAddress = deriveMrvContractAddress(request.from, request.nonce, options.artifactHash);\n } else if (options.artifactHash !== undefined) {\n validateHexLength(\"artifactHash\", options.artifactHash, 32);\n }\n return plan;\n}\n\nexport function buildMrvCallPlan(\n contractAddress: string,\n input: MrvBytesLike = \"0x\",\n options: MrvRequestBuildOptions = {},\n): MrvCallPlan {\n return {\n request: buildMrvCallRequest(contractAddress, input, options),\n extension: mrvV1TransactionExtension(),\n };\n}\n\nexport function buildMrvDeployNativeTxPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployNativeTxOptions,\n): MrvDeployNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvDeployPlan(artifactBytes, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: null,\n value: plan.request.valueLythoshi,\n input: plan.request.artifactBytes,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function buildMrvDeployPayloadNativeTxPlan(\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadNativeTxOptions,\n): MrvDeployNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvDeployPayloadPlan(artifactBytes, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: null,\n value: plan.request.valueLythoshi,\n input: plan.request.artifactBytes,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function buildMrvCallNativeTxPlan(\n contractAddress: string,\n input: MrvBytesLike,\n options: MrvCallNativeTxOptions,\n): MrvCallNativeTxPlan {\n const chainId = normalizeU64(options.chainId, \"chainId\");\n const nonce = normalizeU64(options.nonce, \"nonce\");\n const executionUnitLimit = normalizeU64(options.executionUnitLimit, \"executionUnitLimit\");\n const maxExecutionFee = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", options.maxExecutionFeeLythoshi);\n const priorityTip =\n options.priorityTipLythoshi === undefined\n ? undefined\n : normalizeDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n const plan = buildMrvCallPlan(contractAddress, input, {\n ...options,\n nonce,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip,\n });\n return {\n ...plan,\n nativeTx: {\n chainId,\n nonce,\n valueLythoshi: plan.request.valueLythoshi,\n executionUnitLimit,\n maxExecutionFeeLythoshi: maxExecutionFee,\n priorityTipLythoshi: priorityTip ?? \"0\",\n },\n feePreview: buildMrvNativeFeePreview(executionUnitLimit, maxExecutionFee, priorityTip ?? \"0\"),\n tx: {\n chainId,\n nonce,\n maxPriorityFeePerGas: priorityTip ?? \"0\",\n maxFeePerGas: maxExecutionFee,\n gasLimit: executionUnitLimit,\n to: typedBech32ToAddress(plan.request.contractAddress, \"contract\").hex,\n value: plan.request.valueLythoshi,\n input: plan.request.input,\n extensions: [plan.extension],\n },\n };\n}\n\nexport function assertMrvDeployNativeSubmissionPlan(plan: MrvDeployNativeTxPlan): void {\n assertMrvNativeSubmissionEnvelope(plan);\n if (plan.tx.to !== null) {\n throw new MrvValidationError(\"MRV deploy submission tx.to must be null\");\n }\n const txInput = normalizeBytesHex(plan.tx.input ?? \"0x\", \"tx.input\");\n if (txInput !== plan.request.artifactBytes) {\n throw new MrvValidationError(\"MRV deploy submission tx.input must match artifactBytes\");\n }\n}\n\nexport function assertMrvCallNativeSubmissionPlan(plan: MrvCallNativeTxPlan): void {\n assertMrvNativeSubmissionEnvelope(plan);\n const actualTo = normalizeNativeTxToHex(plan.tx.to, \"tx.to\");\n if (actualTo === null) {\n throw new MrvValidationError(\"MRV call submission tx.to must be a 20-byte contract address\");\n }\n const expectedTo = typedBech32ToAddress(plan.request.contractAddress, \"contract\").hex.toLowerCase();\n if (actualTo !== expectedTo) {\n throw new MrvValidationError(\"MRV call submission tx.to must match contractAddress\");\n }\n const txInput = normalizeBytesHex(plan.tx.input ?? \"0x\", \"tx.input\");\n if (txInput !== plan.request.input) {\n throw new MrvValidationError(\"MRV call submission tx.input must match request input\");\n }\n}\n\nfunction buildMrvNativeFeePreview(\n executionUnitLimit: bigint,\n maxExecutionFeeLythoshi: string,\n priorityTipLythoshi: string,\n): MrvNativeFeePreview {\n const totalLythoshi = normalizeDecimalLike(\"maxExecutionFeeLythoshi\", maxExecutionFeeLythoshi);\n return {\n totalLythoshi,\n totalLyth: formatLyth(totalLythoshi, { includeUnit: false }),\n cyclesUsed: executionUnitLimit,\n executionUnitLimit,\n maxExecutionFeeLythoshi: totalLythoshi,\n priorityTipLythoshi: normalizeDecimalLike(\"priorityTipLythoshi\", priorityTipLythoshi),\n };\n}\n\nexport async function submitMrvDeployNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n artifactBytes: MrvBytesLike,\n options: MrvDeploySubmitOptions,\n): Promise<MrvDeploySubmission> {\n const plan = buildMrvDeployNativeTxPlan(artifactBytes, options);\n assertMrvDeployNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nexport async function submitMrvDeployPayloadNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n artifactBytes: MrvBytesLike,\n options: MrvDeployPayloadSubmitOptions,\n): Promise<MrvDeployPayloadSubmission> {\n const plan = buildMrvDeployPayloadNativeTxPlan(artifactBytes, options);\n assertMrvDeployNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nexport async function submitMrvCallNativeTx(\n client: RpcClient,\n backend: MlDsa65Backend,\n contractAddress: string,\n input: MrvBytesLike,\n options: MrvCallSubmitOptions,\n): Promise<MrvCallSubmission> {\n const plan = buildMrvCallNativeTxPlan(contractAddress, input, options);\n assertMrvCallNativeSubmissionPlan(plan);\n const submission = await buildEncryptedSubmission({\n backend,\n tx: plan.tx,\n encryptionKey: options.encryptionKey ?? (await fetchEncryptionKey(client)),\n class: options.class,\n });\n return {\n ...plan,\n ...submission,\n txHash: await submitEncryptedEnvelope(client, submission.envelopeWireHex),\n };\n}\n\nfunction assertMrvNativeSubmissionEnvelope(plan: MrvDeployNativeTxPlan | MrvCallNativeTxPlan): void {\n const extensions = plan.tx.extensions ?? [];\n if (extensions.length !== 1) {\n throw new MrvValidationError(\"MRV native submission must carry exactly one transaction extension\");\n }\n assertMrvV1Extension(plan.extension, \"extension\");\n assertMrvV1Extension(extensions[0], \"tx.extensions[0]\");\n assertSameBigint(\"tx.chainId\", plan.tx.chainId, plan.nativeTx.chainId);\n assertSameBigint(\"tx.nonce\", plan.tx.nonce, plan.nativeTx.nonce);\n assertSameBigint(\"tx.gasLimit\", plan.tx.gasLimit, plan.nativeTx.executionUnitLimit);\n assertSameDecimal(\"tx.value\", plan.tx.value, plan.nativeTx.valueLythoshi);\n assertSameDecimal(\"tx.maxFeePerGas\", plan.tx.maxFeePerGas, plan.nativeTx.maxExecutionFeeLythoshi);\n assertSameDecimal(\"tx.maxPriorityFeePerGas\", plan.tx.maxPriorityFeePerGas, plan.nativeTx.priorityTipLythoshi);\n assertU128Lythoshi(\"maxExecutionFeeLythoshi\", plan.nativeTx.maxExecutionFeeLythoshi);\n assertU128Lythoshi(\"priorityTipLythoshi\", plan.nativeTx.priorityTipLythoshi);\n}\n\nfunction assertMrvV1Extension(extension: NativeTxExtensionLike, field: string): void {\n if (extension.kind !== MRV_TX_EXTENSION_KIND) {\n throw new MrvValidationError(`${field}.kind must be MRV v1 extension kind`);\n }\n const bodyHex = normalizeBytesHex(\"bodyHex\" in extension ? extension.bodyHex : extension.body, `${field}.body`);\n if (bodyHex !== \"0x01\") {\n throw new MrvValidationError(`${field}.body must be MRV v1 extension body`);\n }\n}\n\nfunction assertSameBigint(field: string, actual: bigint | number | string, expected: bigint): void {\n if (normalizeU64Like(actual, field) !== expected) {\n throw new MrvValidationError(`${field} must match nativeTx`);\n }\n}\n\nfunction assertSameDecimal(field: string, actual: MrvDecimalLike, expected: string): void {\n if (normalizeDecimalLike(field, actual) !== expected) {\n throw new MrvValidationError(`${field} must match nativeTx`);\n }\n}\n\nfunction assertU128Lythoshi(field: string, value: MrvDecimalLike): void {\n const normalized = BigInt(normalizeDecimalLike(field, value));\n if (normalized > (1n << 128n) - 1n) {\n throw new MrvValidationError(`${field} must fit in u128 for encrypted submission`);\n }\n}\n\nfunction normalizeNativeTxToHex(value: NativeEvmTxFields[\"to\"], field: string): string | null {\n if (value === null) return null;\n const bytes = bytesFrom(value, field);\n if (bytes.length !== 20) {\n throw new MrvValidationError(`${field} must be a 20-byte address`);\n }\n return bytesToHex(bytes).toLowerCase();\n}\n\nfunction normalizeU64Like(value: bigint | number | string, field: string): bigint {\n if (typeof value === \"string\") {\n return normalizeU64(BigInt(normalizeDecimalLike(field, value)), field);\n }\n return normalizeU64(value, field);\n}\n\nfunction validateMemory(initialPages: number, maxPages: number, stackBytes: number): void {\n if (initialPages === 0) throw new MrvValidationError(\"initialPages is zero\");\n if (maxPages === 0) throw new MrvValidationError(\"maxPages is zero\");\n if (initialPages > maxPages) throw new MrvValidationError(\"initialPages exceeds maxPages\");\n if (maxPages > MRV_MAX_MEMORY_PAGES) throw new MrvValidationError(\"maxPages exceeds bound\");\n if (stackBytes === 0) throw new MrvValidationError(\"stackBytes is zero\");\n const maxBytes = maxPages * MRV_MEMORY_PAGE_BYTES;\n if (stackBytes > maxBytes) throw new MrvValidationError(\"stackBytes exceeds max memory\");\n if (stackBytes % 16 !== 0) throw new MrvValidationError(\"stackBytes must be 16-byte aligned\");\n}\n\nfunction validateStorageNamespace(name: string, version: number): void {\n if (version === 0) throw new MrvValidationError(\"storage namespace version must be non-zero\");\n if (name.length > MRV_MAX_STORAGE_NAMESPACE_BYTES) throw new MrvValidationError(\"storage namespace is too long\");\n if (!isIdentifier(name)) throw new MrvValidationError(\"storage namespace is not canonical\");\n}\n\nfunction validateAbi(abi: MrvAbiManifest): void {\n if (abi.symbols.length === 0) throw new MrvValidationError(\"MRV ABI must declare at least one symbol\");\n if (abi.symbols.length > MRV_MAX_ABI_SYMBOLS) {\n throw new MrvValidationError(`MRV ABI has ${abi.symbols.length} symbols, max ${MRV_MAX_ABI_SYMBOLS}`);\n }\n const seen = new Set<string>();\n for (const symbol of abi.symbols) {\n if (!isIdentifier(symbol.name)) throw new MrvValidationError(`invalid MRV ABI symbol '${symbol.name}'`);\n if (seen.has(symbol.name)) throw new MrvValidationError(`duplicate MRV ABI symbol '${symbol.name}'`);\n seen.add(symbol.name);\n for (const param of [...symbol.inputs, ...symbol.outputs]) {\n if (!isIdentifier(param.name)) throw new MrvValidationError(`invalid MRV ABI parameter '${param.name}'`);\n validateAbiType(param.ty);\n }\n }\n}\n\nfunction validateAbiType(ty: MrvAbiType): void {\n if (ty.kind === \"fixedBytes\" && ty.len === 0) {\n throw new MrvValidationError(\"fixed bytes length is zero\");\n }\n}\n\nfunction validateImports(imports: MrvArtifactMetadata[\"imports\"]): MrvResolvedSyscall[] {\n const seen = new Set<number>();\n const resolved: MrvResolvedSyscall[] = [];\n for (const imp of imports) {\n if (imp.module !== MONO_SYSCALL_MODULE) {\n throw new MrvValidationError(`forbidden host import ${imp.module}.${imp.name}`);\n }\n const expectedName = SYSCALL_NAME_BY_ID.get(imp.id);\n if (expectedName === undefined) throw new MrvValidationError(`unknown MRV syscall id ${imp.id}`);\n const expectedId = SYSCALL_ID_BY_NAME.get(imp.name);\n if (expectedId === undefined) throw new MrvValidationError(`unknown MRV syscall name '${imp.name}'`);\n if (expectedId !== imp.id) {\n throw new MrvValidationError(`MRV syscall name/id mismatch for ${imp.name}: declared ${imp.id}`);\n }\n if (seen.has(imp.id)) throw new MrvValidationError(`duplicate MRV syscall '${expectedName}'`);\n seen.add(imp.id);\n resolved.push({ id: imp.id, name: expectedName });\n }\n return resolved;\n}\n\nfunction validateOptionalDecimal(field: string, value: string | undefined): void {\n if (value !== undefined) validateDecimal(field, value);\n}\n\nfunction applyRequestOptions(request: MrvDeployRequest | MrvCallRequest, options: MrvRequestBuildOptions): void {\n if (options.from !== undefined) request.from = options.from;\n const executionUnitLimit = normalizeOptionalU64(\"executionUnitLimit\", options.executionUnitLimit);\n if (executionUnitLimit !== undefined) request.executionUnitLimit = executionUnitLimit;\n const maxExecutionFee = normalizeOptionalDecimalLike(\n \"maxExecutionFeeLythoshi\",\n options.maxExecutionFeeLythoshi,\n );\n if (maxExecutionFee !== undefined) request.maxExecutionFeeLythoshi = maxExecutionFee;\n const priorityTip = normalizeOptionalDecimalLike(\"priorityTipLythoshi\", options.priorityTipLythoshi);\n if (priorityTip !== undefined) request.priorityTipLythoshi = priorityTip;\n const nonce = normalizeOptionalU64(\"nonce\", options.nonce);\n if (nonce !== undefined) request.nonce = nonce;\n}\n\nfunction normalizeBytesHex(value: MrvBytesLike, field: string): string {\n return bytesToHex(bytesFrom(value, field));\n}\n\nfunction normalizeOptionalDecimalLike(field: string, value: MrvDecimalLike | undefined): string | undefined {\n return value === undefined ? undefined : normalizeDecimalLike(field, value);\n}\n\nfunction formatWholeWithCommas(value: bigint): string {\n const digits = value.toString();\n const firstGroupLen = digits.length % 3;\n const groups: string[] = [];\n let index = 0;\n if (firstGroupLen !== 0) {\n groups.push(digits.slice(0, firstGroupLen));\n index = firstGroupLen;\n }\n while (index < digits.length) {\n groups.push(digits.slice(index, index + 3));\n index += 3;\n }\n return groups.join(\",\");\n}\n\nfunction stripLythUnit(input: string): string {\n const trimmed = input.trim();\n const withoutUnit = trimmed.replace(/\\s+LYTH$/i, \"\").trim();\n if (withoutUnit.length === 0) {\n throw new MrvValidationError(\"lyth amount must be a canonical LYTH decimal\");\n }\n return withoutUnit;\n}\n\nfunction isCanonicalWholeLyth(value: string): boolean {\n if (/^(0|[1-9][0-9]*)$/.test(value)) {\n return true;\n }\n return /^[1-9][0-9]{0,2}(,[0-9]{3})+$/.test(value);\n}\n\nfunction extractLythAmountCandidates(text: string): string[] {\n return [...text.matchAll(/(?:^|[^A-Za-z0-9_])([0-9][0-9,]*(?:\\.[0-9]+)?)\\s+LYTH\\b/g)].map(\n (match) => match[1],\n );\n}\n\nfunction firstForbiddenDefaultFeeTerm(text: string): string | undefined {\n const tokens = feeTermTokens(text);\n for (const forbidden of [\"gas\", \"gwei\", \"wei\", \"cycle\", \"cycles\", \"lythoshi\"]) {\n if (tokens.includes(forbidden)) return forbidden;\n }\n if (hasAdjacentTerms(tokens, \"state\", \"io\") || hasStateIOTerms(tokens)) return \"state I/O\";\n return undefined;\n}\n\nfunction firstForbiddenDetailFeeTerm(text: string): string | undefined {\n const tokens = feeTermTokens(text);\n for (const forbidden of [\"gas\", \"gwei\", \"wei\"]) {\n if (tokens.includes(forbidden)) return forbidden;\n }\n return undefined;\n}\n\nfunction feeTermTokens(text: string): string[] {\n return text.toLowerCase().match(/[a-z]+/g) ?? [];\n}\n\nfunction hasAdjacentTerms(tokens: readonly string[], first: string, second: string): boolean {\n return tokens.some((token, index) => token === first && tokens[index + 1] === second);\n}\n\nfunction hasStateIOTerms(tokens: readonly string[]): boolean {\n return tokens.some((token, index) => token === \"state\" && tokens[index + 1] === \"i\" && tokens[index + 2] === \"o\");\n}\n\nfunction checkStructuredFeeObject(\n value: unknown,\n expectedTotalLythoshi: string | undefined,\n failures: string[],\n label = \"structuredFee\",\n): void {\n if (!isRecord(value)) {\n failures.push(`${label} must be an object`);\n return;\n }\n const expectedFields = new Set<string>([...MRV_STRUCTURED_FEE_FIELDS, \"total_lyth\"]);\n const actualFields = Object.keys(value);\n for (const field of MRV_STRUCTURED_FEE_FIELDS) {\n if (!(field in value)) failures.push(`${label} is missing '${field}'`);\n }\n for (const field of actualFields) {\n if (!expectedFields.has(field)) failures.push(`${label} has unexpected field '${field}'`);\n }\n\n const totalLythoshi = stringField(value, \"total_lythoshi\", failures, label);\n const expectedTotal = expectedTotalLythoshi ?? totalLythoshi;\n if (\n totalLythoshi !== undefined &&\n expectedTotalLythoshi !== undefined &&\n totalLythoshi !== expectedTotalLythoshi\n ) {\n failures.push(`${label}.total_lythoshi must be ${expectedTotalLythoshi}`);\n }\n const totalLyth =\n \"total_lyth\" in value ? lythDecimalField(value, \"total_lyth\", failures, label) : undefined;\n if (totalLyth !== undefined && expectedTotal !== undefined) {\n const expectedTotalLyth = formatLyth(expectedTotal, { includeUnit: false });\n if (totalLyth !== expectedTotalLyth) {\n failures.push(`${label}.total_lyth must be ${expectedTotalLyth}`);\n }\n }\n for (const field of [\n \"base_price_per_cycle_lythoshi\",\n \"state_io_price_per_unit_lythoshi\",\n \"priority_tip_lythoshi\",\n ]) {\n stringField(value, field, failures, label);\n }\n for (const field of [\"cycles_used\", \"state_io_units\"]) {\n integerField(value, field, failures, label);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): string | undefined {\n const fieldValue = value[field];\n if (typeof fieldValue !== \"string\" || !isCanonicalUnsignedDecimalString(fieldValue)) {\n failures.push(`${label}.${field} must be a canonical unsigned decimal string`);\n return undefined;\n }\n return fieldValue;\n}\n\nfunction lythDecimalField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): string | undefined {\n const fieldValue = value[field];\n if (typeof fieldValue !== \"string\") {\n failures.push(`${label}.${field} must be a canonical LYTH decimal string`);\n return undefined;\n }\n try {\n parseLythToLythoshi(`${fieldValue} LYTH`);\n } catch {\n failures.push(`${label}.${field} must be a canonical LYTH decimal string`);\n return undefined;\n }\n return fieldValue;\n}\n\nfunction integerField(\n value: Record<string, unknown>,\n field: string,\n failures: string[],\n label: string,\n): void {\n const fieldValue = value[field];\n if (\n typeof fieldValue !== \"number\" ||\n !Number.isSafeInteger(fieldValue) ||\n fieldValue < 0\n ) {\n failures.push(`${label}.${field} must be a non-negative safe integer`);\n }\n}\n\nfunction isCanonicalUnsignedDecimalString(value: string): boolean {\n if (!/^(0|[1-9][0-9]*)$/.test(value)) return false;\n try {\n BigInt(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalizeDecimalLike(field: string, value: MrvDecimalLike | undefined, defaultValue?: string): string {\n if (value === undefined) {\n if (defaultValue === undefined) throw new MrvValidationError(`${field} is required`);\n return defaultValue;\n }\n if (typeof value === \"string\") {\n validateDecimal(field, value);\n return value;\n }\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n throw new MrvValidationError(`${field} must be a safe unsigned integer`);\n }\n const out = BigInt(value);\n if (out < 0n) throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n return out.toString();\n}\n\nfunction normalizeOptionalU64(field: string, value: number | bigint | undefined): bigint | undefined {\n return value === undefined ? undefined : normalizeU64(value, field);\n}\n\nfunction validateDecimal(field: string, value: string): void {\n if (!/^(0|[1-9][0-9]*)$/.test(value)) {\n throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n }\n try {\n BigInt(value);\n } catch {\n throw new MrvValidationError(`${field} must be a canonical unsigned decimal string`);\n }\n}\n\nfunction validateExecutionUnitLimit(field: string, value: number | bigint | undefined): void {\n if (value !== undefined && BigInt(value) === 0n) {\n throw new MrvValidationError(`${field} must be greater than zero`);\n }\n}\n\nfunction normalizeU64(value: number | bigint, field: string): bigint {\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n throw new MrvValidationError(`${field} must be a safe unsigned integer`);\n }\n const out = BigInt(value);\n if (out < 0n || out > 0xffff_ffff_ffff_ffffn) {\n throw new MrvValidationError(`${field} must fit in u64`);\n }\n return out;\n}\n\nfunction validateHexLength(field: string, value: string, expected: number): void {\n const bytes = hexToBytes(value, field);\n if (bytes.length !== expected) throw new MrvValidationError(`${field} must be ${expected} bytes`);\n}\n\nfunction bytesFrom(value: MrvBytesLike, field: string): Uint8Array {\n if (typeof value === \"string\") return hexToBytes(value, field);\n return value instanceof Uint8Array ? value : Uint8Array.from(value);\n}\n\nfunction hexToBytes(value: string, field: string): Uint8Array {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new MrvValidationError(`${field} must be 0x-prefixed even-length hex`);\n }\n const out = new Uint8Array((value.length - 2) / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = Number.parseInt(value.slice(2 + i * 2, 4 + i * 2), 16);\n }\n return out;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const len = parts.reduce((sum, item) => sum + item.length, 0);\n const out = new Uint8Array(len);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction isIdentifier(value: string): boolean {\n return /^[a-z][a-z0-9_]*$/.test(value);\n}\n","/**\n * Chain-registry snapshot and helpers.\n *\n * Source of truth:\n * https://github.com/monolythium/chain-registry\n *\n * The SDK vendors a release-time snapshot so callers can bootstrap without\n * network access to GitHub. Callers that want the newest registry state can\n * opt into `fetchChainRegistryLatest()`.\n */\n\nimport { ML_DSA_65_PUBLIC_KEY_LEN } from \"./crypto/ml-dsa.js\";\nimport { hexToBytes } from \"./crypto/bytes.js\";\nimport type { NoEvmReceiptTrustPolicy } from \"./receipt-proof.js\";\n\nexport type NetworkSlug = \"testnet-69420\";\n\nconst BLS_PUBLIC_KEY_BYTE_LENGTH = 48;\n\nexport interface RpcEndpoint {\n url: string;\n provider: string;\n region?: string;\n tier: \"official\" | \"community\";\n archive?: boolean;\n ws_url?: string;\n notes?: string;\n}\n\nexport interface P2pSeed {\n multiaddr: string;\n region?: string;\n}\n\nexport interface ExplorerEndpoint {\n url: string;\n name: string;\n kind?: \"monoscan\" | \"etherscan-fork\" | \"custom\";\n}\n\nexport interface ReceiptProofTrustArchiveSigner {\n public_key: string;\n signer_id?: string;\n valid_from_height?: number;\n valid_to_height?: number;\n notes?: string;\n}\n\nexport interface ReceiptProofTrustArchivePolicy {\n signature_threshold: number;\n valid_from_height?: number;\n valid_to_height?: number;\n signers: ReceiptProofTrustArchiveSigner[];\n}\n\nexport interface ReceiptProofTrustFinalitySigner {\n authority_index: number;\n public_key: string;\n valid_from_round?: number;\n valid_to_round?: number;\n notes?: string;\n}\n\nexport interface ReceiptProofTrustFinalityPolicy {\n mode: \"cluster\" | \"multisig\";\n chain_id?: number;\n threshold: number;\n committee_size?: number;\n cluster_public_key?: string;\n valid_from_round?: number;\n valid_to_round?: number;\n signers?: ReceiptProofTrustFinalitySigner[];\n}\n\nexport interface ReceiptProofTrustPolicy {\n archive?: ReceiptProofTrustArchivePolicy;\n finality?: ReceiptProofTrustFinalityPolicy;\n}\n\nexport interface ChainInfo {\n chain_id: number;\n network: NetworkSlug | string;\n display_name?: string;\n description?: string;\n genesis_hash: string;\n binary_sha: string;\n rpc: RpcEndpoint[];\n p2p: P2pSeed[];\n explorer?: ExplorerEndpoint[];\n receipt_proof_trust?: ReceiptProofTrustPolicy;\n}\n\nexport type ChainRegistry = Record<NetworkSlug | string, ChainInfo>;\n\nexport const TESTNET_69420: ChainInfo = {\n chain_id: 69420,\n network: \"testnet-69420\",\n display_name: \"Monolythium Testnet\",\n description:\n \"Public Monolythium testnet. Testnet state may reset without notice; do not store value on this network.\",\n genesis_hash:\n \"0x325057e476b7be3730a22c92b9289f4a14a3414a2a081bd279b43eeba36b0075\",\n binary_sha: \"44a9ec4\",\n rpc: [\n {\n url: \"https://rpc.monolythium.com\",\n provider: \"monolythium\",\n tier: \"official\",\n },\n ],\n p2p: [],\n};\n\nexport const CHAIN_REGISTRY: ChainRegistry = {\n \"testnet-69420\": TESTNET_69420,\n};\n\nexport const CHAIN_REGISTRY_RAW_BASE =\n \"https://raw.githubusercontent.com/monolythium/chain-registry/master/chains\" as const;\n\nexport function getChainInfo(network: NetworkSlug | string): ChainInfo {\n const info = CHAIN_REGISTRY[network];\n if (!info) {\n throw new Error(`unknown Monolythium network: ${network}`);\n }\n return info;\n}\n\nexport function getRpcEndpoints(network: NetworkSlug | string): readonly RpcEndpoint[] {\n return getChainInfo(network).rpc;\n}\n\nexport function getP2pSeeds(network: NetworkSlug | string): readonly P2pSeed[] {\n return getChainInfo(network).p2p;\n}\n\nexport function getNoEvmReceiptTrustPolicy(\n network: NetworkSlug | string,\n registry: ChainRegistry = CHAIN_REGISTRY,\n): NoEvmReceiptTrustPolicy | null {\n const info = registry[network];\n if (!info) {\n throw new Error(`unknown Monolythium network: ${network}`);\n }\n return noEvmReceiptTrustPolicyFromChainInfo(info);\n}\n\nexport function noEvmReceiptTrustPolicyFromChainInfo(\n info: ChainInfo,\n): NoEvmReceiptTrustPolicy | null {\n const trust = info.receipt_proof_trust;\n if (trust == null || (trust.archive == null && trust.finality == null)) return null;\n\n const policy: NoEvmReceiptTrustPolicy = { chainId: info.chain_id };\n if (trust.archive != null) {\n policy.archive = {\n threshold: assertSafeIntegerAtLeast(\n trust.archive.signature_threshold,\n 1,\n \"receipt_proof_trust.archive.signature_threshold\",\n ),\n validFromHeight: trust.archive.valid_from_height,\n validToHeight: trust.archive.valid_to_height,\n trustedSigners: trust.archive.signers.map((signer, index) => ({\n publicKey: decodeFixedHex(\n signer.public_key,\n ML_DSA_65_PUBLIC_KEY_LEN,\n `receipt_proof_trust.archive.signers[${index}].public_key`,\n ),\n signerId: signer.signer_id,\n validFromHeight: signer.valid_from_height,\n validToHeight: signer.valid_to_height,\n })),\n };\n }\n if (trust.finality != null) {\n const threshold = assertSafeIntegerAtLeast(\n trust.finality.threshold,\n 1,\n \"receipt_proof_trust.finality.threshold\",\n );\n const chainId = trust.finality.chain_id ?? info.chain_id;\n if (trust.finality.mode === \"cluster\") {\n if (trust.finality.cluster_public_key == null) {\n throw new Error(\n \"receipt_proof_trust.finality.cluster_public_key is required for cluster mode\",\n );\n }\n policy.finality = {\n mode: \"cluster\",\n chainId,\n threshold,\n validFromRound: trust.finality.valid_from_round,\n validToRound: trust.finality.valid_to_round,\n committeeSize: assertSafeIntegerAtLeast(\n trust.finality.committee_size,\n 1,\n \"receipt_proof_trust.finality.committee_size\",\n ),\n clusterPublicKey: decodeFixedHex(\n trust.finality.cluster_public_key,\n BLS_PUBLIC_KEY_BYTE_LENGTH,\n \"receipt_proof_trust.finality.cluster_public_key\",\n ),\n };\n } else if (trust.finality.mode === \"multisig\") {\n const signers = trust.finality.signers ?? [];\n policy.finality = {\n mode: \"multisig\",\n chainId,\n threshold,\n validFromRound: trust.finality.valid_from_round,\n validToRound: trust.finality.valid_to_round,\n trustedSigners: signers.map((signer, index) => ({\n authorityIndex: assertSafeIntegerAtLeast(\n signer.authority_index,\n 0,\n `receipt_proof_trust.finality.signers[${index}].authority_index`,\n ),\n publicKey: decodeFixedHex(\n signer.public_key,\n BLS_PUBLIC_KEY_BYTE_LENGTH,\n `receipt_proof_trust.finality.signers[${index}].public_key`,\n ),\n validFromRound: signer.valid_from_round,\n validToRound: signer.valid_to_round,\n })),\n };\n } else {\n throw new Error(\n `unsupported receipt_proof_trust.finality.mode: ${String(trust.finality.mode)}`,\n );\n }\n }\n\n return policy;\n}\n\nexport interface FetchChainRegistryOptions {\n fetch?: typeof fetch;\n rawBaseUrl?: string;\n}\n\nexport async function fetchChainInfoLatest(\n network: NetworkSlug | string,\n options: FetchChainRegistryOptions = {},\n): Promise<ChainInfo> {\n const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n const rawBaseUrl = options.rawBaseUrl ?? CHAIN_REGISTRY_RAW_BASE;\n const resp = await fetchImpl(`${rawBaseUrl}/${network}.toml`);\n if (!resp.ok) {\n throw new Error(`failed to fetch chain registry ${network}: HTTP ${resp.status}`);\n }\n return parseChainRegistryToml(await resp.text());\n}\n\nexport async function fetchChainRegistryLatest(\n networks: readonly (NetworkSlug | string)[] = [\"testnet-69420\"],\n options: FetchChainRegistryOptions = {},\n): Promise<ChainRegistry> {\n const entries = await Promise.all(\n networks.map(async (network) => [network, await fetchChainInfoLatest(network, options)] as const),\n );\n return Object.fromEntries(entries);\n}\n\nexport function parseChainRegistryToml(input: string): ChainInfo {\n const info: Partial<ChainInfo> & {\n rpc: RpcEndpoint[];\n p2p: P2pSeed[];\n explorer: ExplorerEndpoint[];\n receipt_proof_trust?: ReceiptProofTrustPolicy;\n } = {\n rpc: [],\n p2p: [],\n explorer: [],\n };\n let section:\n | \"root\"\n | \"rpc\"\n | \"p2p\"\n | \"explorer\"\n | \"receipt_proof_trust.archive\"\n | \"receipt_proof_trust.archive.signers\"\n | \"receipt_proof_trust.finality\"\n | \"receipt_proof_trust.finality.signers\" = \"root\";\n for (const rawLine of input.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\s+#.*$/, \"\").trim();\n if (!line || line.startsWith(\"#\")) continue;\n if (line === \"[[rpc]]\") {\n section = \"rpc\";\n info.rpc.push({ url: \"\", provider: \"\", tier: \"community\" });\n continue;\n }\n if (line === \"[[p2p]]\") {\n section = \"p2p\";\n info.p2p.push({ multiaddr: \"\" });\n continue;\n }\n if (line === \"[[explorer]]\") {\n section = \"explorer\";\n info.explorer.push({ url: \"\", name: \"\" });\n continue;\n }\n if (line === \"[receipt_proof_trust.archive]\") {\n section = \"receipt_proof_trust.archive\";\n ensureReceiptProofTrust(info).archive ??= { signature_threshold: 0, signers: [] };\n continue;\n }\n if (line === \"[[receipt_proof_trust.archive.signers]]\") {\n section = \"receipt_proof_trust.archive.signers\";\n const trust = ensureReceiptProofTrust(info);\n trust.archive ??= { signature_threshold: 0, signers: [] };\n trust.archive.signers.push({ public_key: \"\" });\n continue;\n }\n if (line === \"[receipt_proof_trust.finality]\") {\n section = \"receipt_proof_trust.finality\";\n ensureReceiptProofTrust(info).finality ??= {\n mode: \"cluster\",\n threshold: 0,\n };\n continue;\n }\n if (line === \"[[receipt_proof_trust.finality.signers]]\") {\n section = \"receipt_proof_trust.finality.signers\";\n const trust = ensureReceiptProofTrust(info);\n trust.finality ??= {\n mode: \"multisig\",\n threshold: 0,\n signers: [],\n };\n trust.finality.signers ??= [];\n trust.finality.signers.push({ authority_index: 0, public_key: \"\" });\n continue;\n }\n const match = /^([A-Za-z0-9_]+)\\s*=\\s*(.+)$/.exec(line);\n if (!match) continue;\n const [, key, rawValue] = match;\n const value = parseTomlScalar(rawValue);\n if (section === \"root\") {\n (info as Record<string, unknown>)[key] = value;\n } else if (section === \"rpc\" || section === \"p2p\" || section === \"explorer\") {\n const list = info[section];\n const target = list[list.length - 1] as unknown as Record<string, unknown>;\n target[key] = value;\n } else if (section === \"receipt_proof_trust.archive\") {\n const trust = ensureReceiptProofTrust(info);\n trust.archive ??= { signature_threshold: 0, signers: [] };\n (trust.archive as unknown as Record<string, unknown>)[key] = value;\n } else if (section === \"receipt_proof_trust.archive.signers\") {\n const archive = ensureReceiptProofTrust(info).archive ??= {\n signature_threshold: 0,\n signers: [],\n };\n const target = archive.signers[archive.signers.length - 1] as unknown as Record<\n string,\n unknown\n >;\n target[key] = value;\n } else if (section === \"receipt_proof_trust.finality\") {\n const trust = ensureReceiptProofTrust(info);\n trust.finality ??= { mode: \"cluster\", threshold: 0 };\n (trust.finality as unknown as Record<string, unknown>)[key] = value;\n } else {\n const finality = ensureReceiptProofTrust(info).finality ??= {\n mode: \"multisig\",\n threshold: 0,\n signers: [],\n };\n finality.signers ??= [];\n const target = finality.signers[finality.signers.length - 1] as unknown as Record<\n string,\n unknown\n >;\n target[key] = value;\n }\n }\n if (!info.network || !info.chain_id || !info.genesis_hash || !info.binary_sha) {\n throw new Error(\"chain registry TOML is missing required top-level fields\");\n }\n if (info.rpc.length === 0 || info.rpc.some((r) => !r.url || !r.provider || !r.tier)) {\n throw new Error(\"chain registry TOML must include at least one complete rpc endpoint\");\n }\n if (info.p2p.length === 0 || info.p2p.some((p) => !p.multiaddr)) {\n throw new Error(\"chain registry TOML must include at least one p2p seed\");\n }\n const out: ChainInfo = {\n chain_id: Number(info.chain_id),\n network: String(info.network),\n display_name: info.display_name ? String(info.display_name) : undefined,\n description: info.description ? String(info.description) : undefined,\n genesis_hash: String(info.genesis_hash),\n binary_sha: String(info.binary_sha),\n rpc: info.rpc,\n p2p: info.p2p,\n };\n if (info.explorer.length > 0) out.explorer = info.explorer;\n if (info.receipt_proof_trust) {\n out.receipt_proof_trust = normalizeReceiptProofTrust(info.receipt_proof_trust);\n }\n return out;\n}\n\nfunction parseTomlScalar(raw: string): string | number | boolean {\n const value = raw.trim();\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n }\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (/^-?\\d+$/.test(value)) return Number(value);\n return value;\n}\n\nfunction ensureReceiptProofTrust(\n info: Partial<ChainInfo> & { receipt_proof_trust?: ReceiptProofTrustPolicy },\n): ReceiptProofTrustPolicy {\n info.receipt_proof_trust ??= {};\n return info.receipt_proof_trust;\n}\n\nfunction normalizeReceiptProofTrust(trust: ReceiptProofTrustPolicy): ReceiptProofTrustPolicy {\n const out: ReceiptProofTrustPolicy = {};\n if (trust.archive == null || trust.finality == null) {\n throw new Error(\"receipt_proof_trust must include both archive and finality policies\");\n }\n if (trust.archive != null) {\n const threshold = assertSafeIntegerAtLeast(\n trust.archive.signature_threshold,\n 1,\n \"receipt_proof_trust.archive.signature_threshold\",\n );\n if (trust.archive.signers.length === 0 || trust.archive.signers.some((s) => !s.public_key)) {\n throw new Error(\"receipt_proof_trust.archive.signers must contain complete signer rows\");\n }\n if (threshold > trust.archive.signers.length) {\n throw new Error(\"receipt_proof_trust.archive.signature_threshold exceeds signer count\");\n }\n assertOptionalRange(\n trust.archive.valid_from_height,\n trust.archive.valid_to_height,\n \"receipt_proof_trust.archive\",\n );\n assertUniqueStrings(\n trust.archive.signers.map((signer) => signer.public_key),\n \"receipt_proof_trust.archive.signers.public_key\",\n );\n assertUniqueStrings(\n trust.archive.signers.flatMap((signer) => (signer.signer_id ? [signer.signer_id] : [])),\n \"receipt_proof_trust.archive.signers.signer_id\",\n );\n out.archive = {\n signature_threshold: threshold,\n valid_from_height: optionalSafeInteger(trust.archive.valid_from_height),\n valid_to_height: optionalSafeInteger(trust.archive.valid_to_height),\n signers: trust.archive.signers.map((signer) => {\n assertOptionalRange(\n signer.valid_from_height,\n signer.valid_to_height,\n \"receipt_proof_trust.archive.signers\",\n );\n return {\n public_key: assertString(\n signer.public_key,\n \"receipt_proof_trust.archive.signers.public_key\",\n ),\n signer_id: optionalString(signer.signer_id),\n valid_from_height: optionalSafeInteger(signer.valid_from_height),\n valid_to_height: optionalSafeInteger(signer.valid_to_height),\n notes: optionalString(signer.notes),\n };\n }),\n };\n }\n if (trust.finality != null) {\n const mode = trust.finality.mode;\n if (mode !== \"cluster\" && mode !== \"multisig\") {\n throw new Error(`unsupported receipt_proof_trust.finality.mode: ${String(mode)}`);\n }\n const finality: ReceiptProofTrustFinalityPolicy = {\n mode,\n chain_id: optionalSafeInteger(trust.finality.chain_id),\n threshold: assertSafeIntegerAtLeast(\n trust.finality.threshold,\n 1,\n \"receipt_proof_trust.finality.threshold\",\n ),\n valid_from_round: optionalSafeInteger(trust.finality.valid_from_round),\n valid_to_round: optionalSafeInteger(trust.finality.valid_to_round),\n };\n assertOptionalRange(\n trust.finality.valid_from_round,\n trust.finality.valid_to_round,\n \"receipt_proof_trust.finality\",\n );\n if (mode === \"cluster\") {\n finality.committee_size = assertSafeIntegerAtLeast(\n trust.finality.committee_size,\n 1,\n \"receipt_proof_trust.finality.committee_size\",\n );\n if (finality.threshold > finality.committee_size) {\n throw new Error(\"receipt_proof_trust.finality.threshold exceeds committee_size\");\n }\n finality.cluster_public_key = assertString(\n trust.finality.cluster_public_key,\n \"receipt_proof_trust.finality.cluster_public_key\",\n );\n if ((trust.finality.signers ?? []).length > 0) {\n throw new Error(\"receipt_proof_trust.finality.signers are invalid in cluster mode\");\n }\n } else {\n const signers = trust.finality.signers ?? [];\n if (signers.length === 0 || signers.some((s) => !s.public_key)) {\n throw new Error(\"receipt_proof_trust.finality.signers must contain complete signer rows\");\n }\n if (finality.threshold > signers.length) {\n throw new Error(\"receipt_proof_trust.finality.threshold exceeds signer count\");\n }\n if (trust.finality.committee_size != null || trust.finality.cluster_public_key != null) {\n throw new Error(\"receipt_proof_trust.finality cluster fields are invalid in multisig mode\");\n }\n assertUniqueNumbers(\n signers.map((signer) => signer.authority_index),\n \"receipt_proof_trust.finality.signers.authority_index\",\n );\n assertUniqueStrings(\n signers.map((signer) => signer.public_key),\n \"receipt_proof_trust.finality.signers.public_key\",\n );\n finality.signers = signers.map((signer) => {\n assertOptionalRange(\n signer.valid_from_round,\n signer.valid_to_round,\n \"receipt_proof_trust.finality.signers\",\n );\n return {\n authority_index: assertSafeIntegerAtLeast(\n signer.authority_index,\n 0,\n \"receipt_proof_trust.finality.signers.authority_index\",\n ),\n public_key: assertString(\n signer.public_key,\n \"receipt_proof_trust.finality.signers.public_key\",\n ),\n valid_from_round: optionalSafeInteger(signer.valid_from_round),\n valid_to_round: optionalSafeInteger(signer.valid_to_round),\n notes: optionalString(signer.notes),\n };\n });\n }\n out.finality = finality;\n }\n return out;\n}\n\nfunction decodeFixedHex(value: string, expectedLength: number, field: string): Uint8Array {\n const bytes = hexToBytes(assertString(value, field), field);\n if (bytes.length !== expectedLength) {\n throw new Error(`${field} must be ${expectedLength} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\nfunction assertString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`${field} must be a non-empty string`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return value === undefined ? undefined : assertString(value, \"optional string field\");\n}\n\nfunction optionalSafeInteger(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || Number(value) < 0) {\n throw new Error(\"optional integer field must be a non-negative safe integer\");\n }\n return Number(value);\n}\n\nfunction assertSafeIntegerAtLeast(value: unknown, min: number, field: string): number {\n if (!Number.isSafeInteger(value) || Number(value) < min) {\n throw new Error(`${field} must be a safe integer >= ${min}`);\n }\n return Number(value);\n}\n\nfunction assertOptionalRange(from: unknown, to: unknown, field: string): void {\n const start = optionalSafeInteger(from);\n const end = optionalSafeInteger(to);\n if (start != null && end != null && end < start) {\n throw new Error(`${field} valid_to must be >= valid_from`);\n }\n}\n\nfunction assertUniqueStrings(values: readonly string[], field: string): void {\n const seen = new Set<string>();\n for (const value of values) {\n const normalized = assertString(value, field).toLowerCase();\n if (seen.has(normalized)) {\n throw new Error(`${field} values must be unique`);\n }\n seen.add(normalized);\n }\n}\n\nfunction assertUniqueNumbers(values: readonly number[], field: string): void {\n const seen = new Set<number>();\n for (const value of values) {\n const normalized = assertSafeIntegerAtLeast(value, 0, field);\n if (seen.has(normalized)) {\n throw new Error(`${field} values must be unique`);\n }\n seen.add(normalized);\n }\n}\n","/**\n * Wire-shape types served by a `mono-core` node.\n *\n * Re-exports the `ts-rs`-generated definitions in `./bindings/`. Those\n * files are the authoritative source — they are written from Rust by\n * `cargo test --features ts-bindings` and copied into this package via\n * `pnpm run build:bindings` / `bash scripts/sync-bindings.sh`.\n *\n * Quantities (`u64` etc.) surface as `bigint` to preserve full\n * precision against the chain's 256-bit world. Hashes / addresses /\n * `0x`-hex byte vectors surface as `string`.\n */\n\nexport type * from \"./bindings/index.js\";\n\n/** `0x`-prefixed hex byte vector. */\nexport type Hex = string;\n\n/** `0x`-prefixed hex 20-byte address. */\nexport type Address = string;\n\n/** `0x`-prefixed hex 32-byte hash. */\nexport type Hash = string;\n\n/** `0x`-prefixed hex unsigned quantity. */\nexport type Quantity = string;\n\nimport type { BlockTag } from \"./bindings/BlockTag.js\";\nexport type { BlockTag };\n\n/**\n * Block selector for `eth_getBlock*`, `eth_call`, etc. — accepts a tag,\n * a numeric height (encoded by the client as `0x`-hex), a `bigint`, or\n * a 32-byte hash where the spec allows it.\n */\nexport type BlockSelector = BlockTag | number | bigint | Hash;\n\n/** Encode a `BlockSelector` for a JSON-RPC params array. */\nexport function encodeBlockSelector(b: BlockSelector): string {\n if (typeof b === \"number\") return `0x${b.toString(16)}`;\n if (typeof b === \"bigint\") return `0x${b.toString(16)}`;\n return b;\n}\n","/**\n * Typed JSON-RPC client for a `mono-core` node.\n *\n * Mirrors the Rust SDK's `RpcClient` — every public method maps 1:1 to\n * a method on the Rust client, returns the same wire-shape value, and\n * sends the same `lyth_*` / `eth_*` / `debug_*` JSON-RPC method strings.\n */\n\nimport {\n requireTypedAddress,\n type AddressKind,\n} from \"./address.js\";\nimport { SdkError } from \"./error.js\";\nimport type { BridgeRouteDisclosure, BridgeRoutesRequest, BridgeRoutesResponse } from \"./bridge.js\";\nimport {\n nativeEventsFromHistory,\n nativeEventsFromReceipt,\n nativeMarketEventsFromHistory,\n nativeMarketEventsFromReceipt,\n} from \"./native-events.js\";\nimport {\n isConcreteServiceProbeStatus,\n isSinglePublicServiceProbeMask,\n isValidPublicServiceProbeMask,\n} from \"./node-registry.js\";\nimport { assertMrvStructuredFeeConformance } from \"./mrv.js\";\nimport { getChainInfo, type ChainInfo, type ChainRegistry, type NetworkSlug } from \"./registry.js\";\nimport type {\n AccountPolicy,\n AccountProofResponse,\n AddressActivityEntry,\n AddressActivityKindResponse,\n AddressLabelRecord,\n AssetPolicy,\n BlsCertificateResponse,\n BlockHeader,\n CallRequest,\n CapabilitiesResponse,\n CheckpointRecord,\n ClobMarketResponse,\n ClusterDelegatorsResponse,\n ClusterEntityResponse,\n ClusterResignationsResponse,\n DagParentsResponse,\n DagSyncStatus,\n DecodeTxResponse,\n DelegationCapResponse,\n DelegationHistoryRecord,\n DelegationsResponse,\n EncryptionKeyResponse,\n EntityRatchetResponse,\n FeeHistoryResponse,\n GapRecordsResponse,\n IndexerStatus,\n MempoolSnapshot,\n MeshDecodedTx,\n MeshSignedTxResponse,\n MeshTxIntent,\n MeshUnsignedTxResponse,\n MrcAccountRequest,\n MrcAccountResponse,\n MrcHoldersRequest,\n MrcHoldersResponse,\n MrcMetadataResponse,\n PeerSummary,\n PendingRewardsResponse,\n PendingTxSummary,\n PrecompileDescriptor,\n RedemptionQueueResponse,\n RegistryRecord,\n RichListResponse,\n RoundInfo,\n StorageProofBatch,\n SyncStatus,\n TpmAttestationResponse,\n TransactionReceipt,\n TransactionView,\n TokenBalanceMrcIdentity,\n TokenBalanceRecord,\n} from \"./bindings/index.js\";\nimport type { BlockSelector } from \"./types.js\";\nimport { encodeBlockSelector } from \"./types.js\";\nimport type { ApiStreamTopic } from \"./streams.js\";\nimport type {\n NativeDecodedEvent,\n NativeEventFilter,\n TypedNativeReceiptEvent,\n} from \"./native-events.js\";\n\n/** Optional per-client configuration. */\nexport interface RpcClientOptions {\n /** Override `fetch`. Useful for tests or non-Node environments. */\n fetch?: typeof fetch;\n /** Extra headers to attach to every request. */\n headers?: Record<string, string>;\n}\n\nexport interface NetworkClientOptions extends RpcClientOptions {\n /** Registry snapshot to use instead of the SDK-bundled snapshot. */\n registry?: ChainRegistry;\n /** Probe all known endpoints and choose the first one that answers. */\n probe?: boolean;\n}\n\n/** Typed user address (`mono1...`) accepted at public SDK boundaries. */\nexport type UserAddressInput = string;\n\nexport interface TxFeedReceipt {\n status: number;\n executionUnitsUsed: number;\n logsCount: number;\n}\n\nexport interface TxFeedTransaction {\n txHash: string;\n blockHash: string;\n blockNumber: number;\n blockTimestamp: number | null;\n txIndex: number;\n from: string;\n to: string | null;\n nonce: number;\n /** Native value in lythoshi. The tx-feed wire key is still `value`. */\n value: string;\n executionUnitLimit: number;\n maxExecutionFeeLythoshi: string;\n priorityTipLythoshi: string;\n fee: NativeReceiptFee;\n input: string;\n receipt: TxFeedReceipt | null;\n}\n\nexport interface TxFeedResponse {\n schemaVersion: number;\n latestHeight: number;\n limit: number;\n nextCursor: string | null;\n transactions: TxFeedTransaction[];\n}\n\nexport interface ExecutionUnitPriceResponse {\n executionUnitPriceLythoshi: string;\n basePricePerExecutionUnitLythoshi: string;\n priorityTipLythoshi: string;\n blockNumber: number | null;\n source: string;\n}\n\nexport const MAX_NATIVE_RECEIPT_EVENTS = 1_000;\n\nexport interface NativeReceiptCounters {\n cycles: number;\n syscallUnits: number;\n stateIoUnits: number;\n}\n\nexport interface NativeReceiptFee {\n total_lythoshi: string;\n total_lyth?: string;\n cycles_used: number;\n base_price_per_cycle_lythoshi: string;\n state_io_units: number;\n state_io_price_per_unit_lythoshi: string;\n priority_tip_lythoshi: string;\n}\n\nexport interface NativeReceiptEvent<TDecoded = unknown> {\n blockHeight: number;\n txIndex: number;\n logIndex: number;\n address: string;\n eventTopic: string;\n decoded: TDecoded;\n decodedJson: string;\n}\n\nexport interface NativeReceiptSource {\n chainProvider: string;\n indexerProvider: string;\n metadataLogIndex: number;\n}\n\nexport interface NoEvmCompactInclusionProof {\n schema: \"mono.no_evm_receipt_compact_inclusion.v1\";\n treeAlgorithm: \"binary-keccak-receipt-tree\";\n root: string;\n leafHash: string;\n siblingHashes: string[];\n pathSides: boolean[];\n}\n\nexport interface NoEvmArchiveProof {\n schema: \"mono.no_evm_receipt_archive_binding.v1\";\n source: \"indexerReceiptArchiveContentDigest\" | string;\n manifestHash: string;\n contentHash: string;\n signatureDigest?: string | null;\n signatures: string[];\n coveringSnapshot?: NoEvmArchiveCoveringSnapshot | null;\n}\n\nexport interface NoEvmArchiveCoveringSnapshot {\n snapshotHeight: number;\n manifestHash: string;\n signatureDigest: string;\n contentHash: string;\n checkpointContentHash: string;\n checkpointFrom: number;\n checkpointTo: number;\n signatures: string[];\n}\n\nexport interface NoEvmFinalityCertificate {\n round: number;\n signature: string;\n signersBitmap: string;\n signerIndices: number[];\n signerCount: number;\n}\n\nexport interface NoEvmFinalityBlockReference {\n round: number;\n authority: number;\n digest: string;\n}\n\nexport interface NoEvmFinalityEvidence {\n schema: \"mono.no_evm_receipt_finality.v1\";\n source: \"blsRoundCertificate\" | string;\n round: number;\n certificate: NoEvmFinalityCertificate;\n blockReference?: NoEvmFinalityBlockReference | null;\n leaderCertificate?: NoEvmFinalityCertificate | null;\n dacCertificate?: NoEvmFinalityCertificate | null;\n}\n\ninterface NoEvmReceiptProofBase {\n schema: \"mono.no_evm_receipt_proof.v1\";\n rootAlgorithm: string;\n receiptCodec: \"bincode(protocore_execution_types::Receipt)\";\n blockHash: string;\n txHash: string;\n receiptsRoot: string;\n targetReceiptHash: string;\n blockHeight: number;\n txIndex: number;\n receiptCount: number;\n finalityEvidence?: NoEvmFinalityEvidence | null;\n}\n\nexport interface NoEvmBoundedReceiptProof extends NoEvmReceiptProofBase {\n proofKind?: \"boundedCacheTranscript\";\n proofType: \"canonicalReceiptsTranscript\";\n historySource?: \"legacyUnspecified\" | \"liveBlockCache\";\n compactInclusionProof?: null;\n archiveProof?: null;\n missingProofMaterial?: string[];\n receiptTranscript: string[];\n}\n\nexport interface NoEvmCompactReceiptProof extends NoEvmReceiptProofBase {\n proofKind: \"compactInclusion\";\n proofType: \"canonicalReceiptInclusion\";\n historySource: \"liveBlockCache\" | \"indexerReceiptArchive\";\n compactInclusionProof: NoEvmCompactInclusionProof;\n archiveProof?: NoEvmArchiveProof | null;\n missingProofMaterial?: string[];\n targetReceiptBytes: string;\n receiptTranscript?: string[];\n}\n\nexport type NoEvmReceiptProof = NoEvmBoundedReceiptProof | NoEvmCompactReceiptProof;\n\nexport interface NativeReceiptResponse<TDecoded = unknown> {\n txHash: string;\n blockHash: string;\n blockHeight: number;\n txIndex: number;\n schema: string;\n artifactHash: string;\n receiptCommitment: string;\n /** Current nodes may return `null`; older nodes may omit the field. */\n noEvmProof?: NoEvmReceiptProof | null;\n counters: NativeReceiptCounters;\n fee: NativeReceiptFee;\n reverted: boolean;\n nativeDeltaCount: number;\n eventCount: number;\n events: Array<NativeReceiptEvent<TDecoded>>;\n source: NativeReceiptSource;\n}\n\n/** Filter object passed to `lyth_nativeEvents` and `/api/v1/native-events`. */\nexport interface NativeEventsFilter {\n fromBlock: number | bigint | string;\n toBlock: number | bigint | string;\n limit?: number | bigint | string | null;\n txIndex?: number | bigint | string | null;\n logIndex?: number | bigint | string | null;\n address?: string | null;\n eventTopic?: string | null;\n family?: string | null;\n eventName?: string | null;\n primaryId?: string | null;\n relatedId?: string | null;\n tokenId?: string | null;\n account?: string | null;\n counterparty?: string | null;\n}\n\nexport interface NativeEventsResponseFilters {\n txIndex?: number | null;\n logIndex?: number | null;\n address?: string | null;\n eventTopic?: string | null;\n family?: string | null;\n eventName?: string | null;\n primaryId?: string | null;\n relatedId?: string | null;\n tokenId?: string | null;\n account?: string | null;\n counterparty?: string | null;\n}\n\nexport interface NativeEventsSource {\n indexerProvider: string;\n}\n\nexport interface NativeEventsResponse<TDecoded = unknown> {\n schemaVersion: number;\n fromBlock: number;\n toBlock: number;\n limit: number;\n filters: NativeEventsResponseFilters;\n events: Array<NativeReceiptEvent<TDecoded>>;\n source: NativeEventsSource;\n}\n\n/** Filter object passed to `lyth_nativeAgentState` and `/api/v1/native-agent-state`. */\nexport interface NativeAgentStateFilter {\n policyId?: string | null;\n escrowId?: string | null;\n account?: string | null;\n includePolicySpends?: boolean | null;\n limit?: number | bigint | string | null;\n}\n\nexport interface NativeAgentStateResponseFilters {\n policyId?: string | null;\n escrowId?: string | null;\n account?: string | null;\n includePolicySpends: boolean;\n}\n\nexport interface NativeAgentStateSource {\n indexerProvider: string;\n projection: string;\n}\n\nexport interface NativeAgentPolicyStateRecord {\n policyId: string;\n owner: string;\n controller: string;\n assetId: string;\n /** Owner/controller-local policy nonce; omitted by older nodes. */\n nonce?: number | null;\n enabled: boolean;\n perActionLimit: string;\n windowLimit: string;\n windowSecs: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentPolicySpendStateRecord {\n policyId: string;\n controller: string;\n assetId: string;\n window: number;\n amount: string;\n spent: string;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentEscrowStateRecord {\n escrowId: string;\n buyer: string;\n provider: string;\n arbiter: string;\n assetId: string;\n /** Buyer-local escrow nonce; omitted by older nodes. */\n nonce?: number | null;\n amount: string;\n termsHash: string;\n round: number;\n buyerAccepted: boolean;\n providerAccepted: boolean;\n submittedPayloadHash?: string | null;\n status: string;\n resolution?: string | null;\n lastActor?: string | null;\n createdAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentIssuerStateRecord {\n issuerId: string;\n issuer: string;\n /** Issuer-local nonce; omitted by older nodes. */\n nonce?: number | null;\n metadataHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentAttestationStateRecord {\n attestationId: string;\n /** Issuer-local attestation nonce; omitted by older nodes. */\n nonce?: number | null;\n issuerId?: string | null;\n issuer?: string | null;\n subject: string;\n schemaHash?: string | null;\n payloadHash?: string | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentConsentStateRecord {\n consentId: string;\n subject: string;\n grantee: string;\n /** Subject-local consent nonce; omitted by older nodes. */\n nonce?: number | null;\n scopeHash?: string | null;\n expiresAt?: number | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentServiceStateRecord {\n serviceId: string;\n provider: string;\n /** Provider-local service nonce; omitted by older nodes. */\n nonce?: number | null;\n categoryHash?: string | null;\n metadataHash?: string | null;\n active: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentAvailabilityStateRecord {\n provider: string;\n maxConcurrent: number;\n openRequests: number;\n paused: boolean;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentArbiterStateRecord {\n arbiterId: string;\n arbiter: string;\n /** Arbiter-local registration nonce; omitted by older nodes. */\n nonce?: number | null;\n tier?: number | null;\n metadataHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentReputationReviewStateRecord {\n reviewId: string;\n reviewer: string;\n subject: string;\n categoryId: number;\n speedScore: number;\n qualityScore: number;\n communicationScore: number;\n accuracyScore: number;\n payloadHash?: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeAgentStateResponse {\n schemaVersion: number;\n limit: number;\n filters: NativeAgentStateResponseFilters;\n issuers: NativeAgentIssuerStateRecord[];\n attestations: NativeAgentAttestationStateRecord[];\n consents: NativeAgentConsentStateRecord[];\n services: NativeAgentServiceStateRecord[];\n availability: NativeAgentAvailabilityStateRecord[];\n arbiters: NativeAgentArbiterStateRecord[];\n reputationReviews: NativeAgentReputationReviewStateRecord[];\n spendingPolicies: NativeAgentPolicyStateRecord[];\n policySpends: NativeAgentPolicySpendStateRecord[];\n escrows: NativeAgentEscrowStateRecord[];\n source: NativeAgentStateSource;\n}\n\nexport type NativeAgentStateFilterParamValue = string | number | boolean;\n\n/** Filter object passed to `lyth_nativeMarketState` and `/api/v1/native-market-state`. */\nexport interface NativeMarketStateFilter {\n marketId?: string | null;\n orderId?: string | null;\n listingId?: string | null;\n collectionId?: string | null;\n account?: string | null;\n includeSpotOrders?: boolean | null;\n limit?: number | bigint | string | null;\n}\n\nexport interface NativeMarketStateResponseFilters {\n marketId?: string | null;\n orderId?: string | null;\n listingId?: string | null;\n collectionId?: string | null;\n account?: string | null;\n includeSpotOrders: boolean;\n}\n\nexport interface NativeMarketStateSource {\n indexerProvider: string;\n projection: string;\n}\n\nexport interface NativeSpotMarketStateRecord {\n marketId: string;\n owner: string;\n baseAssetId: string;\n quoteAssetId: string;\n tickSize: string;\n lotSize: string;\n minQuantity: string;\n minNotional: string;\n tradeCount: string;\n totalVolumeBase: string;\n lastPrice: string | null;\n lastBlockHeight: number | null;\n createdAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeSpotOrderStateRecord {\n orderId: string;\n marketId: string;\n owner: string;\n /** Owner-local spot order nonce; omitted by older nodes. */\n nonce?: number | null;\n side: string;\n price: string;\n quantity: string;\n remaining: string;\n status: string;\n expiresAtBlock: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeNftListingStateRecord {\n listingId: string;\n seller: string;\n /** Seller-local NFT listing nonce; omitted by older nodes. */\n nonce?: number | null;\n standard: string;\n collectionId: string;\n tokenId: string;\n quantity: string;\n paymentAssetId: string;\n price: string;\n listingKind: unknown;\n status: string;\n expiresAtBlock: number;\n highestBidder: string | null;\n highestBid: string | null;\n updatedAtBlock: number;\n}\n\nexport interface NativeCollectionRoyaltyStateRecord {\n collectionId: string;\n creator: string | null;\n recipient: string;\n bps: number;\n updatedAtBlock: number;\n}\n\nexport interface NativeMarketStateResponse {\n schemaVersion: number;\n limit: number;\n filters: NativeMarketStateResponseFilters;\n spotMarkets: NativeSpotMarketStateRecord[];\n spotOrders: NativeSpotOrderStateRecord[];\n nftListings: NativeNftListingStateRecord[];\n collectionRoyalties: NativeCollectionRoyaltyStateRecord[];\n source: NativeMarketStateSource;\n}\n\nexport type NativeMarketStateFilterParamValue = string | number | boolean;\n\nexport type AgentReputationCategoryScope = \"global\" | \"category\";\n\nexport interface AgentReputationRecord {\n provider: string;\n categoryId: number;\n blockHeight: number;\n speedSumX10: number;\n qualitySumX10: number;\n communicationSumX10: number;\n accuracySumX10: number;\n sampleCount: number;\n avgSpeedX10: number;\n avgQualityX10: number;\n avgCommunicationX10: number;\n avgAccuracyX10: number;\n}\n\nexport interface AgentReputationResponse {\n schemaVersion: 1;\n provider: string;\n categoryId: number;\n categoryScope: AgentReputationCategoryScope;\n record: AgentReputationRecord | null;\n}\n\nexport interface AddressProfileResponse {\n schemaVersion: number;\n address: string;\n account: {\n nativeBalance: string;\n nonce: number;\n codeHash: string;\n isContract: boolean;\n };\n label: {\n category: string;\n displayName: string | null;\n updatedAtBlock: number;\n } | null;\n activity: {\n kind: string;\n retention: unknown | null;\n latest: unknown | null;\n };\n tokenBalances: Array<{\n tokenId: string;\n balance: string;\n updatedAtBlock: number;\n mrc?: TokenBalanceMrcIdentity | null;\n }>;\n bridgeRouteDisclosures?: BridgeRouteDisclosure[] | null;\n}\n\nexport interface AddressFlowResponse {\n schemaVersion: number;\n address: string;\n sampleSize: number;\n limit: number;\n totals: {\n inbound: string;\n outbound: string;\n swapVolume: string;\n stake: string;\n unstake: string;\n };\n topCounterparties: Array<{\n address: string;\n eventCount: number;\n inbound: string;\n outbound: string;\n }>;\n}\n\nexport interface SearchHit {\n type: string;\n id: string;\n route: string;\n label: string;\n score: number;\n meta?: unknown;\n}\n\nexport interface SearchResponse {\n schemaVersion: number;\n query: string;\n hits: SearchHit[];\n nextCursor: string | null;\n}\n\nexport interface ChainStatsResponse {\n schemaVersion: number;\n chainId: number;\n genesisHash: string | null;\n latestHeight: number;\n latestBlockHash: string | null;\n latestTimestamp: number | null;\n peerCount: number;\n mempool: {\n ready: number;\n pending: number;\n mailboxDepth: number;\n };\n indexer: unknown | null;\n clusters: {\n total: number;\n pageSize: number;\n };\n}\n\nexport interface ClobMarketSummary {\n marketId: string;\n tradeCount: number;\n totalVolumeBase: string;\n lastPrice: string;\n lastBlockHeight: number;\n}\n\nexport interface ClobMarketsResponse {\n schemaVersion: number;\n limit: number;\n markets: ClobMarketSummary[];\n source: string;\n}\n\nexport interface ClobTrade {\n blockHeight: number;\n txIndex: number;\n logIndex: number;\n marketId: string;\n takerOrder: string;\n makerOrder: string;\n price: string;\n amount: string;\n taker: string;\n maker: string;\n}\n\nexport interface ClobTradesResponse {\n schemaVersion: number;\n marketId: string;\n limit: number;\n nextCursor: string | null;\n trades: ClobTrade[];\n}\n\nexport interface ClobOhlcResponse {\n schemaVersion: number;\n marketId: string;\n fromBlock: number;\n toBlock: number;\n bucketBlocks: number;\n candles: Array<{\n startBlock: number;\n endBlock: number;\n open: string;\n high: string;\n low: string;\n close: string;\n volumeBase: string;\n tradeCount: number;\n }>;\n}\n\nexport interface ClobOrderBookResponse {\n schemaVersion: number;\n marketId: string;\n levels?: number;\n bids: Array<{ price: string; size: string }>;\n asks: Array<{ price: string; size: string }>;\n}\n\n/** Public-safe aggregate returned by `lyth_peerSummary`. */\nexport interface PeerSummaryAggregate {\n peerCount: number;\n inboundCount: number | null;\n outboundCount: number | null;\n latencyBands: {\n lt_50ms: number;\n lt_200ms: number;\n lt_1s: number;\n ge_1s: number;\n } | null;\n versionDistribution: Record<string, number>;\n healthSummary: {\n synced: number;\n lagging: number;\n stale: number;\n };\n asOfBlock: number;\n}\n\n/** Live `lyth_listActivePrecompiles` response envelope. */\nexport interface PrecompileCatalogueResponse {\n /** Block height sampled by the node. */\n blockNumber: bigint;\n /** Precompile descriptors active or known at the sampled block. */\n precompiles: PrecompileDescriptor[];\n}\n\nexport interface OperatorInfoResponse {\n operatorId: string;\n moniker: string | null;\n alias: string | null;\n chainAddress: string;\n bonded: boolean;\n commissionBps: number | null;\n delegationCount: number | null;\n bondedAmount: string;\n activeClusterIds: number[];\n operatorKeyFingerprint: string | null;\n blsKeyFingerprint: string | null;\n lifecycleState: string;\n capability: Record<string, unknown>;\n}\n\nexport interface ClusterMemberResponse {\n operatorId: string;\n blsPubkey: string;\n state: string;\n}\n\nexport interface ClusterStatusResponse {\n clusterId: number;\n threshold: number;\n size: number;\n live: number;\n lagging: number;\n offline: number;\n maintenance: number;\n members: ClusterMemberResponse[];\n epoch: bigint | null;\n round: bigint | null;\n quorum: string;\n reputationScore: number | null;\n livenessScore: number | null;\n lastUpdateHeight: bigint;\n}\n\nexport interface ClusterDirectoryEntryResponse {\n clusterId: number;\n size: number;\n threshold: number;\n aggregateHealth: string;\n regionDiversity: string[] | null;\n active: boolean;\n}\n\nexport interface ClusterDirectoryPageResponse {\n page: number;\n limit: number;\n totalClusters: number;\n clusters: ClusterDirectoryEntryResponse[];\n}\n\nexport type OperatorSurfaceStatus =\n | \"available\"\n | \"disabled\"\n | \"not_implemented\"\n | \"not_retained\"\n | \"ws_only\"\n | string;\n\nexport interface OperatorSurfaceCapability {\n status: OperatorSurfaceStatus;\n tracking?: string;\n}\n\nexport interface OperatorCapabilitiesResponse {\n schemaVersion: number;\n surfaces: Record<string, OperatorSurfaceCapability>;\n}\n\nexport interface OperatorAuthorityResponse {\n schemaVersion: number;\n operatorId: string;\n authorityIndex: number;\n blsPubkey: string;\n active: boolean;\n}\n\nexport type SigningEntryStatus = \"signed\" | \"missed\" | \"no_cert\" | string;\n\nexport interface OperatorSigningEntry {\n round: bigint;\n status: SigningEntryStatus;\n}\n\nexport interface OperatorSigningActivityResponse {\n schemaVersion: number;\n authorityIndex: number;\n currentRound: bigint;\n limit: number;\n entries: OperatorSigningEntry[];\n}\n\nexport interface AttestationWindow {\n startRound: bigint;\n endRound: bigint;\n kind: string;\n}\n\nexport interface DutyAbsence {\n reason: string;\n}\n\nexport type KeyRotationWindow =\n | { nextRound: bigint; epochLengthRounds: bigint }\n | DutyAbsence;\n\nexport interface UpcomingDutyMap {\n attestation: AttestationWindow;\n blockProduction: DutyAbsence;\n sync: DutyAbsence;\n keyRotation: KeyRotationWindow;\n}\n\nexport interface UpcomingDutiesResponse {\n schemaVersion: number;\n authorityIndex: number;\n currentRound: bigint;\n horizonRounds: number;\n duties: UpcomingDutyMap;\n}\n\nexport type JailStatusWindow =\n | {\n jailed: boolean;\n tombstoned: boolean;\n jailedUntilHeight: bigint;\n unjailCount: bigint;\n }\n | DutyAbsence;\n\nexport interface OperatorRiskResponse {\n schemaVersion: number;\n authorityIndex: number;\n dataHeight: bigint;\n windowRounds: number;\n missedRounds: number;\n observedRounds: number;\n missRateBps: number;\n thresholdBps: number;\n remainingHeadroomBps: number;\n jailStatus: JailStatusWindow;\n reasons: string[];\n}\n\nexport interface LythUpgradePlanStatus {\n upgradeId: string;\n activationHeight: number;\n activationRound: number | null;\n requiredBinaryVersion: string;\n expectedBinaryDigest: string;\n p2pProtocolVersion: number;\n requiredFeatures: string[];\n milestoneFileDigest: string | null;\n stateMigrationId: string | null;\n stateMigrationHash: string | null;\n expectedPreStateRoot: string | null;\n expectedPostStateRoot: string | null;\n}\n\nexport interface LythUpgradeStatusResponse {\n chainId: number;\n blockNumber: number;\n configured: boolean;\n planCount: number;\n state: \"active\" | \"none\" | \"pending\" | string;\n active: LythUpgradePlanStatus | null;\n pendingCount: number;\n pending: LythUpgradePlanStatus[];\n}\n\nexport interface RuntimeBuildProvenance {\n clientName: string;\n version: string;\n gitCommit: string;\n gitDirty: boolean;\n buildTimestampUtc: number;\n rustc: string;\n target: string;\n profile: string;\n features: string;\n p2pProtocolVersion: number;\n binarySha256: string | null;\n stateMigrations: string[];\n}\n\nexport interface RuntimeUpgradeStatus {\n blockNumber: number;\n configured: boolean;\n planCount: number;\n state: \"active\" | \"none\" | \"pending\" | string;\n active: LythUpgradePlanStatus | null;\n pending: LythUpgradePlanStatus[];\n}\n\nexport interface RuntimeProvenanceResponse {\n schemaVersion: number;\n chainId: number;\n genesisHash: string | null;\n latestHeight: number;\n runtime: RuntimeBuildProvenance;\n upgrade: RuntimeUpgradeStatus | null;\n}\n\nexport type ServiceProbeStatusLabel =\n | \"unknown\"\n | \"reachable\"\n | \"degraded\"\n | \"unreachable\"\n | string;\n\nexport interface ServiceProbeResponse {\n serviceMask: number;\n status: ServiceProbeStatusLabel;\n statusCode: number;\n lastProbeBlock: number;\n latencyMs: number;\n probeDigest: string;\n reporter: string;\n}\n\nexport interface ReportServiceProbeRequest {\n peerId: string;\n serviceMask: number;\n status: number;\n latencyMs: number;\n probeDigest: string;\n signedRawTx: string;\n}\n\nexport interface ReportServiceProbeResponse {\n txHash: string;\n peerId: string;\n serviceMask: number;\n statusCode: number;\n}\n\nexport type TxStatusResponse = TxStatusFoundResponse | TxStatusNotFoundResponse;\n\nexport interface TxStatusFoundResponse {\n status: \"found\";\n txHash: string;\n blockHash: string;\n blockNumber: number;\n txIndex: number;\n}\n\nexport interface TxStatusNotFoundResponse {\n status: \"not_found\";\n txHash: string;\n latestHeight: number;\n indexerEnabled: boolean;\n providerKind: string;\n}\n\nexport interface VertexAtRound {\n vertexHash: string;\n author: number;\n}\n\nexport interface VerticesAtRoundResponse {\n schemaVersion: number;\n round: number;\n vertices: VertexAtRound[] | null;\n}\n\nexport type MetricsRangeStatus = \"available\" | \"not_retained\" | \"unknown\" | string;\n\nexport interface MetricsRangeSample {\n blockNumber: number;\n value: number;\n}\n\nexport interface MetricsRangeSeries {\n selector: string;\n status: MetricsRangeStatus;\n unit: string | null;\n samples: MetricsRangeSample[] | null;\n}\n\nexport interface MetricsRangeResponse {\n schemaVersion: number;\n range: [number, number] | null;\n tracking: string;\n series: MetricsRangeSeries[];\n}\n\nexport type AddressActivityKind =\n | \"found\"\n | \"not_found\"\n | \"indexer_disabled\"\n | \"pruned\"\n | \"private\"\n | string;\n\ninterface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id: number;\n method: string;\n params: unknown;\n}\n\ninterface JsonRpcResponse {\n jsonrpc?: \"2.0\";\n id?: number;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst SDK_VERSION = \"0.1.0\";\nconst ETH_COMPAT_RPC_PREFIX = \"eth_\";\nconst ethCompatMethod = (name: string): string => `${ETH_COMPAT_RPC_PREFIX}${name}`;\n\nfunction resolveChainInfo(network: NetworkSlug | string, registry?: ChainRegistry): ChainInfo {\n if (registry) {\n const info = registry[network];\n if (!info) {\n throw SdkError.endpoint(`unknown Monolythium network: ${network}`);\n }\n return info;\n }\n try {\n return getChainInfo(network);\n } catch (err) {\n throw SdkError.endpoint((err as Error)?.message ?? String(err));\n }\n}\n\nexport class RpcClient {\n readonly endpoint: string;\n readonly #fetch: typeof fetch;\n readonly #headers: Record<string, string>;\n #nextId: number;\n\n constructor(endpoint: string, options: RpcClientOptions = {}) {\n if (!endpoint || endpoint.length === 0) {\n throw SdkError.endpoint(\"endpoint cannot be empty\");\n }\n this.endpoint = endpoint;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#headers = {\n \"content-type\": \"application/json\",\n \"user-agent\": `monolythium-core-sdk/${SDK_VERSION}`,\n ...(options.headers ?? {}),\n };\n this.#nextId = 1;\n }\n\n /**\n * Construct a client from the chain-registry network slug.\n *\n * Defaults to the SDK-bundled registry snapshot from\n * `monolythium/chain-registry`. Set `probe: true` to walk the\n * registry endpoints in order and return the first endpoint whose\n * `eth_chainId` matches the registry chain id.\n */\n static async forNetwork(\n network: NetworkSlug | string = \"testnet-69420\",\n options: NetworkClientOptions = {},\n ): Promise<RpcClient> {\n const info = resolveChainInfo(network, options.registry);\n if (info.rpc.length === 0) {\n throw SdkError.endpoint(`network ${network} has no RPC endpoints`);\n }\n if (options.probe) {\n return this.fromFirstReachable(info, options);\n }\n return new RpcClient(info.rpc[0].url, options);\n }\n\n /**\n * Walk a chain-registry entry in order and return the first endpoint\n * whose `eth_chainId` matches the registry `chain_id`.\n */\n static async fromFirstReachable(\n chain: ChainInfo,\n options: RpcClientOptions = {},\n ): Promise<RpcClient> {\n const errors: string[] = [];\n for (const endpoint of chain.rpc) {\n const client = new RpcClient(endpoint.url, options);\n try {\n const chainId = await client.ethChainId();\n if (chainId === BigInt(chain.chain_id)) {\n return client;\n }\n errors.push(`${endpoint.url}: chain id ${chainId} != ${chain.chain_id}`);\n } catch (err) {\n errors.push(`${endpoint.url}: ${(err as Error)?.message ?? err}`);\n }\n }\n throw SdkError.endpoint(\n `no reachable RPC endpoint for ${chain.network}; tried ${errors.join(\"; \")}`,\n );\n }\n\n /**\n * Send an arbitrary JSON-RPC method. Most callers should prefer the\n * typed wrappers below; this is the escape hatch for methods the\n * SDK does not yet wrap.\n */\n async call<T>(method: string, params: unknown = []): Promise<T> {\n const id = this.#nextId++;\n const body: JsonRpcRequest = { jsonrpc: \"2.0\", id, method, params };\n let resp: Response;\n try {\n resp = await this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: this.#headers,\n body: JSON.stringify(body),\n });\n } catch (cause) {\n throw SdkError.transport(\n `transport failure calling ${method}: ${(cause as Error)?.message ?? cause}`,\n cause,\n );\n }\n let parsed: JsonRpcResponse;\n try {\n parsed = (await resp.json()) as JsonRpcResponse;\n } catch (cause) {\n throw SdkError.malformed(\n `non-JSON response (HTTP ${resp.status}): ${(cause as Error)?.message ?? cause}`,\n );\n }\n if (parsed.error) {\n throw SdkError.rpc(parsed.error.code, parsed.error.message, parsed.error.data);\n }\n if (!(\"result\" in parsed) || parsed.result === undefined) {\n if (!resp.ok) {\n throw SdkError.malformed(`HTTP ${resp.status} with no JSON-RPC result`);\n }\n throw SdkError.malformed(\"response is missing both `result` and `error`\");\n }\n return parsed.result as T;\n }\n\n // ---- eth_* / net_* / web3_* ---------------------------------------\n\n /** `eth_chainId` — configured chain id. */\n async ethChainId(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"eth_chainId\", []));\n }\n\n /** Compatibility block-height read. */\n async ethBlockNumber(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(ethCompatMethod(\"blockNumber\"), []));\n }\n\n /** `eth_getBalance` — balance + Merkle proof envelope. */\n async ethGetBalance(\n address: string,\n block: BlockSelector = \"latest\",\n ): Promise<AccountProofResponse> {\n return this.call(\"eth_getBalance\", [address, encodeBlockSelector(block)]);\n }\n\n /** `eth_getStorageAt` — storage word + Merkle proof. */\n async ethGetStorageAt(\n address: string,\n slot: string,\n block: BlockSelector = \"latest\",\n ): Promise<AccountProofResponse> {\n return this.call(\"eth_getStorageAt\", [\n address,\n slot,\n encodeBlockSelector(block),\n ]);\n }\n\n /** `eth_getTransactionCount` — sender nonce. */\n async ethGetTransactionCount(\n address: string,\n block: BlockSelector = \"latest\",\n ): Promise<bigint> {\n return parseQuantityBig(\n await this.call<string>(\"eth_getTransactionCount\", [\n address,\n encodeBlockSelector(block),\n ]),\n );\n }\n\n /** `eth_getCode` — deployed bytecode (`0x` for an EOA, `0xfe` for a precompile). */\n async ethGetCode(address: string, block: BlockSelector = \"latest\"): Promise<string> {\n return this.call(\"eth_getCode\", [address, encodeBlockSelector(block)]);\n }\n\n /** Compatibility block-header read by height/tag. */\n async ethGetBlockByNumber(\n block: BlockSelector = \"latest\",\n ): Promise<BlockHeader | null> {\n return normalizeBlockHeader(await this.call(ethCompatMethod(\"getBlockByNumber\"), [encodeBlockSelector(block)]));\n }\n\n /** Compatibility block-header read by hash. */\n async ethGetBlockByHash(hash: string): Promise<BlockHeader | null> {\n return normalizeBlockHeader(await this.call(ethCompatMethod(\"getBlockByHash\"), [hash]));\n }\n\n /** `eth_getTransactionByHash` — fetch an included transaction by hash. */\n async ethGetTransactionByHash(txHash: string): Promise<TransactionView | null> {\n return this.call(\"eth_getTransactionByHash\", [txHash]);\n }\n\n /** `eth_getTransactionReceipt` — receipt for a confirmed tx. */\n async ethGetTransactionReceipt(txHash: string): Promise<TransactionReceipt | null> {\n return normalizeTransactionReceipt(await this.call(\"eth_getTransactionReceipt\", [txHash]));\n }\n\n /** `eth_sendRawTransaction` — submit a signed raw tx. */\n async ethSendRawTransaction(rawTx: string): Promise<string> {\n return this.call(\"eth_sendRawTransaction\", [rawTx]);\n }\n\n /** `eth_call` — dry-run a transaction. */\n async ethCall(request: CallRequest, block: BlockSelector = \"latest\"): Promise<string> {\n return this.call(\"eth_call\", [request, encodeBlockSelector(block)]);\n }\n\n /** `eth_estimateGas` — gas estimate for a dry-run. */\n async ethEstimateGas(\n request: CallRequest,\n block: BlockSelector = \"latest\",\n ): Promise<bigint> {\n return parseQuantityBig(\n await this.call<string>(\"eth_estimateGas\", [request, encodeBlockSelector(block)]),\n );\n }\n\n /**\n * `eth_gasPrice` — legacy compatibility fee quote for ethers/viem shims.\n * Native v4.1 surfaces should use execution-unit and lythoshi fee fields.\n */\n async ethGasPrice(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"eth_gasPrice\", []));\n }\n\n /** `eth_feeHistory` — base-fee + gas-used history. */\n async ethFeeHistory(\n blockCount: number,\n newestBlock: BlockSelector = \"latest\",\n rewardPercentiles: number[] = [],\n ): Promise<FeeHistoryResponse> {\n return this.call(\"eth_feeHistory\", [\n `0x${blockCount.toString(16)}`,\n encodeBlockSelector(newestBlock),\n rewardPercentiles,\n ]);\n }\n\n /** `eth_syncing` — `null` when caught up. */\n async ethSyncing(): Promise<SyncStatus | null> {\n const v = await this.call<unknown>(\"eth_syncing\", []);\n if (v === false || v === null || v === undefined) return null;\n return v as SyncStatus;\n }\n\n /** `net_version` — chain id as a decimal string. */\n async netVersion(): Promise<string> {\n return this.call(\"net_version\", []);\n }\n\n /** `net_peerCount` — number of connected peers. */\n async netPeerCount(): Promise<bigint> {\n return parseQuantityBig(await this.call<string>(\"net_peerCount\", []));\n }\n\n /** `net_listening` — whether the node accepts inbound peers. */\n async netListening(): Promise<boolean> {\n return this.call(\"net_listening\", []);\n }\n\n /** `web3_clientVersion` — server's client-version string. */\n async web3ClientVersion(): Promise<string> {\n return this.call(\"web3_clientVersion\", []);\n }\n\n /** `web3_sha3` — Keccak-256 of `data`. */\n async web3Sha3(data: string): Promise<string> {\n return this.call(\"web3_sha3\", [data]);\n }\n\n // ---- lyth_* native namespace --------------------------------------\n\n /** `lyth_listProviders` — paged registry enumeration. */\n async lythListProviders(\n capabilityMask: number,\n cursor: string | null = null,\n limit = 100,\n ): Promise<RegistryRecord[]> {\n return this.call(\"lyth_listProviders\", [capabilityMask, cursor, limit]);\n }\n\n /** `lyth_getRegistration` — single registry lookup. */\n async lythGetRegistration(peerId: string): Promise<RegistryRecord | null> {\n return this.call(\"lyth_getRegistration\", [peerId]);\n }\n\n /** `lyth_registryStateProof` — Merkle proof for a registry entry. */\n async lythRegistryStateProof(peerId: string): Promise<AccountProofResponse> {\n return this.call(\"lyth_registryStateProof\", [peerId]);\n }\n\n /** `lyth_getAccountPolicy` — privacy posture for an account. */\n async lythGetAccountPolicy(address: string): Promise<AccountPolicy> {\n return this.call(\"lyth_getAccountPolicy\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_getAssetPolicy` — privacy posture for an asset. */\n async lythGetAssetPolicy(tokenId: string): Promise<AssetPolicy> {\n return this.call(\"lyth_getAssetPolicy\", [tokenId]);\n }\n\n /** `lyth_getTokenBalances` — indexed per-asset balances for one address. */\n async lythGetTokenBalances(address: string): Promise<TokenBalanceRecord[]> {\n return this.call(\"lyth_getTokenBalances\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_bridgeRoutes` — read-only bridge route-selection/readiness. */\n async lythBridgeRoutes(request: BridgeRoutesRequest): Promise<BridgeRoutesResponse> {\n return this.call(\"lyth_bridgeRoutes\", [request]);\n }\n\n /** `lyth_mrcMetadata` — exact current-state native MRC metadata lookup. */\n async lythMrcMetadata(\n assetId: string,\n tokenId?: string | null,\n ): Promise<MrcMetadataResponse> {\n const params = tokenId == null ? [assetId] : [assetId, tokenId];\n return this.call(\"lyth_mrcMetadata\", params);\n }\n\n /** `lyth_mrcAccount` — exact current-state native MRC account lookup. */\n async lythMrcAccount(\n account: string,\n spendLimit?: number | null,\n ): Promise<MrcAccountResponse> {\n const request: MrcAccountRequest = {\n account: sdkTypedAddress(account, \"smartAccount\", \"account\"),\n };\n if (spendLimit != null) request.spendLimit = spendLimit;\n const params =\n request.spendLimit == null\n ? [request.account]\n : [request.account, request.spendLimit];\n return this.call(\"lyth_mrcAccount\", params);\n }\n\n /** `lyth_mrcHolders` — top holders for a native MRC asset/token key. */\n async lythMrcHolders(\n standard: string,\n assetId: string,\n tokenId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcHoldersScoped(standard, assetId, tokenId, limit);\n }\n\n /**\n * `lyth_mrcHolders` — top holders for a native MRC asset/vault key.\n *\n * This is the asset-scoped form used by MRC-4626 vault share balances.\n */\n async lythMrcAssetHolders(\n standard: string,\n assetId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcHoldersScoped(standard, assetId, null, limit);\n }\n\n /** `lyth_mrcHolders` — top holders for MRC-4626 vault shares. */\n async lythMrc4626Holders(\n vaultId: string,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n return this.lythMrcAssetHolders(\"mrc4626\", vaultId, limit);\n }\n\n private async lythMrcHoldersScoped(\n standard: string,\n assetId: string,\n tokenId: string | null,\n limit?: number | null,\n ): Promise<MrcHoldersResponse> {\n const request: MrcHoldersRequest = {\n standard,\n assetId,\n tokenId,\n };\n if (limit != null) request.limit = limit;\n const params =\n request.limit == null\n ? [request.standard, request.assetId, request.tokenId]\n : [request.standard, request.assetId, request.tokenId, request.limit];\n return this.call(\"lyth_mrcHolders\", params);\n }\n\n /** `lyth_getAddressLabel` — indexed display/category label for one address. */\n async lythGetAddressLabel(address: string): Promise<AddressLabelRecord | null> {\n const v = await this.call<unknown>(\"lyth_getAddressLabel\", [\n sdkTypedAddress(address, \"user\", \"address\"),\n ]);\n if (v === null || v === undefined) return null;\n return v as AddressLabelRecord;\n }\n\n /** `lyth_getAddressActivity` — indexed per-address activity timeline. */\n async lythGetAddressActivity(\n address: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<AddressActivityEntry[]> {\n const userAddress = sdkTypedAddress(address, \"user\", \"address\");\n const params = cursor === undefined ? [userAddress, limit] : [userAddress, limit, cursor];\n return this.call(\"lyth_getAddressActivity\", params);\n }\n\n /** `lyth_addressActivityKind` — activity index coverage for one address. */\n async lythAddressActivityKind(address: string): Promise<AddressActivityKindResponse> {\n return this.call(\"lyth_addressActivityKind\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_agentReputation` — reputation accumulators for an agent provider. */\n async lythAgentReputation(\n provider: UserAddressInput,\n categoryId = 0,\n ): Promise<AgentReputationResponse> {\n return this.call(\"lyth_agentReputation\", [\n sdkTypedAddress(provider, \"user\", \"provider address\"),\n categoryId,\n ]);\n }\n\n /** `lyth_decodeTx` — explorer-grade decoded transaction envelope. */\n async lythDecodeTx(txHash: string): Promise<DecodeTxResponse> {\n return this.call(\"lyth_decodeTx\", [txHash]);\n }\n\n /** `lyth_nativeReceipt` — native RISC-V receipt metadata and typed native event rows. */\n async lythNativeReceipt<TDecoded = unknown>(\n txHash: string,\n ): Promise<NativeReceiptResponse<TDecoded>> {\n return decodeNativeReceiptResponse<TDecoded>(\n await this.call<unknown>(\"lyth_nativeReceipt\", [txHash]),\n );\n }\n\n /**\n * Typed native event rows from `lyth_nativeReceipt`.\n *\n * This helper intentionally consumes the existing receipt RPC surface;\n * it does not require a separate `lyth_nativeEvents` node method.\n */\n async lythNativeReceiptEvents<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n txHash: string,\n filter: NativeEventFilter = {},\n ): Promise<Array<TypedNativeReceiptEvent<TDecoded>>> {\n const receipt = await this.lythNativeReceipt(txHash);\n return nativeEventsFromReceipt<TDecoded>(receipt, filter);\n }\n\n /** Typed native market event rows from `lyth_nativeReceipt`. */\n async lythNativeReceiptMarketEvents<TDecoded extends NativeDecodedEvent = NativeDecodedEvent>(\n txHash: string,\n filter: NativeEventFilter = {},\n ): Promise<Array<TypedNativeReceiptEvent<TDecoded>>> {\n const receipt = await this.lythNativeReceipt(txHash);\n return nativeMarketEventsFromReceipt<TDecoded>(receipt, filter);\n }\n\n /** `lyth_nativeEvents` — historical indexed native event rows. */\n async lythNativeEvents<TDecoded = unknown>(\n filter: NativeEventsFilter,\n ): Promise<NativeEventsResponse<TDecoded>> {\n return this.call(\"lyth_nativeEvents\", [nativeEventsFilterParams(filter)]);\n }\n\n /** `lyth_nativeEvents` with decoded rows converted into a caller-selected type. */\n async lythNativeEventsTyped<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n >(filter: NativeEventsFilter): Promise<NativeEventsResponse<TDecoded>> {\n const response = await this.lythNativeEvents(filter);\n return nativeEventsFromHistory<TDecoded>(response);\n }\n\n /** `lyth_nativeEvents` restricted to native marketplace event rows. */\n async lythNativeMarketEvents<TDecoded = unknown>(\n filter: NativeEventsFilter,\n ): Promise<NativeEventsResponse<TDecoded>> {\n return this.lythNativeEvents<TDecoded>({\n ...filter,\n family: \"market\",\n });\n }\n\n /** `lyth_nativeEvents` market rows with decoded rows converted into a caller-selected type. */\n async lythNativeMarketEventsTyped<\n TDecoded extends NativeDecodedEvent = NativeDecodedEvent,\n >(filter: NativeEventsFilter): Promise<NativeEventsResponse<TDecoded>> {\n const response = await this.lythNativeEvents({\n ...filter,\n family: \"market\",\n });\n return nativeMarketEventsFromHistory<TDecoded>(response);\n }\n\n /** `lyth_nativeAgentState` — current-state native agent policy and escrow rows. */\n async lythNativeAgentState(\n filter: NativeAgentStateFilter = {},\n ): Promise<NativeAgentStateResponse> {\n const response = await this.call(\"lyth_nativeAgentState\", [\n nativeAgentStateFilterParams(filter),\n ]);\n return decodeNativeAgentStateResponse(response);\n }\n\n /** `lyth_nativeMarketState` — current-state native spot and NFT market rows. */\n async lythNativeMarketState(\n filter: NativeMarketStateFilter = {},\n ): Promise<NativeMarketStateResponse> {\n return this.call(\"lyth_nativeMarketState\", [nativeMarketStateFilterParams(filter)]);\n }\n\n /** `lyth_gapRecords` — retained ingestion/indexing gaps for a block range. */\n async lythGapRecords(\n fromBlock: number | bigint | string,\n toBlock: number | bigint | string,\n ): Promise<GapRecordsResponse> {\n return this.call(\"lyth_gapRecords\", [\n encodeRpcU64Number(fromBlock, \"fromBlock\"),\n encodeRpcU64Number(toBlock, \"toBlock\"),\n ]);\n }\n\n /** `lyth_dagParents` — parent vertices for a DAG round. */\n async lythDagParents(round: number | bigint | string): Promise<DagParentsResponse> {\n return this.call(\"lyth_dagParents\", [encodeRpcU64Number(round, \"round\")]);\n }\n\n /** `lyth_richList` — top holders for a token id. */\n async lythRichList(tokenId: string, limit?: number | null): Promise<RichListResponse> {\n const params = limit == null ? [tokenId] : [tokenId, limit];\n return this.call(\"lyth_richList\", params);\n }\n\n /** `lyth_clobMarket` — live CLOB market metadata for a market id. */\n async lythClobMarket(marketId: string): Promise<ClobMarketResponse> {\n return this.call(\"lyth_clobMarket\", [marketId]);\n }\n\n /** `lyth_clobMarkets` — CLOB markets observed through indexed trades. */\n async lythClobMarkets(limit?: number | null): Promise<ClobMarketsResponse> {\n const params = limit == null ? [] : [limit];\n return this.call(\"lyth_clobMarkets\", params);\n }\n\n /** `lyth_clobTrades` — CLOB fills for one market. */\n async lythClobTrades(\n marketId: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<ClobTradesResponse> {\n const params = cursor === undefined ? [marketId, limit] : [marketId, limit, cursor];\n return this.call(\"lyth_clobTrades\", params);\n }\n\n /** `lyth_clobOhlc` — CLOB OHLC candles for a market over a block range. */\n async lythClobOhlc(\n marketId: string,\n fromBlock?: number | bigint | string | null,\n toBlock?: number | bigint | string | null,\n bucketBlocks?: number | bigint | string | null,\n ): Promise<ClobOhlcResponse> {\n const params =\n fromBlock == null && toBlock == null && bucketBlocks == null\n ? [marketId]\n : [\n marketId,\n fromBlock == null ? null : encodeRpcU64Number(fromBlock, \"fromBlock\"),\n toBlock == null ? null : encodeRpcU64Number(toBlock, \"toBlock\"),\n bucketBlocks == null ? null : encodeRpcU64Number(bucketBlocks, \"bucketBlocks\"),\n ];\n return this.call(\"lyth_clobOhlc\", params);\n }\n\n /** `lyth_clobOrderBook` — live CLOB depth from canonical state. */\n async lythClobOrderBook(\n marketId: string,\n levels?: number | null,\n ): Promise<ClobOrderBookResponse> {\n const params = levels == null ? [marketId] : [marketId, levels];\n return this.call(\"lyth_clobOrderBook\", params);\n }\n\n /** `lyth_txFeed` — paged global transaction feed. */\n async lythTxFeed(limit = 50, cursor?: string | null): Promise<TxFeedResponse> {\n const params = cursor === undefined ? [limit] : [limit, cursor];\n return decodeTxFeedResponse(await this.call<unknown>(\"lyth_txFeed\", params));\n }\n\n /** `lyth_addressProfile` — live account + label + activity aggregate. */\n async lythAddressProfile(address: string): Promise<AddressProfileResponse> {\n return this.call(\"lyth_addressProfile\", [sdkTypedAddress(address, \"user\", \"address\")]);\n }\n\n /** `lyth_addressFlow` — recent indexed address-flow aggregate. */\n async lythAddressFlow(address: string, limit = 250): Promise<AddressFlowResponse> {\n return this.call(\"lyth_addressFlow\", [sdkTypedAddress(address, \"user\", \"address\"), limit]);\n }\n\n /** `lyth_search` — exact live resolver for hashes, addresses, blocks, and clusters. */\n async lythSearch(query: string, limit = 10): Promise<SearchResponse> {\n return this.call(\"lyth_search\", [query, limit]);\n }\n\n /** `lyth_chainStats` — compact live chain/indexer/mempool summary. */\n async lythChainStats(): Promise<ChainStatsResponse> {\n return this.call(\"lyth_chainStats\", []);\n }\n\n /** `lyth_mempoolStatus` — aggregate mempool snapshot. */\n async lythMempoolStatus(): Promise<MempoolSnapshot> {\n return normalizeMempoolSnapshot(await this.call(\"lyth_mempoolStatus\", []));\n }\n\n /** `lyth_mempoolPending` — pending txs for a sender. */\n async lythMempoolPending(sender: string): Promise<PendingTxSummary[]> {\n return this.call(\"lyth_mempoolPending\", [sdkTypedAddress(sender, \"user\", \"sender\")]);\n }\n\n /** `lyth_currentRound` — latest committed height. */\n async lythCurrentRound(): Promise<RoundInfo> {\n return normalizeRoundInfo(await this.call(\"lyth_currentRound\", []));\n }\n\n /** `lyth_getTransactionCount` — native sender nonce. */\n async lythGetTransactionCount(address: string): Promise<bigint> {\n return parseRpcBigint(\n await this.call<unknown>(\"lyth_getTransactionCount\", [\n sdkTypedAddress(address, \"user\", \"address\"),\n ]),\n \"lyth_getTransactionCount\",\n );\n }\n\n /** `lyth_executionUnitPrice` — native execution-unit price in lythoshi. */\n async lythExecutionUnitPrice(): Promise<ExecutionUnitPriceResponse> {\n return normalizeExecutionUnitPriceResponse(\n await this.call<unknown>(\"lyth_executionUnitPrice\", []),\n );\n }\n\n /** `lyth_peerSummary` — public-safe aggregate peer-network diagnostics. */\n async lythPeerSummary(): Promise<PeerSummaryAggregate> {\n return this.call(\"lyth_peerSummary\", []);\n }\n\n /** `lyth_listActivePrecompiles` — native precompile catalogue. */\n async lythListActivePrecompiles(\n block: BlockSelector = \"latest\",\n ): Promise<PrecompileCatalogueResponse> {\n return this.call(\"lyth_listActivePrecompiles\", [encodeBlockSelector(block)]);\n }\n\n /** `lyth_capabilities` — address-keyed precompile capability map. */\n async lythCapabilities(block?: BlockSelector): Promise<CapabilitiesResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return normalizeCapabilitiesResponse(\n await this.call<CapabilitiesResponse>(\"lyth_capabilities\", params),\n );\n }\n\n /**\n * `lyth_operatorCapabilities` — node-level availability for operator UI\n * and explorer surfaces.\n */\n async lythOperatorCapabilities(): Promise<OperatorCapabilitiesResponse> {\n return this.call(\"lyth_operatorCapabilities\", []);\n }\n\n /** `lyth_indexerStatus` — indexer status; `null` when disabled. */\n async lythIndexerStatus(): Promise<IndexerStatus | null> {\n const v = await this.call<unknown>(\"lyth_indexerStatus\", []);\n if (v === null || v === undefined) return null;\n return v as IndexerStatus;\n }\n\n /** `lyth_getStorageProof` — batched Merkle proofs. */\n async lythGetStorageProof(\n address: string,\n slots: string[],\n ): Promise<StorageProofBatch> {\n return this.call(\"lyth_getStorageProof\", [address, slots]);\n }\n\n /** `lyth_getDelegations` — wallet delegation rows at a block. */\n async lythGetDelegations(\n wallet: string,\n block?: BlockSelector,\n ): Promise<DelegationsResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_getDelegations\", params);\n }\n\n /** `lyth_pendingRewards` — wallet pending rewards at a block. */\n async lythPendingRewards(\n wallet: string,\n block?: BlockSelector,\n ): Promise<PendingRewardsResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_pendingRewards\", params);\n }\n\n /** `lyth_redemptionQueue` — wallet redemption tickets at a block. */\n async lythRedemptionQueue(\n wallet: string,\n block?: BlockSelector,\n ): Promise<RedemptionQueueResponse> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params =\n block === undefined ? [userWallet] : [userWallet, encodeBlockSelector(block)];\n return this.call(\"lyth_redemptionQueue\", params);\n }\n\n /** `lyth_getDelegationHistory` — indexed per-wallet delegation event timeline. */\n async lythGetDelegationHistory(\n wallet: string,\n limit = 50,\n cursor?: string | null,\n ): Promise<DelegationHistoryRecord[]> {\n const userWallet = sdkTypedAddress(wallet, \"user\", \"wallet\");\n const params = cursor === undefined ? [userWallet, limit] : [userWallet, limit, cursor];\n return this.call(\"lyth_getDelegationHistory\", params);\n }\n\n /** `lyth_getClusterDelegators` — delegator addresses for a cluster. */\n async lythGetClusterDelegators(\n cluster: number,\n block?: BlockSelector,\n ): Promise<ClusterDelegatorsResponse> {\n const params =\n block === undefined ? [cluster] : [cluster, encodeBlockSelector(block)];\n return this.call(\"lyth_getClusterDelegators\", params);\n }\n\n /** `lyth_getDelegationCap` — active per-cluster cap at a block. */\n async lythGetDelegationCap(\n block?: BlockSelector,\n ): Promise<DelegationCapResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_getDelegationCap\", params);\n }\n\n /** `lyth_getTpmAttestation` — TPM quote digest + EK id for a peer. */\n async lythGetTpmAttestation(\n peerId: string,\n block?: BlockSelector,\n ): Promise<TpmAttestationResponse> {\n const params =\n block === undefined ? [peerId] : [peerId, encodeBlockSelector(block)];\n return this.call(\"lyth_getTpmAttestation\", params);\n }\n\n /** `lyth_getClusterEntity` — entity flag for a cluster. */\n async lythGetClusterEntity(\n cluster: number,\n block?: BlockSelector,\n ): Promise<ClusterEntityResponse> {\n const params =\n block === undefined ? [cluster] : [cluster, encodeBlockSelector(block)];\n return this.call(\"lyth_getClusterEntity\", params);\n }\n\n /** `lyth_getEntityRatchet` — entity-ratchet snapshot at a block. */\n async lythGetEntityRatchet(\n block?: BlockSelector,\n ): Promise<EntityRatchetResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_getEntityRatchet\", params);\n }\n\n /** `lyth_operatorInfo` — canonical operator identity envelope. */\n async lythOperatorInfo(operatorId: string): Promise<OperatorInfoResponse> {\n return normalizeOperatorInfo(await this.call(\"lyth_operatorInfo\", [operatorId]));\n }\n\n /** `lyth_getServiceProbe` — latest external reachability report for one public service. */\n async lythGetServiceProbe(\n peerId: string,\n serviceMask: number,\n ): Promise<ServiceProbeResponse | null> {\n assertHexBytes(peerId, 32, \"peerId\");\n if (!isSinglePublicServiceProbeMask(serviceMask)) {\n throw SdkError.malformed(\"serviceMask must contain exactly one public-service bit\");\n }\n const value = await this.call<unknown>(\"lyth_getServiceProbe\", [peerId, serviceMask]);\n if (value === null || value === undefined) return null;\n return normalizeServiceProbe(value);\n }\n\n /** `lyth_reportServiceProbe` — submit a pre-signed public-service probe report. */\n async lythReportServiceProbe(\n req: ReportServiceProbeRequest,\n ): Promise<ReportServiceProbeResponse> {\n assertHexBytes(req.peerId, 32, \"peerId\");\n if (!isValidPublicServiceProbeMask(req.serviceMask)) {\n throw SdkError.malformed(\"serviceMask must name one or more public-service bits\");\n }\n if (!isConcreteServiceProbeStatus(req.status)) {\n throw SdkError.malformed(\"status must be reachable, degraded, or unreachable\");\n }\n assertSafeUint32(req.latencyMs, \"latencyMs\");\n assertHexBytes(req.probeDigest, 32, \"probeDigest\");\n assertNonEmptyHex(req.signedRawTx, \"signedRawTx\");\n return this.call(\"lyth_reportServiceProbe\", [req]);\n }\n\n /** `lyth_clusterStatus` — canonical cluster status envelope. */\n async lythClusterStatus(clusterId: number): Promise<ClusterStatusResponse> {\n return normalizeClusterStatus(await this.call(\"lyth_clusterStatus\", [clusterId]));\n }\n\n /** `lyth_clusterDirectory` — paged public cluster directory. */\n async lythClusterDirectory(page = 0, limit = 25): Promise<ClusterDirectoryPageResponse> {\n return normalizeClusterDirectoryPage(\n await this.call(\"lyth_clusterDirectory\", [page, limit]),\n );\n }\n\n /** `lyth_clusters` — alias for `lyth_clusterDirectory`. */\n async lythClusters(page = 0, limit = 25): Promise<ClusterDirectoryPageResponse> {\n return normalizeClusterDirectoryPage(await this.call(\"lyth_clusters\", [page, limit]));\n }\n\n /**\n * `lyth_submitPendingChange` — operator-onboarding transport for the\n * pending-change ledger. Server validates the envelope shape.\n */\n async lythSubmitPendingChange(envelope: unknown): Promise<unknown> {\n return this.call(\"lyth_submitPendingChange\", [envelope]);\n }\n\n /** `lyth_submitEncrypted` — submit a bincode-encoded encrypted envelope hex. */\n async lythSubmitEncrypted(envelopeHex: string): Promise<string> {\n return this.call(\"lyth_submitEncrypted\", [envelopeHex]);\n }\n\n /** `lyth_getEncryptionKey` — cluster ML-KEM encapsulation key. */\n async lythGetEncryptionKey(): Promise<EncryptionKeyResponse> {\n return this.call(\"lyth_getEncryptionKey\", []);\n }\n\n /** `lyth_syncStatus` — DAG-sync driver snapshot. */\n async lythSyncStatus(): Promise<DagSyncStatus | null> {\n const v = await this.call<unknown>(\"lyth_syncStatus\", []);\n if (v === null || v === undefined) return null;\n return v as DagSyncStatus;\n }\n\n /** `lyth_resolveOperatorAuthority` — operator id to authority index. */\n async lythResolveOperatorAuthority(operatorId: string): Promise<OperatorAuthorityResponse> {\n return normalizeOperatorAuthority(\n await this.call(\"lyth_resolveOperatorAuthority\", [operatorId]),\n );\n }\n\n /** `lyth_signingActivity` — recent per-round signing participation. */\n async lythSigningActivity(\n authorityIndex: number,\n limit?: number | null,\n ): Promise<OperatorSigningActivityResponse> {\n const params = limit == null ? [authorityIndex] : [authorityIndex, limit];\n return normalizeSigningActivity(await this.call(\"lyth_signingActivity\", params));\n }\n\n /** `lyth_upcomingDuties` — deterministic upcoming duty windows. */\n async lythUpcomingDuties(\n authorityIndex: number,\n horizonRounds?: number | null,\n ): Promise<UpcomingDutiesResponse> {\n const params =\n horizonRounds == null ? [authorityIndex] : [authorityIndex, horizonRounds];\n return normalizeUpcomingDuties(await this.call(\"lyth_upcomingDuties\", params));\n }\n\n /** `lyth_operatorRisk` — miss-rate and jail-status window. */\n async lythOperatorRisk(\n authorityIndex: number,\n windowRounds?: number | null,\n ): Promise<OperatorRiskResponse> {\n const params =\n windowRounds == null ? [authorityIndex] : [authorityIndex, windowRounds];\n return normalizeOperatorRisk(await this.call(\"lyth_operatorRisk\", params));\n }\n\n /** `lyth_upgradeStatus` — signed network-upgrade readiness at a height. */\n async lythUpgradeStatus(block?: BlockSelector): Promise<LythUpgradeStatusResponse> {\n const params = block === undefined ? [] : [encodeBlockSelector(block)];\n return this.call(\"lyth_upgradeStatus\", params);\n }\n\n /** `lyth_runtimeProvenance` — public-safe build/runtime provenance. */\n async lythRuntimeProvenance(): Promise<RuntimeProvenanceResponse> {\n return this.call(\"lyth_runtimeProvenance\", []);\n }\n\n /** `lyth_txStatus` — discriminated transaction lookup outcome. */\n async lythTxStatus(txHash: string): Promise<TxStatusResponse> {\n return this.call(\"lyth_txStatus\", [txHash]);\n }\n\n /** `lyth_verticesAtRound` — per-vertex authorship observed at a DAG round. */\n async lythVerticesAtRound(\n round: number | bigint | string,\n ): Promise<VerticesAtRoundResponse> {\n return this.call(\"lyth_verticesAtRound\", [\n encodeRpcU64Number(round, \"round\"),\n ]);\n }\n\n /** `lyth_metricsRange` — retained telemetry series when the node has them. */\n async lythMetricsRange(\n selectors: string[],\n range?: readonly [number | bigint | string, number | bigint | string] | null,\n ): Promise<MetricsRangeResponse> {\n const params =\n range === undefined\n ? [selectors]\n : [\n selectors,\n range === null\n ? null\n : [\n encodeRpcU64Number(range[0], \"fromBlock\"),\n encodeRpcU64Number(range[1], \"toBlock\"),\n ],\n ];\n return this.call(\"lyth_metricsRange\", params);\n }\n\n /** `lyth_getLatestCheckpoint` — latest PQ-finality checkpoint rows. */\n async lythGetLatestCheckpoint(belowHeight?: number | bigint | string | null): Promise<CheckpointRecord[]> {\n const params = belowHeight === undefined ? [] : [encodeOptionalHeight(belowHeight)];\n return this.call(\"lyth_getLatestCheckpoint\", params);\n }\n\n /** `lyth_getClusterResignations` — in-flight + applied operator resignations. */\n async lythGetClusterResignations(\n operator?: string | null,\n status?: \"pending\" | \"applied\" | \"all\" | string | null,\n ): Promise<ClusterResignationsResponse> {\n const params =\n status === undefined\n ? operator == null\n ? []\n : [operator]\n : [operator ?? null, status];\n return this.call(\"lyth_getClusterResignations\", params);\n }\n\n /** `lyth_getBlsRoundCertificate` — round-advancement BLS aggregate. */\n async lythGetBlsRoundCertificate(round: number | bigint | string): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getBlsRoundCertificate\", [encodeRpcInteger(round)]);\n }\n\n /** `lyth_getLeaderCertificate` — leader-vote BLS aggregate for a block ref. */\n async lythGetLeaderCertificate(\n round: number | bigint | string,\n authority: number,\n digest: string,\n ): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getLeaderCertificate\", [encodeRpcInteger(round), authority, digest]);\n }\n\n /** `lyth_getDacCertificate` — data-availability certificate for a block ref. */\n async lythGetDacCertificate(\n round: number | bigint | string,\n authority: number,\n digest: string,\n ): Promise<BlsCertificateResponse | null> {\n return this.call(\"lyth_getDacCertificate\", [encodeRpcInteger(round), authority, digest]);\n }\n\n /** `lyth_subscribe` — WebSocket-only; returns an RPC error over HTTP. */\n async lythSubscribe(channel: ApiStreamTopic | (string & {})): Promise<unknown> {\n return this.call(\"lyth_subscribe\", [channel]);\n }\n\n /** `lyth_unsubscribe` — counterpart to `lythSubscribe`. */\n async lythUnsubscribe(subId: string): Promise<unknown> {\n return this.call(\"lyth_unsubscribe\", [subId]);\n }\n\n // ---- debug_* ------------------------------------------------------\n // Server-side gated by `RpcConfig::debug_enabled`. When the namespace\n // is disabled, every call surfaces as `SdkError.rpc`.\n\n /** `debug_traceTransaction` — legacy compatibility trace for a confirmed tx. */\n async debugTraceTransaction(txHash: string): Promise<unknown> {\n return this.call(\"debug_traceTransaction\", [txHash]);\n }\n\n /** `debug_traceCall` — legacy compatibility trace for a dry-run. */\n async debugTraceCall(\n request: CallRequest,\n block: BlockSelector = \"latest\",\n ): Promise<unknown> {\n return this.call(\"debug_traceCall\", [request, encodeBlockSelector(block)]);\n }\n\n /** `debug_traceBlockByNumber` — legacy compatibility traces for an entire block. */\n async debugTraceBlockByNumber(block: BlockSelector): Promise<unknown> {\n return this.call(\"debug_traceBlockByNumber\", [encodeBlockSelector(block)]);\n }\n\n /** `debug_mempoolDump` — full mempool snapshot. */\n async debugMempoolDump(): Promise<MempoolSnapshot> {\n return normalizeMempoolSnapshot(await this.call(\"debug_mempoolDump\", []));\n }\n\n /** `debug_p2pPeers` — connected libp2p peer list. */\n async debugP2pPeers(): Promise<PeerSummary[]> {\n return this.call(\"debug_p2pPeers\", []);\n }\n\n /** `debug_stateDiff` — state-diff for a block range. */\n async debugStateDiff(params: unknown): Promise<unknown> {\n return this.call(\"debug_stateDiff\", params);\n }\n\n /** `debug_chainReorg` — testnet-only reorg trigger. */\n async debugChainReorg(params: unknown): Promise<unknown> {\n return this.call(\"debug_chainReorg\", params);\n }\n\n // ---- mesh_* -------------------------------------------------------\n\n /** `mesh_buildUnsignedTx` — build an unsigned transaction envelope. */\n async meshBuildUnsignedTx(intent: MeshTxIntent): Promise<MeshUnsignedTxResponse> {\n return this.call(\"mesh_buildUnsignedTx\", [intent]);\n }\n\n /** `mesh_combineTx` — combine an unsigned envelope with a wallet signature. */\n async meshCombineTx(\n unsignedTx: string,\n signatureHex: string,\n algo?: \"secp256k1\" | \"ml_dsa_65\" | string,\n pubkeyHex?: string,\n ): Promise<MeshSignedTxResponse> {\n const params =\n algo === undefined\n ? [unsignedTx, signatureHex]\n : pubkeyHex === undefined\n ? [unsignedTx, signatureHex, algo]\n : [unsignedTx, signatureHex, algo, pubkeyHex];\n return this.call(\"mesh_combineTx\", params);\n }\n\n /** `mesh_decodeTx` — decode a signed or unsigned mesh envelope. */\n async meshDecodeTx(envelopeHex: string, signed = false): Promise<MeshDecodedTx> {\n return this.call(\"mesh_decodeTx\", [envelopeHex, signed]);\n }\n\n /** `mesh_submitTx` — submit a signed mesh envelope. */\n async meshSubmitTx(signedTx: string): Promise<string> {\n return this.call(\"mesh_submitTx\", [signedTx]);\n }\n}\n\n/** Decode a `0x`-prefixed hex quantity to a `bigint`. */\nexport function parseQuantityBig(hex: string): bigint {\n if (!hex) return 0n;\n const rest = hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n if (rest.length === 0) return 0n;\n if (!/^[0-9a-fA-F]+$/.test(rest)) {\n throw SdkError.malformed(`invalid hex quantity: ${hex}`);\n }\n return BigInt(`0x${rest}`);\n}\n\n/**\n * Decode a `0x`-prefixed hex quantity to a JS `number`. Convenience for\n * small quantities (chain id, block height, gas estimate). Throws if the\n * value exceeds `Number.MAX_SAFE_INTEGER`.\n */\nexport function parseQuantity(hex: string): number {\n const big = parseQuantityBig(hex);\n if (big > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw SdkError.malformed(`hex quantity exceeds safe integer: ${hex}`);\n }\n return Number(big);\n}\n\nfunction encodeRpcInteger(v: number | bigint | string): number | string {\n if (typeof v === \"bigint\") return `0x${v.toString(16)}`;\n return v;\n}\n\nfunction encodeOptionalHeight(v: number | bigint | string | null): number | string | null {\n if (v === null) return null;\n return encodeRpcInteger(v);\n}\n\nfunction encodeRpcU64Number(v: number | bigint | string, label: string): number {\n return parseRpcNumber(v, label);\n}\n\nexport function nativeEventsFilterParams(filter: NativeEventsFilter): Record<string, unknown> {\n return {\n fromBlock: encodeRpcU64Number(filter.fromBlock, \"fromBlock\"),\n toBlock: encodeRpcU64Number(filter.toBlock, \"toBlock\"),\n ...optionalRpcNumber(\"limit\", filter.limit),\n ...optionalRpcNumber(\"txIndex\", filter.txIndex),\n ...optionalRpcNumber(\"logIndex\", filter.logIndex),\n ...optionalString(\"address\", filter.address),\n ...optionalString(\"eventTopic\", filter.eventTopic),\n ...optionalString(\"family\", filter.family),\n ...optionalString(\"eventName\", filter.eventName),\n ...optionalString(\"primaryId\", filter.primaryId),\n ...optionalString(\"relatedId\", filter.relatedId),\n ...optionalString(\"tokenId\", filter.tokenId),\n ...optionalString(\"account\", filter.account),\n ...optionalString(\"counterparty\", filter.counterparty),\n };\n}\n\nfunction optionalRpcNumber(\n key: string,\n value: number | bigint | string | null | undefined,\n): Record<string, number> {\n return value == null ? {} : { [key]: encodeRpcU64Number(value, key) };\n}\n\nfunction optionalString(key: string, value: string | null | undefined): Record<string, string> {\n return value == null ? {} : { [key]: value };\n}\n\nfunction parseRpcBigint(value: unknown, label: string): bigint {\n if (typeof value === \"bigint\") {\n if (value < 0n) {\n throw SdkError.malformed(`${label} must be a non-negative quantity`);\n }\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw SdkError.malformed(`${label} must be a non-negative safe integer`);\n }\n return BigInt(value);\n }\n if (typeof value === \"string\") {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) return parseQuantityBig(value);\n if (/^\\d+$/.test(value)) return BigInt(value);\n }\n throw SdkError.malformed(`${label} must be a bigint-compatible quantity`);\n}\n\nfunction parseRpcNumber(value: unknown, label: string): number {\n const big = parseRpcBigint(value, label);\n if (big > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw SdkError.malformed(`${label} exceeds safe integer range`);\n }\n return Number(big);\n}\n\nfunction parseRpcNumberNullable(value: unknown, label: string): number | null {\n return value === null || value === undefined ? null : parseRpcNumber(value, label);\n}\n\nfunction parseRpcBigintNullable(value: unknown, label: string): bigint | null {\n return value === null || value === undefined ? null : parseRpcBigint(value, label);\n}\n\nfunction parseStringNullable(value: unknown): string | null {\n return value === null || value === undefined ? null : String(value);\n}\n\nfunction parseStringField(value: unknown, label: string): string {\n if (value === null || value === undefined) {\n throw SdkError.malformed(`${label} is missing`);\n }\n return String(value);\n}\n\nfunction parseBooleanField(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") {\n throw SdkError.malformed(`${label} must be a boolean`);\n }\n return value;\n}\n\nfunction parseRpcUint(value: unknown, label: string, max: number, typeName: string): number {\n const parsed = parseRpcNumber(value, label);\n if (parsed > max) {\n throw SdkError.malformed(`${label} must be a ${typeName}`);\n }\n return parsed;\n}\n\nfunction parseRpcUintNullable(\n value: unknown,\n label: string,\n max: number,\n typeName: string,\n): number | null {\n return value === null || value === undefined ? null : parseRpcUint(value, label, max, typeName);\n}\n\nfunction decodeNativeAgentStateArray<T>(\n row: Record<string, unknown>,\n key: string,\n decode: (value: unknown, label: string) => T,\n defaultMissing: boolean,\n): T[] {\n const value = row[key];\n if (value === undefined && defaultMissing) return [];\n if (!Array.isArray(value)) {\n throw SdkError.malformed(`native agent state ${key} must be an array`);\n }\n return value.map((item, index) => decode(item, `native agent state ${key}[${index}]`));\n}\n\nfunction decodeNativeAgentExistingStateRecord<T>(value: unknown, label: string): T {\n return expectObject(value, label) as unknown as T;\n}\n\nfunction decodeNativeAgentIssuerStateRecord(\n value: unknown,\n label: string,\n): NativeAgentIssuerStateRecord {\n const row = expectObject(value, label);\n return {\n issuerId: parseStringField(row[\"issuerId\"], `${label}.issuerId`),\n issuer: parseStringField(row[\"issuer\"], `${label}.issuer`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentAttestationStateRecord(\n value: unknown,\n label: string,\n): NativeAgentAttestationStateRecord {\n const row = expectObject(value, label);\n return {\n attestationId: parseStringField(row[\"attestationId\"], `${label}.attestationId`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n issuerId: parseStringNullable(row[\"issuerId\"]),\n issuer: parseStringNullable(row[\"issuer\"]),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n schemaHash: parseStringNullable(row[\"schemaHash\"]),\n payloadHash: parseStringNullable(row[\"payloadHash\"]),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentConsentStateRecord(\n value: unknown,\n label: string,\n): NativeAgentConsentStateRecord {\n const row = expectObject(value, label);\n return {\n consentId: parseStringField(row[\"consentId\"], `${label}.consentId`),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n grantee: parseStringField(row[\"grantee\"], `${label}.grantee`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n scopeHash: parseStringNullable(row[\"scopeHash\"]),\n expiresAt: parseRpcNumberNullable(row[\"expiresAt\"], `${label}.expiresAt`),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentServiceStateRecord(\n value: unknown,\n label: string,\n): NativeAgentServiceStateRecord {\n const row = expectObject(value, label);\n return {\n serviceId: parseStringField(row[\"serviceId\"], `${label}.serviceId`),\n provider: parseStringField(row[\"provider\"], `${label}.provider`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n categoryHash: parseStringNullable(row[\"categoryHash\"]),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n active: parseBooleanField(row[\"active\"], `${label}.active`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentAvailabilityStateRecord(\n value: unknown,\n label: string,\n): NativeAgentAvailabilityStateRecord {\n const row = expectObject(value, label);\n return {\n provider: parseStringField(row[\"provider\"], `${label}.provider`),\n maxConcurrent: parseRpcUint(row[\"maxConcurrent\"], `${label}.maxConcurrent`, 0xffffffff, \"uint32\"),\n openRequests: parseRpcUint(row[\"openRequests\"], `${label}.openRequests`, 0xffffffff, \"uint32\"),\n paused: parseBooleanField(row[\"paused\"], `${label}.paused`),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentArbiterStateRecord(\n value: unknown,\n label: string,\n): NativeAgentArbiterStateRecord {\n const row = expectObject(value, label);\n return {\n arbiterId: parseStringField(row[\"arbiterId\"], `${label}.arbiterId`),\n arbiter: parseStringField(row[\"arbiter\"], `${label}.arbiter`),\n nonce: parseRpcNumberNullable(row[\"nonce\"], `${label}.nonce`),\n tier: parseRpcUintNullable(row[\"tier\"], `${label}.tier`, 0xffff, \"uint16\"),\n metadataHash: parseStringNullable(row[\"metadataHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction decodeNativeAgentReputationReviewStateRecord(\n value: unknown,\n label: string,\n): NativeAgentReputationReviewStateRecord {\n const row = expectObject(value, label);\n return {\n reviewId: parseStringField(row[\"reviewId\"], `${label}.reviewId`),\n reviewer: parseStringField(row[\"reviewer\"], `${label}.reviewer`),\n subject: parseStringField(row[\"subject\"], `${label}.subject`),\n categoryId: parseRpcUint(row[\"categoryId\"], `${label}.categoryId`, 0xffffffff, \"uint32\"),\n speedScore: parseRpcUint(row[\"speedScore\"], `${label}.speedScore`, 0xff, \"uint8\"),\n qualityScore: parseRpcUint(row[\"qualityScore\"], `${label}.qualityScore`, 0xff, \"uint8\"),\n communicationScore: parseRpcUint(\n row[\"communicationScore\"],\n `${label}.communicationScore`,\n 0xff,\n \"uint8\",\n ),\n accuracyScore: parseRpcUint(row[\"accuracyScore\"], `${label}.accuracyScore`, 0xff, \"uint8\"),\n payloadHash: parseStringNullable(row[\"payloadHash\"]),\n updatedAtBlock: parseRpcNumber(row[\"updatedAtBlock\"], `${label}.updatedAtBlock`),\n };\n}\n\nfunction expectObject(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw SdkError.malformed(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nexport function decodeNativeReceiptResponse<TDecoded = unknown>(\n value: unknown,\n): NativeReceiptResponse<TDecoded> {\n const row = expectObject(value, \"native receipt response\");\n assertNativeReceiptFee(row[\"fee\"], \"native receipt response.fee\");\n return value as NativeReceiptResponse<TDecoded>;\n}\n\nexport function decodeTxFeedResponse(value: unknown): TxFeedResponse {\n const row = expectObject(value, \"tx feed response\");\n const transactions = row[\"transactions\"];\n if (!Array.isArray(transactions)) {\n throw SdkError.malformed(\"tx feed response.transactions must be an array\");\n }\n transactions.forEach((transaction, index) => {\n const tx = expectObject(transaction, `tx feed response.transactions[${index}]`);\n assertNativeReceiptFee(tx[\"fee\"], `tx feed response.transactions[${index}].fee`);\n });\n return value as TxFeedResponse;\n}\n\nfunction assertNativeReceiptFee(value: unknown, label: string): asserts value is NativeReceiptFee {\n try {\n assertMrvStructuredFeeConformance(value, { label });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw SdkError.malformed(`structured native fee violation: ${message}`);\n }\n}\n\nfunction firstField(row: Record<string, unknown>, keys: readonly string[], label: string): unknown {\n for (const key of keys) {\n if (row[key] !== undefined) return row[key];\n }\n throw SdkError.malformed(`${label} is missing (${keys.join(\" | \")})`);\n}\n\nfunction normalizeServiceProbe(value: unknown): ServiceProbeResponse {\n const row = expectObject(value, \"service probe response\");\n return {\n serviceMask: parseRpcNumber(row[\"serviceMask\"], \"service probe serviceMask\"),\n status: String(row[\"status\"]),\n statusCode: parseRpcNumber(row[\"statusCode\"], \"service probe statusCode\"),\n lastProbeBlock: parseRpcNumber(row[\"lastProbeBlock\"], \"service probe lastProbeBlock\"),\n latencyMs: parseRpcNumber(row[\"latencyMs\"], \"service probe latencyMs\"),\n probeDigest: String(row[\"probeDigest\"]),\n reporter: String(row[\"reporter\"]),\n };\n}\n\nfunction assertSafeUint32(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw SdkError.malformed(`${label} must be a uint32`);\n }\n}\n\nfunction assertHexBytes(value: string, expectedLen: number, label: string): void {\n const body = hexBody(value, label);\n if (body.length !== expectedLen * 2) {\n throw SdkError.malformed(`${label} must be ${expectedLen} bytes`);\n }\n}\n\nfunction assertNonEmptyHex(value: string, label: string): void {\n const body = hexBody(value, label);\n if (body.length === 0) {\n throw SdkError.malformed(`${label} must be non-empty`);\n }\n}\n\nfunction hexBody(value: string, label: string): string {\n const body = value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {\n throw SdkError.malformed(`${label} must be hex bytes`);\n }\n return body;\n}\n\nfunction normalizeOperatorInfo(value: unknown): OperatorInfoResponse {\n const row = expectObject(value, \"operator info response\");\n const activeClusterIds = row[\"activeClusterIds\"];\n if (!Array.isArray(activeClusterIds)) {\n throw SdkError.malformed(\"operator info activeClusterIds must be an array\");\n }\n const capability = row[\"capability\"];\n return {\n operatorId: String(row[\"operatorId\"]),\n moniker: parseStringNullable(row[\"moniker\"]),\n alias: parseStringNullable(row[\"alias\"]),\n chainAddress: String(row[\"chainAddress\"]),\n bonded: Boolean(row[\"bonded\"]),\n commissionBps: parseRpcNumberNullable(row[\"commissionBps\"], \"operator info commissionBps\"),\n delegationCount: parseRpcNumberNullable(\n row[\"delegationCount\"],\n \"operator info delegationCount\",\n ),\n bondedAmount: String(row[\"bondedAmount\"]),\n activeClusterIds: activeClusterIds.map((v, i) =>\n parseRpcNumber(v, `operator info activeClusterIds[${i}]`),\n ),\n operatorKeyFingerprint: parseStringNullable(row[\"operatorKeyFingerprint\"]),\n blsKeyFingerprint: parseStringNullable(row[\"blsKeyFingerprint\"]),\n lifecycleState: String(row[\"lifecycleState\"]),\n capability:\n capability && typeof capability === \"object\" && !Array.isArray(capability)\n ? (capability as Record<string, unknown>)\n : {},\n };\n}\n\nfunction normalizeClusterMember(value: unknown, label: string): ClusterMemberResponse {\n const row = expectObject(value, label);\n return {\n operatorId: String(row[\"operatorId\"]),\n blsPubkey: String(row[\"blsPubkey\"]),\n state: String(row[\"state\"]),\n };\n}\n\nfunction normalizeClusterStatus(value: unknown): ClusterStatusResponse {\n const row = expectObject(value, \"cluster status response\");\n const members = row[\"members\"];\n if (!Array.isArray(members)) {\n throw SdkError.malformed(\"cluster status members must be an array\");\n }\n return {\n clusterId: parseRpcNumber(row[\"clusterId\"], \"cluster status clusterId\"),\n threshold: parseRpcNumber(row[\"threshold\"], \"cluster status threshold\"),\n size: parseRpcNumber(row[\"size\"], \"cluster status size\"),\n live: parseRpcNumber(row[\"live\"], \"cluster status live\"),\n lagging: parseRpcNumber(row[\"lagging\"], \"cluster status lagging\"),\n offline: parseRpcNumber(row[\"offline\"], \"cluster status offline\"),\n maintenance: parseRpcNumber(row[\"maintenance\"], \"cluster status maintenance\"),\n members: members.map((member, i) => normalizeClusterMember(member, `cluster status members[${i}]`)),\n epoch: parseRpcBigintNullable(row[\"epoch\"], \"cluster status epoch\"),\n round: parseRpcBigintNullable(row[\"round\"], \"cluster status round\"),\n quorum: String(row[\"quorum\"]),\n reputationScore: parseRpcNumberNullable(\n row[\"reputationScore\"],\n \"cluster status reputationScore\",\n ),\n livenessScore: parseRpcNumberNullable(row[\"livenessScore\"], \"cluster status livenessScore\"),\n lastUpdateHeight: parseRpcBigint(row[\"lastUpdateHeight\"], \"cluster status lastUpdateHeight\"),\n };\n}\n\nfunction normalizeClusterDirectoryEntry(value: unknown, label: string): ClusterDirectoryEntryResponse {\n const row = expectObject(value, label);\n const regionDiversity = row[\"regionDiversity\"];\n if (regionDiversity !== null && regionDiversity !== undefined && !Array.isArray(regionDiversity)) {\n throw SdkError.malformed(`${label}.regionDiversity must be an array or null`);\n }\n return {\n clusterId: parseRpcNumber(row[\"clusterId\"], `${label}.clusterId`),\n size: parseRpcNumber(row[\"size\"], `${label}.size`),\n threshold: parseRpcNumber(row[\"threshold\"], `${label}.threshold`),\n aggregateHealth: String(row[\"aggregateHealth\"]),\n regionDiversity: Array.isArray(regionDiversity) ? regionDiversity.map(String) : null,\n active: Boolean(row[\"active\"]),\n };\n}\n\nfunction normalizeClusterDirectoryPage(value: unknown): ClusterDirectoryPageResponse {\n const row = expectObject(value, \"cluster directory response\");\n const clusters = row[\"clusters\"];\n if (!Array.isArray(clusters)) {\n throw SdkError.malformed(\"cluster directory clusters must be an array\");\n }\n return {\n page: parseRpcNumber(row[\"page\"], \"cluster directory page\"),\n limit: parseRpcNumber(row[\"limit\"], \"cluster directory limit\"),\n totalClusters: parseRpcNumber(row[\"totalClusters\"], \"cluster directory totalClusters\"),\n clusters: clusters.map((cluster, i) =>\n normalizeClusterDirectoryEntry(cluster, `cluster directory clusters[${i}]`),\n ),\n };\n}\n\nfunction normalizeOperatorAuthority(value: unknown): OperatorAuthorityResponse {\n const row = expectObject(value, \"operator authority response\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"operator authority schemaVersion\"),\n operatorId: String(row[\"operatorId\"]),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"operator authority authorityIndex\"),\n blsPubkey: String(row[\"blsPubkey\"]),\n active: Boolean(row[\"active\"]),\n };\n}\n\nfunction normalizeSigningActivity(value: unknown): OperatorSigningActivityResponse {\n const row = expectObject(value, \"signing activity response\");\n const entries = row[\"entries\"];\n if (!Array.isArray(entries)) {\n throw SdkError.malformed(\"signing activity entries must be an array\");\n }\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"signing activity schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"signing activity authorityIndex\"),\n currentRound: parseRpcBigint(row[\"currentRound\"], \"signing activity currentRound\"),\n limit: parseRpcNumber(row[\"limit\"], \"signing activity limit\"),\n entries: entries.map((entry, i) => {\n const e = expectObject(entry, `signing activity entries[${i}]`);\n return {\n round: parseRpcBigint(e[\"round\"], `signing activity entries[${i}].round`),\n status: String(e[\"status\"]),\n };\n }),\n };\n}\n\nfunction normalizeDutyAbsence(value: unknown, label: string): DutyAbsence {\n const row = expectObject(value, label);\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeKeyRotationWindow(value: unknown): KeyRotationWindow {\n const row = expectObject(value, \"upcoming duties keyRotation\");\n if (\"nextRound\" in row) {\n return {\n nextRound: parseRpcBigint(row[\"nextRound\"], \"upcoming duties keyRotation.nextRound\"),\n epochLengthRounds: parseRpcBigint(\n row[\"epochLengthRounds\"],\n \"upcoming duties keyRotation.epochLengthRounds\",\n ),\n };\n }\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeUpcomingDuties(value: unknown): UpcomingDutiesResponse {\n const row = expectObject(value, \"upcoming duties response\");\n const duties = expectObject(row[\"duties\"], \"upcoming duties duties\");\n const attestation = expectObject(duties[\"attestation\"], \"upcoming duties attestation\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"upcoming duties schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"upcoming duties authorityIndex\"),\n currentRound: parseRpcBigint(row[\"currentRound\"], \"upcoming duties currentRound\"),\n horizonRounds: parseRpcNumber(row[\"horizonRounds\"], \"upcoming duties horizonRounds\"),\n duties: {\n attestation: {\n startRound: parseRpcBigint(attestation[\"startRound\"], \"upcoming duties attestation.startRound\"),\n endRound: parseRpcBigint(attestation[\"endRound\"], \"upcoming duties attestation.endRound\"),\n kind: String(attestation[\"kind\"]),\n },\n blockProduction: normalizeDutyAbsence(\n duties[\"blockProduction\"],\n \"upcoming duties blockProduction\",\n ),\n sync: normalizeDutyAbsence(duties[\"sync\"], \"upcoming duties sync\"),\n keyRotation: normalizeKeyRotationWindow(duties[\"keyRotation\"]),\n },\n };\n}\n\nfunction normalizeJailStatus(value: unknown): JailStatusWindow {\n const row = expectObject(value, \"operator risk jailStatus\");\n if (\"jailed\" in row || \"tombstoned\" in row) {\n return {\n jailed: Boolean(row[\"jailed\"]),\n tombstoned: Boolean(row[\"tombstoned\"]),\n jailedUntilHeight: parseRpcBigint(\n row[\"jailedUntilHeight\"],\n \"operator risk jailStatus.jailedUntilHeight\",\n ),\n unjailCount: parseRpcBigint(row[\"unjailCount\"], \"operator risk jailStatus.unjailCount\"),\n };\n }\n return { reason: String(row[\"reason\"]) };\n}\n\nfunction normalizeOperatorRisk(value: unknown): OperatorRiskResponse {\n const row = expectObject(value, \"operator risk response\");\n const reasons = row[\"reasons\"];\n if (!Array.isArray(reasons)) {\n throw SdkError.malformed(\"operator risk reasons must be an array\");\n }\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"operator risk schemaVersion\"),\n authorityIndex: parseRpcNumber(row[\"authorityIndex\"], \"operator risk authorityIndex\"),\n dataHeight: parseRpcBigint(row[\"dataHeight\"], \"operator risk dataHeight\"),\n windowRounds: parseRpcNumber(row[\"windowRounds\"], \"operator risk windowRounds\"),\n missedRounds: parseRpcNumber(row[\"missedRounds\"], \"operator risk missedRounds\"),\n observedRounds: parseRpcNumber(row[\"observedRounds\"], \"operator risk observedRounds\"),\n missRateBps: parseRpcNumber(row[\"missRateBps\"], \"operator risk missRateBps\"),\n thresholdBps: parseRpcNumber(row[\"thresholdBps\"], \"operator risk thresholdBps\"),\n remainingHeadroomBps: parseRpcNumber(\n row[\"remainingHeadroomBps\"],\n \"operator risk remainingHeadroomBps\",\n ),\n jailStatus: normalizeJailStatus(row[\"jailStatus\"]),\n reasons: reasons.map(String),\n };\n}\n\nexport function nativeAgentStateFilterParams(\n filter: NativeAgentStateFilter,\n): Record<string, NativeAgentStateFilterParamValue> {\n const out: Record<string, NativeAgentStateFilterParamValue> = {};\n if (filter.policyId != null) out.policyId = filter.policyId;\n if (filter.escrowId != null) out.escrowId = filter.escrowId;\n if (filter.account != null) out.account = filter.account;\n if (filter.includePolicySpends != null) out.includePolicySpends = filter.includePolicySpends;\n if (filter.limit != null) out.limit = encodeRpcU64Number(filter.limit, \"limit\");\n return out;\n}\n\nexport function decodeNativeAgentStateResponse(value: unknown): NativeAgentStateResponse {\n const row = expectObject(value, \"native agent state response\");\n return {\n schemaVersion: parseRpcNumber(row[\"schemaVersion\"], \"native agent state schemaVersion\"),\n limit: parseRpcNumber(row[\"limit\"], \"native agent state limit\"),\n filters: expectObject(\n row[\"filters\"],\n \"native agent state filters\",\n ) as unknown as NativeAgentStateResponseFilters,\n issuers: decodeNativeAgentStateArray(\n row,\n \"issuers\",\n decodeNativeAgentIssuerStateRecord,\n true,\n ),\n attestations: decodeNativeAgentStateArray(\n row,\n \"attestations\",\n decodeNativeAgentAttestationStateRecord,\n true,\n ),\n consents: decodeNativeAgentStateArray(\n row,\n \"consents\",\n decodeNativeAgentConsentStateRecord,\n true,\n ),\n services: decodeNativeAgentStateArray(\n row,\n \"services\",\n decodeNativeAgentServiceStateRecord,\n true,\n ),\n availability: decodeNativeAgentStateArray(\n row,\n \"availability\",\n decodeNativeAgentAvailabilityStateRecord,\n true,\n ),\n arbiters: decodeNativeAgentStateArray(\n row,\n \"arbiters\",\n decodeNativeAgentArbiterStateRecord,\n true,\n ),\n reputationReviews: decodeNativeAgentStateArray(\n row,\n \"reputationReviews\",\n decodeNativeAgentReputationReviewStateRecord,\n true,\n ),\n spendingPolicies: decodeNativeAgentStateArray(\n row,\n \"spendingPolicies\",\n decodeNativeAgentExistingStateRecord<NativeAgentPolicyStateRecord>,\n false,\n ),\n policySpends: decodeNativeAgentStateArray(\n row,\n \"policySpends\",\n decodeNativeAgentExistingStateRecord<NativeAgentPolicySpendStateRecord>,\n false,\n ),\n escrows: decodeNativeAgentStateArray(\n row,\n \"escrows\",\n decodeNativeAgentExistingStateRecord<NativeAgentEscrowStateRecord>,\n false,\n ),\n source: expectObject(\n row[\"source\"],\n \"native agent state source\",\n ) as unknown as NativeAgentStateSource,\n };\n}\n\nexport function nativeMarketStateFilterParams(\n filter: NativeMarketStateFilter,\n): Record<string, NativeMarketStateFilterParamValue> {\n const out: Record<string, NativeMarketStateFilterParamValue> = {};\n if (filter.marketId != null) out.marketId = filter.marketId;\n if (filter.orderId != null) out.orderId = filter.orderId;\n if (filter.listingId != null) out.listingId = filter.listingId;\n if (filter.collectionId != null) out.collectionId = filter.collectionId;\n if (filter.account != null) out.account = filter.account;\n if (filter.includeSpotOrders != null) out.includeSpotOrders = filter.includeSpotOrders;\n if (filter.limit != null) out.limit = encodeRpcU64Number(filter.limit, \"limit\");\n return out;\n}\n\nfunction normalizeBlockHeader(value: unknown): BlockHeader | null {\n if (value === null || value === undefined) return null;\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"block header must be an object or null\");\n }\n const h = value as Record<string, unknown>;\n return {\n number: parseRpcBigint(h[\"number\"], \"block header number\"),\n hash: String(h[\"hash\"]),\n parent_hash: String(firstField(h, [\"parent_hash\", \"parentHash\"], \"block header parent hash\")),\n state_root: String(firstField(h, [\"state_root\", \"stateRoot\"], \"block header state root\")),\n timestamp: parseRpcBigint(h[\"timestamp\"], \"block header timestamp\"),\n executionUnitsUsed: parseRpcBigint(\n firstField(\n h,\n [\"executionUnitsUsed\", \"execution_units_used\", \"gas_used\", \"gasUsed\"],\n \"block header execution units used\",\n ),\n \"block header execution units used\",\n ),\n executionUnitLimit: parseRpcBigint(\n firstField(\n h,\n [\"executionUnitLimit\", \"execution_unit_limit\", \"gas_limit\", \"gasLimit\"],\n \"block header execution unit limit\",\n ),\n \"block header execution unit limit\",\n ),\n };\n}\n\nfunction normalizeTransactionReceipt(value: unknown): TransactionReceipt | null {\n if (value === null || value === undefined) return null;\n const r = expectObject(value, \"transaction receipt\");\n return {\n tx_hash: String(\n firstField(r, [\"tx_hash\", \"txHash\", \"transactionHash\"], \"transaction receipt tx hash\"),\n ),\n block_hash: String(\n firstField(r, [\"block_hash\", \"blockHash\"], \"transaction receipt block hash\"),\n ),\n block_number: parseRpcBigint(\n firstField(r, [\"block_number\", \"blockNumber\"], \"transaction receipt block number\"),\n \"transaction receipt block number\",\n ),\n tx_index: parseRpcNumber(\n firstField(r, [\"tx_index\", \"txIndex\", \"transactionIndex\"], \"transaction receipt tx index\"),\n \"transaction receipt tx index\",\n ),\n status: parseRpcNumber(firstField(r, [\"status\"], \"transaction receipt status\"), \"transaction receipt status\"),\n executionUnitsUsed: parseRpcBigint(\n firstField(\n r,\n [\"executionUnitsUsed\", \"execution_units_used\", \"gas_used\", \"gasUsed\"],\n \"transaction receipt execution units used\",\n ),\n \"transaction receipt execution units used\",\n ),\n };\n}\n\nfunction sdkTypedAddress(address: string, kind: AddressKind, label: string): string {\n try {\n return requireTypedAddress(address, kind, label);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw SdkError.malformed(message);\n }\n}\n\nfunction normalizeRoundInfo(value: unknown): RoundInfo {\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"round info must be an object\");\n }\n const row = value as Record<string, unknown>;\n return {\n height: parseRpcBigint(row[\"height\"], \"round height\"),\n };\n}\n\nfunction normalizeExecutionUnitPriceResponse(value: unknown): ExecutionUnitPriceResponse {\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"execution unit price response must be an object\");\n }\n const row = value as Record<string, unknown>;\n return {\n executionUnitPriceLythoshi: parseRpcBigint(\n fieldAlias(row, [\"executionUnitPriceLythoshi\", \"execution_unit_price_lythoshi\"]),\n \"executionUnitPriceLythoshi\",\n ).toString(),\n basePricePerExecutionUnitLythoshi: parseRpcBigint(\n fieldAlias(row, [\n \"basePricePerExecutionUnitLythoshi\",\n \"base_price_per_execution_unit_lythoshi\",\n ]),\n \"basePricePerExecutionUnitLythoshi\",\n ).toString(),\n priorityTipLythoshi: parseRpcBigint(\n fieldAlias(row, [\"priorityTipLythoshi\", \"priority_tip_lythoshi\"]),\n \"priorityTipLythoshi\",\n ).toString(),\n blockNumber: parseRpcNumberNullable(\n fieldAlias(row, [\"blockNumber\", \"block_number\"]),\n \"blockNumber\",\n ),\n source: readStringField(row, [\"source\"], \"execution unit price source\"),\n };\n}\n\nfunction normalizeMempoolSnapshot(value: unknown): MempoolSnapshot {\n if (!value || typeof value !== \"object\") {\n throw SdkError.malformed(\"mempool snapshot must be an object\");\n }\n const row = value as Record<string, unknown>;\n const bytesByClass = row[\"bytes_by_class\"];\n if (!Array.isArray(bytesByClass) || bytesByClass.length !== 7) {\n throw SdkError.malformed(\"mempool bytes_by_class must contain 7 entries\");\n }\n return {\n count_ready: parseRpcBigint(row[\"count_ready\"], \"mempool count_ready\"),\n count_pending: parseRpcBigint(row[\"count_pending\"], \"mempool count_pending\"),\n mailbox_depth: parseRpcBigint(row[\"mailbox_depth\"], \"mempool mailbox_depth\"),\n bytes_by_class: bytesByClass.map((v, i) => parseRpcBigint(v, `mempool bytes_by_class[${i}]`)) as MempoolSnapshot[\"bytes_by_class\"],\n };\n}\n\nfunction fieldAlias(record: Record<string, unknown>, keys: readonly string[]): unknown {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key)) return record[key];\n }\n return undefined;\n}\n\nfunction readStringField(\n record: Record<string, unknown>,\n keys: readonly string[],\n label: string,\n): string {\n const value = fieldAlias(record, keys);\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw SdkError.malformed(`${label} must be a non-empty string`);\n }\n return value.trim();\n}\n\nfunction normalizeCapabilitiesResponse(value: CapabilitiesResponse): CapabilitiesResponse {\n return {\n ...value,\n nativeModuleForwarders: value.nativeModuleForwarders ?? {},\n };\n}\n","/**\n * Network identity for the ethers.js compat shim.\n *\n * Monolythium testnet `chain_id` is **`69420`**.\n * Mainnet chain id is reserved for the genesis ceremony and not yet\n * exported.\n */\n\n/** Monolythium v4.1 testnet chain id. */\nexport const MONOLYTHIUM_TESTNET_CHAIN_ID = 69420n;\n\n/** Network name surfaced to ethers `Network` instances. */\nexport const MONOLYTHIUM_TESTNET_NETWORK_NAME = \"monolythium-testnet\";\n\n/**\n * Built-in network presets for the ethers shim. Callers that point at a\n * different chain id (e.g. a local dev node) construct `MonolythiumProvider`\n * with an explicit `network` option instead.\n */\nexport const MONOLYTHIUM_NETWORKS = {\n testnet: {\n chainId: MONOLYTHIUM_TESTNET_CHAIN_ID,\n name: MONOLYTHIUM_TESTNET_NETWORK_NAME,\n },\n} as const;\n\n/** Configuration object accepted by the ethers shim factory functions. */\nexport interface MonolythiumNetworkConfig {\n /** Numeric chain id (e.g. `69420n`). */\n chainId: bigint;\n /** Human-readable network name. */\n name: string;\n}\n","/**\n * `MonolythiumProvider` — ethers v6 `JsonRpcApiProvider` that routes\n * every call through the native `RpcClient`.\n *\n * `JsonRpcApiProvider` already knows how to translate the rich\n * `_perform(req)` surface into the standard `eth_*` JSON-RPC calls,\n * so we only need to override `_send`: instead of opening its own\n * fetch transport, we reuse the SDK's transport and `lyth_*`-aware\n * error handling.\n *\n * That keeps a single transport in the process — no double-counted\n * connection pools, no duplicated retry/backoff logic, and any\n * future SDK-side feature (auth headers, ws upgrade, registry-based\n * routing) lights up for ethers callers automatically.\n *\n * **SDK-only compat.** This shim never alters the chain's wire. It wraps\n * compatibility JSON-RPC methods in ethers' interface for migration scripts;\n * current v4.1 app paths should use native MRV/RISC-V builders and `lyth_*`\n * read surfaces.\n */\n\nimport {\n type JsonRpcPayload,\n type JsonRpcResult,\n type JsonRpcError,\n JsonRpcApiProvider,\n Network,\n} from \"ethers\";\nimport { RpcClient, type RpcClientOptions } from \"../client.js\";\nimport { SdkError } from \"../error.js\";\nimport {\n MONOLYTHIUM_TESTNET_CHAIN_ID,\n MONOLYTHIUM_TESTNET_NETWORK_NAME,\n type MonolythiumNetworkConfig,\n} from \"./network.js\";\n\n/** Optional configuration for `MonolythiumProvider`. */\nexport interface MonolythiumProviderOptions extends RpcClientOptions {\n /**\n * Override the chain id / network name surfaced to ethers. Defaults\n * to the Monolythium v4.1 testnet preset (`chain_id` `69420`, name\n * `monolythium-testnet`).\n */\n network?: MonolythiumNetworkConfig;\n}\n\n/**\n * `MonolythiumProvider` adapts `mono-core`'s JSON-RPC surface to\n * ethers v6.\n *\n * Use it the same way you'd use any ethers provider:\n *\n * ```ts\n * import { MonolythiumProvider } from \"@monolythium/core-sdk/ethers\";\n *\n * const provider = new MonolythiumProvider(\"https://rpc.testnet.monolythium.com\");\n * const block = await provider.getBlockNumber();\n * ```\n *\n * Legacy ethers actions such as `getBlockNumber`, `getBalance`,\n * `getTransactionReceipt`, `call`, `estimateGas`, and\n * `broadcastTransaction` flow through `RpcClient.call`, so no-EVM profiles\n * may reject unsupported compatibility methods server-side.\n */\nexport class MonolythiumProvider extends JsonRpcApiProvider {\n /** Underlying SDK client. Exposed for callers that want native types. */\n readonly rpcClient: RpcClient;\n\n constructor(\n endpointOrClient: string | RpcClient,\n options: MonolythiumProviderOptions = {},\n ) {\n const network = options.network ?? {\n chainId: MONOLYTHIUM_TESTNET_CHAIN_ID,\n name: MONOLYTHIUM_TESTNET_NETWORK_NAME,\n };\n // `Network`'s constructor takes `BigNumberish` for `chainId`, which\n // accepts a `bigint` directly — `Networkish` (the literal-shape\n // alternative) restricts to `number`, which would clip our `69420n`\n // testnet id when callers point at a chain id past `Number.MAX_SAFE_INTEGER`.\n //\n // We register the name with ethers' global registry on first\n // construction so any later `Network.from(name)` resolves cleanly,\n // but swallow the error when the same name is registered twice\n // (re-instantiation in tests, multiple shim consumers in one\n // process — both legitimate).\n try {\n Network.register(\n network.name,\n () => new Network(network.name, network.chainId),\n );\n } catch (_e) {\n // already registered — fine, fall through.\n }\n super(new Network(network.name, network.chainId));\n\n this.rpcClient =\n typeof endpointOrClient === \"string\"\n ? new RpcClient(endpointOrClient, {\n fetch: options.fetch,\n headers: options.headers,\n })\n : endpointOrClient;\n }\n\n /**\n * Forward a single JSON-RPC method through the SDK transport. Ethers'\n * `_perform` calls this and ethers callers can also call `provider.send`\n * directly to access methods the rich provider interface does not wrap\n * (e.g. `lyth_*`).\n */\n override async _send(\n payload: JsonRpcPayload | Array<JsonRpcPayload>,\n ): Promise<Array<JsonRpcResult | JsonRpcError>> {\n const calls = Array.isArray(payload) ? payload : [payload];\n return Promise.all(calls.map((p) => this.#sendOne(p)));\n }\n\n async #sendOne(p: JsonRpcPayload): Promise<JsonRpcResult | JsonRpcError> {\n try {\n const params = Array.isArray(p.params)\n ? p.params\n : p.params === undefined\n ? []\n : (p.params as unknown[]);\n const result = await this.rpcClient.call<unknown>(p.method, params);\n return { id: p.id, result };\n } catch (e) {\n if (e instanceof SdkError && e.kind === \"rpc\") {\n return {\n id: p.id,\n error: {\n code: e.code ?? -32603,\n message: e.message,\n data: e.data,\n },\n };\n }\n // Transport / malformed / endpoint errors don't have a JSON-RPC\n // shape — surface them as a generic internal error so ethers'\n // own error wrapper can pick them up cleanly.\n const msg = (e as Error)?.message ?? String(e);\n return {\n id: p.id,\n error: { code: -32603, message: `${msg}` },\n };\n }\n }\n}\n","/**\n * `MonolythiumSigner` — ethers v6 `AbstractSigner` adapter.\n *\n * Two backend strategies are supported, both via the same external\n * surface — `getAddress`, `signTransaction`, `signMessage`,\n * `signTypedData`:\n *\n * 1. **`fromEthersWallet`** — wraps a normal `ethers.Wallet`\n * (secp256k1). Useful for tests, scripts, and any path where the\n * user already has an Ethereum-style key. The SDK does not store\n * the key — the wallet does.\n *\n * 2. **`MonolythiumSignerBackend`** — generic interface a non-ethers\n * backend (keychain, hardware wallet, future ML-DSA-65 signer)\n * implements to plug into ethers without forcing the SDK to take\n * a hard ethers dependency on either the chain side or the\n * consumer side.\n *\n * Native Mono address derivation is ADR-0038:\n * `BLAKE3(\"MONO_ADDRESS_BLAKE3_20_V1\" || algo_id_be_u16 ||\n * canonical_pubkey_bytes)[0..20]`. `fromEthersWallet` preserves the\n * wrapped ethers address only for the compatibility signer path; native\n * ML-DSA-65 callers should use the crypto helpers directly.\n *\n * **What the shim is not.** This is SDK-level compat (per\n * `feedback_no_ethereum_wire_retrofit.md`). The chain's protocol-native\n * signing path is ML-DSA-65 (Law §2.1); ethers cannot produce ML-DSA\n * signatures, and the chain accepts secp256k1 only via the\n * crypto-agile `SignedTransaction` envelope. Use\n * `MonolythiumSignerBackend` to plug a native ML-DSA path in.\n */\n\nimport {\n AbstractSigner,\n type BaseWallet,\n type Provider,\n type Signer as EthersSigner,\n type TransactionRequest,\n type TypedDataDomain,\n type TypedDataField,\n} from \"ethers\";\n\n/**\n * Backend the `MonolythiumSigner` delegates signing to.\n *\n * The intent is to let consumers wire up any signing source — local\n * keystore, OS keychain, hardware wallet, or a future ML-DSA-65\n * adapter — without the shim forcing a particular implementation.\n *\n * Every method's return shape mirrors what ethers'\n * `AbstractSigner` callers expect, so the backend can compose with\n * any tooling built on ethers.\n */\nexport interface MonolythiumSignerBackend {\n /** Resolves to the 20-byte 0x-hex address (Law §2.6 derivation). */\n getAddress(): Promise<string>;\n\n /**\n * Resolves to a fully-encoded raw signed transaction (a 0x-hex\n * string). For secp256k1 this is the canonical EIP-1559 RLP that\n * `eth_sendRawTransaction` expects.\n */\n signTransaction(tx: TransactionRequest): Promise<string>;\n\n /**\n * Resolves to an EIP-191 personal-sign signature (`0x` + 65 bytes\n * for secp256k1 / variable for non-recoverable algorithms).\n */\n signMessage(message: string | Uint8Array): Promise<string>;\n\n /** Resolves to an EIP-712 typed-data signature. */\n signTypedData(\n domain: TypedDataDomain,\n types: Record<string, Array<TypedDataField>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n}\n\n/**\n * `MonolythiumSigner` — ethers v6 `Signer` for the Monolythium chain.\n *\n * Construct one of three ways:\n *\n * 1. `MonolythiumSigner.fromEthersWallet(wallet, provider)` — the\n * fastest path; wraps a normal `ethers.Wallet`.\n * 2. `new MonolythiumSigner(backend, provider)` — supply any object\n * implementing `MonolythiumSignerBackend`.\n *\n * The signer is compatible with ethers v6 migration flows: it can be passed\n * anywhere a `Signer` is accepted and supports legacy contract deploy/call\n * helpers plus `provider.broadcastTransaction(signed)`. New v4.1 app paths\n * should use native MRV/RISC-V builders instead.\n */\nexport class MonolythiumSigner extends AbstractSigner<Provider | null> {\n readonly #backend: MonolythiumSignerBackend;\n\n constructor(backend: MonolythiumSignerBackend, provider?: Provider | null) {\n super(provider ?? null);\n this.#backend = backend;\n }\n\n /**\n * Wrap any ethers v6 `BaseWallet` (the parent class of `Wallet`,\n * `HDNodeWallet`, and friends) so callers don't have to write a\n * `MonolythiumSignerBackend` for the common test / dev path.\n *\n * Both `new Wallet(privateKey)` and `Wallet.createRandom()` /\n * `HDNodeWallet.fromMnemonic(...)` are accepted.\n */\n static fromEthersWallet(\n wallet: BaseWallet,\n provider?: Provider | null,\n ): MonolythiumSigner {\n const backend: MonolythiumSignerBackend = {\n getAddress: async () => wallet.address,\n signTransaction: (tx) => wallet.signTransaction(tx),\n signMessage: (message) => wallet.signMessage(message),\n signTypedData: (domain, types, value) =>\n wallet.signTypedData(domain, types, value),\n };\n return new MonolythiumSigner(backend, provider);\n }\n\n override async getAddress(): Promise<string> {\n return this.#backend.getAddress();\n }\n\n override connect(provider: Provider | null): EthersSigner {\n return new MonolythiumSigner(this.#backend, provider);\n }\n\n override async signTransaction(tx: TransactionRequest): Promise<string> {\n return this.#backend.signTransaction(tx);\n }\n\n override async signMessage(message: string | Uint8Array): Promise<string> {\n return this.#backend.signMessage(message);\n }\n\n override async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, Array<TypedDataField>>,\n value: Record<string, unknown>,\n ): Promise<string> {\n return this.#backend.signTypedData(domain, types, value);\n }\n}\n","/**\n * Tx wire translation between ethers.js and `mono-core`.\n *\n * The chain natively accepts EIP-1559-shape EVM transactions on the\n * `Tx::Evm` (kind tag `0x01`) wire path — a `SignedTransaction` payload\n * carries the legacy EIP-1559 envelope plus the secp256k1 signature.\n * That makes the round-trip simple: ethers produces the canonical\n * EIP-1559 RLP, the client posts it via `eth_sendRawTransaction`, the\n * chain decodes it, and the receipt comes back through the same\n * `eth_getTransactionReceipt` shape ethers expects.\n *\n * Two notes for any future maintainer:\n *\n * 1. **No chain-level Ethereum retrofit.** This shim is SDK-only — see\n * `feedback_no_ethereum_wire_retrofit.md`. The chain keeps its\n * custom envelope and native tx hash for the protocol-native path\n * (ML-DSA-65 signing, native tx kinds beyond EVM). The shim only\n * spans the **EIP-1559 EVM subset** of the chain's tx surface.\n * 2. **Fields ethers does not see.** Monolythium-specific extension\n * fields (privacy flags, native tx kinds, ML-DSA-65 signatures) are\n * intentionally dropped by these helpers. Callers that need those\n * surfaces use the native SDK signer trait, not the ethers shim.\n */\n\nimport type { CallRequest } from \"../bindings/CallRequest.js\";\nimport type { TransactionReceipt as MonoTransactionReceipt } from \"../bindings/TransactionReceipt.js\";\n\n/**\n * The EIP-1559 subset of fields ethers' `TransactionRequest` carries\n * across the shim. We don't import ethers' type here so the shim can be\n * compiled (and its types re-exported) even when ethers isn't installed\n * — ethers is a peerDependency, not a hard dependency.\n */\nexport interface EthersTxRequestSubset {\n to?: string | null;\n from?: string | null;\n nonce?: number | bigint | null;\n gasLimit?: bigint | string | null;\n gasPrice?: bigint | string | null;\n maxFeePerGas?: bigint | string | null;\n maxPriorityFeePerGas?: bigint | string | null;\n value?: bigint | string | null;\n data?: string | null;\n chainId?: bigint | number | null;\n type?: number | null;\n}\n\n/** `0x`-prefixed hex helpers — kept local so this module has no import surface. */\nfunction toHexQuantity(v: bigint | number | string | null | undefined): string | undefined {\n if (v === null || v === undefined) return undefined;\n if (typeof v === \"string\") {\n if (v.startsWith(\"0x\") || v.startsWith(\"0X\")) return v;\n // Ethers occasionally hands us decimal strings — be lenient.\n return `0x${BigInt(v).toString(16)}`;\n }\n if (typeof v === \"number\") return `0x${v.toString(16)}`;\n return `0x${v.toString(16)}`;\n}\n\n/**\n * Translate ethers' `TransactionRequest` into the wire shape the\n * `mono-core` JSON-RPC accepts for `eth_call` / `eth_estimateGas`.\n *\n * Returns the SDK's `CallRequest` shape (which mirrors the chain's\n * accepted `eth_call` argument). Round-trips losslessly for the\n * EIP-1559 EVM subset; Monolythium-specific extension fields are\n * intentionally not surfaced here.\n */\nexport function translateTxIn(req: EthersTxRequestSubset): CallRequest {\n const out: CallRequest = {};\n if (req.from !== undefined && req.from !== null) out.from = req.from;\n if (req.to !== undefined && req.to !== null) out.to = req.to;\n const gas = toHexQuantity(req.gasLimit);\n if (gas !== undefined) out.gas = gas;\n // Use `gasPrice` for legacy / non-EIP-1559 paths. EIP-1559 priority +\n // fee fields are not part of the v0.0.x server's `eth_call` shape; the\n // chain ignores them on dry-runs.\n const gasPrice = toHexQuantity(req.gasPrice);\n if (gasPrice !== undefined) out.gasPrice = gasPrice;\n const value = toHexQuantity(req.value);\n if (value !== undefined) out.value = value;\n if (req.data !== undefined && req.data !== null) out.data = req.data;\n return out;\n}\n\n/**\n * The ethers v6 wire shape for `eth_getTransactionReceipt`. We hand-roll\n * this rather than importing ethers' internal types because the shim\n * has to compile without ethers installed (peerDependency).\n *\n * Field naming and casing match what `JsonRpcApiProvider._perform` expects\n * back — the provider then normalises into ethers' rich\n * `TransactionReceipt` for callers.\n */\nexport interface EthersReceiptShape {\n transactionHash: string;\n blockHash: string;\n blockNumber: string; // 0x-hex\n transactionIndex: string; // 0x-hex\n status: string; // \"0x0\" | \"0x1\"\n gasUsed: string; // 0x-hex\n cumulativeGasUsed: string; // 0x-hex\n effectiveGasPrice: string; // 0x-hex\n contractAddress: string | null;\n from: string;\n to: string | null;\n type: string; // 0x-hex\n logsBloom: string; // 0x-hex 256 bytes\n logs: unknown[];\n}\n\n/**\n * Translate `mono-core`'s native `TransactionReceipt` into the wire\n * shape ethers expects. Required for `eth_getTransactionReceipt` to\n * surface a usable `TransactionResponse` to ethers callers.\n *\n * The chain's receipt today is intentionally narrow — log emission,\n * cumulative execution-unit aggregation, and effective-fee disclosure are\n * tracked OI items. This translator fills in zero-equivalent values for\n * those gaps; callers that need the full native surface consume the SDK\n * receipt shape directly.\n */\nexport function translateReceiptOut(\n monoReceipt: MonoTransactionReceipt,\n fromAddress: string | null,\n toAddress: string | null,\n): EthersReceiptShape {\n return {\n transactionHash: monoReceipt.tx_hash,\n blockHash: monoReceipt.block_hash,\n blockNumber: `0x${BigInt(monoReceipt.block_number).toString(16)}`,\n transactionIndex: `0x${monoReceipt.tx_index.toString(16)}`,\n status: monoReceipt.status === 1 ? \"0x1\" : \"0x0\",\n gasUsed: `0x${BigInt(monoReceipt.executionUnitsUsed).toString(16)}`,\n cumulativeGasUsed: `0x${BigInt(monoReceipt.executionUnitsUsed).toString(16)}`,\n effectiveGasPrice: \"0x0\",\n contractAddress: null,\n from: fromAddress ?? \"0x0000000000000000000000000000000000000000\",\n to: toAddress,\n type: \"0x2\",\n logsBloom: `0x${\"0\".repeat(512)}`,\n logs: [],\n };\n}\n\n/**\n * Translate `mono-core`'s `BlockHeader` into the ethers v6 wire shape\n * for `eth_getBlockByNumber` / `eth_getBlockByHash`.\n *\n * The chain's block header is intentionally narrower than Ethereum's\n * — it omits fields that don't exist in Monolythium (uncles, mix hash,\n * difficulty, nonce, sha3Uncles). This translator emits zero-valued\n * stand-ins so ethers' normaliser does not throw. Callers needing the\n * authoritative shape import the native `BlockHeader` from the SDK.\n */\nexport interface EthersBlockShape {\n number: string;\n hash: string;\n parentHash: string;\n timestamp: string;\n gasUsed: string;\n gasLimit: string;\n stateRoot: string;\n miner: string;\n difficulty: string;\n nonce: string;\n baseFeePerGas: string | null;\n extraData: string;\n mixHash: string;\n transactions: string[];\n transactionsRoot: string;\n receiptsRoot: string;\n logsBloom: string;\n sha3Uncles: string;\n uncles: string[];\n size: string;\n}\n\n/**\n * Translate `mono-core`'s `BlockHeader` to the ethers wire shape.\n * `transactions` defaults to an empty list — the SDK's\n * `eth_getBlockByNumber` does not yet return tx hashes; once Stage 1+\n * surfaces them, callers update this translator.\n */\nexport function translateBlockOut(header: {\n number: bigint;\n hash: string;\n parent_hash: string;\n state_root: string;\n timestamp: bigint;\n executionUnitsUsed: bigint;\n executionUnitLimit: bigint;\n}): EthersBlockShape {\n return {\n number: `0x${header.number.toString(16)}`,\n hash: header.hash,\n parentHash: header.parent_hash,\n timestamp: `0x${header.timestamp.toString(16)}`,\n gasUsed: `0x${header.executionUnitsUsed.toString(16)}`,\n gasLimit: `0x${header.executionUnitLimit.toString(16)}`,\n stateRoot: header.state_root,\n miner: \"0x0000000000000000000000000000000000000000\",\n difficulty: \"0x0\",\n nonce: \"0x0000000000000000\",\n baseFeePerGas: null,\n extraData: \"0x\",\n mixHash: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n transactions: [],\n transactionsRoot: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n receiptsRoot: \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n logsBloom: `0x${\"0\".repeat(512)}`,\n sha3Uncles: \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n uncles: [],\n size: \"0x0\",\n };\n}\n"]}
|