@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
package/dist/esm/index.js CHANGED
@@ -1,8 +1,5 @@
1
- import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o,D as s,E as c,M as l,N as u,O as d,P as ee,S as f,T as te,_ as ne,a as re,b as ie,c as ae,d as oe,f as p,g as se,h as m,i as ce,j as le,k as ue,l as h,m as de,n as fe,o as pe,p as me,r as g,s as he,t as ge,u as _,v as _e,w as ve,x as ye,y as be}from"./readonly-token-D4GjTj0q.js";import{n as v,t as xe}from"./encryption-CmIPBcfP.js";import{i as Se,n as Ce,r as we,t as y}from"./memory-storage-F8xjMzVy.js";import{c as Te,i as Ee,n as De,o as b,r as x,s as S,t as Oe}from"./assertions-BARApuMj.js";import{n as C}from"./error-B6H-mBAh.js";import{t as w}from"./hex-D_B-zoId.js";import{a as ke,i as T,n as Ae,o as E,r as D,t as O}from"./relayer-utils-BeoTNDM4.js";import{C as je,E as Me,S as Ne,T as Pe,_ as Fe,a as k,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,l as Ue,m as We,n as A,o as j,p as Ge,r as Ke,s as qe,t as M,u as Je,v as Ye,w as Xe,x as Ze,y as Qe}from"./wrappers-registry-ydyySM9g.js";import{n as $e}from"./cleartext-Cs28cTsa.js";import{getAddress as N,isAddress as P,keccak256 as et,toBytes as tt,zeroAddress as nt}from"viem";var F=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},I=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},rt=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},it=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},at=class extends r{constructor(e,n){super(t.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},ot=class extends r{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function st(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 L={AlreadyDelegatedOrRevokedInSameBlock:e=>new ye(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new ie(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new be(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new f(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new o(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new te(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new c(`Cannot revoke: no active delegation exists.`,{cause:e})};function R(e){let t=e instanceof Error?e:void 0,n=st(e);if(n&&n in L)return L[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(L))if(r.includes(e))return n(t);return null}var z=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 ct=new z;function lt(e){try{return b(e,`runtime`),Te(e,`id`,`runtime.id`),Ee(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function ut(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(b(t,`ns`),lt(t.runtime))return t.runtime}catch{continue}}var dt=class extends Se{constructor(e){super(e,e.logger)}createWorker(){let e=ut();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
1
+ import{a as e,i as t,n,r,t as i}from"./build-CvenCk6R.js";import{a,i as o,n as s,r as c,t as l}from"./relayer-7Hd00A6X.js";import{A as u,C as d,D as ee,E as f,M as te,N as ne,O as re,P as ie,S as p,T as m,_ as h,a as ae,b as oe,c as se,d as ce,f as le,g as ue,h as de,i as fe,j as pe,k as me,l as he,m as ge,n as _e,o as ve,p as ye,r as g,s as be,t as _,u as v,v as xe,w as Se,x as Ce,y as we}from"./readonly-token-DCLOYhws.js";import{n as y,t as Te}from"./encryption-YS-Kb7qm.js";import{a as Ee,i as De,n as Oe,r as b,t as ke}from"./cleartext-I-etE_7S.js";import{n as x}from"./error-B6H-mBAh.js";import{c as Ae,i as je,n as Me,o as S,r as C,s as w,t as Ne}from"./assertions-CfqI3AJv.js";import{t as T}from"./hex-BZVTzEK6.js";import{n as Pe,t as E}from"./memory-storage-CFXqXUcm.js";import{a as D,i as O,n as Fe,o as k,r as Ie,t as Le}from"./chains-aHmrozPh.js";import{C as Re,D as ze,E as Be,S as Ve,T as He,_ as Ue,a as A,b as We,c as Ge,d as Ke,f as qe,g as Je,h as Ye,i as Xe,l as Ze,m as Qe,n as j,o as M,p as $e,r as et,s as tt,t as N,u as nt,v as rt,w as it,x as at,y as ot}from"./wrappers-registry-CXNs4eR0.js";import{getAddress as P,isAddress as F,keccak256 as st,toBytes as ct,zeroAddress as lt}from"viem";var I=class extends c{constructor(e,t){super(o.ApprovalFailed,e,t),this.name=`ApprovalFailedError`}},L=class extends c{constructor(e,t){super(o.TransactionReverted,e,t),this.name=`TransactionRevertedError`}},ut=class extends c{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:t,providerChainId:n},r){super(o.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${t} and provider is on chain ${n}.`,r),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=t,this.providerChainId=n}},dt=class extends c{requested;available;token;constructor(e,t,n){super(o.InsufficientConfidentialBalance,e,n),this.name=`InsufficientConfidentialBalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},ft=class extends c{requested;available;token;constructor(e,t,n){super(o.InsufficientERC20Balance,e,n),this.name=`InsufficientERC20BalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},pt=class extends c{constructor(e,t){super(o.BalanceCheckUnavailable,e,t),this.name=`BalanceCheckUnavailableError`}},mt=class extends c{constructor(e,t){super(o.ERC20ReadFailed,e,t),this.name=`ERC20ReadFailedError`}};function ht(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 R={AlreadyDelegatedOrRevokedInSameBlock:e=>new Ce(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new oe(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new we(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new re(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new p(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new d(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new m(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new f(`Cannot revoke: no active delegation exists.`,{cause:e})};function gt(e){let t=e instanceof Error?e:void 0,n=ht(e);if(n&&n in R)return R[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(R))if(r.includes(e))return n(t);return null}var _t=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 t(`FheArtifactCache`,1,`artifacts`),new De({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 b(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 b(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return b(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 b(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return b(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)}};function vt(e){try{return S(e,`runtime`),Ae(e,`id`,`runtime.id`),je(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function yt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(S(t,`ns`),vt(t.runtime))return t.runtime}catch{continue}}var bt=class extends Oe{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=yt();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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{A as a,C as o
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})}},ft=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:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==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({},O[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}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 e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new z(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},O[e],this.#l.transports[e]);this.#a=new we({storage:this.#o,chainId:e,relayerUrl:t.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(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new dt(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:ke(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return E(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return E(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return E(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 E(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return E(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 e=await this.#l.getChainId(),t=Object.assign({},O[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},pt=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=N(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}:${N(e)}:${N(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))}},mt=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 w(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 ht(e){b(e,`Stored credentials`),S(e.publicKey,`credentials.publicKey`),Oe(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)x(typeof t==`string`&&P(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);b(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),S(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),S(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),x(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),x(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function gt(e){ht(e);let t=e;x(typeof t.delegatorAddress==`string`&&P(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),x(typeof t.delegateAddress==`string`&&P(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),x(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),x(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function B(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function V(e,t){let n=new Set(t.map(e=>N(e))),r=new Set(e.map(e=>N(e)));return n.isSubsetOf(r)}function _t(e,t){return B(e)?V(e.contractAddresses,t):!1}function H(e){return[...new Set(e.map(e=>N(e)))].toSorted()}async function vt(...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 yt=class{#e;constructor(e){this.#e=e}#t(e){b(e,`Session entry`),S(e.signature,`session.signature`),x(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),x(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}},bt=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 yt(e.sessionStorage),this.crypto=new mt,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:t,createKey:n,createFn:i}){this.emit({type:g.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:g.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(_t(i,t))return this.emit({type:g.CredentialsCached,contractAddresses:t}),this.emit({type:g.CredentialsAllowed,contractAddresses:t}),i;if(B(i))return this.#a({key:e,credentials:i,requiredContracts:t});this.emit({type:g.CredentialsExpired,contractAddresses:t})}if(B(n)){if(V(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:g.CredentialsCached,contractAddresses:t}),this.emit({type:g.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#a({key:e,credentials:i,requiredContracts:t})}this.emit({type:g.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof r)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),this.emit({type:g.CredentialsCorrupted,error:C(t)}),await this.#s(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=i().then(e=>(this.emit({type:g.CredentialsAllowed,contractAddresses:t}),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),!_t(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:g.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),_t(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:t,createFn:n,errorContext:i}){this.emit({type:g.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:g.CredentialsCreated,contractAddresses:t}),r}catch(e){if(e instanceof r)throw e;return ee(e,i)}}async#a({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(V(e.contractAddresses,n))return this.emit({type:g.CredentialsAllowed,contractAddresses:n}),e;t=e}else if(this.#i){let e=this.#i;if(V(e.contractAddresses,n))return this.emit({type:g.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#o({key:e,credentials:t,requiredContracts:n});this.#r=r;try{let e=await r;return this.#i=e,e}finally{this.#r===r&&(this.#r=null)}}async#o({key:e,credentials:t,requiredContracts:n}){let r=H([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:g.CredentialsAllowed,contractAddresses:n}),a}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:g.CredentialsPersistFailed,error:C(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:g.CredentialsPersistFailed,error:C(e)})}}};function xt(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 U=class e extends bt{#e;#t=null;#n=null;static async computeStoreKey(e,t){return vt(N(e),t)}constructor(e){super(e),this.#e=e.relayer,xt(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof y&&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=H(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=H(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){ht(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=`${N(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},St=class e extends bt{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return vt(N(e),N(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=N(e),r=H(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(N(e)),t)}async revoke(e){await this.revokeSession(await this.#i(N(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i(N(e)),t)}async clear(e){await this.clearAll(await this.#i(N(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){gt(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=`${N(n)}:${N(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({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 W(e){return et(tt(e))}const G={ConfidentialTransfer:W(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:W(`Wrapped(address,uint256)`),UnwrapRequested:W(`UnwrapRequested(address,bytes32,bytes32)`),UnwrappedFinalized:W(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:W(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function K(e){return N(w(e.slice(-40)))}function Ct(e){return BigInt(e)}function wt(e){return e}function q(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Tt(e,t){return N(w(q(e,t).slice(-40)))}function J(e,t){return BigInt(`0x`+q(e,t))}function Et(e,t){return BigInt(`0x`+q(e,t))!==0n}function Y(e,t){return w(q(e,t))}function Dt(e){return e.topics[0]!==G.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:K(e.topics[1]),to:K(e.topics[2]),encryptedAmountHandle:wt(e.topics[3])}}function Ot(e){return e.topics[0]!==G.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:K(e.topics[1]),amountIn:J(e.data,0)}}function kt(e){return e.topics[0]!==G.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:K(e.topics[1]),unwrapRequestId:wt(e.topics[2]),encryptedAmount:Y(e.data,0)}}function At(e){return e.topics[0]!==G.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,receiver:K(e.topics[1]),unwrapRequestId:wt(e.topics[2]),encryptedAmount:Y(e.data,0),cleartextAmount:J(e.data,1)}}function jt(e){return e.topics[0]!==G.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ct(e.topics[1]),txId:Ct(e.topics[2]),to:K(e.topics[3]),returnVal:Et(e.data,0),refund:Tt(e.data,1),requestedAmount:Y(e.data,2),burnAmount:Y(e.data,3)}}function Mt(e){return Dt(e)??Ot(e)??kt(e)??At(e)??jt(e)}function Nt(e){let t=[];for(let n of e){let e=Mt(n);e&&t.push(e)}return t}function Pt(e){for(let t of e){let e=kt(t);if(e)return e}return null}function Ft(e){for(let t of e){let e=Ot(t);if(e)return e}return null}const It=[G.ConfidentialTransfer,G.Wrapped,G.UnwrapRequested,G.UnwrappedFinalized,G.UnwrappedStarted],X={DelegatedForUserDecryption:W(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:W(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Lt(e){return e.topics[0]!==X.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:Tt(e.data,0),delegationCounter:J(e.data,1),oldExpirationDate:J(e.data,2),newExpirationDate:J(e.data,3)}}function Rt(e){return e.topics[0]!==X.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:Tt(e.data,0),delegationCounter:J(e.data,1),oldExpirationDate:J(e.data,2)}}function zt(e){return Lt(e)??Rt(e)}function Bt(e){let t=[];for(let n of e){let e=zt(n);e&&t.push(e)}return t}function Vt(e){for(let t of e){let e=Lt(t);if(e)return e}return null}function Ht(e){for(let t of e){let e=Rt(t);if(e)return e}return null}const Ut=[X.DelegatedForUserDecryption,X.RevokedDelegationForUserDecryption];var Wt=class e extends ge{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?N(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(Pe(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,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=N(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:g.EncryptStart}),{handles:c,inputProof:l}=await this.sdk.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-u}),Z(()=>a?.())}catch(e){throw this.emit({type:g.EncryptError,error:C(e),durationMs:Date.now()-u}),e instanceof r?e:new v(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new v(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(Ve(this.address,s,c[0],l));return this.emit({type:g.TransferSubmitted,txHash:e}),Z(()=>o?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:C(e)}),e instanceof r?e:new I(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=N(e),o=N(t),s,c,l=Date.now();try{this.emit({type:g.EncryptStart}),{handles:s,inputProof:c}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-l}),Z(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:C(e),durationMs:Date.now()-l}),e instanceof r?e:new v(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new v(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(Be(this.address,a,o,s[0],c));return this.emit({type:g.TransferFromSubmitted,txHash:e}),Z(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:C(e)}),e instanceof r?e:new I(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=N(e);try{let e=await this.sdk.signer.writeContract(Qe(this.address,n,t));return this.emit({type:g.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approve`,error:C(e)}),e instanceof r?e:new F(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=N(e),r=t?N(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(Fe(this.address,r,n))}async shield(e,t){let n=await this.#n(),i;try{let e=await this.sdk.signer.getAddress();i=await this.sdk.signer.readContract(oe(n,e))}catch(e){throw e instanceof r?e:new ot(`Could not read ERC-20 balance for shield validation (token: ${n})`,{cause:C(e)})}if(i<e)throw new it(`Insufficient ERC-20 balance: requested ${e}, available ${i} (token: ${n})`,{requested:e,available:i,token:n});let a=t?.approvalStrategy??`exact`;a!==`skip`&&await this.#o(e,a===`max`,t);try{let n=t?.to?N(t.to):await this.sdk.signer.getAddress(),r=await this.sdk.signer.writeContract(Me(this.wrapper,n,e));return this.emit({type:g.ShieldSubmitted,txHash:r}),Z(()=>t?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.sdk.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:C(e)}),e instanceof r?e:new I(`Shield transaction failed`,{cause:e})}}async unwrap(e){let t=await this.sdk.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:g.EncryptStart}),{handles:n,inputProof:i}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:g.EncryptError,error:C(e),durationMs:Date.now()-a}),e instanceof r?e:new v(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new v(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(Ze(this.address,t,t,n[0],i));return this.emit({type:g.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:C(e)}),e instanceof r?e:new I(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.sdk.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(ne(t))throw new xe(`Cannot unshield: balance is zero`);try{let n=await this.sdk.signer.writeContract(Ne(this.address,e,e,t));return this.emit({type:g.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.sdk.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:C(e)}),e instanceof r?e:new I(`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 Z(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Z(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t=await this.sdk.publicDecrypt([e]),n=t.clearValues[e];De(n,`finalizeUnwrap: clearValue`);try{let r=await this.sdk.signer.writeContract(je(this.wrapper,e,n,t.decryptionProof));return this.emit({type:g.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.sdk.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`finalizeUnwrap`,error:C(e)}),e instanceof r?e:new I(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(h(t,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(_(t,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(_(t,this.wrapper,n));return this.emit({type:g.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approveUnderlying`,error:C(e)}),e instanceof r?e:new F(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new o(`Expiration date must be at least 1 hour in the future`);let n=N(e),i=await this.sdk.signer.getAddress();if(n===N(i))throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new f(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):ce,c;try{c=await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})}catch{c=-1n}if(c===s)throw new te(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(re(a,n,this.address,s));return this.emit({type:g.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`delegateDecryption`,error:C(e)}),e instanceof r?e:R(e)||new I(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=N(e),n=await this.sdk.signer.getAddress(),i=await this.getAclAddress(),a;try{a=await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})}catch{a=1n}if(a===0n)throw new c(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(ae(i,t,this.address));return this.emit({type:g.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`revokeDelegation`,error:C(e)}),e instanceof r?e:R(e)||new I(`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,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new I(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t;try{t=await this.balanceOf()}catch(e){throw e instanceof r?e:new at(`Balance validation failed (token: ${this.address})`,{cause:e})}if(t<e)throw new rt(`Insufficient confidential balance: requested ${e}, available ${t} (token: ${this.address})`,{requested:e,available:t,token:this.address})}async#a(e,t,n){this.emit({type:g.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.sdk.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new I(`Failed to get unshield receipt`,{cause:e})}let a=Pt(i.logs);if(!a)throw new I(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:t}),Z(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.unwrapRequestId);return this.emit({type:g.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),Z(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.sdk.signer.getAddress(),o=await this.sdk.signer.readContract(h(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.sdk.signer.writeContract(_(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.sdk.signer.writeContract(_(i,this.wrapper,r));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:a}),Z(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new F(`ERC-20 approval failed`,{cause:e})}}};function Z(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Gt={[D.chainId]:D.registryAddress,[T.chainId]:T.registryAddress,[$e.chainId]:$e.registryAddress},Kt=300*1e3;var qt=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Gt,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.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return N(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(k(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(j(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let ee=`metadata:${a}:${c}:${l}`,f=this.#r(ee);if(f===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));f=this.#i(ee,n,t?Kt:void 0)}return{items:f,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(de(e.tokenAddress)),this.signer.readContract(m(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(me(e.tokenAddress)),this.signer.readContract(de(e.confidentialTokenAddress)),this.signer.readContract(m(e.confidentialTokenAddress)),this.signer.readContract(p(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=N(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(M(t,n));return o===nt?this.#i(r,null,Kt):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=N(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(A(t,n));return o===nt?this.#i(r,null,Kt):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(He(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(k(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(j(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(Ke(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(M(t,N(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(A(t,N(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(qe(t,N(e)))}};const Q=365*86400;var Jt=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 y,this.cache=new pt(e.storage),this.#t=e.onEvent??function(){},this.registry=new qt({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={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>Q?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Q}s); capping to ${Q}s.`),Q):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new U(t),this.delegatedCredentials=new St(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.emitEvent({type:g.TransactionError,operation:e,error:C(t)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=N(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.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 U.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new ge(this,e)}createToken(e,t){return new Wt(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 qt({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 t=e.map(e=>({handle:e.handle,contractAddress:N(e.contractAddress)})),n={},r=[];for(let e of t)ne(e.handle)?n[e.handle]=0n:r.push(e);if(r.length===0)return n;let i=await this.signer.getAddress(),a=[];for(let e of r){let t=await this.cache.get(i,e.contractAddress,e.handle);t===null?a.push(e):n[e.handle]=t}if(a.length===0)return n;let o=await this.credentials.allow(...new Set(t.map(e=>e.contractAddress))),s=new Map;for(let e of a){let t=s.get(e.contractAddress);t?t.push(e.handle):s.set(e.contractAddress,[e.handle])}let c=Date.now(),l=a.map(e=>e.handle);try{this.emitEvent({type:g.DecryptStart,handles:l}),await fe([...s.entries()].map(([e,t])=>async()=>{let r=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:i,startTimestamp:o.startTimestamp,durationDays:o.durationDays});for(let[t,a]of Object.entries(r))n[t]=a,await this.cache.set(i,e,t,a)}),5);let e={};for(let t of l){let r=n[t];r!==void 0&&(e[t]=r)}return this.emitEvent({type:g.DecryptEnd,durationMs:Date.now()-c,handles:l,result:e}),n}catch(e){throw this.emitEvent({type:g.DecryptError,error:C(e),durationMs:Date.now()-c,handles:l}),_e(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 _e(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 U.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 $(e){return`zama:pending-unshield:${e}`}async function Yt(e,t,n){await e.set($(t),n)}async function Xt(e,t){return e.get($(t))}async function Zt(e,t){await e.delete($(t))}var Qt=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 $t=new Qt;export{Ut as ACL_TOPICS,be as AclPausedError,X as AclTopics,F as ApprovalFailedError,at as BalanceCheckUnavailableError,Qt as ChromeSessionStorage,i as ConfigurationError,U as CredentialsManager,pt as DecryptCache,xe as DecryptionFailedError,Gt as DefaultRegistryAddresses,St as DelegatedCredentialsManager,ie as DelegationContractIsSelfError,ye as DelegationCooldownError,f as DelegationDelegateEqualsContractError,o as DelegationExpirationTooSoonError,ve as DelegationExpiredError,te as DelegationExpiryUnchangedError,c as DelegationNotFoundError,s as DelegationNotPropagatedError,d as DelegationSelfNotAllowedError,ot as ERC20ReadFailedError,Le as ERC7984_INTERFACE_ID,Ue as ERC7984_WRAPPER_INTERFACE_ID,v as EncryptionFailedError,Ae as HardhatConfig,z as IndexedDBStorage,rt as InsufficientConfidentialBalanceError,it as InsufficientERC20BalanceError,ue as InvalidKeypairError,a as KeypairExpiredError,D as MainnetConfig,y as MemoryStorage,le as NoCiphertextError,ge as ReadonlyToken,n as RelayerRequestFailedError,ft as RelayerWeb,T as SepoliaConfig,l as SigningFailedError,u as SigningRejectedError,It as TOKEN_TOPICS,Wt as Token,G as Topics,I as TransactionRevertedError,qt as WrappersRegistry,se as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,Jt as ZamaSDK,g as ZamaSDKEvents,h as allowanceContract,_ as approveContract,oe as balanceOfContract,$t as chromeSessionStorage,Zt as clearPendingUnshield,Ge as confidentialBalanceOfContract,We as confidentialTotalSupplyContract,Ve as confidentialTransferContract,Be as confidentialTransferFromContract,p as decimalsContract,zt as decodeAclEvent,Bt as decodeAclEvents,Dt as decodeConfidentialTransfer,Lt as decodeDelegatedForUserDecryption,Mt as decodeOnChainEvent,Nt as decodeOnChainEvents,Rt as decodeRevokedDelegationForUserDecryption,kt as decodeUnwrapRequested,At as decodeUnwrappedFinalized,jt as decodeUnwrappedStarted,Ot as decodeWrapped,re as delegateForUserDecryptionContract,je as finalizeUnwrapContract,Vt as findDelegatedForUserDecryption,Ht as findRevokedDelegationForUserDecryption,Pt as findUnwrapRequested,Ft as findWrapped,M as getConfidentialTokenAddressContract,pe as getDelegationExpiryContract,A as getTokenAddressContract,Ke as getTokenPairContract,He as getTokenPairsContract,k as getTokenPairsLengthContract,j as getTokenPairsSliceContract,ct as indexedDBStorage,Xe as inferredTotalSupplyContract,Je as isConfidentialTokenContract,qe as isConfidentialTokenValidContract,Re as isConfidentialWrapperContract,he as isHandleDelegatedContract,Fe as isOperatorContract,ne as isZeroHandle,Xt as loadPendingUnshield,R as matchAclRevert,e as matchZamaError,Ce as memoryStorage,de as nameContract,Ye as rateContract,ae as revokeDelegationContract,Yt as savePendingUnshield,Qe as setOperatorContract,ze as supportsInterfaceContract,m as symbolContract,Ie as totalSupplyContract,Pe as underlyingContract,Ze as unwrapContract,Ne as unwrapFromBalanceContract,Me as wrapContract};
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 xt(e){return{type:`web`,createWorker:t=>new bt({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 _t({chain:t,worker:n,...e})}}function St(e){return i(e.signer,e.provider,e)}var Ct=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=P(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}:${P(e)}:${P(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))}},wt=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 T(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 Tt(e){S(e,`Stored credentials`),w(e.publicKey,`credentials.publicKey`),Ne(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)C(typeof t==`string`&&F(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);S(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),w(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),w(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),C(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),C(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function Et(e){Tt(e);let t=e;C(typeof t.delegatorAddress==`string`&&F(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),C(typeof t.delegateAddress==`string`&&F(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),C(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),C(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function Dt(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function z(e,t){let n=new Set(t.map(e=>P(e))),r=new Set(e.map(e=>P(e)));return n.isSubsetOf(r)}function Ot(e,t){return Dt(e)?z(e.contractAddresses,t):!1}function B(e){return[...new Set(e.map(e=>P(e)))].toSorted()}async function kt(...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 At=class{#e;constructor(e){this.#e=e}#t(e){S(e,`Session entry`),w(e.signature,`session.signature`),C(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),C(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}},jt=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 At(e.sessionStorage),this.crypto=new wt,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:t,createKey:n,createFn:r}){this.emit({type:g.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:g.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(Ot(i,t))return this.emit({type:g.CredentialsCached,contractAddresses:t}),this.emit({type:g.CredentialsAllowed,contractAddresses:t}),i;if(Dt(i))return this.#a({key:e,credentials:i,requiredContracts:t});this.emit({type:g.CredentialsExpired,contractAddresses:t})}if(Dt(n)){if(z(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:g.CredentialsCached,contractAddresses:t}),this.emit({type:g.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#a({key:e,credentials:i,requiredContracts:t})}this.emit({type:g.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof c)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),this.emit({type:g.CredentialsCorrupted,error:x(t)}),await this.#s(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=r().then(e=>(this.emit({type:g.CredentialsAllowed,contractAddresses:t}),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),!Ot(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:g.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),Ot(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:t,createFn:n,errorContext:r}){this.emit({type:g.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:g.CredentialsCreated,contractAddresses:t}),r}catch(e){if(e instanceof c)throw e;return ie(e,r)}}async#a({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(z(e.contractAddresses,n))return this.emit({type:g.CredentialsAllowed,contractAddresses:n}),e;t=e}else if(this.#i){let e=this.#i;if(z(e.contractAddresses,n))return this.emit({type:g.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#o({key:e,credentials:t,requiredContracts:n});this.#r=r;try{let e=await r;return this.#i=e,e}finally{this.#r===r&&(this.#r=null)}}async#o({key:e,credentials:t,requiredContracts:n}){let r=B([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:g.CredentialsAllowed,contractAddresses:n}),a}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:g.CredentialsPersistFailed,error:x(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:g.CredentialsPersistFailed,error:x(e)})}}};function Mt(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 Nt=class e extends jt{#e;#t=null;#n=null;static async computeStoreKey(e,t){return kt(P(e),t)}constructor(e){super(e),this.#e=e.relayer,Mt(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof E&&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=B(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(t){await this.revokeSession(await e.computeStoreKey(t.address,t.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=B(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){Tt(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=`${P(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},Pt=class e extends jt{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return kt(P(e),P(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=P(e),r=B(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(P(e)),t)}async revoke(e){await this.revokeSession(await this.#i(P(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i(P(e)),t)}async clear(e){await this.clearAll(await this.#i(P(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){Et(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=`${P(n)}:${P(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 V(e){return st(ct(e))}const H={ConfidentialTransfer:V(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:V(`Wrapped(address,uint256)`),UnwrapRequested:V(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:V(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:V(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:V(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:V(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:V(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function U(e){return P(T(e.slice(-40)))}function Ft(e){return BigInt(e)}function It(e){return e}function W(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Lt(e,t){return P(T(W(e,t).slice(-40)))}function G(e,t){return BigInt(`0x`+W(e,t))}function Rt(e,t){return BigInt(`0x`+W(e,t))!==0n}function K(e,t){return T(W(e,t))}function zt(e){return e.topics[0]!==H.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:U(e.topics[1]),to:U(e.topics[2]),encryptedAmountHandle:It(e.topics[3])}}function Bt(e){return e.topics[0]!==H.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:U(e.topics[1]),amountIn:G(e.data,0)}}function Vt(e){return e.topics[0]===H.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:U(e.topics[1]),unwrapRequestId:It(e.topics[2]),encryptedAmount:K(e.data,0)}:e.topics[0]===H.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:U(e.topics[1]),encryptedAmount:K(e.data,0)}:null}function q(e){return e.topics[0]===H.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:U(e.topics[1]),unwrapRequestId:It(e.topics[2]),encryptedAmount:K(e.data,0),cleartextAmount:G(e.data,1)}:e.topics[0]===H.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:U(e.topics[1]),encryptedAmount:K(e.data,0),cleartextAmount:G(e.data,1)}:null}function Ht(e){let t=q(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Ut(e){if(e.topics[0]!==H.UnwrapFinalizedLegacy)return null;let t=q(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Wt(e){return e.topics[0]!==H.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ft(e.topics[1]),txId:Ft(e.topics[2]),to:U(e.topics[3]),returnVal:Rt(e.data,0),refund:Lt(e.data,1),requestedAmount:K(e.data,2),burnAmount:K(e.data,3)}}function Gt(e){return zt(e)??Bt(e)??Vt(e)??Ut(e)??q(e)??Wt(e)}function Kt(e){let t=[];for(let n of e){let e=Gt(n);e&&t.push(e)}return t}function qt(e){for(let t of e){let e=Vt(t);if(e)return e}return null}function Jt(e){for(let t of e){let e=Bt(t);if(e)return e}return null}const Yt=[H.ConfidentialTransfer,H.Wrapped,H.UnwrapRequested,H.UnwrapRequestedLegacy,H.UnwrapFinalized,H.UnwrapFinalizedLegacy,H.UnwrappedStarted],J={DelegatedForUserDecryption:V(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:V(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Xt(e){return e.topics[0]!==J.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:Lt(e.data,0),delegationCounter:G(e.data,1),oldExpirationDate:G(e.data,2),newExpirationDate:G(e.data,3)}}function Y(e){return e.topics[0]!==J.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:Lt(e.data,0),delegationCounter:G(e.data,1),oldExpirationDate:G(e.data,2)}}function Zt(e){return Xt(e)??Y(e)}function Qt(e){let t=[];for(let n of e){let e=Zt(n);e&&t.push(e)}return t}function $t(e){for(let t of e){let e=Xt(t);if(e)return e}return null}function en(e){for(let t of e){let e=Y(t);if(e)return e}return null}const tn=[J.DelegatedForUserDecryption,J.RevokedDelegationForUserDecryption];var nn=class e extends _{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?P(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(Je(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,t,n){await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:r=!1,onEncryptComplete:i,onTransferSubmitted:a}=n??{},o=P(e);r||await this.#i(t);let s,l,u=Date.now();try{this.emit({type:g.EncryptStart}),{handles:s,inputProof:l}=await this.sdk.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-u}),X(()=>i?.())}catch(e){throw this.emit({type:g.EncryptError,error:x(e),durationMs:Date.now()-u}),e instanceof c?e:new y(`Failed to encrypt transfer amount`,{cause:e})}if(s.length===0)throw new y(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(We(this.address,o,s[0],l));return this.emit({type:g.TransferSubmitted,txHash:e}),X(()=>a?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:x(e)}),e instanceof c?e:new L(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,r){await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let i=P(e),a=P(t),o,s,l=Date.now();try{this.emit({type:g.EncryptStart}),{handles:o,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:i}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-l}),X(()=>r?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:x(e),durationMs:Date.now()-l}),e instanceof c?e:new y(`Failed to encrypt transferFrom amount`,{cause:e})}if(o.length===0)throw new y(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(at(this.address,i,a,o[0],s));return this.emit({type:g.TransferFromSubmitted,txHash:e}),X(()=>r?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:x(e)}),e instanceof c?e:new L(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){await this.sdk.requireChainAlignment(`approve`);let n=P(e);try{let e=await this.sdk.signer.writeContract(it(this.address,n,t));return this.emit({type:g.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approve`,error:x(e)}),e instanceof c?e:new I(`Operator approval failed`,{cause:e})}}async isApproved(e,t){return this.sdk.provider.readContract(Ve(this.address,P(t),P(e)))}async shield(e,t){await this.sdk.requireChainAlignment(`shield`);let n=await this.#n(),r;try{let e=await this.sdk.signer.getAddress();r=await this.sdk.provider.readContract(ce(n,e))}catch(e){throw e instanceof c?e:new mt(`Could not read ERC-20 balance for shield validation (token: ${n})`,{cause:x(e)})}if(r<e)throw new ft(`Insufficient ERC-20 balance: requested ${e}, available ${r} (token: ${n})`,{requested:e,available:r,token:n});let i=t?.approvalStrategy??`exact`;i!==`skip`&&await this.#o(e,i===`max`,t);try{let n=t?.to?P(t.to):await this.sdk.signer.getAddress(),r=await this.sdk.signer.writeContract(Ue(this.wrapper,n,e));return this.emit({type:g.ShieldSubmitted,txHash:r}),X(()=>t?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.sdk.provider.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:x(e)}),e instanceof c?e:new L(`Shield transaction failed`,{cause:e})}}async unwrap(e){await this.sdk.requireChainAlignment(`unwrap`);let t=await this.sdk.signer.getAddress(),n,r,i=Date.now();try{this.emit({type:g.EncryptStart}),{handles:n,inputProof:r}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-i})}catch(e){throw this.emit({type:g.EncryptError,error:x(e),durationMs:Date.now()-i}),e instanceof c?e:new y(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new y(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(Be(this.address,t,t,n[0],r));return this.emit({type:g.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:x(e)}),e instanceof c?e:new L(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){await this.sdk.requireChainAlignment(`unwrapAll`);let e=await this.sdk.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(h(t))throw new Te(`Cannot unshield: balance is zero`);try{let n=await this.sdk.signer.writeContract(ze(this.address,e,e,t));return this.emit({type:g.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.sdk.provider.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:x(e)}),e instanceof c?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 X(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return X(()=>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 t=await this.sdk.publicDecrypt([e]),n=t.clearValues[e];Me(n,`finalizeUnwrap: clearValue`);try{let r=await this.sdk.signer.writeContract(Qe(this.wrapper,e,n,t.decryptionProof));return this.emit({type:g.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.sdk.provider.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`finalizeUnwrap`,error:x(e)}),e instanceof c?e:new L(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){await this.sdk.requireChainAlignment(`approveUnderlying`);let t=await this.#n(),n=e??2n**256n-1n;try{let e=this.sdk.signer;if(n>0n){let n=await e.getAddress();await this.sdk.provider.readContract(he(t,n,this.wrapper))>0n&&await e.writeContract(v(t,this.wrapper,0n))}let r=await e.writeContract(v(t,this.wrapper,n));return this.emit({type:g.ApproveUnderlyingSubmitted,txHash:r}),{txHash:r,receipt:await this.sdk.provider.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approveUnderlying`,error:x(e)}),e instanceof c?e:new I(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(await this.sdk.requireChainAlignment(`delegateDecryption`),t&&t.getTime()<Date.now()+36e5)throw new d(`Expiration date must be at least 1 hour in the future`);let n=P(e),r=this.sdk.signer,i=await r.getAddress();if(n===P(i))throw new re(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new p(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),o=t?BigInt(Math.floor(t.getTime()/1e3)):fe,s;try{s=await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})}catch{s=-1n}if(s===o)throw new m(`The new expiration date (${o}) is the same as the current one. No on-chain change needed.`);try{let e=await r.writeContract(ae(a,n,this.address,o));return this.emit({type:g.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`delegateDecryption`,error:x(e)}),e instanceof c?e:gt(e)||new L(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){await this.sdk.requireChainAlignment(`revokeDelegation`);let t=P(e),n=this.sdk.signer,r=await n.getAddress(),i=await this.getAclAddress(),a;try{a=await this.getDelegationExpiry({delegatorAddress:r,delegateAddress:t})}catch{a=1n}if(a===0n)throw new f(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await n.writeContract(se(i,t,this.address));return this.emit({type:g.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`revokeDelegation`,error:x(e)}),e instanceof c?e:gt(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,t,n){let r=new Map;for(let i=0;i<e.length;i++)try{r.set(e[i].address,await t(e[i]))}catch(t){t instanceof c?r.set(e[i].address,t):r.set(e[i].address,new L(n,{cause:t}))}return r}async#i(e){if(e===0n)return;let t;try{t=await this.balanceOf(await this.sdk.signer.getAddress())}catch(e){throw e instanceof c?e:new pt(`Balance validation failed (token: ${this.address})`,{cause:e})}if(t<e)throw new dt(`Insufficient confidential balance: requested ${e}, available ${t} (token: ${this.address})`,{requested:e,available:t,token:this.address})}async#a(e,t,n){this.emit({type:g.UnshieldPhase1Submitted,txHash:e,operationId:t});let r;try{r=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof c?e:new L(`Failed to get unshield receipt`,{cause:e})}let i=qt(r.logs);if(!i)throw new L(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:t}),X(()=>n?.onFinalizing?.());let a=await this.finalizeUnwrap(i.unwrapRequestId??i.encryptedAmount);return this.emit({type:g.UnshieldPhase2Submitted,txHash:a.txHash,operationId:t}),X(()=>n?.onFinalizeSubmitted?.(a.txHash)),a}async#o(e,t,n){let r=await this.#n(),i=this.sdk.signer,a=await i.getAddress(),o=await this.sdk.provider.readContract(he(r,a,this.wrapper));if(!(o>=e))try{if(o>0n){let e=await i.writeContract(v(r,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let a=t?2n**256n-1n:e,s=await i.writeContract(v(r,this.wrapper,a));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:s}),X(()=>n?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(e){throw e instanceof c?e:new I(`ERC-20 approval failed`,{cause:e})}}};function X(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const rn={[D.id]:D.registryAddress,[k.id]:k.registryAddress,[O.id]:O.registryAddress},an=300*1e3;var on=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},rn,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(),t=this.#e[e];if(!t)throw new l(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return P(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new l(`page must be >= 1, got ${t}`);if(n<1)throw new l(`pageSize must be >= 1, got ${n}`);let i=await this.getRegistryAddress(),a=`total:${i}`,o=this.#r(a);if(o===void 0){let e=await this.provider.readContract(A(i));o=this.#i(a,Number(e))}let s=BigInt((t-1)*n),c=s+BigInt(n)>BigInt(o)?BigInt(o):s+BigInt(n);if(s>=BigInt(o))return{items:[],total:o,page:t,pageSize:n};let u=`slice:${i}:${s}:${c}`,d=this.#r(u);if(d===void 0){let e=await this.provider.readContract(M(i,s,c));d=this.#i(u,[...e])}if(!r)return{items:d,total:o,page:t,pageSize:n};let ee=`metadata:${i}:${s}:${c}`,f=this.#r(ee);if(f===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));f=this.#i(ee,n,t?an:void 0)}return{items:f,total:o,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.provider.readContract(ge(e.tokenAddress)),this.provider.readContract(de(e.tokenAddress)),this.provider.readContract(le(e.tokenAddress)),this.provider.readContract(ye(e.tokenAddress)),this.provider.readContract(ge(e.confidentialTokenAddress)),this.provider.readContract(de(e.confidentialTokenAddress)),this.provider.readContract(le(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=P(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(N(t,n));return o===lt?this.#i(r,null,an):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=P(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(j(t,n));return o===lt?this.#i(r,null,an):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(Xe(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(A(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(M(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(et(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(N(t,P(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(j(t,P(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(tt(t,P(e)))}};const Z=365*86400;async function Q(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var sn=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new E,this.cache=new Ct(e.storage),this.#t=e.onEvent??function(){};let t={};for(let n of e.chains??[])n.registryAddress&&(t[n.id]=n.registryAddress);Object.assign(t,e.registryAddresses),this.registry=new on({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:e.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};this.credentials=new Nt(n),this.delegatedCredentials=new Pt(n),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 ut({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 _(this,e)}createToken(e,t){return new nn(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 on({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:P(e.contractAddress)})),n={},r=[];for(let e of t)h(e.handle)?n[e.handle]=0n:r.push(e);if(r.length===0)return n;let i=await this.signer.getAddress(),a=[];for(let e of r){let t=await this.cache.get(i,e.contractAddress,e.handle);t===null?a.push(e):n[e.handle]=t}if(a.length===0)return n;let o=await this.credentials.allow(...new Set(t.map(e=>e.contractAddress))),s=new Map;for(let e of a){let t=s.get(e.contractAddress);t?t.push(e.handle):s.set(e.contractAddress,[e.handle])}let c=Date.now(),l=a.map(e=>e.handle);try{this.emitEvent({type:g.DecryptStart,handles:l}),await _e([...s.entries()].map(([e,t])=>async()=>{let r=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:i,startTimestamp:o.startTimestamp,durationDays:o.durationDays});for(let[t,a]of Object.entries(r))n[t]=a,await this.cache.set(i,e,t,a)}),5);let e={};for(let t of l){let r=n[t];r!==void 0&&(e[t]=r)}return this.emitEvent({type:g.DecryptEnd,durationMs:Date.now()-c,handles:l,result:e}),n}catch(e){throw this.emitEvent({type:g.DecryptError,error:x(e),durationMs:Date.now()-c,handles:l}),xe(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 xe(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 cn(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 ln(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 un(e,t){return(await dn(e,t))?.unwrapTxHash??null}async function dn(e,t){return cn(await e.get($(t)))}async function fn(e,t){await e.delete($(t))}var pn=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 mn=new pn;export{tn as ACL_TOPICS,we as AclPausedError,J as AclTopics,I as ApprovalFailedError,pt as BalanceCheckUnavailableError,ut as ChainMismatchError,pn as ChromeSessionStorage,l as ConfigurationError,Nt as CredentialsManager,Ct as DecryptCache,Te as DecryptionFailedError,rn as DefaultRegistryAddresses,Pt as DelegatedCredentialsManager,oe as DelegationContractIsSelfError,Ce as DelegationCooldownError,p as DelegationDelegateEqualsContractError,d as DelegationExpirationTooSoonError,Se as DelegationExpiredError,m as DelegationExpiryUnchangedError,f as DelegationNotFoundError,ee as DelegationNotPropagatedError,re as DelegationSelfNotAllowedError,mt as ERC20ReadFailedError,Ge as ERC7984_INTERFACE_ID,Ze as ERC7984_WRAPPER_INTERFACE_ID,nt as ERC7984_WRAPPER_INTERFACE_ID_LEGACY,y as EncryptionFailedError,t as IndexedDBStorage,dt as InsufficientConfidentialBalanceError,ft as InsufficientERC20BalanceError,me as InvalidKeypairError,u as KeypairExpiredError,E as MemoryStorage,pe as NoCiphertextError,_ as ReadonlyToken,s as RelayerRequestFailedError,_t as RelayerWeb,te as SigningFailedError,ne as SigningRejectedError,Yt as TOKEN_TOPICS,nn as Token,H as Topics,L as TransactionRevertedError,on as WrappersRegistry,ue as ZERO_HANDLE,c as ZamaError,o as ZamaErrorCode,sn as ZamaSDK,g as ZamaSDKEvents,he as allowanceContract,Le as anvil,v as approveContract,ce as balanceOfContract,i as buildZamaConfig,Fe as chains,mn as chromeSessionStorage,fn as clearPendingUnshield,ke as cleartext,rt as confidentialBalanceOfContract,ot as confidentialTotalSupplyContract,We as confidentialTransferContract,at as confidentialTransferFromContract,St as createConfig,le as decimalsContract,Zt as decodeAclEvent,Qt as decodeAclEvents,zt as decodeConfidentialTransfer,Xt as decodeDelegatedForUserDecryption,Gt as decodeOnChainEvent,Kt as decodeOnChainEvents,Y as decodeRevokedDelegationForUserDecryption,q as decodeUnwrapFinalized,Vt as decodeUnwrapRequested,Ht as decodeUnwrappedFinalized,Wt as decodeUnwrappedStarted,Bt as decodeWrapped,ae as delegateForUserDecryptionContract,Qe as finalizeUnwrapContract,$t as findDelegatedForUserDecryption,en as findRevokedDelegationForUserDecryption,qt as findUnwrapRequested,Jt as findWrapped,N as getConfidentialTokenAddressContract,ve as getDelegationExpiryContract,j as getTokenAddressContract,et as getTokenPairContract,Xe as getTokenPairsContract,A as getTokenPairsLengthContract,M as getTokenPairsSliceContract,Ie as hardhat,O as hoodi,e as indexedDBStorage,Ye as inferredTotalSupplyContract,Ke as isConfidentialTokenContract,tt as isConfidentialTokenValidContract,qe as isConfidentialWrapperContract,be as isHandleDelegatedContract,Ve as isOperatorContract,h as isZeroHandle,un as loadPendingUnshield,dn as loadPendingUnshieldRequest,D as mainnet,gt as matchAclRevert,a as matchZamaError,Pe as memoryStorage,ge as nameContract,Re as rateContract,n as resolveChainRelayers,r as resolveStorage,se as revokeDelegationContract,ln as savePendingUnshield,k as sepolia,it as setOperatorContract,$e as supportsInterfaceContract,de as symbolContract,He as totalSupplyContract,Je as underlyingContract,Be as unwrapContract,ze as unwrapFromBalanceContract,xt as web,Ue as wrapContract};
515
515
  //# sourceMappingURL=index.js.map