@zkproofport-app/sdk 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +5 -0
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +5 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/constants.ts","../src/circuits.ts","../src/typedAction.ts","../src/deeplink.ts","../src/qrcode.ts","../src/verifier.ts","../src/offChainVerifier.ts","../src/ProofportSDK.ts"],"sourcesContent":["/**\n * ZKProofport SDK Constants\n */\n\nimport type { CircuitType, SDKEnvironment } from './types';\n\n/**\n * Pre-configured relay server URLs for each environment.\n * Used by `ProofportSDK.create('production')` for zero-config initialization.\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * // Uses RELAY_URLS.production = 'https://relay.zkproofport.app'\n * ```\n */\nexport const RELAY_URLS: Record<SDKEnvironment, string> = {\n production: 'https://relay.zkproofport.app',\n staging: 'https://stg-relay.zkproofport.app',\n local: 'http://localhost:4001',\n};\n\n/**\n * Default deep link URL scheme for ZKProofport mobile app.\n * Used to construct deep link URLs that open the mobile app.\n *\n * @example\n * ```typescript\n * const deepLink = `${DEFAULT_SCHEME}://proof-request?...`;\n * // Results in: zkproofport://proof-request?...\n * ```\n */\nexport const DEFAULT_SCHEME = 'zkproofport';\n\n/**\n * Deep link URL hosts for different proof request flows.\n * Used as the host component in deep link URLs.\n *\n * @example\n * ```typescript\n * const requestUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_REQUEST}`;\n * const responseUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_RESPONSE}`;\n * ```\n */\nexport const DEEP_LINK_HOSTS = {\n /** Host for proof requests sent to mobile app */\n PROOF_REQUEST: 'proof-request',\n /** Host for proof responses returned from mobile app */\n PROOF_RESPONSE: 'proof-response',\n} as const;\n\n/**\n * Circuit metadata containing display names, descriptions, and public input specifications.\n * Each circuit has a defined number and layout of public inputs that must match\n * the Noir circuit definition.\n *\n * @example\n * ```typescript\n * const metadata = CIRCUIT_METADATA['coinbase_attestation'];\n * console.log(metadata.name); // \"Coinbase KYC\"\n * console.log(metadata.publicInputsCount); // 128\n * ```\n */\nexport const CIRCUIT_METADATA: Record<CircuitType, {\n name: string;\n description: string;\n publicInputsCount: number;\n publicInputNames: string[];\n}> = {\n coinbase_attestation: {\n name: 'Coinbase KYC',\n description: 'Prove Coinbase identity verification',\n // 4 x `pub [u8; 32]` in coinbase-attestation/src/main.nr, flattened to\n // bytes: signal_hash, signer_list_merkle_root, scope, nullifier.\n // Read 2 here until 2026-09-04, which was wrong under any reading —\n // the circuit has never had two public inputs, logical or flattened.\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root'],\n },\n coinbase_country_attestation: {\n name: 'Coinbase Country',\n description: 'Prove Coinbase country verification',\n // 32 + 32 + (10 x 2) + 1 + 1 + 32 + 32 = 150, counted off\n // coinbase-country-attestation/src/main.nr. Read 14 until 2026-09-04.\n publicInputsCount: 150,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'country_list', 'country_list_length', 'is_included'],\n },\n oidc_domain_attestation: {\n name: 'OIDC Domain',\n description: 'Prove email domain affiliation via OIDC JWT',\n publicInputsCount: 148,\n publicInputNames: ['pubkey_modulus_limbs', 'domain', 'scope', 'nullifier', 'provider'],\n },\n arc_eligibility: {\n name: 'Arc Eligibility',\n description: 'Prove eligibility and authorize one EIP-712 action, for an Arc gate',\n // 6 x `pub [u8; 32]` in arc-eligibility/src/main.nr, flattened to bytes.\n // Read off the compiled ABI rather than counted: signal_hash 0-31,\n // domain_separator 32-63, action_hash 64-95, signer_list_merkle_root\n // 96-127, scope 128-159, nullifier 160-191.\n publicInputsCount: 192,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'signer_list_merkle_root'],\n },\n // Planned circuit — the identifier is reserved and the circuit exists, but it\n // is not officially supported yet. See CIRCUIT_SUPPORT_STATUS in ./circuits.\n // Forked from coinbase_attestation and shares its four public inputs, so the\n // count is the byte-flattened total (4 x [u8; 32] = 128), matching the\n // COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT indices below. The\n // coinbase_attestation entry above reports a legacy logical count of 2 and is\n // left as-is for backwards compatibility.\n giwa_attestation: {\n name: 'GIWA Attestation',\n description: 'Prove GIWA identity verification (planned — not officially supported yet)',\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'scope', 'nullifier'],\n },\n // Korea Mobile ID (mDL) circuits. Planned — not officially supported yet.\n // Counts are byte-flattened field totals from the compiled circuit ABIs:\n // [u8; 32] arrays contribute 32 inputs each.\n mdl_kr_ownership: {\n name: 'Korea Mobile ID — Ownership',\n description: \"Prove valid Korean mobile driver's license ownership with selective disclosure\",\n publicInputsCount: 97,\n publicInputNames: ['scope', 'nullifier_value', 'disclose_flags', 'owner_commit'],\n },\n mdl_kr_age: {\n name: 'Korea Mobile ID — Age',\n description: \"Prove minimum age from Korean mobile driver's license without revealing birth date\",\n publicInputsCount: 66,\n publicInputNames: ['scope', 'nullifier_value', 'age_threshold', 'current_year'],\n },\n mdl_kr_region: {\n name: 'Korea Mobile ID — Region',\n description: \"Prove si/do residency from Korean mobile driver's license without revealing address\",\n publicInputsCount: 96,\n publicInputNames: ['scope', 'nullifier_value', 'region_code'],\n },\n};\n\n/**\n * Standard verifier contract ABI shared across all Barretenberg-generated verifiers.\n * This ABI defines the interface for calling the verify function on deployed verifier contracts.\n *\n * Uses ethers v6 human-readable ABI format.\n *\n * @example\n * ```typescript\n * import { Contract } from 'ethers';\n *\n * const verifier = new Contract(verifierAddress, VERIFIER_ABI, provider);\n * const isValid = await verifier.verify(proofBytes, publicInputs);\n * ```\n */\nexport const VERIFIER_ABI = [\n 'function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool)',\n];\n\n/**\n * Public RPC endpoint URLs for supported blockchain networks.\n * Used as fallback when no custom provider is supplied.\n *\n * Supported networks:\n * - 84532: Base Sepolia (testnet)\n * - 8453: Base Mainnet (production)\n * - 91342: GIWA Sepolia (testnet) — where the GIWA account circuit verifies\n *\n * A chain missing from this map is not a quiet degradation: `getDefaultProvider`\n * throws \"No RPC endpoint configured for chain N\". That is what a caller saw\n * when verifying a GIWA proof on chain 91342 — the verifier contract had been\n * deployed and the proof was valid, but the SDK had no way to reach the chain\n * to ask. Deploying a verifier to a new network means adding it here too.\n *\n * @example\n * ```typescript\n * import { JsonRpcProvider } from 'ethers';\n *\n * const provider = new JsonRpcProvider(RPC_ENDPOINTS[84532]);\n * ```\n */\nexport const RPC_ENDPOINTS: Record<number, string> = {\n 84532: 'https://sepolia.base.org', // Base Sepolia\n 8453: 'https://mainnet.base.org', // Base Mainnet\n 91342: 'https://sepolia-rpc.giwa.io', // GIWA Sepolia\n};\n\n/**\n * Default proof request expiration time in milliseconds.\n * Requests older than this are considered expired and should not be processed.\n *\n * Default: 10 minutes (600,000 ms)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * // ...\n * createdAt: Date.now(),\n * expiresAt: Date.now() + DEFAULT_REQUEST_EXPIRY_MS\n * };\n * ```\n */\nexport const DEFAULT_REQUEST_EXPIRY_MS = 10 * 60 * 1000;\n\n/**\n * Maximum data size (in bytes) that can be encoded in a QR code.\n * Based on QR Code Version 40 with L (Low) error correction level.\n *\n * Requests exceeding this size should use alternative methods (HTTP, WebSocket).\n *\n * @example\n * ```typescript\n * const deepLinkUrl = generateDeepLink(request);\n * if (deepLinkUrl.length > MAX_QR_DATA_SIZE) {\n * console.warn('Request too large for QR code');\n * }\n * ```\n */\nexport const MAX_QR_DATA_SIZE = 2953; // Version 40 with L error correction\n\n/**\n * Coinbase Attestation circuit public input layout (byte offsets).\n * Defines the byte positions of each field in the flattened public inputs array.\n *\n * Public inputs are packed as bytes32 values:\n * - signal_hash: bytes 0-31\n * - merkle_root: bytes 32-63\n * - scope: bytes 64-95\n *\n * @example\n * ```typescript\n * const publicInputs = response.publicInputs;\n * const signalHash = publicInputs.slice(\n * COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT.SIGNAL_HASH_START,\n * COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT.SIGNAL_HASH_END + 1\n * );\n * ```\n */\nexport const COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT = {\n SIGNAL_HASH_START: 0,\n SIGNAL_HASH_END: 31,\n MERKLE_ROOT_START: 32,\n MERKLE_ROOT_END: 63,\n SCOPE_START: 64,\n SCOPE_END: 95,\n NULLIFIER_START: 96,\n NULLIFIER_END: 127,\n} as const;\n\n/**\n * Coinbase Country Attestation circuit public input layout (byte offsets).\n * Defines the byte positions of each field in the flattened public inputs array.\n *\n * Public inputs are packed as bytes32 values:\n * - signal_hash: bytes 0-31\n * - merkle_root: bytes 32-63\n * - country_list: bytes 64-83 (20 bytes for 10 countries)\n * - country_list_length: byte 84\n * - is_included: byte 85\n * - scope: bytes 86-117\n *\n * @example\n * ```typescript\n * const publicInputs = response.publicInputs;\n * const countryList = publicInputs.slice(\n * COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT.COUNTRY_LIST_START,\n * COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT.COUNTRY_LIST_END + 1\n * );\n * ```\n */\nexport const COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT = {\n SIGNAL_HASH_START: 0,\n SIGNAL_HASH_END: 31,\n MERKLE_ROOT_START: 32,\n MERKLE_ROOT_END: 63,\n COUNTRY_LIST_START: 64,\n COUNTRY_LIST_END: 83,\n COUNTRY_LIST_LENGTH: 84,\n IS_INCLUDED: 85,\n SCOPE_START: 86,\n SCOPE_END: 117,\n NULLIFIER_START: 118,\n NULLIFIER_END: 149,\n} as const;\n\n/**\n * Korea Mobile ID (mDL) circuit public input layout (field offsets).\n * All three mDL circuits share the same prefix: scope [0..31] and\n * nullifier_value [32..63], each stored one byte per field element.\n * The suffix differs per predicate circuit:\n * - mdl_kr_ownership (97 inputs): disclose_flags [64], owner_commit [65..96]\n * - mdl_kr_age (66 inputs): age_threshold [64], current_year [65]\n * - mdl_kr_region (96 inputs): region_code [64..95]\n *\n * @example\n * ```typescript\n * const nullifier = publicInputs.slice(\n * MDL_KR_PUBLIC_INPUT_LAYOUT.NULLIFIER_START,\n * MDL_KR_PUBLIC_INPUT_LAYOUT.NULLIFIER_END + 1\n * );\n * ```\n */\nexport const MDL_KR_PUBLIC_INPUT_LAYOUT = {\n SCOPE_START: 0,\n SCOPE_END: 31,\n NULLIFIER_START: 32,\n NULLIFIER_END: 63,\n OWNERSHIP_DISCLOSE_FLAGS: 64,\n OWNERSHIP_OWNER_COMMIT_START: 65,\n OWNERSHIP_OWNER_COMMIT_END: 96,\n AGE_THRESHOLD: 64,\n AGE_CURRENT_YEAR: 65,\n REGION_CODE_START: 64,\n REGION_CODE_END: 95,\n} as const;\n\n/**\n * OIDC Domain Attestation circuit public input layout (field offsets).\n * Defines the field positions in the flattened public inputs array (148 fields total).\n *\n * Circuit public inputs (from main.nr):\n * - pubkey_modulus_limbs: pub [u128; 18] → 18 fields (0–17)\n * - domain: pub BoundedVec<u8, 64> → 1 len + 64 storage = 65 fields (18–82)\n * - scope: pub [u8; 32] → 32 fields (83–114)\n * - nullifier: pub [u8; 32] → 32 fields (115–146)\n * - provider: pub u8 → 1 field (147)\n *\n * @example\n * ```typescript\n * const scope = publicInputs.slice(\n * OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT.SCOPE_START,\n * OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT.SCOPE_END + 1\n * );\n * ```\n */\nexport const OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT = {\n PUBKEY_MODULUS_START: 0,\n PUBKEY_MODULUS_END: 17,\n DOMAIN_STORAGE_START: 18,\n DOMAIN_STORAGE_END: 81,\n DOMAIN_LEN: 82,\n SCOPE_START: 83,\n SCOPE_END: 114,\n NULLIFIER_START: 115,\n NULLIFIER_END: 146,\n PROVIDER: 147,\n /** @deprecated Use DOMAIN_STORAGE_START */\n DOMAIN_START: 18,\n /** @deprecated Use DOMAIN_LEN */\n DOMAIN_END: 82,\n} as const;\n","/**\n * Canonical ZKProofport circuit identifiers.\n *\n * This module is the single source of truth for circuit IDs. Every other layer\n * — the mobile app, the demo, the relay, server-side provers — reads its list\n * from here instead of keeping a private copy that silently drifts.\n *\n * It has **no imports and no dependencies**, so it can be pulled in on its own:\n *\n * ```typescript\n * import { CIRCUIT_IDS, isCircuitId } from '@zkproofport-app/sdk/circuits';\n * ```\n *\n * The same names are also re-exported from the package root\n * (`@zkproofport-app/sdk`) for callers that already import the SDK.\n *\n * ## Identifiers are canonical and case-sensitive\n *\n * Each ID is the circuit's `name` in its `Nargo.toml`, verbatim. The format is\n * lowercase with underscores. Hyphenated spellings (`coinbase-kyc`,\n * `mdl-kr-age`) are directory or UI route names in other repositories — they\n * are **not** circuit IDs, and passing one produces a nullifier mismatch or a\n * failed on-chain lookup rather than a clear error.\n */\n\n/**\n * Whether a circuit is officially supported today or still on the roadmap.\n *\n * - `supported` — generally available. Safe to build a product on.\n * - `planned` — the identifier is reserved and the circuit exists, but it is\n * not officially supported yet. Availability, inputs and public-input layout\n * may change without a major version bump.\n */\nexport type CircuitSupportStatus = 'supported' | 'experimental' | 'planned';\n\n/**\n * Canonical circuit identifiers, keyed by a stable constant name.\n *\n * Prefer these constants over string literals so a rename is a compile error\n * rather than a runtime surprise.\n *\n * @example\n * ```typescript\n * import { CIRCUIT_IDS } from '@zkproofport-app/sdk/circuits';\n *\n * const relay = await sdk.createRelayRequest(CIRCUIT_IDS.COINBASE_ATTESTATION, {\n * scope: 'myapp.com',\n * });\n * ```\n */\nexport const CIRCUIT_IDS = Object.freeze({\n /** Coinbase KYC attestation. Officially supported. */\n COINBASE_ATTESTATION: 'coinbase_attestation',\n /** Coinbase country attestation (inclusion / exclusion). Officially supported. */\n COINBASE_COUNTRY_ATTESTATION: 'coinbase_country_attestation',\n /** OIDC email-domain attestation. Officially supported. */\n OIDC_DOMAIN_ATTESTATION: 'oidc_domain_attestation',\n /** Arc eligibility: one EIP-712 action, authorized. Officially supported. */\n ARC_ELIGIBILITY: 'arc_eligibility',\n /** GIWA attestation. Planned — not officially supported yet. */\n GIWA_ATTESTATION: 'giwa_attestation',\n /** Korea Mobile ID ownership. Planned — not officially supported yet. */\n MDL_KR_OWNERSHIP: 'mdl_kr_ownership',\n /** Korea Mobile ID age threshold. Planned — not officially supported yet. */\n MDL_KR_AGE: 'mdl_kr_age',\n /** Korea Mobile ID si/do region. Planned — not officially supported yet. */\n MDL_KR_REGION: 'mdl_kr_region',\n} as const);\n\n/**\n * Union of every canonical circuit identifier.\n *\n * `CircuitType` (exported from the package root) is an alias of this type — the\n * two names refer to the same union, and this module is where it is defined.\n */\nexport type CircuitId = (typeof CIRCUIT_IDS)[keyof typeof CIRCUIT_IDS];\n\n/**\n * Support status for every circuit.\n *\n * The record is exhaustive over {@link CircuitId}: adding an identifier without\n * giving it a status is a compile error, so this list cannot drift from\n * {@link CIRCUIT_IDS}.\n *\n * @example\n * ```typescript\n * import { CIRCUIT_SUPPORT_STATUS } from '@zkproofport-app/sdk/circuits';\n *\n * CIRCUIT_SUPPORT_STATUS.coinbase_attestation; // 'supported'\n * CIRCUIT_SUPPORT_STATUS.mdl_kr_age; // 'planned'\n * ```\n */\nexport const CIRCUIT_SUPPORT_STATUS: Readonly<Record<CircuitId, CircuitSupportStatus>> =\n Object.freeze({\n coinbase_attestation: 'supported',\n coinbase_country_attestation: 'supported',\n oidc_domain_attestation: 'supported',\n arc_eligibility: 'experimental',\n giwa_attestation: 'planned',\n mdl_kr_ownership: 'planned',\n mdl_kr_age: 'planned',\n mdl_kr_region: 'planned',\n } as const);\n\n/**\n * Where each circuit's verification key FILE lives inside the\n * `zkproofport/circuits` repository, relative to its root.\n *\n * Off-chain verification needs the verification key and nothing else — no\n * circuit bytecode, no witness. The key is public by nature: it is what anyone\n * checking a proof must already have, and the Solidity verifiers deployed\n * on-chain embed the same key.\n *\n * NOTE THE TRAILING `/vk` TWICE. In that repository `target/vk` is a DIRECTORY\n * holding `vk`, `vk_hash` and `SHA256SUMS`; the key itself is `target/vk/vk`.\n * These paths were first copied here from the mobile app, which keeps the\n * directory and the filename as two fields and joins them — so taking only the\n * directory produced a URL that answers 404, and the first browser to try\n * off-chain verification said \"Could not fetch the verification key (HTTP 404)\".\n *\n * Exhaustive over {@link CircuitId} on purpose. A new circuit whose key path is\n * not listed here fails to compile rather than failing at verification time,\n * where the only symptom would be a proof that cannot be checked.\n */\nexport const CIRCUIT_VK_PATHS: Readonly<Record<CircuitId, string>> = Object.freeze({\n coinbase_attestation: 'coinbase-attestation/target/vk/vk',\n coinbase_country_attestation: 'coinbase-country-attestation/target/vk/vk',\n oidc_domain_attestation: 'oidc-domain-attestation/target/vk/vk',\n arc_eligibility: 'arc-eligibility/target/vk/vk',\n giwa_attestation: 'giwa-attestation/target/vk/vk',\n mdl_kr_ownership: 'mdl/kr-ownership/target/vk/vk',\n mdl_kr_age: 'mdl/kr-age/target/vk/vk',\n mdl_kr_region: 'mdl/kr-region/target/vk/vk',\n} as const);\n\n/**\n * Every canonical circuit identifier, in declaration order.\n *\n * Includes circuits that are still `planned`. Use {@link SUPPORTED_CIRCUIT_IDS}\n * when you only want the ones that are officially supported today.\n */\nexport const ALL_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n Object.values(CIRCUIT_IDS) as CircuitId[]\n);\n\n/**\n * Circuits that are officially supported today: the two Coinbase circuits and\n * OIDC domain attestation.\n *\n * Derived from {@link CIRCUIT_SUPPORT_STATUS}, so it cannot fall out of sync.\n */\nexport const SUPPORTED_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter((id) => CIRCUIT_SUPPORT_STATUS[id] === 'supported')\n);\n\n/**\n * Circuits whose identifiers are reserved but which are not officially\n * supported yet: GIWA attestation and the three Korea Mobile ID circuits.\n *\n * Derived from {@link CIRCUIT_SUPPORT_STATUS}, so it cannot fall out of sync.\n */\n/**\n * Circuits you can prove today, on a testnet, with everything subject to change.\n *\n * `arc_eligibility` is the reason this status exists. Calling it `planned`\n * would be wrong — the circuit compiles, the verifier is deployed and a proof\n * verifies against it — and calling it `supported` would be worse, because the\n * only deployment is Arc Testnet, Circle has not published a mainnet chain id,\n * and the public-input layout is still open. Neither existing word was true, so\n * the honest move was a third word rather than picking the closer lie.\n */\nexport const EXPERIMENTAL_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter(id => CIRCUIT_SUPPORT_STATUS[id] === 'experimental'),\n);\n\nexport const PLANNED_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter((id) => CIRCUIT_SUPPORT_STATUS[id] === 'planned')\n);\n\n/**\n * Narrows an unknown value to a canonical circuit identifier.\n *\n * Returns `false` for hyphenated route names such as `'coinbase-kyc'`, which\n * are not circuit IDs.\n *\n * @example\n * ```typescript\n * isCircuitId('coinbase_attestation'); // true\n * isCircuitId('coinbase-kyc'); // false\n * ```\n */\nexport function isCircuitId(value: unknown): value is CircuitId {\n return typeof value === 'string' && (ALL_CIRCUIT_IDS as readonly string[]).includes(value);\n}\n\n/**\n * Narrows an unknown value to a circuit identifier that is officially supported\n * today. Planned circuits return `false`.\n *\n * @example\n * ```typescript\n * isSupportedCircuitId('oidc_domain_attestation'); // true\n * isSupportedCircuitId('mdl_kr_age'); // false — planned\n * ```\n */\nexport function isSupportedCircuitId(value: unknown): value is CircuitId {\n return isCircuitId(value) && CIRCUIT_SUPPORT_STATUS[value] === 'supported';\n}\n\n/**\n * Returns the support status of a circuit.\n *\n * @param circuit - A canonical circuit identifier.\n * @throws Error when the value is not a canonical circuit identifier.\n *\n * @example\n * ```typescript\n * getCircuitSupportStatus('giwa_attestation'); // 'planned'\n * ```\n */\nexport function getCircuitSupportStatus(circuit: CircuitId): CircuitSupportStatus {\n if (!isCircuitId(circuit)) {\n throw new Error(\n `Unknown circuit '${String(circuit)}'. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`\n );\n }\n return CIRCUIT_SUPPORT_STATUS[circuit];\n}\n\n/**\n * Whether a circuit's relay request must carry a wallet signature.\n *\n * The SDK checks this to fail fast — \"Signer not set\" locally beats a 401 from\n * the relay two round trips later, with nothing saying which circuit needed\n * what. The relay declares its OWN copy on purpose and does not import this\n * one: it is a security boundary, and an auth policy that a published package\n * can change is not a policy. A test in the relay asserts the two agree.\n *\n * `satisfies` and not an annotation, so a circuit added above is a compile\n * error here until somebody decides which it is.\n */\nexport const CIRCUIT_NEEDS_WALLET_SIGNATURE = {\n coinbase_attestation: true,\n coinbase_country_attestation: true,\n // Same Coinbase-attested wallet as above; what changes is that it signs an\n // EIP-712 action rather than signal_hash.\n arc_eligibility: true,\n // The signature is inside the OIDC identity token, checked by the prover.\n oidc_domain_attestation: false,\n // Web2 (OmniOne CX) flows with no wallet binding at all.\n mdl_kr_ownership: false,\n mdl_kr_age: false,\n mdl_kr_region: false,\n giwa_attestation: false,\n} satisfies Record<CircuitId, boolean>;\n","/**\n * Checking the EIP-712 action an `arc_eligibility` proof binds to.\n *\n * Three places need this answer and they have to agree: a dapp building the\n * request, this SDK validating a deep link, and the mobile app before it asks\n * a wallet to sign. The check lived in the mobile app's demo screen and\n * nowhere else, so an action arriving from a dapp reached the prover\n * unexamined — and that is the path that ships.\n *\n * The circuit hashes the domain and the struct and proves the wallet signed\n * them. It never learns what the action says, so a malformed one does not\n * fail: it produces a valid proof of the wrong thing.\n */\nimport type { TypedAction } from './types';\n\nexport type { TypedAction };\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The reason the value is not a usable action, or `null` when it is one.\n *\n * A string rather than a boolean because every caller shows it to somebody —\n * a dapp developer reading a validation error, or a person looking at the\n * mobile app's demo screen.\n */\nexport function validateTypedAction(value: unknown): string | null {\n if (value === undefined || value === null) {\n return 'action is required for arc_eligibility. The circuit proves that a wallet authorised ONE EIP-712 action; there is nothing to prove without it.';\n }\n if (typeof value !== 'object' || Array.isArray(value)) {\n return 'action must be an object.';\n }\n const a = value as Partial<TypedAction>;\n\n const d = a.domain;\n if (!d || typeof d !== 'object') {\n return 'action.domain is required.';\n }\n for (const k of ['name', 'version', 'verifyingContract'] as const) {\n if (typeof d[k] !== 'string' || !d[k]) {\n return `action.domain.${k} must be a non-empty string.`;\n }\n }\n if (typeof d.chainId !== 'number' || !Number.isInteger(d.chainId)) {\n return 'action.domain.chainId must be an integer.';\n }\n if (!ADDRESS.test(d.verifyingContract)) {\n return 'action.domain.verifyingContract must be a 20-byte hex address.';\n }\n\n if (!a.types || typeof a.types !== 'object' || Array.isArray(a.types)) {\n return 'action.types is required.';\n }\n if (typeof a.primaryType !== 'string' || !a.primaryType) {\n return 'action.primaryType is required.';\n }\n if (!(a.primaryType in a.types)) {\n return `action.primaryType '${a.primaryType}' is not one of the structs in action.types.`;\n }\n if (!a.message || typeof a.message !== 'object' || Array.isArray(a.message)) {\n return 'action.message is required.';\n }\n\n // Every field the struct declares must be present, or the wallet signs a\n // different message than the one the caller described.\n const fields = a.types[a.primaryType];\n if (!Array.isArray(fields) || fields.length === 0) {\n return `action.types.${a.primaryType} declares no fields.`;\n }\n const missing = fields\n .map(f => f?.name)\n .filter(n => typeof n === 'string' && !(n in (a.message as object)));\n if (missing.length) {\n return `action.message is missing: ${missing.join(', ')}`;\n }\n\n return null;\n}\n\n/** The action, or the reason it is not one. For text a person typed. */\nexport function parseTypedAction(text: string): { action: TypedAction } | { error: string } {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (e) {\n return { error: `Not valid JSON: ${(e as Error).message}` };\n }\n const error = validateTypedAction(raw);\n return error ? { error } : { action: raw as TypedAction };\n}\n","/**\n * Deep Link utilities for ZKProofport SDK\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n OidcDomainInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n DeepLinkComponents,\n CircuitType,\n ArcEligibilityInputs,\n} from './types';\nimport { DEFAULT_SCHEME, DEEP_LINK_HOSTS } from './constants';\nimport { isCircuitId, ALL_CIRCUIT_IDS } from './circuits';\nimport { validateTypedAction } from './typedAction';\n\n/**\n * Generates a unique request ID for proof requests.\n *\n * Creates an ID by combining a base36-encoded timestamp with a random string,\n * prefixed with \"req-\". This ensures uniqueness across concurrent requests.\n *\n * @returns A unique string identifier in the format \"req-{timestamp}-{random}\"\n *\n * @example\n * ```typescript\n * const id = generateRequestId();\n * // \"req-lh8k3f2g-a9b7c4d2\"\n * ```\n */\nexport function generateRequestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 10);\n return `req-${timestamp}-${random}`;\n}\n\n/**\n * Encodes an object into a URL-safe base64url string with UTF-8 support.\n *\n * Converts the input object to JSON, then encodes it using base64url format\n * (RFC 4648 §5) which replaces '+' with '-', '/' with '_', and removes padding.\n * Works in both browser and Node.js environments.\n *\n * @param data - The object to encode (will be JSON stringified)\n * @returns Base64url-encoded string safe for URL parameters\n *\n * @example\n * ```typescript\n * const encoded = encodeData({ circuit: 'coinbase_attestation', requestId: 'req-123' });\n * // \"eyJjaXJjdWl0IjoiY29pbmJhc2VfYXR0ZXN0YXRpb24iLCJyZXF1ZXN0SWQiOiJyZXEtMTIzIn0\"\n * ```\n */\nexport function encodeData(data: object): string {\n const json = JSON.stringify(data);\n // Use base64url encoding (URL-safe) with UTF-8 support\n if (typeof btoa === 'function') {\n // Browser: UTF-8 encode first, then base64\n const utf8Encoded = encodeURIComponent(json).replace(/%([0-9A-F]{2})/g, (_, p1) =>\n String.fromCharCode(parseInt(p1, 16))\n );\n return btoa(utf8Encoded)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n // Node.js environment\n return Buffer.from(json, 'utf-8')\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decodes a base64url-encoded string back into a typed object.\n *\n * Reverses the encoding process by converting base64url to standard base64,\n * decoding it, and parsing the resulting JSON. Handles UTF-8 correctly in\n * both browser and Node.js environments.\n *\n * @typeParam T - The expected type of the decoded object\n * @param encoded - Base64url-encoded string (from encodeData)\n * @returns Decoded and parsed object of type T\n *\n * @throws {SyntaxError} If the decoded string is not valid JSON\n *\n * @example\n * ```typescript\n * const request = decodeData<ProofRequest>(encodedString);\n * console.log(request.circuit); // \"coinbase_attestation\"\n * ```\n */\nexport function decodeData<T>(encoded: string): T {\n // Restore base64 padding\n let base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');\n while (base64.length % 4) {\n base64 += '=';\n }\n\n let json: string;\n if (typeof atob === 'function') {\n // Browser: decode base64, then UTF-8 decode\n const decoded = atob(base64);\n json = decodeURIComponent(\n decoded.split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')\n );\n } else {\n json = Buffer.from(base64, 'base64').toString('utf-8');\n }\n\n return JSON.parse(json) as T;\n}\n\n/**\n * Builds a deep link URL for a proof request.\n *\n * Encodes the proof request and constructs a deep link URL that can be opened\n * by the ZKProofport mobile app. The URL format is:\n * `{scheme}://proof-request?data={encodedRequest}`\n *\n * @param request - The proof request to encode in the deep link\n * @param scheme - Custom URL scheme (defaults to \"zkproofport\")\n * @returns Complete deep link URL ready to be opened or embedded in a QR code\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n * const url = buildProofRequestUrl(request);\n * // \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\"\n * ```\n */\nexport function buildProofRequestUrl(\n request: ProofRequest,\n scheme: string = DEFAULT_SCHEME\n): string {\n const encodedRequest = encodeData(request);\n return `${scheme}://${DEEP_LINK_HOSTS.PROOF_REQUEST}?data=${encodedRequest}`;\n}\n\n/**\n * Builds a callback URL with proof response data as query parameters.\n *\n * Appends proof response fields to the provided callback URL. For completed proofs,\n * includes proof data, public inputs, and nullifier. For errors, includes error message.\n *\n * @internal Used by the mobile app to construct callback URLs — not intended for SDK consumers.\n *\n * @param callbackUrl - Base callback URL (from the original proof request)\n * @param response - Proof response containing status and optional proof data\n * @returns Complete callback URL with proof response as query parameters\n */\nexport function buildCallbackUrl(\n callbackUrl: string,\n response: ProofResponse\n): string {\n const url = new URL(callbackUrl);\n url.searchParams.set('requestId', response.requestId);\n url.searchParams.set('status', response.status);\n\n if (response.status === 'completed' && response.proof) {\n url.searchParams.set('proof', response.proof);\n if (response.publicInputs) {\n url.searchParams.set('publicInputs', response.publicInputs.join(','));\n }\n if (response.numPublicInputs !== undefined) {\n url.searchParams.set('numPublicInputs', response.numPublicInputs.toString());\n }\n if (response.timestamp) {\n url.searchParams.set('timestamp', response.timestamp.toString());\n }\n } else if (response.status === 'error' && response.error) {\n url.searchParams.set('error', response.error);\n }\n\n return url.toString();\n}\n\n/**\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a ZKProofport deep link URL.\n * Returns null if the URL is invalid or missing required parameters.\n *\n * @param url - Deep link URL (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Decoded ProofRequest object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\";\n * const request = parseProofRequestUrl(url);\n * if (request) {\n * console.log(request.circuit); // \"coinbase_attestation\"\n * }\n * ```\n */\nexport function parseProofRequestUrl(url: string): ProofRequest | null {\n try {\n const urlObj = new URL(url);\n const data = urlObj.searchParams.get('data');\n\n if (!data) {\n return null;\n }\n\n return decodeData<ProofRequest>(data);\n } catch (error) {\n console.error('Failed to parse proof request URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a proof response from a callback URL.\n *\n * Extracts proof response data from query parameters in a callback URL.\n * Handles both successful proof completions and error responses.\n * Returns null if required parameters (requestId, status) are missing.\n *\n * @param url - Callback URL with proof response query parameters\n * @returns Decoded ProofResponse object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const callbackUrl = \"https://example.com/callback?requestId=req-123&status=completed&proof=0x...\";\n * const response = parseProofResponseUrl(callbackUrl);\n * if (response && response.status === 'completed') {\n * console.log(response.proof); // \"0x...\"\n * }\n * ```\n */\nexport function parseProofResponseUrl(url: string): ProofResponse | null {\n try {\n const urlObj = new URL(url);\n const requestId = urlObj.searchParams.get('requestId');\n const status = urlObj.searchParams.get('status') as ProofResponse['status'];\n\n if (!requestId || !status) {\n return null;\n }\n\n // A missing or unrecognised circuit is a REJECTION, not a default.\n //\n // This used to fall back to `coinbase_attestation`. A callback carrying a\n // country or OIDC proof, or a circuit this build has never heard of, was\n // then handed to the caller labelled Coinbase KYC -- the parse succeeded,\n // the label was wrong, and nothing downstream could tell. Whoever reads\n // `response.circuit` decides which verifier and which public-input layout\n // to use, so the wrong label is a proof checked against another circuit's\n // bytes.\n const circuit = urlObj.searchParams.get('circuit');\n if (!circuit || !isCircuitId(circuit)) {\n return null;\n }\n\n const response: ProofResponse = {\n requestId,\n circuit,\n status,\n };\n\n if (status === 'completed') {\n response.proof = urlObj.searchParams.get('proof') || undefined;\n const publicInputsStr = urlObj.searchParams.get('publicInputs');\n if (publicInputsStr) {\n response.publicInputs = publicInputsStr.split(',');\n }\n const numPublicInputs = urlObj.searchParams.get('numPublicInputs');\n if (numPublicInputs) {\n response.numPublicInputs = parseInt(numPublicInputs, 10);\n }\n const timestamp = urlObj.searchParams.get('timestamp');\n if (timestamp) {\n response.timestamp = parseInt(timestamp, 10);\n }\n } else if (status === 'error') {\n response.error = urlObj.searchParams.get('error') || undefined;\n }\n\n return response;\n } catch (error) {\n console.error('Failed to parse proof response URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a deep link URL into its component parts.\n *\n * Breaks down a custom scheme URL into scheme, host, path, and query parameters.\n * Useful for routing and handling different types of deep links.\n *\n * @param url - Custom scheme URL to parse (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Object containing scheme, host, path, and params, or null if invalid\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request/verify?data=abc123\";\n * const components = parseDeepLink(url);\n * // {\n * // scheme: \"zkproofport\",\n * // host: \"proof-request\",\n * // path: \"/verify\",\n * // params: { data: \"abc123\" }\n * // }\n * ```\n */\nexport function parseDeepLink(url: string): DeepLinkComponents | null {\n try {\n // Handle custom scheme URLs\n const schemeMatch = url.match(/^([a-z][a-z0-9+.-]*):\\/\\/(.+)$/i);\n if (!schemeMatch) {\n return null;\n }\n\n const scheme = schemeMatch[1];\n const rest = schemeMatch[2];\n\n // Parse host and path\n const [hostPath, queryString] = rest.split('?');\n const [host, ...pathParts] = hostPath.split('/');\n const path = '/' + pathParts.join('/');\n\n // Parse query parameters\n const params: Record<string, string> = {};\n if (queryString) {\n const searchParams = new URLSearchParams(queryString);\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n }\n\n return { scheme, host, path, params };\n } catch (error) {\n console.error('Failed to parse deep link:', error);\n return null;\n }\n}\n\n/**\n * Checks if a URL is a valid ZKProofport deep link.\n *\n * Performs a case-insensitive check to see if the URL starts with the\n * ZKProofport scheme. Does not validate the URL structure beyond the scheme.\n *\n * @param url - URL to check\n * @param scheme - Expected URL scheme (defaults to \"zkproofport\")\n * @returns True if the URL starts with the specified scheme\n *\n * @example\n * ```typescript\n * isProofportDeepLink(\"zkproofport://proof-request?data=...\"); // true\n * isProofportDeepLink(\"https://example.com\"); // false\n * isProofportDeepLink(\"ZKPROOFPORT://proof-request\"); // true (case-insensitive)\n * ```\n */\nexport function isProofportDeepLink(\n url: string,\n scheme: string = DEFAULT_SCHEME\n): boolean {\n return url.toLowerCase().startsWith(`${scheme.toLowerCase()}://`);\n}\n\n/**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Performs comprehensive validation including:\n * - Required fields (requestId, circuit, callbackUrl)\n * - Circuit type validity (must be a supported circuit)\n * - Circuit-specific input validation (e.g., userAddress format, countryList structure)\n * - Expiration check (if expiresAt is provided)\n *\n * Note: userAddress is optional for both circuits - the mobile app will prompt\n * for wallet connection if not provided.\n *\n * @param request - Proof request to validate\n * @returns Validation result with `valid` flag and optional `error` message\n */\n/**\n * Validates a free-text mDL input (scope / targetRegion).\n * Rejects empty or whitespace-only values, control characters (which break\n * deep-link query encoding and downstream logging), and values over 256 chars\n * (server-side length cap mirror). UTF-8 text such as Korean region names is\n * allowed.\n *\n * @returns Error message string, or null when valid.\n */\nfunction validateMdlTextInput(value: unknown, fieldName: string): string | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return `${fieldName} is required and must be a non-empty string`;\n }\n if (value.length > 256) {\n return `${fieldName} must be 256 characters or fewer`;\n }\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001F\\u007F]/.test(value)) {\n return `${fieldName} must not contain control characters`;\n }\n return null;\n}\n\n/**\n * Validates dapp-supplied inputs for the Korea Mobile ID (mDL) circuits.\n * Shared by deep-link request validation and relay request creation so the\n * same guards apply on every request path.\n *\n * Rules:\n * - `scope` — required non-empty string, ≤256 chars, no control characters\n * - `mdl_kr_ownership.discloseFlags` — optional integer 0–15 (0x0F bitmask)\n * - `mdl_kr_age.ageThreshold` — required integer 1–150\n * - `mdl_kr_region.targetRegion` — required non-empty string (Korean si/do),\n * ≤256 chars, no control characters\n *\n * @param circuit - One of the three mDL circuit identifiers\n * @param inputs - Dapp-supplied circuit inputs\n * @returns Error message string, or null when the inputs are valid\n */\nexport function validateMdlInputs(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs\n): string | null {\n const scopeError = validateMdlTextInput((inputs as MdlKrOwnershipInputs).scope, 'scope');\n if (scopeError) {\n return scopeError;\n }\n\n if (circuit === 'mdl_kr_ownership') {\n const { discloseFlags } = inputs as MdlKrOwnershipInputs;\n if (discloseFlags !== undefined) {\n if (\n typeof discloseFlags !== 'number' ||\n !Number.isInteger(discloseFlags) ||\n discloseFlags < 0 ||\n discloseFlags > 0x0f\n ) {\n return 'discloseFlags must be an integer between 0 and 15';\n }\n }\n } else if (circuit === 'mdl_kr_age') {\n const { ageThreshold } = inputs as MdlKrAgeInputs;\n if (\n typeof ageThreshold !== 'number' ||\n !Number.isInteger(ageThreshold) ||\n ageThreshold < 1 ||\n ageThreshold > 150\n ) {\n return 'ageThreshold is required and must be an integer between 1 and 150';\n }\n } else {\n const { targetRegion } = inputs as MdlKrRegionInputs;\n const regionError = validateMdlTextInput(targetRegion, 'targetRegion');\n if (regionError) {\n return regionError;\n }\n }\n\n return null;\n}\n\n/**\n * Longest accepted `returnScheme` value.\n * Kept in sync with proofport-relay `src/returnScheme.ts`.\n */\nexport const MAX_RETURN_SCHEME_LENGTH = 128;\n\n/** RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`) followed by exactly `://`. */\nconst BARE_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\/$/;\n\n/**\n * Schemes we refuse even in the bare `scheme://` shape.\n *\n * `http` and `https` are the back door the shape rule alone leaves open: with\n * no host, `https://` is shaped exactly like a bare custom scheme and would\n * otherwise pass. A browser pointed at nowhere is not a return target, and\n * accepting it would re-open the URL-shaped door this field just closed.\n * `googlechrome://` and `firefox://` are deliberately NOT denied — bare, they\n * foreground that browser without navigating, which is the whole point.\n */\nconst DENIED_RETURN_SCHEMES = new Set([\n 'about',\n 'blob',\n 'content',\n 'data',\n 'facetime',\n 'facetime-audio',\n 'file',\n 'ftp',\n 'http',\n 'https',\n 'intent',\n 'javascript',\n 'jar',\n 'mailto',\n 'sms',\n 'tel',\n 'vbscript',\n]);\n\n/**\n * Validates a `returnScheme` before it is sent to the relay, so a malformed\n * value fails fast in the integrator's own code instead of coming back as a\n * relay 400. The relay re-validates and is the authority.\n *\n * One shape is accepted: a bare custom scheme such as `mydapp://`. It names an\n * app to switch back to, never a page to visit — so hosts, paths and query\n * strings are rejected, and an https URL is not a valid value. A web page has\n * no app to return to and simply omits the field.\n *\n * @param value - Candidate return target\n * @returns `null` when acceptable, otherwise a human-readable error message\n *\n * @internal\n */\nexport function validateReturnScheme(value: unknown): string | null {\n if (typeof value !== 'string') {\n return 'returnScheme must be a string';\n }\n if (value.length === 0) {\n return 'returnScheme must not be empty';\n }\n // Length is checked before any regex so a huge string never reaches the matcher.\n if (value.length > MAX_RETURN_SCHEME_LENGTH) {\n return `returnScheme must be at most ${MAX_RETURN_SCHEME_LENGTH} characters`;\n }\n if (/\\s/.test(value)) {\n return 'returnScheme must not contain whitespace';\n }\n\n const normalized = value.toLowerCase();\n\n if (!BARE_SCHEME_RE.test(normalized)) {\n return 'returnScheme must be a bare custom scheme such as \"mydapp://\" — hosts, paths, query strings and fragments are not accepted, and an https URL is not a return target';\n }\n\n const schemeName = normalized.slice(0, normalized.indexOf(':'));\n if (DENIED_RETURN_SCHEMES.has(schemeName)) {\n return `returnScheme \"${schemeName}\" is not allowed`;\n }\n\n return null;\n}\n\n/**\n * The return target to use when the integrator named none.\n *\n * Only the requesting PAGE can answer \"which browser is this?\" — iOS gives the\n * ZKProofport app nothing to work with (`sourceApplication` is nil across team\n * identifiers, and there is no public API to foreground an app by bundle id).\n * So the detection has to happen here, in the SDK, and travel with the request.\n *\n * Two cases are detected, each from a POSITIVE token, and each verified in the\n * browser's own source to foreground WITHOUT navigating anywhere:\n *\n * Chrome for iOS (`CriOS/`) -> `googlechrome://`\n * Firefox for iOS (`FxiOS/`) -> `firefox://`\n *\n * The BARE scheme is the point in both cases: it carries no URL, so the browser\n * comes forward with nothing to open and the user lands on the tab they were\n * already reading — no new tab, no navigation, no reload, JS state intact.\n *\n * Chrome: `ios/chrome/app/startup/chrome_app_startup_parameters.mm` replaces\n * the scheme with `http`, producing `http://`, which fails GURL validation\n * (`if (!externalURL.is_valid()) return nil;`), so the startup parameters are\n * nil and there is nothing to open.\n *\n * Firefox: `firefox://` has an empty host, and\n * `Coordinators/Router/RouteBuilder.swift` resolves the host through\n * `DeeplinkInput.Host(rawValue: \"\")`, which is nil because no case has an empty\n * raw value (`Coordinators/Router/DeeplinkInput.swift`). The scheme is not http\n * either, so `makeRoute(url:)` falls to its final `else { return nil }`, and\n * `SceneDelegate.handleOpenURL` then hits `guard let route = ... else\n * { return }` and does nothing at all. Verified on the warm path — the browser\n * is already running, which is always true here, because the user came from a\n * page in it.\n *\n * Everything else deliberately returns undefined, and that is not a gap:\n *\n * - Safari has no equivalent. No scheme means \"just come forward\";\n * `https://<url>` navigates and opens a new tab, `x-web-search://` opens a\n * search page. Both lose the user's page.\n * - Brave and Arc for iOS are UNDETECTABLE. Brave ships no UA token and\n * identifies itself only via Client Hints, which WebKit does not implement,\n * so it looks exactly like Safari. Inferring \"Safari\" by elimination and\n * firing a Safari-ish scheme would throw Brave and Arc users into a browser\n * they were not using — strictly worse than doing nothing.\n * - In-app webviews (KakaoTalk, Naver, Line, Instagram) are not tabs at all.\n * Any scheme destroys the page; the system \"< Back to X\" breadcrumb is the\n * only thing that preserves it.\n * - Edge (`EdgiOS`) and Opera (`OPiOS` / `OPT`) for iOS are NOT included.\n * Both are closed source, so `microsoft-edge://` and `opera-http://` cannot\n * be checked the way Chrome's and Firefox's were. Their bare schemes are\n * plausible analogues, and that is exactly why they stay out: an unverified\n * guess that opens a new tab is the bug this field exists to avoid. Add one\n * only with evidence that it foregrounds WITHOUT navigating.\n * - Android needs nothing: the ZKProofport app brings itself to the back\n * (`moveTaskToBack`), which resumes the browser exactly as it was.\n *\n * When this returns undefined the field is omitted and the ZKProofport app\n * tells the user the proof was delivered and to switch back themselves.\n *\n * @param userAgent - override, for tests. Defaults to `navigator.userAgent`.\n * Returns undefined when there is no navigator at all (Node, SSR).\n * @returns a scheme that is safe to open, or undefined to send nothing\n *\n * @internal\n */\nexport function detectReturnScheme(userAgent?: string): string | undefined {\n const ua =\n userAgent ?? (typeof navigator === 'undefined' ? undefined : navigator.userAgent);\n if (typeof ua !== 'string' || ua.length === 0) {\n return undefined;\n }\n // A device token is required alongside the browser token. `CriOS` and `FxiOS`\n // are already iOS-only and unambiguous on their own, but pairing them with the\n // device token costs nothing and stops a synthetic or spoofed desktop user\n // agent from producing a mobile-only scheme.\n if (!/(iPhone|iPad|iPod)/.test(ua)) {\n return undefined;\n }\n if (/CriOS\\//.test(ua)) {\n return 'googlechrome://';\n }\n if (/FxiOS\\//.test(ua)) {\n return 'firefox://';\n }\n return undefined;\n}\n\nexport function validateProofRequest(request: ProofRequest): { valid: boolean; error?: string } {\n if (!request.requestId) {\n return { valid: false, error: 'Missing requestId' };\n }\n\n if (!request.circuit) {\n return { valid: false, error: 'Missing circuit type' };\n }\n\n // The list is the SDK's own, not a copy. The copy that used to sit here\n // named six circuits and had missed two — `giwa_attestation` and\n // `arc_eligibility` — so a link for either was refused as an invalid type\n // while every other layer accepted it.\n if (!isCircuitId(request.circuit)) {\n return {\n valid: false,\n error: `Invalid circuit type: ${request.circuit}. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n };\n }\n\n if (!request.callbackUrl) {\n return { valid: false, error: 'Missing callbackUrl' };\n }\n\n // Validate circuit-specific inputs\n if (request.circuit === 'coinbase_attestation') {\n // Coinbase KYC: userAddress is optional - app will connect wallet if not provided\n const inputs = request.inputs as CoinbaseKycInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n // If userAddress is not provided, app will prompt wallet connection - this is valid\n } else if (request.circuit === 'coinbase_country_attestation') {\n const inputs = request.inputs as CoinbaseCountryInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n return { valid: false, error: 'countryList is required and must be a non-empty array' };\n }\n if (!inputs.countryList.every(c => typeof c === 'string')) {\n return { valid: false, error: 'countryList must contain only strings' };\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n return { valid: false, error: 'isIncluded is required and must be a boolean' };\n }\n } else if (request.circuit === 'oidc_domain_attestation') {\n const inputs = request.inputs as OidcDomainInputs;\n if (!inputs.domain || typeof inputs.domain !== 'string' || inputs.domain.trim() === '') {\n return { valid: false, error: 'domain is required and must be a non-empty string' };\n }\n if (!inputs.scope || typeof inputs.scope !== 'string' || inputs.scope.trim() === '') {\n return { valid: false, error: 'scope is required and must be a non-empty string' };\n }\n if (inputs.provider !== undefined && (typeof inputs.provider !== 'string' || inputs.provider.trim() === '')) {\n return { valid: false, error: 'provider must be a non-empty string when specified' };\n }\n } else if (\n request.circuit === 'mdl_kr_ownership' ||\n request.circuit === 'mdl_kr_age' ||\n request.circuit === 'mdl_kr_region'\n ) {\n const mdlError = validateMdlInputs(request.circuit, request.inputs);\n if (mdlError) {\n return { valid: false, error: mdlError };\n }\n } else if (request.circuit === 'arc_eligibility') {\n const inputs = request.inputs as Partial<ArcEligibilityInputs>;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n const actionError = validateTypedAction(inputs.action);\n if (actionError) {\n return { valid: false, error: actionError };\n }\n }\n\n // Check expiry\n if (request.expiresAt && Date.now() > request.expiresAt) {\n return { valid: false, error: 'Request has expired' };\n }\n\n return { valid: true };\n}\n","/**\n * QR Code utilities for ZKProofport SDK\n */\n\nimport QRCode from 'qrcode';\nimport type { ProofRequest, QRCodeOptions } from './types';\nimport { buildProofRequestUrl } from './deeplink';\nimport { DEFAULT_SCHEME, MAX_QR_DATA_SIZE } from './constants';\n\n/**\n * Default QR code options\n */\nconst DEFAULT_QR_OPTIONS: QRCodeOptions = {\n width: 300,\n errorCorrectionLevel: 'M',\n margin: 2,\n darkColor: '#000000',\n lightColor: '#ffffff',\n};\n\n/**\n * Generates a QR code as a base64-encoded PNG data URL.\n *\n * Creates a scannable QR code image from a proof request or deep link URL.\n * The returned data URL can be used directly in HTML img src attributes.\n * Validates that the encoded data doesn't exceed the maximum QR code size.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to base64 PNG data URL (e.g., \"data:image/png;base64,...\")\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n *\n * const dataUrl = await generateQRCodeDataUrl(request, {\n * width: 400,\n * darkColor: '#000000',\n * lightColor: '#ffffff'\n * });\n *\n * // Use in HTML: <img src={dataUrl} alt=\"Scan to prove\" />\n * ```\n */\nexport async function generateQRCodeDataUrl(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n // Check data size\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toDataURL(url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Generates a QR code as an SVG string.\n *\n * Creates a scalable vector graphics QR code that can be embedded directly in HTML\n * or saved to a file. SVG QR codes scale perfectly at any size and have smaller\n * file sizes than raster formats.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to SVG markup string\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const svg = await generateQRCodeSVG(request, { width: 300 });\n *\n * // Embed directly: <div dangerouslySetInnerHTML={{ __html: svg }} />\n * // Or save to file: fs.writeFileSync('qr.svg', svg);\n * ```\n */\nexport async function generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toString(url, {\n type: 'svg',\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Browser-only function that draws a QR code onto an existing canvas element.\n * Useful for interactive applications or when you need direct canvas manipulation.\n * The canvas dimensions will be set automatically based on the width option.\n *\n * @param canvas - HTML canvas element to render to (must exist in DOM)\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise that resolves when rendering is complete\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n * @throws {Error} If canvas is not a valid HTMLCanvasElement (browser only)\n *\n * @example\n * ```typescript\n * // In a React component:\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n *\n * useEffect(() => {\n * if (canvasRef.current) {\n * generateQRCodeToCanvas(canvasRef.current, request, { width: 400 });\n * }\n * }, [request]);\n *\n * return <canvas ref={canvasRef} />;\n * ```\n */\nexport async function generateQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<void> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n await QRCode.toCanvas(canvas, url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Estimates the byte size of a QR code's encoded data.\n *\n * Calculates the size of the deep link URL that will be encoded in the QR code,\n * and checks if it's within the maximum supported size (2953 bytes for QR version 40\n * with medium error correction). Use this before generating QR codes to avoid errors.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Object with `size` in bytes and `withinLimit` boolean flag\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const { size, withinLimit } = estimateQRDataSize(request);\n *\n * if (!withinLimit) {\n * console.error(`QR code too large: ${size} bytes (max 2953)`);\n * // Consider reducing request data or splitting into multiple QR codes\n * }\n *\n * // Example output: { size: 384, withinLimit: true }\n * ```\n */\nexport function estimateQRDataSize(\n requestOrUrl: ProofRequest | string,\n scheme: string = DEFAULT_SCHEME\n): { size: number; withinLimit: boolean } {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n return {\n size: url.length,\n withinLimit: url.length <= MAX_QR_DATA_SIZE,\n };\n}\n","/**\n * On-chain verification utilities for ZKProofport SDK\n *\n * Compatible with both ethers v5 and v6.\n */\n\nimport { ethers } from 'ethers';\nimport type { CircuitType, ParsedProof, VerifierContract } from './types';\nimport { VERIFIER_ABI, RPC_ENDPOINTS, OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT } from './constants';\nimport { ALL_CIRCUIT_IDS, isCircuitId, type CircuitId } from './circuits';\n\n// ethers v5/v6 compatibility shims\nconst _ethers = ethers as any;\n\n/** @internal ethers v5/v6 compatibility shim */\nfunction hexZeroPad(value: string, length: number): string {\n // v6: ethers.zeroPadValue, v5: ethers.utils.hexZeroPad\n if (typeof _ethers.zeroPadValue === 'function') return _ethers.zeroPadValue(value, length);\n if (_ethers.utils?.hexZeroPad) return _ethers.utils.hexZeroPad(value, length);\n // manual fallback\n const hex = value.startsWith('0x') ? value.slice(2) : value;\n return '0x' + hex.padStart(length * 2, '0');\n}\n\n/** @internal ethers v5/v6 compatibility shim */\nfunction createJsonRpcProvider(url: string) {\n // v6: ethers.JsonRpcProvider, v5: ethers.providers.JsonRpcProvider\n if (typeof _ethers.JsonRpcProvider === 'function') return new _ethers.JsonRpcProvider(url);\n if (_ethers.providers?.JsonRpcProvider) return new _ethers.providers.JsonRpcProvider(url);\n throw new Error('No JsonRpcProvider found in ethers');\n}\n\n/**\n * @internal Resolve verifier from SDK config or proof response.\n * SDK config (customVerifier) takes priority over response-provided verifier.\n */\nfunction resolveVerifier(\n customVerifier?: VerifierContract,\n responseVerifier?: { verifierAddress?: string; chainId?: number }\n): VerifierContract | null {\n if (customVerifier) return customVerifier;\n if (responseVerifier?.verifierAddress) {\n return {\n address: responseVerifier.verifierAddress,\n chainId: responseVerifier.chainId ?? 0,\n abi: VERIFIER_ABI,\n };\n }\n return null;\n}\n\n/**\n * Get verifier contract instance for interacting with on-chain verifier contracts.\n *\n * @param providerOrSigner - ethers.js Provider or Signer instance (v5 or v6 compatible)\n * @param verifier - Verifier contract configuration containing address and ABI\n * @returns ethers.Contract instance connected to the verifier\n *\n * @example\n * ```typescript\n * const provider = new ethers.JsonRpcProvider(rpcUrl);\n * const contract = getVerifierContract(provider, {\n * address: '0x...',\n * chainId: 11155111,\n * abi: VERIFIER_ABI\n * });\n * ```\n */\nexport function getVerifierContract(\n providerOrSigner: any,\n verifier: VerifierContract\n): ethers.Contract {\n return new ethers.Contract(\n verifier.address,\n verifier.abi,\n providerOrSigner\n );\n}\n\n/**\n * Get default JSON-RPC provider for a chain using pre-configured RPC endpoints.\n *\n * @param chainId - The chain ID (e.g., 11155111 for Sepolia, 84532 for Base Sepolia)\n * @returns ethers.JsonRpcProvider instance for the specified chain\n * @throws Error if no RPC endpoint is configured for the chain\n *\n * @example\n * ```typescript\n * const provider = getDefaultProvider(11155111); // Sepolia\n * ```\n */\nexport function getDefaultProvider(chainId: number) {\n const rpcUrl = RPC_ENDPOINTS[chainId];\n if (!rpcUrl) {\n throw new Error(`No RPC endpoint configured for chain ${chainId}`);\n }\n return createJsonRpcProvider(rpcUrl);\n}\n\n/**\n * Verify a zero-knowledge proof on-chain by calling the verifier smart contract.\n *\n * This function resolves the verifier contract from SDK config or proof response,\n * connects to the blockchain, and calls the verify() method with the proof and public inputs.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param parsedProof - Parsed proof object containing proofHex and publicInputsHex\n * @param providerOrSigner - Optional ethers.js Provider or Signer instance. If not provided, uses default RPC for the chain\n * @param customVerifier - Optional custom verifier contract config (takes priority over responseVerifier)\n * @param responseVerifier - Optional verifier info from proof generation response\n * @returns Promise resolving to verification result with valid flag and optional error message\n *\n * @example\n * ```typescript\n * const parsed = parseProofForOnChain(proof, publicInputs, numPublicInputs);\n * const result = await verifyProofOnChain(\n * 'coinbase_attestation',\n * parsed,\n * provider,\n * { address: '0x...', chainId: 11155111, abi: VERIFIER_ABI }\n * );\n *\n * if (result.valid) {\n * console.log('Proof is valid!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * ```\n */\nexport async function verifyProofOnChain(\n circuit: CircuitType,\n parsedProof: ParsedProof,\n providerOrSigner?: any,\n customVerifier?: VerifierContract,\n responseVerifier?: { verifierAddress?: string; chainId?: number }\n): Promise<{ valid: boolean; error?: string }> {\n const verifier = resolveVerifier(customVerifier, responseVerifier);\n if (!verifier) {\n return {\n valid: false,\n error: 'No verifier address provided. Configure via SDK or ensure proof response includes verifierAddress.',\n };\n }\n\n const provider = providerOrSigner || (verifier.chainId > 0 ? getDefaultProvider(verifier.chainId) : null);\n if (!provider) {\n return {\n valid: false,\n error: 'No provider available. Provide a provider or ensure chainId is set for RPC lookup.',\n };\n }\n\n const contract = getVerifierContract(provider, verifier);\n\n try {\n const isValid = await contract.verify(\n parsedProof.proofHex,\n parsedProof.publicInputsHex\n );\n\n return { valid: isValid };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return { valid: false, error: errorMessage };\n }\n}\n\n/** @internal Ensure a hex string has the 0x prefix */\nfunction ensureHexPrefix(hex: string): string {\n return hex.startsWith('0x') ? hex : `0x${hex}`;\n}\n\n/**\n * Parse proof response into format suitable for on-chain verification.\n *\n * Converts proof and public inputs from relay response format to the format\n * expected by Solidity verifier contracts. Public inputs are zero-padded to\n * 32 bytes (bytes32) to match Solidity's bytes32[] type.\n *\n * @param proof - Proof bytes as hex string (with or without 0x prefix)\n * @param publicInputs - Array of public input values as hex strings\n * @param numPublicInputs - Number of public inputs (for validation)\n * @returns Parsed proof object ready for on-chain verification\n *\n * @example\n * ```typescript\n * const parsed = parseProofForOnChain(\n * '0x1a2b3c...',\n * ['0x01', '0x02', '0x03'],\n * 3\n * );\n *\n * // parsed.proofHex: '0x1a2b3c...'\n * // parsed.publicInputsHex: ['0x0000...01', '0x0000...02', '0x0000...03']\n * ```\n */\nexport function parseProofForOnChain(\n proof: string,\n publicInputs: string[],\n numPublicInputs: number\n): ParsedProof {\n const proofHex = ensureHexPrefix(proof);\n\n const publicInputsHex = publicInputs.map((input) => {\n return hexZeroPad(ensureHexPrefix(input), 32);\n });\n\n return {\n proofHex,\n publicInputsHex,\n numPublicInputs,\n };\n}\n\n/** @internal Require a verifier or throw with a helpful message */\nfunction requireVerifier(circuit: CircuitType, verifier?: VerifierContract): VerifierContract {\n if (!verifier) {\n throw new Error(`No verifier configured for circuit '${circuit}'. Configure via SDK verifiers option.`);\n }\n return verifier;\n}\n\n/**\n * Get verifier contract address for a circuit.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param customVerifier - Optional custom verifier contract config\n * @returns Verifier contract address as hex string\n * @throws Error if no verifier is configured for the circuit\n *\n * @example\n * ```typescript\n * const address = getVerifierAddress('coinbase_attestation', verifierConfig);\n * console.log(address); // '0x1234...'\n * ```\n */\nexport function getVerifierAddress(\n circuit: CircuitType,\n customVerifier?: VerifierContract\n): string {\n return requireVerifier(circuit, customVerifier).address;\n}\n\n/**\n * Get chain ID for a circuit's verifier contract.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param customVerifier - Optional custom verifier contract config\n * @returns Chain ID number (e.g., 11155111 for Sepolia, 84532 for Base Sepolia)\n * @throws Error if no verifier is configured for the circuit\n *\n * @example\n * ```typescript\n * const chainId = getVerifierChainId('coinbase_attestation', verifierConfig);\n * console.log(chainId); // 11155111\n * ```\n */\nexport function getVerifierChainId(\n circuit: CircuitType,\n customVerifier?: VerifierContract\n): number {\n return requireVerifier(circuit, customVerifier).chainId;\n}\n\n\n/**\n * Where `scope` and `nullifier` sit in each circuit's public inputs.\n *\n * Keyed by `CircuitId`, which is the point: adding a circuit to the SDK makes\n * this object a compile error until somebody opens that circuit's `fn main`\n * and writes its offsets down. Nothing here can be inferred from the proof —\n * the public inputs are a flat array of bytes with no framing.\n *\n * It replaced an `if / else if / else` chain whose final `else` handed every\n * unrecognised circuit — and every call that named no circuit at all —\n * Coinbase's offsets. For `arc_eligibility` that is not a near miss: its\n * public inputs are signal_hash, domain_separator, action_hash, merkle root,\n * scope, nullifier, so the nullifier slot under Coinbase's offsets holds the\n * MERKLE ROOT, a value identical for every user. Duplicate detection built on\n * it would report one person.\n */\nconst PUBLIC_INPUT_OFFSETS: Readonly<Record<CircuitId, { scope: readonly [number, number]; nullifier: readonly [number, number] }>> = Object.freeze({\n // signal_hash, signer_list_merkle_root, scope, nullifier\n coinbase_attestation: { scope: [64, 95], nullifier: [96, 127] },\n // Same four fields in the same order as Coinbase.\n giwa_attestation: { scope: [64, 95], nullifier: [96, 127] },\n // country_list, country_list_length and is_included sit before scope.\n coinbase_country_attestation: { scope: [86, 117], nullifier: [118, 149] },\n // pubkey_modulus_limbs and the bounded domain sit before scope.\n oidc_domain_attestation: { scope: [83, 114], nullifier: [115, 146] },\n // signal_hash, domain_separator, action_hash, merkle root, then the pair.\n arc_eligibility: { scope: [128, 159], nullifier: [160, 191] },\n // The Korea mDL circuits open with the pair; signal_hash is commented out.\n mdl_kr_ownership: { scope: [0, 31], nullifier: [32, 63] },\n mdl_kr_age: { scope: [0, 31], nullifier: [32, 63] },\n mdl_kr_region: { scope: [0, 31], nullifier: [32, 63] },\n});\n\n/**\n * The offsets for a circuit, or an error naming what was asked for.\n *\n * Throwing is the whole point. A caller that omits the circuit, or names one\n * this SDK has never heard of, is asking a question with no answer; returning\n * a guess produced a scope and a nullifier that belong to different bytes and\n * looked exactly like real ones.\n */\nfunction offsetsFor(circuit: string | undefined): { scope: readonly [number, number]; nullifier: readonly [number, number] } {\n if (circuit === undefined) {\n throw new Error(\n `A circuit id is required to read public inputs: the layout differs per circuit and cannot be inferred from the proof. Pass one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n );\n }\n if (!isCircuitId(circuit)) {\n throw new Error(\n `Unknown circuit '${circuit}'. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n );\n }\n return PUBLIC_INPUT_OFFSETS[circuit];\n}\n\n/**\n * Extract scope value from public inputs array.\n *\n * The scope is a bytes32 value encoded across 32 consecutive field elements\n * in the public inputs. The exact position depends on the circuit type.\n *\n * @param publicInputsHex - Array of public input hex strings (zero-padded to 32 bytes)\n * @param circuit - Optional circuit identifier to determine field positions\n * @returns Reconstructed scope as hex string with 0x prefix, or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const scope = extractScopeFromPublicInputs(publicInputsHex, 'coinbase_attestation');\n * console.log(scope); // '0x7a6b70726f6f66706f72742e636f6d...'\n * ```\n */\nexport function extractScopeFromPublicInputs(\n publicInputsHex: string[],\n circuit: string,\n): string | null {\n const [start, end] = offsetsFor(circuit).scope;\n if (publicInputsHex.length <= end) return null;\n const scopeFields = publicInputsHex.slice(start, end + 1);\n return reconstructBytes32FromFields(scopeFields);\n}\n\n/**\n * Extracts the nullifier (bytes32) from public inputs based on circuit type.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputsHex - Array of hex-encoded field elements\n * @param circuit - Circuit id. REQUIRED: the layout differs per circuit and\n * cannot be inferred from the proof. It used to default to\n * `coinbase_attestation`, which returned the right-shaped bytes read from\n * the wrong place for every other circuit.\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const nullifier = extractNullifierFromPublicInputs(publicInputs, 'coinbase_attestation');\n * console.log(nullifier); // '0xabc123...'\n * ```\n */\nexport function extractNullifierFromPublicInputs(\n publicInputsHex: string[],\n circuit: string,\n): string | null {\n const [start, end] = offsetsFor(circuit).nullifier;\n if (publicInputsHex.length <= end) return null;\n const nullifierFields = publicInputsHex.slice(start, end + 1);\n return reconstructBytes32FromFields(nullifierFields);\n}\n\n/**\n * Extract domain string from OIDC Domain Attestation public inputs.\n *\n * The domain is stored as a Noir BoundedVec<u8, 64>, which serializes as\n * [storage[0..64], len]. Each storage element is a u8 value in a field element.\n *\n * @param publicInputsHex - Array of public input hex strings\n * @param circuit - Circuit identifier (must be 'oidc_domain_attestation')\n * @returns Domain as ASCII string, or null if circuit doesn't match or inputs are insufficient\n *\n * @example\n * ```typescript\n * const domain = extractDomainFromPublicInputs(publicInputs, 'oidc_domain_attestation');\n * console.log(domain); // 'example.com'\n * ```\n */\nexport function extractDomainFromPublicInputs(\n publicInputsHex: string[],\n circuit?: string,\n): string | null {\n if (circuit !== 'oidc_domain_attestation') return null;\n\n const layout = OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT;\n if (publicInputsHex.length <= layout.DOMAIN_LEN) return null;\n\n const len = Number(BigInt(publicInputsHex[layout.DOMAIN_LEN]) & 0xFFn);\n if (len === 0 || len > 64) return null;\n\n const storageFields = publicInputsHex.slice(\n layout.DOMAIN_STORAGE_START,\n layout.DOMAIN_STORAGE_START + len,\n );\n\n const chars = storageFields.map(f => {\n const byte = Number(BigInt(f) & 0xFFn);\n return String.fromCharCode(byte);\n });\n\n return chars.join('');\n}\n\n/** @internal Reconstruct a bytes32 value from 32 individual field elements */\nfunction reconstructBytes32FromFields(fields: string[]): string {\n if (fields.length !== 32) {\n throw new Error(`Expected 32 fields, got ${fields.length}`);\n }\n const bytes = fields.map(f => {\n const byte = BigInt(f) & 0xFFn;\n return byte.toString(16).padStart(2, '0');\n }).join('');\n return '0x' + bytes;\n}\n","/**\n * Off-chain proof verification — checking a proof against its verification key,\n * with no chain, no RPC, and no gas.\n *\n * WHY THIS EXISTS. The SDK had only `verifyProofOnChain`, and every caller that\n * wanted an off-chain check called that instead and relabelled the result. The\n * demo page did exactly this from its first commit: pressing \"Off-Chain Verify\"\n * ran an on-chain verification and printed \"Off-Chain Verification Passed!\".\n * The answer was true and the label was a lie, which is the worst combination —\n * nothing looked broken. The mobile app has always verified off-chain properly\n * (through mopro's native Barretenberg); it was only the JavaScript side that\n * had no such thing.\n *\n * HOW IT WORKS. Proofs here are made with `--oracle_hash keccak` and ZK on, so\n * the matching check is `acirVerifyUltraKeccakZkHonk(proof, vk)`. Two things\n * have to line up:\n *\n * The version. `@aztec/bb.js@1.0.0-nightly.20250723` is the WASM build of the\n * same bb the circuits are compiled with. Versions are not interchangeable:\n * measured on the Korea Mobile ID age circuit, the pinned bb writes a 16256-\n * byte proof where bb 1.2.0 writes 16224 for the identical circuit and\n * witness — and the verification key comes out the SAME either way, so the\n * key cannot warn you. A mismatch shows up only as verification failing.\n *\n * The flavour. There are four verify entry points and picking the wrong one\n * is not a polite false. `acirVerifyUltraZKHonk` (poseidon) answers false for\n * a perfectly good proof, and `acirVerifyUltraKeccakHonk` — keccak without ZK\n * — TRAPS the WebAssembly with a bare \"unreachable\", which looks exactly like\n * a corrupt proof, a mismatched key, or a missing SRS.\n *\n * THE PROOF ARRIVES IN TWO PIECES. The mobile app splits what Barretenberg\n * produced into `proof` and `publicInputs` before sending it, because the\n * Solidity verifier takes them separately. Verifying needs them joined back, in\n * that order, which is what `reconstructHonkProof` does.\n */\nimport { CIRCUIT_VK_PATHS, type CircuitId } from './circuits';\n\n/**\n * Where verification keys are published.\n *\n * Not configurable, deliberately: a caller who could point this somewhere else\n * could point it at a key of their choosing, and \"the proof verified\" would\n * then mean nothing. Same repository the mobile app downloads circuit data\n * from.\n */\nconst CIRCUITS_VK_BASE =\n 'https://raw.githubusercontent.com/zkproofport/circuits/main';\n\n/** How long a fetched verification key is reused. Keys change only on a recompile. */\nconst VK_CACHE_TTL_MS = 60 * 60 * 1000;\n\nconst vkCache = new Map<string, { vk: Uint8Array; at: number }>();\n\nexport interface OffChainVerifyResult {\n valid: boolean;\n error?: string;\n}\n\nexport interface OffChainVerifyOptions {\n /**\n * Verification key bytes, if the caller already has them. Skips the fetch —\n * useful offline, in tests, and for anyone who would rather pin the key they\n * checked than trust a download.\n */\n verificationKey?: Uint8Array;\n /** Milliseconds before the fetch is abandoned. Default 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Make sure a Node-shaped `Buffer` exists before Barretenberg is loaded.\n *\n * WHY THE SDK DOES THIS RATHER THAN THE CALLER. bb.js's own BROWSER build —\n * not just its node build — converts field elements through `Buffer.alloc` and\n * `buf.writeBigUInt64BE`. Browsers have no Buffer, and bundlers stopped\n * polyfilling Node globals years ago, so in a browser the first verification\n * dies with \"r.writeBigUInt64BE is not a function\" — a message that names\n * nothing a caller could act on. Measured on the demo page, 2026-09-04, against\n * a real GIWA proof.\n *\n * Leaving it to callers would mean every browser customer editing their\n * bundler config to make an SDK method work, which is the configuration this\n * SDK promises not to require.\n *\n * Deliberately narrow:\n * - It only fills a GAP. A real Buffer (Node, or a page that already has one)\n * is left alone, so nothing is shadowed by a lesser implementation.\n * - It checks for the METHOD, not just the global. A partial Buffer — which is\n * what several bundlers leave behind, and what the demo page actually had —\n * passes a `typeof Buffer` test and then fails inside Barretenberg.\n */\nasync function ensureBufferForBarretenberg(): Promise<void> {\n const existing = (globalThis as { Buffer?: { alloc?: (n: number) => unknown } }).Buffer;\n if (existing?.alloc) {\n const probe = existing.alloc(8) as { writeBigUInt64BE?: unknown };\n if (typeof probe.writeBigUInt64BE === 'function') return;\n }\n const { Buffer } = await import('buffer/');\n (globalThis as { Buffer?: unknown }).Buffer = Buffer;\n}\n\n/** @internal Hex string (with or without 0x) to bytes. */\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length === 0) return new Uint8Array(0);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has an odd length (${clean.length}); it cannot be bytes`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('Hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/**\n * @internal Public inputs as the flat byte run Barretenberg expects: each one a\n * 32-byte big-endian field element, concatenated in order.\n *\n * The relay carries them as hex strings that are USUALLY already 32 bytes, but\n * a value that happens to have leading zeros can arrive short (`0x01`). Left-\n * padding here rather than trusting the sender is the difference between a\n * verification that works and one that fails on roughly one proof in a hundred,\n * for no reason the caller can see.\n */\nfunction packPublicInputs(publicInputs: string[]): Uint8Array {\n const out = new Uint8Array(publicInputs.length * 32);\n publicInputs.forEach((input, i) => {\n const bytes = hexToBytes(input);\n if (bytes.length > 32) {\n throw new Error(\n `Public input ${i} is ${bytes.length} bytes; a field element is at most 32`\n );\n }\n out.set(bytes, i * 32 + (32 - bytes.length));\n });\n return out;\n}\n\n/**\n * Fetch a circuit's verification key, with a small cache.\n *\n * @internal\n */\nasync function fetchVerificationKey(\n circuit: CircuitId,\n timeoutMs: number\n): Promise<Uint8Array> {\n const cached = vkCache.get(circuit);\n if (cached && Date.now() - cached.at < VK_CACHE_TTL_MS) return cached.vk;\n\n const vkPath = CIRCUIT_VK_PATHS[circuit];\n if (!vkPath) {\n throw new Error(\n `No verification key path for circuit '${circuit}'. ` +\n `Add it to CIRCUIT_VK_PATHS, or pass verificationKey directly.`\n );\n }\n\n const url = `${CIRCUITS_VK_BASE}/${vkPath}`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const resp = await fetch(url, { signal: controller.signal });\n if (!resp.ok) {\n throw new Error(`Could not fetch the verification key (HTTP ${resp.status}) from ${url}`);\n }\n const vk = new Uint8Array(await resp.arrayBuffer());\n // A 404 page or an HTML redirect arrives as a successful response full of\n // text, and would reach Barretenberg as a \"verification key\" that fails for\n // reasons no one could guess from the message.\n if (vk.length < 512) {\n throw new Error(\n `The verification key at ${url} is ${vk.length} bytes, far too small to be one. ` +\n `The path is probably wrong and something else was served.`\n );\n }\n vkCache.set(circuit, { vk, at: Date.now() });\n return vk;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Verify a proof off-chain, against its verification key.\n *\n * Needs no setup from the caller: the verifier ships with this SDK and is\n * loaded on first use.\n *\n * @param circuit - Canonical circuit identifier\n * @param proof - Proof bytes as hex, WITHOUT public inputs (as the relay sends it)\n * @param publicInputs - Public inputs as hex strings, in circuit order\n * @param options - Optional verification key and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` when the check could not run\n *\n * @example\n * ```typescript\n * const result = await verifyProofOffChain(\n * 'coinbase_attestation',\n * response.proof,\n * response.publicInputs\n * );\n * if (result.valid) console.log('Proof is valid, no chain involved');\n * ```\n */\nexport async function verifyProofOffChain(\n circuit: CircuitId,\n proof: string,\n publicInputs: string[],\n options: OffChainVerifyOptions = {}\n): Promise<OffChainVerifyResult> {\n const timeoutMs = options.timeoutMs ?? 30000;\n\n // A REQUIRED dependency, loaded lazily.\n //\n // It was briefly an optional peer dependency, on the reasoning that the WASM\n // is 16MB and most callers verify on-chain. That was wrong: it would have\n // meant a customer calling this method got an error telling them to install\n // something, and \"works with zero customer configuration\" is the SDK's rule.\n // A caller should never have to know this is implemented with Barretenberg.\n //\n // The dynamic import is what keeps the cost off everyone else — a bundler\n // splits it out, and a caller who never verifies off-chain never loads it.\n // Before bb.js, not after: its module-level code already reaches for Buffer.\n await ensureBufferForBarretenberg();\n\n let bb: typeof import('@aztec/bb.js');\n try {\n bb = await import('@aztec/bb.js');\n } catch (error) {\n // Reaching here means the install is broken, not that something is missing\n // by design. Say so, rather than sending the caller off to install a\n // package they should never have had to hear about.\n return {\n valid: false,\n error:\n 'Could not load the proof verifier (@aztec/bb.js), which ships with this ' +\n 'SDK. This usually means a broken or partial install — try reinstalling ' +\n `@zkproofport-app/sdk. Underlying error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n let api:\n | {\n initSRSForCircuitSize(size: number): Promise<void>;\n acirVerifyUltraKeccakZkHonk(p: Uint8Array, v: unknown): Promise<boolean>;\n destroy(): Promise<void>;\n }\n | undefined;\n try {\n const proofBytes = hexToBytes(proof);\n if (proofBytes.length === 0) {\n return { valid: false, error: 'Proof is empty' };\n }\n const publicInputBytes = packPublicInputs(publicInputs);\n\n const vk =\n options.verificationKey ?? (await fetchVerificationKey(circuit, timeoutMs));\n\n // Public inputs first, then the proof — the order Barretenberg wrote them in\n // before the mobile app split them apart for the Solidity verifier.\n const full = bb.reconstructHonkProof(publicInputBytes, proofBytes);\n\n api = (await bb.Barretenberg.new({ threads: 1 })) as unknown as typeof api;\n\n // THE VERIFY MUST MATCH HOW THE PROOF WAS MADE, AND THERE ARE FOUR OF THEM.\n //\n // `scripts/build.sh` in the circuits repo proves with `--oracle_hash keccak`\n // and ZK on — so the only entry point that answers correctly is the one that\n // is BOTH. Measured against a real proof of the Korea Mobile ID age circuit,\n // freshly generated against its own key:\n //\n // acirVerifyUltraKeccakZkHonk true ← the right one\n // acirVerifyUltraKeccakHonk TRAPS with a bare \"unreachable\"\n // acirVerifyUltraZKHonk false (poseidon: wrong oracle hash)\n //\n // The middle row is why this took a while: picking keccak-without-ZK does\n // not return false, it kills the WebAssembly instance with a message that\n // names nothing. It looks identical to a malformed proof, to a mismatched\n // key, and to a missing SRS.\n //\n // Two more things that produce that same trap, both required:\n // initSRSForCircuitSize must be called before the first verify.\n // The key must be a RawBuffer — a plain Uint8Array is marshalled as a\n // length-prefixed vector, so its length is read as key material.\n // Both are what bb.js's own BarretenbergVerifier does before verifying.\n await api!.initSRSForCircuitSize(0);\n const valid = await api!.acirVerifyUltraKeccakZkHonk(full, new bb.RawBuffer(vk));\n return { valid };\n } catch (error) {\n return { valid: false, error: error instanceof Error ? error.message : String(error) };\n } finally {\n // The WASM instance holds worker threads; leaving them running keeps a Node\n // process alive after the check is done.\n if (api) {\n try {\n await api.destroy();\n } catch {\n /* nothing useful to do if teardown fails */\n }\n }\n }\n}\n\n/** @internal Test seam — lets a test start from a known-empty cache. */\nexport function clearVerificationKeyCache(): void {\n vkCache.clear();\n}\n","/**\n * Proofport SDK - Main class\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitType,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n ProofportConfig,\n QRCodeOptions,\n ParsedProof,\n VerifierContract,\n ChallengeResponse,\n WalletSigner,\n RelayProofRequest,\n RelayProofResult,\n} from './types';\nimport {\n generateRequestId,\n buildProofRequestUrl,\n buildCallbackUrl,\n parseProofRequestUrl,\n parseProofResponseUrl,\n validateProofRequest,\n validateMdlInputs,\n validateReturnScheme,\n detectReturnScheme,\n isProofportDeepLink,\n} from './deeplink';\nimport {\n generateQRCodeDataUrl,\n generateQRCodeSVG,\n generateQRCodeToCanvas,\n estimateQRDataSize,\n} from './qrcode';\nimport {\n verifyProofOnChain,\n parseProofForOnChain,\n getVerifierAddress,\n getVerifierChainId,\n getDefaultProvider,\n extractScopeFromPublicInputs,\n extractNullifierFromPublicInputs,\n extractDomainFromPublicInputs,\n} from './verifier';\nimport {\n verifyProofOffChain,\n type OffChainVerifyOptions,\n} from './offChainVerifier';\nimport {\n DEFAULT_SCHEME,\n DEFAULT_REQUEST_EXPIRY_MS,\n CIRCUIT_METADATA,\n RELAY_URLS,\n} from './constants';\nimport { CIRCUIT_NEEDS_WALLET_SIGNATURE, type CircuitId } from './circuits';\nimport { validateTypedAction } from './typedAction';\nimport type { SDKEnvironment } from './types';\n\n\n/**\n * Main SDK class for interacting with the ZKProofport mobile app.\n *\n * Provides methods for creating proof requests, generating QR codes and deep links,\n * verifying proofs on-chain, and handling proof responses from the mobile app.\n *\n * @example\n * ```typescript\n * import { ProofportSDK } from '@zkproofport-app/sdk';\n * import { BrowserProvider } from 'ethers';\n *\n * // Initialize SDK (uses production relay by default)\n * const sdk = ProofportSDK.create();\n *\n * // Set wallet signer for challenge-signature auth\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n *\n * // Create proof request via relay\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * });\n *\n * // Generate QR code for desktop users\n * const qrDataUrl = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof via WebSocket (primary) or polling (fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof received:', result.proof);\n * }\n * ```\n */\nexport class ProofportSDK {\n private config: Required<Omit<ProofportConfig, 'relayUrl'>>;\n private pendingRequests: Map<string, ProofRequest> = new Map();\n private signer: WalletSigner | null = null;\n private relayUrl: string;\n private socket: any = null;\n\n /**\n * Creates a new ProofportSDK instance.\n *\n * For most use cases, prefer the static factory with environment presets:\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * ```\n *\n * @param config - SDK configuration options\n * @param config.scheme - Custom deep link scheme (default: 'zkproofport')\n * @param config.relayUrl - Relay server URL (required for relay features)\n * @param config.verifiers - Custom verifier contract addresses per circuit\n *\n * @example\n * ```typescript\n * const sdk = new ProofportSDK({\n * relayUrl: 'https://relay.zkproofport.app',\n * verifiers: {\n * coinbase_attestation: {\n * verifierAddress: '0x...',\n * chainId: 1\n * }\n * }\n * });\n * ```\n */\n constructor(config: ProofportConfig = {}) {\n this.config = {\n scheme: config.scheme || DEFAULT_SCHEME,\n verifiers: config.verifiers || {},\n };\n this.relayUrl = config.relayUrl || '';\n }\n\n // ============ Request Creation ============\n\n /**\n * @internal\n * Creates a Coinbase KYC verification proof request.\n *\n * Generates a proof request for verifying Coinbase KYC status without revealing\n * the actual attestation data. The proof confirms the user has passed Coinbase KYC\n * while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase KYC\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your KYC status to access this feature'\n * });\n *\n * const deepLink = sdk.getDeepLinkUrl(request);\n * ```\n */\n private createCoinbaseKycRequest(\n inputs: CoinbaseKycInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a Coinbase Country attestation proof request.\n *\n * Generates a proof request for verifying country eligibility through Coinbase\n * attestation without revealing the actual country data. The proof confirms the\n * user's country status while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase Country attestation\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseCountryRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your country eligibility'\n * });\n * ```\n */\n private createCoinbaseCountryRequest(\n inputs: CoinbaseCountryInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_country_attestation circuit');\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n throw new Error('countryList is required for coinbase_country_attestation circuit');\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n throw new Error('isIncluded is required for coinbase_country_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_country_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a generic proof request for any supported circuit type.\n *\n * Routes to the appropriate circuit-specific request creation method based on\n * the circuit type. Use this for dynamic circuit selection or when the circuit\n * type is determined at runtime.\n *\n * @param circuit - Circuit type identifier ('coinbase_attestation' | 'coinbase_country_attestation')\n * @param inputs - Circuit-specific inputs\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 15 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if required inputs are missing for the specified circuit\n *\n * @example\n * ```typescript\n * const circuitType = userSelection; // Dynamic selection\n * const request = sdk.createProofRequest(\n * circuitType,\n * { scope: 'myapp.com' },\n * { dappName: 'My DApp' }\n * );\n * ```\n */\n private createProofRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (circuit === 'coinbase_country_attestation') {\n return this.createCoinbaseCountryRequest(inputs as CoinbaseCountryInputs, options);\n } else if (\n circuit === 'mdl_kr_ownership' ||\n circuit === 'mdl_kr_age' ||\n circuit === 'mdl_kr_region'\n ) {\n return this.createMdlKrRequest(circuit, inputs, options);\n } else {\n return this.createCoinbaseKycRequest(inputs as CoinbaseKycInputs, options);\n }\n }\n\n /**\n * @internal\n * Creates a Korea Mobile ID (mDL) proof request for any of the three\n * mDL predicate circuits (ownership / age / region).\n *\n * The mobile app collects the license data on-device; the dapp only\n * supplies the predicate parameters validated here. No wallet signature\n * is required for mDL circuits.\n *\n * @param circuit - 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region'\n * @param inputs - Predicate inputs (see MdlKr*Inputs types)\n * @param options - Request configuration options\n *\n * @throws Error if the predicate inputs fail validation\n */\n private createMdlKrRequest(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit,\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n // ============ Deep Link Generation ============\n\n /**\n * @internal\n * Generates a deep link URL for a proof request.\n *\n * Creates a zkproofport:// URL that opens the ZKProofport mobile app with the\n * specified proof request. The URL contains all request details encoded as query\n * parameters.\n *\n * @param request - ProofRequest object to encode as deep link\n *\n * @returns Deep link URL string (e.g., 'zkproofport://proof?requestId=...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const url = sdk.getDeepLinkUrl(request);\n * // url: 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...'\n * ```\n */\n private getDeepLinkUrl(request: ProofRequest): string {\n return buildProofRequestUrl(request, this.config.scheme);\n }\n\n /**\n * @internal\n * Opens the ZKProofport mobile app with a proof request.\n *\n * Redirects the browser to the deep link URL, which opens the ZKProofport app\n * if installed. Only works in mobile browser environments. For desktop, use\n * requestProof() to display a QR code instead.\n *\n * @param request - ProofRequest object to send to the app\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * if (ProofportSDK.isMobile()) {\n * sdk.openProofRequest(request); // Opens app directly\n * }\n * ```\n */\n private openProofRequest(request: ProofRequest): void {\n const url = this.getDeepLinkUrl(request);\n window.location.href = url;\n }\n\n /**\n * @internal\n * Requests a proof with automatic platform detection.\n *\n * Detects whether the user is on mobile or desktop and automatically chooses\n * the appropriate flow:\n * - Mobile: Opens the deep link directly to launch the ZKProofport app\n * - Desktop: Generates a QR code data URL for the user to scan\n *\n * @param request - ProofRequest object to send\n * @param qrOptions - QR code generation options (size, colors, logo) for desktop\n *\n * @returns Object containing deep link URL, optional QR code data URL, and platform detection result\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const result = await sdk.requestProof(request);\n *\n * if (result.mobile) {\n * console.log('Opening app directly');\n * } else {\n * // Display QR code for desktop users\n * document.getElementById('qr').src = result.qrDataUrl;\n * }\n * ```\n */\n private async requestProof(\n request: ProofRequest,\n qrOptions?: QRCodeOptions\n ): Promise<{ deepLink: string; qrDataUrl?: string; mobile: boolean }> {\n const deepLink = this.getDeepLinkUrl(request);\n const mobile = ProofportSDK.isMobile();\n\n if (mobile) {\n window.location.href = deepLink;\n return { deepLink, mobile: true };\n }\n\n const qrDataUrl = await this.generateQRCode(request, qrOptions);\n return { deepLink, qrDataUrl, mobile: false };\n }\n\n // ============ QR Code Generation ============\n\n /**\n * Generates a QR code as a data URL for a proof request.\n *\n * Creates a PNG image data URL that can be directly set as an img src attribute.\n * Suitable for embedding QR codes in web pages for desktop users to scan with\n * their mobile device.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n * @param options.logoUrl - Optional center logo image URL\n * @param options.logoSize - Logo size as fraction of QR code (default: 0.2)\n *\n * @returns Promise resolving to PNG data URL (e.g., 'data:image/png;base64,...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const qrUrl = await sdk.generateQRCode(request, {\n * size: 400,\n * darkColor: '#1a1a1a',\n * logoUrl: 'https://myapp.com/logo.png'\n * });\n * document.getElementById('qr-image').src = qrUrl;\n * ```\n */\n async generateQRCode(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeDataUrl(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Generates a QR code as an SVG string for a proof request.\n *\n * Creates a scalable vector graphics representation of the QR code, ideal for\n * high-resolution displays or when vector format is preferred over raster images.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise resolving to SVG string\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const svgString = await sdk.generateQRCodeSVG(request);\n * document.getElementById('qr-container').innerHTML = svgString;\n * ```\n */\n async generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeSVG(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Draws the QR code onto the provided canvas element, useful for custom\n * rendering workflows or when you need direct canvas manipulation.\n *\n * @param canvas - HTML canvas element to render to\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise that resolves when rendering is complete\n *\n * @example\n * ```typescript\n * const canvas = document.getElementById('qr-canvas') as HTMLCanvasElement;\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * await sdk.renderQRCodeToCanvas(canvas, request, { size: 400 });\n * ```\n */\n async renderQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<void> {\n return generateQRCodeToCanvas(canvas, requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Checks if a proof request fits within QR code size limits.\n *\n * Estimates the encoded data size and validates it against QR code capacity limits.\n * Useful for validating requests before generating QR codes, especially when\n * including large custom messages or metadata.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n *\n * @returns Object with size in bytes and whether it fits within limits\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const check = sdk.checkQRCodeSize(request);\n * if (!check.withinLimit) {\n * console.warn(`Request too large: ${check.size} bytes`);\n * }\n * ```\n */\n checkQRCodeSize(requestOrUrl: ProofRequest | string): { size: number; withinLimit: boolean } {\n return estimateQRDataSize(requestOrUrl, this.config.scheme);\n }\n\n // ============ Response Handling ============\n\n /**\n * @internal\n * Parses a proof response from a callback URL.\n *\n * Extracts and decodes proof response data from the callback URL query parameters\n * after the user completes proof generation in the ZKProofport app. The app\n * redirects to your callback URL with the proof data encoded as query parameters.\n *\n * @param url - Callback URL containing proof response data\n *\n * @returns ProofResponse object with status, proof data, and public inputs, or null if invalid\n *\n * @example\n * ```typescript\n * // In your callback endpoint handler\n * app.get('/callback', (req, res) => {\n * const callbackUrl = req.url;\n * const response = sdk.parseResponse(callbackUrl);\n *\n * if (response?.status === 'completed') {\n * console.log('Proof received:', response.proof);\n * console.log('Public inputs:', response.publicInputs);\n * } else if (response?.status === 'rejected') {\n * console.log('User rejected the request');\n * }\n * });\n * ```\n */\n private parseResponse(url: string): ProofResponse | null {\n return parseProofResponseUrl(url);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport proof response callback.\n *\n * Validates whether the given URL contains the required query parameters for a\n * proof response. Useful for filtering and routing callback requests.\n *\n * @param url - URL to check\n *\n * @returns True if the URL appears to be a ZKProofport response callback\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n * if (sdk.isProofportResponse(fullUrl)) {\n * const response = sdk.parseResponse(fullUrl);\n * // Handle proof response\n * }\n * });\n * ```\n */\n private isProofportResponse(url: string): boolean {\n try {\n const urlObj = new URL(url);\n return urlObj.searchParams.has('requestId') && urlObj.searchParams.has('status');\n } catch {\n return false;\n }\n }\n\n /**\n * @internal\n * Retrieves a pending proof request by its ID.\n *\n * Looks up a previously created proof request from the SDK's internal cache.\n * Useful for validating callback responses and maintaining request state.\n *\n * @param requestId - Unique request identifier\n *\n * @returns ProofRequest object if found, undefined otherwise\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * const originalRequest = sdk.getPendingRequest(response.requestId);\n *\n * if (originalRequest) {\n * console.log('Original request:', originalRequest);\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private getPendingRequest(requestId: string): ProofRequest | undefined {\n return this.pendingRequests.get(requestId);\n }\n\n /**\n * @internal\n * Clears a pending proof request from the internal cache.\n *\n * Removes a proof request from the SDK's pending requests map. Should be called\n * after successfully processing a proof response to prevent memory leaks.\n *\n * @param requestId - Unique request identifier to remove\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * if (response?.status === 'completed') {\n * // Process proof...\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private clearPendingRequest(requestId: string): void {\n this.pendingRequests.delete(requestId);\n }\n\n // ============ Verification ============\n\n /**\n * Verifies a zero-knowledge proof on-chain using the deployed verifier contract.\n *\n * Calls the Solidity verifier contract to cryptographically verify the proof's\n * validity. This ensures the proof was generated correctly and the public inputs\n * match the claimed values.\n *\n * @param circuit - Circuit type identifier\n * @param proof - Hex-encoded proof string from the ZKProofport app\n * @param publicInputs - Array of hex-encoded public input strings\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * const response = sdk.parseResponse(callbackUrl);\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyOnChain(\n * response.circuit,\n * response.proof,\n * response.publicInputs,\n * provider\n * );\n *\n * if (result.valid) {\n * console.log('Proof verified on-chain!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * }\n * ```\n */\n async verifyOnChain(\n circuit: CircuitType,\n proof: string,\n publicInputs: string[],\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n const parsedProof = parseProofForOnChain(\n proof,\n publicInputs,\n publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[circuit];\n return verifyProofOnChain(circuit, parsedProof, providerOrSigner, customVerifier);\n }\n\n /**\n * Verifies a proof response on-chain using the deployed verifier contract.\n *\n * Convenience method that extracts proof data from a ProofResponse object and\n * verifies it on-chain. Automatically handles incomplete or rejected responses.\n *\n * @param response - ProofResponse object from parseResponse()\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * app.get('/callback', async (req, res) => {\n * const response = sdk.parseResponse(req.url);\n *\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyResponseOnChain(response, provider);\n *\n * if (result.valid) {\n * // Grant access to user\n * res.json({ success: true, verified: true });\n * } else {\n * res.status(400).json({ error: result.error });\n * }\n * } else {\n * res.status(400).json({ error: 'Proof generation failed or rejected' });\n * }\n * });\n * ```\n */\n async verifyResponseOnChain(\n response: ProofResponse,\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n\n const parsedProof = parseProofForOnChain(\n response.proof,\n response.publicInputs,\n response.publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[response.circuit];\n const responseVerifier = {\n verifierAddress: response.verifierAddress,\n chainId: response.chainId,\n };\n return verifyProofOnChain(response.circuit, parsedProof, providerOrSigner, customVerifier, responseVerifier);\n }\n\n /**\n * Verifies a proof response off-chain, against the circuit's verification key.\n *\n * No chain, no RPC, no gas, and no verifier contract — so this works for a\n * circuit whose verifier has not been deployed anywhere, and it does not\n * depend on a network being reachable. What it does not give you is the\n * chain's own opinion: use {@link verifyResponseOnChain} when the answer has\n * to be one a contract will agree with.\n *\n * Needs no setup: the verifier ships with this SDK. It is loaded on first\n * use, so a caller who only verifies on-chain never pays for it.\n *\n * @param response - Proof response from the relay\n * @param options - Optional verification key (skips the fetch) and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` if the check could not run\n *\n * @example\n * ```typescript\n * const result = await sdk.verifyResponseOffChain(response);\n * if (result.valid) {\n * console.log('Valid, and nothing was asked of any chain');\n * }\n * ```\n */\n async verifyResponseOffChain(\n response: ProofResponse,\n options?: OffChainVerifyOptions\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n return verifyProofOffChain(\n response.circuit,\n response.proof,\n response.publicInputs,\n options\n );\n }\n\n // ============ Utility Methods ============\n\n /**\n * Gets the deployed verifier contract address for a circuit.\n *\n * Returns the Ethereum address of the Solidity verifier contract for the\n * specified circuit. Uses custom verifier if configured, otherwise returns\n * the default deployed address.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Ethereum address of the verifier contract (0x...)\n *\n * @example\n * ```typescript\n * const address = sdk.getVerifierAddress('coinbase_attestation');\n * console.log('Verifier deployed at:', address);\n * ```\n */\n getVerifierAddress(circuit: CircuitType): string {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierAddress(circuit, customVerifier);\n }\n\n /**\n * Gets the blockchain chain ID where the verifier contract is deployed.\n *\n * Returns the EIP-155 chain ID for the network where the verifier contract\n * is deployed. Uses custom verifier if configured, otherwise returns the\n * default chain ID (Base mainnet: 8453).\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Chain ID number (e.g., 8453 for Base mainnet)\n *\n * @example\n * ```typescript\n * const chainId = sdk.getVerifierChainId('coinbase_attestation');\n * console.log('Verifier on chain:', chainId); // 8453 (Base mainnet)\n * ```\n */\n getVerifierChainId(circuit: CircuitType): number {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierChainId(circuit, customVerifier);\n }\n\n /**\n * Gets metadata for a specific circuit type.\n *\n * Returns circuit metadata including display name, description, required inputs,\n * and other configuration details.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Circuit metadata object with name, description, and configuration\n *\n * @example\n * ```typescript\n * const metadata = sdk.getCircuitMetadata('coinbase_attestation');\n * console.log('Circuit name:', metadata.name);\n * console.log('Description:', metadata.description);\n * ```\n */\n getCircuitMetadata(circuit: CircuitType) {\n return CIRCUIT_METADATA[circuit];\n }\n\n /**\n * Gets all supported circuit types.\n *\n * Returns an array of all circuit type identifiers that are currently supported\n * by the SDK and ZKProofport app.\n *\n * @returns Array of supported circuit type identifiers\n *\n * @example\n * ```typescript\n * const circuits = sdk.getSupportedCircuits();\n * console.log('Supported circuits:', circuits);\n * // ['coinbase_attestation', 'coinbase_country_attestation']\n * ```\n */\n getSupportedCircuits(): CircuitType[] {\n return Object.keys(CIRCUIT_METADATA) as CircuitType[];\n }\n\n /**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Checks that the proof request contains all required fields and that the\n * circuit-specific inputs are valid. Useful for catching configuration errors\n * before generating QR codes or sending requests to users.\n *\n * @param request - ProofRequest object to validate\n *\n * @returns Validation result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const validation = sdk.validateRequest(request);\n *\n * if (!validation.valid) {\n * console.error('Invalid request:', validation.error);\n * }\n * ```\n */\n private validateRequest(request: ProofRequest): { valid: boolean; error?: string } {\n return validateProofRequest(request);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport deep link.\n *\n * Validates whether the given URL uses the ZKProofport deep link scheme\n * (zkproofport:// by default) and has the correct format for a proof request.\n *\n * @param url - URL string to check\n *\n * @returns True if the URL is a valid ZKProofport deep link\n *\n * @example\n * ```typescript\n * const url = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation';\n * if (sdk.isProofportDeepLink(url)) {\n * const request = sdk.parseDeepLink(url);\n * console.log('Parsed request:', request);\n * }\n * ```\n */\n private isProofportDeepLink(url: string): boolean {\n return isProofportDeepLink(url, this.config.scheme);\n }\n\n /**\n * @internal\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a zkproofport:// deep link URL.\n * Useful for handling deep link navigation in web applications or validating\n * deep link URLs before displaying QR codes.\n *\n * @param url - ZKProofport deep link URL string\n *\n * @returns ProofRequest object with all request details, or null if invalid\n *\n * @example\n * ```typescript\n * const deepLink = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...';\n * const request = sdk.parseDeepLink(deepLink);\n *\n * if (request) {\n * console.log('Request ID:', request.requestId);\n * console.log('Circuit:', request.circuit);\n * }\n * ```\n */\n private parseDeepLink(url: string): ProofRequest | null {\n return parseProofRequestUrl(url);\n }\n\n // ============ Static Factory ============\n\n /**\n * Creates a new ProofportSDK instance with environment preset or custom config.\n * Defaults to `'production'` if no argument is provided.\n *\n * **Recommended usage** — use the default production relay:\n * ```typescript\n * const sdk = ProofportSDK.create();\n * ```\n *\n * Environment presets:\n * - `'production'` — relay.zkproofport.app (default)\n * - `'staging'` — stg-relay.zkproofport.app\n * - `'local'` — localhost:4001\n *\n * @param envOrConfig - Environment name or custom SDK configuration\n *\n * @returns New ProofportSDK instance\n *\n * @example\n * ```typescript\n * // Environment preset (recommended)\n * const sdk = ProofportSDK.create(); // production (default)\n * const sdk = ProofportSDK.create('staging');\n *\n * // Custom config\n * const sdk = ProofportSDK.create({\n * relayUrl: 'https://my-custom-relay.example.com',\n * });\n * ```\n */\n static create(envOrConfig?: SDKEnvironment | ProofportConfig): ProofportSDK {\n if (typeof envOrConfig === 'undefined') {\n return new ProofportSDK({ relayUrl: RELAY_URLS.production });\n }\n if (typeof envOrConfig === 'string') {\n const relayUrl = RELAY_URLS[envOrConfig];\n if (!relayUrl) {\n throw new Error(`Unknown environment: ${envOrConfig}. Use 'production', 'staging', or 'local'.`);\n }\n return new ProofportSDK({ relayUrl });\n }\n return new ProofportSDK(envOrConfig);\n }\n\n /**\n * Detects if the code is running on a mobile device.\n *\n * Uses user agent detection to determine if the current environment is a mobile\n * browser. This helps the SDK automatically choose between direct deep link\n * navigation (mobile) and QR code display (desktop).\n *\n * @returns True if running on a mobile device (iOS, Android, etc.)\n *\n * @example\n * ```typescript\n * if (ProofportSDK.isMobile()) {\n * // Open deep link directly\n * sdk.openProofRequest(request);\n * } else {\n * // Show QR code\n * const qr = await sdk.generateQRCode(request);\n * displayQRCode(qr);\n * }\n * ```\n */\n static isMobile(): boolean {\n if (typeof navigator === 'undefined') return false;\n return /Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n }\n\n // ============ Relay Integration ============\n\n /**\n * Sets the wallet signer for challenge-signature authentication.\n * The signer will be used to sign challenges from the relay server.\n *\n * @param signer - Wallet signer (ethers v6 Signer or compatible object with signMessage/getAddress)\n *\n * @example\n * ```typescript\n * import { BrowserProvider } from 'ethers';\n *\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n * ```\n */\n setSigner(signer: WalletSigner): void {\n this.signer = signer;\n }\n\n /**\n * Fetches a random challenge from the relay server.\n * The challenge must be signed and included in proof requests.\n *\n * @returns Promise resolving to ChallengeResponse with challenge hex and expiry\n * @throws Error if relayUrl is not configured\n */\n async getChallenge(): Promise<ChallengeResponse> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/challenge`);\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Failed to get challenge: HTTP ${response.status}`);\n }\n\n return await response.json() as ChallengeResponse;\n }\n\n /**\n * Creates a proof request through the relay server.\n *\n * This is the recommended way to create proof requests. The relay server:\n * - Issues a server-side requestId (validated by the mobile app)\n * - Tracks request status in Redis\n * - Builds the deep link with relay callback URL\n * - Stores inputs hash for deep link integrity verification\n *\n * @param circuit - Circuit type identifier\n * @param inputs - Circuit-specific inputs\n * @param options - Request options (message, dappName, dappIcon, nonce, returnScheme)\n * @param options.returnScheme - Which app the ZKProofport app should switch back\n * to once it has finished. Put **your own** deep link scheme here — the bare\n * scheme your app registers, e.g. `'mydapp://'`. Only a native app has an\n * answer to this question; a web app omits the option entirely, because\n * opening its https origin would launch a new browser tab on a fresh page\n * rather than return the user to the tab they started from.\n *\n * This is intentionally **not** a URL and not a return address: no path, query\n * string or fragment is accepted, and the ZKProofport app never sends the proof\n * there. The proof still comes back to you the same way it always did — over the\n * relay, via `waitForProof()` / `waitForResult()`. `returnScheme` only answers\n * \"which app should come back to the foreground\", exactly like the\n * `redirect.native` value a wallet uses to hand control back after signing.\n *\n * **Omit it and the SDK decides for you.** When the request is created from a\n * page running in Chrome for iOS (`CriOS`) or Firefox for iOS (`FxiOS`), the\n * SDK fills in `'googlechrome://'` or `'firefox://'` by itself: opening either\n * scheme bare brings that browser forward without navigating, so the user lands\n * back on the tab they were already reading. Every other browser sends nothing,\n * because nothing safe exists to send — Safari has no such scheme, and Brave\n * and Arc are indistinguishable from Safari on iOS, so guessing would eject the\n * user into the wrong browser.\n * On Android nothing is needed at all: the ZKProofport app brings itself to the\n * back and the browser resumes exactly as it was. When no target is sent and\n * none can be inferred, the ZKProofport app tells the user the proof was\n * delivered and lets them switch back themselves.\n *\n * There is no auto-switch on proof failure; only on success and on the user\n * declining the request.\n *\n * Rejected with an error before the request is sent: empty or whitespace values,\n * anything longer than 128 characters, values carrying a host/path/query/fragment\n * (including https origins such as `'https://myapp.com'`), and the `http:`,\n * `file:`, `data:`, `javascript:`, `intent:`, `tel:`, `sms:`, `mailto:` families.\n * @returns Promise resolving to RelayProofRequest with requestId, deepLink, pollUrl\n * @throws Error if signer not set, returnScheme is malformed, or the relay request fails\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create();\n * sdk.setSigner(signer);\n *\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * }, { dappName: 'My DApp', returnScheme: 'mydapp://' });\n *\n * // Generate QR code from relay deep link\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof (WebSocket primary, polling fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * ```\n */\n // Which circuits need a wallet signature, from the one record in\n // src/circuits.ts. The typed-out pair that used to sit here had missed\n // arc_eligibility, so a dapp calling createRelayRequest() for it with no\n // signer got no local error and a relay 401 two round trips later.\n private static needsWalletSignature(circuit: CircuitType): boolean {\n return CIRCUIT_NEEDS_WALLET_SIGNATURE[circuit as CircuitId] === true;\n }\n\n async createRelayRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n nonce?: string;\n returnScheme?: string;\n } = {}\n ): Promise<RelayProofRequest> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const needsSignature = ProofportSDK.needsWalletSignature(circuit);\n\n if (needsSignature && !this.signer) {\n throw new Error('Signer not set. Call setSigner() first. Wallet signature is required for this circuit.');\n }\n\n // mDL circuits: validate predicate inputs client-side before hitting the\n // relay, so a bad ageThreshold / targetRegion fails fast with a clear error.\n if (circuit === 'mdl_kr_ownership' || circuit === 'mdl_kr_age' || circuit === 'mdl_kr_region') {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n }\n\n // arc_eligibility: the action is what the proof binds to, so a request\n // without a usable one cannot be honoured. Checked here, before a\n // challenge is burned, because the alternative is a refusal from inside\n // the mobile app -- a screen the dapp developer never sees, reached after\n // the person has already scanned a QR code.\n if (circuit === 'arc_eligibility') {\n const actionError = validateTypedAction((inputs as { action?: unknown }).action);\n if (actionError) {\n throw new Error(`${actionError} (circuit: ${circuit})`);\n }\n }\n\n // Return target: validated before we burn a challenge, so a typo surfaces\n // as a local error instead of a relay 400 on the second round trip.\n if (options.returnScheme !== undefined) {\n const returnSchemeError = validateReturnScheme(options.returnScheme);\n if (returnSchemeError) {\n throw new Error(returnSchemeError);\n }\n }\n\n // Get challenge + requestId from relay\n const { requestId, challenge } = await this.getChallenge();\n\n const body: Record<string, unknown> = {\n requestId,\n circuitId: circuit,\n inputs,\n challenge,\n };\n\n // Sign challenge for circuits that require wallet signature\n if (needsSignature && this.signer) {\n body.signature = await this.signer.signMessage(challenge);\n }\n\n if (options.message) body.message = options.message;\n if (options.dappName) body.dappName = options.dappName;\n if (options.dappIcon) body.dappIcon = options.dappIcon;\n if (options.nonce) body.nonce = options.nonce;\n // An explicit value always wins. Otherwise ask the SDK to work one out from\n // the page's own user agent — the requesting page is the only side that can\n // (iOS tells the app nothing about who launched it). Both paths can end in\n // \"send nothing\", which is a legitimate outcome, not a failure.\n const returnScheme = options.returnScheme ?? detectReturnScheme();\n if (returnScheme) body.returnScheme = returnScheme;\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/request`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Relay request failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofRequest;\n }\n\n /**\n * Polls the relay for proof result status.\n *\n * @param requestId - The relay-issued request ID\n * @returns Promise resolving to RelayProofResult\n * @throws Error if relay URL not configured or request not found\n *\n * @example\n * ```typescript\n * const result = await sdk.pollResult(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof:', result.proof);\n * console.log('Public inputs:', result.publicInputs);\n * }\n * ```\n */\n async pollResult(requestId: string): Promise<RelayProofResult> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/${requestId}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new Error('Request not found or expired');\n }\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Poll failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofResult;\n }\n\n /**\n * Polls the relay until proof is completed or failed, with configurable interval and timeout.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Polling options\n * @param options.intervalMs - Polling interval in milliseconds (default: 2000)\n * @param options.timeoutMs - Maximum polling time in milliseconds (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback when status changes\n * @returns Promise resolving to final RelayProofResult\n * @throws Error if timeout or relay error\n */\n async waitForResult(\n requestId: string,\n options: {\n intervalMs?: number;\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const interval = options.intervalMs || 2000;\n const timeout = options.timeoutMs || 300000;\n const startTime = Date.now();\n let lastStatus = '';\n\n while (Date.now() - startTime < timeout) {\n const result = await this.pollResult(requestId);\n\n if (result.status !== lastStatus) {\n lastStatus = result.status;\n options.onStatusChange?.(result);\n }\n\n if (result.status === 'completed' || result.status === 'failed') {\n return result;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Polling timed out after ${timeout}ms`);\n }\n\n /**\n * Subscribes to real-time proof status updates via Socket.IO.\n *\n * This is the recommended way to receive proof results. Uses WebSocket\n * connection for instant delivery instead of polling.\n *\n * Requires `socket.io-client` package: `npm install socket.io-client`\n *\n * @param requestId - The relay-issued request ID to subscribe to\n * @param callbacks - Event callbacks for status changes and results\n * @param callbacks.onStatus - Called on status updates (pending, generating)\n * @param callbacks.onResult - Called when proof is completed or failed\n * @param callbacks.onError - Called on errors\n * @returns Unsubscribe function to clean up the connection\n * @throws Error if relayUrl not set or socket.io-client not installed\n *\n * @example\n * ```typescript\n * const relay = await sdk.createRelayRequest('coinbase_attestation', { scope: 'myapp.com' });\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * const unsubscribe = await sdk.subscribe(relay.requestId, {\n * onResult: (result) => {\n * if (result.status === 'completed') {\n * console.log('Proof received!', result.proof);\n * }\n * },\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\n async subscribe(\n requestId: string,\n callbacks: {\n onStatus?: (data: { requestId: string; status: string; deepLink?: string }) => void;\n onResult?: (result: RelayProofResult) => void;\n onError?: (error: { error: string; code?: number; requestId?: string }) => void;\n }\n ): Promise<() => void> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n let ioConnect: any;\n try {\n const mod: any = await import('socket.io-client');\n ioConnect = mod.io ?? mod.connect ?? mod.default;\n } catch {\n throw new Error(\n 'socket.io-client is required for real-time updates. Install it: npm install socket.io-client'\n );\n }\n\n if (typeof ioConnect !== 'function') {\n throw new Error('Failed to load socket.io-client: io function not found');\n }\n\n // Connect to relay /proof namespace (no JWT — open connections)\n const socket = ioConnect(`${this.relayUrl}/proof`, {\n path: '/socket.io',\n transports: ['websocket', 'polling'],\n });\n\n this.socket = socket;\n\n // Subscribe to the request room\n socket.on('connect', () => {\n socket.emit('proof:subscribe', { requestId });\n });\n\n // Handle connection errors (e.g. rejected by relay middleware)\n socket.on('connect_error', (err: Error) => {\n console.error(`[ProofportSDK] Socket.IO connect_error for requestId=${requestId}: ${err.message}`);\n callbacks.onError?.({ error: err.message, requestId });\n });\n\n // Listen for events\n if (callbacks.onStatus) {\n socket.on('proof:status', callbacks.onStatus);\n }\n if (callbacks.onResult) {\n socket.on('proof:result', callbacks.onResult);\n }\n if (callbacks.onError) {\n socket.on('proof:error', callbacks.onError);\n }\n\n // Return unsubscribe function\n return () => {\n socket.off('proof:status');\n socket.off('proof:result');\n socket.off('proof:error');\n socket.disconnect();\n if (this.socket === socket) {\n this.socket = null;\n }\n };\n }\n\n /**\n * Waits for a proof result using Socket.IO (primary) with polling fallback.\n *\n * Tries Socket.IO first for real-time delivery. If socket.io-client is not\n * installed or connection fails, automatically falls back to HTTP polling.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Configuration options\n * @param options.timeoutMs - Maximum wait time in ms (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback for status updates\n * @returns Promise resolving to final RelayProofResult\n */\n async waitForProof(\n requestId: string,\n options: {\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult | { requestId: string; status: string; deepLink?: string }) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const timeout = options.timeoutMs || 300000;\n\n // Try Socket.IO first\n if (this.relayUrl) {\n try {\n return await new Promise<RelayProofResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n unsubscribePromise?.then(fn => fn());\n reject(new Error(`Waiting for proof timed out after ${timeout}ms`));\n }, timeout);\n\n const unsubscribePromise = this.subscribe(requestId, {\n onStatus: (data) => {\n options.onStatusChange?.(data);\n },\n onResult: (result) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n resolve(result);\n },\n onError: (error) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n reject(new Error(error.error));\n },\n });\n });\n } catch (err: any) {\n // Re-throw timeout — that's a real failure the caller should handle\n if (err.message?.includes('timed out')) {\n throw err;\n }\n // socket.io-client missing or connection failed → fall back to polling silently\n console.warn('Socket.IO unavailable, falling back to HTTP polling:', err.message);\n }\n }\n\n // Fallback: HTTP polling\n return this.waitForResult(requestId, {\n timeoutMs: timeout,\n onStatusChange: options.onStatusChange as any,\n });\n }\n\n /**\n * Disconnects the Socket.IO connection if active.\n */\n disconnect(): void {\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n // ============ Public Input Utilities ============\n\n /**\n * Extracts the scope from proof public inputs.\n *\n * The scope is an application-specific identifier (e.g., domain name) encoded\n * as bytes32 in the proof's public inputs.\n *\n * @param publicInputs - Array of public input hex strings from proof response\n * @param circuit - Circuit type to determine field positions\n * @returns Scope as hex string (0x...), or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const scope = sdk.extractScope(result.publicInputs, result.circuit);\n * console.log('Scope:', scope);\n * }\n * ```\n */\n extractScope(publicInputs: string[], circuit: CircuitType): string | null {\n return extractScopeFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the nullifier (bytes32) from proof public inputs.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const nullifier = sdk.extractNullifier(result.publicInputs, result.circuit);\n * console.log('Nullifier:', nullifier); // '0xabc123...'\n * }\n * ```\n */\n extractNullifier(publicInputs: string[], circuit: CircuitType): string | null {\n return extractNullifierFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the domain string from OIDC Domain Attestation proof public inputs.\n *\n * Only works with 'oidc_domain_attestation' circuit. Returns null for other circuits.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Domain as ASCII string (e.g., 'example.com'), or null if not applicable\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const domain = sdk.extractDomain(result.publicInputs, result.circuit);\n * console.log('Domain:', domain); // 'example.com'\n * }\n * ```\n */\n extractDomain(publicInputs: string[], circuit: CircuitType): string | null {\n return extractDomainFromPublicInputs(publicInputs, circuit);\n }\n\n}\n\nexport default ProofportSDK;\n"],"names":["ethers"],"mappings":";;;;;;;AAAA;;AAEG;AAIH;;;;;;;;;AASG;AACI,MAAM,UAAU,GAAmC;AACxD,IAAA,UAAU,EAAE,+BAA+B;AAC3C,IAAA,OAAO,EAAE,mCAAmC;AAC5C,IAAA,KAAK,EAAE,uBAAuB;CAC/B;AAED;;;;;;;;;AASG;AACI,MAAM,cAAc,GAAG,aAAa;AAE3C;;;;;;;;;AASG;AACI,MAAM,eAAe,GAAG;;AAE7B,IAAA,aAAa,EAAE,gBAGP;AAEV;;;;;;;;;;;AAWG;AACI,MAAM,gBAAgB,GAKxB;AACH,IAAA,oBAAoB,EAAE;AACpB,QAAA,IAAI,EAAE,cAAc;AACpB,QAAA,WAAW,EAAE,sCAAsC;;;;;AAKnD,QAAA,iBAAiB,EAAE,GAAG;AACtB,QAAA,gBAAgB,EAAE,CAAC,aAAa,EAAE,yBAAyB,CAAC;AAC7D,KAAA;AACD,IAAA,4BAA4B,EAAE;AAC5B,QAAA,IAAI,EAAE,kBAAkB;AACxB,QAAA,WAAW,EAAE,qCAAqC;;;AAGlD,QAAA,iBAAiB,EAAE,GAAG;QACtB,gBAAgB,EAAE,CAAC,aAAa,EAAE,yBAAyB,EAAE,cAAc,EAAE,qBAAqB,EAAE,aAAa,C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ts","../src/typedAction.ts","../src/deeplink.ts","../src/qrcode.ts","../src/verifier.ts","../src/offChainVerifier.ts","../src/ProofportSDK.ts"],"sourcesContent":["/**\n * ZKProofport SDK Constants\n */\n\nimport type { CircuitType, SDKEnvironment } from './types';\n\n/**\n * Pre-configured relay server URLs for each environment.\n * Used by `ProofportSDK.create('production')` for zero-config initialization.\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * // Uses RELAY_URLS.production = 'https://relay.zkproofport.app'\n * ```\n */\nexport const RELAY_URLS: Record<SDKEnvironment, string> = {\n production: 'https://relay.zkproofport.app',\n staging: 'https://stg-relay.zkproofport.app',\n local: 'http://localhost:4001',\n};\n\n/**\n * Default deep link URL scheme for ZKProofport mobile app.\n * Used to construct deep link URLs that open the mobile app.\n *\n * @example\n * ```typescript\n * const deepLink = `${DEFAULT_SCHEME}://proof-request?...`;\n * // Results in: zkproofport://proof-request?...\n * ```\n */\nexport const DEFAULT_SCHEME = 'zkproofport';\n\n/**\n * Deep link URL hosts for different proof request flows.\n * Used as the host component in deep link URLs.\n *\n * @example\n * ```typescript\n * const requestUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_REQUEST}`;\n * const responseUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_RESPONSE}`;\n * ```\n */\nexport const DEEP_LINK_HOSTS = {\n /** Host for proof requests sent to mobile app */\n PROOF_REQUEST: 'proof-request',\n /** Host for proof responses returned from mobile app */\n PROOF_RESPONSE: 'proof-response',\n} as const;\n\n/**\n * Circuit metadata containing display names, descriptions, and public input specifications.\n * Each circuit has a defined number and layout of public inputs that must match\n * the Noir circuit definition.\n *\n * @example\n * ```typescript\n * const metadata = CIRCUIT_METADATA['coinbase_attestation'];\n * console.log(metadata.name); // \"Coinbase KYC\"\n * console.log(metadata.publicInputsCount); // 128\n * ```\n */\nexport const CIRCUIT_METADATA: Record<CircuitType, {\n name: string;\n description: string;\n publicInputsCount: number;\n publicInputNames: string[];\n}> = {\n coinbase_attestation: {\n name: 'Coinbase KYC',\n description: 'Prove Coinbase identity verification',\n // 4 x `pub [u8; 32]` in coinbase-attestation/src/main.nr, flattened to\n // bytes: signal_hash, signer_list_merkle_root, scope, nullifier.\n // Read 2 here until 2026-09-04, which was wrong under any reading —\n // the circuit has never had two public inputs, logical or flattened.\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root'],\n },\n coinbase_country_attestation: {\n name: 'Coinbase Country',\n description: 'Prove Coinbase country verification',\n // 32 + 32 + (10 x 2) + 1 + 1 + 32 + 32 = 150, counted off\n // coinbase-country-attestation/src/main.nr. Read 14 until 2026-09-04.\n publicInputsCount: 150,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'country_list', 'country_list_length', 'is_included'],\n },\n oidc_domain_attestation: {\n name: 'OIDC Domain',\n description: 'Prove email domain affiliation via OIDC JWT',\n publicInputsCount: 148,\n publicInputNames: ['pubkey_modulus_limbs', 'domain', 'scope', 'nullifier', 'provider'],\n },\n arc_eligibility: {\n name: 'Arc Eligibility',\n description: 'Prove eligibility and authorize one EIP-712 action, for an Arc gate',\n // 6 x `pub [u8; 32]` in arc-eligibility/src/main.nr, flattened to bytes.\n // Read off the compiled ABI rather than counted: signal_hash 0-31,\n // domain_separator 32-63, action_hash 64-95, signer_list_merkle_root\n // 96-127, scope 128-159, nullifier 160-191.\n publicInputsCount: 192,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'signer_list_merkle_root'],\n },\n // Planned circuit — the identifier is reserved and the circuit exists, but it\n // is not officially supported yet. See CIRCUIT_SUPPORT_STATUS in ./circuits.\n // Forked from coinbase_attestation and shares its four public inputs, so the\n // count is the byte-flattened total (4 x [u8; 32] = 128), matching the\n // COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT indices below. The\n // coinbase_attestation entry above reports a legacy logical count of 2 and is\n // left as-is for backwards compatibility.\n giwa_attestation: {\n name: 'GIWA Attestation',\n description: 'Prove GIWA identity verification (planned — not officially supported yet)',\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'scope', 'nullifier'],\n },\n // Korea Mobile ID (mDL) circuits. Planned — not officially supported yet.\n // Counts are byte-flattened field totals from the compiled circuit ABIs:\n // [u8; 32] arrays contribute 32 inputs each.\n mdl_kr_ownership: {\n name: 'Korea Mobile ID — Ownership',\n description: \"Prove valid Korean mobile driver's license ownership with selective disclosure\",\n publicInputsCount: 97,\n publicInputNames: ['scope', 'nullifier_value', 'disclose_flags', 'owner_commit'],\n },\n mdl_kr_age: {\n name: 'Korea Mobile ID — Age',\n description: \"Prove minimum age from Korean mobile driver's license without revealing birth date\",\n publicInputsCount: 66,\n publicInputNames: ['scope', 'nullifier_value', 'age_threshold', 'current_year'],\n },\n mdl_kr_region: {\n name: 'Korea Mobile ID — Region',\n description: \"Prove si/do residency from Korean mobile driver's license without revealing address\",\n publicInputsCount: 96,\n publicInputNames: ['scope', 'nullifier_value', 'region_code'],\n },\n};\n\n/**\n * Standard verifier contract ABI shared across all Barretenberg-generated verifiers.\n * This ABI defines the interface for calling the verify function on deployed verifier contracts.\n *\n * Uses ethers v6 human-readable ABI format.\n *\n * @example\n * ```typescript\n * import { Contract } from 'ethers';\n *\n * const verifier = new Contract(verifierAddress, VERIFIER_ABI, provider);\n * const isValid = await verifier.verify(proofBytes, publicInputs);\n * ```\n */\nexport const VERIFIER_ABI = [\n 'function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool)',\n];\n\n/**\n * Public RPC endpoint URLs for supported blockchain networks.\n * Used as fallback when no custom provider is supplied.\n *\n * Supported networks:\n * - 84532: Base Sepolia (testnet)\n * - 8453: Base Mainnet (production)\n * - 91342: GIWA Sepolia (testnet) — where the GIWA account circuit verifies\n *\n * A chain missing from this map is not a quiet degradation: `getDefaultProvider`\n * throws \"No RPC endpoint configured for chain N\". That is what a caller saw\n * when verifying a GIWA proof on chain 91342 — the verifier contract had been\n * deployed and the proof was valid, but the SDK had no way to reach the chain\n * to ask. Deploying a verifier to a new network means adding it here too.\n *\n * @example\n * ```typescript\n * import { JsonRpcProvider } from 'ethers';\n *\n * const provider = new JsonRpcProvider(RPC_ENDPOINTS[84532]);\n * ```\n */\nexport const RPC_ENDPOINTS: Record<number, string> = {\n 84532: 'https://sepolia.base.org', // Base Sepolia\n 8453: 'https://mainnet.base.org', // Base Mainnet\n 91342: 'https://sepolia-rpc.giwa.io', // GIWA Sepolia\n // Arc Testnet. The arc_eligibility verifier is deployed here and nowhere\n // else, and this line was missing on 2026-09-12 — the circuit shipped, a\n // phone produced a valid proof, and on-chain verification answered \"No RPC\n // endpoint configured for chain 5042002\", which reads like the proof's fault.\n 5042002: 'https://rpc.testnet.arc.io', // Arc Testnet\n};\n\n/**\n * Default proof request expiration time in milliseconds.\n * Requests older than this are considered expired and should not be processed.\n *\n * Default: 10 minutes (600,000 ms)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * // ...\n * createdAt: Date.now(),\n * expiresAt: Date.now() + DEFAULT_REQUEST_EXPIRY_MS\n * };\n * ```\n */\nexport const DEFAULT_REQUEST_EXPIRY_MS = 10 * 60 * 1000;\n\n/**\n * Maximum data size (in bytes) that can be encoded in a QR code.\n * Based on QR Code Version 40 with L (Low) error correction level.\n *\n * Requests exceeding this size should use alternative methods (HTTP, WebSocket).\n *\n * @example\n * ```typescript\n * const deepLinkUrl = generateDeepLink(request);\n * if (deepLinkUrl.length > MAX_QR_DATA_SIZE) {\n * console.warn('Request too large for QR code');\n * }\n * ```\n */\nexport const MAX_QR_DATA_SIZE = 2953; // Version 40 with L error correction\n\n/**\n * Coinbase Attestation circuit public input layout (byte offsets).\n * Defines the byte positions of each field in the flattened public inputs array.\n *\n * Public inputs are packed as bytes32 values:\n * - signal_hash: bytes 0-31\n * - merkle_root: bytes 32-63\n * - scope: bytes 64-95\n *\n * @example\n * ```typescript\n * const publicInputs = response.publicInputs;\n * const signalHash = publicInputs.slice(\n * COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT.SIGNAL_HASH_START,\n * COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT.SIGNAL_HASH_END + 1\n * );\n * ```\n */\nexport const COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT = {\n SIGNAL_HASH_START: 0,\n SIGNAL_HASH_END: 31,\n MERKLE_ROOT_START: 32,\n MERKLE_ROOT_END: 63,\n SCOPE_START: 64,\n SCOPE_END: 95,\n NULLIFIER_START: 96,\n NULLIFIER_END: 127,\n} as const;\n\n/**\n * Coinbase Country Attestation circuit public input layout (byte offsets).\n * Defines the byte positions of each field in the flattened public inputs array.\n *\n * Public inputs are packed as bytes32 values:\n * - signal_hash: bytes 0-31\n * - merkle_root: bytes 32-63\n * - country_list: bytes 64-83 (20 bytes for 10 countries)\n * - country_list_length: byte 84\n * - is_included: byte 85\n * - scope: bytes 86-117\n *\n * @example\n * ```typescript\n * const publicInputs = response.publicInputs;\n * const countryList = publicInputs.slice(\n * COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT.COUNTRY_LIST_START,\n * COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT.COUNTRY_LIST_END + 1\n * );\n * ```\n */\nexport const COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT = {\n SIGNAL_HASH_START: 0,\n SIGNAL_HASH_END: 31,\n MERKLE_ROOT_START: 32,\n MERKLE_ROOT_END: 63,\n COUNTRY_LIST_START: 64,\n COUNTRY_LIST_END: 83,\n COUNTRY_LIST_LENGTH: 84,\n IS_INCLUDED: 85,\n SCOPE_START: 86,\n SCOPE_END: 117,\n NULLIFIER_START: 118,\n NULLIFIER_END: 149,\n} as const;\n\n/**\n * Korea Mobile ID (mDL) circuit public input layout (field offsets).\n * All three mDL circuits share the same prefix: scope [0..31] and\n * nullifier_value [32..63], each stored one byte per field element.\n * The suffix differs per predicate circuit:\n * - mdl_kr_ownership (97 inputs): disclose_flags [64], owner_commit [65..96]\n * - mdl_kr_age (66 inputs): age_threshold [64], current_year [65]\n * - mdl_kr_region (96 inputs): region_code [64..95]\n *\n * @example\n * ```typescript\n * const nullifier = publicInputs.slice(\n * MDL_KR_PUBLIC_INPUT_LAYOUT.NULLIFIER_START,\n * MDL_KR_PUBLIC_INPUT_LAYOUT.NULLIFIER_END + 1\n * );\n * ```\n */\nexport const MDL_KR_PUBLIC_INPUT_LAYOUT = {\n SCOPE_START: 0,\n SCOPE_END: 31,\n NULLIFIER_START: 32,\n NULLIFIER_END: 63,\n OWNERSHIP_DISCLOSE_FLAGS: 64,\n OWNERSHIP_OWNER_COMMIT_START: 65,\n OWNERSHIP_OWNER_COMMIT_END: 96,\n AGE_THRESHOLD: 64,\n AGE_CURRENT_YEAR: 65,\n REGION_CODE_START: 64,\n REGION_CODE_END: 95,\n} as const;\n\n/**\n * OIDC Domain Attestation circuit public input layout (field offsets).\n * Defines the field positions in the flattened public inputs array (148 fields total).\n *\n * Circuit public inputs (from main.nr):\n * - pubkey_modulus_limbs: pub [u128; 18] → 18 fields (0–17)\n * - domain: pub BoundedVec<u8, 64> → 1 len + 64 storage = 65 fields (18–82)\n * - scope: pub [u8; 32] → 32 fields (83–114)\n * - nullifier: pub [u8; 32] → 32 fields (115–146)\n * - provider: pub u8 → 1 field (147)\n *\n * @example\n * ```typescript\n * const scope = publicInputs.slice(\n * OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT.SCOPE_START,\n * OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT.SCOPE_END + 1\n * );\n * ```\n */\nexport const OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT = {\n PUBKEY_MODULUS_START: 0,\n PUBKEY_MODULUS_END: 17,\n DOMAIN_STORAGE_START: 18,\n DOMAIN_STORAGE_END: 81,\n DOMAIN_LEN: 82,\n SCOPE_START: 83,\n SCOPE_END: 114,\n NULLIFIER_START: 115,\n NULLIFIER_END: 146,\n PROVIDER: 147,\n /** @deprecated Use DOMAIN_STORAGE_START */\n DOMAIN_START: 18,\n /** @deprecated Use DOMAIN_LEN */\n DOMAIN_END: 82,\n} as const;\n","/**\n * Canonical ZKProofport circuit identifiers.\n *\n * This module is the single source of truth for circuit IDs. Every other layer\n * — the mobile app, the demo, the relay, server-side provers — reads its list\n * from here instead of keeping a private copy that silently drifts.\n *\n * It has **no imports and no dependencies**, so it can be pulled in on its own:\n *\n * ```typescript\n * import { CIRCUIT_IDS, isCircuitId } from '@zkproofport-app/sdk/circuits';\n * ```\n *\n * The same names are also re-exported from the package root\n * (`@zkproofport-app/sdk`) for callers that already import the SDK.\n *\n * ## Identifiers are canonical and case-sensitive\n *\n * Each ID is the circuit's `name` in its `Nargo.toml`, verbatim. The format is\n * lowercase with underscores. Hyphenated spellings (`coinbase-kyc`,\n * `mdl-kr-age`) are directory or UI route names in other repositories — they\n * are **not** circuit IDs, and passing one produces a nullifier mismatch or a\n * failed on-chain lookup rather than a clear error.\n */\n\n/**\n * Whether a circuit is officially supported today or still on the roadmap.\n *\n * - `supported` — generally available. Safe to build a product on.\n * - `planned` — the identifier is reserved and the circuit exists, but it is\n * not officially supported yet. Availability, inputs and public-input layout\n * may change without a major version bump.\n */\nexport type CircuitSupportStatus = 'supported' | 'experimental' | 'planned';\n\n/**\n * Canonical circuit identifiers, keyed by a stable constant name.\n *\n * Prefer these constants over string literals so a rename is a compile error\n * rather than a runtime surprise.\n *\n * @example\n * ```typescript\n * import { CIRCUIT_IDS } from '@zkproofport-app/sdk/circuits';\n *\n * const relay = await sdk.createRelayRequest(CIRCUIT_IDS.COINBASE_ATTESTATION, {\n * scope: 'myapp.com',\n * });\n * ```\n */\nexport const CIRCUIT_IDS = Object.freeze({\n /** Coinbase KYC attestation. Officially supported. */\n COINBASE_ATTESTATION: 'coinbase_attestation',\n /** Coinbase country attestation (inclusion / exclusion). Officially supported. */\n COINBASE_COUNTRY_ATTESTATION: 'coinbase_country_attestation',\n /** OIDC email-domain attestation. Officially supported. */\n OIDC_DOMAIN_ATTESTATION: 'oidc_domain_attestation',\n /** Arc eligibility: one EIP-712 action, authorized. Officially supported. */\n ARC_ELIGIBILITY: 'arc_eligibility',\n /** GIWA attestation. Planned — not officially supported yet. */\n GIWA_ATTESTATION: 'giwa_attestation',\n /** Korea Mobile ID ownership. Planned — not officially supported yet. */\n MDL_KR_OWNERSHIP: 'mdl_kr_ownership',\n /** Korea Mobile ID age threshold. Planned — not officially supported yet. */\n MDL_KR_AGE: 'mdl_kr_age',\n /** Korea Mobile ID si/do region. Planned — not officially supported yet. */\n MDL_KR_REGION: 'mdl_kr_region',\n} as const);\n\n/**\n * Union of every canonical circuit identifier.\n *\n * `CircuitType` (exported from the package root) is an alias of this type — the\n * two names refer to the same union, and this module is where it is defined.\n */\nexport type CircuitId = (typeof CIRCUIT_IDS)[keyof typeof CIRCUIT_IDS];\n\n/**\n * Support status for every circuit.\n *\n * The record is exhaustive over {@link CircuitId}: adding an identifier without\n * giving it a status is a compile error, so this list cannot drift from\n * {@link CIRCUIT_IDS}.\n *\n * @example\n * ```typescript\n * import { CIRCUIT_SUPPORT_STATUS } from '@zkproofport-app/sdk/circuits';\n *\n * CIRCUIT_SUPPORT_STATUS.coinbase_attestation; // 'supported'\n * CIRCUIT_SUPPORT_STATUS.mdl_kr_age; // 'planned'\n * ```\n */\nexport const CIRCUIT_SUPPORT_STATUS: Readonly<Record<CircuitId, CircuitSupportStatus>> =\n Object.freeze({\n coinbase_attestation: 'supported',\n coinbase_country_attestation: 'supported',\n oidc_domain_attestation: 'supported',\n arc_eligibility: 'experimental',\n giwa_attestation: 'planned',\n mdl_kr_ownership: 'planned',\n mdl_kr_age: 'planned',\n mdl_kr_region: 'planned',\n } as const);\n\n/**\n * Where each circuit's verification key FILE lives inside the\n * `zkproofport/circuits` repository, relative to its root.\n *\n * Off-chain verification needs the verification key and nothing else — no\n * circuit bytecode, no witness. The key is public by nature: it is what anyone\n * checking a proof must already have, and the Solidity verifiers deployed\n * on-chain embed the same key.\n *\n * NOTE THE TRAILING `/vk` TWICE. In that repository `target/vk` is a DIRECTORY\n * holding `vk`, `vk_hash` and `SHA256SUMS`; the key itself is `target/vk/vk`.\n * These paths were first copied here from the mobile app, which keeps the\n * directory and the filename as two fields and joins them — so taking only the\n * directory produced a URL that answers 404, and the first browser to try\n * off-chain verification said \"Could not fetch the verification key (HTTP 404)\".\n *\n * Exhaustive over {@link CircuitId} on purpose. A new circuit whose key path is\n * not listed here fails to compile rather than failing at verification time,\n * where the only symptom would be a proof that cannot be checked.\n */\nexport const CIRCUIT_VK_PATHS: Readonly<Record<CircuitId, string>> = Object.freeze({\n coinbase_attestation: 'coinbase-attestation/target/vk/vk',\n coinbase_country_attestation: 'coinbase-country-attestation/target/vk/vk',\n oidc_domain_attestation: 'oidc-domain-attestation/target/vk/vk',\n arc_eligibility: 'arc-eligibility/target/vk/vk',\n giwa_attestation: 'giwa-attestation/target/vk/vk',\n mdl_kr_ownership: 'mdl/kr-ownership/target/vk/vk',\n mdl_kr_age: 'mdl/kr-age/target/vk/vk',\n mdl_kr_region: 'mdl/kr-region/target/vk/vk',\n} as const);\n\n/**\n * Every canonical circuit identifier, in declaration order.\n *\n * Includes circuits that are still `planned`. Use {@link SUPPORTED_CIRCUIT_IDS}\n * when you only want the ones that are officially supported today.\n */\nexport const ALL_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n Object.values(CIRCUIT_IDS) as CircuitId[]\n);\n\n/**\n * Circuits that are officially supported today: the two Coinbase circuits and\n * OIDC domain attestation.\n *\n * Derived from {@link CIRCUIT_SUPPORT_STATUS}, so it cannot fall out of sync.\n */\nexport const SUPPORTED_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter((id) => CIRCUIT_SUPPORT_STATUS[id] === 'supported')\n);\n\n/**\n * Circuits whose identifiers are reserved but which are not officially\n * supported yet: GIWA attestation and the three Korea Mobile ID circuits.\n *\n * Derived from {@link CIRCUIT_SUPPORT_STATUS}, so it cannot fall out of sync.\n */\n/**\n * Circuits you can prove today, on a testnet, with everything subject to change.\n *\n * `arc_eligibility` is the reason this status exists. Calling it `planned`\n * would be wrong — the circuit compiles, the verifier is deployed and a proof\n * verifies against it — and calling it `supported` would be worse, because the\n * only deployment is Arc Testnet, Circle has not published a mainnet chain id,\n * and the public-input layout is still open. Neither existing word was true, so\n * the honest move was a third word rather than picking the closer lie.\n */\nexport const EXPERIMENTAL_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter(id => CIRCUIT_SUPPORT_STATUS[id] === 'experimental'),\n);\n\nexport const PLANNED_CIRCUIT_IDS: readonly CircuitId[] = Object.freeze(\n ALL_CIRCUIT_IDS.filter((id) => CIRCUIT_SUPPORT_STATUS[id] === 'planned')\n);\n\n/**\n * Narrows an unknown value to a canonical circuit identifier.\n *\n * Returns `false` for hyphenated route names such as `'coinbase-kyc'`, which\n * are not circuit IDs.\n *\n * @example\n * ```typescript\n * isCircuitId('coinbase_attestation'); // true\n * isCircuitId('coinbase-kyc'); // false\n * ```\n */\nexport function isCircuitId(value: unknown): value is CircuitId {\n return typeof value === 'string' && (ALL_CIRCUIT_IDS as readonly string[]).includes(value);\n}\n\n/**\n * Narrows an unknown value to a circuit identifier that is officially supported\n * today. Planned circuits return `false`.\n *\n * @example\n * ```typescript\n * isSupportedCircuitId('oidc_domain_attestation'); // true\n * isSupportedCircuitId('mdl_kr_age'); // false — planned\n * ```\n */\nexport function isSupportedCircuitId(value: unknown): value is CircuitId {\n return isCircuitId(value) && CIRCUIT_SUPPORT_STATUS[value] === 'supported';\n}\n\n/**\n * Returns the support status of a circuit.\n *\n * @param circuit - A canonical circuit identifier.\n * @throws Error when the value is not a canonical circuit identifier.\n *\n * @example\n * ```typescript\n * getCircuitSupportStatus('giwa_attestation'); // 'planned'\n * ```\n */\nexport function getCircuitSupportStatus(circuit: CircuitId): CircuitSupportStatus {\n if (!isCircuitId(circuit)) {\n throw new Error(\n `Unknown circuit '${String(circuit)}'. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`\n );\n }\n return CIRCUIT_SUPPORT_STATUS[circuit];\n}\n\n/**\n * Whether a circuit's relay request must carry a wallet signature.\n *\n * The SDK checks this to fail fast — \"Signer not set\" locally beats a 401 from\n * the relay two round trips later, with nothing saying which circuit needed\n * what. The relay declares its OWN copy on purpose and does not import this\n * one: it is a security boundary, and an auth policy that a published package\n * can change is not a policy. A test in the relay asserts the two agree.\n *\n * `satisfies` and not an annotation, so a circuit added above is a compile\n * error here until somebody decides which it is.\n */\nexport const CIRCUIT_NEEDS_WALLET_SIGNATURE = {\n coinbase_attestation: true,\n coinbase_country_attestation: true,\n // Same Coinbase-attested wallet as above; what changes is that it signs an\n // EIP-712 action rather than signal_hash.\n arc_eligibility: true,\n // The signature is inside the OIDC identity token, checked by the prover.\n oidc_domain_attestation: false,\n // Web2 (OmniOne CX) flows with no wallet binding at all.\n mdl_kr_ownership: false,\n mdl_kr_age: false,\n mdl_kr_region: false,\n giwa_attestation: false,\n} satisfies Record<CircuitId, boolean>;\n","/**\n * Checking the EIP-712 action an `arc_eligibility` proof binds to.\n *\n * Three places need this answer and they have to agree: a dapp building the\n * request, this SDK validating a deep link, and the mobile app before it asks\n * a wallet to sign. The check lived in the mobile app's demo screen and\n * nowhere else, so an action arriving from a dapp reached the prover\n * unexamined — and that is the path that ships.\n *\n * The circuit hashes the domain and the struct and proves the wallet signed\n * them. It never learns what the action says, so a malformed one does not\n * fail: it produces a valid proof of the wrong thing.\n */\nimport type { TypedAction } from './types';\n\nexport type { TypedAction };\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The reason the value is not a usable action, or `null` when it is one.\n *\n * A string rather than a boolean because every caller shows it to somebody —\n * a dapp developer reading a validation error, or a person looking at the\n * mobile app's demo screen.\n */\nexport function validateTypedAction(value: unknown): string | null {\n if (value === undefined || value === null) {\n return 'action is required for arc_eligibility. The circuit proves that a wallet authorised ONE EIP-712 action; there is nothing to prove without it.';\n }\n if (typeof value !== 'object' || Array.isArray(value)) {\n return 'action must be an object.';\n }\n const a = value as Partial<TypedAction>;\n\n const d = a.domain;\n if (!d || typeof d !== 'object') {\n return 'action.domain is required.';\n }\n for (const k of ['name', 'version', 'verifyingContract'] as const) {\n if (typeof d[k] !== 'string' || !d[k]) {\n return `action.domain.${k} must be a non-empty string.`;\n }\n }\n if (typeof d.chainId !== 'number' || !Number.isInteger(d.chainId)) {\n return 'action.domain.chainId must be an integer.';\n }\n if (!ADDRESS.test(d.verifyingContract)) {\n return 'action.domain.verifyingContract must be a 20-byte hex address.';\n }\n\n if (!a.types || typeof a.types !== 'object' || Array.isArray(a.types)) {\n return 'action.types is required.';\n }\n if (typeof a.primaryType !== 'string' || !a.primaryType) {\n return 'action.primaryType is required.';\n }\n if (!(a.primaryType in a.types)) {\n return `action.primaryType '${a.primaryType}' is not one of the structs in action.types.`;\n }\n if (!a.message || typeof a.message !== 'object' || Array.isArray(a.message)) {\n return 'action.message is required.';\n }\n\n // Every field the struct declares must be present, or the wallet signs a\n // different message than the one the caller described.\n const fields = a.types[a.primaryType];\n if (!Array.isArray(fields) || fields.length === 0) {\n return `action.types.${a.primaryType} declares no fields.`;\n }\n const missing = fields\n .map(f => f?.name)\n .filter(n => typeof n === 'string' && !(n in (a.message as object)));\n if (missing.length) {\n return `action.message is missing: ${missing.join(', ')}`;\n }\n\n return null;\n}\n\n/** The action, or the reason it is not one. For text a person typed. */\nexport function parseTypedAction(text: string): { action: TypedAction } | { error: string } {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (e) {\n return { error: `Not valid JSON: ${(e as Error).message}` };\n }\n const error = validateTypedAction(raw);\n return error ? { error } : { action: raw as TypedAction };\n}\n","/**\n * Deep Link utilities for ZKProofport SDK\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n OidcDomainInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n DeepLinkComponents,\n CircuitType,\n ArcEligibilityInputs,\n} from './types';\nimport { DEFAULT_SCHEME, DEEP_LINK_HOSTS } from './constants';\nimport { isCircuitId, ALL_CIRCUIT_IDS } from './circuits';\nimport { validateTypedAction } from './typedAction';\n\n/**\n * Generates a unique request ID for proof requests.\n *\n * Creates an ID by combining a base36-encoded timestamp with a random string,\n * prefixed with \"req-\". This ensures uniqueness across concurrent requests.\n *\n * @returns A unique string identifier in the format \"req-{timestamp}-{random}\"\n *\n * @example\n * ```typescript\n * const id = generateRequestId();\n * // \"req-lh8k3f2g-a9b7c4d2\"\n * ```\n */\nexport function generateRequestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 10);\n return `req-${timestamp}-${random}`;\n}\n\n/**\n * Encodes an object into a URL-safe base64url string with UTF-8 support.\n *\n * Converts the input object to JSON, then encodes it using base64url format\n * (RFC 4648 §5) which replaces '+' with '-', '/' with '_', and removes padding.\n * Works in both browser and Node.js environments.\n *\n * @param data - The object to encode (will be JSON stringified)\n * @returns Base64url-encoded string safe for URL parameters\n *\n * @example\n * ```typescript\n * const encoded = encodeData({ circuit: 'coinbase_attestation', requestId: 'req-123' });\n * // \"eyJjaXJjdWl0IjoiY29pbmJhc2VfYXR0ZXN0YXRpb24iLCJyZXF1ZXN0SWQiOiJyZXEtMTIzIn0\"\n * ```\n */\nexport function encodeData(data: object): string {\n const json = JSON.stringify(data);\n // Use base64url encoding (URL-safe) with UTF-8 support\n if (typeof btoa === 'function') {\n // Browser: UTF-8 encode first, then base64\n const utf8Encoded = encodeURIComponent(json).replace(/%([0-9A-F]{2})/g, (_, p1) =>\n String.fromCharCode(parseInt(p1, 16))\n );\n return btoa(utf8Encoded)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n // Node.js environment\n return Buffer.from(json, 'utf-8')\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decodes a base64url-encoded string back into a typed object.\n *\n * Reverses the encoding process by converting base64url to standard base64,\n * decoding it, and parsing the resulting JSON. Handles UTF-8 correctly in\n * both browser and Node.js environments.\n *\n * @typeParam T - The expected type of the decoded object\n * @param encoded - Base64url-encoded string (from encodeData)\n * @returns Decoded and parsed object of type T\n *\n * @throws {SyntaxError} If the decoded string is not valid JSON\n *\n * @example\n * ```typescript\n * const request = decodeData<ProofRequest>(encodedString);\n * console.log(request.circuit); // \"coinbase_attestation\"\n * ```\n */\nexport function decodeData<T>(encoded: string): T {\n // Restore base64 padding\n let base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');\n while (base64.length % 4) {\n base64 += '=';\n }\n\n let json: string;\n if (typeof atob === 'function') {\n // Browser: decode base64, then UTF-8 decode\n const decoded = atob(base64);\n json = decodeURIComponent(\n decoded.split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')\n );\n } else {\n json = Buffer.from(base64, 'base64').toString('utf-8');\n }\n\n return JSON.parse(json) as T;\n}\n\n/**\n * Builds a deep link URL for a proof request.\n *\n * Encodes the proof request and constructs a deep link URL that can be opened\n * by the ZKProofport mobile app. The URL format is:\n * `{scheme}://proof-request?data={encodedRequest}`\n *\n * @param request - The proof request to encode in the deep link\n * @param scheme - Custom URL scheme (defaults to \"zkproofport\")\n * @returns Complete deep link URL ready to be opened or embedded in a QR code\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n * const url = buildProofRequestUrl(request);\n * // \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\"\n * ```\n */\nexport function buildProofRequestUrl(\n request: ProofRequest,\n scheme: string = DEFAULT_SCHEME\n): string {\n const encodedRequest = encodeData(request);\n return `${scheme}://${DEEP_LINK_HOSTS.PROOF_REQUEST}?data=${encodedRequest}`;\n}\n\n/**\n * Builds a callback URL with proof response data as query parameters.\n *\n * Appends proof response fields to the provided callback URL. For completed proofs,\n * includes proof data, public inputs, and nullifier. For errors, includes error message.\n *\n * @internal Used by the mobile app to construct callback URLs — not intended for SDK consumers.\n *\n * @param callbackUrl - Base callback URL (from the original proof request)\n * @param response - Proof response containing status and optional proof data\n * @returns Complete callback URL with proof response as query parameters\n */\nexport function buildCallbackUrl(\n callbackUrl: string,\n response: ProofResponse\n): string {\n const url = new URL(callbackUrl);\n url.searchParams.set('requestId', response.requestId);\n url.searchParams.set('status', response.status);\n\n if (response.status === 'completed' && response.proof) {\n url.searchParams.set('proof', response.proof);\n if (response.publicInputs) {\n url.searchParams.set('publicInputs', response.publicInputs.join(','));\n }\n if (response.numPublicInputs !== undefined) {\n url.searchParams.set('numPublicInputs', response.numPublicInputs.toString());\n }\n if (response.timestamp) {\n url.searchParams.set('timestamp', response.timestamp.toString());\n }\n } else if (response.status === 'error' && response.error) {\n url.searchParams.set('error', response.error);\n }\n\n return url.toString();\n}\n\n/**\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a ZKProofport deep link URL.\n * Returns null if the URL is invalid or missing required parameters.\n *\n * @param url - Deep link URL (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Decoded ProofRequest object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\";\n * const request = parseProofRequestUrl(url);\n * if (request) {\n * console.log(request.circuit); // \"coinbase_attestation\"\n * }\n * ```\n */\nexport function parseProofRequestUrl(url: string): ProofRequest | null {\n try {\n const urlObj = new URL(url);\n const data = urlObj.searchParams.get('data');\n\n if (!data) {\n return null;\n }\n\n return decodeData<ProofRequest>(data);\n } catch (error) {\n console.error('Failed to parse proof request URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a proof response from a callback URL.\n *\n * Extracts proof response data from query parameters in a callback URL.\n * Handles both successful proof completions and error responses.\n * Returns null if required parameters (requestId, status) are missing.\n *\n * @param url - Callback URL with proof response query parameters\n * @returns Decoded ProofResponse object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const callbackUrl = \"https://example.com/callback?requestId=req-123&status=completed&proof=0x...\";\n * const response = parseProofResponseUrl(callbackUrl);\n * if (response && response.status === 'completed') {\n * console.log(response.proof); // \"0x...\"\n * }\n * ```\n */\nexport function parseProofResponseUrl(url: string): ProofResponse | null {\n try {\n const urlObj = new URL(url);\n const requestId = urlObj.searchParams.get('requestId');\n const status = urlObj.searchParams.get('status') as ProofResponse['status'];\n\n if (!requestId || !status) {\n return null;\n }\n\n // A missing or unrecognised circuit is a REJECTION, not a default.\n //\n // This used to fall back to `coinbase_attestation`. A callback carrying a\n // country or OIDC proof, or a circuit this build has never heard of, was\n // then handed to the caller labelled Coinbase KYC -- the parse succeeded,\n // the label was wrong, and nothing downstream could tell. Whoever reads\n // `response.circuit` decides which verifier and which public-input layout\n // to use, so the wrong label is a proof checked against another circuit's\n // bytes.\n const circuit = urlObj.searchParams.get('circuit');\n if (!circuit || !isCircuitId(circuit)) {\n return null;\n }\n\n const response: ProofResponse = {\n requestId,\n circuit,\n status,\n };\n\n if (status === 'completed') {\n response.proof = urlObj.searchParams.get('proof') || undefined;\n const publicInputsStr = urlObj.searchParams.get('publicInputs');\n if (publicInputsStr) {\n response.publicInputs = publicInputsStr.split(',');\n }\n const numPublicInputs = urlObj.searchParams.get('numPublicInputs');\n if (numPublicInputs) {\n response.numPublicInputs = parseInt(numPublicInputs, 10);\n }\n const timestamp = urlObj.searchParams.get('timestamp');\n if (timestamp) {\n response.timestamp = parseInt(timestamp, 10);\n }\n } else if (status === 'error') {\n response.error = urlObj.searchParams.get('error') || undefined;\n }\n\n return response;\n } catch (error) {\n console.error('Failed to parse proof response URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a deep link URL into its component parts.\n *\n * Breaks down a custom scheme URL into scheme, host, path, and query parameters.\n * Useful for routing and handling different types of deep links.\n *\n * @param url - Custom scheme URL to parse (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Object containing scheme, host, path, and params, or null if invalid\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request/verify?data=abc123\";\n * const components = parseDeepLink(url);\n * // {\n * // scheme: \"zkproofport\",\n * // host: \"proof-request\",\n * // path: \"/verify\",\n * // params: { data: \"abc123\" }\n * // }\n * ```\n */\nexport function parseDeepLink(url: string): DeepLinkComponents | null {\n try {\n // Handle custom scheme URLs\n const schemeMatch = url.match(/^([a-z][a-z0-9+.-]*):\\/\\/(.+)$/i);\n if (!schemeMatch) {\n return null;\n }\n\n const scheme = schemeMatch[1];\n const rest = schemeMatch[2];\n\n // Parse host and path\n const [hostPath, queryString] = rest.split('?');\n const [host, ...pathParts] = hostPath.split('/');\n const path = '/' + pathParts.join('/');\n\n // Parse query parameters\n const params: Record<string, string> = {};\n if (queryString) {\n const searchParams = new URLSearchParams(queryString);\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n }\n\n return { scheme, host, path, params };\n } catch (error) {\n console.error('Failed to parse deep link:', error);\n return null;\n }\n}\n\n/**\n * Checks if a URL is a valid ZKProofport deep link.\n *\n * Performs a case-insensitive check to see if the URL starts with the\n * ZKProofport scheme. Does not validate the URL structure beyond the scheme.\n *\n * @param url - URL to check\n * @param scheme - Expected URL scheme (defaults to \"zkproofport\")\n * @returns True if the URL starts with the specified scheme\n *\n * @example\n * ```typescript\n * isProofportDeepLink(\"zkproofport://proof-request?data=...\"); // true\n * isProofportDeepLink(\"https://example.com\"); // false\n * isProofportDeepLink(\"ZKPROOFPORT://proof-request\"); // true (case-insensitive)\n * ```\n */\nexport function isProofportDeepLink(\n url: string,\n scheme: string = DEFAULT_SCHEME\n): boolean {\n return url.toLowerCase().startsWith(`${scheme.toLowerCase()}://`);\n}\n\n/**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Performs comprehensive validation including:\n * - Required fields (requestId, circuit, callbackUrl)\n * - Circuit type validity (must be a supported circuit)\n * - Circuit-specific input validation (e.g., userAddress format, countryList structure)\n * - Expiration check (if expiresAt is provided)\n *\n * Note: userAddress is optional for both circuits - the mobile app will prompt\n * for wallet connection if not provided.\n *\n * @param request - Proof request to validate\n * @returns Validation result with `valid` flag and optional `error` message\n */\n/**\n * Validates a free-text mDL input (scope / targetRegion).\n * Rejects empty or whitespace-only values, control characters (which break\n * deep-link query encoding and downstream logging), and values over 256 chars\n * (server-side length cap mirror). UTF-8 text such as Korean region names is\n * allowed.\n *\n * @returns Error message string, or null when valid.\n */\nfunction validateMdlTextInput(value: unknown, fieldName: string): string | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return `${fieldName} is required and must be a non-empty string`;\n }\n if (value.length > 256) {\n return `${fieldName} must be 256 characters or fewer`;\n }\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001F\\u007F]/.test(value)) {\n return `${fieldName} must not contain control characters`;\n }\n return null;\n}\n\n/**\n * Validates dapp-supplied inputs for the Korea Mobile ID (mDL) circuits.\n * Shared by deep-link request validation and relay request creation so the\n * same guards apply on every request path.\n *\n * Rules:\n * - `scope` — required non-empty string, ≤256 chars, no control characters\n * - `mdl_kr_ownership.discloseFlags` — optional integer 0–15 (0x0F bitmask)\n * - `mdl_kr_age.ageThreshold` — required integer 1–150\n * - `mdl_kr_region.targetRegion` — required non-empty string (Korean si/do),\n * ≤256 chars, no control characters\n *\n * @param circuit - One of the three mDL circuit identifiers\n * @param inputs - Dapp-supplied circuit inputs\n * @returns Error message string, or null when the inputs are valid\n */\nexport function validateMdlInputs(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs\n): string | null {\n const scopeError = validateMdlTextInput((inputs as MdlKrOwnershipInputs).scope, 'scope');\n if (scopeError) {\n return scopeError;\n }\n\n if (circuit === 'mdl_kr_ownership') {\n const { discloseFlags } = inputs as MdlKrOwnershipInputs;\n if (discloseFlags !== undefined) {\n if (\n typeof discloseFlags !== 'number' ||\n !Number.isInteger(discloseFlags) ||\n discloseFlags < 0 ||\n discloseFlags > 0x0f\n ) {\n return 'discloseFlags must be an integer between 0 and 15';\n }\n }\n } else if (circuit === 'mdl_kr_age') {\n const { ageThreshold } = inputs as MdlKrAgeInputs;\n if (\n typeof ageThreshold !== 'number' ||\n !Number.isInteger(ageThreshold) ||\n ageThreshold < 1 ||\n ageThreshold > 150\n ) {\n return 'ageThreshold is required and must be an integer between 1 and 150';\n }\n } else {\n const { targetRegion } = inputs as MdlKrRegionInputs;\n const regionError = validateMdlTextInput(targetRegion, 'targetRegion');\n if (regionError) {\n return regionError;\n }\n }\n\n return null;\n}\n\n/**\n * Longest accepted `returnScheme` value.\n * Kept in sync with proofport-relay `src/returnScheme.ts`.\n */\nexport const MAX_RETURN_SCHEME_LENGTH = 128;\n\n/** RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`) followed by exactly `://`. */\nconst BARE_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\/$/;\n\n/**\n * Schemes we refuse even in the bare `scheme://` shape.\n *\n * `http` and `https` are the back door the shape rule alone leaves open: with\n * no host, `https://` is shaped exactly like a bare custom scheme and would\n * otherwise pass. A browser pointed at nowhere is not a return target, and\n * accepting it would re-open the URL-shaped door this field just closed.\n * `googlechrome://` and `firefox://` are deliberately NOT denied — bare, they\n * foreground that browser without navigating, which is the whole point.\n */\nconst DENIED_RETURN_SCHEMES = new Set([\n 'about',\n 'blob',\n 'content',\n 'data',\n 'facetime',\n 'facetime-audio',\n 'file',\n 'ftp',\n 'http',\n 'https',\n 'intent',\n 'javascript',\n 'jar',\n 'mailto',\n 'sms',\n 'tel',\n 'vbscript',\n]);\n\n/**\n * Validates a `returnScheme` before it is sent to the relay, so a malformed\n * value fails fast in the integrator's own code instead of coming back as a\n * relay 400. The relay re-validates and is the authority.\n *\n * One shape is accepted: a bare custom scheme such as `mydapp://`. It names an\n * app to switch back to, never a page to visit — so hosts, paths and query\n * strings are rejected, and an https URL is not a valid value. A web page has\n * no app to return to and simply omits the field.\n *\n * @param value - Candidate return target\n * @returns `null` when acceptable, otherwise a human-readable error message\n *\n * @internal\n */\nexport function validateReturnScheme(value: unknown): string | null {\n if (typeof value !== 'string') {\n return 'returnScheme must be a string';\n }\n if (value.length === 0) {\n return 'returnScheme must not be empty';\n }\n // Length is checked before any regex so a huge string never reaches the matcher.\n if (value.length > MAX_RETURN_SCHEME_LENGTH) {\n return `returnScheme must be at most ${MAX_RETURN_SCHEME_LENGTH} characters`;\n }\n if (/\\s/.test(value)) {\n return 'returnScheme must not contain whitespace';\n }\n\n const normalized = value.toLowerCase();\n\n if (!BARE_SCHEME_RE.test(normalized)) {\n return 'returnScheme must be a bare custom scheme such as \"mydapp://\" — hosts, paths, query strings and fragments are not accepted, and an https URL is not a return target';\n }\n\n const schemeName = normalized.slice(0, normalized.indexOf(':'));\n if (DENIED_RETURN_SCHEMES.has(schemeName)) {\n return `returnScheme \"${schemeName}\" is not allowed`;\n }\n\n return null;\n}\n\n/**\n * The return target to use when the integrator named none.\n *\n * Only the requesting PAGE can answer \"which browser is this?\" — iOS gives the\n * ZKProofport app nothing to work with (`sourceApplication` is nil across team\n * identifiers, and there is no public API to foreground an app by bundle id).\n * So the detection has to happen here, in the SDK, and travel with the request.\n *\n * Two cases are detected, each from a POSITIVE token, and each verified in the\n * browser's own source to foreground WITHOUT navigating anywhere:\n *\n * Chrome for iOS (`CriOS/`) -> `googlechrome://`\n * Firefox for iOS (`FxiOS/`) -> `firefox://`\n *\n * The BARE scheme is the point in both cases: it carries no URL, so the browser\n * comes forward with nothing to open and the user lands on the tab they were\n * already reading — no new tab, no navigation, no reload, JS state intact.\n *\n * Chrome: `ios/chrome/app/startup/chrome_app_startup_parameters.mm` replaces\n * the scheme with `http`, producing `http://`, which fails GURL validation\n * (`if (!externalURL.is_valid()) return nil;`), so the startup parameters are\n * nil and there is nothing to open.\n *\n * Firefox: `firefox://` has an empty host, and\n * `Coordinators/Router/RouteBuilder.swift` resolves the host through\n * `DeeplinkInput.Host(rawValue: \"\")`, which is nil because no case has an empty\n * raw value (`Coordinators/Router/DeeplinkInput.swift`). The scheme is not http\n * either, so `makeRoute(url:)` falls to its final `else { return nil }`, and\n * `SceneDelegate.handleOpenURL` then hits `guard let route = ... else\n * { return }` and does nothing at all. Verified on the warm path — the browser\n * is already running, which is always true here, because the user came from a\n * page in it.\n *\n * Everything else deliberately returns undefined, and that is not a gap:\n *\n * - Safari has no equivalent. No scheme means \"just come forward\";\n * `https://<url>` navigates and opens a new tab, `x-web-search://` opens a\n * search page. Both lose the user's page.\n * - Brave and Arc for iOS are UNDETECTABLE. Brave ships no UA token and\n * identifies itself only via Client Hints, which WebKit does not implement,\n * so it looks exactly like Safari. Inferring \"Safari\" by elimination and\n * firing a Safari-ish scheme would throw Brave and Arc users into a browser\n * they were not using — strictly worse than doing nothing.\n * - In-app webviews (KakaoTalk, Naver, Line, Instagram) are not tabs at all.\n * Any scheme destroys the page; the system \"< Back to X\" breadcrumb is the\n * only thing that preserves it.\n * - Edge (`EdgiOS`) and Opera (`OPiOS` / `OPT`) for iOS are NOT included.\n * Both are closed source, so `microsoft-edge://` and `opera-http://` cannot\n * be checked the way Chrome's and Firefox's were. Their bare schemes are\n * plausible analogues, and that is exactly why they stay out: an unverified\n * guess that opens a new tab is the bug this field exists to avoid. Add one\n * only with evidence that it foregrounds WITHOUT navigating.\n * - Android needs nothing: the ZKProofport app brings itself to the back\n * (`moveTaskToBack`), which resumes the browser exactly as it was.\n *\n * When this returns undefined the field is omitted and the ZKProofport app\n * tells the user the proof was delivered and to switch back themselves.\n *\n * @param userAgent - override, for tests. Defaults to `navigator.userAgent`.\n * Returns undefined when there is no navigator at all (Node, SSR).\n * @returns a scheme that is safe to open, or undefined to send nothing\n *\n * @internal\n */\nexport function detectReturnScheme(userAgent?: string): string | undefined {\n const ua =\n userAgent ?? (typeof navigator === 'undefined' ? undefined : navigator.userAgent);\n if (typeof ua !== 'string' || ua.length === 0) {\n return undefined;\n }\n // A device token is required alongside the browser token. `CriOS` and `FxiOS`\n // are already iOS-only and unambiguous on their own, but pairing them with the\n // device token costs nothing and stops a synthetic or spoofed desktop user\n // agent from producing a mobile-only scheme.\n if (!/(iPhone|iPad|iPod)/.test(ua)) {\n return undefined;\n }\n if (/CriOS\\//.test(ua)) {\n return 'googlechrome://';\n }\n if (/FxiOS\\//.test(ua)) {\n return 'firefox://';\n }\n return undefined;\n}\n\nexport function validateProofRequest(request: ProofRequest): { valid: boolean; error?: string } {\n if (!request.requestId) {\n return { valid: false, error: 'Missing requestId' };\n }\n\n if (!request.circuit) {\n return { valid: false, error: 'Missing circuit type' };\n }\n\n // The list is the SDK's own, not a copy. The copy that used to sit here\n // named six circuits and had missed two — `giwa_attestation` and\n // `arc_eligibility` — so a link for either was refused as an invalid type\n // while every other layer accepted it.\n if (!isCircuitId(request.circuit)) {\n return {\n valid: false,\n error: `Invalid circuit type: ${request.circuit}. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n };\n }\n\n if (!request.callbackUrl) {\n return { valid: false, error: 'Missing callbackUrl' };\n }\n\n // Validate circuit-specific inputs\n if (request.circuit === 'coinbase_attestation') {\n // Coinbase KYC: userAddress is optional - app will connect wallet if not provided\n const inputs = request.inputs as CoinbaseKycInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n // If userAddress is not provided, app will prompt wallet connection - this is valid\n } else if (request.circuit === 'coinbase_country_attestation') {\n const inputs = request.inputs as CoinbaseCountryInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n return { valid: false, error: 'countryList is required and must be a non-empty array' };\n }\n if (!inputs.countryList.every(c => typeof c === 'string')) {\n return { valid: false, error: 'countryList must contain only strings' };\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n return { valid: false, error: 'isIncluded is required and must be a boolean' };\n }\n } else if (request.circuit === 'oidc_domain_attestation') {\n const inputs = request.inputs as OidcDomainInputs;\n if (!inputs.domain || typeof inputs.domain !== 'string' || inputs.domain.trim() === '') {\n return { valid: false, error: 'domain is required and must be a non-empty string' };\n }\n if (!inputs.scope || typeof inputs.scope !== 'string' || inputs.scope.trim() === '') {\n return { valid: false, error: 'scope is required and must be a non-empty string' };\n }\n if (inputs.provider !== undefined && (typeof inputs.provider !== 'string' || inputs.provider.trim() === '')) {\n return { valid: false, error: 'provider must be a non-empty string when specified' };\n }\n } else if (\n request.circuit === 'mdl_kr_ownership' ||\n request.circuit === 'mdl_kr_age' ||\n request.circuit === 'mdl_kr_region'\n ) {\n const mdlError = validateMdlInputs(request.circuit, request.inputs);\n if (mdlError) {\n return { valid: false, error: mdlError };\n }\n } else if (request.circuit === 'arc_eligibility') {\n const inputs = request.inputs as Partial<ArcEligibilityInputs>;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n const actionError = validateTypedAction(inputs.action);\n if (actionError) {\n return { valid: false, error: actionError };\n }\n }\n\n // Check expiry\n if (request.expiresAt && Date.now() > request.expiresAt) {\n return { valid: false, error: 'Request has expired' };\n }\n\n return { valid: true };\n}\n","/**\n * QR Code utilities for ZKProofport SDK\n */\n\nimport QRCode from 'qrcode';\nimport type { ProofRequest, QRCodeOptions } from './types';\nimport { buildProofRequestUrl } from './deeplink';\nimport { DEFAULT_SCHEME, MAX_QR_DATA_SIZE } from './constants';\n\n/**\n * Default QR code options\n */\nconst DEFAULT_QR_OPTIONS: QRCodeOptions = {\n width: 300,\n errorCorrectionLevel: 'M',\n margin: 2,\n darkColor: '#000000',\n lightColor: '#ffffff',\n};\n\n/**\n * Generates a QR code as a base64-encoded PNG data URL.\n *\n * Creates a scannable QR code image from a proof request or deep link URL.\n * The returned data URL can be used directly in HTML img src attributes.\n * Validates that the encoded data doesn't exceed the maximum QR code size.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to base64 PNG data URL (e.g., \"data:image/png;base64,...\")\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n *\n * const dataUrl = await generateQRCodeDataUrl(request, {\n * width: 400,\n * darkColor: '#000000',\n * lightColor: '#ffffff'\n * });\n *\n * // Use in HTML: <img src={dataUrl} alt=\"Scan to prove\" />\n * ```\n */\nexport async function generateQRCodeDataUrl(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n // Check data size\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toDataURL(url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Generates a QR code as an SVG string.\n *\n * Creates a scalable vector graphics QR code that can be embedded directly in HTML\n * or saved to a file. SVG QR codes scale perfectly at any size and have smaller\n * file sizes than raster formats.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to SVG markup string\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const svg = await generateQRCodeSVG(request, { width: 300 });\n *\n * // Embed directly: <div dangerouslySetInnerHTML={{ __html: svg }} />\n * // Or save to file: fs.writeFileSync('qr.svg', svg);\n * ```\n */\nexport async function generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toString(url, {\n type: 'svg',\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Browser-only function that draws a QR code onto an existing canvas element.\n * Useful for interactive applications or when you need direct canvas manipulation.\n * The canvas dimensions will be set automatically based on the width option.\n *\n * @param canvas - HTML canvas element to render to (must exist in DOM)\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise that resolves when rendering is complete\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n * @throws {Error} If canvas is not a valid HTMLCanvasElement (browser only)\n *\n * @example\n * ```typescript\n * // In a React component:\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n *\n * useEffect(() => {\n * if (canvasRef.current) {\n * generateQRCodeToCanvas(canvasRef.current, request, { width: 400 });\n * }\n * }, [request]);\n *\n * return <canvas ref={canvasRef} />;\n * ```\n */\nexport async function generateQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<void> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n await QRCode.toCanvas(canvas, url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Estimates the byte size of a QR code's encoded data.\n *\n * Calculates the size of the deep link URL that will be encoded in the QR code,\n * and checks if it's within the maximum supported size (2953 bytes for QR version 40\n * with medium error correction). Use this before generating QR codes to avoid errors.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Object with `size` in bytes and `withinLimit` boolean flag\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const { size, withinLimit } = estimateQRDataSize(request);\n *\n * if (!withinLimit) {\n * console.error(`QR code too large: ${size} bytes (max 2953)`);\n * // Consider reducing request data or splitting into multiple QR codes\n * }\n *\n * // Example output: { size: 384, withinLimit: true }\n * ```\n */\nexport function estimateQRDataSize(\n requestOrUrl: ProofRequest | string,\n scheme: string = DEFAULT_SCHEME\n): { size: number; withinLimit: boolean } {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n return {\n size: url.length,\n withinLimit: url.length <= MAX_QR_DATA_SIZE,\n };\n}\n","/**\n * On-chain verification utilities for ZKProofport SDK\n *\n * Compatible with both ethers v5 and v6.\n */\n\nimport { ethers } from 'ethers';\nimport type { CircuitType, ParsedProof, VerifierContract } from './types';\nimport { VERIFIER_ABI, RPC_ENDPOINTS, OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT } from './constants';\nimport { ALL_CIRCUIT_IDS, isCircuitId, type CircuitId } from './circuits';\n\n// ethers v5/v6 compatibility shims\nconst _ethers = ethers as any;\n\n/** @internal ethers v5/v6 compatibility shim */\nfunction hexZeroPad(value: string, length: number): string {\n // v6: ethers.zeroPadValue, v5: ethers.utils.hexZeroPad\n if (typeof _ethers.zeroPadValue === 'function') return _ethers.zeroPadValue(value, length);\n if (_ethers.utils?.hexZeroPad) return _ethers.utils.hexZeroPad(value, length);\n // manual fallback\n const hex = value.startsWith('0x') ? value.slice(2) : value;\n return '0x' + hex.padStart(length * 2, '0');\n}\n\n/** @internal ethers v5/v6 compatibility shim */\nfunction createJsonRpcProvider(url: string) {\n // v6: ethers.JsonRpcProvider, v5: ethers.providers.JsonRpcProvider\n if (typeof _ethers.JsonRpcProvider === 'function') return new _ethers.JsonRpcProvider(url);\n if (_ethers.providers?.JsonRpcProvider) return new _ethers.providers.JsonRpcProvider(url);\n throw new Error('No JsonRpcProvider found in ethers');\n}\n\n/**\n * @internal Resolve verifier from SDK config or proof response.\n * SDK config (customVerifier) takes priority over response-provided verifier.\n */\nfunction resolveVerifier(\n customVerifier?: VerifierContract,\n responseVerifier?: { verifierAddress?: string; chainId?: number }\n): VerifierContract | null {\n if (customVerifier) return customVerifier;\n if (responseVerifier?.verifierAddress) {\n return {\n address: responseVerifier.verifierAddress,\n chainId: responseVerifier.chainId ?? 0,\n abi: VERIFIER_ABI,\n };\n }\n return null;\n}\n\n/**\n * Get verifier contract instance for interacting with on-chain verifier contracts.\n *\n * @param providerOrSigner - ethers.js Provider or Signer instance (v5 or v6 compatible)\n * @param verifier - Verifier contract configuration containing address and ABI\n * @returns ethers.Contract instance connected to the verifier\n *\n * @example\n * ```typescript\n * const provider = new ethers.JsonRpcProvider(rpcUrl);\n * const contract = getVerifierContract(provider, {\n * address: '0x...',\n * chainId: 11155111,\n * abi: VERIFIER_ABI\n * });\n * ```\n */\nexport function getVerifierContract(\n providerOrSigner: any,\n verifier: VerifierContract\n): ethers.Contract {\n return new ethers.Contract(\n verifier.address,\n verifier.abi,\n providerOrSigner\n );\n}\n\n/**\n * Get default JSON-RPC provider for a chain using pre-configured RPC endpoints.\n *\n * @param chainId - The chain ID (e.g., 11155111 for Sepolia, 84532 for Base Sepolia)\n * @returns ethers.JsonRpcProvider instance for the specified chain\n * @throws Error if no RPC endpoint is configured for the chain\n *\n * @example\n * ```typescript\n * const provider = getDefaultProvider(11155111); // Sepolia\n * ```\n */\nexport function getDefaultProvider(chainId: number) {\n const rpcUrl = RPC_ENDPOINTS[chainId];\n if (!rpcUrl) {\n throw new Error(`No RPC endpoint configured for chain ${chainId}`);\n }\n return createJsonRpcProvider(rpcUrl);\n}\n\n/**\n * Verify a zero-knowledge proof on-chain by calling the verifier smart contract.\n *\n * This function resolves the verifier contract from SDK config or proof response,\n * connects to the blockchain, and calls the verify() method with the proof and public inputs.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param parsedProof - Parsed proof object containing proofHex and publicInputsHex\n * @param providerOrSigner - Optional ethers.js Provider or Signer instance. If not provided, uses default RPC for the chain\n * @param customVerifier - Optional custom verifier contract config (takes priority over responseVerifier)\n * @param responseVerifier - Optional verifier info from proof generation response\n * @returns Promise resolving to verification result with valid flag and optional error message\n *\n * @example\n * ```typescript\n * const parsed = parseProofForOnChain(proof, publicInputs, numPublicInputs);\n * const result = await verifyProofOnChain(\n * 'coinbase_attestation',\n * parsed,\n * provider,\n * { address: '0x...', chainId: 11155111, abi: VERIFIER_ABI }\n * );\n *\n * if (result.valid) {\n * console.log('Proof is valid!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * ```\n */\nexport async function verifyProofOnChain(\n circuit: CircuitType,\n parsedProof: ParsedProof,\n providerOrSigner?: any,\n customVerifier?: VerifierContract,\n responseVerifier?: { verifierAddress?: string; chainId?: number }\n): Promise<{ valid: boolean; error?: string }> {\n const verifier = resolveVerifier(customVerifier, responseVerifier);\n if (!verifier) {\n return {\n valid: false,\n error: 'No verifier address provided. Configure via SDK or ensure proof response includes verifierAddress.',\n };\n }\n\n const provider = providerOrSigner || (verifier.chainId > 0 ? getDefaultProvider(verifier.chainId) : null);\n if (!provider) {\n return {\n valid: false,\n error: 'No provider available. Provide a provider or ensure chainId is set for RPC lookup.',\n };\n }\n\n const contract = getVerifierContract(provider, verifier);\n\n try {\n const isValid = await contract.verify(\n parsedProof.proofHex,\n parsedProof.publicInputsHex\n );\n\n return { valid: isValid };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return { valid: false, error: errorMessage };\n }\n}\n\n/** @internal Ensure a hex string has the 0x prefix */\nfunction ensureHexPrefix(hex: string): string {\n return hex.startsWith('0x') ? hex : `0x${hex}`;\n}\n\n/**\n * Parse proof response into format suitable for on-chain verification.\n *\n * Converts proof and public inputs from relay response format to the format\n * expected by Solidity verifier contracts. Public inputs are zero-padded to\n * 32 bytes (bytes32) to match Solidity's bytes32[] type.\n *\n * @param proof - Proof bytes as hex string (with or without 0x prefix)\n * @param publicInputs - Array of public input values as hex strings\n * @param numPublicInputs - Number of public inputs (for validation)\n * @returns Parsed proof object ready for on-chain verification\n *\n * @example\n * ```typescript\n * const parsed = parseProofForOnChain(\n * '0x1a2b3c...',\n * ['0x01', '0x02', '0x03'],\n * 3\n * );\n *\n * // parsed.proofHex: '0x1a2b3c...'\n * // parsed.publicInputsHex: ['0x0000...01', '0x0000...02', '0x0000...03']\n * ```\n */\nexport function parseProofForOnChain(\n proof: string,\n publicInputs: string[],\n numPublicInputs: number\n): ParsedProof {\n const proofHex = ensureHexPrefix(proof);\n\n const publicInputsHex = publicInputs.map((input) => {\n return hexZeroPad(ensureHexPrefix(input), 32);\n });\n\n return {\n proofHex,\n publicInputsHex,\n numPublicInputs,\n };\n}\n\n/** @internal Require a verifier or throw with a helpful message */\nfunction requireVerifier(circuit: CircuitType, verifier?: VerifierContract): VerifierContract {\n if (!verifier) {\n throw new Error(`No verifier configured for circuit '${circuit}'. Configure via SDK verifiers option.`);\n }\n return verifier;\n}\n\n/**\n * Get verifier contract address for a circuit.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param customVerifier - Optional custom verifier contract config\n * @returns Verifier contract address as hex string\n * @throws Error if no verifier is configured for the circuit\n *\n * @example\n * ```typescript\n * const address = getVerifierAddress('coinbase_attestation', verifierConfig);\n * console.log(address); // '0x1234...'\n * ```\n */\nexport function getVerifierAddress(\n circuit: CircuitType,\n customVerifier?: VerifierContract\n): string {\n return requireVerifier(circuit, customVerifier).address;\n}\n\n/**\n * Get chain ID for a circuit's verifier contract.\n *\n * @param circuit - The canonical circuit identifier. REQUIRED.\n * @param customVerifier - Optional custom verifier contract config\n * @returns Chain ID number (e.g., 11155111 for Sepolia, 84532 for Base Sepolia)\n * @throws Error if no verifier is configured for the circuit\n *\n * @example\n * ```typescript\n * const chainId = getVerifierChainId('coinbase_attestation', verifierConfig);\n * console.log(chainId); // 11155111\n * ```\n */\nexport function getVerifierChainId(\n circuit: CircuitType,\n customVerifier?: VerifierContract\n): number {\n return requireVerifier(circuit, customVerifier).chainId;\n}\n\n\n/**\n * Where `scope` and `nullifier` sit in each circuit's public inputs.\n *\n * Keyed by `CircuitId`, which is the point: adding a circuit to the SDK makes\n * this object a compile error until somebody opens that circuit's `fn main`\n * and writes its offsets down. Nothing here can be inferred from the proof —\n * the public inputs are a flat array of bytes with no framing.\n *\n * It replaced an `if / else if / else` chain whose final `else` handed every\n * unrecognised circuit — and every call that named no circuit at all —\n * Coinbase's offsets. For `arc_eligibility` that is not a near miss: its\n * public inputs are signal_hash, domain_separator, action_hash, merkle root,\n * scope, nullifier, so the nullifier slot under Coinbase's offsets holds the\n * MERKLE ROOT, a value identical for every user. Duplicate detection built on\n * it would report one person.\n */\nconst PUBLIC_INPUT_OFFSETS: Readonly<Record<CircuitId, { scope: readonly [number, number]; nullifier: readonly [number, number] }>> = Object.freeze({\n // signal_hash, signer_list_merkle_root, scope, nullifier\n coinbase_attestation: { scope: [64, 95], nullifier: [96, 127] },\n // Same four fields in the same order as Coinbase.\n giwa_attestation: { scope: [64, 95], nullifier: [96, 127] },\n // country_list, country_list_length and is_included sit before scope.\n coinbase_country_attestation: { scope: [86, 117], nullifier: [118, 149] },\n // pubkey_modulus_limbs and the bounded domain sit before scope.\n oidc_domain_attestation: { scope: [83, 114], nullifier: [115, 146] },\n // signal_hash, domain_separator, action_hash, merkle root, then the pair.\n arc_eligibility: { scope: [128, 159], nullifier: [160, 191] },\n // The Korea mDL circuits open with the pair; signal_hash is commented out.\n mdl_kr_ownership: { scope: [0, 31], nullifier: [32, 63] },\n mdl_kr_age: { scope: [0, 31], nullifier: [32, 63] },\n mdl_kr_region: { scope: [0, 31], nullifier: [32, 63] },\n});\n\n/**\n * The offsets for a circuit, or an error naming what was asked for.\n *\n * Throwing is the whole point. A caller that omits the circuit, or names one\n * this SDK has never heard of, is asking a question with no answer; returning\n * a guess produced a scope and a nullifier that belong to different bytes and\n * looked exactly like real ones.\n */\nfunction offsetsFor(circuit: string | undefined): { scope: readonly [number, number]; nullifier: readonly [number, number] } {\n if (circuit === undefined) {\n throw new Error(\n `A circuit id is required to read public inputs: the layout differs per circuit and cannot be inferred from the proof. Pass one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n );\n }\n if (!isCircuitId(circuit)) {\n throw new Error(\n `Unknown circuit '${circuit}'. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n );\n }\n return PUBLIC_INPUT_OFFSETS[circuit];\n}\n\n/**\n * Extract scope value from public inputs array.\n *\n * The scope is a bytes32 value encoded across 32 consecutive field elements\n * in the public inputs. The exact position depends on the circuit type.\n *\n * @param publicInputsHex - Array of public input hex strings (zero-padded to 32 bytes)\n * @param circuit - Optional circuit identifier to determine field positions\n * @returns Reconstructed scope as hex string with 0x prefix, or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const scope = extractScopeFromPublicInputs(publicInputsHex, 'coinbase_attestation');\n * console.log(scope); // '0x7a6b70726f6f66706f72742e636f6d...'\n * ```\n */\nexport function extractScopeFromPublicInputs(\n publicInputsHex: string[],\n circuit: string,\n): string | null {\n const [start, end] = offsetsFor(circuit).scope;\n if (publicInputsHex.length <= end) return null;\n const scopeFields = publicInputsHex.slice(start, end + 1);\n return reconstructBytes32FromFields(scopeFields);\n}\n\n/**\n * Extracts the nullifier (bytes32) from public inputs based on circuit type.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputsHex - Array of hex-encoded field elements\n * @param circuit - Circuit id. REQUIRED: the layout differs per circuit and\n * cannot be inferred from the proof. It used to default to\n * `coinbase_attestation`, which returned the right-shaped bytes read from\n * the wrong place for every other circuit.\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const nullifier = extractNullifierFromPublicInputs(publicInputs, 'coinbase_attestation');\n * console.log(nullifier); // '0xabc123...'\n * ```\n */\nexport function extractNullifierFromPublicInputs(\n publicInputsHex: string[],\n circuit: string,\n): string | null {\n const [start, end] = offsetsFor(circuit).nullifier;\n if (publicInputsHex.length <= end) return null;\n const nullifierFields = publicInputsHex.slice(start, end + 1);\n return reconstructBytes32FromFields(nullifierFields);\n}\n\n/**\n * Extract domain string from OIDC Domain Attestation public inputs.\n *\n * The domain is stored as a Noir BoundedVec<u8, 64>, which serializes as\n * [storage[0..64], len]. Each storage element is a u8 value in a field element.\n *\n * @param publicInputsHex - Array of public input hex strings\n * @param circuit - Circuit identifier (must be 'oidc_domain_attestation')\n * @returns Domain as ASCII string, or null if circuit doesn't match or inputs are insufficient\n *\n * @example\n * ```typescript\n * const domain = extractDomainFromPublicInputs(publicInputs, 'oidc_domain_attestation');\n * console.log(domain); // 'example.com'\n * ```\n */\nexport function extractDomainFromPublicInputs(\n publicInputsHex: string[],\n circuit?: string,\n): string | null {\n if (circuit !== 'oidc_domain_attestation') return null;\n\n const layout = OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT;\n if (publicInputsHex.length <= layout.DOMAIN_LEN) return null;\n\n const len = Number(BigInt(publicInputsHex[layout.DOMAIN_LEN]) & 0xFFn);\n if (len === 0 || len > 64) return null;\n\n const storageFields = publicInputsHex.slice(\n layout.DOMAIN_STORAGE_START,\n layout.DOMAIN_STORAGE_START + len,\n );\n\n const chars = storageFields.map(f => {\n const byte = Number(BigInt(f) & 0xFFn);\n return String.fromCharCode(byte);\n });\n\n return chars.join('');\n}\n\n/** @internal Reconstruct a bytes32 value from 32 individual field elements */\nfunction reconstructBytes32FromFields(fields: string[]): string {\n if (fields.length !== 32) {\n throw new Error(`Expected 32 fields, got ${fields.length}`);\n }\n const bytes = fields.map(f => {\n const byte = BigInt(f) & 0xFFn;\n return byte.toString(16).padStart(2, '0');\n }).join('');\n return '0x' + bytes;\n}\n","/**\n * Off-chain proof verification — checking a proof against its verification key,\n * with no chain, no RPC, and no gas.\n *\n * WHY THIS EXISTS. The SDK had only `verifyProofOnChain`, and every caller that\n * wanted an off-chain check called that instead and relabelled the result. The\n * demo page did exactly this from its first commit: pressing \"Off-Chain Verify\"\n * ran an on-chain verification and printed \"Off-Chain Verification Passed!\".\n * The answer was true and the label was a lie, which is the worst combination —\n * nothing looked broken. The mobile app has always verified off-chain properly\n * (through mopro's native Barretenberg); it was only the JavaScript side that\n * had no such thing.\n *\n * HOW IT WORKS. Proofs here are made with `--oracle_hash keccak` and ZK on, so\n * the matching check is `acirVerifyUltraKeccakZkHonk(proof, vk)`. Two things\n * have to line up:\n *\n * The version. `@aztec/bb.js@1.0.0-nightly.20250723` is the WASM build of the\n * same bb the circuits are compiled with. Versions are not interchangeable:\n * measured on the Korea Mobile ID age circuit, the pinned bb writes a 16256-\n * byte proof where bb 1.2.0 writes 16224 for the identical circuit and\n * witness — and the verification key comes out the SAME either way, so the\n * key cannot warn you. A mismatch shows up only as verification failing.\n *\n * The flavour. There are four verify entry points and picking the wrong one\n * is not a polite false. `acirVerifyUltraZKHonk` (poseidon) answers false for\n * a perfectly good proof, and `acirVerifyUltraKeccakHonk` — keccak without ZK\n * — TRAPS the WebAssembly with a bare \"unreachable\", which looks exactly like\n * a corrupt proof, a mismatched key, or a missing SRS.\n *\n * THE PROOF ARRIVES IN TWO PIECES. The mobile app splits what Barretenberg\n * produced into `proof` and `publicInputs` before sending it, because the\n * Solidity verifier takes them separately. Verifying needs them joined back, in\n * that order, which is what `reconstructHonkProof` does.\n */\nimport { CIRCUIT_VK_PATHS, type CircuitId } from './circuits';\n\n/**\n * Where verification keys are published.\n *\n * Not configurable, deliberately: a caller who could point this somewhere else\n * could point it at a key of their choosing, and \"the proof verified\" would\n * then mean nothing. Same repository the mobile app downloads circuit data\n * from.\n */\nconst CIRCUITS_VK_BASE =\n 'https://raw.githubusercontent.com/zkproofport/circuits/main';\n\n/** How long a fetched verification key is reused. Keys change only on a recompile. */\nconst VK_CACHE_TTL_MS = 60 * 60 * 1000;\n\nconst vkCache = new Map<string, { vk: Uint8Array; at: number }>();\n\nexport interface OffChainVerifyResult {\n valid: boolean;\n error?: string;\n}\n\nexport interface OffChainVerifyOptions {\n /**\n * Verification key bytes, if the caller already has them. Skips the fetch —\n * useful offline, in tests, and for anyone who would rather pin the key they\n * checked than trust a download.\n */\n verificationKey?: Uint8Array;\n /** Milliseconds before the fetch is abandoned. Default 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Make sure a Node-shaped `Buffer` exists before Barretenberg is loaded.\n *\n * WHY THE SDK DOES THIS RATHER THAN THE CALLER. bb.js's own BROWSER build —\n * not just its node build — converts field elements through `Buffer.alloc` and\n * `buf.writeBigUInt64BE`. Browsers have no Buffer, and bundlers stopped\n * polyfilling Node globals years ago, so in a browser the first verification\n * dies with \"r.writeBigUInt64BE is not a function\" — a message that names\n * nothing a caller could act on. Measured on the demo page, 2026-09-04, against\n * a real GIWA proof.\n *\n * Leaving it to callers would mean every browser customer editing their\n * bundler config to make an SDK method work, which is the configuration this\n * SDK promises not to require.\n *\n * Deliberately narrow:\n * - It only fills a GAP. A real Buffer (Node, or a page that already has one)\n * is left alone, so nothing is shadowed by a lesser implementation.\n * - It checks for the METHOD, not just the global. A partial Buffer — which is\n * what several bundlers leave behind, and what the demo page actually had —\n * passes a `typeof Buffer` test and then fails inside Barretenberg.\n */\nasync function ensureBufferForBarretenberg(): Promise<void> {\n const existing = (globalThis as { Buffer?: { alloc?: (n: number) => unknown } }).Buffer;\n if (existing?.alloc) {\n const probe = existing.alloc(8) as { writeBigUInt64BE?: unknown };\n if (typeof probe.writeBigUInt64BE === 'function') return;\n }\n const { Buffer } = await import('buffer/');\n (globalThis as { Buffer?: unknown }).Buffer = Buffer;\n}\n\n/** @internal Hex string (with or without 0x) to bytes. */\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length === 0) return new Uint8Array(0);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has an odd length (${clean.length}); it cannot be bytes`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('Hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/**\n * @internal Public inputs as the flat byte run Barretenberg expects: each one a\n * 32-byte big-endian field element, concatenated in order.\n *\n * The relay carries them as hex strings that are USUALLY already 32 bytes, but\n * a value that happens to have leading zeros can arrive short (`0x01`). Left-\n * padding here rather than trusting the sender is the difference between a\n * verification that works and one that fails on roughly one proof in a hundred,\n * for no reason the caller can see.\n */\nfunction packPublicInputs(publicInputs: string[]): Uint8Array {\n const out = new Uint8Array(publicInputs.length * 32);\n publicInputs.forEach((input, i) => {\n const bytes = hexToBytes(input);\n if (bytes.length > 32) {\n throw new Error(\n `Public input ${i} is ${bytes.length} bytes; a field element is at most 32`\n );\n }\n out.set(bytes, i * 32 + (32 - bytes.length));\n });\n return out;\n}\n\n/**\n * Fetch a circuit's verification key, with a small cache.\n *\n * @internal\n */\nasync function fetchVerificationKey(\n circuit: CircuitId,\n timeoutMs: number\n): Promise<Uint8Array> {\n const cached = vkCache.get(circuit);\n if (cached && Date.now() - cached.at < VK_CACHE_TTL_MS) return cached.vk;\n\n const vkPath = CIRCUIT_VK_PATHS[circuit];\n if (!vkPath) {\n throw new Error(\n `No verification key path for circuit '${circuit}'. ` +\n `Add it to CIRCUIT_VK_PATHS, or pass verificationKey directly.`\n );\n }\n\n const url = `${CIRCUITS_VK_BASE}/${vkPath}`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const resp = await fetch(url, { signal: controller.signal });\n if (!resp.ok) {\n throw new Error(`Could not fetch the verification key (HTTP ${resp.status}) from ${url}`);\n }\n const vk = new Uint8Array(await resp.arrayBuffer());\n // A 404 page or an HTML redirect arrives as a successful response full of\n // text, and would reach Barretenberg as a \"verification key\" that fails for\n // reasons no one could guess from the message.\n if (vk.length < 512) {\n throw new Error(\n `The verification key at ${url} is ${vk.length} bytes, far too small to be one. ` +\n `The path is probably wrong and something else was served.`\n );\n }\n vkCache.set(circuit, { vk, at: Date.now() });\n return vk;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Verify a proof off-chain, against its verification key.\n *\n * Needs no setup from the caller: the verifier ships with this SDK and is\n * loaded on first use.\n *\n * @param circuit - Canonical circuit identifier\n * @param proof - Proof bytes as hex, WITHOUT public inputs (as the relay sends it)\n * @param publicInputs - Public inputs as hex strings, in circuit order\n * @param options - Optional verification key and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` when the check could not run\n *\n * @example\n * ```typescript\n * const result = await verifyProofOffChain(\n * 'coinbase_attestation',\n * response.proof,\n * response.publicInputs\n * );\n * if (result.valid) console.log('Proof is valid, no chain involved');\n * ```\n */\nexport async function verifyProofOffChain(\n circuit: CircuitId,\n proof: string,\n publicInputs: string[],\n options: OffChainVerifyOptions = {}\n): Promise<OffChainVerifyResult> {\n const timeoutMs = options.timeoutMs ?? 30000;\n\n // A REQUIRED dependency, loaded lazily.\n //\n // It was briefly an optional peer dependency, on the reasoning that the WASM\n // is 16MB and most callers verify on-chain. That was wrong: it would have\n // meant a customer calling this method got an error telling them to install\n // something, and \"works with zero customer configuration\" is the SDK's rule.\n // A caller should never have to know this is implemented with Barretenberg.\n //\n // The dynamic import is what keeps the cost off everyone else — a bundler\n // splits it out, and a caller who never verifies off-chain never loads it.\n // Before bb.js, not after: its module-level code already reaches for Buffer.\n await ensureBufferForBarretenberg();\n\n let bb: typeof import('@aztec/bb.js');\n try {\n bb = await import('@aztec/bb.js');\n } catch (error) {\n // Reaching here means the install is broken, not that something is missing\n // by design. Say so, rather than sending the caller off to install a\n // package they should never have had to hear about.\n return {\n valid: false,\n error:\n 'Could not load the proof verifier (@aztec/bb.js), which ships with this ' +\n 'SDK. This usually means a broken or partial install — try reinstalling ' +\n `@zkproofport-app/sdk. Underlying error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n let api:\n | {\n initSRSForCircuitSize(size: number): Promise<void>;\n acirVerifyUltraKeccakZkHonk(p: Uint8Array, v: unknown): Promise<boolean>;\n destroy(): Promise<void>;\n }\n | undefined;\n try {\n const proofBytes = hexToBytes(proof);\n if (proofBytes.length === 0) {\n return { valid: false, error: 'Proof is empty' };\n }\n const publicInputBytes = packPublicInputs(publicInputs);\n\n const vk =\n options.verificationKey ?? (await fetchVerificationKey(circuit, timeoutMs));\n\n // Public inputs first, then the proof — the order Barretenberg wrote them in\n // before the mobile app split them apart for the Solidity verifier.\n const full = bb.reconstructHonkProof(publicInputBytes, proofBytes);\n\n api = (await bb.Barretenberg.new({ threads: 1 })) as unknown as typeof api;\n\n // THE VERIFY MUST MATCH HOW THE PROOF WAS MADE, AND THERE ARE FOUR OF THEM.\n //\n // `scripts/build.sh` in the circuits repo proves with `--oracle_hash keccak`\n // and ZK on — so the only entry point that answers correctly is the one that\n // is BOTH. Measured against a real proof of the Korea Mobile ID age circuit,\n // freshly generated against its own key:\n //\n // acirVerifyUltraKeccakZkHonk true ← the right one\n // acirVerifyUltraKeccakHonk TRAPS with a bare \"unreachable\"\n // acirVerifyUltraZKHonk false (poseidon: wrong oracle hash)\n //\n // The middle row is why this took a while: picking keccak-without-ZK does\n // not return false, it kills the WebAssembly instance with a message that\n // names nothing. It looks identical to a malformed proof, to a mismatched\n // key, and to a missing SRS.\n //\n // Two more things that produce that same trap, both required:\n // initSRSForCircuitSize must be called before the first verify.\n // The key must be a RawBuffer — a plain Uint8Array is marshalled as a\n // length-prefixed vector, so its length is read as key material.\n // Both are what bb.js's own BarretenbergVerifier does before verifying.\n await api!.initSRSForCircuitSize(0);\n const valid = await api!.acirVerifyUltraKeccakZkHonk(full, new bb.RawBuffer(vk));\n return { valid };\n } catch (error) {\n return { valid: false, error: error instanceof Error ? error.message : String(error) };\n } finally {\n // The WASM instance holds worker threads; leaving them running keeps a Node\n // process alive after the check is done.\n if (api) {\n try {\n await api.destroy();\n } catch {\n /* nothing useful to do if teardown fails */\n }\n }\n }\n}\n\n/** @internal Test seam — lets a test start from a known-empty cache. */\nexport function clearVerificationKeyCache(): void {\n vkCache.clear();\n}\n","/**\n * Proofport SDK - Main class\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitType,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n ProofportConfig,\n QRCodeOptions,\n ParsedProof,\n VerifierContract,\n ChallengeResponse,\n WalletSigner,\n RelayProofRequest,\n RelayProofResult,\n} from './types';\nimport {\n generateRequestId,\n buildProofRequestUrl,\n buildCallbackUrl,\n parseProofRequestUrl,\n parseProofResponseUrl,\n validateProofRequest,\n validateMdlInputs,\n validateReturnScheme,\n detectReturnScheme,\n isProofportDeepLink,\n} from './deeplink';\nimport {\n generateQRCodeDataUrl,\n generateQRCodeSVG,\n generateQRCodeToCanvas,\n estimateQRDataSize,\n} from './qrcode';\nimport {\n verifyProofOnChain,\n parseProofForOnChain,\n getVerifierAddress,\n getVerifierChainId,\n getDefaultProvider,\n extractScopeFromPublicInputs,\n extractNullifierFromPublicInputs,\n extractDomainFromPublicInputs,\n} from './verifier';\nimport {\n verifyProofOffChain,\n type OffChainVerifyOptions,\n} from './offChainVerifier';\nimport {\n DEFAULT_SCHEME,\n DEFAULT_REQUEST_EXPIRY_MS,\n CIRCUIT_METADATA,\n RELAY_URLS,\n} from './constants';\nimport { CIRCUIT_NEEDS_WALLET_SIGNATURE, type CircuitId } from './circuits';\nimport { validateTypedAction } from './typedAction';\nimport type { SDKEnvironment } from './types';\n\n\n/**\n * Main SDK class for interacting with the ZKProofport mobile app.\n *\n * Provides methods for creating proof requests, generating QR codes and deep links,\n * verifying proofs on-chain, and handling proof responses from the mobile app.\n *\n * @example\n * ```typescript\n * import { ProofportSDK } from '@zkproofport-app/sdk';\n * import { BrowserProvider } from 'ethers';\n *\n * // Initialize SDK (uses production relay by default)\n * const sdk = ProofportSDK.create();\n *\n * // Set wallet signer for challenge-signature auth\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n *\n * // Create proof request via relay\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * });\n *\n * // Generate QR code for desktop users\n * const qrDataUrl = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof via WebSocket (primary) or polling (fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof received:', result.proof);\n * }\n * ```\n */\nexport class ProofportSDK {\n private config: Required<Omit<ProofportConfig, 'relayUrl'>>;\n private pendingRequests: Map<string, ProofRequest> = new Map();\n private signer: WalletSigner | null = null;\n private relayUrl: string;\n private socket: any = null;\n\n /**\n * Creates a new ProofportSDK instance.\n *\n * For most use cases, prefer the static factory with environment presets:\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * ```\n *\n * @param config - SDK configuration options\n * @param config.scheme - Custom deep link scheme (default: 'zkproofport')\n * @param config.relayUrl - Relay server URL (required for relay features)\n * @param config.verifiers - Custom verifier contract addresses per circuit\n *\n * @example\n * ```typescript\n * const sdk = new ProofportSDK({\n * relayUrl: 'https://relay.zkproofport.app',\n * verifiers: {\n * coinbase_attestation: {\n * verifierAddress: '0x...',\n * chainId: 1\n * }\n * }\n * });\n * ```\n */\n constructor(config: ProofportConfig = {}) {\n this.config = {\n scheme: config.scheme || DEFAULT_SCHEME,\n verifiers: config.verifiers || {},\n };\n this.relayUrl = config.relayUrl || '';\n }\n\n // ============ Request Creation ============\n\n /**\n * @internal\n * Creates a Coinbase KYC verification proof request.\n *\n * Generates a proof request for verifying Coinbase KYC status without revealing\n * the actual attestation data. The proof confirms the user has passed Coinbase KYC\n * while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase KYC\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your KYC status to access this feature'\n * });\n *\n * const deepLink = sdk.getDeepLinkUrl(request);\n * ```\n */\n private createCoinbaseKycRequest(\n inputs: CoinbaseKycInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a Coinbase Country attestation proof request.\n *\n * Generates a proof request for verifying country eligibility through Coinbase\n * attestation without revealing the actual country data. The proof confirms the\n * user's country status while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase Country attestation\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseCountryRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your country eligibility'\n * });\n * ```\n */\n private createCoinbaseCountryRequest(\n inputs: CoinbaseCountryInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_country_attestation circuit');\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n throw new Error('countryList is required for coinbase_country_attestation circuit');\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n throw new Error('isIncluded is required for coinbase_country_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_country_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a generic proof request for any supported circuit type.\n *\n * Routes to the appropriate circuit-specific request creation method based on\n * the circuit type. Use this for dynamic circuit selection or when the circuit\n * type is determined at runtime.\n *\n * @param circuit - Circuit type identifier ('coinbase_attestation' | 'coinbase_country_attestation')\n * @param inputs - Circuit-specific inputs\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 15 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if required inputs are missing for the specified circuit\n *\n * @example\n * ```typescript\n * const circuitType = userSelection; // Dynamic selection\n * const request = sdk.createProofRequest(\n * circuitType,\n * { scope: 'myapp.com' },\n * { dappName: 'My DApp' }\n * );\n * ```\n */\n private createProofRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (circuit === 'coinbase_country_attestation') {\n return this.createCoinbaseCountryRequest(inputs as CoinbaseCountryInputs, options);\n } else if (\n circuit === 'mdl_kr_ownership' ||\n circuit === 'mdl_kr_age' ||\n circuit === 'mdl_kr_region'\n ) {\n return this.createMdlKrRequest(circuit, inputs, options);\n } else {\n return this.createCoinbaseKycRequest(inputs as CoinbaseKycInputs, options);\n }\n }\n\n /**\n * @internal\n * Creates a Korea Mobile ID (mDL) proof request for any of the three\n * mDL predicate circuits (ownership / age / region).\n *\n * The mobile app collects the license data on-device; the dapp only\n * supplies the predicate parameters validated here. No wallet signature\n * is required for mDL circuits.\n *\n * @param circuit - 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region'\n * @param inputs - Predicate inputs (see MdlKr*Inputs types)\n * @param options - Request configuration options\n *\n * @throws Error if the predicate inputs fail validation\n */\n private createMdlKrRequest(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit,\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n // ============ Deep Link Generation ============\n\n /**\n * @internal\n * Generates a deep link URL for a proof request.\n *\n * Creates a zkproofport:// URL that opens the ZKProofport mobile app with the\n * specified proof request. The URL contains all request details encoded as query\n * parameters.\n *\n * @param request - ProofRequest object to encode as deep link\n *\n * @returns Deep link URL string (e.g., 'zkproofport://proof?requestId=...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const url = sdk.getDeepLinkUrl(request);\n * // url: 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...'\n * ```\n */\n private getDeepLinkUrl(request: ProofRequest): string {\n return buildProofRequestUrl(request, this.config.scheme);\n }\n\n /**\n * @internal\n * Opens the ZKProofport mobile app with a proof request.\n *\n * Redirects the browser to the deep link URL, which opens the ZKProofport app\n * if installed. Only works in mobile browser environments. For desktop, use\n * requestProof() to display a QR code instead.\n *\n * @param request - ProofRequest object to send to the app\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * if (ProofportSDK.isMobile()) {\n * sdk.openProofRequest(request); // Opens app directly\n * }\n * ```\n */\n private openProofRequest(request: ProofRequest): void {\n const url = this.getDeepLinkUrl(request);\n window.location.href = url;\n }\n\n /**\n * @internal\n * Requests a proof with automatic platform detection.\n *\n * Detects whether the user is on mobile or desktop and automatically chooses\n * the appropriate flow:\n * - Mobile: Opens the deep link directly to launch the ZKProofport app\n * - Desktop: Generates a QR code data URL for the user to scan\n *\n * @param request - ProofRequest object to send\n * @param qrOptions - QR code generation options (size, colors, logo) for desktop\n *\n * @returns Object containing deep link URL, optional QR code data URL, and platform detection result\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const result = await sdk.requestProof(request);\n *\n * if (result.mobile) {\n * console.log('Opening app directly');\n * } else {\n * // Display QR code for desktop users\n * document.getElementById('qr').src = result.qrDataUrl;\n * }\n * ```\n */\n private async requestProof(\n request: ProofRequest,\n qrOptions?: QRCodeOptions\n ): Promise<{ deepLink: string; qrDataUrl?: string; mobile: boolean }> {\n const deepLink = this.getDeepLinkUrl(request);\n const mobile = ProofportSDK.isMobile();\n\n if (mobile) {\n window.location.href = deepLink;\n return { deepLink, mobile: true };\n }\n\n const qrDataUrl = await this.generateQRCode(request, qrOptions);\n return { deepLink, qrDataUrl, mobile: false };\n }\n\n // ============ QR Code Generation ============\n\n /**\n * Generates a QR code as a data URL for a proof request.\n *\n * Creates a PNG image data URL that can be directly set as an img src attribute.\n * Suitable for embedding QR codes in web pages for desktop users to scan with\n * their mobile device.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n * @param options.logoUrl - Optional center logo image URL\n * @param options.logoSize - Logo size as fraction of QR code (default: 0.2)\n *\n * @returns Promise resolving to PNG data URL (e.g., 'data:image/png;base64,...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const qrUrl = await sdk.generateQRCode(request, {\n * size: 400,\n * darkColor: '#1a1a1a',\n * logoUrl: 'https://myapp.com/logo.png'\n * });\n * document.getElementById('qr-image').src = qrUrl;\n * ```\n */\n async generateQRCode(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeDataUrl(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Generates a QR code as an SVG string for a proof request.\n *\n * Creates a scalable vector graphics representation of the QR code, ideal for\n * high-resolution displays or when vector format is preferred over raster images.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise resolving to SVG string\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const svgString = await sdk.generateQRCodeSVG(request);\n * document.getElementById('qr-container').innerHTML = svgString;\n * ```\n */\n async generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeSVG(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Draws the QR code onto the provided canvas element, useful for custom\n * rendering workflows or when you need direct canvas manipulation.\n *\n * @param canvas - HTML canvas element to render to\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise that resolves when rendering is complete\n *\n * @example\n * ```typescript\n * const canvas = document.getElementById('qr-canvas') as HTMLCanvasElement;\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * await sdk.renderQRCodeToCanvas(canvas, request, { size: 400 });\n * ```\n */\n async renderQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<void> {\n return generateQRCodeToCanvas(canvas, requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Checks if a proof request fits within QR code size limits.\n *\n * Estimates the encoded data size and validates it against QR code capacity limits.\n * Useful for validating requests before generating QR codes, especially when\n * including large custom messages or metadata.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n *\n * @returns Object with size in bytes and whether it fits within limits\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const check = sdk.checkQRCodeSize(request);\n * if (!check.withinLimit) {\n * console.warn(`Request too large: ${check.size} bytes`);\n * }\n * ```\n */\n checkQRCodeSize(requestOrUrl: ProofRequest | string): { size: number; withinLimit: boolean } {\n return estimateQRDataSize(requestOrUrl, this.config.scheme);\n }\n\n // ============ Response Handling ============\n\n /**\n * @internal\n * Parses a proof response from a callback URL.\n *\n * Extracts and decodes proof response data from the callback URL query parameters\n * after the user completes proof generation in the ZKProofport app. The app\n * redirects to your callback URL with the proof data encoded as query parameters.\n *\n * @param url - Callback URL containing proof response data\n *\n * @returns ProofResponse object with status, proof data, and public inputs, or null if invalid\n *\n * @example\n * ```typescript\n * // In your callback endpoint handler\n * app.get('/callback', (req, res) => {\n * const callbackUrl = req.url;\n * const response = sdk.parseResponse(callbackUrl);\n *\n * if (response?.status === 'completed') {\n * console.log('Proof received:', response.proof);\n * console.log('Public inputs:', response.publicInputs);\n * } else if (response?.status === 'rejected') {\n * console.log('User rejected the request');\n * }\n * });\n * ```\n */\n private parseResponse(url: string): ProofResponse | null {\n return parseProofResponseUrl(url);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport proof response callback.\n *\n * Validates whether the given URL contains the required query parameters for a\n * proof response. Useful for filtering and routing callback requests.\n *\n * @param url - URL to check\n *\n * @returns True if the URL appears to be a ZKProofport response callback\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n * if (sdk.isProofportResponse(fullUrl)) {\n * const response = sdk.parseResponse(fullUrl);\n * // Handle proof response\n * }\n * });\n * ```\n */\n private isProofportResponse(url: string): boolean {\n try {\n const urlObj = new URL(url);\n return urlObj.searchParams.has('requestId') && urlObj.searchParams.has('status');\n } catch {\n return false;\n }\n }\n\n /**\n * @internal\n * Retrieves a pending proof request by its ID.\n *\n * Looks up a previously created proof request from the SDK's internal cache.\n * Useful for validating callback responses and maintaining request state.\n *\n * @param requestId - Unique request identifier\n *\n * @returns ProofRequest object if found, undefined otherwise\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * const originalRequest = sdk.getPendingRequest(response.requestId);\n *\n * if (originalRequest) {\n * console.log('Original request:', originalRequest);\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private getPendingRequest(requestId: string): ProofRequest | undefined {\n return this.pendingRequests.get(requestId);\n }\n\n /**\n * @internal\n * Clears a pending proof request from the internal cache.\n *\n * Removes a proof request from the SDK's pending requests map. Should be called\n * after successfully processing a proof response to prevent memory leaks.\n *\n * @param requestId - Unique request identifier to remove\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * if (response?.status === 'completed') {\n * // Process proof...\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private clearPendingRequest(requestId: string): void {\n this.pendingRequests.delete(requestId);\n }\n\n // ============ Verification ============\n\n /**\n * Verifies a zero-knowledge proof on-chain using the deployed verifier contract.\n *\n * Calls the Solidity verifier contract to cryptographically verify the proof's\n * validity. This ensures the proof was generated correctly and the public inputs\n * match the claimed values.\n *\n * @param circuit - Circuit type identifier\n * @param proof - Hex-encoded proof string from the ZKProofport app\n * @param publicInputs - Array of hex-encoded public input strings\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * const response = sdk.parseResponse(callbackUrl);\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyOnChain(\n * response.circuit,\n * response.proof,\n * response.publicInputs,\n * provider\n * );\n *\n * if (result.valid) {\n * console.log('Proof verified on-chain!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * }\n * ```\n */\n async verifyOnChain(\n circuit: CircuitType,\n proof: string,\n publicInputs: string[],\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n const parsedProof = parseProofForOnChain(\n proof,\n publicInputs,\n publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[circuit];\n return verifyProofOnChain(circuit, parsedProof, providerOrSigner, customVerifier);\n }\n\n /**\n * Verifies a proof response on-chain using the deployed verifier contract.\n *\n * Convenience method that extracts proof data from a ProofResponse object and\n * verifies it on-chain. Automatically handles incomplete or rejected responses.\n *\n * @param response - ProofResponse object from parseResponse()\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * app.get('/callback', async (req, res) => {\n * const response = sdk.parseResponse(req.url);\n *\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyResponseOnChain(response, provider);\n *\n * if (result.valid) {\n * // Grant access to user\n * res.json({ success: true, verified: true });\n * } else {\n * res.status(400).json({ error: result.error });\n * }\n * } else {\n * res.status(400).json({ error: 'Proof generation failed or rejected' });\n * }\n * });\n * ```\n */\n async verifyResponseOnChain(\n response: ProofResponse,\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n\n const parsedProof = parseProofForOnChain(\n response.proof,\n response.publicInputs,\n response.publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[response.circuit];\n const responseVerifier = {\n verifierAddress: response.verifierAddress,\n chainId: response.chainId,\n };\n return verifyProofOnChain(response.circuit, parsedProof, providerOrSigner, customVerifier, responseVerifier);\n }\n\n /**\n * Verifies a proof response off-chain, against the circuit's verification key.\n *\n * No chain, no RPC, no gas, and no verifier contract — so this works for a\n * circuit whose verifier has not been deployed anywhere, and it does not\n * depend on a network being reachable. What it does not give you is the\n * chain's own opinion: use {@link verifyResponseOnChain} when the answer has\n * to be one a contract will agree with.\n *\n * Needs no setup: the verifier ships with this SDK. It is loaded on first\n * use, so a caller who only verifies on-chain never pays for it.\n *\n * @param response - Proof response from the relay\n * @param options - Optional verification key (skips the fetch) and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` if the check could not run\n *\n * @example\n * ```typescript\n * const result = await sdk.verifyResponseOffChain(response);\n * if (result.valid) {\n * console.log('Valid, and nothing was asked of any chain');\n * }\n * ```\n */\n async verifyResponseOffChain(\n response: ProofResponse,\n options?: OffChainVerifyOptions\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n return verifyProofOffChain(\n response.circuit,\n response.proof,\n response.publicInputs,\n options\n );\n }\n\n // ============ Utility Methods ============\n\n /**\n * Gets the deployed verifier contract address for a circuit.\n *\n * Returns the Ethereum address of the Solidity verifier contract for the\n * specified circuit. Uses custom verifier if configured, otherwise returns\n * the default deployed address.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Ethereum address of the verifier contract (0x...)\n *\n * @example\n * ```typescript\n * const address = sdk.getVerifierAddress('coinbase_attestation');\n * console.log('Verifier deployed at:', address);\n * ```\n */\n getVerifierAddress(circuit: CircuitType): string {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierAddress(circuit, customVerifier);\n }\n\n /**\n * Gets the blockchain chain ID where the verifier contract is deployed.\n *\n * Returns the EIP-155 chain ID for the network where the verifier contract\n * is deployed. Uses custom verifier if configured, otherwise returns the\n * default chain ID (Base mainnet: 8453).\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Chain ID number (e.g., 8453 for Base mainnet)\n *\n * @example\n * ```typescript\n * const chainId = sdk.getVerifierChainId('coinbase_attestation');\n * console.log('Verifier on chain:', chainId); // 8453 (Base mainnet)\n * ```\n */\n getVerifierChainId(circuit: CircuitType): number {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierChainId(circuit, customVerifier);\n }\n\n /**\n * Gets metadata for a specific circuit type.\n *\n * Returns circuit metadata including display name, description, required inputs,\n * and other configuration details.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Circuit metadata object with name, description, and configuration\n *\n * @example\n * ```typescript\n * const metadata = sdk.getCircuitMetadata('coinbase_attestation');\n * console.log('Circuit name:', metadata.name);\n * console.log('Description:', metadata.description);\n * ```\n */\n getCircuitMetadata(circuit: CircuitType) {\n return CIRCUIT_METADATA[circuit];\n }\n\n /**\n * Gets all supported circuit types.\n *\n * Returns an array of all circuit type identifiers that are currently supported\n * by the SDK and ZKProofport app.\n *\n * @returns Array of supported circuit type identifiers\n *\n * @example\n * ```typescript\n * const circuits = sdk.getSupportedCircuits();\n * console.log('Supported circuits:', circuits);\n * // ['coinbase_attestation', 'coinbase_country_attestation']\n * ```\n */\n getSupportedCircuits(): CircuitType[] {\n return Object.keys(CIRCUIT_METADATA) as CircuitType[];\n }\n\n /**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Checks that the proof request contains all required fields and that the\n * circuit-specific inputs are valid. Useful for catching configuration errors\n * before generating QR codes or sending requests to users.\n *\n * @param request - ProofRequest object to validate\n *\n * @returns Validation result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const validation = sdk.validateRequest(request);\n *\n * if (!validation.valid) {\n * console.error('Invalid request:', validation.error);\n * }\n * ```\n */\n private validateRequest(request: ProofRequest): { valid: boolean; error?: string } {\n return validateProofRequest(request);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport deep link.\n *\n * Validates whether the given URL uses the ZKProofport deep link scheme\n * (zkproofport:// by default) and has the correct format for a proof request.\n *\n * @param url - URL string to check\n *\n * @returns True if the URL is a valid ZKProofport deep link\n *\n * @example\n * ```typescript\n * const url = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation';\n * if (sdk.isProofportDeepLink(url)) {\n * const request = sdk.parseDeepLink(url);\n * console.log('Parsed request:', request);\n * }\n * ```\n */\n private isProofportDeepLink(url: string): boolean {\n return isProofportDeepLink(url, this.config.scheme);\n }\n\n /**\n * @internal\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a zkproofport:// deep link URL.\n * Useful for handling deep link navigation in web applications or validating\n * deep link URLs before displaying QR codes.\n *\n * @param url - ZKProofport deep link URL string\n *\n * @returns ProofRequest object with all request details, or null if invalid\n *\n * @example\n * ```typescript\n * const deepLink = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...';\n * const request = sdk.parseDeepLink(deepLink);\n *\n * if (request) {\n * console.log('Request ID:', request.requestId);\n * console.log('Circuit:', request.circuit);\n * }\n * ```\n */\n private parseDeepLink(url: string): ProofRequest | null {\n return parseProofRequestUrl(url);\n }\n\n // ============ Static Factory ============\n\n /**\n * Creates a new ProofportSDK instance with environment preset or custom config.\n * Defaults to `'production'` if no argument is provided.\n *\n * **Recommended usage** — use the default production relay:\n * ```typescript\n * const sdk = ProofportSDK.create();\n * ```\n *\n * Environment presets:\n * - `'production'` — relay.zkproofport.app (default)\n * - `'staging'` — stg-relay.zkproofport.app\n * - `'local'` — localhost:4001\n *\n * @param envOrConfig - Environment name or custom SDK configuration\n *\n * @returns New ProofportSDK instance\n *\n * @example\n * ```typescript\n * // Environment preset (recommended)\n * const sdk = ProofportSDK.create(); // production (default)\n * const sdk = ProofportSDK.create('staging');\n *\n * // Custom config\n * const sdk = ProofportSDK.create({\n * relayUrl: 'https://my-custom-relay.example.com',\n * });\n * ```\n */\n static create(envOrConfig?: SDKEnvironment | ProofportConfig): ProofportSDK {\n if (typeof envOrConfig === 'undefined') {\n return new ProofportSDK({ relayUrl: RELAY_URLS.production });\n }\n if (typeof envOrConfig === 'string') {\n const relayUrl = RELAY_URLS[envOrConfig];\n if (!relayUrl) {\n throw new Error(`Unknown environment: ${envOrConfig}. Use 'production', 'staging', or 'local'.`);\n }\n return new ProofportSDK({ relayUrl });\n }\n return new ProofportSDK(envOrConfig);\n }\n\n /**\n * Detects if the code is running on a mobile device.\n *\n * Uses user agent detection to determine if the current environment is a mobile\n * browser. This helps the SDK automatically choose between direct deep link\n * navigation (mobile) and QR code display (desktop).\n *\n * @returns True if running on a mobile device (iOS, Android, etc.)\n *\n * @example\n * ```typescript\n * if (ProofportSDK.isMobile()) {\n * // Open deep link directly\n * sdk.openProofRequest(request);\n * } else {\n * // Show QR code\n * const qr = await sdk.generateQRCode(request);\n * displayQRCode(qr);\n * }\n * ```\n */\n static isMobile(): boolean {\n if (typeof navigator === 'undefined') return false;\n return /Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n }\n\n // ============ Relay Integration ============\n\n /**\n * Sets the wallet signer for challenge-signature authentication.\n * The signer will be used to sign challenges from the relay server.\n *\n * @param signer - Wallet signer (ethers v6 Signer or compatible object with signMessage/getAddress)\n *\n * @example\n * ```typescript\n * import { BrowserProvider } from 'ethers';\n *\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n * ```\n */\n setSigner(signer: WalletSigner): void {\n this.signer = signer;\n }\n\n /**\n * Fetches a random challenge from the relay server.\n * The challenge must be signed and included in proof requests.\n *\n * @returns Promise resolving to ChallengeResponse with challenge hex and expiry\n * @throws Error if relayUrl is not configured\n */\n async getChallenge(): Promise<ChallengeResponse> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/challenge`);\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Failed to get challenge: HTTP ${response.status}`);\n }\n\n return await response.json() as ChallengeResponse;\n }\n\n /**\n * Creates a proof request through the relay server.\n *\n * This is the recommended way to create proof requests. The relay server:\n * - Issues a server-side requestId (validated by the mobile app)\n * - Tracks request status in Redis\n * - Builds the deep link with relay callback URL\n * - Stores inputs hash for deep link integrity verification\n *\n * @param circuit - Circuit type identifier\n * @param inputs - Circuit-specific inputs\n * @param options - Request options (message, dappName, dappIcon, nonce, returnScheme)\n * @param options.returnScheme - Which app the ZKProofport app should switch back\n * to once it has finished. Put **your own** deep link scheme here — the bare\n * scheme your app registers, e.g. `'mydapp://'`. Only a native app has an\n * answer to this question; a web app omits the option entirely, because\n * opening its https origin would launch a new browser tab on a fresh page\n * rather than return the user to the tab they started from.\n *\n * This is intentionally **not** a URL and not a return address: no path, query\n * string or fragment is accepted, and the ZKProofport app never sends the proof\n * there. The proof still comes back to you the same way it always did — over the\n * relay, via `waitForProof()` / `waitForResult()`. `returnScheme` only answers\n * \"which app should come back to the foreground\", exactly like the\n * `redirect.native` value a wallet uses to hand control back after signing.\n *\n * **Omit it and the SDK decides for you.** When the request is created from a\n * page running in Chrome for iOS (`CriOS`) or Firefox for iOS (`FxiOS`), the\n * SDK fills in `'googlechrome://'` or `'firefox://'` by itself: opening either\n * scheme bare brings that browser forward without navigating, so the user lands\n * back on the tab they were already reading. Every other browser sends nothing,\n * because nothing safe exists to send — Safari has no such scheme, and Brave\n * and Arc are indistinguishable from Safari on iOS, so guessing would eject the\n * user into the wrong browser.\n * On Android nothing is needed at all: the ZKProofport app brings itself to the\n * back and the browser resumes exactly as it was. When no target is sent and\n * none can be inferred, the ZKProofport app tells the user the proof was\n * delivered and lets them switch back themselves.\n *\n * There is no auto-switch on proof failure; only on success and on the user\n * declining the request.\n *\n * Rejected with an error before the request is sent: empty or whitespace values,\n * anything longer than 128 characters, values carrying a host/path/query/fragment\n * (including https origins such as `'https://myapp.com'`), and the `http:`,\n * `file:`, `data:`, `javascript:`, `intent:`, `tel:`, `sms:`, `mailto:` families.\n * @returns Promise resolving to RelayProofRequest with requestId, deepLink, pollUrl\n * @throws Error if signer not set, returnScheme is malformed, or the relay request fails\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create();\n * sdk.setSigner(signer);\n *\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * }, { dappName: 'My DApp', returnScheme: 'mydapp://' });\n *\n * // Generate QR code from relay deep link\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof (WebSocket primary, polling fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * ```\n */\n // Which circuits need a wallet signature, from the one record in\n // src/circuits.ts. The typed-out pair that used to sit here had missed\n // arc_eligibility, so a dapp calling createRelayRequest() for it with no\n // signer got no local error and a relay 401 two round trips later.\n private static needsWalletSignature(circuit: CircuitType): boolean {\n return CIRCUIT_NEEDS_WALLET_SIGNATURE[circuit as CircuitId] === true;\n }\n\n async createRelayRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n nonce?: string;\n returnScheme?: string;\n } = {}\n ): Promise<RelayProofRequest> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const needsSignature = ProofportSDK.needsWalletSignature(circuit);\n\n if (needsSignature && !this.signer) {\n throw new Error('Signer not set. Call setSigner() first. Wallet signature is required for this circuit.');\n }\n\n // mDL circuits: validate predicate inputs client-side before hitting the\n // relay, so a bad ageThreshold / targetRegion fails fast with a clear error.\n if (circuit === 'mdl_kr_ownership' || circuit === 'mdl_kr_age' || circuit === 'mdl_kr_region') {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n }\n\n // arc_eligibility: the action is what the proof binds to, so a request\n // without a usable one cannot be honoured. Checked here, before a\n // challenge is burned, because the alternative is a refusal from inside\n // the mobile app -- a screen the dapp developer never sees, reached after\n // the person has already scanned a QR code.\n if (circuit === 'arc_eligibility') {\n const actionError = validateTypedAction((inputs as { action?: unknown }).action);\n if (actionError) {\n throw new Error(`${actionError} (circuit: ${circuit})`);\n }\n }\n\n // Return target: validated before we burn a challenge, so a typo surfaces\n // as a local error instead of a relay 400 on the second round trip.\n if (options.returnScheme !== undefined) {\n const returnSchemeError = validateReturnScheme(options.returnScheme);\n if (returnSchemeError) {\n throw new Error(returnSchemeError);\n }\n }\n\n // Get challenge + requestId from relay\n const { requestId, challenge } = await this.getChallenge();\n\n const body: Record<string, unknown> = {\n requestId,\n circuitId: circuit,\n inputs,\n challenge,\n };\n\n // Sign challenge for circuits that require wallet signature\n if (needsSignature && this.signer) {\n body.signature = await this.signer.signMessage(challenge);\n }\n\n if (options.message) body.message = options.message;\n if (options.dappName) body.dappName = options.dappName;\n if (options.dappIcon) body.dappIcon = options.dappIcon;\n if (options.nonce) body.nonce = options.nonce;\n // An explicit value always wins. Otherwise ask the SDK to work one out from\n // the page's own user agent — the requesting page is the only side that can\n // (iOS tells the app nothing about who launched it). Both paths can end in\n // \"send nothing\", which is a legitimate outcome, not a failure.\n const returnScheme = options.returnScheme ?? detectReturnScheme();\n if (returnScheme) body.returnScheme = returnScheme;\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/request`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Relay request failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofRequest;\n }\n\n /**\n * Polls the relay for proof result status.\n *\n * @param requestId - The relay-issued request ID\n * @returns Promise resolving to RelayProofResult\n * @throws Error if relay URL not configured or request not found\n *\n * @example\n * ```typescript\n * const result = await sdk.pollResult(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof:', result.proof);\n * console.log('Public inputs:', result.publicInputs);\n * }\n * ```\n */\n async pollResult(requestId: string): Promise<RelayProofResult> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/${requestId}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new Error('Request not found or expired');\n }\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Poll failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofResult;\n }\n\n /**\n * Polls the relay until proof is completed or failed, with configurable interval and timeout.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Polling options\n * @param options.intervalMs - Polling interval in milliseconds (default: 2000)\n * @param options.timeoutMs - Maximum polling time in milliseconds (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback when status changes\n * @returns Promise resolving to final RelayProofResult\n * @throws Error if timeout or relay error\n */\n async waitForResult(\n requestId: string,\n options: {\n intervalMs?: number;\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const interval = options.intervalMs || 2000;\n const timeout = options.timeoutMs || 300000;\n const startTime = Date.now();\n let lastStatus = '';\n\n while (Date.now() - startTime < timeout) {\n const result = await this.pollResult(requestId);\n\n if (result.status !== lastStatus) {\n lastStatus = result.status;\n options.onStatusChange?.(result);\n }\n\n if (result.status === 'completed' || result.status === 'failed') {\n return result;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Polling timed out after ${timeout}ms`);\n }\n\n /**\n * Subscribes to real-time proof status updates via Socket.IO.\n *\n * This is the recommended way to receive proof results. Uses WebSocket\n * connection for instant delivery instead of polling.\n *\n * Requires `socket.io-client` package: `npm install socket.io-client`\n *\n * @param requestId - The relay-issued request ID to subscribe to\n * @param callbacks - Event callbacks for status changes and results\n * @param callbacks.onStatus - Called on status updates (pending, generating)\n * @param callbacks.onResult - Called when proof is completed or failed\n * @param callbacks.onError - Called on errors\n * @returns Unsubscribe function to clean up the connection\n * @throws Error if relayUrl not set or socket.io-client not installed\n *\n * @example\n * ```typescript\n * const relay = await sdk.createRelayRequest('coinbase_attestation', { scope: 'myapp.com' });\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * const unsubscribe = await sdk.subscribe(relay.requestId, {\n * onResult: (result) => {\n * if (result.status === 'completed') {\n * console.log('Proof received!', result.proof);\n * }\n * },\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\n async subscribe(\n requestId: string,\n callbacks: {\n onStatus?: (data: { requestId: string; status: string; deepLink?: string }) => void;\n onResult?: (result: RelayProofResult) => void;\n onError?: (error: { error: string; code?: number; requestId?: string }) => void;\n }\n ): Promise<() => void> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n let ioConnect: any;\n try {\n const mod: any = await import('socket.io-client');\n ioConnect = mod.io ?? mod.connect ?? mod.default;\n } catch {\n throw new Error(\n 'socket.io-client is required for real-time updates. Install it: npm install socket.io-client'\n );\n }\n\n if (typeof ioConnect !== 'function') {\n throw new Error('Failed to load socket.io-client: io function not found');\n }\n\n // Connect to relay /proof namespace (no JWT — open connections)\n const socket = ioConnect(`${this.relayUrl}/proof`, {\n path: '/socket.io',\n transports: ['websocket', 'polling'],\n });\n\n this.socket = socket;\n\n // Subscribe to the request room\n socket.on('connect', () => {\n socket.emit('proof:subscribe', { requestId });\n });\n\n // Handle connection errors (e.g. rejected by relay middleware)\n socket.on('connect_error', (err: Error) => {\n console.error(`[ProofportSDK] Socket.IO connect_error for requestId=${requestId}: ${err.message}`);\n callbacks.onError?.({ error: err.message, requestId });\n });\n\n // Listen for events\n if (callbacks.onStatus) {\n socket.on('proof:status', callbacks.onStatus);\n }\n if (callbacks.onResult) {\n socket.on('proof:result', callbacks.onResult);\n }\n if (callbacks.onError) {\n socket.on('proof:error', callbacks.onError);\n }\n\n // Return unsubscribe function\n return () => {\n socket.off('proof:status');\n socket.off('proof:result');\n socket.off('proof:error');\n socket.disconnect();\n if (this.socket === socket) {\n this.socket = null;\n }\n };\n }\n\n /**\n * Waits for a proof result using Socket.IO (primary) with polling fallback.\n *\n * Tries Socket.IO first for real-time delivery. If socket.io-client is not\n * installed or connection fails, automatically falls back to HTTP polling.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Configuration options\n * @param options.timeoutMs - Maximum wait time in ms (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback for status updates\n * @returns Promise resolving to final RelayProofResult\n */\n async waitForProof(\n requestId: string,\n options: {\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult | { requestId: string; status: string; deepLink?: string }) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const timeout = options.timeoutMs || 300000;\n\n // Try Socket.IO first\n if (this.relayUrl) {\n try {\n return await new Promise<RelayProofResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n unsubscribePromise?.then(fn => fn());\n reject(new Error(`Waiting for proof timed out after ${timeout}ms`));\n }, timeout);\n\n const unsubscribePromise = this.subscribe(requestId, {\n onStatus: (data) => {\n options.onStatusChange?.(data);\n },\n onResult: (result) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n resolve(result);\n },\n onError: (error) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n reject(new Error(error.error));\n },\n });\n });\n } catch (err: any) {\n // Re-throw timeout — that's a real failure the caller should handle\n if (err.message?.includes('timed out')) {\n throw err;\n }\n // socket.io-client missing or connection failed → fall back to polling silently\n console.warn('Socket.IO unavailable, falling back to HTTP polling:', err.message);\n }\n }\n\n // Fallback: HTTP polling\n return this.waitForResult(requestId, {\n timeoutMs: timeout,\n onStatusChange: options.onStatusChange as any,\n });\n }\n\n /**\n * Disconnects the Socket.IO connection if active.\n */\n disconnect(): void {\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n // ============ Public Input Utilities ============\n\n /**\n * Extracts the scope from proof public inputs.\n *\n * The scope is an application-specific identifier (e.g., domain name) encoded\n * as bytes32 in the proof's public inputs.\n *\n * @param publicInputs - Array of public input hex strings from proof response\n * @param circuit - Circuit type to determine field positions\n * @returns Scope as hex string (0x...), or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const scope = sdk.extractScope(result.publicInputs, result.circuit);\n * console.log('Scope:', scope);\n * }\n * ```\n */\n extractScope(publicInputs: string[], circuit: CircuitType): string | null {\n return extractScopeFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the nullifier (bytes32) from proof public inputs.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const nullifier = sdk.extractNullifier(result.publicInputs, result.circuit);\n * console.log('Nullifier:', nullifier); // '0xabc123...'\n * }\n * ```\n */\n extractNullifier(publicInputs: string[], circuit: CircuitType): string | null {\n return extractNullifierFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the domain string from OIDC Domain Attestation proof public inputs.\n *\n * Only works with 'oidc_domain_attestation' circuit. Returns null for other circuits.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Domain as ASCII string (e.g., 'example.com'), or null if not applicable\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const domain = sdk.extractDomain(result.publicInputs, result.circuit);\n * console.log('Domain:', domain); // 'example.com'\n * }\n * ```\n */\n extractDomain(publicInputs: string[], circuit: CircuitType): string | null {\n return extractDomainFromPublicInputs(publicInputs, circuit);\n }\n\n}\n\nexport default ProofportSDK;\n"],"names":["ethers"],"mappings":";;;;;;;AAAA;;AAEG;AAIH;;;;;;;;;AASG;AACI,MAAM,UAAU,GAAmC;AACxD,IAAA,UAAU,EAAE,+BAA+B;AAC3C,IAAA,OAAO,EAAE,mCAAmC;AAC5C,IAAA,KAAK,EAAE,uBAAuB;CAC/B;AAED;;;;;;;;;AASG;AACI,MAAM,cAAc,GAAG,aAAa;AAE3C;;;;;;;;;AASG;AACI,MAAM,eAAe,GAAG;;AAE7B,IAAA,aAAa,EAAE,gBAGP;AAEV;;;;;;;;;;;AAWG;AACI,MAAM,gBAAgB,GAKxB;AACH,IAAA,oBAAoB,EAAE;AACpB,QAAA,IAAI,EAAE,cAAc;AACpB,QAAA,WAAW,EAAE,sCAAsC;;;;;AAKnD,QAAA,iBAAiB,EAAE,GAAG;AACtB,QAAA,gBAAgB,EAAE,CAAC,aAAa,EAAE,yBAAyB,CAAC;AAC7D,KAAA;AACD,IAAA,4BAA4B,EAAE;AAC5B,QAAA,IAAI,EAAE,kBAAkB;AACxB,QAAA,WAAW,EAAE,qCAAqC;;;AAGlD,QAAA,iBAAiB,EAAE,GAAG;QACtB,gBAAgB,EAAE,CAAC,aAAa,EAAE,yBAAyB,EAAE,cAAc,EAAE,qBAAqB,EAAE,aAAa,CAAC;AACnH,KAAA;AACD,IAAA,uBAAuB,EAAE;AACvB,QAAA,IAAI,EAAE,aAAa;AACnB,QAAA,WAAW,EAAE,6CAA6C;AAC1D,QAAA,iBAAiB,EAAE,GAAG;QACtB,gBAAgB,EAAE,CAAC,sBAA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