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

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 (99) hide show
  1. package/README.md +207 -122
  2. package/dist/cjs/build.cjs +2 -0
  3. package/dist/cjs/build.cjs.map +1 -0
  4. package/dist/cjs/chains/index.cjs +1 -0
  5. package/dist/cjs/chains.cjs +2 -0
  6. package/dist/cjs/chains.cjs.map +1 -0
  7. package/dist/cjs/cleartext/index.cjs +1 -1
  8. package/dist/cjs/eip1193-subscribe.cjs +1 -1
  9. package/dist/cjs/eip1193-subscribe.cjs.map +1 -1
  10. package/dist/cjs/encryption.cjs +2 -0
  11. package/dist/cjs/encryption.cjs.map +1 -0
  12. package/dist/cjs/ethers/index.cjs +1 -1
  13. package/dist/cjs/ethers/index.cjs.map +1 -1
  14. package/dist/cjs/index.cjs +73 -73
  15. package/dist/cjs/index.cjs.map +1 -1
  16. package/dist/cjs/query/index.cjs +1 -1
  17. package/dist/cjs/query/index.cjs.map +1 -1
  18. package/dist/cjs/readonly-token.cjs +1 -1
  19. package/dist/cjs/readonly-token.cjs.map +1 -1
  20. package/dist/cjs/relayer-cleartext.cjs +2 -0
  21. package/dist/cjs/relayer-cleartext.cjs.map +1 -0
  22. package/dist/cjs/relayer-sdk.worker.js +71 -71
  23. package/dist/cjs/relayer.cjs +1 -1
  24. package/dist/cjs/relayer.cjs.map +1 -1
  25. package/dist/cjs/viem/index.cjs +1 -1
  26. package/dist/cjs/viem/index.cjs.map +1 -1
  27. package/dist/cjs/wrappers-registry.cjs +1 -1
  28. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  29. package/dist/esm/{assertions-BARApuMj.js → assertions-CfqI3AJv.js} +1 -1
  30. package/dist/esm/{assertions-BARApuMj.js.map → assertions-CfqI3AJv.js.map} +1 -1
  31. package/dist/esm/build-CvenCk6R.js +2 -0
  32. package/dist/esm/build-CvenCk6R.js.map +1 -0
  33. package/dist/esm/chains/index.d.ts +3 -0
  34. package/dist/esm/chains/index.js +1 -0
  35. package/dist/esm/chains-aHmrozPh.js +2 -0
  36. package/dist/esm/chains-aHmrozPh.js.map +1 -0
  37. package/dist/esm/cleartext/index.d.ts +2 -86
  38. package/dist/esm/cleartext/index.js +1 -1
  39. package/dist/esm/cleartext-BHu6-LCv.d.ts +19 -0
  40. package/dist/esm/cleartext-I-etE_7S.js +2 -0
  41. package/dist/esm/cleartext-I-etE_7S.js.map +1 -0
  42. package/dist/esm/eip1193-subscribe-CcotSOIm.js +2 -0
  43. package/dist/esm/eip1193-subscribe-CcotSOIm.js.map +1 -0
  44. package/dist/esm/{encryption-CmIPBcfP.js → encryption-YS-Kb7qm.js} +2 -2
  45. package/dist/esm/{encryption-CmIPBcfP.js.map → encryption-YS-Kb7qm.js.map} +1 -1
  46. package/dist/esm/ethers/index.d.ts +53 -8
  47. package/dist/esm/ethers/index.js +1 -1
  48. package/dist/esm/ethers/index.js.map +1 -1
  49. package/dist/esm/{hex-D_B-zoId.js → hex-BZVTzEK6.js} +2 -2
  50. package/dist/esm/{hex-D_B-zoId.js.map → hex-BZVTzEK6.js.map} +1 -1
  51. package/dist/esm/{relayer-utils-iSPis4x-.d.ts → index-BTY0MxOt.d.ts} +50 -23
  52. package/dist/esm/{onchain-events-2VNiL78c.d.ts → index-BdyljG1F.d.ts} +387 -1505
  53. package/dist/esm/index.d.ts +61 -93
  54. package/dist/esm/index.js +73 -73
  55. package/dist/esm/index.js.map +1 -1
  56. package/dist/esm/memory-storage-CFXqXUcm.js +2 -0
  57. package/dist/esm/memory-storage-CFXqXUcm.js.map +1 -0
  58. package/dist/esm/node/index.d.ts +88 -110
  59. package/dist/esm/node/index.js +1 -1
  60. package/dist/esm/node/index.js.map +1 -1
  61. package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
  62. package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
  63. package/dist/esm/query/index.d.ts +40 -50
  64. package/dist/esm/query/index.js +1 -1
  65. package/dist/esm/query/index.js.map +1 -1
  66. package/dist/esm/readonly-token-DCLOYhws.js +2 -0
  67. package/dist/esm/readonly-token-DCLOYhws.js.map +1 -0
  68. package/dist/esm/{relayer-C6u3eOlN.js → relayer-7Hd00A6X.js} +2 -2
  69. package/dist/esm/relayer-7Hd00A6X.js.map +1 -0
  70. package/dist/esm/{relayer-sdk.types-CGfXwKcB.d.ts → relayer-cleartext-DJkSUlZ2.d.ts} +263 -106
  71. package/dist/esm/relayer-cleartext-SZCM9wTx.js +2 -0
  72. package/dist/esm/relayer-cleartext-SZCM9wTx.js.map +1 -0
  73. package/dist/esm/relayer-sdk.worker.js +71 -71
  74. package/dist/esm/types-C1S426x4.d.ts +48 -0
  75. package/dist/esm/types-CVyJHEya.d.ts +14 -0
  76. package/dist/esm/types-DePjTTbo.d.ts +30 -0
  77. package/dist/esm/types-FY7ciI37.d.ts +615 -0
  78. package/dist/esm/viem/index.d.ts +39 -11
  79. package/dist/esm/viem/index.js +1 -1
  80. package/dist/esm/viem/index.js.map +1 -1
  81. package/dist/esm/wrappers-registry-CXNs4eR0.js +2 -0
  82. package/dist/esm/wrappers-registry-CXNs4eR0.js.map +1 -0
  83. package/package.json +17 -3
  84. package/dist/cjs/cleartext.cjs +0 -2
  85. package/dist/cjs/cleartext.cjs.map +0 -1
  86. package/dist/esm/cleartext-Cs28cTsa.js +0 -2
  87. package/dist/esm/cleartext-Cs28cTsa.js.map +0 -1
  88. package/dist/esm/eip1193-subscribe-Cl_wlVuQ.js +0 -2
  89. package/dist/esm/eip1193-subscribe-Cl_wlVuQ.js.map +0 -1
  90. package/dist/esm/memory-storage-F8xjMzVy.js +0 -2
  91. package/dist/esm/memory-storage-F8xjMzVy.js.map +0 -1
  92. package/dist/esm/readonly-token-D4GjTj0q.js +0 -2
  93. package/dist/esm/readonly-token-D4GjTj0q.js.map +0 -1
  94. package/dist/esm/relayer-C6u3eOlN.js.map +0 -1
  95. package/dist/esm/relayer-sdk-DPqytEbO.d.ts +0 -44
  96. package/dist/esm/relayer-utils-BeoTNDM4.js +0 -2
  97. package/dist/esm/relayer-utils-BeoTNDM4.js.map +0 -1
  98. package/dist/esm/wrappers-registry-ydyySM9g.js +0 -2
  99. package/dist/esm/wrappers-registry-ydyySM9g.js.map +0 -1
