@zama-fhe/sdk 3.2.0 → 3.3.0-alpha.10
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/cjs/assertions.cjs +1 -1
- package/dist/cjs/assertions.cjs.map +1 -1
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer-cleartext.cjs +1 -1
- package/dist/cjs/relayer-cleartext.cjs.map +1 -1
- package/dist/cjs/relayer-sdk.worker.js +134 -34
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/timeout.cjs +2 -0
- package/dist/cjs/timeout.cjs.map +1 -0
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/web/index.cjs +136 -36
- package/dist/cjs/web/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/assertions-zYseN5Xz.js +2 -0
- package/dist/esm/assertions-zYseN5Xz.js.map +1 -0
- package/dist/esm/{base-signer-ByGw5ReU.d.ts → base-signer-C3Wc5oi9.d.ts} +2 -2
- package/dist/esm/base-signer-DjytqPkd.js +2 -0
- package/dist/esm/base-signer-DjytqPkd.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-DMW5nK1M.d.ts → cleartext-DAkOTlrE.d.ts} +2 -2
- package/dist/esm/{cleartext-CTla3A3O.js → cleartext-rTWFctyd.js} +2 -2
- package/dist/esm/{cleartext-CTla3A3O.js.map → cleartext-rTWFctyd.js.map} +1 -1
- package/dist/esm/{encryption-BGmINekJ.js → encryption-x4Z_Icqk.js} +2 -2
- package/dist/esm/{encryption-BGmINekJ.js.map → encryption-x4Z_Icqk.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +4 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{hex-CxtyupeQ.js → hex-A72GrTf9.js} +2 -2
- package/dist/esm/{hex-CxtyupeQ.js.map → hex-A72GrTf9.js.map} +1 -1
- package/dist/esm/{index-DoVo9J1n.d.ts → index-C1Mtc8Rw.d.ts} +450 -163
- package/dist/esm/index.d.ts +17 -13
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +25 -7
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
- package/dist/esm/query/index.d.ts +42 -4
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js +2 -0
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +1 -0
- package/dist/esm/{relayer-cleartext-DkKKjfI6.d.ts → relayer-cleartext-CSeMlmGO.d.ts} +102 -13
- package/dist/esm/relayer-eavK5bfZ.js +2 -0
- package/dist/esm/relayer-eavK5bfZ.js.map +1 -0
- package/dist/esm/relayer-sdk.worker.js +134 -34
- package/dist/esm/timeout-CNVfiaJD.js +2 -0
- package/dist/esm/timeout-CNVfiaJD.js.map +1 -0
- package/dist/esm/token-Bt33g0zQ.js +2 -0
- package/dist/esm/token-Bt33g0zQ.js.map +1 -0
- package/dist/esm/{types-BjDu-RZg.d.ts → types-Gn5MeDsr.d.ts} +14 -2
- package/dist/esm/{types-Xg_On_yY.d.ts → types-OHIaPwCy.d.ts} +2 -2
- package/dist/esm/{types-DiZhtG8i.d.ts → types-piBsdTIP.d.ts} +2 -2
- package/dist/esm/{validation-DHZ3JPOn.js → validation-DLszOweh.js} +2 -2
- package/dist/esm/{validation-DHZ3JPOn.js.map → validation-DLszOweh.js.map} +1 -1
- package/dist/esm/viem/index.d.ts +4 -4
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +2 -2
- package/dist/esm/web/index.js +135 -35
- package/dist/esm/web/index.js.map +1 -1
- package/dist/esm/worker.base-client-BVnT4yJa.js +2 -0
- package/dist/esm/worker.base-client-BVnT4yJa.js.map +1 -0
- package/dist/esm/{wrappers-registry-BWWG0aze.js → wrappers-registry-C1oK8Bi6.js} +2 -2
- package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +1 -0
- package/package.json +51 -51
- package/dist/esm/assertions-CnPIS0VN.js +0 -2
- package/dist/esm/assertions-CnPIS0VN.js.map +0 -1
- package/dist/esm/base-signer-BVqcM5jt.js +0 -2
- package/dist/esm/base-signer-BVqcM5jt.js.map +0 -1
- package/dist/esm/error-W1N-FGwV.js +0 -2
- package/dist/esm/error-W1N-FGwV.js.map +0 -1
- package/dist/esm/relayer-D-nicEYJ.js +0 -2
- package/dist/esm/relayer-D-nicEYJ.js.map +0 -1
- package/dist/esm/relayer-cleartext-DGcb5qtE.js +0 -2
- package/dist/esm/relayer-cleartext-DGcb5qtE.js.map +0 -1
- package/dist/esm/token-TQ-VFHS4.js +0 -2
- package/dist/esm/token-TQ-VFHS4.js.map +0 -1
- package/dist/esm/worker.base-client-x522sMBy.js +0 -2
- package/dist/esm/worker.base-client-x522sMBy.js.map +0 -1
- package/dist/esm/wrappers-registry-BWWG0aze.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relayer-cleartext.cjs","names":["EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts"],"sourcesContent":["import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nimport type { TransportKeyPair } from \"../../credentials/types\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { FheChain } from \"../../chains/types\";\nimport { ConfigurationError, DecryptionFailedError, EncryptionFailedError } from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValue(encryptedValue: EncryptedValue, rawValue: bigint): ClearValue {\n const typeByte = Number((BigInt(encryptedValue) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: FheChain;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: FheChain) {\n if (FORBIDDEN_CHAIN_IDS.has(config.id)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.id}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n if (!config.executorAddress) {\n throw new ConfigurationError(\n `Cleartext transport requires an executorAddress for chain ${config.id}.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateTransportKeyPair(): Promise<TransportKeyPair> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress as Address,\n BigInt(this.#config.id),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification as Address,\n ),\n types: {\n CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.id),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]);\n\n return { encryptedValues: handles, inputProof };\n }\n\n async userDecrypt(\n params: UserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDecryptAuthorization(\n params.encryptedValues,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n const normalizedHandles = encryptedValues;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#isAllowedForDecryption(encryptedValue)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Encrypted value ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return {\n clearValues,\n abiEncodedClearValues,\n decryptionProof,\n };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDelegation(\n params.encryptedValues,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return {\n publicKeyId: \"mock-public-key-id\",\n publicKey: new Uint8Array([32]),\n };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return {\n publicParams: new Uint8Array([32]),\n publicParamsId: \"mock-public-params-id\",\n };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress as Address;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedEncryptedValues: EncryptedValue[],\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n const values = await Promise.all(\n normalizedEncryptedValues.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n\n return Object.fromEntries(\n normalizedEncryptedValues.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedEncryptedValues: EncryptedValue[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedEncryptedValues.flatMap((encryptedValue) => [\n this.#persistAllowed(encryptedValue, actorAddress),\n this.#persistAllowed(encryptedValue, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedEncryptedValues.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new DecryptionFailedError(\n `${actorLabel} ${actorAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n encryptedValues: EncryptedValue[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, encryptedValue],\n }),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Encrypted value ${encryptedValues[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(encryptedValue: EncryptedValue, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [encryptedValue, account],\n });\n }\n\n async #isAllowedForDecryption(encryptedValue: EncryptedValue): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [encryptedValue],\n });\n }\n\n async #readPlaintext(encryptedValue: EncryptedValue): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [encryptedValue],\n });\n }\n}\n"],"mappings":"yIAUA,MAAM,GACJ,EACA,KACiC,CACjC,KAAM,oBACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEM,GACJ,EACA,KACyB,CACzB,KAAM,aACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEa,EAA4B,CACvC,OAAQ,EACR,MAAO,CACL,uBAAwB,CACtB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,cAAe,KAAM,SAAU,EACvC,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAwB,CACnC,OAAQ,EACR,MAAO,CACL,0BAA2B,CACzB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,kBAAmB,KAAM,OAAQ,EACzC,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAsB,CACjC,OAAQ,EACR,MAAO,CACL,+BAAgC,CAC9B,CAAE,KAAM,YAAa,KAAM,OAAQ,EACnC,CAAE,KAAM,oBAAqB,KAAM,WAAY,EAC/C,CAAE,KAAM,iBAAkB,KAAM,SAAU,EAC1C,CAAE,KAAM,eAAgB,KAAM,SAAU,EACxC,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAgC,CAC3C,OAAQ,EACR,MAAO,CACL,wCAAyC,CACvC,CAAE,KAAM,YAAa,KAAM,OAAQ,EACnC,CAAE,KAAM,oBAAqB,KAAM,WAAY,EAC/C,CAAE,KAAM,mBAAoB,KAAM,SAAU,EAC5C,CAAE,KAAM,iBAAkB,KAAM,SAAU,EAC1C,CAAE,KAAM,eAAgB,KAAM,SAAU,EACxC,CAAE,KAAM,YAAa,KAAM,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CACH,CAEA,KAAMM,GAAe,EAAiD,CACpE,OAAO,KAAKP,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,gBACtB,IAAK,EACL,aAAc,aACd,KAAM,CAAC,CAAc,CACvB,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"relayer-cleartext.cjs","names":["ZamaError","ZamaErrorCode","EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/errors/entitlement.ts","../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The signer (or delegator) lacks ACL permission to decrypt the encrypted value —\n * `persistAllowed` returned `false`. Terminal and **non-retryable**: the fix is\n * an on-chain grant (`FHE.allow`), or for indexers, to wait for a backfill once\n * the grant lands. Distinct from transient failures like {@link RpcRateLimitError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof NotEntitledError) {\n * // don't retry — wait for an ACL grant / backfill\n * }\n * }\n * ```\n */\nexport class NotEntitledError extends ZamaError {\n /** The encrypted value the actor is not entitled to decrypt. */\n readonly encryptedValue: string;\n /** The contract the encrypted value belongs to. */\n readonly contractAddress: string;\n /** The actor (signer or delegator) that lacks ACL permission. */\n readonly account: string;\n\n constructor(\n args: { encryptedValue: string; contractAddress: string; account: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.NotEntitled,\n `Account ${args.account} is not entitled to decrypt encrypted value ${args.encryptedValue} ` +\n `on contract ${args.contractAddress}. This is not a transient failure — ` +\n `the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,\n options,\n );\n this.name = \"NotEntitledError\";\n this.encryptedValue = args.encryptedValue;\n this.contractAddress = args.contractAddress;\n this.account = args.account;\n }\n}\n","import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nimport type { TransportKeyPair } from \"../../credentials/types\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { FheChain } from \"../../chains/types\";\nimport {\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n NotEntitledError,\n} from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValue(encryptedValue: EncryptedValue, rawValue: bigint): ClearValue {\n const typeByte = Number((BigInt(encryptedValue) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: FheChain;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: FheChain) {\n if (FORBIDDEN_CHAIN_IDS.has(config.id)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.id}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n if (!config.executorAddress) {\n throw new ConfigurationError(\n `Cleartext transport requires an executorAddress for chain ${config.id}.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateTransportKeyPair(): Promise<TransportKeyPair> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress as Address,\n BigInt(this.#config.id),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification as Address,\n ),\n types: { CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.id),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]);\n\n return { encryptedValues: handles, inputProof };\n }\n\n async userDecrypt(\n params: UserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDecryptAuthorization(\n params.encryptedValues,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n const normalizedHandles = encryptedValues;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#isAllowedForDecryption(encryptedValue)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Encrypted value ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return { clearValues, abiEncodedClearValues, decryptionProof };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDelegation(\n params.encryptedValues,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress as Address;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedEncryptedValues: EncryptedValue[],\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n const values = await Promise.all(\n normalizedEncryptedValues.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n\n return Object.fromEntries(\n normalizedEncryptedValues.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedEncryptedValues: EncryptedValue[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedEncryptedValues.flatMap((encryptedValue) => [\n this.#persistAllowed(encryptedValue, actorAddress),\n this.#persistAllowed(encryptedValue, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedEncryptedValues.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new NotEntitledError({\n encryptedValue: normalizedEncryptedValues[i]!,\n contractAddress,\n account: actorAddress,\n });\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n encryptedValues: EncryptedValue[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, encryptedValue],\n }),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Encrypted value ${encryptedValues[i]!} is not delegated for user decryption`,\n );\n }\n }\n\n // Parity with the relayer/worker path: a delegated handle still requires the\n // *delegator* to hold the ACL grant (`persistAllowed`). Without this check,\n // the same condition surfaces differently in local cleartext dev than in\n // production — exactly where integrators wire up their error handling.\n // Cleartext is host-chain-only: `#persistAllowed` reads the ACL directly on\n // the local chain, with no gateway and no cross-chain sync. A failed check\n // here can never be a propagation lag — it is authoritative and permanent —\n // so it maps to the terminal NotEntitledError, not the retryable\n // DelegationNotPropagatedError (which would make the delegated-decrypt retry\n // loop spin its full budget on a local misconfig before failing).\n const delegatorAllowed = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#persistAllowed(encryptedValue, delegatorAddress),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!delegatorAllowed[i]) {\n throw new NotEntitledError({\n encryptedValue: encryptedValues[i]!,\n contractAddress,\n account: delegatorAddress,\n });\n }\n }\n }\n\n async #persistAllowed(encryptedValue: EncryptedValue, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [encryptedValue, account],\n });\n }\n\n async #isAllowedForDecryption(encryptedValue: EncryptedValue): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [encryptedValue],\n });\n }\n\n async #readPlaintext(encryptedValue: EncryptedValue): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [encryptedValue],\n });\n }\n}\n"],"mappings":"yIAmBA,IAAa,EAAb,cAAsCA,EAAAA,CAAU,CAE9C,eAEA,gBAEA,QAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,YACd,WAAW,EAAK,QAAQ,8CAA8C,EAAK,eAAe,eACzE,EAAK,gBAAgB,yHAEtC,CACF,EACA,KAAK,KAAO,mBACZ,KAAK,eAAiB,EAAK,eAC3B,KAAK,gBAAkB,EAAK,gBAC5B,KAAK,QAAU,EAAK,OACtB,CACF,ECjCA,MAAM,GACJ,EACA,KACiC,CACjC,KAAM,oBACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEM,GACJ,EACA,KACyB,CACzB,KAAM,aACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEa,EAA4B,CACvC,OAAQ,EACR,MAAO,CACL,uBAAwB,CACtB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,cAAe,KAAM,SAAU,EACvC,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAwB,CACnC,OAAQ,EAC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KAAME,GACJ,EACA,EACA,EACA,EACe,CACf,IAAM,EAAU,MAAM,QAAQ,IAC5B,EAAgB,IAAK,GACnB,KAAKR,GAAQ,aAAa,CACxB,QAAS,KAAKC,GAAQ,mBACtB,IAAK,EACL,aAAc,qCACd,KAAM,CAAC,EAAkB,EAAiB,EAAiB,CAAc,CAC3E,CAAC,CACH,CACF,EAEA,IAAK,IAAI,EAAI,EAAG,EAAI,EAAgB,OAAQ,IAC1C,GAAI,CAAC,EAAQ,GACX,MAAM,IAAIK,EAAAA,EACR,mBAAmB,EAAgB,GAAI,sCACzC,EAcJ,IAAM,EAAmB,MAAM,QAAQ,IACrC,EAAgB,IAAK,GACnB,KAAKG,GAAgB,EAAgB,CAAgB,CACvD,CACF,EAEA,IAAK,IAAI,EAAI,EAAG,EAAI,EAAgB,OAAQ,IAC1C,GAAI,CAAC,EAAiB,GACpB,MAAM,IAAI,EAAiB,CACzB,eAAgB,EAAgB,GAChC,kBACA,QAAS,CACX,CAAC,CAGP,CAEA,KAAMA,GAAgB,EAAgC,EAAoC,CACxF,OAAO,KAAKT,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,mBACtB,IAAK,EACL,aAAc,iBACd,KAAM,CAAC,EAAgB,CAAO,CAChC,CAAC,CACH,CAEA,KAAMI,GAAwB,EAAkD,CAC9E,OAAO,KAAKL,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,mBACtB,IAAK,EACL,aAAc,yBACd,KAAM,CAAC,CAAc,CACvB,CAAC,CACH,CAEA,KAAMM,GAAe,EAAiD,CACpE,OAAO,KAAKP,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,gBACtB,IAAK,EACL,aAAc,aACd,KAAM,CAAC,CAAc,CACvB,CAAC,CACH,CACF"}
|
|
@@ -1,4 +1,121 @@
|
|
|
1
1
|
(function() {
|
|
2
|
+
//#region src/utils/error.ts
|
|
3
|
+
/** Coerce an unknown caught value to an Error instance. */
|
|
4
|
+
function toError(error) {
|
|
5
|
+
if (error instanceof Error) return error;
|
|
6
|
+
if (typeof error === "object" && error !== null && "message" in error) return new Error(String(error.message));
|
|
7
|
+
return new Error(String(error));
|
|
8
|
+
}
|
|
9
|
+
/** Properties that may nest a lower-level cause across viem / ethers / fetch. */
|
|
10
|
+
const NESTED_ERROR_KEYS = [
|
|
11
|
+
"cause",
|
|
12
|
+
"error",
|
|
13
|
+
"info"
|
|
14
|
+
];
|
|
15
|
+
/**
|
|
16
|
+
* ethers reports its HTTP status only as a string on `info.responseStatus`
|
|
17
|
+
* (e.g. `"429 Too Many Requests"`). Read it directly off the node — not via the
|
|
18
|
+
* cause-chain flattening, which descends a single branch — so it survives even
|
|
19
|
+
* when the error also carries an `error` link that would be walked first.
|
|
20
|
+
*/
|
|
21
|
+
function responseStatusFromNode(node) {
|
|
22
|
+
const info = node.info;
|
|
23
|
+
if (info !== null && typeof info === "object") {
|
|
24
|
+
const responseStatus = info.responseStatus;
|
|
25
|
+
if (typeof responseStatus === "string") return responseStatus;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Copy the scalar signal fields the classifier keys on from a raw error node
|
|
30
|
+
* onto the envelope, only where not already set — so a shallower node keeps
|
|
31
|
+
* priority. Also lifts ethers' string `info.responseStatus` and the relayer's
|
|
32
|
+
* `Retry-After` header (both destroyed by structured clone: the header lives on
|
|
33
|
+
* a non-cloneable `Headers`, the status on a nested `info` the flattening skips).
|
|
34
|
+
*/
|
|
35
|
+
function captureNodeSignals(node, into) {
|
|
36
|
+
if (into.code === void 0 && (typeof node.code === "string" || typeof node.code === "number")) into.code = node.code;
|
|
37
|
+
if (into.status === void 0 && typeof node.status === "number") into.status = node.status;
|
|
38
|
+
if (into.statusCode === void 0 && typeof node.statusCode === "number") into.statusCode = node.statusCode;
|
|
39
|
+
if (into.responseStatus === void 0) {
|
|
40
|
+
const responseStatus = responseStatusFromNode(node);
|
|
41
|
+
if (responseStatus !== void 0) into.responseStatus = responseStatus;
|
|
42
|
+
}
|
|
43
|
+
if (into.retryAfter === void 0) if (typeof node.retryAfter === "number") into.retryAfter = node.retryAfter;
|
|
44
|
+
else {
|
|
45
|
+
const fromHeader = retryAfterFromHeader(node);
|
|
46
|
+
if (fromHeader !== void 0) into.retryAfter = fromHeader;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Lift any still-missing scalar signal from an already-serialized child up. */
|
|
50
|
+
function hoistMissingSignals(from, into) {
|
|
51
|
+
if (into.code === void 0 && from.code !== void 0) into.code = from.code;
|
|
52
|
+
if (into.status === void 0 && from.status !== void 0) into.status = from.status;
|
|
53
|
+
if (into.statusCode === void 0 && from.statusCode !== void 0) into.statusCode = from.statusCode;
|
|
54
|
+
if (into.responseStatus === void 0 && from.responseStatus !== void 0) into.responseStatus = from.responseStatus;
|
|
55
|
+
if (into.retryAfter === void 0 && from.retryAfter !== void 0) into.retryAfter = from.retryAfter;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Flatten an error (and its `cause` / `error` / `info` chain) into a
|
|
59
|
+
* structured-clone-safe {@link SerializedError}. Depth-bounded to mirror
|
|
60
|
+
* {@link findInErrorChain} and guard against cyclic structures.
|
|
61
|
+
*/
|
|
62
|
+
function serializeError(error, depth = 6) {
|
|
63
|
+
const coerced = toError(error);
|
|
64
|
+
const node = typeof error === "object" && error !== null ? error : coerced;
|
|
65
|
+
const serialized = {
|
|
66
|
+
name: coerced.name,
|
|
67
|
+
message: coerced.message
|
|
68
|
+
};
|
|
69
|
+
captureNodeSignals(node, serialized);
|
|
70
|
+
if (depth > 0) for (const key of NESTED_ERROR_KEYS) {
|
|
71
|
+
const next = node[key];
|
|
72
|
+
if (next !== void 0 && next !== null && typeof next === "object") {
|
|
73
|
+
const child = serializeError(next, depth - 1);
|
|
74
|
+
if (serialized.cause === void 0) serialized.cause = child;
|
|
75
|
+
hoistMissingSignals(child, serialized);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return serialized;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration
|
|
82
|
+
* unit and the header's own unit), or `undefined` when absent/unparseable. Per
|
|
83
|
+
* RFC 9110 the value is either a non-negative number of seconds (`"120"`) or an
|
|
84
|
+
* HTTP-date; a past date floors to `0`.
|
|
85
|
+
*/
|
|
86
|
+
function parseRetryAfterHeader(value) {
|
|
87
|
+
if (value === null || value === void 0) return;
|
|
88
|
+
const trimmed = value.trim();
|
|
89
|
+
if (trimmed === "") return;
|
|
90
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
91
|
+
if (/[a-zA-Z]/.test(trimmed)) {
|
|
92
|
+
const dateMs = Date.parse(trimmed);
|
|
93
|
+
if (!Number.isNaN(dateMs)) return Math.max(0, Math.round((dateMs - Date.now()) / 1e3));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */
|
|
97
|
+
function readRetryAfterHeader(headers) {
|
|
98
|
+
if (headers === null || typeof headers !== "object") return;
|
|
99
|
+
const get = headers.get;
|
|
100
|
+
if (typeof get !== "function") return;
|
|
101
|
+
return parseRetryAfterHeader(get.call(headers, "Retry-After"));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch
|
|
105
|
+
* `Response` (the relayer SDK's `cause.response.headers`). The SDK owns the
|
|
106
|
+
* relayer fetch, so parsing the header there is legitimate.
|
|
107
|
+
*
|
|
108
|
+
* The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:
|
|
109
|
+
* for consumer RPC the integrator's viem/ethers transport already honors
|
|
110
|
+
* `Retry-After` in its own retry loop (and retries) before the error ever
|
|
111
|
+
* surfaces, so re-reading it here would re-implement a transport concern.
|
|
112
|
+
* Chain-RPC backoff is configured on the consumer's transport (`chain.network`).
|
|
113
|
+
*/
|
|
114
|
+
function retryAfterFromHeader(node) {
|
|
115
|
+
const response = node.response;
|
|
116
|
+
if (response !== null && typeof response === "object") return readRetryAfterHeader(response.headers);
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
2
119
|
//#region src/utils/assertions.ts
|
|
3
120
|
function assertObject(value, context) {
|
|
4
121
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${context} must be an object, got ${typeof value}`);
|
|
@@ -130,15 +247,14 @@
|
|
|
130
247
|
/**
|
|
131
248
|
* Send an error response back to the main thread.
|
|
132
249
|
*/
|
|
133
|
-
function sendError(id, type, error
|
|
134
|
-
|
|
250
|
+
function sendError(id, type, error) {
|
|
251
|
+
self.postMessage({
|
|
135
252
|
id,
|
|
136
253
|
type,
|
|
137
254
|
success: false,
|
|
138
|
-
error
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
self.postMessage(response);
|
|
255
|
+
error: error instanceof Error ? error.message : String(error),
|
|
256
|
+
serialized: serializeError(error)
|
|
257
|
+
});
|
|
142
258
|
}
|
|
143
259
|
const originalFetch = fetch;
|
|
144
260
|
/** Allowed CDN hostnames for loading the relayer SDK script. */
|
|
@@ -240,7 +356,7 @@
|
|
|
240
356
|
for (const chain of payload.chains) configs.set(chain.id, chain);
|
|
241
357
|
sendSuccess(id, type, { initialized: true });
|
|
242
358
|
} catch (error) {
|
|
243
|
-
sendError(id, type, error
|
|
359
|
+
sendError(id, type, error);
|
|
244
360
|
}
|
|
245
361
|
}
|
|
246
362
|
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
@@ -295,7 +411,7 @@
|
|
|
295
411
|
inputProof: encrypted.inputProof
|
|
296
412
|
}, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
|
|
297
413
|
} catch (error) {
|
|
298
|
-
sendError(id, type, error
|
|
414
|
+
sendError(id, type, error);
|
|
299
415
|
}
|
|
300
416
|
}
|
|
301
417
|
/**
|
|
@@ -311,22 +427,7 @@
|
|
|
311
427
|
}));
|
|
312
428
|
sendSuccess(id, type, { clearValues: await instance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
|
|
313
429
|
} catch (error) {
|
|
314
|
-
sendError(id, type, error
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Extract an HTTP status code from an error, if present.
|
|
319
|
-
* Relayer SDK errors may carry a `status` or `statusCode` property.
|
|
320
|
-
*/
|
|
321
|
-
function extractHttpStatus(error) {
|
|
322
|
-
if (error === null || error === void 0 || typeof error !== "object") return;
|
|
323
|
-
const e = error;
|
|
324
|
-
if (typeof e.statusCode === "number") return e.statusCode;
|
|
325
|
-
if (typeof e.status === "number") return e.status;
|
|
326
|
-
if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
|
|
327
|
-
const cause = e.cause;
|
|
328
|
-
if (typeof cause.statusCode === "number") return cause.statusCode;
|
|
329
|
-
if (typeof cause.status === "number") return cause.status;
|
|
430
|
+
sendError(id, type, error);
|
|
330
431
|
}
|
|
331
432
|
}
|
|
332
433
|
/**
|
|
@@ -337,7 +438,7 @@
|
|
|
337
438
|
try {
|
|
338
439
|
sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.encryptedValues) });
|
|
339
440
|
} catch (error) {
|
|
340
|
-
sendError(id, type, error
|
|
441
|
+
sendError(id, type, error);
|
|
341
442
|
}
|
|
342
443
|
}
|
|
343
444
|
/**
|
|
@@ -352,7 +453,7 @@
|
|
|
352
453
|
privateKey: prefixHex(keypair.privateKey)
|
|
353
454
|
});
|
|
354
455
|
} catch (error) {
|
|
355
|
-
sendError(id, type, error
|
|
456
|
+
sendError(id, type, error);
|
|
356
457
|
}
|
|
357
458
|
}
|
|
358
459
|
/**
|
|
@@ -363,7 +464,7 @@
|
|
|
363
464
|
try {
|
|
364
465
|
sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
|
|
365
466
|
} catch (error) {
|
|
366
|
-
sendError(id, type, error
|
|
467
|
+
sendError(id, type, error);
|
|
367
468
|
}
|
|
368
469
|
}
|
|
369
470
|
/**
|
|
@@ -374,7 +475,7 @@
|
|
|
374
475
|
try {
|
|
375
476
|
sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
|
|
376
477
|
} catch (error) {
|
|
377
|
-
sendError(id, type, error
|
|
478
|
+
sendError(id, type, error);
|
|
378
479
|
}
|
|
379
480
|
}
|
|
380
481
|
/**
|
|
@@ -390,7 +491,7 @@
|
|
|
390
491
|
}));
|
|
391
492
|
sendSuccess(id, type, { clearValues: await instance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
|
|
392
493
|
} catch (error) {
|
|
393
|
-
sendError(id, type, error
|
|
494
|
+
sendError(id, type, error);
|
|
394
495
|
}
|
|
395
496
|
}
|
|
396
497
|
/**
|
|
@@ -402,7 +503,7 @@
|
|
|
402
503
|
const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
|
|
403
504
|
sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
|
|
404
505
|
} catch (error) {
|
|
405
|
-
sendError(id, type, error
|
|
506
|
+
sendError(id, type, error);
|
|
406
507
|
}
|
|
407
508
|
}
|
|
408
509
|
/**
|
|
@@ -413,7 +514,7 @@
|
|
|
413
514
|
try {
|
|
414
515
|
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
|
|
415
516
|
} catch (error) {
|
|
416
|
-
sendError(id, type, error
|
|
517
|
+
sendError(id, type, error);
|
|
417
518
|
}
|
|
418
519
|
}
|
|
419
520
|
/**
|
|
@@ -424,7 +525,7 @@
|
|
|
424
525
|
try {
|
|
425
526
|
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
|
|
426
527
|
} catch (error) {
|
|
427
|
-
sendError(id, type, error
|
|
528
|
+
sendError(id, type, error);
|
|
428
529
|
}
|
|
429
530
|
}
|
|
430
531
|
/**
|
|
@@ -481,8 +582,7 @@
|
|
|
481
582
|
default: throw new Error(`Unknown request type: ${request.type}`);
|
|
482
583
|
}
|
|
483
584
|
} catch (error) {
|
|
484
|
-
|
|
485
|
-
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
|
|
585
|
+
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", error);
|
|
486
586
|
}
|
|
487
587
|
};
|
|
488
588
|
//#endregion
|
package/dist/cjs/relayer.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,TransactionReverted:`TRANSACTION_REVERTED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,Configuration:`CONFIGURATION`,DelegationSelfNotAllowed:`DELEGATION_SELF_NOT_ALLOWED`,DelegationCooldown:`DELEGATION_COOLDOWN`,DelegationNotFound:`DELEGATION_NOT_FOUND`,DelegationExpired:`DELEGATION_EXPIRED`,InsufficientConfidentialBalance:`INSUFFICIENT_CONFIDENTIAL_BALANCE`,InsufficientERC20Balance:`INSUFFICIENT_ERC20_BALANCE`,BalanceCheckUnavailable:`BALANCE_CHECK_UNAVAILABLE`,ERC20ReadFailed:`ERC20_READ_FAILED`,DelegationExpiryUnchanged:`DELEGATION_EXPIRY_UNCHANGED`,DelegationDelegateEqualsContract:`DELEGATION_DELEGATE_EQUALS_CONTRACT`,DelegationContractIsSelf:`DELEGATION_CONTRACT_IS_SELF`,AclPaused:`ACL_PAUSED`,DelegationExpirationTooSoon:`DELEGATION_EXPIRATION_TOO_SOON`,DelegationNotPropagated:`DELEGATION_NOT_PROPAGATED`,ChainMismatch:`CHAIN_MISMATCH`,SignerNotConfigured:`SIGNER_NOT_CONFIGURED`,WalletNotConnected:`WALLET_NOT_CONNECTED`,WalletAccountNotReady:`WALLET_ACCOUNT_NOT_READY`};var t=class extends Error{code;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e}}
|
|
1
|
+
const e={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,TransactionReverted:`TRANSACTION_REVERTED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,NotEntitled:`NOT_ENTITLED`,RpcRateLimited:`RPC_RATE_LIMITED`,OperationTimeout:`OPERATION_TIMEOUT`,WorkerRecycled:`WORKER_RECYCLED`,Configuration:`CONFIGURATION`,DelegationSelfNotAllowed:`DELEGATION_SELF_NOT_ALLOWED`,DelegationCooldown:`DELEGATION_COOLDOWN`,DelegationNotFound:`DELEGATION_NOT_FOUND`,DelegationExpired:`DELEGATION_EXPIRED`,InsufficientConfidentialBalance:`INSUFFICIENT_CONFIDENTIAL_BALANCE`,InsufficientERC20Balance:`INSUFFICIENT_ERC20_BALANCE`,BalanceCheckUnavailable:`BALANCE_CHECK_UNAVAILABLE`,ERC20ReadFailed:`ERC20_READ_FAILED`,DelegationExpiryUnchanged:`DELEGATION_EXPIRY_UNCHANGED`,DelegationDelegateEqualsContract:`DELEGATION_DELEGATE_EQUALS_CONTRACT`,DelegationContractIsSelf:`DELEGATION_CONTRACT_IS_SELF`,AclPaused:`ACL_PAUSED`,DelegationExpirationTooSoon:`DELEGATION_EXPIRATION_TOO_SOON`,DelegationNotPropagated:`DELEGATION_NOT_PROPAGATED`,ChainMismatch:`CHAIN_MISMATCH`,SignerNotConfigured:`SIGNER_NOT_CONFIGURED`,WalletNotConnected:`WALLET_NOT_CONNECTED`,WalletAccountNotReady:`WALLET_ACCOUNT_NOT_READY`};var t=class extends Error{code;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e}},n=class extends t{statusCode;retryAfter;retryable;constructor(t,n,r){super(e.RelayerRequestFailed,t,r),this.name=`RelayerRequestFailedError`,this.statusCode=n,this.retryable=n===429,this.retryAfter=this.retryable?r?.retryAfter:void 0}},r=class extends t{constructor(t,n){super(e.Configuration,t,n),this.name=`ConfigurationError`}};Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
|
|
2
2
|
//# sourceMappingURL=relayer.cjs.map
|
package/dist/cjs/relayer.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relayer.cjs","names":[],"sources":["../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n constructor(code: ZamaErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n }\n}\n
|
|
1
|
+
{"version":3,"file":"relayer.cjs","names":[],"sources":["../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */\n NotEntitled: \"NOT_ENTITLED\",\n /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */\n RpcRateLimited: \"RPC_RATE_LIMITED\",\n /** A worker operation exceeded its configured timeout; the worker is recycled by default. Retryable. */\n OperationTimeout: \"OPERATION_TIMEOUT\",\n /** An in-flight worker operation was aborted as collateral of another operation's timeout recycle. Retryable. */\n WorkerRecycled: \"WORKER_RECYCLED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n constructor(code: ZamaErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Relayer HTTP request failed. */\nexport class RelayerRequestFailedError extends ZamaError {\n /** HTTP status code from the relayer, if available. */\n readonly statusCode: number | undefined;\n\n /**\n * Server-driven retry delay in **seconds** (the SDK's duration unit and the\n * header's own unit), from the relayer's `Retry-After` header. Set only on\n * back-pressure (HTTP 429) responses that carry the header; `undefined`\n * otherwise. Implies {@link retryable}.\n */\n readonly retryAfter: number | undefined;\n\n /**\n * Whether the request may be safely retried. `true` for relayer back-pressure\n * (HTTP 429); pair with {@link retryAfter} for the server's suggested delay.\n */\n readonly retryable: boolean;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number },\n ) {\n super(ZamaErrorCode.RelayerRequestFailed, message, options);\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n this.retryable = statusCode === 429;\n // Keep the two fields consistent: a delay only makes sense when retryable.\n this.retryAfter = this.retryable ? options?.retryAfter : undefined;\n }\n}\n\n/** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\nexport class ConfigurationError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.Configuration, message, options);\n this.name = \"ConfigurationError\";\n }\n}\n"],"mappings":"AAeA,MAAa,EAAgB,CAE3B,gBAAiB,mBAEjB,cAAe,iBAEf,iBAAkB,oBAElB,iBAAkB,oBAElB,oBAAqB,uBAErB,wBAAyB,kBAEzB,wBAAyB,kBAEzB,aAAc,gBAEd,qBAAsB,yBAEtB,YAAa,eAEb,eAAgB,mBAEhB,iBAAkB,oBAElB,eAAgB,kBAEhB,cAAe,gBAEf,yBAA0B,8BAE1B,mBAAoB,sBAEpB,mBAAoB,uBAEpB,kBAAmB,qBAEnB,gCAAiC,oCAEjC,yBAA0B,6BAE1B,wBAAyB,4BAEzB,gBAAiB,oBAEjB,0BAA2B,8BAE3B,iCAAkC,sCAElC,yBAA0B,8BAE1B,UAAW,aAEX,4BAA6B,iCAE7B,wBAAyB,4BAEzB,cAAe,iBAEf,oBAAqB,wBAErB,mBAAoB,uBAEpB,sBAAuB,0BACzB,EAUA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KAEA,YAAY,EAAqB,EAAiB,EAAwB,CACxE,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,CACd,CACF,ECjGa,EAAb,cAA+C,CAAU,CAEvD,WAQA,WAMA,UAEA,YACE,EACA,EACA,EACA,CACA,MAAM,EAAc,qBAAsB,EAAS,CAAO,EAC1D,KAAK,KAAO,4BACZ,KAAK,WAAa,EAClB,KAAK,UAAY,IAAe,IAEhC,KAAK,WAAa,KAAK,UAAY,GAAS,WAAa,IAAA,EAC3D,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./relayer.cjs");var t=class extends e.r{operation;timeout;elapsed;worker;constructor(t,n){super(e.i.OperationTimeout,`Worker operation ${t.operation} timed out after ${t.timeout}s`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerTimeoutError`,this.operation=t.operation,this.timeout=t.timeout,this.elapsed=t.elapsed,this.worker=t.worker}},n=class extends e.r{operation;worker;constructor(t,n){super(e.i.WorkerRecycled,`Worker operation ${t.operation} was aborted because its worker was recycled after a timeout`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerRecycledError`,this.operation=t.operation,this.worker=t.worker}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
|
|
2
|
+
//# sourceMappingURL=timeout.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout.cjs","names":["ZamaError","ZamaErrorCode"],"sources":["../../src/errors/timeout.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * A worker operation (encrypt / decrypt / EIP-712 / key fetch) did not complete\n * within its configured timeout — typically a stuck relayer or WASM call. On the\n * Node pool the SDK **recycles the affected worker** (terminating the hung\n * thread) so it self-heals; the operation itself is **retryable**.\n *\n * Configure the bound (seconds) via `node({ operationTimeout })`. Distinct from a\n * decryption/entitlement failure — a timeout is an infrastructure/latency\n * condition, so it no longer collapses into {@link DecryptionFailedError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof WorkerTimeoutError) {\n * // retry (the worker was recycled); consider raising operationTimeout\n * }\n * }\n * ```\n */\nexport class WorkerTimeoutError extends ZamaError {\n /**\n * The worker operation that timed out. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** The configured timeout that was exceeded, in **seconds** (the SDK's duration unit). */\n readonly timeout: number;\n /** Wall-clock time the operation ran before being abandoned, in **seconds** (may be fractional). */\n readonly elapsed: number;\n /** Label of the worker that stalled, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(\n args: { operation: string; timeout: number; elapsed: number; worker?: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.OperationTimeout,\n `Worker operation ${args.operation} timed out after ${args.timeout}s` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerTimeoutError\";\n this.operation = args.operation;\n this.timeout = args.timeout;\n this.elapsed = args.elapsed;\n this.worker = args.worker;\n }\n}\n\n/**\n * An in-flight worker operation was aborted as **collateral** when its worker was\n * recycled — the worker was torn down to recover from *another* operation's\n * timeout (Node pool self-healing), not because this operation itself timed out.\n *\n * The operation never reached a verdict, so it is **retryable**: the next call\n * lazily re-inits a fresh worker. It is intentionally distinct from\n * {@link WorkerTimeoutError} (this op did not exceed its own bound) and from\n * {@link DecryptionFailedError} (nothing actually failed to decrypt) — so a\n * consumer can retry it instead of surfacing a terminal failure.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * WORKER_RECYCLED: () => retry(), // transient: the worker was replaced\n * });\n * ```\n */\nexport class WorkerRecycledError extends ZamaError {\n /**\n * The worker operation that was aborted. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** Label of the recycled worker, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(args: { operation: string; worker?: string }, options?: ErrorOptions) {\n super(\n ZamaErrorCode.WorkerRecycled,\n `Worker operation ${args.operation} was aborted because its worker was recycled after a timeout` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerRecycledError\";\n this.operation = args.operation;\n this.worker = args.worker;\n }\n}\n"],"mappings":"iCAuBA,IAAa,EAAb,cAAwCA,EAAAA,CAAU,CAKhD,UAEA,QAEA,QAEA,OAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,iBACd,oBAAoB,EAAK,UAAU,mBAAmB,EAAK,QAAQ,IAChE,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,qBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,QAAU,EAAK,QACpB,KAAK,QAAU,EAAK,QACpB,KAAK,OAAS,EAAK,MACrB,CACF,EAoBa,EAAb,cAAyCD,EAAAA,CAAU,CAKjD,UAEA,OAEA,YAAY,EAA8C,EAAwB,CAChF,MACEC,EAAAA,EAAc,eACd,oBAAoB,EAAK,UAAU,+DAChC,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,sBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,MACrB,CACF"}
|