@zama-fhe/sdk 3.0.0-alpha.2 → 3.0.0-alpha.4

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.
Files changed (38) hide show
  1. package/dist/cjs/cleartext.cjs +1 -1
  2. package/dist/cjs/cleartext.cjs.map +1 -1
  3. package/dist/cjs/index.cjs +2 -21
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/query/index.cjs +1 -1
  6. package/dist/cjs/query/index.cjs.map +1 -1
  7. package/dist/cjs/relayer-sdk.worker.js +1 -20
  8. package/dist/cjs/viem/index.cjs +1 -1
  9. package/dist/cjs/viem/index.cjs.map +1 -1
  10. package/dist/esm/cleartext/index.d.ts +4 -10
  11. package/dist/esm/cleartext/index.js +1 -1
  12. package/dist/esm/{cleartext-Cs28cTsa.js → cleartext-hS6TVszr.js} +2 -2
  13. package/dist/esm/cleartext-hS6TVszr.js.map +1 -0
  14. package/dist/esm/ethers/index.d.ts +1 -1
  15. package/dist/esm/index.d.ts +6 -12
  16. package/dist/esm/index.js +3 -22
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/esm/memory-storage-F8xjMzVy.js.map +1 -1
  19. package/dist/esm/node/index.d.ts +4 -10
  20. package/dist/esm/node/index.js +1 -1
  21. package/dist/esm/node/index.js.map +1 -1
  22. package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
  23. package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
  24. package/dist/esm/{onchain-events-2VNiL78c.d.ts → onchain-events-CfGPYFaF.d.ts} +6 -4
  25. package/dist/esm/query/index.d.ts +13 -22
  26. package/dist/esm/query/index.js +1 -1
  27. package/dist/esm/query/index.js.map +1 -1
  28. package/dist/esm/{relayer-sdk-DPqytEbO.d.ts → relayer-sdk-CjKGIodc.d.ts} +4 -10
  29. package/dist/esm/{relayer-sdk.types-CGfXwKcB.d.ts → relayer-sdk.types-DawSwNjS.d.ts} +24 -61
  30. package/dist/esm/relayer-sdk.worker.js +1 -20
  31. package/dist/esm/{relayer-utils-BeoTNDM4.js → relayer-utils-DDa_R8Ft.js} +2 -2
  32. package/dist/esm/relayer-utils-DDa_R8Ft.js.map +1 -0
  33. package/dist/esm/viem/index.d.ts +1 -1
  34. package/dist/esm/viem/index.js +1 -1
  35. package/dist/esm/viem/index.js.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/esm/cleartext-Cs28cTsa.js.map +0 -1
  38. package/dist/esm/relayer-utils-BeoTNDM4.js.map +0 -1