@@ -1,8 +1,5 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./cleartext.cjs`),r=require(`./wrappers-registry.cjs`);let i=require(`viem`);var a=class extends e.a{constructor(t,n){super(e.o.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},o=class extends e.a{constructor(t,n){super(e.o.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},s=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},c=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},l=class extends e.a{constructor(t,n){super(e.o.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},u=class extends e.a{constructor(t,n){super(e.o.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function d(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const f={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.j(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.A(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.k(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.R(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.M(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.N(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.F(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.I(`Cannot revoke: no active delegation exists.`,{cause:e})};function p(e){let t=e instanceof Error?e:void 0,n=d(e);if(n&&n in f)return f[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(f))if(r.includes(e))return n(t);return null}var m=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{console.warn(`IndexedDB "${this.#n}" closing due to version change from another tab`),this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const ee=new m,h=3e4;var te=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=h){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=h){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(){return this.sendRequest(`GENERATE_KEYPAIR`,{})}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,{handles:e})}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,{zkProof:e})}async getPublicKey(){return this.sendRequest(`GET_PUBLIC_KEY`,{})}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,{bits:e})}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function ne(e){try{return t.T(e,`runtime`),t.D(e,`id`,`runtime.id`),t.C(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function re(){let e=globalThis;for(let n of[e.chrome,e.browser])try{if(t.T(n,`ns`),ne(n.runtime))return n.runtime}catch{continue}}var ie=class extends te{constructor(e){super(e,e.logger)}createWorker(){let e=re();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./build.cjs`),t=require(`./relayer.cjs`),n=require(`./readonly-token.cjs`),r=require(`./encryption.cjs`),i=require(`./wrappers-registry.cjs`),a=require(`./relayer-cleartext.cjs`),o=require(`./chains.cjs`);let s=require(`viem`);var c=class extends t.r{constructor(e,n){super(t.i.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},l=class extends t.r{constructor(e,n){super(t.i.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},u=class extends t.r{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:n,providerChainId:r},i){super(t.i.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=n,this.providerChainId=r}},d=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},f=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},p=class extends t.r{constructor(e,n){super(t.i.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},m=class extends t.r{constructor(e,n){super(t.i.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function h(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const g={AlreadyDelegatedOrRevokedInSameBlock:e=>new n.x(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new n.b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new n.y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new n.O(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new n.S(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new n.C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new n.T(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new n.E(`Cannot revoke: no active delegation exists.`,{cause:e})};function _(e){let t=e instanceof Error?e:void 0,n=h(e);if(n&&n in g)return g[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(g))if(r.includes(e))return n(t);return null}var ee=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){if(!this.chain.aclContractAddress)throw new t.t(`No ACL address configured for chain ${this.chain.id}`);return this.chain.aclContractAddress}};function v(e){return e.startsWith(`0x`)?e:`0x${e}`}const y=8192,b=300*1e3;function te(e){let t=[];for(let n=0;n<e.length;n+=y)t.push(String.fromCharCode(...e.subarray(n,n+y)));return btoa(t.join(``))}function ne(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 x(e){return`fhe:pubkey:${e}`}function S(e,t){return`fhe:params:${e}:${t}`}function C(e){return`fhe:params-index:${e}`}function re(e){i.N(e,`CachedPublicKey`),i.F(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),i.F(e,`publicKey`,`CachedPublicKey.publicKey`)}function ie(e){i.N(e,`CachedPublicParams`),i.F(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),i.F(e,`publicParams`,`CachedPublicParams.publicParams`)}var ae=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 t=x(this.#t);try{let e=await this.#e.get(t);if(e){re(e);let t={publicKeyId:e.publicKeyId,publicKey:ne(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(t),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:i.L(e).message})}let n=await e();if(n===null)return null;this.#a=n;try{let e={publicKeyId:n.publicKeyId,publicKey:te(n.publicKey),lastValidatedAt:Date.now()};await this.#e.set(t,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:i.L(e).message})}return n}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,t){let n=S(this.#t,e);try{let t=await this.#e.get(n);if(t){ie(t);let n={publicParamsId:t.publicParamsId,publicParams:ne(t.publicParams)};return this.#o.set(e,n),n}}catch(t){await this.#g(n),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:i.L(t).message})}let r=await t();if(r===null)return null;this.#o.set(e,r);try{let t={publicParamsId:r.publicParamsId,publicParams:te(r.publicParams),lastValidatedAt:Date.now()};await this.#e.set(n,t);let a=C(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:i.L(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(t){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:i.L(t).message})}return r}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 t=x(this.#t),n=null,r=[];try{let[a,o]=await Promise.all([this.#e.get(t),this.#h()]);if(a)try{re(a),n={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:i.L(e).message}),await this.#g(t)}if(r=o,!n)return!1;if([n,...r.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 i=e-this.#r+b;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let c=await s.json(),l=c?.response?.fheKeyInfo?.[0];if(!c||typeof c!=`object`||c.status!==`succeeded`||!l?.fhePublicKey?.urls?.length||typeof c.response?.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 i=e-this.#r+b;return await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let u=c.response,d=l.fhePublicKey.urls[0];if(n.artifactUrl&&d&&d!==n.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let f={...n,lastValidatedAt:e};if(d){let e=await this.#m(d,n);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;f={...f,artifactUrl:d,etag:e.etag,lastModified:e.lastModified}}let p=[];for(let n of r){let i=u.crs[String(n.bits)]?.urls[0];if(n.data.artifactUrl&&i&&i!==n.data.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let a={...n.data,lastValidatedAt:e};if(i){let e=await this.#m(i,n.data);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;a={...a,artifactUrl:i,etag:e.etag,lastModified:e.lastModified}}p.push({...n,data:a})}return await this.#v(t,f,p),this.#u=e,!1}catch(a){let o=i.L(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+b;try{n&&await this.#v(t,{...n,lastValidatedAt:l},r.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:i.L(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=C(this.#t),t=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:i.L(e).message}),null))??[],n=new Set([...this.#o.keys(),...t]),r=Array.from(n);return(await Promise.all(r.map(async e=>{let t=S(this.#t,e),n;try{n=await this.#e.get(t)}catch(t){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:i.L(t).message}),null}if(!n)return null;try{return ie(n),{bits:e,key:t,data:{...n,lastValidatedAt:n.lastValidatedAt??0}}}catch(n){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:i.L(n).message}),await this.#g(t),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(t=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:i.L(t).message})})}async#_(e,t){let n=C(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(n),...t.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:i.L(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,t,n){let r=[this.#e.set(e,t).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:i.L(e).message})}),...n.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:i.L(e).message})}))];await Promise.all(r)}};async function w(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&oe(e)){await se(500*2**r);continue}throw e}throw n}function oe(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 se(e){return new Promise(t=>setTimeout(t,e))}var ce=class extends ee{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new e.o(`FheArtifactCache`,1,`artifacts`),new ae({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateKeypair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;await this.ensureInit();let i=this.chain.id;return w(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:i,values:t,contractAddress:n,userAddress:r});return{handles:e.handles,inputProof:e.inputProof}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,handles:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async getPublicKey(){await this.ensureInit();let e=this.chain.id;return this.#i().getPublicKey(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}};const le=3e4;var ue=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=le){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=le){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function de(e){try{return i.N(e,`runtime`),i.F(e,`id`,`runtime.id`),i.j(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function fe(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(i.N(t,`ns`),de(t.runtime))return t.runtime}catch{continue}}var pe=class extends ue{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=fe();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
2
2
  //#region src/utils/assertions.ts
3
- function assertNonNullable(value, context) {
4
- if (value === null || value === void 0) throw new TypeError(\`\${context} must not be null or undefined\`);
5
- }
6
3
  function assertObject(value, context) {
7
4
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
8
5
  }
@@ -63,19 +60,46 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
63
60
  }
64
61
  //#endregion
65
62
  //#region src/worker/relayer-sdk.worker.ts
66
- let sdkInstance = null;
63
+ const instances = /* @__PURE__ */ new Map();
64
+ const pending = /* @__PURE__ */ new Map();
65
+ const configs = /* @__PURE__ */ new Map();
66
+ /** Convert an FheChain to the FhevmInstanceConfig shape expected by createInstance. */
67
+ function toInstanceConfig(chain) {
68
+ return {
69
+ ...chain,
70
+ chainId: chain.id
71
+ };
72
+ }
67
73
  let sdkGlobal = null;
68
- function assertSdkInstance(instance) {
69
- try {
70
- assertNonNullable(instance, "Relayer SDK instance");
71
- } catch (error) {
72
- throw new Error("Relayer SDK is not initialized. Call INIT first.", { cause: error });
73
- }
74
+ /**
75
+ * Get or lazily create an FhevmInstance for the given chain.
76
+ */
77
+ async function getInstance(chainId) {
78
+ const existing = instances.get(chainId);
79
+ if (existing) return existing;
80
+ const inflight = pending.get(chainId);
81
+ if (inflight) return inflight;
82
+ const config = configs.get(chainId);
83
+ if (!config) throw new Error(\`No config for chain \${chainId}. Available: [\${[...configs.keys()].join(", ")}]\`);
84
+ if (!sdkGlobal) throw new Error("Relayer SDK is not initialized. Call INIT first.");
85
+ const promise = sdkGlobal.createInstance({
86
+ ...toInstanceConfig(config),
87
+ batchRpcCalls: false
88
+ }).then((instance) => {
89
+ instances.set(chainId, instance);
90
+ pending.delete(chainId);
91
+ return instance;
92
+ }).catch((err) => {
93
+ pending.delete(chainId);
94
+ throw err;
95
+ });
96
+ pending.set(chainId, promise);
97
+ return promise;
74
98
  }
75
99
  function unreachableFheType(_) {
76
100
  throw new Error("Unsupported FHE type");
77
101
  }
78
- let relayerUrlBase = "";
102
+ const relayerUrls = /* @__PURE__ */ new Set();
79
103
  let csrfTokenBase = "";
80
104
  const CSRF_HEADER_NAME = "x-csrf-token";
81
105
  const MUTATING_METHODS = new Set([
@@ -85,6 +109,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
85
109
  "PATCH"
86
110
  ]);
87
111
  /**
112
+ * Register relayer URLs from chain configs for fetch interception.
113
+ */
114
+ function registerRelayerUrls(chainConfigs) {
115
+ for (const c of chainConfigs) if (c.relayerUrl) relayerUrls.add(c.relayerUrl);
116
+ }
117
+ /**
88
118
  * Send a success response back to the main thread.
89
119
  * Optionally transfers ArrayBuffers for zero-copy performance.
90
120
  */
@@ -138,7 +168,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
138
168
  globalThis.fetch = async (input, init) => {
139
169
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
140
170
  const method = init?.method?.toUpperCase() ?? "GET";
141
- if (relayerUrlBase && url.startsWith(relayerUrlBase)) {
171
+ if (relayerUrls.size > 0 && [...relayerUrls].some((base) => url.startsWith(base))) {
142
172
  const headers = new Headers(init?.headers);
143
173
  if (MUTATING_METHODS.has(method) && csrfTokenBase) headers.set(CSRF_HEADER_NAME, csrfTokenBase);
144
174
  return originalFetch(input, {
@@ -193,24 +223,21 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
193
223
  }
194
224
  }
195
225
  /**
196
- * Handle INIT request - load SDK and initialize WASM.
226
+ * Handle INIT request - load SDK WASM and register chain configs (instances are lazy).
197
227
  */
198
228
  async function handleInit(request) {
199
229
  const { id, type, payload } = request;
200
- const { cdnUrl, fhevmConfig, csrfToken, integrity, thread } = payload;
201
230
  try {
202
- relayerUrlBase = fhevmConfig.relayerUrl ?? "";
231
+ if (payload.env !== "web") throw new Error(\`Web worker received unexpected env: \${payload.env}\`);
232
+ const { cdnUrl, csrfToken, integrity, thread } = payload;
203
233
  csrfTokenBase = csrfToken;
204
234
  setupFetchInterceptor();
205
235
  await loadSdkScript(cdnUrl, integrity);
206
236
  if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
207
237
  sdkGlobal = self.relayerSDK;
208
238
  await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
209
- const config = {
210
- ...fhevmConfig,
211
- batchRpcCalls: false
212
- };
213
- sdkInstance = await sdkGlobal.createInstance(config);
239
+ registerRelayerUrls(payload.chains);
240
+ for (const chain of payload.chains) configs.set(chain.id, chain);
214
241
  sendSuccess(id, type, { initialized: true });
215
242
  } catch (error) {
216
243
  const message = error instanceof Error ? error.message : String(error);
@@ -262,8 +289,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
262
289
  const { id, type, payload } = request;
263
290
  const { values, contractAddress, userAddress } = payload;
264
291
  try {
265
- assertSdkInstance(sdkInstance);
266
- const input = sdkInstance.createEncryptedInput(contractAddress, userAddress);
292
+ const input = (await getInstance(payload.chainId)).createEncryptedInput(contractAddress, userAddress);
267
293
  for (const entry of values) addTypedValue(input, entry);
268
294
  const encrypted = await input.encrypt();
269
295
  sendSuccess(id, type, {
@@ -282,12 +308,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
282
308
  async function handleUserDecrypt(request) {
283
309
  const { id, type, payload } = request;
284
310
  try {
285
- assertSdkInstance(sdkInstance);
311
+ const instance = await getInstance(payload.chainId);
286
312
  const handleContractPairs = payload.handles.map((handle) => ({
287
313
  handle,
288
314
  contractAddress: payload.contractAddress
289
315
  }));
290
- sendSuccess(id, type, { clearValues: await sdkInstance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
316
+ sendSuccess(id, type, { clearValues: await instance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
291
317
  } catch (error) {
292
318
  const message = error instanceof Error ? error.message : String(error);
293
319
  const statusCode = extractHttpStatus(error);
@@ -316,8 +342,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
316
342
  async function handlePublicDecrypt(request) {
317
343
  const { id, type, payload } = request;
318
344
  try {
319
- assertSdkInstance(sdkInstance);
320
- sendSuccess(id, type, { ...await sdkInstance.publicDecrypt(payload.handles) });
345
+ sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.handles) });
321
346
  } catch (error) {
322
347
  const message = error instanceof Error ? error.message : String(error);
323
348
  console.error("[Worker] PublicDecrypt error:", message);
@@ -327,11 +352,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
327
352
  /**
328
353
  * Handle GENERATE_KEYPAIR request.
329
354
  */
330
- function handleGenerateKeypair(request) {
331
- const { id, type } = request;
355
+ async function handleGenerateKeypair(request) {
356
+ const { id, type, payload } = request;
332
357
  try {
333
- assertSdkInstance(sdkInstance);
334
- const keypair = sdkInstance.generateKeypair();
358
+ const keypair = (await getInstance(payload.chainId)).generateKeypair();
335
359
  sendSuccess(id, type, {
336
360
  publicKey: prefixHex(keypair.publicKey),
337
361
  privateKey: prefixHex(keypair.privateKey)
@@ -345,30 +369,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
345
369
  /**
346
370
  * Handle CREATE_EIP712 request.
347
371
  */
348
- function handleCreateEIP712(request) {
372
+ async function handleCreateEIP712(request) {
349
373
  const { id, type, payload } = request;
350
374
  try {
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
- });
375
+ sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
372
376
  } catch (error) {
373
377
  const message = error instanceof Error ? error.message : String(error);
374
378
  console.error("[Worker] CreateEIP712 error:", message);
@@ -378,11 +382,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
378
382
  /**
379
383
  * Handle CREATE_DELEGATED_EIP712 request.
380
384
  */
381
- function handleCreateDelegatedEIP712(request) {
385
+ async function handleCreateDelegatedEIP712(request) {
382
386
  const { id, type, payload } = request;
383
387
  try {
384
- assertSdkInstance(sdkInstance);
385
- sendSuccess(id, type, sdkInstance.createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
388
+ sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
386
389
  } catch (error) {
387
390
  const message = error instanceof Error ? error.message : String(error);
388
391
  console.error("[Worker] CreateDelegatedEIP712 error:", message);
@@ -395,12 +398,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
395
398
  async function handleDelegatedUserDecrypt(request) {
396
399
  const { id, type, payload } = request;
397
400
  try {
398
- assertSdkInstance(sdkInstance);
401
+ const instance = await getInstance(payload.chainId);
399
402
  const handleContractPairs = payload.handles.map((handle) => ({
400
403
  handle,
401
404
  contractAddress: payload.contractAddress
402
405
  }));
403
- sendSuccess(id, type, { clearValues: await sdkInstance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
406
+ sendSuccess(id, type, { clearValues: await instance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
404
407
  } catch (error) {
405
408
  const message = error instanceof Error ? error.message : String(error);
406
409
  const statusCode = extractHttpStatus(error);
@@ -414,8 +417,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
414
417
  async function handleRequestZKProofVerification(request) {
415
418
  const { id, type, payload } = request;
416
419
  try {
417
- assertSdkInstance(sdkInstance);
418
- const result = await sdkInstance.requestZKProofVerification(payload.zkProof);
420
+ const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
419
421
  sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
420
422
  } catch (error) {
421
423
  const message = error instanceof Error ? error.message : String(error);
@@ -426,11 +428,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
426
428
  /**
427
429
  * Handle GET_PUBLIC_KEY request.
428
430
  */
429
- function handleGetPublicKey(request) {
430
- const { id, type } = request;
431
+ async function handleGetPublicKey(request) {
432
+ const { id, type, payload } = request;
431
433
  try {
432
- assertSdkInstance(sdkInstance);
433
- sendSuccess(id, type, { result: sdkInstance.getPublicKey() });
434
+ sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
434
435
  } catch (error) {
435
436
  const message = error instanceof Error ? error.message : String(error);
436
437
  console.error("[Worker] GetPublicKey error:", message);
@@ -440,11 +441,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
440
441
  /**
441
442
  * Handle GET_PUBLIC_PARAMS request.
442
443
  */
443
- function handleGetPublicParams(request) {
444
+ async function handleGetPublicParams(request) {
444
445
  const { id, type, payload } = request;
445
446
  try {
446
- assertSdkInstance(sdkInstance);
447
- sendSuccess(id, type, { result: sdkInstance.getPublicParams(payload.bits) });
447
+ sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
448
448
  } catch (error) {
449
449
  const message = error instanceof Error ? error.message : String(error);
450
450
  console.error("[Worker] GetPublicParams error:", message);
@@ -482,13 +482,13 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
482
482
  await handlePublicDecrypt(request);
483
483
  break;
484
484
  case "GENERATE_KEYPAIR":
485
- handleGenerateKeypair(request);
485
+ await handleGenerateKeypair(request);
486
486
  break;
487
487
  case "CREATE_EIP712":
488
- handleCreateEIP712(request);
488
+ await handleCreateEIP712(request);
489
489
  break;
490
490
  case "CREATE_DELEGATED_EIP712":
491
- handleCreateDelegatedEIP712(request);
491
+ await handleCreateDelegatedEIP712(request);
492
492
  break;
493
493
  case "DELEGATED_USER_DECRYPT":
494
494
  await handleDelegatedUserDecrypt(request);
@@ -497,10 +497,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
497
497
  await handleRequestZKProofVerification(request);
498
498
  break;
499
499
  case "GET_PUBLIC_KEY":
500
- handleGetPublicKey(request);
500
+ await handleGetPublicKey(request);
501
501
  break;
502
502
  case "GET_PUBLIC_PARAMS":
503
- handleGetPublicParams(request);
503
+ await handleGetPublicParams(request);
504
504
  break;
505
505
  default: console.error("[Worker] Unknown request type:", request.type);
506
506
  }
@@ -511,5 +511,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
511
511
  };
512
512
  //#endregion
513
513
  })();
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;
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,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function me(e){return{type:`web`,createWorker:t=>new pe({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:e?.logger,thread:e?.threads}),createRelayer:(t,n)=>new ce({chain:t,worker:n,...e})}}function he(){return{type:`cleartext`,createRelayer:e=>{if(!e.executorAddress)throw new t.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new a.t(e)}}}function ge(t){return e.t(t.signer,t.provider,t)}var _e=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,s.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}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,s.getAddress)(e)}:${(0,s.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))}},ve=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 v(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 ye(e){i.N(e,`Stored credentials`),i.P(e.publicKey,`credentials.publicKey`),i.O(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)i.A(typeof t==`string`&&(0,s.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);i.N(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),i.P(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),i.P(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),i.A(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),i.A(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function be(e){ye(e);let t=e;i.A(typeof t.delegatorAddress==`string`&&(0,s.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),i.A(typeof t.delegateAddress==`string`&&(0,s.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),i.A(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),i.A(typeof t.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,s.getAddress)(e))),r=new Set(e.map(e=>(0,s.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,s.getAddress)(e)))].toSorted()}async function k(...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 xe=class{#e;constructor(e){this.#e=e}#t(e){i.N(e,`Session entry`),i.P(e.signature,`session.signature`),i.A(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),i.A(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}},A=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 xe(e.sessionStorage),this.crypto=new ve,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:e,contracts:r,createKey:a,createFn:o}){this.emit({type:n.r.CredentialsLoading,contractAddresses:r});try{let t=await this.storage.get(e);if(t){this.assertEncrypted(t);let i=await this.sessionSignatures.get(e);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(e),this.emit({type:n.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(t,i.signature);if(D(a,r))return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:e,credentials:a,requiredContracts:r});this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}if(T(t)){if(E(t.contractAddresses,r)){let i=await this.signForContracts(t,t.contractAddresses);await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(t,i);return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(t,t.contractAddresses),a=await this.decryptCredentials(t,i);return this.#a({key:e,credentials:a,requiredContracts:r})}this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof t.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:n.r.CredentialsCorrupted,error:i.L(r)}),await this.#s(e)}return(!this.#t||this.#n!==a)&&(this.#n=a,this.#t=o().then(e=>(this.emit({type:n.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,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:n.r.CredentialsRevoked,...t?{contractAddresses:t}:{}})}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:e,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:n.r.CredentialsCreating,contractAddresses:r});try{let t=await i();return await this.persistCredentials(e,t),await this.sessionSignatures.set({key:e,signature:t.signature,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsCreated,contractAddresses:r}),t}catch(e){if(e instanceof t.r)throw e;return n.P(e,a)}}async#a({key:e,credentials:t,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}let i=this.#o({key:e,credentials:t,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:t,requiredContracts:r}){let i=O([...t.contractAddresses,...r]),a=await this.signForContracts(t,i),o={...t,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}};function Se(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 j=class t extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return k((0,s.getAddress)(e),t)}constructor(t){super(t),this.#e=t.relayer,Se(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&t.sessionStorage instanceof e.i&&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 revokeFor(e){await this.revokeSession(await t.computeStoreKey(e.address,e.chainId))}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){ye(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 e=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,s.getAddress)(e)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await t.computeStoreKey(e,n);return this.#n=r,this.#t=i,i}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return k((0,s.getAddress)(e),(0,s.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,s.getAddress)(e),r=O(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,s.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,s.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,s.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,s.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){be(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(),i=`${(0,s.getAddress)(n)}:${(0,s.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}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 N(e){return(0,s.keccak256)((0,s.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,s.getAddress)(v(e.slice(-40)))}function Ce(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,s.getAddress)(v(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function we(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return v(L(e,t))}function Te(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function V(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function H(e){return e.topics[0]===P.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}:null}function U(e){return e.topics[0]===P.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:null}function Ee(e){let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function De(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Oe(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ce(e.topics[1]),txId:Ce(e.topics[2]),to:F(e.topics[3]),returnVal:we(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ke(e){return Te(e)??V(e)??H(e)??De(e)??U(e)??Oe(e)}function Ae(e){let t=[];for(let n of e){let e=ke(n);e&&t.push(e)}return t}function je(e){for(let t of e){let e=H(t);if(e)return e}return null}function Me(e){for(let t of e){let e=V(t);if(e)return e}return null}const Ne=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,P.UnwrappedStarted],W={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Pe(e){return G(e)??K(e)}function Fe(e){let t=[];for(let n of e){let e=Pe(n);e&&t.push(e)}return t}function Ie(e){for(let t of e){let e=G(t);if(e)return e}return null}function Le(e){for(let t of e){let e=K(t);if(e)return e}return null}const Re=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var ze=class e extends n.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,s.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(i.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,a,o){await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:u,onTransferSubmitted:d}=o??{},f=(0,s.getAddress)(e);c||await this.#i(a);let p,m,h=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:p,inputProof:m}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-h}),q(()=>u?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-h}),e instanceof t.r?e:new r.n(`Failed to encrypt transfer amount`,{cause:e})}if(p.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.b(this.address,f,p[0],m));return this.emit({type:n.r.TransferSubmitted,txHash:e}),q(()=>d?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transfer`,error:i.L(e)}),e instanceof t.r?e:new l(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,a,o,c){await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let u=(0,s.getAddress)(e),d=(0,s.getAddress)(a),f,p,m=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:u}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-m}),q(()=>c?.onEncryptComplete?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-m}),e instanceof t.r?e:new r.n(`Failed to encrypt transferFrom amount`,{cause:e})}if(f.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.x(this.address,u,d,f[0],p));return this.emit({type:n.r.TransferFromSubmitted,txHash:e}),q(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transferFrom`,error:i.L(e)}),e instanceof t.r?e:new l(`TransferFrom transaction failed`,{cause:e})}}async approve(e,r){await this.sdk.requireChainAlignment(`approve`);let a=(0,s.getAddress)(e);try{let e=await this.sdk.signer.writeContract(i.w(this.address,a,r));return this.emit({type:n.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approve`,error:i.L(e)}),e instanceof t.r?e:new c(`Operator approval failed`,{cause:e})}}async isApproved(e,t){return this.sdk.provider.readContract(i.S(this.address,(0,s.getAddress)(t),(0,s.getAddress)(e)))}async shield(e,r){await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await this.sdk.signer.getAddress();o=await this.sdk.provider.readContract(n.d(a,e))}catch(e){throw e instanceof t.r?e:new m(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:i.L(e)})}if(o<e)throw new f(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${a})`,{requested:e,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(e,c===`max`,r);try{let t=r?.to?(0,s.getAddress)(r.to):await this.sdk.signer.getAddress(),a=await this.sdk.signer.writeContract(i._(this.wrapper,t,e));return this.emit({type:n.r.ShieldSubmitted,txHash:a}),q(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`shield`,error:i.L(e)}),e instanceof t.r?e:new l(`Shield transaction failed`,{cause:e})}}async unwrap(e){await this.sdk.requireChainAlignment(`unwrap`);let a=await this.sdk.signer.getAddress(),o,s,c=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:o,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:a}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-c})}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-c}),e instanceof t.r?e:new r.n(`Failed to encrypt unshield amount`,{cause:e})}if(o.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.E(this.address,a,a,o[0],s));return this.emit({type:n.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){await this.sdk.requireChainAlignment(`unwrapAll`);let e=await this.sdk.signer.getAddress(),a=await this.readConfidentialBalanceOf(e);if(n._(a))throw new r.t(`Cannot unshield: balance is zero`);try{let t=await this.sdk.signer.writeContract(i.D(this.address,e,e,a));return this.emit({type:n.r.UnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield-all transaction failed`,{cause:e})}}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 q(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return q(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){await this.sdk.requireChainAlignment(`finalizeUnwrap`);let r=await this.sdk.publicDecrypt([e]),a=r.clearValues[e];i.k(a,`finalizeUnwrap: clearValue`);try{let t=await this.sdk.signer.writeContract(i.m(this.wrapper,e,a,r.decryptionProof));return this.emit({type:n.r.FinalizeUnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`finalizeUnwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){await this.sdk.requireChainAlignment(`approveUnderlying`);let r=await this.#n(),a=e??2n**256n-1n;try{let e=this.sdk.signer;if(a>0n){let t=await e.getAddress();await this.sdk.provider.readContract(n.l(r,t,this.wrapper))>0n&&await e.writeContract(n.u(r,this.wrapper,0n))}let t=await e.writeContract(n.u(r,this.wrapper,a));return this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approveUnderlying`,error:i.L(e)}),e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:r}){if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new n.C(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(e),o=this.sdk.signer,c=await o.getAddress();if(a===(0,s.getAddress)(c))throw new n.O(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new n.S(`Delegate address cannot be the same as the contract address (${this.address}).`);let u=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):n.i,f;try{f=await this.getDelegationExpiry({delegatorAddress:c,delegateAddress:a})}catch{f=-1n}if(f===d)throw new n.T(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await o.writeContract(n.a(u,a,this.address,d));return this.emit({type:n.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`delegateDecryption`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){await this.sdk.requireChainAlignment(`revokeDelegation`);let r=(0,s.getAddress)(e),a=this.sdk.signer,o=await a.getAddress(),c=await this.getAclAddress(),u;try{u=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:r})}catch{u=1n}if(u===0n)throw new n.E(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await a.writeContract(n.c(c,r,this.address));return this.emit({type:n.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`revokeDelegation`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,n,r){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await n(e[a]))}catch(n){n instanceof t.r?i.set(e[a].address,n):i.set(e[a].address,new l(r,{cause:n}))}return i}async#i(e){if(e===0n)return;let n;try{n=await this.balanceOf(await this.sdk.signer.getAddress())}catch(e){throw e instanceof t.r?e:new p(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new d(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}async#a(e,r,i){this.emit({type:n.r.UnshieldPhase1Submitted,txHash:e,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof t.r?e:new l(`Failed to get unshield receipt`,{cause:e})}let o=je(a.logs);if(!o)throw new l(`No UnwrapRequested event found in unshield receipt`);this.emit({type:n.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:n.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(e,r,i){let a=await this.#n(),o=this.sdk.signer,s=await o.getAddress(),l=await this.sdk.provider.readContract(n.l(a,s,this.wrapper));if(!(l>=e))try{if(l>0n){let e=await o.writeContract(n.u(a,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let t=r?2n**256n-1n:e,s=await o.writeContract(n.u(a,this.wrapper,t));this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(e){throw e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const J={[o.a.id]:o.a.registryAddress,[o.o.id]:o.o.registryAddress,[o.i.id]:o.i.registryAddress},Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},J,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 e=await this.provider.getChainId(),n=this.#e[e];if(!n)throw new t.t(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return(0,s.getAddress)(n)}async listPairs(e={}){let n=e.page??1,r=e.pageSize??100,a=e.metadata??!1;if(n<1)throw new t.t(`page must be >= 1, got ${n}`);if(r<1)throw new t.t(`pageSize must be >= 1, got ${r}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(i.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*r),u=l+BigInt(r)>BigInt(c)?BigInt(c):l+BigInt(r);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:r};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(i.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:r};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:r}}async#a(e){let[t,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(n.m(e.tokenAddress)),this.provider.readContract(n.h(e.tokenAddress)),this.provider.readContract(n.f(e.tokenAddress)),this.provider.readContract(n.p(e.tokenAddress)),this.provider.readContract(n.m(e.confidentialTokenAddress)),this.provider.readContract(n.h(e.confidentialTokenAddress)),this.provider.readContract(n.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ct:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.t(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{confidentialTokenAddress:c,isValid:o})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ut:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.n(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{tokenAddress:c,isValid:o})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(i.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(i.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(i.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.t(t,(0,s.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.n(t,(0,s.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.s(t,(0,s.getAddress)(e)))}};const Z=365*86400;async function Q(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var Be=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(t){this.relayer=t.relayer,this.provider=t.provider,this.signer=t.signer,this.storage=t.storage,this.sessionStorage=t.sessionStorage??new e.i,this.cache=new _e(t.storage),this.#t=t.onEvent??function(){};let n={};for(let e of t.chains??[])e.registryAddress&&(n[e.id]=e.registryAddress);Object.assign(n,t.registryAddresses),this.registry=new X({provider:this.provider,registryTTL:t.registryTTL,registryAddresses:n}),this.#e=t.registryTTL;let r={relayer:this.relayer,signer:t.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let e=t.keypairTTL??2592e3;if(e<=0||isNaN(e))throw Error(`keypairTTL must be a positive number (seconds)`);return e>Z?(console.warn(`[zama-sdk] keypairTTL (${e}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):e})(),sessionTTL:t.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new j(r),this.delegatedCredentials=new M(r),this.#r=this.signer.subscribe?.(e=>{this.#i(e)})}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let[t,n]=await Promise.all([this.signer.getChainId(),this.provider.getChainId()]);if(t!==n)throw new u({operation:e,signerChainId:t,providerChainId:n});return t}async#i(e){if(e.previous){let t=e.previous;await Q(`revoke previous identity`,()=>this.credentials.revokeFor(t)),await Q(`clear decrypt cache`,()=>this.cache.clearForRequester(t.address))}let t=e.next?.chainId;t!==void 0&&await Q(`switch relayer chain`,()=>{this.relayer.switchChain(t)});for(let t of this.#n)await Q(`identity listener`,()=>t(e))}createReadonlyToken(e){return new n.t(this,e)}createToken(e,t){return new ze(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({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let t=e.map(e=>({handle:e.handle,contractAddress:(0,s.getAddress)(e.contractAddress)})),r={},a=[];for(let e of t)n._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),c=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?c.push(e):r[e.handle]=t}if(c.length===0)return r;let l=await this.credentials.allow(...new Set(t.map(e=>e.contractAddress))),u=new Map;for(let e of c){let t=u.get(e.contractAddress);t?t.push(e.handle):u.set(e.contractAddress,[e.handle])}let d=Date.now(),f=c.map(e=>e.handle);try{this.emitEvent({type:n.r.DecryptStart,handles:f}),await n.n([...u.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:l.contractAddresses,privateKey:l.privateKey,publicKey:l.publicKey,signature:l.signature,signerAddress:o,startTimestamp:l.startTimestamp,durationDays:l.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 f){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:n.r.DecryptEnd,durationMs:Date.now()-d,handles:f,result:e}),r}catch(e){throw this.emitEvent({type:n.r.DecryptError,error:i.L(e),durationMs:Date.now()-d,handles:f}),n.v(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 n.v(e,`Public decryption failed`)}}async revokeSession(){let e=await this.signer.getAddress(),t=await this.signer.getChainId();try{await this.credentials.revokeFor({address:e,chainId:t})}finally{await this.cache.clearForRequester(e)}}dispose(){this.#r?.(),this.#r=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}function Ve(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function He(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ue(e,t){return(await We(e,t))?.unwrapTxHash??null}async function We(e,t){return Ve(await e.get($(t)))}async function Ge(e,t){await e.delete($(t))}var Ke=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 qe=new Ke;exports.ACL_TOPICS=Re,exports.AclPausedError=n.y,exports.AclTopics=W,exports.ApprovalFailedError=c,exports.BalanceCheckUnavailableError=p,exports.ChainMismatchError=u,exports.ChromeSessionStorage=Ke,exports.ConfigurationError=t.t,exports.CredentialsManager=j,exports.DecryptCache=_e,exports.DecryptionFailedError=r.t,exports.DefaultRegistryAddresses=J,exports.DelegatedCredentialsManager=M,exports.DelegationContractIsSelfError=n.b,exports.DelegationCooldownError=n.x,exports.DelegationDelegateEqualsContractError=n.S,exports.DelegationExpirationTooSoonError=n.C,exports.DelegationExpiredError=n.w,exports.DelegationExpiryUnchangedError=n.T,exports.DelegationNotFoundError=n.E,exports.DelegationNotPropagatedError=n.D,exports.DelegationSelfNotAllowedError=n.O,exports.ERC20ReadFailedError=m,exports.ERC7984_INTERFACE_ID=i.c,exports.ERC7984_WRAPPER_INTERFACE_ID=i.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=i.u,exports.EncryptionFailedError=r.n,exports.IndexedDBStorage=e.o,exports.InsufficientConfidentialBalanceError=d,exports.InsufficientERC20BalanceError=f,exports.InvalidKeypairError=n.k,exports.KeypairExpiredError=n.A,exports.MemoryStorage=e.i,exports.NoCiphertextError=n.j,exports.ReadonlyToken=n.t,exports.RelayerRequestFailedError=t.n,exports.RelayerWeb=ce,exports.SigningFailedError=n.M,exports.SigningRejectedError=n.N,exports.TOKEN_TOPICS=Ne,exports.Token=ze,exports.Topics=P,exports.TransactionRevertedError=l,exports.WrappersRegistry=X,exports.ZERO_HANDLE=n.g,exports.ZamaError=t.r,exports.ZamaErrorCode=t.i,exports.ZamaSDK=Be,exports.ZamaSDKEvents=n.r,exports.allowanceContract=n.l,exports.anvil=o.t,exports.approveContract=n.u,exports.balanceOfContract=n.d,exports.buildZamaConfig=e.t,exports.chains=o.n,exports.chromeSessionStorage=qe,exports.clearPendingUnshield=Ge,exports.cleartext=he,exports.confidentialBalanceOfContract=i.v,exports.confidentialTotalSupplyContract=i.y,exports.confidentialTransferContract=i.b,exports.confidentialTransferFromContract=i.x,exports.createConfig=ge,exports.decimalsContract=n.f,exports.decodeAclEvent=Pe,exports.decodeAclEvents=Fe,exports.decodeConfidentialTransfer=Te,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=ke,exports.decodeOnChainEvents=Ae,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=U,exports.decodeUnwrapRequested=H,exports.decodeUnwrappedFinalized=Ee,exports.decodeUnwrappedStarted=Oe,exports.decodeWrapped=V,exports.delegateForUserDecryptionContract=n.a,exports.finalizeUnwrapContract=i.m,exports.findDelegatedForUserDecryption=Ie,exports.findRevokedDelegationForUserDecryption=Le,exports.findUnwrapRequested=je,exports.findWrapped=Me,exports.getConfidentialTokenAddressContract=i.t,exports.getDelegationExpiryContract=n.o,exports.getTokenAddressContract=i.n,exports.getTokenPairContract=i.r,exports.getTokenPairsContract=i.i,exports.getTokenPairsLengthContract=i.a,exports.getTokenPairsSliceContract=i.o,exports.hardhat=o.r,exports.hoodi=o.i,exports.indexedDBStorage=e.s,exports.inferredTotalSupplyContract=i.h,exports.isConfidentialTokenContract=i.d,exports.isConfidentialTokenValidContract=i.s,exports.isConfidentialWrapperContract=i.f,exports.isHandleDelegatedContract=n.s,exports.isOperatorContract=i.S,exports.isZeroHandle=n._,exports.loadPendingUnshield=Ue,exports.loadPendingUnshieldRequest=We,exports.mainnet=o.a,exports.matchAclRevert=_,exports.matchZamaError=t.a,exports.memoryStorage=e.a,exports.nameContract=n.m,exports.rateContract=i.C,exports.resolveChainRelayers=e.n,exports.resolveStorage=e.r,exports.revokeDelegationContract=n.c,exports.savePendingUnshield=He,exports.sepolia=o.o,exports.setOperatorContract=i.w,exports.supportsInterfaceContract=i.p,exports.symbolContract=n.h,exports.totalSupplyContract=i.T,exports.underlyingContract=i.g,exports.unwrapContract=i.E,exports.unwrapFromBalanceContract=i.D,exports.web=me,exports.wrapContract=i._;
515
515
  //# sourceMappingURL=index.cjs.map