@qorechain/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/networks.ts","../src/query/http.ts","../src/query/rest.ts","../src/query/jsonrpc.ts","../src/query/qor.ts","../src/tx/fees.ts","../src/tx/builder.ts","../src/cosmwasm/index.ts","../src/query/crossvm.ts","../src/client.ts","../src/utils/denom.ts","../src/utils/address.ts","../src/accounts/wallet.ts","../src/accounts/pqc-algorithm.ts","../src/accounts/pqc.ts","../src/tx/signer-adapter.ts","../src/tx/hybrid.ts","../src/tx/hybrid-tx.ts","../src/index.ts"],"names":["bip39Generate","bip39Validate","HDKey","Slip10HDKey","TxBody"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAM,MAAA,GAAyB;AAAA,EAC7B,OAAA,EAAS,KAAA;AAAA,EACT,SAAA,EAAW,YAAA;AAAA,EACX,SAAA,EAAW;AACb,CAAA;AAEA,IAAM,IAAA,GAAiB;AAAA,EACrB,OAAA,EAAS,KAAA;AAAA,EACT,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU;AACZ,CAAA;AAGO,IAAM,QAAA,GAA+C;AAAA,EAC1D,OAAA,EAAS;AAAA,IACP,IAAA,EAAM,SAAA;AAAA,IACN,IAAA,EAAM,IAAA;AAAA,IACN,OAAA,EAAS,iBAAA;AAAA,IACT,MAAA,EAAQ,MAAA;AAAA,IACR,IAAA,EAAM,IAAA;AAAA,IACN,SAAA,EAAW;AAAA,MACT,IAAA,EAAM,uBAAA;AAAA,MACN,IAAA,EAAM,uBAAA;AAAA,MACN,GAAA,EAAK,wBAAA;AAAA,MACL,MAAA,EAAQ,uBAAA;AAAA,MACR,KAAA,EAAO,qBAAA;AAAA,MACP,MAAA,EAAQ;AAAA;AACV,GACF;AAAA,EACA,OAAA,EAAS;AAAA,IACP,IAAA,EAAM,SAAA;AAAA,IACN,IAAA,EAA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AAI;AAAA,KACd;AAAA,EACF;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,SAAA,CAAU,eAAA,CAAgB,MAAM,UAAU,CAAA;AAC7D,EAAA,OAAO,EAAE,eAAA,EAAiB,IAAA,EAAM,IAAA,EAAM,CAAA,EAAE;AAC1C;;;AClUO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Network presets for the QoreChain SDK.\n *\n * Both the `testnet` and `mainnet` presets are fully populated and live. Their\n * endpoints default to localhost ports so the SDK works out of the box against a\n * locally running node; callers override these with real hostnames when creating\n * a client. {@link getNetwork} returns either preset.\n */\n\n/** Bech32 human-readable prefixes used across QoreChain address types. */\nexport interface Bech32Prefixes {\n /** Prefix for account addresses (e.g. `qor1...`). */\n account: string;\n /** Prefix for validator operator addresses (e.g. `qorvaloper1...`). */\n validator: string;\n /** Prefix for validator consensus addresses (e.g. `qorvalcons1...`). */\n consensus: string;\n}\n\n/** Display and base denomination metadata for the network's staking coin. */\nexport interface CoinInfo {\n /** Human-facing denomination (e.g. `QOR`). */\n display: string;\n /** Base (smallest) denomination used on-chain (e.g. `uqor`). */\n base: string;\n /** Decimal exponent relating base to display (1 display = 10^exponent base). */\n exponent: number;\n}\n\n/** Service endpoints for talking to a network across its supported VMs. */\nexport interface NetworkEndpoints {\n /** Cosmos SDK REST (LCD) endpoint. */\n rest: string;\n /** Cosmos SDK gRPC endpoint. */\n grpc: string;\n /** Consensus RPC endpoint. */\n rpc: string;\n /** EVM JSON-RPC HTTP endpoint. */\n evmRpc: string;\n /** EVM JSON-RPC WebSocket endpoint. */\n evmWs: string;\n /** SVM JSON-RPC endpoint. */\n svmRpc: string;\n}\n\n/** A fully described network preset. */\nexport interface NetworkConfig {\n /** Canonical preset name. */\n name: string;\n /** Whether the network is live and usable without custom endpoints. */\n live: boolean;\n /** Chain ID. */\n chainId: string;\n /** Bech32 prefixes for address encoding. */\n bech32: Bech32Prefixes;\n /** Staking coin metadata. */\n coin: CoinInfo;\n /** Default endpoints. */\n endpoints: NetworkEndpoints;\n}\n\n/** Known network preset names. */\nexport type NetworkName = \"testnet\" | \"mainnet\";\n\n/**\n * QoreChain uses the same token and address prefixes on every network, so these\n * are shared (not invented) values across the presets below.\n */\nconst BECH32: Bech32Prefixes = {\n account: \"qor\",\n validator: \"qorvaloper\",\n consensus: \"qorvalcons\",\n};\n\nconst COIN: CoinInfo = {\n display: \"QOR\",\n base: \"uqor\",\n exponent: 6,\n};\n\n/** The set of built-in network presets, keyed by name. */\nexport const NETWORKS: Record<NetworkName, NetworkConfig> = {\n testnet: {\n name: \"testnet\",\n live: true,\n chainId: \"qorechain-diana\",\n bech32: BECH32,\n coin: COIN,\n endpoints: {\n rest: \"http://localhost:1317\",\n grpc: \"http://localhost:9090\",\n rpc: \"http://localhost:26657\",\n evmRpc: \"http://localhost:8545\",\n evmWs: \"ws://localhost:8546\",\n svmRpc: \"http://localhost:8899\",\n },\n },\n mainnet: {\n name: \"mainnet\",\n live: true,\n chainId: \"qorechain-vladi\",\n bech32: BECH32,\n coin: COIN,\n endpoints: {\n rest: \"http://localhost:1317\",\n grpc: \"http://localhost:9090\",\n rpc: \"http://localhost:26657\",\n evmRpc: \"http://localhost:8545\",\n evmWs: \"ws://localhost:8546\",\n svmRpc: \"http://localhost:8899\",\n },\n },\n};\n\n/**\n * Resolve a network preset by name.\n *\n * @returns The requested {@link NetworkConfig}, guaranteed to be live and usable.\n */\nexport function getNetwork(name: NetworkName): NetworkConfig {\n return NETWORKS[name];\n}\n\n/** List the known network preset names without triggering any liveness check. */\nexport function listNetworks(): NetworkName[] {\n return Object.keys(NETWORKS) as NetworkName[];\n}\n","/**\n * Shared HTTP transport for the read/query clients.\n *\n * Provides two primitives — {@link getJson} for REST GETs and\n * {@link postJsonRpc} for JSON-RPC POSTs — both built on the global `fetch`.\n * `fetch` is injectable so tests can mock the network entirely; nothing here\n * ever performs a real request on its own.\n *\n * Failures surface as a typed {@link QoreHttpError} (non-2xx HTTP responses).\n * Transient transport failures (5xx and network errors) are retried with a\n * small fixed backoff up to a configurable count; 4xx responses are never\n * retried. Each attempt is bounded by an `AbortSignal`-driven timeout.\n */\n\n/** A `fetch`-compatible function. Defaults to `globalThis.fetch`. */\nexport type FetchLike = (\n input: string,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** A JSON-serializable value usable as a query-string parameter. */\nexport type QueryValue = string | number | boolean | undefined | null;\n\n/** Options shared by all HTTP helpers. */\nexport interface HttpOptions {\n /** Injectable `fetch`. Defaults to `globalThis.fetch`. */\n fetch?: FetchLike;\n /** Per-attempt timeout in milliseconds. Defaults to 30000. `0` disables it. */\n timeoutMs?: number;\n /** Number of retries after the initial attempt for retryable errors. Defaults to 2. */\n retries?: number;\n /** Fixed delay between retries in milliseconds. Defaults to 250. */\n retryDelayMs?: number;\n /** Extra request headers, merged over the defaults. */\n headers?: Record<string, string>;\n}\n\n/** Options for {@link getJson}, adding query-string parameters. */\nexport interface GetJsonOptions extends HttpOptions {\n /** Query parameters; `undefined`/`null` values are omitted. */\n query?: Record<string, QueryValue>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_RETRIES = 2;\nconst DEFAULT_RETRY_DELAY_MS = 250;\n\n/** Thrown when an HTTP response has a non-2xx status. */\nexport class QoreHttpError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number;\n /** The URL that was requested. */\n readonly url: string;\n /** Raw response body text, when available. */\n readonly body?: string;\n\n constructor(status: number, url: string, body?: string) {\n super(`HTTP ${status} for ${url}`);\n this.name = \"QoreHttpError\";\n this.status = status;\n this.url = url;\n this.body = body;\n Object.setPrototypeOf(this, QoreHttpError.prototype);\n }\n}\n\nfunction resolveFetch(opts?: HttpOptions): FetchLike {\n const f = opts?.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!f) {\n throw new Error(\n \"no fetch implementation available — pass `fetch` in the client options\",\n );\n }\n return f;\n}\n\n/** Append query params to a URL, skipping `undefined`/`null` values. */\nexport function buildUrl(base: string, query?: Record<string, QueryValue>): string {\n if (!query) return base;\n const parts: string[] = [];\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n }\n if (parts.length === 0) return base;\n const sep = base.includes(\"?\") ? \"&\" : \"?\";\n return `${base}${sep}${parts.join(\"&\")}`;\n}\n\n/** Join a base URL and a path without producing double slashes. */\nexport function joinUrl(base: string, path: string): string {\n const left = base.replace(/\\/+$/, \"\");\n const right = path.replace(/^\\/+/, \"\");\n return `${left}/${right}`;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** 5xx responses are retryable; 4xx are not. */\nfunction isRetryableStatus(status: number): boolean {\n return status >= 500 && status < 600;\n}\n\n/**\n * Run one `fetch` attempt with an abort-driven timeout, parsing the JSON body\n * on success and throwing {@link QoreHttpError} on a non-2xx response.\n */\nasync function attempt<T>(\n url: string,\n init: RequestInit,\n fetchImpl: FetchLike,\n timeoutMs: number,\n): Promise<T> {\n const controller = timeoutMs > 0 ? new AbortController() : undefined;\n const timer =\n controller && timeoutMs > 0\n ? setTimeout(() => controller.abort(), timeoutMs)\n : undefined;\n try {\n const res = await fetchImpl(url, {\n ...init,\n signal: controller?.signal,\n });\n if (!res.ok) {\n let body: string | undefined;\n try {\n body = await res.text();\n } catch {\n body = undefined;\n }\n throw new QoreHttpError(res.status, url, body);\n }\n return (await res.json()) as T;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/** Execute `attempt` with retry on retryable HTTP/transport errors. */\nasync function withRetry<T>(\n url: string,\n init: RequestInit,\n opts: HttpOptions | undefined,\n): Promise<T> {\n const fetchImpl = resolveFetch(opts);\n const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const retries = opts?.retries ?? DEFAULT_RETRIES;\n const retryDelayMs = opts?.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n\n let lastError: unknown;\n for (let i = 0; i <= retries; i++) {\n try {\n return await attempt<T>(url, init, fetchImpl, timeoutMs);\n } catch (err) {\n lastError = err;\n const retryable =\n err instanceof QoreHttpError ? isRetryableStatus(err.status) : true;\n if (!retryable || i === retries) throw err;\n if (retryDelayMs > 0) await delay(retryDelayMs);\n }\n }\n throw lastError;\n}\n\n/**\n * Perform a GET request and parse the JSON response.\n *\n * @param url - Fully-qualified URL (without query string).\n * @param opts - Query params, injectable `fetch`, timeout, and retry settings.\n * @throws {@link QoreHttpError} on a non-2xx response.\n */\nexport function getJson<T>(url: string, opts?: GetJsonOptions): Promise<T> {\n const fullUrl = buildUrl(url, opts?.query);\n const init: RequestInit = {\n method: \"GET\",\n headers: { accept: \"application/json\", ...(opts?.headers ?? {}) },\n };\n return withRetry<T>(fullUrl, init, opts);\n}\n\n/**\n * POST a JSON-RPC body and parse the JSON response.\n *\n * This handles only the HTTP layer; JSON-RPC error envelopes are interpreted by\n * the {@link JsonRpcClient}.\n *\n * @throws {@link QoreHttpError} on a non-2xx response.\n */\nexport function postJsonRpc<T>(\n url: string,\n body: unknown,\n opts?: HttpOptions,\n): Promise<T> {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n ...(opts?.headers ?? {}),\n },\n body: JSON.stringify(body),\n };\n return withRetry<T>(url, init, opts);\n}\n","/**\n * REST (LCD) read client for QoreChain.\n *\n * Wraps the standard Cosmos SDK bank endpoints plus QoreChain's custom module\n * read routes under `/qorechain/<module>/v1/...`. All requests go through the\n * shared {@link getJson} helper, so `fetch` is injectable and failures surface\n * as {@link QoreHttpError}.\n *\n * Response shapes are modeled only where they are simple and stable (e.g. bank\n * balances); richer module responses are returned as a caller-supplied generic\n * defaulting to {@link Record}<string, unknown> rather than over-modeled here.\n */\n\nimport type { Coin } from \"@cosmjs/amino\";\nimport {\n getJson,\n joinUrl,\n type FetchLike,\n type HttpOptions,\n type QueryValue,\n} from \"./http\";\n\n/**\n * A Cosmos coin amount. Re-exported from `@cosmjs/amino` so the SDK has a single\n * canonical `Coin` type shared across query, fee, and tx code (no duplicated\n * structural definition).\n */\nexport type { Coin };\n\n/** Cosmos pagination response metadata. */\nexport interface PageResponse {\n next_key: string | null;\n total?: string;\n}\n\n/** Response of the all-balances endpoint. */\nexport interface AllBalancesResponse {\n balances: Coin[];\n pagination?: PageResponse;\n}\n\n/** Response of the single-denom balance endpoint. */\nexport interface BalanceResponse {\n balance: Coin;\n}\n\n/** Cosmos-style key/limit pagination input. */\nexport interface Pagination {\n key?: string;\n limit?: number;\n}\n\n/** Options accepted by paginated list endpoints. */\nexport interface PaginatedOptions {\n pagination?: Pagination;\n}\n\n/** Options for {@link RestClient}. */\nexport type RestClientOptions = HttpOptions;\n\n/** Relative urgency of a fee estimate. */\nexport type FeeUrgency = \"fast\" | \"normal\" | \"slow\";\n\n/** Map a {@link Pagination} into Cosmos `pagination.*` query params. */\nfunction paginationQuery(p?: Pagination): Record<string, QueryValue> {\n const q: Record<string, QueryValue> = {};\n if (p?.key !== undefined) q[\"pagination.key\"] = p.key;\n if (p?.limit !== undefined) q[\"pagination.limit\"] = p.limit;\n return q;\n}\n\n/** Cosmos + QoreChain REST read client. */\nexport class RestClient {\n private readonly baseUrl: string;\n private readonly opts: RestClientOptions;\n\n /**\n * @param baseUrl - The network's REST endpoint (e.g. `endpoints.rest`).\n * @param opts - Injectable `fetch`, timeout, and retry settings.\n */\n constructor(baseUrl: string, opts: RestClientOptions = {}) {\n this.baseUrl = baseUrl;\n this.opts = opts;\n }\n\n /** Injectable fetch passthrough so the escape hatch reuses the same transport. */\n private get fetchImpl(): FetchLike | undefined {\n return this.opts.fetch;\n }\n\n /**\n * Generic GET escape hatch for any documented REST route.\n *\n * @param path - Path beginning with `/` (e.g. `/qorechain/foo/v1/bar`).\n * Embedded path params must be URL-encoded by the caller.\n * @param query - Optional query parameters.\n */\n get<T = Record<string, unknown>>(\n path: string,\n query?: Record<string, QueryValue>,\n ): Promise<T> {\n return getJson<T>(joinUrl(this.baseUrl, path), {\n ...this.opts,\n query,\n });\n }\n\n // --- Standard Cosmos bank ------------------------------------------------\n\n /** All balances of `address` (`/cosmos/bank/v1beta1/balances/{address}`). */\n getAllBalances(\n address: string,\n opts?: PaginatedOptions,\n ): Promise<AllBalancesResponse> {\n return this.get<AllBalancesResponse>(\n `/cosmos/bank/v1beta1/balances/${encodeURIComponent(address)}`,\n paginationQuery(opts?.pagination),\n );\n }\n\n /** Balance of `address` in `denom` (`.../balances/{address}/by_denom`). */\n getBalance(address: string, denom: string): Promise<BalanceResponse> {\n return this.get<BalanceResponse>(\n `/cosmos/bank/v1beta1/balances/${encodeURIComponent(address)}/by_denom`,\n { denom },\n );\n }\n\n // --- Custom QoreChain module reads ---------------------------------------\n\n /** QCAI fee/network stats (`/qorechain/ai/v1/stats`). */\n getAiStats<T = Record<string, unknown>>(): Promise<T> {\n return this.get<T>(\"/qorechain/ai/v1/stats\");\n }\n\n /** QCAI fee estimate for an urgency level (`/qorechain/ai/v1/fee-estimate`). */\n getFeeEstimate<T = Record<string, unknown>>(urgency: FeeUrgency): Promise<T> {\n return this.get<T>(\"/qorechain/ai/v1/fee-estimate\", { urgency });\n }\n\n /** Supported bridge chains (`/qorechain/bridge/v1/chains`). */\n getBridgeChains<T = Record<string, unknown>>(): Promise<T> {\n return this.get<T>(\"/qorechain/bridge/v1/chains\");\n }\n\n /** PQC account record (`/qorechain/pqc/v1/accounts/{address}`). */\n getPqcAccount<T = Record<string, unknown>>(address: string): Promise<T> {\n return this.get<T>(`/qorechain/pqc/v1/accounts/${encodeURIComponent(address)}`);\n }\n\n /** Validator reputation (`/qorechain/reputation/v1/validators/{address}`). */\n getReputation<T = Record<string, unknown>>(\n validatorAddress: string,\n ): Promise<T> {\n return this.get<T>(\n `/qorechain/reputation/v1/validators/${encodeURIComponent(validatorAddress)}`,\n );\n }\n\n /** Token burn statistics (`/qorechain/burn/v1/stats`). */\n getBurnStats<T = Record<string, unknown>>(): Promise<T> {\n return this.get<T>(\"/qorechain/burn/v1/stats\");\n }\n\n /** xQORE staking position (`/qorechain/xqore/v1/position/{address}`). */\n getXqorePosition<T = Record<string, unknown>>(address: string): Promise<T> {\n return this.get<T>(`/qorechain/xqore/v1/position/${encodeURIComponent(address)}`);\n }\n\n /** Current inflation rate (`/qorechain/inflation/v1/rate`). */\n getInflationRate<T = Record<string, unknown>>(): Promise<T> {\n return this.get<T>(\"/qorechain/inflation/v1/rate\");\n }\n}\n","/**\n * Generic JSON-RPC 2.0 client.\n *\n * Manages request ids (auto-incrementing per client), serializes the standard\n * `{ jsonrpc, id, method, params }` envelope, and maps JSON-RPC error responses\n * to a typed {@link JsonRpcError}. It is the transport base for both the EVM\n * `eth_*`/`net_*`/`web3_*` methods and the QoreChain `qor_*` namespace.\n *\n * The underlying `fetch` is injectable via {@link HttpOptions} so callers and\n * tests can supply their own transport.\n */\n\nimport { postJsonRpc, type HttpOptions } from \"./http\";\n\n/** A JSON-RPC 2.0 error object. */\nexport interface JsonRpcErrorObject {\n code: number;\n message: string;\n data?: unknown;\n}\n\n/** A JSON-RPC 2.0 response envelope. */\nexport interface JsonRpcResponse<T> {\n jsonrpc: \"2.0\";\n id: number | string | null;\n result?: T;\n error?: JsonRpcErrorObject;\n}\n\n/** Thrown when a JSON-RPC response carries an `error` member. */\nexport class JsonRpcError extends Error {\n /** JSON-RPC error code. */\n readonly code: number;\n /** Optional implementation-defined error data. */\n readonly data?: unknown;\n\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = \"JsonRpcError\";\n this.code = code;\n this.data = data;\n Object.setPrototypeOf(this, JsonRpcError.prototype);\n }\n}\n\n/** Options for {@link JsonRpcClient}. */\nexport type JsonRpcClientOptions = HttpOptions;\n\n/** A minimal JSON-RPC 2.0 client over HTTP POST. */\nexport class JsonRpcClient {\n protected readonly url: string;\n protected readonly opts: JsonRpcClientOptions;\n private nextId = 1;\n\n constructor(url: string, opts: JsonRpcClientOptions = {}) {\n this.url = url;\n this.opts = opts;\n }\n\n /**\n * Invoke a JSON-RPC method and return its `result`.\n *\n * @param method - Wire method name (e.g. `\"eth_chainId\"`).\n * @param params - Positional params; defaults to an empty array.\n * @throws {@link JsonRpcError} when the response contains an `error`.\n * @throws {@link QoreHttpError} on a non-2xx transport response.\n */\n async call<T>(method: string, params: unknown[] = []): Promise<T> {\n const id = this.nextId++;\n const body = { jsonrpc: \"2.0\", id, method, params };\n const res = await postJsonRpc<JsonRpcResponse<T>>(this.url, body, this.opts);\n if (res.error) {\n throw new JsonRpcError(res.error.code, res.error.message, res.error.data);\n }\n return res.result as T;\n }\n\n /** `eth_chainId` — the chain id as a hex quantity string. */\n ethChainId(): Promise<string> {\n return this.call<string>(\"eth_chainId\", []);\n }\n\n /** `eth_blockNumber` — the latest block height as a hex quantity string. */\n ethBlockNumber(): Promise<string> {\n return this.call<string>(\"eth_blockNumber\", []);\n }\n\n /** `eth_getBalance` — wei balance of `address` as a hex quantity string. */\n ethGetBalance(address: string, block: string = \"latest\"): Promise<string> {\n return this.call<string>(\"eth_getBalance\", [address, block]);\n }\n\n /** `net_version` — the network id as a decimal string. */\n netVersion(): Promise<string> {\n return this.call<string>(\"net_version\", []);\n }\n\n /** `web3_clientVersion` — the node client version string. */\n web3ClientVersion(): Promise<string> {\n return this.call<string>(\"web3_clientVersion\", []);\n }\n}\n","/**\n * Typed wrappers for the QoreChain `qor_*` JSON-RPC namespace.\n *\n * Each method maps one-to-one to a chain RPC method, exposed against the EVM\n * JSON-RPC endpoint (`endpoints.evmRpc`). The on-the-wire method names use the\n * chain's exact casing (e.g. `qor_getPQCKeyStatus`, `qor_getAIStats`) and must\n * not be altered.\n *\n * Results are intentionally returned as generics defaulting to\n * {@link Record}<string, unknown>: the chain returns rich, evolving JSON and the\n * SDK does not model every field. Callers pass a concrete type argument when\n * they know the shape.\n */\n\nimport { JsonRpcClient, type JsonRpcClientOptions } from \"./jsonrpc\";\n\n/** Convenience default for unmodeled `qor_*` responses. */\ntype Json = Record<string, unknown>;\n\n/**\n * Client for the QoreChain `qor_*` JSON-RPC namespace.\n *\n * Built on {@link JsonRpcClient}; point it at the network's `evmRpc` endpoint.\n */\nexport class QorClient extends JsonRpcClient {\n constructor(url: string, opts: JsonRpcClientOptions = {}) {\n super(url, opts);\n }\n\n /** `qor_getPQCKeyStatus` — PQC key registration status for an address. */\n getPqcKeyStatus<T = Json>(address: string): Promise<T> {\n return this.call<T>(\"qor_getPQCKeyStatus\", [address]);\n }\n\n /** `qor_getHybridSignatureMode` — active hybrid-signature policy. */\n getHybridSignatureMode<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getHybridSignatureMode\", []);\n }\n\n /** `qor_getAIStats` — QCAI engine statistics. */\n getAiStats<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getAIStats\", []);\n }\n\n /** `qor_getCrossVMMessage` — a cross-VM message by id. */\n getCrossVmMessage<T = Json>(messageId: string): Promise<T> {\n return this.call<T>(\"qor_getCrossVMMessage\", [messageId]);\n }\n\n /** `qor_getReputationScore` — reputation score for a validator. */\n getReputationScore<T = Json>(validator: string): Promise<T> {\n return this.call<T>(\"qor_getReputationScore\", [validator]);\n }\n\n /** `qor_getLayerInfo` — info about a chain layer. */\n getLayerInfo<T = Json>(layerId: string): Promise<T> {\n return this.call<T>(\"qor_getLayerInfo\", [layerId]);\n }\n\n /** `qor_getBridgeStatus` — bridge status for a remote chain id. */\n getBridgeStatus<T = Json>(chainId: string): Promise<T> {\n return this.call<T>(\"qor_getBridgeStatus\", [chainId]);\n }\n\n /** `qor_getRLAgentStatus` — reinforcement-learning agent status. */\n getRlAgentStatus<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getRLAgentStatus\", []);\n }\n\n /** `qor_getRLObservation` — latest RL observation vector. */\n getRlObservation<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getRLObservation\", []);\n }\n\n /** `qor_getRLReward` — latest RL reward signal. */\n getRlReward<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getRLReward\", []);\n }\n\n /** `qor_getPoolClassification` — validator pool classification. */\n getPoolClassification<T = Json>(validator: string): Promise<T> {\n return this.call<T>(\"qor_getPoolClassification\", [validator]);\n }\n\n /** `qor_getBurnStats` — token burn statistics. */\n getBurnStats<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getBurnStats\", []);\n }\n\n /** `qor_getXQOREPosition` — xQORE staking position for an address. */\n getXqorePosition<T = Json>(address: string): Promise<T> {\n return this.call<T>(\"qor_getXQOREPosition\", [address]);\n }\n\n /** `qor_getInflationRate` — current inflation rate. */\n getInflationRate<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getInflationRate\", []);\n }\n\n /** `qor_getTokenomicsOverview` — aggregate tokenomics snapshot. */\n getTokenomicsOverview<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getTokenomicsOverview\", []);\n }\n\n /** `qor_getRollupStatus` — status of a rollup. */\n getRollupStatus<T = Json>(rollupId: string): Promise<T> {\n return this.call<T>(\"qor_getRollupStatus\", [rollupId]);\n }\n\n /** `qor_listRollups` — all known rollups. */\n listRollups<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_listRollups\", []);\n }\n\n /** `qor_getSettlementBatch` — a settlement batch by rollup and index. */\n getSettlementBatch<T = Json>(rollupId: string, batchIndex: number): Promise<T> {\n return this.call<T>(\"qor_getSettlementBatch\", [rollupId, batchIndex]);\n }\n\n /** `qor_suggestRollupProfile` — a suggested rollup profile for a use case. */\n suggestRollupProfile<T = Json>(useCase: string): Promise<T> {\n return this.call<T>(\"qor_suggestRollupProfile\", [useCase]);\n }\n\n /** `qor_getDABlobStatus` — data-availability blob status by rollup and index. */\n getDaBlobStatus<T = Json>(rollupId: string, blobIndex: number): Promise<T> {\n return this.call<T>(\"qor_getDABlobStatus\", [rollupId, blobIndex]);\n }\n\n /** `qor_getBTCStakingPosition` — BTC staking position for an address. */\n getBtcStakingPosition<T = Json>(address: string): Promise<T> {\n return this.call<T>(\"qor_getBTCStakingPosition\", [address]);\n }\n\n /** `qor_getAbstractAccount` — account-abstraction record for an address. */\n getAbstractAccount<T = Json>(address: string): Promise<T> {\n return this.call<T>(\"qor_getAbstractAccount\", [address]);\n }\n\n /** `qor_getFairBlockStatus` — fair-ordering / fair-block status. */\n getFairBlockStatus<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getFairBlockStatus\", []);\n }\n\n /** `qor_getGasAbstractionConfig` — gas-abstraction configuration. */\n getGasAbstractionConfig<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getGasAbstractionConfig\", []);\n }\n\n /** `qor_getLaneConfiguration` — mempool lane configuration. */\n getLaneConfiguration<T = Json>(): Promise<T> {\n return this.call<T>(\"qor_getLaneConfiguration\", []);\n }\n}\n","/**\n * Native-transaction fee estimation for QoreChain.\n *\n * QoreChain exposes an AI-assisted fee oracle at the REST route\n * `/qorechain/ai/v1/fee-estimate?urgency=fast|normal|slow` (see the core\n * `AI_ENGINE.md` / `API_REFERENCE.md`). {@link estimateFee} queries it via the\n * shared {@link RestClient} and shapes the answer as a Cosmos `StdFee`\n * (`{ amount: Coin[]; gas: string }`).\n *\n * The oracle can be unavailable (node still syncing, sidecar down, custom RPC\n * without the AI module). To keep transaction building robust, this falls back\n * to a deterministic static fee computed from a configurable gas price in the\n * base denom — `ceil(gas * gasPrice)` — exactly as a wallet would compute a\n * minimum-gas-price fee. The fallback is transparent and never throws on a\n * missing/erroring endpoint; only a successful response is preferred.\n */\n\nimport type { StdFee } from \"@cosmjs/amino\";\nimport type { RestClient, FeeUrgency } from \"../query/rest\";\n\n/**\n * Re-export cosmjs's canonical `StdFee` so the SDK shares one fee type with what\n * `SigningStargateClient.signAndBroadcast` expects. This is the cosmjs shape\n * (`{ amount: readonly Coin[]; gas: string; granter?; payer? }`), so feegrant\n * `granter`/`payer` are supported.\n */\nexport type { StdFee };\n\n/**\n * Default static-fallback parameters, used when the AI fee oracle is\n * unavailable. The gas price (`uqor` per unit of gas) is intentionally\n * conservative and matches the relayer default in the core repo\n * (`gas_price = 0.025 uqor`).\n */\nexport const STATIC_FALLBACK = {\n /** Fallback gas price, in base denom per unit of gas. */\n gasPrice: \"0.025\",\n /** Base denomination fees are paid in. */\n denom: \"uqor\",\n /** Default gas limit when the caller does not supply one. */\n gas: \"200000\",\n} as const;\n\n/** Options for {@link estimateFee}. */\nexport interface EstimateFeeOptions {\n /** Relative urgency tier passed to the oracle. Defaults to `\"normal\"`. */\n urgency?: FeeUrgency;\n /**\n * Gas limit to request, as a number or decimal string. Defaults to\n * {@link STATIC_FALLBACK.gas}. The oracle only suggests a *fee amount*; the\n * gas limit is chosen by the caller (or via {@link TxClient.simulate}).\n */\n gas?: number | string;\n /**\n * Static-fallback gas price (base denom per gas unit) used only when the\n * oracle is unavailable. Defaults to {@link STATIC_FALLBACK.gasPrice}.\n */\n fallbackGasPrice?: string;\n /** Base denomination for the fee. Defaults to {@link STATIC_FALLBACK.denom}. */\n denom?: string;\n}\n\n/**\n * Shape of the AI fee-estimate REST response.\n *\n * Mirrors the core `FeeEstimateResponse` proto (gateway JSON): `suggested_fee_uqor`\n * is a `uint64`, which proto3 JSON encodes as a string, but tolerate a number too.\n */\ninterface FeeEstimateResponse {\n suggested_fee_uqor?: string | number;\n estimated_blocks?: number;\n current_congestion?: number;\n predicted_congestion?: number;\n confidence?: number;\n}\n\n/** Normalize a `number | string` gas value to a decimal string. */\nfunction gasString(gas: number | string | undefined): string {\n if (gas === undefined) return STATIC_FALLBACK.gas;\n return typeof gas === \"number\" ? Math.ceil(gas).toString() : gas;\n}\n\n/**\n * Compute a static fee as `ceil(gas * gasPrice)` in `denom`.\n *\n * Uses BigInt math on a scaled integer to avoid floating-point drift on the\n * fee amount; the gas price is parsed to a fixed number of decimal places.\n */\nfunction staticFee(gas: string, gasPrice: string, denom: string): StdFee {\n const gasUnits = BigInt(gas);\n // Parse \"0.025\" into (numerator=25, scale=1000) so amount = gas*num/scale.\n const [intPart, fracPart = \"\"] = gasPrice.split(\".\");\n const scale = 10n ** BigInt(fracPart.length);\n const numerator = BigInt(intPart || \"0\") * scale + BigInt(fracPart || \"0\");\n // ceil division: (gas*numerator + scale - 1) / scale\n const raw = gasUnits * numerator;\n const amount = (raw + scale - 1n) / scale;\n return { amount: [{ denom, amount: amount.toString() }], gas };\n}\n\n/**\n * Estimate a transaction fee for the given urgency.\n *\n * Queries the QoreChain AI fee oracle and returns a Cosmos `StdFee`. If the\n * oracle is unavailable or returns no usable fee, falls back to a deterministic\n * static fee computed from {@link EstimateFeeOptions.fallbackGasPrice}.\n *\n * @param rest - A {@link RestClient} bound to the network's REST endpoint.\n * @param opts - Urgency, gas limit, and static-fallback parameters.\n */\nexport async function estimateFee(\n rest: RestClient,\n opts: EstimateFeeOptions = {},\n): Promise<StdFee> {\n const urgency: FeeUrgency = opts.urgency ?? \"normal\";\n const gas = gasString(opts.gas);\n const denom = opts.denom ?? STATIC_FALLBACK.denom;\n const fallbackGasPrice = opts.fallbackGasPrice ?? STATIC_FALLBACK.gasPrice;\n\n try {\n const res = await rest.getFeeEstimate<FeeEstimateResponse>(urgency);\n const suggested = res?.suggested_fee_uqor;\n if (suggested !== undefined && suggested !== null) {\n const amount =\n typeof suggested === \"number\"\n ? Math.ceil(suggested).toString()\n : suggested;\n // Treat a zero/empty suggestion as \"no answer\" and fall through.\n if (amount !== \"\" && amount !== \"0\") {\n return { amount: [{ denom, amount }], gas };\n }\n }\n } catch {\n // Oracle unavailable — fall through to the static fee.\n }\n\n return staticFee(gas, fallbackGasPrice, denom);\n}\n","/**\n * Native transaction builder and broadcaster for QoreChain.\n *\n * {@link TxClient} wraps cosmjs's `SigningStargateClient` to simulate, sign, and\n * broadcast native (Cosmos SDK) transactions, with a `bankSend` convenience for\n * the common transfer case. It is constructed in two ways:\n *\n * - {@link TxClient.connect} — the production path: connect to the network's\n * consensus RPC with an offline signer (see {@link directSignerFromPrivateKey})\n * and an optional custom message {@link Registry}.\n * - `new TxClient({ signingClient, senderAddress })` — the testable path: inject\n * any object satisfying {@link SigningClientLike}, so unit tests never touch\n * the network.\n *\n * Custom QoreChain module messages are out of scope for v0.1 codegen; instead,\n * callers may register their own protobuf types by passing `registryTypes` to\n * {@link TxClient.connect} (added to cosmjs's default bank/staking/gov/etc.\n * registry), then build `{ typeUrl, value }` messages for them.\n */\n\nimport {\n SigningStargateClient,\n type SigningStargateClientOptions,\n type DeliverTxResponse,\n defaultRegistryTypes,\n} from \"@cosmjs/stargate\";\nimport {\n Registry,\n type EncodeObject,\n type OfflineDirectSigner,\n type GeneratedType,\n} from \"@cosmjs/proto-signing\";\nimport { MsgSend } from \"cosmjs-types/cosmos/bank/v1beta1/tx\";\nimport type { Coin } from \"../query/rest\";\nimport type { StdFee } from \"./fees\";\nimport type { BroadcastMode, BroadcastResult } from \"./broadcast\";\n\n/** The `/cosmos.bank.v1beta1.MsgSend` type URL. */\nexport const MSG_SEND_TYPE_URL = \"/cosmos.bank.v1beta1.MsgSend\";\n\n/**\n * The subset of `SigningStargateClient` that {@link TxClient} depends on.\n * Declaring it explicitly lets unit tests inject a lightweight fake.\n */\nexport interface SigningClientLike {\n simulate(\n signerAddress: string,\n messages: readonly EncodeObject[],\n memo: string | undefined,\n ): Promise<number>;\n signAndBroadcast(\n signerAddress: string,\n messages: readonly EncodeObject[],\n fee: StdFee,\n memo?: string,\n ): Promise<DeliverTxResponse>;\n signAndBroadcastSync(\n signerAddress: string,\n messages: readonly EncodeObject[],\n fee: StdFee,\n memo?: string,\n ): Promise<string>;\n disconnect?(): void;\n}\n\n/** Options for constructing a {@link TxClient} directly (testing/advanced). */\nexport interface TxClientOptions {\n /** The underlying signing client (real or fake). */\n signingClient: SigningClientLike;\n /** The bech32 address transactions are signed and sent from. */\n senderAddress: string;\n}\n\n/** Options for {@link TxClient.connect}. */\nexport interface TxConnectOptions {\n /** Consensus RPC endpoint (e.g. `endpoints.rpc`). */\n rpcEndpoint: string;\n /** An offline direct signer (see {@link directSignerFromPrivateKey}). */\n signer: OfflineDirectSigner;\n /**\n * Extra protobuf message types to register, as `[typeUrl, GeneratedType]`\n * pairs. Added to cosmjs's default registry (bank/staking/gov/distribution/…).\n * Use this to support custom QoreChain module messages without bundling full\n * codegen into the SDK.\n */\n registryTypes?: ReadonlyArray<[string, GeneratedType]>;\n /** Additional cosmjs `SigningStargateClientOptions` (gas price, etc.). */\n clientOptions?: SigningStargateClientOptions;\n}\n\n/** Options accepted when signing and broadcasting. */\nexport interface SignAndBroadcastOptions {\n /** Broadcast mode. Defaults to `\"commit\"`. */\n mode?: BroadcastMode;\n}\n\n/** Options for {@link TxClient.simulate}. */\nexport interface SimulateOptions {\n /** Optional tx memo to include in the simulation. */\n memo?: string;\n}\n\n/** Options for {@link TxClient.bankSend}. */\nexport interface BankSendOptions extends SignAndBroadcastOptions {\n /** The fee to pay. Required (estimate via `estimateFee`). */\n fee: StdFee;\n /** Optional memo. */\n memo?: string;\n}\n\n/**\n * A native-transaction client: simulate, sign, broadcast, and send tokens.\n */\nexport class TxClient {\n private readonly client: SigningClientLike;\n /** The signing/sending bech32 address. */\n readonly senderAddress: string;\n\n constructor(opts: TxClientOptions) {\n this.client = opts.signingClient;\n this.senderAddress = opts.senderAddress;\n }\n\n /**\n * Connect to a network's consensus RPC and build a {@link TxClient}.\n *\n * Resolves the signer's first account as the sender address and merges any\n * `registryTypes` into cosmjs's default message registry.\n */\n static async connect(opts: TxConnectOptions): Promise<TxClient> {\n const registry = new Registry(defaultRegistryTypes);\n for (const [typeUrl, type] of opts.registryTypes ?? []) {\n registry.register(typeUrl, type);\n }\n const client = await SigningStargateClient.connectWithSigner(\n opts.rpcEndpoint,\n opts.signer,\n { registry, ...opts.clientOptions },\n );\n const accounts = await opts.signer.getAccounts();\n if (accounts.length === 0) {\n throw new Error(\"signer exposes no accounts\");\n }\n return new TxClient({\n signingClient: client,\n senderAddress: accounts[0].address,\n });\n }\n\n /**\n * Simulate the given messages and return the estimated gas units.\n *\n * Use the result (with a safety multiplier) as the `gas` for `estimateFee`.\n */\n simulate(\n messages: readonly EncodeObject[],\n opts: SimulateOptions = {},\n ): Promise<number> {\n return this.client.simulate(this.senderAddress, messages, opts.memo);\n }\n\n /**\n * Sign and broadcast the given messages with an explicit fee.\n *\n * Broadcast mode maps onto cosmjs transports:\n * - `commit` (default): polls until the tx lands in a block; returns the full\n * result and throws on a non-zero delivery code.\n * - `sync` / `async`: returns after mempool submission with just the tx hash.\n */\n async signAndBroadcast(\n messages: readonly EncodeObject[],\n fee: StdFee,\n memo = \"\",\n opts: SignAndBroadcastOptions = {},\n ): Promise<BroadcastResult> {\n const mode: BroadcastMode = opts.mode ?? \"commit\";\n\n if (mode === \"commit\") {\n const res = await this.client.signAndBroadcast(\n this.senderAddress,\n messages,\n fee,\n memo,\n );\n if (res.code !== 0) {\n throw new Error(\n `transaction failed with code ${res.code}: ${res.rawLog ?? \"(no log)\"} (hash ${res.transactionHash})`,\n );\n }\n return {\n transactionHash: res.transactionHash,\n code: res.code,\n height: res.height,\n gasUsed: res.gasUsed,\n gasWanted: res.gasWanted,\n rawLog: res.rawLog,\n };\n }\n\n // sync / async: both return after CheckTx without polling for a block.\n const hash = await this.client.signAndBroadcastSync(\n this.senderAddress,\n messages,\n fee,\n memo,\n );\n return { transactionHash: hash, code: 0 };\n }\n\n /**\n * Send `amount` to `toAddress` via a bank `MsgSend`, then broadcast.\n *\n * Constructs `/cosmos.bank.v1beta1.MsgSend` from this client's sender address.\n */\n bankSend(\n toAddress: string,\n amount: Coin[],\n opts: BankSendOptions,\n ): Promise<BroadcastResult> {\n const msg: EncodeObject = {\n typeUrl: MSG_SEND_TYPE_URL,\n value: MsgSend.fromPartial({\n fromAddress: this.senderAddress,\n toAddress,\n amount,\n }),\n };\n return this.signAndBroadcast([msg], opts.fee, opts.memo ?? \"\", {\n mode: opts.mode,\n });\n }\n\n /** Disconnect the underlying client's transport, if it supports it. */\n disconnect(): void {\n this.client.disconnect?.();\n }\n}\n","/**\n * CosmWasm contract interaction for QoreChain.\n *\n * This module rounds out the triple-VM surface (native + EVM + SVM + CosmWasm)\n * with thin, type-safe conveniences over `@cosmjs/cosmwasm-stargate`. It does\n * NOT reimplement cosmjs: the wrappers forward to a `CosmWasmClient` (reads) or\n * `SigningCosmWasmClient` (writes) with QoreChain-friendly defaults.\n *\n * Two construction helpers ({@link createCosmWasmClient}, {@link\n * connectCosmWasmSigner}) build the cosmjs clients against a network's `rpc`\n * endpoint. The wrapper functions, however, accept an already-built client so\n * they are unit-testable with a stubbed fake — no real connection required.\n */\n\nimport {\n CosmWasmClient,\n SigningCosmWasmClient,\n} from \"@cosmjs/cosmwasm-stargate\";\nimport type { OfflineSigner } from \"@cosmjs/proto-signing\";\nimport type { Coin, StdFee } from \"@cosmjs/amino\";\n\n/**\n * Arbitrary JSON value accepted/returned by contract calls. Mirrors cosmjs's\n * `JsonObject` (which is `any`) but keeps our public types honest.\n */\nexport type ContractMsg = Record<string, unknown>;\n\n/** A `StdFee`, or cosmjs's `\"auto\"` (simulate) / a raw gas multiplier number. */\nexport type FeeInput = StdFee | \"auto\" | number;\n\n/**\n * Read-only slice of `CosmWasmClient` used by the read wrappers. Declaring the\n * methods we use (rather than importing the concrete class) lets tests inject a\n * minimal fake.\n */\nexport interface CosmWasmReadClient {\n queryContractSmart(address: string, queryMsg: ContractMsg): Promise<unknown>;\n getContract(address: string): Promise<unknown>;\n}\n\n/** Signing slice of `SigningCosmWasmClient` used by the write wrappers. */\nexport interface CosmWasmSigningClient {\n upload(\n senderAddress: string,\n wasmCode: Uint8Array,\n fee: FeeInput,\n memo?: string,\n ): Promise<unknown>;\n instantiate(\n senderAddress: string,\n codeId: number,\n msg: ContractMsg,\n label: string,\n fee: FeeInput,\n options?: InstantiateOpts,\n ): Promise<unknown>;\n execute(\n senderAddress: string,\n contractAddress: string,\n msg: ContractMsg,\n fee: FeeInput,\n memo?: string,\n funds?: readonly Coin[],\n ): Promise<unknown>;\n}\n\n/** Options for {@link instantiate}: cosmjs `InstantiateOptions` plus the fee. */\nexport interface InstantiateOpts {\n /** Fee for the instantiate tx. Defaults to `\"auto\"` (simulate). */\n fee?: FeeInput;\n /** Optional memo. */\n memo?: string;\n /** Native funds sent to the new contract on instantiation. */\n funds?: readonly Coin[];\n /** Optional admin address (can migrate the contract). */\n admin?: string;\n}\n\n/**\n * Connect a read-only {@link CosmWasmClient} to a network's RPC endpoint.\n *\n * @param rpcUrl - The network's `rpc` endpoint (e.g. `endpoints.rpc`).\n */\nexport function createCosmWasmClient(rpcUrl: string): Promise<CosmWasmClient> {\n return CosmWasmClient.connect(rpcUrl);\n}\n\n/**\n * Connect a {@link SigningCosmWasmClient} for contract writes.\n *\n * @param rpcUrl - The network's `rpc` endpoint.\n * @param signer - An offline signer (e.g. from `@cosmjs/proto-signing`).\n */\nexport function connectCosmWasmSigner(\n rpcUrl: string,\n signer: OfflineSigner,\n): Promise<SigningCosmWasmClient> {\n return SigningCosmWasmClient.connectWithSigner(rpcUrl, signer);\n}\n\n/** Run a contract's smart query (`queryContractSmart`). */\nexport function queryContractSmart<T = unknown>(\n client: CosmWasmReadClient,\n contractAddress: string,\n queryMsg: ContractMsg,\n): Promise<T> {\n return client.queryContractSmart(contractAddress, queryMsg) as Promise<T>;\n}\n\n/** Fetch a contract's on-chain metadata (`getContract`). */\nexport function getContractInfo<T = unknown>(\n client: CosmWasmReadClient,\n contractAddress: string,\n): Promise<T> {\n return client.getContract(contractAddress) as Promise<T>;\n}\n\n/**\n * Instantiate a contract from an uploaded code id.\n *\n * Forwards to `SigningCosmWasmClient.instantiate`, splitting our {@link\n * InstantiateOpts} into cosmjs's positional `fee` (default `\"auto\"`) and its\n * `InstantiateOptions` (`memo`/`funds`/`admin`).\n */\nexport function instantiate<T = unknown>(\n client: CosmWasmSigningClient,\n sender: string,\n codeId: number,\n initMsg: ContractMsg,\n label: string,\n opts: InstantiateOpts = {},\n): Promise<T> {\n const { fee = \"auto\", memo, funds, admin } = opts;\n const options: InstantiateOpts = {};\n if (funds !== undefined) options.funds = funds;\n if (admin !== undefined) options.admin = admin;\n if (memo !== undefined) options.memo = memo;\n return client.instantiate(\n sender,\n codeId,\n initMsg,\n label,\n fee,\n options,\n ) as Promise<T>;\n}\n\n/** Execute a message against an instantiated contract. */\nexport function execute<T = unknown>(\n client: CosmWasmSigningClient,\n sender: string,\n contractAddress: string,\n msg: ContractMsg,\n fee: FeeInput,\n funds?: readonly Coin[],\n): Promise<T> {\n return client.execute(\n sender,\n contractAddress,\n msg,\n fee,\n undefined,\n funds,\n ) as Promise<T>;\n}\n\n/** Upload (store) WASM bytecode, returning the assigned code id in the result. */\nexport function uploadCode<T = unknown>(\n client: CosmWasmSigningClient,\n sender: string,\n wasmBytes: Uint8Array,\n fee: FeeInput,\n): Promise<T> {\n return client.upload(sender, wasmBytes, fee) as Promise<T>;\n}\n","/**\n * Cross-VM read helpers for QoreChain's `x/crossvm` module.\n *\n * These are thin, typed wrappers over {@link RestClient} for the module's REST\n * routes under `/qorechain/crossvm/v1/...`. They are standalone functions taking\n * a {@link RestClient} so they compose with the existing read surface without\n * widening the `RestClient` class itself.\n *\n * Responses are returned as generics defaulting to small interfaces / {@link\n * Record}<string, unknown>: the module returns rich, evolving JSON and the SDK\n * does not model every field.\n *\n * Note on direction: these helpers READ cross-VM message state. The actual\n * EVM→native routing — e.g. an EVM contract triggering a native AMM swap — is\n * performed on-chain via the cross-VM bridge precompile exposed in the\n * `@qorechain/evm` package (not duplicated here). Once a message is in flight,\n * track its status either through these REST reads or via the\n * `qor_getCrossVMMessage` JSON-RPC method already wrapped on `QorClient`.\n */\n\nimport type { RestClient } from \"./rest\";\n\n/** A single cross-VM message record (unmodeled fields surface as-is). */\nexport interface CrossVmMessage {\n [key: string]: unknown;\n}\n\n/** Response of the single-message-by-id route. */\nexport interface CrossVmMessageResponse {\n message?: CrossVmMessage;\n [key: string]: unknown;\n}\n\n/** Response of the pending-messages route. */\nexport interface PendingCrossVmMessagesResponse {\n messages?: CrossVmMessage[];\n [key: string]: unknown;\n}\n\n/** Response of the module params route. */\nexport interface CrossVmParamsResponse {\n params?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * Fetch a cross-VM message by id.\n *\n * GET `/qorechain/crossvm/v1/message/{id}`.\n */\nexport function getCrossVmMessage<T = CrossVmMessageResponse>(\n rest: RestClient,\n id: string,\n): Promise<T> {\n return rest.get<T>(\n `/qorechain/crossvm/v1/message/${encodeURIComponent(id)}`,\n );\n}\n\n/**\n * Fetch all currently pending cross-VM messages.\n *\n * GET `/qorechain/crossvm/v1/pending`.\n */\nexport function getPendingCrossVmMessages<\n T = PendingCrossVmMessagesResponse,\n>(rest: RestClient): Promise<T> {\n return rest.get<T>(\"/qorechain/crossvm/v1/pending\");\n}\n\n/**\n * Fetch the `x/crossvm` module parameters.\n *\n * GET `/qorechain/crossvm/v1/params`.\n */\nexport function getCrossVmParams<T = CrossVmParamsResponse>(\n rest: RestClient,\n): Promise<T> {\n return rest.get<T>(\"/qorechain/crossvm/v1/params\");\n}\n","/**\n * Top-level `createClient` factory for the QoreChain SDK.\n *\n * {@link createClient} resolves a {@link NetworkConfig} (applying any endpoint\n * overrides) and composes the read clients ({@link RestClient}, the EVM\n * {@link JsonRpcClient}, and the `qor_` {@link QorClient}) plus a fee-estimate\n * convenience over {@link estimateFee}. Signing is opt-in: call\n * {@link QoreChainClient.connectTx} with an offline signer to get a\n * {@link TxClient}.\n *\n * Network resolution rules:\n * - The default network is `testnet`. Both `testnet` and `mainnet` are live and\n * ship localhost endpoint defaults; pass `endpoints` to point at real\n * hostnames.\n *\n * Read sub-clients are lazy getters: each only needs its own endpoint, so\n * accessing one whose endpoint is missing throws a clear, actionable error\n * naming the missing endpoint rather than failing later with an opaque request.\n */\n\nimport type { OfflineDirectSigner, GeneratedType } from \"@cosmjs/proto-signing\";\nimport type { StdFee } from \"@cosmjs/amino\";\nimport {\n getNetwork,\n type NetworkConfig,\n type NetworkEndpoints,\n type NetworkName,\n} from \"./config/networks\";\nimport type { FetchLike, HttpOptions } from \"./query/http\";\nimport { RestClient } from \"./query/rest\";\nimport { JsonRpcClient } from \"./query/jsonrpc\";\nimport { QorClient } from \"./query/qor\";\nimport { estimateFee } from \"./tx/fees\";\nimport type { FeeUrgency } from \"./query/rest\";\nimport { TxClient } from \"./tx/builder\";\nimport { createCosmWasmClient } from \"./cosmwasm\";\nimport type { CosmWasmClient } from \"@cosmjs/cosmwasm-stargate\";\nimport {\n getCrossVmMessage,\n getPendingCrossVmMessages,\n getCrossVmParams,\n type CrossVmMessageResponse,\n type PendingCrossVmMessagesResponse,\n type CrossVmParamsResponse,\n} from \"./query/crossvm\";\n\n/** Options for {@link createClient}. */\nexport interface CreateClientOptions {\n /** Network preset to target. Defaults to `\"testnet\"`. */\n network?: NetworkName;\n /**\n * Endpoint overrides, merged over the preset's defaults. Both `testnet` and\n * `mainnet` default to localhost; pass real hostnames here to override them.\n */\n endpoints?: Partial<NetworkEndpoints>;\n /**\n * Chain ID override. Both presets ship a live chain ID, so this is only needed\n * to point at a non-standard chain.\n */\n chainId?: string;\n /** Injectable `fetch` for the read clients (used by tests). */\n fetch?: FetchLike;\n /**\n * Additional HTTP transport options (timeout, retries, headers) shared by the\n * read clients.\n */\n http?: Omit<HttpOptions, \"fetch\">;\n}\n\n/** Options for {@link QoreChainClient.connectTx}. */\nexport interface ConnectTxOptions {\n /**\n * Extra protobuf message types to register, as `[typeUrl, GeneratedType]`\n * pairs (forwarded to {@link TxClient.connect}).\n */\n registryTypes?: ReadonlyArray<[string, GeneratedType]>;\n}\n\n/** Fee convenience surface exposed by {@link QoreChainClient}. */\nexport interface ClientFees {\n /**\n * Estimate a fee for the given urgency via the AI fee oracle (with a static\n * fallback). See {@link estimateFee}.\n */\n estimate(urgency?: FeeUrgency): Promise<StdFee>;\n}\n\n/** Cross-VM read convenience surface, bound to the client's REST endpoint. */\nexport interface ClientCrossVm {\n /** A cross-VM message by id (`/qorechain/crossvm/v1/message/{id}`). */\n message(id: string): Promise<CrossVmMessageResponse>;\n /** Currently pending cross-VM messages (`/qorechain/crossvm/v1/pending`). */\n pending(): Promise<PendingCrossVmMessagesResponse>;\n /** Cross-VM module params (`/qorechain/crossvm/v1/params`). */\n params(): Promise<CrossVmParamsResponse>;\n}\n\n/**\n * A composed QoreChain client: resolved config, read clients, fee helper, and a\n * lazy signing entrypoint.\n */\nexport interface QoreChainClient {\n /** The resolved network config (with any endpoint/chain-id overrides applied). */\n readonly network: NetworkConfig;\n /** Cosmos + QoreChain REST read client (uses `endpoints.rest`). */\n readonly rest: RestClient;\n /** EVM JSON-RPC client (uses `endpoints.evmRpc`). */\n readonly evm: JsonRpcClient;\n /** QoreChain `qor_` namespace client (uses `endpoints.evmRpc`). */\n readonly qor: QorClient;\n /** Fee-estimate convenience over the REST client. */\n readonly fees: ClientFees;\n /** Cross-VM read helpers over the REST client. */\n readonly crossvm: ClientCrossVm;\n /**\n * Connect a read-only CosmWasm client at `endpoints.rpc`.\n *\n * Async (the cosmjs client opens an RPC connection on connect), so this is a\n * method rather than a lazy getter; the result is memoized across calls.\n */\n cosmwasm(): Promise<CosmWasmClient>;\n /**\n * Connect a signer and return a {@link TxClient} bound to `endpoints.rpc`.\n * The heavy lifting lives in {@link TxClient.connect}.\n */\n connectTx(\n signer: OfflineDirectSigner,\n opts?: ConnectTxOptions,\n ): Promise<TxClient>;\n}\n\n/**\n * Resolve the effective {@link NetworkConfig} for the given options.\n *\n * Starts from the live preset (`testnet` or `mainnet`) and overlays\n * `opts.endpoints` and an optional `opts.chainId`.\n */\nfunction resolveNetwork(opts: CreateClientOptions): NetworkConfig {\n const name: NetworkName = opts.network ?? \"testnet\";\n const overrides = opts.endpoints ?? {};\n\n const base = getNetwork(name);\n return {\n ...base,\n chainId: opts.chainId ?? base.chainId,\n endpoints: { ...base.endpoints, ...overrides },\n };\n}\n\n/** Read a required endpoint or throw an actionable error naming it. */\nfunction requireEndpoint(\n endpoints: NetworkEndpoints,\n key: keyof NetworkEndpoints,\n): string {\n const value = endpoints?.[key];\n if (!value) {\n throw new Error(\n `endpoint \"${key}\" is not configured — pass it via createClient({ endpoints: { ${key}: \"...\" } })`,\n );\n }\n return value;\n}\n\n/**\n * Create a composed {@link QoreChainClient}.\n *\n * @param opts - Network selection, endpoint overrides, and transport options.\n */\nexport function createClient(opts: CreateClientOptions = {}): QoreChainClient {\n const network = resolveNetwork(opts);\n const httpOptions: HttpOptions = { ...opts.http, fetch: opts.fetch };\n\n // Memoize each sub-client so repeated access returns the same instance, while\n // still deferring construction (and the missing-endpoint check) until first use.\n let restClient: RestClient | undefined;\n let evmClient: JsonRpcClient | undefined;\n let qorClient: QorClient | undefined;\n\n const getRest = (): RestClient => {\n if (!restClient) {\n restClient = new RestClient(\n requireEndpoint(network.endpoints, \"rest\"),\n httpOptions,\n );\n }\n return restClient;\n };\n const getEvm = (): JsonRpcClient => {\n if (!evmClient) {\n evmClient = new JsonRpcClient(\n requireEndpoint(network.endpoints, \"evmRpc\"),\n httpOptions,\n );\n }\n return evmClient;\n };\n const getQor = (): QorClient => {\n if (!qorClient) {\n qorClient = new QorClient(\n requireEndpoint(network.endpoints, \"evmRpc\"),\n httpOptions,\n );\n }\n return qorClient;\n };\n\n const fees: ClientFees = {\n estimate: (urgency?: FeeUrgency) => estimateFee(getRest(), { urgency }),\n };\n\n const crossvm: ClientCrossVm = {\n message: (id: string) => getCrossVmMessage(getRest(), id),\n pending: () => getPendingCrossVmMessages(getRest()),\n params: () => getCrossVmParams(getRest()),\n };\n\n // Memoize the (async) CosmWasm client so repeated calls reuse one connection.\n let cosmWasmClient: Promise<CosmWasmClient> | undefined;\n\n return {\n network,\n get rest() {\n return getRest();\n },\n get evm() {\n return getEvm();\n },\n get qor() {\n return getQor();\n },\n fees,\n crossvm,\n cosmwasm() {\n if (!cosmWasmClient) {\n cosmWasmClient = createCosmWasmClient(\n requireEndpoint(network.endpoints, \"rpc\"),\n );\n }\n return cosmWasmClient;\n },\n connectTx(signer: OfflineDirectSigner, txOpts: ConnectTxOptions = {}) {\n return TxClient.connect({\n rpcEndpoint: requireEndpoint(network.endpoints, \"rpc\"),\n signer,\n registryTypes: txOpts.registryTypes,\n });\n },\n };\n}\n","/**\n * Conversion between human display amounts (e.g. `\"1.5\"` QOR) and integer base\n * amounts (e.g. `\"1500000\"` uqor).\n *\n * All value math is performed with {@link BigInt} on decimal strings — there is\n * no floating-point arithmetic anywhere in this module, so conversions are exact\n * for any magnitude and never drift (e.g. `toBase(\"0.1\")` is exactly\n * `\"100000\"`).\n *\n * QoreChain's staking coin uses a default exponent of `6` (1 QOR = 10^6 uqor),\n * but every function accepts a custom `exponent` for other denominations.\n */\n\n/** The QoreChain staking coin's default decimal exponent (1 QOR = 10^6 uqor). */\nconst DEFAULT_EXPONENT = 6;\n\n/** Options shared by the denom conversion helpers. */\nexport interface DenomOptions {\n /** Decimal exponent relating base to display (1 display = 10^exponent base). Defaults to 6. */\n exponent?: number;\n}\n\nfunction resolveExponent(opts?: DenomOptions): number {\n const exponent = opts?.exponent ?? DEFAULT_EXPONENT;\n if (!Number.isInteger(exponent) || exponent < 0) {\n throw new Error(`invalid exponent: ${exponent} (must be a non-negative integer)`);\n }\n return exponent;\n}\n\n/**\n * Convert a human display amount to its integer base amount string.\n *\n * @param amount - A non-negative decimal string, e.g. `\"1.5\"`. Surrounding\n * whitespace and a single leading `+` are tolerated. Scientific notation,\n * thousands separators, and other formatting are rejected.\n * @param opts - Optional `exponent` (defaults to 6).\n * @returns The integer base amount as a string with no leading zeros, e.g.\n * `\"1500000\"`.\n * @throws If `amount` is not a valid decimal string, is negative, or has more\n * fractional digits than `exponent` allows.\n */\nexport function toBase(amount: string, opts?: DenomOptions): string {\n const exponent = resolveExponent(opts);\n const trimmed = amount.trim();\n\n let body = trimmed;\n if (body.startsWith(\"-\")) {\n throw new Error(`negative amounts are not supported: ${amount}`);\n }\n if (body.startsWith(\"+\")) {\n body = body.slice(1);\n }\n\n // Strict decimal: optional integer part, optional single fractional part,\n // digits only. Rejects \"\", \".\", \"1.2.3\", \"1e3\", \"abc\", etc.\n if (!/^\\d+(\\.\\d+)?$/.test(body)) {\n throw new Error(`invalid decimal amount: ${amount}`);\n }\n\n const [intPart, fracPart = \"\"] = body.split(\".\");\n if (fracPart.length > exponent) {\n throw new Error(\n `too many decimal places in ${amount}: ${fracPart.length} > exponent ${exponent}`,\n );\n }\n\n // Right-pad the fractional digits to exactly `exponent` places, then read the\n // whole thing as one big integer. Pure string + BigInt math, no floats.\n const padded = fracPart.padEnd(exponent, \"0\");\n const base = BigInt(intPart + padded);\n return base.toString();\n}\n\n/**\n * Convert an integer base amount string to a normalized display string.\n *\n * @param base - A non-negative integer string, e.g. `\"1500000\"`.\n * @param opts - Optional `exponent` (defaults to 6).\n * @returns The display amount with no trailing zeros and no trailing dot, e.g.\n * `\"1.5\"`. `\"1000000\"` becomes `\"1\"`, `\"1\"` becomes `\"0.000001\"`, `\"0\"`\n * becomes `\"0\"`.\n * @throws If `base` is not a valid non-negative integer string.\n */\nexport function fromBase(base: string, opts?: DenomOptions): string {\n const exponent = resolveExponent(opts);\n const trimmed = base.trim();\n\n if (trimmed.startsWith(\"-\")) {\n throw new Error(`negative amounts are not supported: ${base}`);\n }\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(`invalid base amount: ${base}`);\n }\n\n if (exponent === 0) {\n // No fractional component; strip leading zeros via BigInt.\n return BigInt(trimmed).toString();\n }\n\n // Left-pad so there are at least `exponent + 1` digits, then split.\n const padded = trimmed.padStart(exponent + 1, \"0\");\n const intPart = padded.slice(0, padded.length - exponent);\n const fracPart = padded.slice(padded.length - exponent);\n\n const normalizedInt = BigInt(intPart).toString();\n const trimmedFrac = fracPart.replace(/0+$/, \"\");\n return trimmedFrac.length > 0 ? `${normalizedInt}.${trimmedFrac}` : normalizedInt;\n}\n","/**\n * Conversion and validation for QoreChain bech32 addresses (e.g. `qor1...`) and\n * their underlying byte payloads expressed as `0x`-prefixed hex.\n *\n * bech32 stores data as 5-bit groups (\"words\"), so encoding/decoding goes\n * through {@link bech32.toWords}/{@link bech32.fromWords} to convert to and from\n * the 8-bit byte representation that callers work with as hex.\n */\n\nimport { bech32 } from \"bech32\";\n\n/** Default bech32 human-readable prefix for QoreChain account addresses. */\nconst DEFAULT_PREFIX = \"qor\";\n\n/**\n * bech32 enforces a 90-character limit by default. QoreChain addresses are\n * short, but validator/consensus prefixes plus longer payloads can approach it,\n * so we raise the limit to a safe upper bound to avoid spurious failures.\n */\nconst LIMIT = 1023;\n\n/** Strip an optional `0x`/`0X` prefix from a hex string. */\nfunction stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/** Parse a hex string (with or without `0x`) into bytes, validating strictly. */\nfunction hexToBytes(hex: string): Uint8Array {\n const body = stripHexPrefix(hex);\n if (body.length === 0 || body.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(body)) {\n throw new Error(`invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(body.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(body.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Encode bytes to a lowercase `0x`-prefixed hex string. */\nfunction bytesToHex(bytes: ArrayLike<number>): string {\n let out = \"0x\";\n for (let i = 0; i < bytes.length; i++) {\n out += bytes[i].toString(16).padStart(2, \"0\");\n }\n return out;\n}\n\n/**\n * Decode a bech32 address to a `0x`-prefixed hex string of its byte payload.\n *\n * @param addr - A bech32 address, e.g. `qor1...`.\n * @returns The underlying bytes as lowercase `0x`-prefixed hex.\n * @throws If `addr` is not a valid bech32 string.\n */\nexport function bech32ToHex(addr: string): string {\n const { words } = bech32.decode(addr, LIMIT);\n const bytes = bech32.fromWords(words);\n return bytesToHex(bytes);\n}\n\n/**\n * Encode raw bytes to a bech32 address with the given prefix.\n *\n * This is the primitive encoder; callers holding a `Uint8Array` payload (e.g.\n * the 20-byte `ripemd160(sha256(pubkey))` account hash) should use this\n * directly rather than round-tripping through hex.\n *\n * @param bytes - The raw byte payload.\n * @param prefix - The bech32 human-readable prefix. Defaults to `\"qor\"`.\n * @returns The bech32-encoded address, e.g. `qor1...`.\n */\nexport function bytesToBech32(\n bytes: Uint8Array,\n prefix: string = DEFAULT_PREFIX,\n): string {\n const words = bech32.toWords(bytes);\n return bech32.encode(prefix, words, LIMIT);\n}\n\n/**\n * Encode hex bytes to a bech32 address with the given prefix.\n *\n * @param hex - The byte payload as hex, with or without a `0x` prefix.\n * @param prefix - The bech32 human-readable prefix. Defaults to `\"qor\"`.\n * @returns The bech32-encoded address, e.g. `qor1...`.\n * @throws If `hex` is not a valid hex string.\n */\nexport function hexToBech32(hex: string, prefix: string = DEFAULT_PREFIX): string {\n return bytesToBech32(hexToBytes(hex), prefix);\n}\n\n/**\n * Validate a bech32 address, optionally requiring a specific prefix.\n *\n * @param addr - The candidate address string.\n * @param prefix - If given, the decoded prefix must match exactly.\n * @returns `true` if `addr` is a structurally valid bech32 string (correct\n * checksum) and, when `prefix` is supplied, its prefix matches; `false`\n * otherwise. Never throws.\n */\nexport function isValidBech32(addr: string, prefix?: string): boolean {\n const decoded = bech32.decodeUnsafe(addr, LIMIT);\n if (!decoded) {\n return false;\n }\n return prefix === undefined ? true : decoded.prefix === prefix;\n}\n","/**\n * Mnemonic generation/validation and hierarchical-deterministic (HD) derivation\n * of QoreChain accounts in all three supported schemes:\n *\n * 1. native — Cosmos-style secp256k1, BIP-44 path `m/44'/118'/0'/0/{index}`,\n * address = bech32(`qor`, ripemd160(sha256(compressedPubkey))).\n * 2. evm — secp256k1, BIP-44 path `m/44'/60'/0'/0/{index}`,\n * address = `0x` + last 20 bytes of keccak256(uncompressedPubkey[1:]),\n * rendered with an EIP-55 mixed-case checksum.\n * 3. svm — ed25519, SLIP-0010 path `m/44'/501'/{index}'/0'` (all hardened,\n * the Solana standard), address = base58(32-byte ed25519 public key).\n *\n * Derivation uses audited primitives: @scure/bip39 (mnemonic + seed), @scure/bip32\n * (secp256k1 HD), micro-key-producer SLIP-0010 (ed25519 HD), @noble/hashes and\n * @noble/curves. Secret material is returned explicitly from the derive functions\n * and is never logged.\n *\n * Dependency note: this module pins @noble/hashes/@noble/curves/@scure/base on\n * the 1.x line, while `micro-key-producer` brings its own 2.x copies of those\n * packages. The two majors are installed side by side intentionally. They never\n * exchange hash or curve instances across the boundary — micro-key-producer is\n * used only as a self-contained SLIP-0010 derivation black box (seed in, ed25519\n * node out), so the duplicate copies are isolated and harmless. Do not force a\n * `pnpm.overrides` that drags micro-key-producer onto a different major; that\n * would risk breaking its internals for no behavioural gain here.\n */\n\nimport {\n generateMnemonic as bip39Generate,\n validateMnemonic as bip39Validate,\n mnemonicToSeed,\n} from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english\";\nimport { HDKey } from \"@scure/bip32\";\nimport { HDKey as Slip10HDKey } from \"micro-key-producer/slip10.js\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { ripemd160 } from \"@noble/hashes/ripemd160\";\nimport { keccak_256 } from \"@noble/hashes/sha3\";\nimport { base58 } from \"@scure/base\";\n\nimport { bytesToBech32 } from \"../utils/address\";\nimport type {\n DerivationOptions,\n Secp256k1Account,\n Ed25519Account,\n} from \"./types\";\n\n/** Bech32 human-readable prefix for native QoreChain account addresses. */\nconst NATIVE_PREFIX = \"qor\";\n\n/** Coin types per SLIP-0044. */\nconst COIN_TYPE_NATIVE = 118; // Cosmos\nconst COIN_TYPE_EVM = 60; // Ethereum\nconst COIN_TYPE_SVM = 501; // Solana\n\n/**\n * Generate a fresh BIP-39 mnemonic.\n *\n * @param strength - Entropy in bits: `128` → 12 words (default), `256` → 24 words.\n * @returns A space-separated English mnemonic phrase.\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return bip39Generate(wordlist, strength);\n}\n\n/**\n * Validate a BIP-39 mnemonic against the English wordlist and its checksum.\n *\n * @param mnemonic - The candidate phrase.\n * @returns `true` if the phrase is a structurally valid, checksum-correct\n * English BIP-39 mnemonic; `false` otherwise. Never throws.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return bip39Validate(mnemonic, wordlist);\n}\n\n/** Resolve the address index from options, defaulting to 0. */\nfunction addressIndex(opts?: DerivationOptions): number {\n const index = opts?.accountIndex ?? 0;\n if (!Number.isInteger(index) || index < 0) {\n throw new Error(`accountIndex must be a non-negative integer, got ${index}`);\n }\n return index;\n}\n\n/**\n * Validate a mnemonic and derive its BIP-39 seed.\n *\n * Centralizing this here is the single guard against the fund-loss footgun where\n * a typo'd phrase (valid words, wrong checksum) would otherwise silently derive\n * a valid-looking but WRONG account. {@link mnemonicToSeed} does NOT check the\n * checksum, so we must validate first. The thrown error deliberately omits the\n * mnemonic text to avoid leaking secret material into logs.\n */\nasync function seedFromMnemonic(mnemonic: string): Promise<Uint8Array> {\n if (!validateMnemonic(mnemonic)) {\n throw new Error(\"invalid mnemonic\");\n }\n return mnemonicToSeed(mnemonic);\n}\n\n/** Derive a secp256k1 HD node at the given BIP-44 path from a mnemonic. */\nasync function deriveSecp256k1(\n mnemonic: string,\n coinType: number,\n index: number,\n): Promise<{ privateKey: Uint8Array; publicKey: Uint8Array }> {\n const seed = await seedFromMnemonic(mnemonic);\n const node = HDKey.fromMasterSeed(seed).derive(\n `m/44'/${coinType}'/0'/0/${index}`,\n );\n if (!node.privateKey || !node.publicKey) {\n throw new Error(\"failed to derive secp256k1 key from mnemonic\");\n }\n // node.publicKey is the 33-byte compressed form.\n return { privateKey: node.privateKey, publicKey: node.publicKey };\n}\n\n/**\n * Render 20 address bytes as an EIP-55 mixed-case checksummed `0x` address.\n *\n * EIP-55: lowercase the hex address, take keccak256 of the lowercase hex\n * (without `0x`) as ASCII, and uppercase each hex nibble whose corresponding\n * keccak nibble is >= 8.\n */\nfunction toEip55Checksum(addressBytes: Uint8Array): string {\n const lowerHex = Array.from(addressBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n const hashHex = Array.from(keccak_256(new TextEncoder().encode(lowerHex)))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let out = \"0x\";\n for (let i = 0; i < lowerHex.length; i++) {\n const c = lowerHex[i];\n out += parseInt(hashHex[i], 16) >= 8 ? c.toUpperCase() : c;\n }\n return out;\n}\n\n/**\n * Derive a native QoreChain account (Cosmos-style secp256k1) from a mnemonic.\n *\n * Path: `m/44'/118'/0'/0/{accountIndex}`. The address is the bech32 (`qor`)\n * encoding of `ripemd160(sha256(compressedPublicKey))`.\n *\n * @returns The account including its 32-byte secp256k1 private key.\n */\nexport async function deriveNativeAccount(\n mnemonic: string,\n opts?: DerivationOptions,\n): Promise<Secp256k1Account> {\n const index = addressIndex(opts);\n const { privateKey, publicKey } = await deriveSecp256k1(\n mnemonic,\n COIN_TYPE_NATIVE,\n index,\n );\n const digest = ripemd160(sha256(publicKey)); // 20 bytes\n const address = bytesToBech32(digest, NATIVE_PREFIX);\n return { type: \"native\", address, publicKey, privateKey };\n}\n\n/**\n * Derive an EVM account from a mnemonic.\n *\n * Path: `m/44'/60'/0'/0/{accountIndex}`. The address is the last 20 bytes of\n * `keccak256(uncompressedPublicKey[1:])`, EIP-55 checksummed.\n *\n * @returns The account including its 32-byte secp256k1 private key.\n */\nexport async function deriveEvmAccount(\n mnemonic: string,\n opts?: DerivationOptions,\n): Promise<Secp256k1Account> {\n const index = addressIndex(opts);\n const { privateKey, publicKey } = await deriveSecp256k1(\n mnemonic,\n COIN_TYPE_EVM,\n index,\n );\n // EVM addresses are computed from the 64-byte uncompressed public key body\n // (drop the 0x04 prefix byte). Decompress the already-derived compressed key\n // rather than touching the private key again.\n const uncompressed = secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(\n false,\n ); // 65 bytes\n const hash = keccak_256(uncompressed.slice(1)); // 32 bytes\n const addressBytes = hash.slice(-20); // last 20 bytes\n const address = toEip55Checksum(addressBytes);\n return { type: \"evm\", address, publicKey, privateKey };\n}\n\n/**\n * Derive an SVM (Solana-style ed25519) account from a mnemonic.\n *\n * Path: `m/44'/501'/{accountIndex}'/0'` — the conventional Solana derivation,\n * all segments hardened (SLIP-0010 for ed25519 supports hardened keys only).\n * The address is the base58 encoding of the 32-byte ed25519 public key.\n *\n * @returns The account including its 64-byte Solana-style secret key\n * (`privateSeed32 || publicKey32`).\n */\nexport async function deriveSvmAccount(\n mnemonic: string,\n opts?: DerivationOptions,\n): Promise<Ed25519Account> {\n const index = addressIndex(opts);\n const seed = await seedFromMnemonic(mnemonic);\n const node = Slip10HDKey.fromMasterSeed(seed).derive(\n `m/44'/${COIN_TYPE_SVM}'/${index}'/0'`,\n );\n const publicKey = node.publicKeyRaw; // bare 32-byte ed25519 public key\n // Solana secret keys are 64 bytes: the 32-byte private seed followed by the\n // 32-byte public key (the format Keypair.fromSecretKey expects).\n const secretKey = new Uint8Array(64);\n secretKey.set(node.privateKey, 0);\n secretKey.set(publicKey, 32);\n const address = base58.encode(publicKey);\n return { type: \"svm\", address, publicKey, secretKey };\n}\n","/**\n * PQC algorithm identifiers, mirroring the chain's `x/pqc` cryptographic-agility\n * framework (core `x/pqc/types/algorithm.go`).\n *\n * These numeric IDs are the on-the-wire values the chain expects in\n * `MsgRegisterPQCKeyV2.algorithm_id` and in the `PQCHybridSignature` TX\n * extension's `algorithm_id` field, so they MUST stay in sync with the core enum.\n */\n\n/**\n * Identifies a PQC algorithm. Numeric to match the chain's `uint32 AlgorithmID`.\n * IDs 1–2 are the initial algorithms; 3–255 are reserved for future\n * governance-approved algorithms.\n */\nexport type AlgorithmID = number;\n\n/** Unset / invalid algorithm (core: `AlgorithmUnspecified`). */\nexport const AlgorithmUnspecified: AlgorithmID = 0;\n/** Dilithium-5 = ML-DSA-87, NIST FIPS 204 signatures (core: `AlgorithmDilithium5`). */\nexport const AlgorithmDilithium5: AlgorithmID = 1;\n/** ML-KEM-1024, NIST FIPS 203 key encapsulation (core: `AlgorithmMLKEM1024`). */\nexport const AlgorithmMLKEM1024: AlgorithmID = 2;\n\n/** Human-readable name for an algorithm ID (matches core `AlgorithmID.String()`). */\nexport function algorithmName(id: AlgorithmID): string {\n switch (id) {\n case AlgorithmUnspecified:\n return \"unspecified\";\n case AlgorithmDilithium5:\n return \"dilithium5\";\n case AlgorithmMLKEM1024:\n return \"mlkem1024\";\n default:\n return `algorithm_${id}`;\n }\n}\n\n/** True if the algorithm is a digital-signature scheme (core `IsSignature`). */\nexport function isSignatureAlgorithm(id: AlgorithmID): boolean {\n return id === AlgorithmDilithium5;\n}\n","/**\n * Post-quantum (PQC) signing for QoreChain, using ML-DSA-87 (Dilithium-5,\n * NIST FIPS 204) for digital signatures.\n *\n * QoreChain treats PQC as a first-class signature scheme via a hybrid\n * architecture (see the core `PQC_INTEGRATION.md`): a transaction carries the\n * usual classical (secp256k1 / ed25519) signature PLUS an ML-DSA-87 signature\n * attached as a `PQCHybridSignature` TX extension. The chain's ante handler\n * verifies both, so quantum-safe wallets stay compatible with classical\n * verification.\n *\n * Scope: this module provides the signing PRIMITIVES (keygen / sign / verify),\n * a pluggable {@link Signer} for the `pqc` and `hybrid` postures, and a builder\n * for the on-chain hybrid-signature extension OBJECT. It deliberately does NOT\n * assemble or broadcast transactions — the tx-builder attaches the extension\n * the {@link buildHybridSignatureExtension} result describes.\n *\n * Crypto is delegated entirely to the audited, pure-TS `@noble/post-quantum`\n * (`ml_dsa87`). No primitives are reimplemented here.\n */\n\nimport { ml_dsa87 } from \"@noble/post-quantum/ml-dsa.js\";\nimport { randomBytes } from \"@noble/hashes/utils\";\nimport {\n AlgorithmDilithium5,\n isSignatureAlgorithm,\n algorithmName,\n type AlgorithmID,\n} from \"./pqc-algorithm\";\nimport type { Signer, SignOutput, PqcSignaturePart } from \"./signer\";\n\nexport {\n AlgorithmUnspecified,\n AlgorithmDilithium5,\n AlgorithmMLKEM1024,\n algorithmName,\n isSignatureAlgorithm,\n type AlgorithmID,\n} from \"./pqc-algorithm\";\nexport type {\n Signer,\n SignOutput,\n SignatureMode,\n PqcSignaturePart,\n} from \"./signer\";\n\n/**\n * ML-DSA-87 (Dilithium-5) byte lengths.\n *\n * These are fixed by NIST FIPS 204 and match the chain's `x/pqc` constants\n * exactly. The installed `@noble/post-quantum` `ml_dsa87` does not expose these\n * as runtime properties, so we encode the standard's values directly; the test\n * suite asserts that the library actually produces keys/signatures of these\n * lengths, guarding against any future library drift.\n */\n/** ML-DSA-87 public-key length, in bytes (FIPS 204 / core: 2592). */\nexport const ML_DSA_87_PUBLIC_KEY_LENGTH = 2592;\n/** ML-DSA-87 secret-key length, in bytes (FIPS 204 / core: 4896). */\nexport const ML_DSA_87_SECRET_KEY_LENGTH = 4896;\n/** ML-DSA-87 signature length, in bytes (FIPS 204 / core: 4627). */\nexport const ML_DSA_87_SIGNATURE_LENGTH = 4627;\n\n/** Length, in bytes, of the deterministic-keygen seed (xi) per FIPS 204. */\nexport const ML_DSA_87_SEED_LENGTH = 32;\n\n/**\n * The TX-extension type URL for the on-chain `PQCHybridSignature` message\n * (core: `HybridSigTypeURL`). The tx-builder uses this as the extension's\n * type URL when packing the object from {@link buildHybridSignatureExtension}.\n */\nexport const HYBRID_SIG_TYPE_URL = \"/qorechain.pqc.v1.PQCHybridSignature\";\n\n/** An ML-DSA-87 (Dilithium-5) keypair. Treat `secretKey` as a secret. */\nexport interface PqcKeypair {\n /** 2592-byte ML-DSA-87 public key. */\n publicKey: Uint8Array;\n /** 4896-byte ML-DSA-87 secret key. Handle as a secret; never logged. */\n secretKey: Uint8Array;\n}\n\n/**\n * Generate an ML-DSA-87 (Dilithium-5) keypair.\n *\n * @param seed Optional 32-byte seed for deterministic keygen (e.g. derived from\n * a wallet). When omitted, a cryptographically random keypair is produced.\n * Must be exactly {@link ML_DSA_87_SEED_LENGTH} bytes if provided.\n */\nexport function generatePqcKeypair(seed?: Uint8Array): PqcKeypair {\n if (seed !== undefined && seed.length !== ML_DSA_87_SEED_LENGTH) {\n throw new Error(\n `ML-DSA-87 seed must be ${ML_DSA_87_SEED_LENGTH} bytes, got ${seed.length}`,\n );\n }\n // When no seed is supplied, draw a fresh random 32-byte seed so keygen always\n // receives one explicitly (a random seed yields a random keypair).\n const xi = seed ?? randomBytes(ML_DSA_87_SEED_LENGTH);\n const kp = ml_dsa87.keygen(xi);\n return { publicKey: kp.publicKey, secretKey: kp.secretKey };\n}\n\n/** Sign a message with an ML-DSA-87 (Dilithium-5) secret key. */\nexport function pqcSign(secretKey: Uint8Array, message: Uint8Array): Uint8Array {\n return ml_dsa87.sign(secretKey, message);\n}\n\n/** Verify an ML-DSA-87 (Dilithium-5) signature over a message. */\nexport function pqcVerify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n return ml_dsa87.verify(publicKey, message, signature);\n}\n\n/**\n * The on-chain `PQCHybridSignature` TX extension, as a plain object whose keys\n * mirror the core struct's JSON field tags EXACTLY\n * (`x/pqc/types/hybrid.go`):\n *\n * ```go\n * type PQCHybridSignature struct {\n * AlgorithmID AlgorithmID `json:\"algorithm_id\"`\n * PQCSignature []byte `json:\"pqc_signature\"`\n * PQCPublicKey []byte `json:\"pqc_public_key,omitempty\"`\n * }\n * ```\n *\n * The tx-builder is responsible for encoding this and attaching it under\n * {@link HYBRID_SIG_TYPE_URL}.\n */\nexport interface PQCHybridSignature {\n /** PQC algorithm ID (core `AlgorithmID`). */\n algorithm_id: AlgorithmID;\n /** Raw PQC signature bytes. */\n pqc_signature: Uint8Array;\n /** Optional PQC public key for auto-registration on first use. */\n pqc_public_key?: Uint8Array;\n}\n\n/**\n * Build the on-chain `PQCHybridSignature` extension object from a signature.\n *\n * Validation mirrors the core `PQCHybridSignature.Validate()`: the algorithm\n * must be a signature scheme, the signature must be non-empty, and for\n * Dilithium-5 the signature/public-key lengths are enforced.\n *\n * `pqc_public_key` is omitted entirely when no public key is supplied, matching\n * the `omitempty` JSON tag on the core struct.\n */\nexport function buildHybridSignatureExtension(args: {\n algorithmId: AlgorithmID;\n signature: Uint8Array;\n publicKey?: Uint8Array;\n}): PQCHybridSignature {\n const { algorithmId, signature, publicKey } = args;\n\n if (!isSignatureAlgorithm(algorithmId)) {\n throw new Error(\n `algorithm ${algorithmName(algorithmId)} is not a PQC signature algorithm`,\n );\n }\n if (signature.length === 0) {\n throw new Error(\"PQC signature cannot be empty\");\n }\n if (algorithmId === AlgorithmDilithium5) {\n if (signature.length !== ML_DSA_87_SIGNATURE_LENGTH) {\n throw new Error(\n `dilithium5 signature must be ${ML_DSA_87_SIGNATURE_LENGTH} bytes, got ${signature.length}`,\n );\n }\n if (publicKey !== undefined && publicKey.length !== ML_DSA_87_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `dilithium5 public key must be ${ML_DSA_87_PUBLIC_KEY_LENGTH} bytes, got ${publicKey.length}`,\n );\n }\n }\n\n const ext: PQCHybridSignature = {\n algorithm_id: algorithmId,\n pqc_signature: signature,\n };\n if (publicKey !== undefined) {\n ext.pqc_public_key = publicKey;\n }\n return ext;\n}\n\n/**\n * A pqc-only {@link Signer}: produces an ML-DSA-87 (Dilithium-5) signature and\n * no classical signature. Corresponds to the chain's `pqc_only` key type.\n */\nexport class PqcSigner implements Signer {\n readonly mode = \"pqc\" as const;\n private readonly keypair: PqcKeypair;\n private readonly algorithmId: AlgorithmID;\n\n constructor(keypair: PqcKeypair, algorithmId: AlgorithmID = AlgorithmDilithium5) {\n this.keypair = keypair;\n this.algorithmId = algorithmId;\n }\n\n /** The PQC public key (the signing identity in pqc-only mode). */\n publicKey(): Uint8Array {\n return this.keypair.publicKey;\n }\n\n async sign(message: Uint8Array): Promise<SignOutput> {\n const part: PqcSignaturePart = {\n algorithmId: this.algorithmId,\n signature: pqcSign(this.keypair.secretKey, message),\n publicKey: this.keypair.publicKey,\n };\n return { pqc: part };\n }\n}\n\n/**\n * A hybrid {@link Signer}: wraps a classical signer and an ML-DSA-87 keypair,\n * producing BOTH a classical signature and a PQC signature over the same\n * message. Corresponds to the chain's `hybrid` key type.\n *\n * The account identity is the wrapped classical signer's public key, so a\n * hybrid account is indistinguishable from a classical one to wallets that do\n * not understand the PQC extension.\n */\nexport class HybridSigner implements Signer {\n readonly mode = \"hybrid\" as const;\n private readonly classical: Signer;\n private readonly keypair: PqcKeypair;\n private readonly algorithmId: AlgorithmID;\n\n /**\n * @param classical The wrapped classical signer. Must be a `classical`-mode\n * signer; its `classicalSignature` output is passed through unchanged.\n * @param keypair The ML-DSA-87 keypair used for the PQC half.\n * @throws if `classical` is not a `classical`-mode signer.\n */\n constructor(\n classical: Signer,\n keypair: PqcKeypair,\n algorithmId: AlgorithmID = AlgorithmDilithium5,\n ) {\n if (classical.mode !== \"classical\") {\n throw new Error(\"HybridSigner requires a classical-mode signer\");\n }\n this.classical = classical;\n this.keypair = keypair;\n this.algorithmId = algorithmId;\n }\n\n /** The classical public key — the on-chain account identity. */\n publicKey(): Uint8Array {\n return this.classical.publicKey();\n }\n\n async sign(message: Uint8Array): Promise<SignOutput> {\n const classicalOut = await this.classical.sign(message);\n if (classicalOut.classicalSignature === undefined) {\n throw new Error(\n \"wrapped classical signer did not produce a classical signature\",\n );\n }\n const part: PqcSignaturePart = {\n algorithmId: this.algorithmId,\n signature: pqcSign(this.keypair.secretKey, message),\n publicKey: this.keypair.publicKey,\n };\n return { classicalSignature: classicalOut.classicalSignature, pqc: part };\n }\n}\n","/**\n * Adapter from a native QoreChain secp256k1 key to a cosmjs signer.\n *\n * The accounts module (`deriveNativeAccount`, Task 13) yields a raw 32-byte\n * secp256k1 private key. The transaction layer signs through cosmjs's\n * `SigningStargateClient`, which expects an `OfflineDirectSigner`. This module\n * bridges the two via `@cosmjs/proto-signing`'s `DirectSecp256k1Wallet`, binding\n * the key to the network's bech32 account prefix (`qor`).\n *\n * The signer performs SIGN_MODE_DIRECT (protobuf) signing — the native chain's\n * default — so the produced address and signatures match what the node's ante\n * handler verifies for a classical secp256k1 account.\n */\n\nimport {\n DirectSecp256k1Wallet,\n type OfflineDirectSigner,\n} from \"@cosmjs/proto-signing\";\n\n/**\n * Adapt a raw secp256k1 private key into a cosmjs {@link OfflineDirectSigner}.\n *\n * @param privateKey - Raw 32-byte secp256k1 private key (e.g. the `privateKey`\n * field of a {@link Secp256k1Account} from `deriveNativeAccount`).\n * @param prefix - Bech32 account prefix for the network (QoreChain: `\"qor\"`).\n * @returns A direct (protobuf) offline signer whose single account address is\n * the bech32 encoding of the key under `prefix`.\n */\nexport async function directSignerFromPrivateKey(\n privateKey: Uint8Array,\n prefix: string,\n): Promise<OfflineDirectSigner> {\n if (privateKey.length !== 32) {\n throw new Error(\n `secp256k1 private key must be 32 bytes, got ${privateKey.length}`,\n );\n }\n return DirectSecp256k1Wallet.fromKey(privateKey, prefix);\n}\n","/**\n * Encoding and attachment of the QoreChain PQC hybrid-signature extension to a\n * native tx.\n *\n * ──────────────────────────────────────────────────────────────────────────\n * The wallet ↔ chain contract (now known and enforced)\n * ──────────────────────────────────────────────────────────────────────────\n * These are low-level encode/attach primitives. The full, contract-correct\n * hybrid build sequence lives in {@link ../tx/hybrid-tx} ({@link buildHybridTx}\n * / {@link signAndBroadcastHybrid}) — prefer those for end-to-end signing. This\n * module documents the on-wire encoding the chain reads:\n *\n * - `PQCHybridSignature` struct, JSON field tags (`algorithm_id`,\n * `pqc_signature`, `pqc_public_key,omitempty`), and type URL\n * `/qorechain.pqc.v1.PQCHybridSignature`.\n * - The ante handler extracts the extension by type URL and JSON-decodes it, so\n * the `Any.value` carries the struct's Go-JSON encoding (Go marshals\n * `[]byte` as standard padded base64 strings), NOT a protobuf message. This\n * module encodes accordingly (see {@link toGoJson}).\n * - PLACEMENT: the extension is a CRITICAL extension option — it goes in\n * `TxBody.extension_options`. {@link buildHybridTx} always uses this slot.\n * This module additionally exposes `non_critical_extension_options` via\n * {@link AttachHybridOptions.placement} for callers with other needs, but the\n * chain reads the critical slot.\n * - SIGNED BYTES: the ML-DSA-87 signature is computed over the tx body WITH the\n * PQC extension REMOVED, framed with the authInfo bytes:\n * `BE32(len(B0)) || B0 || BE32(len(A)) || A` (see {@link buildHybridTx} for\n * the full contract). This module does not decide what the PQC signature\n * signs — {@link buildHybridTx} does.\n *\n * Cross-implementation proto byte-determinism (cosmjs encode vs. the chain's\n * re-marshal) is confirmed on the live testnet for the default registry message\n * types.\n */\n\nimport { Any } from \"cosmjs-types/google/protobuf/any\";\nimport { TxBody } from \"cosmjs-types/cosmos/tx/v1beta1/tx\";\nimport {\n HYBRID_SIG_TYPE_URL,\n type PQCHybridSignature,\n} from \"../accounts/pqc\";\n\n/** Where the hybrid-signature extension is placed within the `TxBody`. */\nexport type HybridPlacement =\n | \"non_critical_extension_options\"\n | \"extension_options\";\n\n/** Options for {@link attachHybridExtension}. */\nexport interface AttachHybridOptions {\n /**\n * Which `TxBody` extension list to attach the extension to. Defaults to\n * `\"non_critical_extension_options\"`. See the module header: the exact slot\n * the ante handler reads is not determinable from public core and needs\n * live-testnet verification.\n */\n placement?: HybridPlacement;\n}\n\n/**\n * Serialize a {@link PQCHybridSignature} the way Go's `encoding/json` would\n * marshal the core struct, so the node's JSON-decoding ante handler can read it.\n *\n * Go marshals `[]byte` fields as standard (padded) base64 strings, and omits\n * `pqc_public_key` entirely when empty (`omitempty`). The numeric `algorithm_id`\n * is emitted as a JSON number.\n */\nfunction toGoJson(ext: PQCHybridSignature): string {\n const obj: {\n algorithm_id: number;\n pqc_signature: string;\n pqc_public_key?: string;\n } = {\n algorithm_id: ext.algorithm_id,\n pqc_signature: base64(ext.pqc_signature),\n };\n if (ext.pqc_public_key !== undefined && ext.pqc_public_key.length > 0) {\n obj.pqc_public_key = base64(ext.pqc_public_key);\n }\n return JSON.stringify(obj);\n}\n\n/** Standard base64 (padded) encoding of bytes, matching Go's `[]byte` marshal. */\nfunction base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n // btoa is available in Node 16+ and all SDK target runtimes.\n return btoa(binary);\n}\n\n/**\n * Encode a {@link PQCHybridSignature} into a protobuf `Any` for use as a\n * `TxBody` extension option.\n *\n * The `Any.typeUrl` is the core {@link HYBRID_SIG_TYPE_URL}; the `Any.value` is\n * the UTF-8 bytes of the struct's Go-JSON encoding (see {@link toGoJson} and the\n * module header — the chain reads this extension by type URL + JSON decoding,\n * not protobuf).\n */\nexport function encodeHybridExtension(ext: PQCHybridSignature): Any {\n const value = new TextEncoder().encode(toGoJson(ext));\n return Any.fromPartial({ typeUrl: HYBRID_SIG_TYPE_URL, value });\n}\n\n/**\n * Return a copy of `body` with the encoded hybrid-signature extension attached.\n *\n * The input `body` is not mutated. By default the extension is added to\n * `non_critical_extension_options`; pass `placement` to use `extension_options`\n * instead.\n *\n * @see The module header — both the placement and the bytes the PQC signature\n * must cover require live-testnet verification against the `full` build.\n */\nexport function attachHybridExtension(\n body: TxBody,\n ext: PQCHybridSignature,\n opts: AttachHybridOptions = {},\n): TxBody {\n const anyExt = encodeHybridExtension(ext);\n const placement = opts.placement ?? \"non_critical_extension_options\";\n const next = TxBody.fromPartial({\n messages: body.messages,\n memo: body.memo,\n timeoutHeight: body.timeoutHeight,\n extensionOptions: [...body.extensionOptions],\n nonCriticalExtensionOptions: [...body.nonCriticalExtensionOptions],\n });\n if (placement === \"extension_options\") {\n next.extensionOptions.push(anyExt);\n } else {\n next.nonCriticalExtensionOptions.push(anyExt);\n }\n return next;\n}\n","/**\n * End-to-end hybrid (classical + post-quantum) transaction signing for\n * QoreChain.\n *\n * A hybrid transaction carries the usual classical secp256k1 signature in\n * `TxRaw.signatures` PLUS an ML-DSA-87 (Dilithium-5) signature attached to the\n * `TxBody` as a `PQCHybridSignature` extension. The chain's ante handler\n * verifies BOTH, so a hybrid account stays interoperable with classical\n * verification while gaining quantum safety.\n *\n * ──────────────────────────────────────────────────────────────────────────\n * The wallet ↔ chain contract (enforced by the chain)\n * ──────────────────────────────────────────────────────────────────────────\n * The chain verifies the ML-DSA-87 signature over the tx body WITH the PQC\n * extension REMOVED. Concretely:\n *\n * - `B0` = canonical protobuf bytes of the `TxBody` containing the\n * messages/memo/timeoutHeight but NOT the `PQCHybridSignature` extension.\n * - `A` = the tx `authInfoBytes`, verbatim — the same bytes that are\n * broadcast.\n * - PQC signed message = `BE32(len(B0)) || B0 || BE32(len(A)) || A`\n * (4-byte big-endian length prefixes; NO hashing, NO domain prefix).\n * - PQC signature = `ml_dsa87.sign(pqcSecretKey, message)` (pure\n * ML-DSA-87, empty context) — 4627 bytes for Dilithium-5.\n * - The `PQCHybridSignature` extension is then added to\n * `TxBody.extension_options` (CRITICAL extension options) as an `Any` with\n * `type_url = \"/qorechain.pqc.v1.PQCHybridSignature\"` and `value` = UTF-8\n * bytes of the Go-JSON `{ \"algorithm_id\", \"pqc_signature\", \"pqc_public_key\"? }`\n * (standard padded base64; `pqc_public_key` omitted when not provided).\n * - The CLASSICAL signature is computed normally (SIGN_MODE_DIRECT) over the\n * FINAL body (the one WITH the PQC extension) + authInfo + chainId +\n * accountNumber, and goes in `TxRaw.signatures` (outside the body). There is\n * no self-reference: the classical signature never signs itself.\n *\n * The signer's PQC key must be registered on-chain (via `MsgRegisterPQCKey`)\n * before hybrid txs PQC-verify — unless `includePqcPublicKey` is set, which\n * embeds the key for auto-registration on first use. Registering the key is the\n * caller's responsibility.\n *\n * Determinism note: the framing above is byte-for-byte deterministic on the\n * wallet side. Cross-implementation determinism (this `cosmjs`/`cosmjs-types`\n * proto encoding vs. the chain's re-marshal of the same `TxBody`) is confirmed\n * against the live testnet; if a custom message type with non-canonical field\n * ordering were used, callers must ensure their `Registry` encodes canonically.\n */\n\nimport type { OfflineDirectSigner, Registry } from \"@cosmjs/proto-signing\";\nimport {\n encodePubkey,\n makeAuthInfoBytes,\n} from \"@cosmjs/proto-signing\";\nimport { encodeSecp256k1Pubkey } from \"@cosmjs/amino\";\nimport { SignMode } from \"cosmjs-types/cosmos/tx/signing/v1beta1/signing\";\nimport {\n TxBody,\n TxRaw,\n SignDoc,\n} from \"cosmjs-types/cosmos/tx/v1beta1/tx\";\nimport type { EncodeObject } from \"@cosmjs/proto-signing\";\n\nimport {\n pqcSign,\n buildHybridSignatureExtension,\n AlgorithmDilithium5,\n type PqcKeypair,\n} from \"../accounts/pqc\";\nimport { encodeHybridExtension } from \"./hybrid\";\nimport type { StdFee } from \"./fees\";\nimport type { BroadcastMode, BroadcastResult } from \"./broadcast\";\n\n/** The fields shared by {@link buildHybridTx} and {@link signAndBroadcastHybrid}. */\nexport interface BuildHybridTxOptions {\n /**\n * The protobuf message {@link Registry} used to encode the messages into the\n * `TxBody`. Use cosmjs's `defaultRegistryTypes` (plus any custom QoreChain\n * message types) — the same registry the network's `TxClient` is built with.\n */\n registry: Registry;\n /**\n * The classical secp256k1 direct signer (e.g. from\n * `directSignerFromPrivateKey`). Its first account is used as the signer\n * identity and to produce the SIGN_MODE_DIRECT classical signature.\n */\n signer: OfflineDirectSigner;\n /** The ML-DSA-87 (Dilithium-5) keypair providing the post-quantum half. */\n pqcKeypair: PqcKeypair;\n /** The transaction messages, as `{ typeUrl, value }` encode objects. */\n messages: readonly EncodeObject[];\n /** The fee to pay. */\n fee: StdFee;\n /** Optional memo. Defaults to `\"\"`. */\n memo?: string;\n /** The chain id (e.g. `\"qorechain-diana\"`). */\n chainId: string;\n /** The on-chain account number of the signer. */\n accountNumber: number | bigint;\n /** The signer's current account sequence (nonce). */\n sequence: number | bigint;\n /** Optional `timeoutHeight` for the tx body. */\n timeoutHeight?: bigint;\n /**\n * When `true`, embed the 2592-byte ML-DSA-87 public key in the extension so\n * the chain can auto-register it on first use. Defaults to `false` (the key\n * is expected to already be registered via `MsgRegisterPQCKey`).\n */\n includePqcPublicKey?: boolean;\n}\n\n/** The fully assembled hybrid transaction and the intermediate artifacts. */\nexport interface BuiltHybridTx {\n /** The assembled `TxRaw` (final body + authInfo + classical signature). */\n txRaw: TxRaw;\n /** Encoded `TxRaw` bytes, ready to broadcast. */\n txRawBytes: Uint8Array;\n /** The `authInfoBytes` (`A`) — identical in the PQC framing and the SignDoc. */\n authInfoBytes: Uint8Array;\n /** The exact bytes the ML-DSA-87 signature was computed over (the framing). */\n pqcSignedMessage: Uint8Array;\n /** The raw ML-DSA-87 signature (Dilithium-5: 4627 bytes). */\n pqcSignature: Uint8Array;\n}\n\n/** A big-endian 4-byte length prefix, matching the chain contract framing. */\nfunction be32(n: number): Uint8Array {\n const b = new Uint8Array(4);\n b[0] = (n >>> 24) & 0xff;\n b[1] = (n >>> 16) & 0xff;\n b[2] = (n >>> 8) & 0xff;\n b[3] = n & 0xff;\n return b;\n}\n\n/** Decode a standard base64 string to bytes (no extra deps; atob is universal). */\nfunction fromBase64(b64: string): Uint8Array {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\n/** Concatenate byte arrays. */\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n out.set(p, off);\n off += p.length;\n }\n return out;\n}\n\n/**\n * Build a fully signed hybrid transaction following the chain contract.\n *\n * The build sequence (see the module header for the exact contract):\n * 1. Encode `B0` — the `TxBody` WITHOUT the PQC extension.\n * 2. Encode `A` — the single-signer `AuthInfo` (SIGN_MODE_DIRECT).\n * 3. Compute `message = BE32(len B0) || B0 || BE32(len A) || A`; ML-DSA-87\n * sign it.\n * 4. Build the PQC extension `Any` and attach it to a NEW body identical to\n * step 1 but with `extensionOptions = [ext]`; encode → final body bytes.\n * 5. SIGN_MODE_DIRECT classical sign over `SignDoc{ finalBody, A, chainId,\n * accountNumber }`.\n * 6. Assemble `TxRaw{ finalBody, A, [classicalSig] }`.\n *\n * The returned {@link BuiltHybridTx} exposes the intermediate artifacts so the\n * contract can be asserted/audited.\n */\nexport async function buildHybridTx(\n opts: BuildHybridTxOptions,\n): Promise<BuiltHybridTx> {\n const {\n registry,\n signer,\n pqcKeypair,\n messages,\n fee,\n chainId,\n accountNumber,\n sequence,\n } = opts;\n const memo = opts.memo ?? \"\";\n const timeoutHeight = opts.timeoutHeight ?? 0n;\n\n const accounts = await signer.getAccounts();\n if (accounts.length === 0) {\n throw new Error(\"signer exposes no accounts\");\n }\n const account = accounts[0];\n\n // 1. B0 — body WITHOUT the PQC extension. Encode the messages via the registry.\n const encodedMessages = messages.map((m) => registry.encodeAsAny(m));\n const baseBody = TxBody.fromPartial({\n messages: encodedMessages,\n memo,\n timeoutHeight,\n });\n const b0 = TxBody.encode(baseBody).finish();\n\n // 2. A — single-signer AuthInfo (SIGN_MODE_DIRECT). The signer's classical\n // secp256k1 pubkey identifies the account.\n const pubkeyAny = encodePubkey(encodeSecp256k1Pubkey(account.pubkey));\n const gasLimit = Number(fee.gas);\n const authInfoBytes = makeAuthInfoBytes(\n [{ pubkey: pubkeyAny, sequence: BigInt(sequence) }],\n fee.amount,\n gasLimit,\n fee.granter,\n fee.payer,\n SignMode.SIGN_MODE_DIRECT,\n );\n\n // 3. PQC framing + ML-DSA-87 signature over B0 + A (NOT the final body).\n const pqcSignedMessage = concatBytes(\n be32(b0.length),\n b0,\n be32(authInfoBytes.length),\n authInfoBytes,\n );\n const pqcSignature = pqcSign(pqcKeypair.secretKey, pqcSignedMessage);\n\n // 4. Build the PQC extension Any and attach it to the FINAL body as a\n // CRITICAL extension option.\n const ext = buildHybridSignatureExtension({\n algorithmId: AlgorithmDilithium5,\n signature: pqcSignature,\n publicKey: opts.includePqcPublicKey ? pqcKeypair.publicKey : undefined,\n });\n const extAny = encodeHybridExtension(ext);\n const finalBody = TxBody.fromPartial({\n messages: encodedMessages,\n memo,\n timeoutHeight,\n extensionOptions: [extAny],\n });\n const bodyBytesFinal = TxBody.encode(finalBody).finish();\n\n // 5. Classical SIGN_MODE_DIRECT signature over the FINAL body + A.\n const signDoc = SignDoc.fromPartial({\n bodyBytes: bodyBytesFinal,\n authInfoBytes,\n chainId,\n accountNumber: BigInt(accountNumber),\n });\n const { signature } = await signer.signDirect(account.address, signDoc);\n const classicalSig = fromBase64(signature.signature);\n\n // 6. Assemble TxRaw.\n const txRaw = TxRaw.fromPartial({\n bodyBytes: bodyBytesFinal,\n authInfoBytes,\n signatures: [classicalSig],\n });\n const txRawBytes = TxRaw.encode(txRaw).finish();\n\n return {\n txRaw,\n txRawBytes,\n authInfoBytes,\n pqcSignedMessage,\n pqcSignature,\n };\n}\n\n/**\n * A minimal broadcast transport for raw tx bytes. cosmjs's `StargateClient`\n * (and `SigningStargateClient`) satisfy this shape via `broadcastTx` /\n * `broadcastTxSync`, so production callers can pass an existing client; unit\n * tests can inject a fake.\n */\nexport interface HybridBroadcaster {\n /** Poll-to-commit broadcast: returns the delivery result. */\n broadcastTx(\n tx: Uint8Array,\n timeoutMs?: number,\n pollIntervalMs?: number,\n ): Promise<{\n code: number;\n transactionHash: string;\n height?: number;\n gasUsed?: bigint;\n gasWanted?: bigint;\n rawLog?: string;\n }>;\n /** Submit and return after CheckTx: returns the tx hash. */\n broadcastTxSync(tx: Uint8Array): Promise<string>;\n}\n\n/** Options for {@link signAndBroadcastHybrid}. */\nexport interface SignAndBroadcastHybridOptions extends BuildHybridTxOptions {\n /** The broadcast transport (e.g. a connected `StargateClient`). */\n transport: HybridBroadcaster;\n /** Broadcast mode. Defaults to `\"commit\"`. */\n mode?: BroadcastMode;\n}\n\n/**\n * Build, sign, and broadcast a hybrid transaction.\n *\n * Broadcast mode maps onto the transport:\n * - `commit` (default): polls until the tx lands in a block; throws on a\n * non-zero delivery code.\n * - `sync` / `async`: returns after mempool submission with just the tx hash.\n */\nexport async function signAndBroadcastHybrid(\n opts: SignAndBroadcastHybridOptions,\n): Promise<BroadcastResult> {\n const { transport } = opts;\n const mode: BroadcastMode = opts.mode ?? \"commit\";\n const built = await buildHybridTx(opts);\n\n if (mode === \"commit\") {\n const res = await transport.broadcastTx(built.txRawBytes);\n if (res.code !== 0) {\n throw new Error(\n `hybrid transaction failed with code ${res.code}: ${res.rawLog ?? \"(no log)\"} (hash ${res.transactionHash})`,\n );\n }\n return {\n transactionHash: res.transactionHash,\n code: res.code,\n height: res.height,\n gasUsed: res.gasUsed,\n gasWanted: res.gasWanted,\n rawLog: res.rawLog,\n };\n }\n\n const hash = await transport.broadcastTxSync(built.txRawBytes);\n return { transactionHash: hash, code: 0 };\n}\n","/**\n * `@qorechain/sdk` public API.\n *\n * The exports below are the deliberate, supported surface of the SDK. Start with\n * {@link createClient} for the high-level composed client; the individual\n * networks, accounts, query clients, and tx primitives are also exported for\n * callers who want to compose them directly. Internal helpers are not exported.\n */\n\n/** SDK version. */\nexport const VERSION = \"0.1.0\";\n\n// Top-level factory: the recommended entrypoint that resolves a network and\n// composes the read clients, fee helper, and a lazy signing entrypoint.\nexport { createClient } from \"./client\";\nexport type {\n QoreChainClient,\n CreateClientOptions,\n ConnectTxOptions,\n ClientFees,\n} from \"./client\";\n\n// Networks: presets, lookup/list helpers, and config types.\nexport * from \"./config/networks\";\n\n// Utilities: denom conversion and address encoding/validation.\nexport * from \"./utils/denom\";\nexport * from \"./utils/address\";\n\n// Accounts & keys. Re-export the documented derivation functions and types only.\n// The derive functions return key material deliberately (callers need it for\n// signing); nothing here leaks secrets implicitly.\nexport {\n generateMnemonic,\n validateMnemonic,\n deriveNativeAccount,\n deriveEvmAccount,\n deriveSvmAccount,\n} from \"./accounts/wallet\";\nexport type {\n KeyType,\n Account,\n DerivationOptions,\n Secp256k1Account,\n Ed25519Account,\n} from \"./accounts/types\";\n\n// Post-quantum (PQC) signing: ML-DSA-87 (Dilithium-5) primitives, the pluggable\n// Signer abstraction, and the on-chain hybrid-signature extension builder.\nexport {\n AlgorithmUnspecified,\n AlgorithmDilithium5,\n AlgorithmMLKEM1024,\n algorithmName,\n isSignatureAlgorithm,\n ML_DSA_87_PUBLIC_KEY_LENGTH,\n ML_DSA_87_SECRET_KEY_LENGTH,\n ML_DSA_87_SIGNATURE_LENGTH,\n ML_DSA_87_SEED_LENGTH,\n HYBRID_SIG_TYPE_URL,\n generatePqcKeypair,\n pqcSign,\n pqcVerify,\n buildHybridSignatureExtension,\n PqcSigner,\n HybridSigner,\n} from \"./accounts/pqc\";\nexport type {\n AlgorithmID,\n PqcKeypair,\n PQCHybridSignature,\n Signer,\n SignOutput,\n SignatureMode,\n PqcSignaturePart,\n} from \"./accounts/pqc\";\n\n// Read/query clients: shared HTTP transport, Cosmos+custom REST, the generic\n// JSON-RPC 2.0 client (with thin EVM helpers), and the typed `qor_` namespace.\nexport {\n getJson,\n postJsonRpc,\n buildUrl,\n joinUrl,\n QoreHttpError,\n} from \"./query/http\";\nexport type {\n FetchLike,\n QueryValue,\n HttpOptions,\n GetJsonOptions,\n} from \"./query/http\";\nexport { JsonRpcClient, JsonRpcError } from \"./query/jsonrpc\";\nexport type {\n JsonRpcClientOptions,\n JsonRpcResponse,\n JsonRpcErrorObject,\n} from \"./query/jsonrpc\";\nexport { RestClient } from \"./query/rest\";\nexport type {\n RestClientOptions,\n Coin,\n PageResponse,\n AllBalancesResponse,\n BalanceResponse,\n Pagination,\n PaginatedOptions,\n FeeUrgency,\n} from \"./query/rest\";\nexport { QorClient } from \"./query/qor\";\n\n// Cross-VM reads: typed REST wrappers over `x/crossvm`. EVM→native routing\n// itself runs on-chain via the cross-VM bridge precompile in `@qorechain/evm`;\n// these helpers (and `QorClient.getCrossVmMessage`) track message state.\nexport {\n getCrossVmMessage,\n getPendingCrossVmMessages,\n getCrossVmParams,\n} from \"./query/crossvm\";\nexport type {\n CrossVmMessage,\n CrossVmMessageResponse,\n PendingCrossVmMessagesResponse,\n CrossVmParamsResponse,\n} from \"./query/crossvm\";\n\n// CosmWasm: read/signing client constructors plus thin typed wrappers over\n// `@cosmjs/cosmwasm-stargate` (query/instantiate/execute/upload).\nexport {\n createCosmWasmClient,\n connectCosmWasmSigner,\n queryContractSmart,\n getContractInfo,\n instantiate,\n execute,\n uploadCode,\n} from \"./cosmwasm\";\nexport type {\n ContractMsg,\n FeeInput,\n CosmWasmReadClient,\n CosmWasmSigningClient,\n InstantiateOpts,\n} from \"./cosmwasm\";\n\n// Native transactions: fee estimation, the signer adapter, the tx builder /\n// broadcaster, the low-level PQC hybrid extension encode/attach helpers, and the\n// end-to-end hybrid (classical + PQC) signing/broadcast builder. See each module\n// for details.\nexport { estimateFee, STATIC_FALLBACK } from \"./tx/fees\";\nexport type { StdFee, EstimateFeeOptions } from \"./tx/fees\";\nexport { directSignerFromPrivateKey } from \"./tx/signer-adapter\";\nexport type { BroadcastMode, BroadcastResult } from \"./tx/broadcast\";\nexport { TxClient, MSG_SEND_TYPE_URL } from \"./tx/builder\";\nexport type {\n SigningClientLike,\n TxClientOptions,\n TxConnectOptions,\n SignAndBroadcastOptions,\n SimulateOptions,\n BankSendOptions,\n} from \"./tx/builder\";\nexport { encodeHybridExtension, attachHybridExtension } from \"./tx/hybrid\";\nexport type { HybridPlacement, AttachHybridOptions } from \"./tx/hybrid\";\nexport { buildHybridTx, signAndBroadcastHybrid } from \"./tx/hybrid-tx\";\nexport type {\n BuildHybridTxOptions,\n BuiltHybridTx,\n HybridBroadcaster,\n SignAndBroadcastHybridOptions,\n} from \"./tx/hybrid-tx\";\n"]}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@qorechain/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Official TypeScript SDK for building decentralized applications on the QoreChain network.",
5
+ "license": "Apache-2.0",
6
+ "author": "QoreChain",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsup",
24
+ "test": "vitest run",
25
+ "test:watch": "vitest",
26
+ "typecheck": "tsc --noEmit",
27
+ "lint": "eslint src test",
28
+ "docs:api": "typedoc"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/qorechain/qorechain-sdk.git",
33
+ "directory": "packages/ts"
34
+ },
35
+ "homepage": "https://github.com/qorechain/qorechain-sdk#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/qorechain/qorechain-sdk/issues"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "dependencies": {
43
+ "@cosmjs/amino": "^0.39.0",
44
+ "@cosmjs/proto-signing": "^0.39.0",
45
+ "@cosmjs/stargate": "^0.39.0",
46
+ "@noble/curves": "^1.9.0",
47
+ "@noble/hashes": "^1.8.0",
48
+ "@noble/post-quantum": "0.4.1",
49
+ "@scure/base": "^1.2.0",
50
+ "@scure/bip32": "^1.7.0",
51
+ "@scure/bip39": "^1.6.0",
52
+ "bech32": "^2.0.0",
53
+ "cosmjs-types": "^0.11.0",
54
+ "micro-key-producer": "^0.9.0",
55
+ "@cosmjs/cosmwasm-stargate": "^0.39.0"
56
+ },
57
+ "devDependencies": {
58
+ "@cosmjs/crypto": "^0.39.0",
59
+ "@types/node": "^22.7.5",
60
+ "tsup": "^8.3.0",
61
+ "typedoc": "^0.28.0",
62
+ "typescript": "^5.6.3",
63
+ "vitest": "^2.1.2"
64
+ }
65
+ }