@@ -1,2 +1,2 @@
1
- const e=require(`./relayer.cjs`);let t=require(`viem`),n=require(`viem/accounts`),r=require(`viem/chains`);async function i(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&a(e)){await o(500*2**r);continue}throw e}throw n}function a(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function o(e){return new Promise(t=>setTimeout(t,e))}const s={chainId:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org/v2`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},c={chainId:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org/v2`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},l={chainId:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0},u={[s.chainId]:s,[c.chainId]:c,[l.chainId]:l},d={name:`string`,version:`string`,chainId:`uint256`,verifyingContract:`address`,salt:`bytes32`};function f(e){return Object.keys(d).filter(t=>t in e).map(e=>({name:e,type:d[e]}))}const p=(e,t)=>({name:`InputVerification`,version:`1`,chainId:Number(e),verifyingContract:t}),m=(e,t)=>({name:`Decryption`,version:`1`,chainId:Number(e),verifyingContract:t}),h={domain:p,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},g={domain:m,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},_={domain:m,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},v={domain:m,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},y={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},b={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},x={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(y),Object.freeze(b),Object.freeze(x),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function S(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function C(e){return typeof e==`string`?e in y:!1}function w(e){if(!C(e))throw Error(`Invalid FheType name '${e}'`);return y[e]}function T(e){if(!S(e))throw Error(`Invalid FheType id '${e}'`);let t=x[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const E=(0,t.toBytes)(`ZK-w_rct`),D=(0,t.toBytes)(`ZK-w_hdl`);function O(e,n){let r=Math.ceil(T(n)/8);return(0,t.toBytes)((0,t.pad)((0,t.toHex)(e),{size:r}))}function k(n,r,i){if(i.length!==32)throw new e.i(`random32 must be exactly 32 bytes`);let a=O(r,n),o=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(new Uint8Array([n])),(0,t.toHex)(a),(0,t.toHex)(i)]));return(0,t.keccak256)((0,t.concat)([(0,t.toHex)(E),o]))}function A(n,r,i,a,o){if(!Number.isInteger(r)||r<0||r>255)throw new e.i(`index must be an integer between 0 and 255`);let s=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(E),n])),c=(0,t.keccak256)((0,t.encodePacked)([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[(0,t.toHex)(D),s,r,a,o])),l=o&18446744073709551615n;return(0,t.toHex)(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(r)<<80n|l<<16n|BigInt(i)<<8n|BigInt(0),{size:32})}const j=(0,t.parseAbi)([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),M=(0,t.parseAbi)([`function plaintexts(bytes32 handle) view returns (uint256)`]),N=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],P={EIP712Domain:N,UserDecryptRequestVerification:_.types.UserDecryptRequestVerification},F={EIP712Domain:N,DelegatedUserDecryptRequestVerification:v.types.DelegatedUserDecryptRequestVerification},I={EIP712Domain:N,PublicDecryptVerification:g.types.PublicDecryptVerification},L=new Set([r.mainnet.id,r.sepolia.id]);function R(e,n){let r=Number(BigInt(e)>>8n&255n);return r===0?n!==0n:r===7?(0,t.toHex)(n,{size:20}):n}function z(n){if(!C(n.type))throw new e.i(`Unsupported FHE type`);let r=w(n.type),i;if(n.type===`ebool`){if(typeof n.value==`boolean`)i=n.value?1n:0n;else if(i=n.value,i!==0n&&i!==1n)throw new e.i(`Bool value must be 0, 1, true, or false`)}else i=n.type===`eaddress`?BigInt((0,t.getAddress)(n.value)):n.value;if(i<0n)throw new e.i(`Only non-negative cleartext values are supported`);let a=T(r),o=(1n<<BigInt(a))-1n;if(i>o)throw new e.i(`Value ${i} exceeds max ${o} for FheType ${r}`);return{fheType:r,value:i}}var B=class{#e;#t;kmsSigner;inputSigner;constructor(r){if(L.has(r.chainId))throw new e.t(`Cleartext mode is not allowed on chain ${r.chainId}. It is intended for local development and testing only.`);this.#e=(0,t.createPublicClient)({transport:typeof r.network==`string`?(0,t.http)(r.network):(0,t.custom)(r.network)}),this.#t=r,this.kmsSigner=(0,n.privateKeyToAccount)(r.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=(0,n.privateKeyToAccount)(r.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateKeypair(){let e=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32))),n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));for(;n===e;)n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:n}}async createEIP712(e,t,n,r=7){return{domain:_.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:P,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:BigInt(n),durationDays:BigInt(r),extraData:`0x00`}}}async encrypt(e){let n=e.values.map(z),r=(0,t.getAddress)(e.contractAddress),i=(0,t.getAddress)(e.userAddress),a=n.map(({fheType:e,value:t})=>k(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=(0,t.keccak256)(a.length>0?(0,t.concat)(a):`0x`),s=n.map(({fheType:e},t)=>A(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.chainId))),c=n.map(({value:e})=>(0,t.pad)((0,t.toHex)(e),{size:32})),l=c.length>0?(0,t.concat)(c):`0x`,u=await this.inputSigner.signTypedData({domain:h.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:h.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:i,contractAddress:r,contractChainId:BigInt(this.#t.chainId),extraData:l}}),d=(0,t.toBytes)((0,t.concat)([(0,t.toHex)(new Uint8Array([s.length])),(0,t.toHex)(new Uint8Array([1])),...s,u,l]));return{handles:s.map(e=>(0,t.toBytes)(e)),inputProof:d}}async userDecrypt(e){return await this.#r(e.handles,(0,t.getAddress)(e.signerAddress),(0,t.getAddress)(e.contractAddress),`User`,`user decrypt`),this.#n(e.handles)}async publicDecrypt(n){let r=n,i=(await Promise.all(r.map(e=>this.#o(e)))).findIndex(e=>!e);if(i!==-1)throw new e.r(`Handle ${r[i]} is not allowed for public decryption`);let a=await Promise.all(r.map(e=>this.#s(e))),o=Object.fromEntries(r.map((e,t)=>[e,R(e,a[t])])),s=(0,t.concat)(a.map(e=>(0,t.pad)((0,t.toHex)(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:g.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:I,primaryType:`PublicDecryptVerification`,message:{ctHandles:r,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:(0,t.concat)([(0,t.toHex)(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,n,r,i,a=7){let o={publicKey:e,contractAddresses:n,delegatorAddress:(0,t.getAddress)(r),startTimestamp:String(i),durationDays:String(a),extraData:`0x00`};return{domain:v.domain(BigInt(this.#t.chainId),this.#t.verifyingContractAddressDecryption),types:F,primaryType:`DelegatedUserDecryptRequestVerification`,message:o}}async delegatedUserDecrypt(e){return await this.#i(e.handles,(0,t.getAddress)(e.delegatorAddress),(0,t.getAddress)(e.delegateAddress),(0,t.getAddress)(e.contractAddress)),this.#n(e.handles)}async requestZKProofVerification(t){throw new e.t(`Not implemented in cleartext mode`)}async getPublicKey(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,R(e,t[n])]))}async#r(t,n,r,i,a){if(n===r)throw new e.r(`${i} address ${n} must not equal contract address for ${a}`);let o=await Promise.all(t.flatMap(e=>[this.#a(e,n),this.#a(e,r)]));for(let s=0;s<t.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new e.r(`${i} ${n} is not authorized for ${a} of handle ${t[s]}`);if(!l)throw new e.r(`Contract ${r} is not authorized for ${a} of handle ${t[s]}`)}}async#i(t,n,r,i){let a=await Promise.all(t.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`isHandleDelegatedForUserDecryption`,args:[n,r,i,e]})));for(let n=0;n<t.length;n++)if(!a[n])throw new e.r(`Handle ${t[n]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:M,functionName:`plaintexts`,args:[e]})}};const V={...l,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},H={chainId:560048,network:`https://rpc.hoodi.ethpandaops.io`,gatewayChainId:l.gatewayChainId,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`,verifyingContractAddressDecryption:l.verifyingContractAddressDecryption,verifyingContractAddressInputVerification:l.verifyingContractAddressInputVerification,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return V}});
1
+ const e=require(`./relayer.cjs`);let t=require(`viem`),n=require(`viem/accounts`),r=require(`viem/chains`);async function i(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&a(e)){await o(500*2**r);continue}throw e}throw n}function a(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function o(e){return new Promise(t=>setTimeout(t,e))}const s={chainId:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org/v2`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},c={chainId:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org/v2`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},l={chainId:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0},u={[s.chainId]:s,[c.chainId]:c,[l.chainId]:l},d=(e,t)=>({name:`InputVerification`,version:`1`,chainId:BigInt(e),verifyingContract:t}),f=(e,t)=>({name:`Decryption`,version:`1`,chainId:BigInt(e),verifyingContract:t}),p={domain:d,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},m={domain:f,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},h={domain:f,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},g={domain:f,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},_={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},v={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},y={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(_),Object.freeze(v),Object.freeze(y),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function b(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function x(e){return typeof e==`string`?e in _:!1}function S(e){if(!x(e))throw Error(`Invalid FheType name '${e}'`);return _[e]}function C(e){if(!b(e))throw Error(`Invalid FheType id '${e}'`);let t=y[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const w=(0,t.toBytes)(`ZK-w_rct`),T=(0,t.toBytes)(`ZK-w_hdl`);function E(e,n){let r=Math.ceil(C(n)/8);return(0,t.toBytes)((0,t.pad)((0,t.toHex)(e),{size:r}))}function D(n,r,i){if(i.length!==32)throw new e.i(`random32 must be exactly 32 bytes`);let a=E(r,n),o=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(new Uint8Array([n])),(0,t.toHex)(a),(0,t.toHex)(i)]));return(0,t.keccak256)((0,t.concat)([(0,t.toHex)(w),o]))}function O(n,r,i,a,o){if(!Number.isInteger(r)||r<0||r>255)throw new e.i(`index must be an integer between 0 and 255`);let s=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(w),n])),c=(0,t.keccak256)((0,t.encodePacked)([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[(0,t.toHex)(T),s,r,a,o])),l=o&18446744073709551615n;return(0,t.toHex)(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(r)<<80n|l<<16n|BigInt(i)<<8n|BigInt(0),{size:32})}const k=(0,t.parseAbi)([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),A=(0,t.parseAbi)([`function plaintexts(bytes32 handle) view returns (uint256)`]),j=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],M={EIP712Domain:j,UserDecryptRequestVerification:h.types.UserDecryptRequestVerification},N={EIP712Domain:j,DelegatedUserDecryptRequestVerification:g.types.DelegatedUserDecryptRequestVerification},P={EIP712Domain:j,PublicDecryptVerification:m.types.PublicDecryptVerification},F=new Set([r.mainnet.id,r.sepolia.id]);function I(e,n){let r=Number(BigInt(e)>>8n&255n);return r===0?n!==0n:r===7?(0,t.toHex)(n,{size:20}):n}function L(n){if(!x(n.type))throw new e.i(`Unsupported FHE type`);let r=S(n.type),i;if(n.type===`ebool`){if(typeof n.value==`boolean`)i=n.value?1n:0n;else if(i=n.value,i!==0n&&i!==1n)throw new e.i(`Bool value must be 0, 1, true, or false`)}else i=n.type===`eaddress`?BigInt((0,t.getAddress)(n.value)):n.value;if(i<0n)throw new e.i(`Only non-negative cleartext values are supported`);let a=C(r),o=(1n<<BigInt(a))-1n;if(i>o)throw new e.i(`Value ${i} exceeds max ${o} for FheType ${r}`);return{fheType:r,value:i}}var R=class{#e;#t;kmsSigner;inputSigner;constructor(r){if(F.has(r.chainId))throw new e.t(`Cleartext mode is not allowed on chain ${r.chainId}. It is intended for local development and testing only.`);this.#e=(0,t.createPublicClient)({transport:typeof r.network==`string`?(0,t.http)(r.network):(0,t.custom)(r.network)}),this.#t=r,this.kmsSigner=(0,n.privateKeyToAccount)(r.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=(0,n.privateKeyToAccount)(r.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateKeypair(){let e=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32))),n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));for(;n===e;)n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:n}}async createEIP712(e,t,n,r=7){return{domain:h.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:M,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:String(n),durationDays:String(r),extraData:`0x00`}}}async encrypt(e){let n=e.values.map(L),r=(0,t.getAddress)(e.contractAddress),i=(0,t.getAddress)(e.userAddress),a=n.map(({fheType:e,value:t})=>D(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=(0,t.keccak256)(a.length>0?(0,t.concat)(a):`0x`),s=n.map(({fheType:e},t)=>O(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.chainId))),c=n.map(({value:e})=>(0,t.pad)((0,t.toHex)(e),{size:32})),l=c.length>0?(0,t.concat)(c):`0x`,u=await this.inputSigner.signTypedData({domain:p.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:p.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:i,contractAddress:r,contractChainId:BigInt(this.#t.chainId),extraData:l}}),d=(0,t.toBytes)((0,t.concat)([(0,t.toHex)(new Uint8Array([s.length])),(0,t.toHex)(new Uint8Array([1])),...s,u,l]));return{handles:s.map(e=>(0,t.toBytes)(e)),inputProof:d}}async userDecrypt(e){return await this.#r(e.handles,(0,t.getAddress)(e.signerAddress),(0,t.getAddress)(e.contractAddress),`User`,`user decrypt`),this.#n(e.handles)}async publicDecrypt(n){let r=n,i=(await Promise.all(r.map(e=>this.#o(e)))).findIndex(e=>!e);if(i!==-1)throw new e.r(`Handle ${r[i]} is not allowed for public decryption`);let a=await Promise.all(r.map(e=>this.#s(e))),o=Object.fromEntries(r.map((e,t)=>[e,I(e,a[t])])),s=(0,t.concat)(a.map(e=>(0,t.pad)((0,t.toHex)(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:m.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:P,primaryType:`PublicDecryptVerification`,message:{ctHandles:r,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:(0,t.concat)([(0,t.toHex)(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,n,r,i,a=7){let o={publicKey:e,contractAddresses:n,delegatorAddress:(0,t.getAddress)(r),startTimestamp:String(i),durationDays:String(a),extraData:`0x00`};return{domain:g.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:N,primaryType:`DelegatedUserDecryptRequestVerification`,message:o}}async delegatedUserDecrypt(e){return await this.#i(e.handles,(0,t.getAddress)(e.delegatorAddress),(0,t.getAddress)(e.delegateAddress),(0,t.getAddress)(e.contractAddress)),this.#n(e.handles)}async requestZKProofVerification(t){throw new e.t(`Not implemented in cleartext mode`)}async getPublicKey(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,I(e,t[n])]))}async#r(t,n,r,i,a){if(n===r)throw new e.r(`${i} address ${n} must not equal contract address for ${a}`);let o=await Promise.all(t.flatMap(e=>[this.#a(e,n),this.#a(e,r)]));for(let s=0;s<t.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new e.r(`${i} ${n} is not authorized for ${a} of handle ${t[s]}`);if(!l)throw new e.r(`Contract ${r} is not authorized for ${a} of handle ${t[s]}`)}}async#i(t,n,r,i){let a=await Promise.all(t.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`isHandleDelegatedForUserDecryption`,args:[n,r,i,e]})));for(let n=0;n<t.length;n++)if(!a[n])throw new e.r(`Handle ${t[n]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:A,functionName:`plaintexts`,args:[e]})}};const z={...l,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},B={chainId:560048,network:`https://rpc.hoodi.ethpandaops.io`,gatewayChainId:l.gatewayChainId,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`,verifyingContractAddressDecryption:l.verifyingContractAddressDecryption,verifyingContractAddressInputVerification:l.verifyingContractAddressInputVerification,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return z}});
2
2
  //# sourceMappingURL=cleartext.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cleartext.cjs","names":["EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/relayer-utils.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","../../src/relayer/cleartext/presets.ts"],"sourcesContent":["import type { FhevmInstanceConfig } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\nimport type { EIP712TypedData } from \"./relayer-sdk.types\";\n\nconst MAX_RETRIES = 2;\nconst RETRY_BASE_MS = 500;\n\n/**\n * Retry an async operation with exponential backoff.\n * Only retries on transient errors (timeout, network). Does not retry user-facing errors.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt < retries && isTransientError(error)) {\n await sleep(RETRY_BASE_MS * 2 ** attempt);\n continue;\n }\n throw error;\n }\n }\n throw lastError;\n}\n\nfunction isTransientError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const msg = error.message.toLowerCase();\n return (\n msg.includes(\"timed out\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"network\") ||\n msg.includes(\"fetch failed\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\")\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Extends the base relayer config with the on-chain wrappers registry address.\n *\n * Used by `DefaultConfigs` and the `WrappersRegistry` class to\n * resolve the correct registry contract per chain.\n */\nexport interface ExtendedFhevmInstanceConfig extends FhevmInstanceConfig {\n /**\n * Address of the `ConfidentialTokenWrappersRegistry` contract.\n * `undefined` for chains where no registry is deployed (e.g. Hardhat).\n */\n registryAddress: Address | undefined;\n}\n\n/**\n * Mainnet network configuration (chainId 1).\n *\n * Contract addresses mirror `MainnetConfigV2` from `@zama-fhe/relayer-sdk`.\n * They are duplicated here because the `/bundle` export path only exposes\n * types at build time (runtime values require `/web` or `/node` which pull\n * in WASM). `satisfies ExtendedFhevmInstanceConfig` ensures structural drift\n * is caught at compile time.\n *\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const MainnetConfig = {\n chainId: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org/v2\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n *\n * See {@link MainnetConfig} for why addresses are hardcoded.\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const SepoliaConfig = {\n chainId: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org/v2\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n *\n * `registryAddress` is `undefined` — pass it explicitly via\n * `registryAddresses` when creating a `WrappersRegistry`.\n */\nexport const HardhatConfig = {\n chainId: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Built-in network configurations keyed by chain ID.\n *\n * Includes Mainnet (1), Sepolia (11155111), and Hardhat (31337).\n * Used by `RelayerWeb` to resolve transport configs and by\n * `WrappersRegistry` to resolve registry addresses.\n */\nexport const DefaultConfigs: Record<number, ExtendedFhevmInstanceConfig> = {\n [MainnetConfig.chainId]: MainnetConfig,\n [SepoliaConfig.chainId]: SepoliaConfig,\n [HardhatConfig.chainId]: HardhatConfig,\n} as const;\n\n/** EIP-712 domain field → Solidity type. Order follows the EIP-712 spec. */\nconst DOMAIN_FIELD_TYPES: Record<string, string> = {\n name: \"string\",\n version: \"string\",\n chainId: \"uint256\",\n verifyingContract: \"address\",\n salt: \"bytes32\",\n};\n\n/**\n * Build `EIP712Domain` type entries from the keys present in a domain object.\n * Order matches the EIP-712 spec (name → version → chainId → verifyingContract → salt).\n */\nexport function buildEIP712DomainType(\n domain: EIP712TypedData[\"domain\"],\n): { name: string; type: string }[] {\n return Object.keys(DOMAIN_FIELD_TYPES)\n .filter((k) => k in domain)\n .map((k) => ({ name: k, type: DOMAIN_FIELD_TYPES[k]! }));\n}\n","import type { Address, TypedDataDomain } from \"viem\";\nimport type {\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\ntype DomainFactory = (chainId: number | bigint, verifyingContract: Address) => TypedDataDomain;\n\nconst inputDomain: DomainFactory = (chainId, verifyingContract) => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: Number(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain: DomainFactory = (chainId, verifyingContract) => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: Number(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 toBytes,\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 KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\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 { CleartextConfig } from \"./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 decodeClearValueType(handle: Handle, rawValue: bigint): ClearValueType {\n const typeByte = Number((BigInt(handle) >> 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: CleartextConfig;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: CleartextConfig) {\n if (FORBIDDEN_CHAIN_IDS.has(config.chainId)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.chainId}. ` +\n `It is intended for local development and testing only.`,\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 generateKeypair(): Promise<KeypairType<Hex>> {\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.chainId,\n this.#config.verifyingContractAddressDecryption,\n ) as EIP712TypedData[\"domain\"],\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: BigInt(startTimestamp),\n durationDays: BigInt(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,\n BigInt(this.#config.chainId),\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,\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.chainId),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = toBytes(\n concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]),\n );\n\n return {\n handles: handles.map((handle) => toBytes(handle)),\n inputProof,\n };\n }\n\n async userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDecryptAuthorization(\n params.handles,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n const normalizedHandles = handles;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((handle) => this.#isAllowedForDecryption(handle)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Handle ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, 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,\n ) as KmsPublicDecryptEIP712Type[\"domain\"],\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: publicKey as KmsDelegatedUserDecryptEIP712Type[\"message\"][\"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 BigInt(this.#config.chainId),\n this.#config.verifyingContractAddressDecryption,\n ) as KmsDelegatedUserDecryptEIP712Type[\"domain\"],\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDelegation(\n params.handles,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async getPublicKey(): Promise<{ publicKeyId: string; publicKey: Uint8Array } | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(\n _bits: number,\n ): Promise<{ publicParams: Uint8Array; publicParamsId: string } | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress;\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 normalizedHandles: Handle[],\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n const values = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n\n return Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedHandles: Handle[],\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 normalizedHandles.flatMap((handle) => [\n this.#persistAllowed(handle, actorAddress),\n this.#persistAllowed(handle, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedHandles.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 handle ${normalizedHandles[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n handles: Handle[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n handles.map((handle) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n }),\n ),\n );\n\n for (let i = 0; i < handles.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Handle ${handles[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(handle: Handle, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [handle, account],\n });\n }\n\n async #isAllowedForDecryption(handle: Handle): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [handle],\n });\n }\n\n async #readPlaintext(handle: Handle): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [handle],\n });\n }\n}\n","import { HardhatConfig } from \"../relayer-utils\";\nimport type { CleartextConfig } from \"./types\";\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n */\nexport const hardhatCleartextConfig = {\n ...HardhatConfig,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} satisfies CleartextConfig;\n\nexport const hoodiCleartextConfig = {\n chainId: 560048,\n network: \"https://rpc.hoodi.ethpandaops.io\",\n gatewayChainId: HardhatConfig.gatewayChainId,\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n // The values used when configuring the deployments are the same as those used for a hardhat deployment, since there's no gateway chain.\n verifyingContractAddressDecryption: HardhatConfig.verifyingContractAddressDecryption,\n verifyingContractAddressInputVerification:\n HardhatConfig.verifyingContractAddressIn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,OACT,QAAS,mCACT,eAAgB,EAAc,eAC9B,mBAAoB,6CACpB,gBAAiB,6CAEjB,mCAAoC,EAAc,mCAClD,0CACE,EAAc,0CAChB,gBAAiB,6CAClB"}
1
+ {"version":3,"file":"cleartext.cjs","names":["EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/relayer-utils.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","../../src/relayer/cleartext/presets.ts"],"sourcesContent":["import type { FhevmInstanceConfig } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\n\nconst MAX_RETRIES = 2;\nconst RETRY_BASE_MS = 500;\n\n/**\n * Retry an async operation with exponential backoff.\n * Only retries on transient errors (timeout, network). Does not retry user-facing errors.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt < retries && isTransientError(error)) {\n await sleep(RETRY_BASE_MS * 2 ** attempt);\n continue;\n }\n throw error;\n }\n }\n throw lastError;\n}\n\nfunction isTransientError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const msg = error.message.toLowerCase();\n return (\n msg.includes(\"timed out\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"network\") ||\n msg.includes(\"fetch failed\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\")\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Extends the base relayer config with the on-chain wrappers registry address.\n *\n * Used by `DefaultConfigs` and the `WrappersRegistry` class to\n * resolve the correct registry contract per chain.\n */\nexport interface ExtendedFhevmInstanceConfig extends FhevmInstanceConfig {\n /**\n * Address of the `ConfidentialTokenWrappersRegistry` contract.\n * `undefined` for chains where no registry is deployed (e.g. Hardhat).\n */\n registryAddress: Address | undefined;\n}\n\n/**\n * Mainnet network configuration (chainId 1).\n *\n * Contract addresses mirror `MainnetConfigV2` from `@zama-fhe/relayer-sdk`.\n * They are duplicated here because the `/bundle` export path only exposes\n * types at build time (runtime values require `/web` or `/node` which pull\n * in WASM). `satisfies ExtendedFhevmInstanceConfig` ensures structural drift\n * is caught at compile time.\n *\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const MainnetConfig = {\n chainId: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org/v2\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n *\n * See {@link MainnetConfig} for why addresses are hardcoded.\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const SepoliaConfig = {\n chainId: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org/v2\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n *\n * `registryAddress` is `undefined` — pass it explicitly via\n * `registryAddresses` when creating a `WrappersRegistry`.\n */\nexport const HardhatConfig = {\n chainId: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Built-in network configurations keyed by chain ID.\n *\n * Includes Mainnet (1), Sepolia (11155111), and Hardhat (31337).\n * Used by `RelayerWeb` to resolve transport configs and by\n * `WrappersRegistry` to resolve registry addresses.\n */\nexport const DefaultConfigs: Record<number, ExtendedFhevmInstanceConfig> = {\n [MainnetConfig.chainId]: MainnetConfig,\n [SepoliaConfig.chainId]: SepoliaConfig,\n [HardhatConfig.chainId]: HardhatConfig,\n} as const;\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 toBytes,\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 KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\n PublicKeyData,\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 { CleartextConfig } from \"./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 decodeClearValueType(handle: Handle, rawValue: bigint): ClearValueType {\n const typeByte = Number((BigInt(handle) >> 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: CleartextConfig;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: CleartextConfig) {\n if (FORBIDDEN_CHAIN_IDS.has(config.chainId)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.chainId}. ` +\n `It is intended for local development and testing only.`,\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 generateKeypair(): Promise<KeypairType<Hex>> {\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.chainId,\n this.#config.verifyingContractAddressDecryption,\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,\n BigInt(this.#config.chainId),\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,\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.chainId),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = toBytes(\n concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]),\n );\n\n return {\n handles: handles.map((handle) => toBytes(handle)),\n inputProof,\n };\n }\n\n async userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDecryptAuthorization(\n params.handles,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n const normalizedHandles = handles;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((handle) => this.#isAllowedForDecryption(handle)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Handle ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, 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,\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.chainId,\n this.#config.verifyingContractAddressDecryption,\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<Handle, ClearValueType>>> {\n await this.#assertDelegation(\n params.handles,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async getPublicKey(): Promise<PublicKeyData | 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;\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 normalizedHandles: Handle[],\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n const values = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n\n return Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedHandles: Handle[],\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 normalizedHandles.flatMap((handle) => [\n this.#persistAllowed(handle, actorAddress),\n this.#persistAllowed(handle, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedHandles.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 handle ${normalizedHandles[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n handles: Handle[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n handles.map((handle) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n }),\n ),\n );\n\n for (let i = 0; i < handles.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Handle ${handles[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(handle: Handle, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [handle, account],\n });\n }\n\n async #isAllowedForDecryption(handle: Handle): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [handle],\n });\n }\n\n async #readPlaintext(handle: Handle): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [handle],\n });\n }\n}\n","import { HardhatConfig } from \"../relayer-utils\";\nimport type { CleartextConfig } from \"./types\";\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n */\nexport const hardhatCleartextConfig = {\n ...HardhatConfig,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} satisfies CleartextConfig;\n\nexport const hoodiCleartextConfig = {\n chainId: 560048,\n network: \"https://rpc.hoodi.ethpandaops.io\",\n gatewayChainId: HardhatConfig.gatewayChainId,\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n // The values used when configuring the deployments are the same as those used for a hardhat deployment, since there's no gateway chain.\n verifyingContractAddressDecryption: HardhatConfig.verifyingContractAddressDecryption,\n verifyingContractAddressInputVerification:\n HardhatConfig.verifyingContractAddressInputVerification,\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n} satisfies CleartextConfig;\n"],"mappings":"2GAUA,eAAsB,EAAa,EAAsB,EAAU,EAAyB,CAC1F,IAAI,EACJ,IAAK,IAAI,EAAU,EAAG,GAAW,EAAS,IACxC,GAAI,CACF,OAAO,MAAM,GAAI,OACV,EAAO,CAEd,GADA,EAAY,EACR,EAAU,GAAW,EAAiB,EAAM,CAAE,CAChD,MAAM,EAAM,IAAgB,GAAK,EAAQ,CACzC,SAEF,MAAM,EAGV,MAAM,EAGR,SAAS,EAAiB,EAAyB,CACjD,GAAI,EAAE,aAAiB,OACrB,MAAO,GAET,IAAM,EAAM,EAAM,QAAQ,aAAa,CACvC,OACE,EAAI,SAAS,YAAY,EACzB,EAAI,SAAS,UAAU,EACvB,EAAI,SAAS,aAAa,EAC1B,EAAI,SAAS,eAAe,EAC5B,EAAI,SAAS,UAAU,EACvB,EAAI,SAAS,eAAe,EAC5B,EAAI,SAAS,iBAAiB,EAC9B,EAAI,SAAS,MAAM,EACnB,EAAI,SAAS,MAAM,EACnB,EAAI,SAAS,MAAM,CAIvB,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,EAAG,CAAC,CA4B1D,MAAa,EAAgB,CAC3B,QAAS,EACT,eAAgB,OAChB,WAAY,sCACZ,QAAS,sCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CAClB,CAQY,EAAgB,CAC3B,QAAS,SACT,eAAgB,MAChB,WAAY,sCACZ,QAAS,8CACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CAClB,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7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
349
349
  const { id, type, payload } = request;
350
350
  try {
351
351
  assertSdkInstance(sdkInstance);
352
- const eip712 = sdkInstance.createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays);
353
- sendSuccess(id, type, {
354
- domain: {
355
- name: eip712.domain.name,
356
- version: eip712.domain.version,
357
- chainId: Number(eip712.domain.chainId),
358
- verifyingContract: eip712.domain.verifyingContract
359
- },
360
- types: { UserDecryptRequestVerification: eip712.types.UserDecryptRequestVerification.map((field) => ({
361
- name: field.name,
362
- type: field.type
363
- })) },
364
- message: {
365
- publicKey: prefixHex(eip712.message.publicKey),
366
- contractAddresses: [...eip712.message.contractAddresses],
367
- startTimestamp: BigInt(eip712.message.startTimestamp),
368
- durationDays: BigInt(eip712.message.durationDays),
369
- extraData: prefixHex(eip712.message.extraData)
370
- }
371
- });
352
+ sendSuccess(id, type, sdkInstance.createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
372
353
  } catch (error) {
373
354
  const message = error instanceof Error ? error.message : String(error);
374
355
  console.error("[Worker] CreateEIP712 error:", message);
@@ -511,5 +492,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
511
492
  };
512
493
  //#endregion
513
494
  })();
514
- `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function g(e){return e.startsWith(`0x`)?e:`0x${e}`}const _=8192,v=300*1e3;function y(e){let t=[];for(let n=0;n<e.length;n+=_)t.push(String.fromCharCode(...e.subarray(n,n+_)));return btoa(t.join(``))}function b(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ae(e){return`fhe:pubkey:${e}`}function oe(e,t){return`fhe:params:${e}:${t}`}function x(e){return`fhe:params-index:${e}`}function se(e){t.T(e,`CachedPublicKey`),t.D(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.D(e,`publicKey`,`CachedPublicKey.publicKey`)}function S(e){t.T(e,`CachedPublicParams`),t.D(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.D(e,`publicParams`,`CachedPublicParams.publicParams`)}var ce=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=ae(this.#t);try{let e=await this.#e.get(n);if(e){se(e);let t={publicKeyId:e.publicKeyId,publicKey:b(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:y(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.y(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=oe(this.#t,e);try{let t=await this.#e.get(r);if(t){S(t);let n={publicParamsId:t.publicParamsId,publicParams:b(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:y(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=x(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.y(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=ae(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{se(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+v;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+v;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+v;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.y(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=x(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=oe(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.y(n).message}),null}if(!r)return null;try{return S(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.y(n).message})})}async#_(e,n){let r=x(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.y(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.y(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.y(e).message})}))];await Promise.all(i)}},le=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new m(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new ce({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new ie(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},ue=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,i.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),a=[],o=[];for(let e of r)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,o)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,i.getAddress)(e)}:${(0,i.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},C=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const de=new C;var fe=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return g(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function w(e){t.T(e,`Stored credentials`),t.E(e.publicKey,`credentials.publicKey`),t.b(e.contractAddresses,`credentials.contractAddresses`);for(let n of e.contractAddresses)t.S(typeof n==`string`&&(0,i.isAddress)(n,{strict:!1}),`Expected each contractAddress to be a valid hex address`);t.T(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),t.E(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),t.E(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),t.S(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),t.S(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function pe(e){w(e);let n=e;t.S(typeof n.delegatorAddress==`string`&&(0,i.isAddress)(n.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),t.S(typeof n.delegateAddress==`string`&&(0,i.isAddress)(n.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),t.S(typeof n.startTimestamp==`number`,`Expected startTimestamp to be a number`),t.S(typeof n.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,i.getAddress)(e))),r=new Set(e.map(e=>(0,i.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,i.getAddress)(e)))].toSorted()}async function me(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var he=class{#e;constructor(e){this.#e=e}#t(e){t.T(e,`Session entry`),t.E(e.signature,`session.signature`),t.S(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),t.S(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},k=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new he(e.sessionStorage),this.crypto=new fe,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.r.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(D(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(T(e)){if(E(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.a)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:t.y(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.r.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.r.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.a)throw n;return t.W(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=O([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}};function ge(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var A=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t){return me((0,i.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ge(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof C&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){w(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,i.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let a=await e.computeStoreKey(t,n);return this.#n=r,this.#t=a,a}},j=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return me((0,i.getAddress)(e),(0,i.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,i.getAddress)(e),r=O(t),a=await this.#i(n);return this.resolveCredentials({key:a,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,i.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,i.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,i.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,i.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){pe(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),a=`${(0,i.getAddress)(n)}:${(0,i.getAddress)(t)}:${r}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(n,t,r);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};function M(e){return(0,i.keccak256)((0,i.toBytes)(e))}const N={ConfidentialTransfer:M(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:M(`Wrapped(address,uint256)`),UnwrapRequested:M(`UnwrapRequested(address,bytes32,bytes32)`),UnwrappedFinalized:M(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:M(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function P(e){return(0,i.getAddress)(g(e.slice(-40)))}function F(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,i.getAddress)(g(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function _e(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return g(L(e,t))}function V(e){return e.topics[0]!==N.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:P(e.topics[1]),to:P(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function H(e){return e.topics[0]!==N.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:P(e.topics[1]),amountIn:z(e.data,0)}}function U(e){return e.topics[0]!==N.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}}function W(e){return e.topics[0]!==N.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}}function ve(e){return e.topics[0]!==N.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:F(e.topics[1]),txId:F(e.topics[2]),to:P(e.topics[3]),returnVal:_e(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ye(e){return V(e)??H(e)??U(e)??W(e)??ve(e)}function be(e){let t=[];for(let n of e){let e=ye(n);e&&t.push(e)}return t}function xe(e){for(let t of e){let e=U(t);if(e)return e}return null}function Se(e){for(let t of e){let e=H(t);if(e)return e}return null}const Ce=[N.ConfidentialTransfer,N.Wrapped,N.UnwrapRequested,N.UnwrappedFinalized,N.UnwrappedStarted],G={DelegatedForUserDecryption:M(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:M(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function K(e){return e.topics[0]!==G.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function q(e){return e.topics[0]!==G.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function we(e){return K(e)??q(e)}function Te(e){let t=[];for(let n of e){let e=we(n);e&&t.push(e)}return t}function Ee(e){for(let t of e){let e=K(t);if(e)return e}return null}function De(e){for(let t of e){let e=q(t);if(e)return e}return null}const Oe=[G.DelegatedForUserDecryption,G.RevokedDelegationForUserDecryption];var ke=class n extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,i.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(r.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,a,s){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=s??{},d=(0,i.getAddress)(n);c||await this.#i(a);let f,p,m=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-m}),J(()=>l?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.h(this.address,d,f[0],p));return this.emit({type:t.r.TransferSubmitted,txHash:e}),J(()=>u?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:t.y(n)}),n instanceof e.a?n:new o(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,a,s,c){let l=(0,i.getAddress)(n),u=(0,i.getAddress)(a),d,f,p=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:d,inputProof:f}=await this.sdk.relayer.encrypt({values:[{value:s,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-p}),J(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.g(this.address,l,u,d[0],f));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),J(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:t.y(n)}),n instanceof e.a?n:new o(`TransferFrom transaction failed`,{cause:n})}}async approve(n,o){let s=(0,i.getAddress)(n);try{let e=await this.sdk.signer.writeContract(r.y(this.address,s,o));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:t.y(n)}),n instanceof e.a?n:new a(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,i.getAddress)(e),a=t?(0,i.getAddress)(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(r._(this.address,a,n))}async shield(n,a){let s=await this.#n(),l;try{let e=await this.sdk.signer.getAddress();l=await this.sdk.signer.readContract(t.d(s,e))}catch(n){throw n instanceof e.a?n:new u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:t.y(n)})}if(l<n)throw new c(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let d=a?.approvalStrategy??`exact`;d!==`skip`&&await this.#o(n,d===`max`,a);try{let e=a?.to?(0,i.getAddress)(a.to):await this.sdk.signer.getAddress(),o=await this.sdk.signer.writeContract(r.E(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:o}),J(()=>a?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.signer.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:t.y(n)}),n instanceof e.a?n:new o(`Shield transaction failed`,{cause:n})}}async unwrap(n){let i=await this.sdk.signer.getAddress(),a,s,c=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:a,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.x(this.address,i,i,a[0],s));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.sdk.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(t._(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.sdk.signer.writeContract(r.S(this.address,n,n,i));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return J(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return J(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];t.x(a,`finalizeUnwrap: clearValue`);try{let e=await this.sdk.signer.writeContract(r.C(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(t.l(r,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(t.u(r,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(t.u(r,this.wrapper,i));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:t.y(n)}),n instanceof e.a?n:new a(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.N(`Expiration date must be at least 1 hour in the future`);let a=(0,i.getAddress)(n),s=await this.sdk.signer.getAddress();if(a===(0,i.getAddress)(s))throw new t.R(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.M(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,u;try{u=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch{u=-1n}if(u===l)throw new t.F(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,i.getAddress)(n),a=await this.sdk.signer.getAddress(),s=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:r})}catch{c=1n}if(c===0n)throw new t.I(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(t.c(s,r,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new o(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{n=await this.balanceOf()}catch(t){throw t instanceof e.a?t:new l(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new s(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new o(`Failed to get unshield receipt`,{cause:t})}let s=xe(a.logs);if(!s)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),J(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),J(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let o=await this.#n(),s=await this.sdk.signer.getAddress(),c=await this.sdk.signer.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.sdk.signer.writeContract(t.u(o,this.wrapper,0n));let e=r?2n**256n-1n:n,a=await this.sdk.signer.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:a}),J(()=>i?.onApprovalSubmitted?.(a))}catch(t){throw t instanceof e.a?t:new a(`ERC-20 approval failed`,{cause:t})}}};function J(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ae={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},Y=300*1e3;var X=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Ae,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,i.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.m(e.tokenAddress)),this.signer.readContract(t.h(e.tokenAddress)),this.signer.readContract(t.f(e.tokenAddress)),this.signer.readContract(t.p(e.tokenAddress)),this.signer.readContract(t.m(e.confidentialTokenAddress)),this.signer.readContract(t.h(e.confidentialTokenAddress)),this.signer.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ct:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ut:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,i.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,i.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,i.getAddress)(e)))}};const Z=365*86400;var je=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new C,this.cache=new ue(e.storage),this.#t=e.onEvent??function(){},this.registry=new X({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Z?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new A(n),this.delegatedCredentials=new j(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.emitEvent({type:t.r.TransactionError,operation:e,error:t.y(n)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=(0,i.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await A.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new ke(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,i.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)t._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),s=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?s.push(e):r[e.handle]=t}if(s.length===0)return r;let c=await this.credentials.allow(...new Set(n.map(e=>e.contractAddress))),l=new Map;for(let e of s){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}let u=Date.now(),d=s.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:d}),await t.n([...l.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:o,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of d){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-u,handles:d,result:e}),r}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:t.y(e),durationMs:Date.now()-u,handles:d}),t.O(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.O(e,`Public decryption failed`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await A.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function Me(e,t,n){await e.set(Q(t),n)}async function Ne(e,t){return e.get(Q(t))}async function Pe(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Fe=new $;exports.ACL_TOPICS=Oe,exports.AclPausedError=t.k,exports.AclTopics=G,exports.ApprovalFailedError=a,exports.BalanceCheckUnavailableError=l,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=A,exports.DecryptCache=ue,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=Ae,exports.DelegatedCredentialsManager=j,exports.DelegationContractIsSelfError=t.A,exports.DelegationCooldownError=t.j,exports.DelegationDelegateEqualsContractError=t.M,exports.DelegationExpirationTooSoonError=t.N,exports.DelegationExpiredError=t.P,exports.DelegationExpiryUnchangedError=t.F,exports.DelegationNotFoundError=t.I,exports.DelegationNotPropagatedError=t.L,exports.DelegationSelfNotAllowedError=t.R,exports.ERC20ReadFailedError=u,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=m,exports.InsufficientConfidentialBalanceError=s,exports.InsufficientERC20BalanceError=c,exports.InvalidKeypairError=t.z,exports.KeypairExpiredError=t.B,exports.MainnetConfig=n.o,exports.MemoryStorage=C,exports.NoCiphertextError=t.V,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=le,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.H,exports.SigningRejectedError=t.U,exports.TOKEN_TOPICS=Ce,exports.Token=ke,exports.Topics=N,exports.TransactionRevertedError=o,exports.WrappersRegistry=X,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=je,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.chromeSessionStorage=Fe,exports.clearPendingUnshield=Pe,exports.confidentialBalanceOfContract=r.p,exports.confidentialTotalSupplyContract=r.m,exports.confidentialTransferContract=r.h,exports.confidentialTransferFromContract=r.g,exports.decimalsContract=t.f,exports.decodeAclEvent=we,exports.decodeAclEvents=Te,exports.decodeConfidentialTransfer=V,exports.decodeDelegatedForUserDecryption=K,exports.decodeOnChainEvent=ye,exports.decodeOnChainEvents=be,exports.decodeRevokedDelegationForUserDecryption=q,exports.decodeUnwrapRequested=U,exports.decodeUnwrappedFinalized=W,exports.decodeUnwrappedStarted=ve,exports.decodeWrapped=H,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=r.C,exports.findDelegatedForUserDecryption=Ee,exports.findRevokedDelegationForUserDecryption=De,exports.findUnwrapRequested=xe,exports.findWrapped=Se,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.indexedDBStorage=ee,exports.inferredTotalSupplyContract=r.w,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=r._,exports.isZeroHandle=t._,exports.loadPendingUnshield=Ne,exports.matchAclRevert=p,exports.matchZamaError=e.s,exports.memoryStorage=de,exports.nameContract=t.m,exports.rateContract=r.v,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=Me,exports.setOperatorContract=r.y,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.h,exports.totalSupplyContract=r.b,exports.underlyingContract=r.T,exports.unwrapContract=r.x,exports.unwrapFromBalanceContract=r.S,exports.wrapContract=r.E;
495
+ `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function g(e){return e.startsWith(`0x`)?e:`0x${e}`}const _=8192,v=300*1e3;function y(e){let t=[];for(let n=0;n<e.length;n+=_)t.push(String.fromCharCode(...e.subarray(n,n+_)));return btoa(t.join(``))}function b(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ae(e){return`fhe:pubkey:${e}`}function oe(e,t){return`fhe:params:${e}:${t}`}function x(e){return`fhe:params-index:${e}`}function se(e){t.T(e,`CachedPublicKey`),t.D(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.D(e,`publicKey`,`CachedPublicKey.publicKey`)}function S(e){t.T(e,`CachedPublicParams`),t.D(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.D(e,`publicParams`,`CachedPublicParams.publicParams`)}var ce=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=ae(this.#t);try{let e=await this.#e.get(n);if(e){se(e);let t={publicKeyId:e.publicKeyId,publicKey:b(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:y(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.y(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=oe(this.#t,e);try{let t=await this.#e.get(r);if(t){S(t);let n={publicParamsId:t.publicParamsId,publicParams:b(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:y(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=x(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.y(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=ae(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{se(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+v;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+v;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+v;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.y(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=x(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=oe(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.y(n).message}),null}if(!r)return null;try{return S(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.y(n).message})})}async#_(e,n){let r=x(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.y(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.y(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.y(e).message})}))];await Promise.all(i)}},le=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new m(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new ce({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new ie(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){return(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.c(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.c(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.c(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.c(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.c(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},ue=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,i.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),a=[],o=[];for(let e of r)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,o)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,i.getAddress)(e)}:${(0,i.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},C=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const de=new C;var fe=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return g(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function w(e){t.T(e,`Stored credentials`),t.E(e.publicKey,`credentials.publicKey`),t.b(e.contractAddresses,`credentials.contractAddresses`);for(let n of e.contractAddresses)t.S(typeof n==`string`&&(0,i.isAddress)(n,{strict:!1}),`Expected each contractAddress to be a valid hex address`);t.T(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),t.E(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),t.E(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),t.S(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),t.S(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function pe(e){w(e);let n=e;t.S(typeof n.delegatorAddress==`string`&&(0,i.isAddress)(n.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),t.S(typeof n.delegateAddress==`string`&&(0,i.isAddress)(n.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),t.S(typeof n.startTimestamp==`number`,`Expected startTimestamp to be a number`),t.S(typeof n.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,i.getAddress)(e))),r=new Set(e.map(e=>(0,i.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,i.getAddress)(e)))].toSorted()}async function me(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var he=class{#e;constructor(e){this.#e=e}#t(e){t.T(e,`Session entry`),t.E(e.signature,`session.signature`),t.S(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),t.S(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},k=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new he(e.sessionStorage),this.crypto=new fe,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.r.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(D(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(T(e)){if(E(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.a)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:t.y(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.r.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.r.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.a)throw n;return t.W(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=O([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}};function ge(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var A=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t){return me((0,i.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ge(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof C&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){w(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,i.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let a=await e.computeStoreKey(t,n);return this.#n=r,this.#t=a,a}},j=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return me((0,i.getAddress)(e),(0,i.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,i.getAddress)(e),r=O(t),a=await this.#i(n);return this.resolveCredentials({key:a,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,i.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,i.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,i.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,i.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){pe(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),a=`${(0,i.getAddress)(n)}:${(0,i.getAddress)(t)}:${r}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(n,t,r);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}};function M(e){return(0,i.keccak256)((0,i.toBytes)(e))}const N={ConfidentialTransfer:M(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:M(`Wrapped(address,uint256)`),UnwrapRequested:M(`UnwrapRequested(address,bytes32,bytes32)`),UnwrappedFinalized:M(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:M(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function P(e){return(0,i.getAddress)(g(e.slice(-40)))}function F(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,i.getAddress)(g(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function _e(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return g(L(e,t))}function V(e){return e.topics[0]!==N.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:P(e.topics[1]),to:P(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function H(e){return e.topics[0]!==N.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:P(e.topics[1]),amountIn:z(e.data,0)}}function U(e){return e.topics[0]!==N.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}}function W(e){return e.topics[0]!==N.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}}function ve(e){return e.topics[0]!==N.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:F(e.topics[1]),txId:F(e.topics[2]),to:P(e.topics[3]),returnVal:_e(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ye(e){return V(e)??H(e)??U(e)??W(e)??ve(e)}function be(e){let t=[];for(let n of e){let e=ye(n);e&&t.push(e)}return t}function xe(e){for(let t of e){let e=U(t);if(e)return e}return null}function Se(e){for(let t of e){let e=H(t);if(e)return e}return null}const Ce=[N.ConfidentialTransfer,N.Wrapped,N.UnwrapRequested,N.UnwrappedFinalized,N.UnwrappedStarted],G={DelegatedForUserDecryption:M(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:M(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function K(e){return e.topics[0]!==G.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function q(e){return e.topics[0]!==G.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function we(e){return K(e)??q(e)}function Te(e){let t=[];for(let n of e){let e=we(n);e&&t.push(e)}return t}function Ee(e){for(let t of e){let e=K(t);if(e)return e}return null}function De(e){for(let t of e){let e=q(t);if(e)return e}return null}const Oe=[G.DelegatedForUserDecryption,G.RevokedDelegationForUserDecryption];var ke=class n extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,i.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(r.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,a,s){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=s??{},d=(0,i.getAddress)(n);c||await this.#i(a);let f,p,m=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-m}),J(()=>l?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.h(this.address,d,f[0],p));return this.emit({type:t.r.TransferSubmitted,txHash:e}),J(()=>u?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:t.y(n)}),n instanceof e.a?n:new o(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,a,s,c){let l=(0,i.getAddress)(n),u=(0,i.getAddress)(a),d,f,p=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:d,inputProof:f}=await this.sdk.relayer.encrypt({values:[{value:s,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-p}),J(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.g(this.address,l,u,d[0],f));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),J(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:t.y(n)}),n instanceof e.a?n:new o(`TransferFrom transaction failed`,{cause:n})}}async approve(n,o){let s=(0,i.getAddress)(n);try{let e=await this.sdk.signer.writeContract(r.y(this.address,s,o));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:t.y(n)}),n instanceof e.a?n:new a(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,i.getAddress)(e),a=t?(0,i.getAddress)(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(r._(this.address,a,n))}async shield(n,a){let s=await this.#n(),l;try{let e=await this.sdk.signer.getAddress();l=await this.sdk.signer.readContract(t.d(s,e))}catch(n){throw n instanceof e.a?n:new u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:t.y(n)})}if(l<n)throw new c(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let d=a?.approvalStrategy??`exact`;d!==`skip`&&await this.#o(n,d===`max`,a);try{let e=a?.to?(0,i.getAddress)(a.to):await this.sdk.signer.getAddress(),o=await this.sdk.signer.writeContract(r.E(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:o}),J(()=>a?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.signer.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:t.y(n)}),n instanceof e.a?n:new o(`Shield transaction failed`,{cause:n})}}async unwrap(n){let i=await this.sdk.signer.getAddress(),a,s,c=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:a,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.x(this.address,i,i,a[0],s));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.sdk.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(t._(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.sdk.signer.writeContract(r.S(this.address,n,n,i));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return J(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return J(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];t.x(a,`finalizeUnwrap: clearValue`);try{let e=await this.sdk.signer.writeContract(r.C(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(t.l(r,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(t.u(r,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(t.u(r,this.wrapper,i));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:t.y(n)}),n instanceof e.a?n:new a(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.N(`Expiration date must be at least 1 hour in the future`);let a=(0,i.getAddress)(n),s=await this.sdk.signer.getAddress();if(a===(0,i.getAddress)(s))throw new t.R(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.M(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,u;try{u=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch{u=-1n}if(u===l)throw new t.F(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,i.getAddress)(n),a=await this.sdk.signer.getAddress(),s=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:r})}catch{c=1n}if(c===0n)throw new t.I(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(t.c(s,r,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new o(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{n=await this.balanceOf()}catch(t){throw t instanceof e.a?t:new l(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new s(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new o(`Failed to get unshield receipt`,{cause:t})}let s=xe(a.logs);if(!s)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),J(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),J(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let o=await this.#n(),s=await this.sdk.signer.getAddress(),c=await this.sdk.signer.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.sdk.signer.writeContract(t.u(o,this.wrapper,0n));let e=r?2n**256n-1n:n,a=await this.sdk.signer.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:a}),J(()=>i?.onApprovalSubmitted?.(a))}catch(t){throw t instanceof e.a?t:new a(`ERC-20 approval failed`,{cause:t})}}};function J(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ae={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},Y=300*1e3;var X=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Ae,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,i.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.m(e.tokenAddress)),this.signer.readContract(t.h(e.tokenAddress)),this.signer.readContract(t.f(e.tokenAddress)),this.signer.readContract(t.p(e.tokenAddress)),this.signer.readContract(t.m(e.confidentialTokenAddress)),this.signer.readContract(t.h(e.confidentialTokenAddress)),this.signer.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ct:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ut:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,i.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,i.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,i.getAddress)(e)))}};const Z=365*86400;var je=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new C,this.cache=new ue(e.storage),this.#t=e.onEvent??function(){},this.registry=new X({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Z?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new A(n),this.delegatedCredentials=new j(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.emitEvent({type:t.r.TransactionError,operation:e,error:t.y(n)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=(0,i.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await A.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new ke(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,i.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)t._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),s=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?s.push(e):r[e.handle]=t}if(s.length===0)return r;let c=await this.credentials.allow(...new Set(n.map(e=>e.contractAddress))),l=new Map;for(let e of s){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}let u=Date.now(),d=s.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:d}),await t.n([...l.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:o,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of d){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-u,handles:d,result:e}),r}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:t.y(e),durationMs:Date.now()-u,handles:d}),t.O(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.O(e,`Public decryption failed`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await A.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function Me(e,t,n){await e.set(Q(t),n)}async function Ne(e,t){return e.get(Q(t))}async function Pe(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Fe=new $;exports.ACL_TOPICS=Oe,exports.AclPausedError=t.k,exports.AclTopics=G,exports.ApprovalFailedError=a,exports.BalanceCheckUnavailableError=l,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=A,exports.DecryptCache=ue,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=Ae,exports.DelegatedCredentialsManager=j,exports.DelegationContractIsSelfError=t.A,exports.DelegationCooldownError=t.j,exports.DelegationDelegateEqualsContractError=t.M,exports.DelegationExpirationTooSoonError=t.N,exports.DelegationExpiredError=t.P,exports.DelegationExpiryUnchangedError=t.F,exports.DelegationNotFoundError=t.I,exports.DelegationNotPropagatedError=t.L,exports.DelegationSelfNotAllowedError=t.R,exports.ERC20ReadFailedError=u,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=m,exports.InsufficientConfidentialBalanceError=s,exports.InsufficientERC20BalanceError=c,exports.InvalidKeypairError=t.z,exports.KeypairExpiredError=t.B,exports.MainnetConfig=n.o,exports.MemoryStorage=C,exports.NoCiphertextError=t.V,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=le,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.H,exports.SigningRejectedError=t.U,exports.TOKEN_TOPICS=Ce,exports.Token=ke,exports.Topics=N,exports.TransactionRevertedError=o,exports.WrappersRegistry=X,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=je,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.chromeSessionStorage=Fe,exports.clearPendingUnshield=Pe,exports.confidentialBalanceOfContract=r.p,exports.confidentialTotalSupplyContract=r.m,exports.confidentialTransferContract=r.h,exports.confidentialTransferFromContract=r.g,exports.decimalsContract=t.f,exports.decodeAclEvent=we,exports.decodeAclEvents=Te,exports.decodeConfidentialTransfer=V,exports.decodeDelegatedForUserDecryption=K,exports.decodeOnChainEvent=ye,exports.decodeOnChainEvents=be,exports.decodeRevokedDelegationForUserDecryption=q,exports.decodeUnwrapRequested=U,exports.decodeUnwrappedFinalized=W,exports.decodeUnwrappedStarted=ve,exports.decodeWrapped=H,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=r.C,exports.findDelegatedForUserDecryption=Ee,exports.findRevokedDelegationForUserDecryption=De,exports.findUnwrapRequested=xe,exports.findWrapped=Se,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.indexedDBStorage=ee,exports.inferredTotalSupplyContract=r.w,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=r._,exports.isZeroHandle=t._,exports.loadPendingUnshield=Ne,exports.matchAclRevert=p,exports.matchZamaError=e.s,exports.memoryStorage=de,exports.nameContract=t.m,exports.rateContract=r.v,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=Me,exports.setOperatorContract=r.y,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.h,exports.totalSupplyContract=r.b,exports.underlyingContract=r.T,exports.unwrapContract=r.x,exports.unwrapFromBalanceContract=r.S,exports.wrapContract=r.E;
515
496
  //# sourceMappingURL=index.cjs.map