@zama-fhe/sdk 3.0.0-alpha.21 → 3.0.0-alpha.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/cjs/assertions.cjs +2 -0
- package/dist/cjs/assertions.cjs.map +1 -0
- package/dist/cjs/build.cjs +1 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -514
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/indexeddb-storage.cjs +2 -0
- package/dist/cjs/indexeddb-storage.cjs.map +1 -0
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/readonly-token.cjs +1 -1
- package/dist/cjs/readonly-token.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/signer.cjs +2 -0
- package/dist/cjs/signer.cjs.map +1 -0
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/web/index.cjs +515 -0
- package/dist/cjs/web/index.cjs.map +1 -0
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/{assertions-CfqI3AJv.js → assertions-DmKW7zPq.js} +1 -1
- package/dist/esm/{assertions-CfqI3AJv.js.map → assertions-DmKW7zPq.js.map} +1 -1
- package/dist/esm/build-Bot28OYv.js +2 -0
- package/dist/esm/build-Bot28OYv.js.map +1 -0
- package/dist/esm/chains/index.d.ts +2 -2
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/{chains-aHmrozPh.js → chains-DKasII-S.js} +1 -1
- package/dist/esm/{chains-aHmrozPh.js.map → chains-DKasII-S.js.map} +1 -1
- package/dist/esm/cleartext/index.d.ts +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/cleartext-BV_jxrwb.js +2 -0
- package/dist/esm/cleartext-BV_jxrwb.js.map +1 -0
- package/dist/esm/{cleartext-BHu6-LCv.d.ts → cleartext-Cr8QJJZy.d.ts} +2 -2
- package/dist/esm/{eip1193-subscribe-CcotSOIm.js → eip1193-subscribe-DDYcH5x3.js} +1 -1
- package/dist/esm/{eip1193-subscribe-CcotSOIm.js.map → eip1193-subscribe-DDYcH5x3.js.map} +1 -1
- package/dist/esm/{encryption-YS-Kb7qm.js → encryption-DhFNrebM.js} +2 -2
- package/dist/esm/{encryption-YS-Kb7qm.js.map → encryption-DhFNrebM.js.map} +1 -1
- package/dist/esm/{error-B6H-mBAh.js → error-BRHDbi2m.js} +1 -1
- package/dist/esm/{error-B6H-mBAh.js.map → error-BRHDbi2m.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +6 -7
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{hex-BZVTzEK6.js → hex-B4YpGJec.js} +2 -2
- package/dist/esm/{hex-BZVTzEK6.js.map → hex-B4YpGJec.js.map} +1 -1
- package/dist/esm/{index-BTY0MxOt.d.ts → index-BYVFG3L9.d.ts} +2 -2
- package/dist/esm/{index-BdyljG1F.d.ts → index-BZ-vGsiw.d.ts} +74 -27
- package/dist/esm/index.d.ts +12 -27
- package/dist/esm/index.js +1 -514
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/indexeddb-storage-Vy1KPGQW.js +2 -0
- package/dist/esm/indexeddb-storage-Vy1KPGQW.js.map +1 -0
- package/dist/esm/{memory-storage-CFXqXUcm.js → memory-storage-CaIfvzoX.js} +1 -1
- package/dist/esm/{memory-storage-CFXqXUcm.js.map → memory-storage-CaIfvzoX.js.map} +1 -1
- package/dist/esm/node/index.d.ts +5 -5
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
- package/dist/esm/query/index.d.ts +9 -8
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/{readonly-token-DCLOYhws.js → readonly-token-CUmBGPjA.js} +2 -2
- package/dist/esm/{readonly-token-DCLOYhws.js.map → readonly-token-CUmBGPjA.js.map} +1 -1
- package/dist/esm/{relayer-7Hd00A6X.js → relayer-DJI4oQ8o.js} +2 -2
- package/dist/esm/{relayer-7Hd00A6X.js.map → relayer-DJI4oQ8o.js.map} +1 -1
- package/dist/esm/{relayer-cleartext-DJkSUlZ2.d.ts → relayer-cleartext-7rkHJT9l.d.ts} +2 -2
- package/dist/esm/{relayer-cleartext-SZCM9wTx.js → relayer-cleartext-BCFRHdRV.js} +2 -2
- package/dist/esm/{relayer-cleartext-SZCM9wTx.js.map → relayer-cleartext-BCFRHdRV.js.map} +1 -1
- package/dist/esm/signer-BeScybq2.js +2 -0
- package/dist/esm/signer-BeScybq2.js.map +1 -0
- package/dist/esm/{types-CVyJHEya.d.ts → types-BwSAux96.d.ts} +3 -3
- package/dist/esm/{types-DePjTTbo.d.ts → types-CO3wLcMI.d.ts} +3 -3
- package/dist/esm/{types-FY7ciI37.d.ts → types-CmfU2ovm.d.ts} +10 -5
- package/dist/esm/{types-C1S426x4.d.ts → types-qTxGTfOc.d.ts} +1 -1
- package/dist/esm/viem/index.d.ts +6 -8
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +21 -0
- package/dist/esm/web/index.js +515 -0
- package/dist/esm/web/index.js.map +1 -0
- package/dist/esm/worker.base-client-ClMPyID1.js +2 -0
- package/dist/esm/worker.base-client-ClMPyID1.js.map +1 -0
- package/dist/esm/{wrappers-registry-CXNs4eR0.js → wrappers-registry-D5orGELU.js} +1 -1
- package/dist/esm/{wrappers-registry-CXNs4eR0.js.map → wrappers-registry-D5orGELU.js.map} +1 -1
- package/package.json +15 -1
- package/dist/esm/build-CvenCk6R.js +0 -2
- package/dist/esm/build-CvenCk6R.js.map +0 -1
- package/dist/esm/cleartext-I-etE_7S.js +0 -2
- package/dist/esm/cleartext-I-etE_7S.js.map +0 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,515 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./build.cjs`),t=require(`./relayer.cjs`),n=require(`./readonly-token.cjs`),r=require(`./encryption.cjs`),i=require(`./wrappers-registry.cjs`),a=require(`./relayer-cleartext.cjs`),o=require(`./chains.cjs`);let s=require(`viem`);var c=class extends t.r{constructor(e,n){super(t.i.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},l=class extends t.r{constructor(e,n){super(t.i.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},u=class extends t.r{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:n,providerChainId:r},i){super(t.i.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=n,this.providerChainId=r}},d=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},f=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},p=class extends t.r{constructor(e,n){super(t.i.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},m=class extends t.r{constructor(e,n){super(t.i.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function h(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const g={AlreadyDelegatedOrRevokedInSameBlock:e=>new n.x(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new n.b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new n.y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new n.O(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new n.S(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new n.C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new n.T(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new n.E(`Cannot revoke: no active delegation exists.`,{cause:e})};function _(e){let t=e instanceof Error?e:void 0,n=h(e);if(n&&n in g)return g[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(g))if(r.includes(e))return n(t);return null}var ee=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){if(!this.chain.aclContractAddress)throw new t.t(`No ACL address configured for chain ${this.chain.id}`);return this.chain.aclContractAddress}};function v(e){return e.startsWith(`0x`)?e:`0x${e}`}const y=8192,b=300*1e3;function te(e){let t=[];for(let n=0;n<e.length;n+=y)t.push(String.fromCharCode(...e.subarray(n,n+y)));return btoa(t.join(``))}function ne(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function x(e){return`fhe:pubkey:${e}`}function S(e,t){return`fhe:params:${e}:${t}`}function C(e){return`fhe:params-index:${e}`}function re(e){i.N(e,`CachedPublicKey`),i.F(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),i.F(e,`publicKey`,`CachedPublicKey.publicKey`)}function ie(e){i.N(e,`CachedPublicParams`),i.F(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),i.F(e,`publicParams`,`CachedPublicParams.publicParams`)}var ae=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let t=x(this.#t);try{let e=await this.#e.get(t);if(e){re(e);let t={publicKeyId:e.publicKeyId,publicKey:ne(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(t),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:i.L(e).message})}let n=await e();if(n===null)return null;this.#a=n;try{let e={publicKeyId:n.publicKeyId,publicKey:te(n.publicKey),lastValidatedAt:Date.now()};await this.#e.set(t,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:i.L(e).message})}return n}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,t){let n=S(this.#t,e);try{let t=await this.#e.get(n);if(t){ie(t);let n={publicParamsId:t.publicParamsId,publicParams:ne(t.publicParams)};return this.#o.set(e,n),n}}catch(t){await this.#g(n),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:i.L(t).message})}let r=await t();if(r===null)return null;this.#o.set(e,r);try{let t={publicParamsId:r.publicParamsId,publicParams:te(r.publicParams),lastValidatedAt:Date.now()};await this.#e.set(n,t);let a=C(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:i.L(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(t){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:i.L(t).message})}return r}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let t=x(this.#t),n=null,r=[];try{let[a,o]=await Promise.all([this.#e.get(t),this.#h()]);if(a)try{re(a),n={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:i.L(e).message}),await this.#g(t)}if(r=o,!n)return!1;if([n,...r.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let i=e-this.#r+b;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let c=await s.json(),l=c?.response?.fheKeyInfo?.[0];if(!c||typeof c!=`object`||c.status!==`succeeded`||!l?.fhePublicKey?.urls?.length||typeof c.response?.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let i=e-this.#r+b;return await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let u=c.response,d=l.fhePublicKey.urls[0];if(n.artifactUrl&&d&&d!==n.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let f={...n,lastValidatedAt:e};if(d){let e=await this.#m(d,n);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;f={...f,artifactUrl:d,etag:e.etag,lastModified:e.lastModified}}let p=[];for(let n of r){let i=u.crs[String(n.bits)]?.urls[0];if(n.data.artifactUrl&&i&&i!==n.data.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let a={...n.data,lastValidatedAt:e};if(i){let e=await this.#m(i,n.data);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;a={...a,artifactUrl:i,etag:e.etag,lastModified:e.lastModified}}p.push({...n,data:a})}return await this.#v(t,f,p),this.#u=e,!1}catch(a){let o=i.L(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+b;try{n&&await this.#v(t,{...n,lastValidatedAt:l},r.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:i.L(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=C(this.#t),t=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:i.L(e).message}),null))??[],n=new Set([...this.#o.keys(),...t]),r=Array.from(n);return(await Promise.all(r.map(async e=>{let t=S(this.#t,e),n;try{n=await this.#e.get(t)}catch(t){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:i.L(t).message}),null}if(!n)return null;try{return ie(n),{bits:e,key:t,data:{...n,lastValidatedAt:n.lastValidatedAt??0}}}catch(n){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:i.L(n).message}),await this.#g(t),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(t=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:i.L(t).message})})}async#_(e,t){let n=C(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(n),...t.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:i.L(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,t,n){let r=[this.#e.set(e,t).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:i.L(e).message})}),...n.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:i.L(e).message})}))];await Promise.all(r)}};async function w(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&oe(e)){await se(500*2**r);continue}throw e}throw n}function oe(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function se(e){return new Promise(t=>setTimeout(t,e))}var ce=class extends ee{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new e.o(`FheArtifactCache`,1,`artifacts`),new ae({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateKeypair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;await this.ensureInit();let i=this.chain.id;return w(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:i,values:t,contractAddress:n,userAddress:r});return{handles:e.handles,inputProof:e.inputProof}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,handles:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async getPublicKey(){await this.ensureInit();let e=this.chain.id;return this.#i().getPublicKey(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}};const le=3e4;var ue=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=le){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=le){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function de(e){try{return i.N(e,`runtime`),i.F(e,`id`,`runtime.id`),i.j(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function fe(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(i.N(t,`ns`),de(t.runtime))return t.runtime}catch{continue}}var pe=class extends ue{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=fe();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
|
|
2
|
-
//#region src/utils/assertions.ts
|
|
3
|
-
function assertObject(value, context) {
|
|
4
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
|
|
5
|
-
}
|
|
6
|
-
function assertString(value, context) {
|
|
7
|
-
if (typeof value !== "string") throw new TypeError(\`\${context} must be a string, got \${typeof value}\`);
|
|
8
|
-
}
|
|
9
|
-
function assertFunction(value, context) {
|
|
10
|
-
if (typeof value !== "function") throw new TypeError(\`\${context} must be a function, got \${typeof value}\`);
|
|
11
|
-
}
|
|
12
|
-
/** Assert that \`obj[key]\` is a string. Narrows \`obj\` to include \`{ [key]: string }\`. */
|
|
13
|
-
function assertStringProp(obj, key, context) {
|
|
14
|
-
assertString(obj[key], context);
|
|
15
|
-
}
|
|
16
|
-
/** Assert that \`obj[key]\` is a function. Narrows \`obj\` to include \`{ [key]: F }\`. */
|
|
17
|
-
function assertFunctionProp(obj, key, context) {
|
|
18
|
-
assertFunction(obj[key], context);
|
|
19
|
-
}
|
|
20
|
-
function assertCondition(condition, message) {
|
|
21
|
-
if (!condition) throw new TypeError(message);
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/utils/hex.ts
|
|
25
|
-
/** Normalize a un-prefixed hex payload to a 0x-prefixed \`Hex\` value. */
|
|
26
|
-
function prefixHex(value) {
|
|
27
|
-
return value.startsWith("0x") ? value : \`0x\${value}\`;
|
|
28
|
-
}
|
|
29
|
-
/** Convert a public \`Hex\` value back an unprefixed format. */
|
|
30
|
-
function unprefixHex(value) {
|
|
31
|
-
assertCondition(value.startsWith("0x"), \`Expected 0x-prefixed hex, got: \${value}\`);
|
|
32
|
-
return value.slice(2);
|
|
33
|
-
}
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region src/worker/browser-extension.ts
|
|
36
|
-
function isValidRuntime(runtime) {
|
|
37
|
-
try {
|
|
38
|
-
assertObject(runtime, "runtime");
|
|
39
|
-
assertStringProp(runtime, "id", "runtime.id");
|
|
40
|
-
assertFunctionProp(runtime, "getURL", "runtime.getURL");
|
|
41
|
-
return true;
|
|
42
|
-
} catch {
|
|
43
|
-
return false;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Return the browser extension runtime object, or \`undefined\` outside extensions.
|
|
48
|
-
* Works across Chrome/Edge (\`chrome.runtime\`) and Firefox/Safari (\`browser.runtime\`).
|
|
49
|
-
* Extensions have restricted CSP that blocks \`blob:\` URLs, so callers use
|
|
50
|
-
* this to detect the environment and resolve file URLs via \`runtime.getURL\`.
|
|
51
|
-
*/
|
|
52
|
-
function getBrowserExtensionRuntime() {
|
|
53
|
-
const g = globalThis;
|
|
54
|
-
for (const ns of [g.chrome, g.browser]) try {
|
|
55
|
-
assertObject(ns, "ns");
|
|
56
|
-
if (isValidRuntime(ns.runtime)) return ns.runtime;
|
|
57
|
-
} catch {
|
|
58
|
-
continue;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
//#endregion
|
|
62
|
-
//#region src/worker/relayer-sdk.worker.ts
|
|
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
|
-
}
|
|
73
|
-
let sdkGlobal = null;
|
|
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;
|
|
98
|
-
}
|
|
99
|
-
function unreachableFheType(_) {
|
|
100
|
-
throw new Error("Unsupported FHE type");
|
|
101
|
-
}
|
|
102
|
-
const relayerUrls = /* @__PURE__ */ new Set();
|
|
103
|
-
let csrfTokenBase = "";
|
|
104
|
-
const CSRF_HEADER_NAME = "x-csrf-token";
|
|
105
|
-
const MUTATING_METHODS = new Set([
|
|
106
|
-
"POST",
|
|
107
|
-
"PUT",
|
|
108
|
-
"DELETE",
|
|
109
|
-
"PATCH"
|
|
110
|
-
]);
|
|
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
|
-
/**
|
|
118
|
-
* Send a success response back to the main thread.
|
|
119
|
-
* Optionally transfers ArrayBuffers for zero-copy performance.
|
|
120
|
-
*/
|
|
121
|
-
function sendSuccess(id, type, data, transfer) {
|
|
122
|
-
const response = {
|
|
123
|
-
id,
|
|
124
|
-
type,
|
|
125
|
-
success: true,
|
|
126
|
-
data
|
|
127
|
-
};
|
|
128
|
-
return transfer ? self.postMessage(response, transfer) : self.postMessage(response);
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Send an error response back to the main thread.
|
|
132
|
-
*/
|
|
133
|
-
function sendError(id, type, error, statusCode) {
|
|
134
|
-
const response = {
|
|
135
|
-
id,
|
|
136
|
-
type,
|
|
137
|
-
success: false,
|
|
138
|
-
error
|
|
139
|
-
};
|
|
140
|
-
if (statusCode !== void 0) response.statusCode = statusCode;
|
|
141
|
-
self.postMessage(response);
|
|
142
|
-
}
|
|
143
|
-
const originalFetch = fetch;
|
|
144
|
-
/** Allowed CDN hostnames for loading the relayer SDK script. */
|
|
145
|
-
const ALLOWED_CDN_HOSTS = new Set(["cdn.zama.org"]);
|
|
146
|
-
/**
|
|
147
|
-
* Validate the CDN URL supplied by the caller.
|
|
148
|
-
* Ensures only HTTPS URLs from approved hosts are used when loading
|
|
149
|
-
* SDK code into the worker.
|
|
150
|
-
*/
|
|
151
|
-
function validateCdnUrl(rawUrl) {
|
|
152
|
-
let url;
|
|
153
|
-
try {
|
|
154
|
-
url = new URL(rawUrl);
|
|
155
|
-
} catch {
|
|
156
|
-
throw new Error("Invalid CDN URL");
|
|
157
|
-
}
|
|
158
|
-
if (url.protocol !== "https:") throw new Error("CDN URL must use https");
|
|
159
|
-
if (!ALLOWED_CDN_HOSTS.has(url.hostname)) throw new Error(\`CDN URL host is not allowed: \${url.hostname}\`);
|
|
160
|
-
return url.toString();
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Set up fetch interceptor to add credentials and CSRF token for relayer requests.
|
|
164
|
-
* Workers don't automatically include cookies, so we intercept fetch calls
|
|
165
|
-
* targeting our relayer proxy to inject credentials and CSRF headers.
|
|
166
|
-
*/
|
|
167
|
-
function setupFetchInterceptor() {
|
|
168
|
-
globalThis.fetch = async (input, init) => {
|
|
169
|
-
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
170
|
-
const method = init?.method?.toUpperCase() ?? "GET";
|
|
171
|
-
if (relayerUrls.size > 0 && [...relayerUrls].some((base) => url.startsWith(base))) {
|
|
172
|
-
const headers = new Headers(init?.headers);
|
|
173
|
-
if (MUTATING_METHODS.has(method) && csrfTokenBase) headers.set(CSRF_HEADER_NAME, csrfTokenBase);
|
|
174
|
-
return originalFetch(input, {
|
|
175
|
-
...init,
|
|
176
|
-
headers,
|
|
177
|
-
credentials: "include"
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
return originalFetch(input, init);
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Verify a fetched script's SHA-384 hash matches the expected integrity value.
|
|
185
|
-
*/
|
|
186
|
-
async function verifyIntegrity(content, expectedHash) {
|
|
187
|
-
const encoder = new TextEncoder();
|
|
188
|
-
const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
|
|
189
|
-
const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
190
|
-
if (hashHex !== expectedHash) throw new Error(\`CDN integrity check failed: expected SHA-384 \${expectedHash}, got \${hashHex}\`);
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Load SDK script from CDN.
|
|
194
|
-
* Uses two strategies depending on the environment:
|
|
195
|
-
* - **Web apps (default):** fetch + blob URL + importScripts. Avoids MIME-type
|
|
196
|
-
* rejections (some CDNs serve .cjs as \`application/node\`) and CSP
|
|
197
|
-
* \`unsafe-eval\` violations.
|
|
198
|
-
* - **Browser extensions (Chrome/Firefox/Safari):** importScripts directly.
|
|
199
|
-
* Blob URLs are blocked by extension CSP, but the CDN must be allowed
|
|
200
|
-
* in the extension's manifest CSP.
|
|
201
|
-
*
|
|
202
|
-
* Integrity is always verified when a hash is provided, regardless of strategy.
|
|
203
|
-
*/
|
|
204
|
-
async function fetchScript(cdnUrl) {
|
|
205
|
-
const response = await originalFetch(cdnUrl);
|
|
206
|
-
if (!response.ok) throw new Error(\`Failed to fetch SDK: \${response.status} \${response.statusText}\`);
|
|
207
|
-
return response.text();
|
|
208
|
-
}
|
|
209
|
-
async function loadSdkScript(cdnUrl, integrity) {
|
|
210
|
-
const validatedUrl = validateCdnUrl(cdnUrl);
|
|
211
|
-
if (getBrowserExtensionRuntime()) {
|
|
212
|
-
if (integrity) await verifyIntegrity(await fetchScript(validatedUrl), integrity);
|
|
213
|
-
return self.importScripts(validatedUrl);
|
|
214
|
-
}
|
|
215
|
-
const scriptContent = await fetchScript(validatedUrl);
|
|
216
|
-
if (integrity) await verifyIntegrity(scriptContent, integrity);
|
|
217
|
-
const blob = new Blob([scriptContent], { type: "application/javascript" });
|
|
218
|
-
const blobUrl = URL.createObjectURL(blob);
|
|
219
|
-
try {
|
|
220
|
-
self.importScripts(blobUrl);
|
|
221
|
-
} finally {
|
|
222
|
-
URL.revokeObjectURL(blobUrl);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Handle INIT request - load SDK WASM and register chain configs (instances are lazy).
|
|
227
|
-
*/
|
|
228
|
-
async function handleInit(request) {
|
|
229
|
-
const { id, type, payload } = request;
|
|
230
|
-
try {
|
|
231
|
-
if (payload.env !== "web") throw new Error(\`Web worker received unexpected env: \${payload.env}\`);
|
|
232
|
-
const { cdnUrl, csrfToken, integrity, thread } = payload;
|
|
233
|
-
csrfTokenBase = csrfToken;
|
|
234
|
-
setupFetchInterceptor();
|
|
235
|
-
await loadSdkScript(cdnUrl, integrity);
|
|
236
|
-
if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
|
|
237
|
-
sdkGlobal = self.relayerSDK;
|
|
238
|
-
await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
|
|
239
|
-
registerRelayerUrls(payload.chains);
|
|
240
|
-
for (const chain of payload.chains) configs.set(chain.id, chain);
|
|
241
|
-
sendSuccess(id, type, { initialized: true });
|
|
242
|
-
} catch (error) {
|
|
243
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
244
|
-
console.error("[Worker] Init error:", message);
|
|
245
|
-
sendError(id, type, message);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
249
|
-
function toBigInt(value) {
|
|
250
|
-
return typeof value === "boolean" ? value ? 1n : 0n : value;
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Add a single typed value to the encrypted input builder.
|
|
254
|
-
*/
|
|
255
|
-
function addTypedValue(input, entry) {
|
|
256
|
-
const { value, type: fheType } = entry;
|
|
257
|
-
switch (fheType) {
|
|
258
|
-
case "ebool":
|
|
259
|
-
input.addBool(typeof value === "boolean" ? value : value !== 0n);
|
|
260
|
-
break;
|
|
261
|
-
case "euint8":
|
|
262
|
-
input.add8(toBigInt(value));
|
|
263
|
-
break;
|
|
264
|
-
case "euint16":
|
|
265
|
-
input.add16(toBigInt(value));
|
|
266
|
-
break;
|
|
267
|
-
case "euint32":
|
|
268
|
-
input.add32(toBigInt(value));
|
|
269
|
-
break;
|
|
270
|
-
case "euint64":
|
|
271
|
-
input.add64(toBigInt(value));
|
|
272
|
-
break;
|
|
273
|
-
case "euint128":
|
|
274
|
-
input.add128(toBigInt(value));
|
|
275
|
-
break;
|
|
276
|
-
case "euint256":
|
|
277
|
-
input.add256(toBigInt(value));
|
|
278
|
-
break;
|
|
279
|
-
case "eaddress":
|
|
280
|
-
input.addAddress(value);
|
|
281
|
-
break;
|
|
282
|
-
default: unreachableFheType(fheType);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
/**
|
|
286
|
-
* Handle ENCRYPT request.
|
|
287
|
-
*/
|
|
288
|
-
async function handleEncrypt(request) {
|
|
289
|
-
const { id, type, payload } = request;
|
|
290
|
-
const { values, contractAddress, userAddress } = payload;
|
|
291
|
-
try {
|
|
292
|
-
const input = (await getInstance(payload.chainId)).createEncryptedInput(contractAddress, userAddress);
|
|
293
|
-
for (const entry of values) addTypedValue(input, entry);
|
|
294
|
-
const encrypted = await input.encrypt();
|
|
295
|
-
sendSuccess(id, type, {
|
|
296
|
-
handles: encrypted.handles,
|
|
297
|
-
inputProof: encrypted.inputProof
|
|
298
|
-
}, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
|
|
299
|
-
} catch (error) {
|
|
300
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
301
|
-
console.error("[Worker] Encrypt error:", message);
|
|
302
|
-
sendError(id, type, message);
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Handle USER_DECRYPT request.
|
|
307
|
-
*/
|
|
308
|
-
async function handleUserDecrypt(request) {
|
|
309
|
-
const { id, type, payload } = request;
|
|
310
|
-
try {
|
|
311
|
-
const instance = await getInstance(payload.chainId);
|
|
312
|
-
const handleContractPairs = payload.handles.map((handle) => ({
|
|
313
|
-
handle,
|
|
314
|
-
contractAddress: payload.contractAddress
|
|
315
|
-
}));
|
|
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) });
|
|
317
|
-
} catch (error) {
|
|
318
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
319
|
-
const statusCode = extractHttpStatus(error);
|
|
320
|
-
console.error("[Worker] UserDecrypt error:", message);
|
|
321
|
-
sendError(id, type, message, statusCode);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Extract an HTTP status code from an error, if present.
|
|
326
|
-
* Relayer SDK errors may carry a \`status\` or \`statusCode\` property.
|
|
327
|
-
*/
|
|
328
|
-
function extractHttpStatus(error) {
|
|
329
|
-
if (error === null || error === void 0 || typeof error !== "object") return;
|
|
330
|
-
const e = error;
|
|
331
|
-
if (typeof e.statusCode === "number") return e.statusCode;
|
|
332
|
-
if (typeof e.status === "number") return e.status;
|
|
333
|
-
if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
|
|
334
|
-
const cause = e.cause;
|
|
335
|
-
if (typeof cause.statusCode === "number") return cause.statusCode;
|
|
336
|
-
if (typeof cause.status === "number") return cause.status;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Handle PUBLIC_DECRYPT request.
|
|
341
|
-
*/
|
|
342
|
-
async function handlePublicDecrypt(request) {
|
|
343
|
-
const { id, type, payload } = request;
|
|
344
|
-
try {
|
|
345
|
-
sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.handles) });
|
|
346
|
-
} catch (error) {
|
|
347
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
348
|
-
console.error("[Worker] PublicDecrypt error:", message);
|
|
349
|
-
sendError(id, type, message);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
/**
|
|
353
|
-
* Handle GENERATE_KEYPAIR request.
|
|
354
|
-
*/
|
|
355
|
-
async function handleGenerateKeypair(request) {
|
|
356
|
-
const { id, type, payload } = request;
|
|
357
|
-
try {
|
|
358
|
-
const keypair = (await getInstance(payload.chainId)).generateKeypair();
|
|
359
|
-
sendSuccess(id, type, {
|
|
360
|
-
publicKey: prefixHex(keypair.publicKey),
|
|
361
|
-
privateKey: prefixHex(keypair.privateKey)
|
|
362
|
-
});
|
|
363
|
-
} catch (error) {
|
|
364
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
365
|
-
console.error("[Worker] GenerateKeypair error:", message);
|
|
366
|
-
sendError(id, type, message);
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Handle CREATE_EIP712 request.
|
|
371
|
-
*/
|
|
372
|
-
async function handleCreateEIP712(request) {
|
|
373
|
-
const { id, type, payload } = request;
|
|
374
|
-
try {
|
|
375
|
-
sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
|
|
376
|
-
} catch (error) {
|
|
377
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
378
|
-
console.error("[Worker] CreateEIP712 error:", message);
|
|
379
|
-
sendError(id, type, message);
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* Handle CREATE_DELEGATED_EIP712 request.
|
|
384
|
-
*/
|
|
385
|
-
async function handleCreateDelegatedEIP712(request) {
|
|
386
|
-
const { id, type, payload } = request;
|
|
387
|
-
try {
|
|
388
|
-
sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
|
|
389
|
-
} catch (error) {
|
|
390
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
391
|
-
console.error("[Worker] CreateDelegatedEIP712 error:", message);
|
|
392
|
-
sendError(id, type, message);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
/**
|
|
396
|
-
* Handle DELEGATED_USER_DECRYPT request.
|
|
397
|
-
*/
|
|
398
|
-
async function handleDelegatedUserDecrypt(request) {
|
|
399
|
-
const { id, type, payload } = request;
|
|
400
|
-
try {
|
|
401
|
-
const instance = await getInstance(payload.chainId);
|
|
402
|
-
const handleContractPairs = payload.handles.map((handle) => ({
|
|
403
|
-
handle,
|
|
404
|
-
contractAddress: payload.contractAddress
|
|
405
|
-
}));
|
|
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) });
|
|
407
|
-
} catch (error) {
|
|
408
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
409
|
-
const statusCode = extractHttpStatus(error);
|
|
410
|
-
console.error("[Worker] DelegatedUserDecrypt error:", message);
|
|
411
|
-
sendError(id, type, message, statusCode);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* Handle REQUEST_ZK_PROOF_VERIFICATION request.
|
|
416
|
-
*/
|
|
417
|
-
async function handleRequestZKProofVerification(request) {
|
|
418
|
-
const { id, type, payload } = request;
|
|
419
|
-
try {
|
|
420
|
-
const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
|
|
421
|
-
sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
|
|
422
|
-
} catch (error) {
|
|
423
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
424
|
-
console.error("[Worker] RequestZKProofVerification error:", message);
|
|
425
|
-
sendError(id, type, message);
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
|
-
* Handle GET_PUBLIC_KEY request.
|
|
430
|
-
*/
|
|
431
|
-
async function handleGetPublicKey(request) {
|
|
432
|
-
const { id, type, payload } = request;
|
|
433
|
-
try {
|
|
434
|
-
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
|
|
435
|
-
} catch (error) {
|
|
436
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
437
|
-
console.error("[Worker] GetPublicKey error:", message);
|
|
438
|
-
sendError(id, type, message);
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Handle GET_PUBLIC_PARAMS request.
|
|
443
|
-
*/
|
|
444
|
-
async function handleGetPublicParams(request) {
|
|
445
|
-
const { id, type, payload } = request;
|
|
446
|
-
try {
|
|
447
|
-
sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
|
|
448
|
-
} catch (error) {
|
|
449
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
450
|
-
console.error("[Worker] GetPublicParams error:", message);
|
|
451
|
-
sendError(id, type, message);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
/**
|
|
455
|
-
* Handle UPDATE_CSRF request - update the stored CSRF token.
|
|
456
|
-
*/
|
|
457
|
-
function handleUpdateCsrf(request) {
|
|
458
|
-
const { id, type, payload } = request;
|
|
459
|
-
csrfTokenBase = payload.csrfToken;
|
|
460
|
-
sendSuccess(id, type, { updated: true });
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Main message handler.
|
|
464
|
-
*/
|
|
465
|
-
self.onmessage = async (event) => {
|
|
466
|
-
const request = event.data;
|
|
467
|
-
try {
|
|
468
|
-
switch (request.type) {
|
|
469
|
-
case "INIT":
|
|
470
|
-
await handleInit(request);
|
|
471
|
-
break;
|
|
472
|
-
case "UPDATE_CSRF":
|
|
473
|
-
handleUpdateCsrf(request);
|
|
474
|
-
break;
|
|
475
|
-
case "ENCRYPT":
|
|
476
|
-
await handleEncrypt(request);
|
|
477
|
-
break;
|
|
478
|
-
case "USER_DECRYPT":
|
|
479
|
-
await handleUserDecrypt(request);
|
|
480
|
-
break;
|
|
481
|
-
case "PUBLIC_DECRYPT":
|
|
482
|
-
await handlePublicDecrypt(request);
|
|
483
|
-
break;
|
|
484
|
-
case "GENERATE_KEYPAIR":
|
|
485
|
-
await handleGenerateKeypair(request);
|
|
486
|
-
break;
|
|
487
|
-
case "CREATE_EIP712":
|
|
488
|
-
await handleCreateEIP712(request);
|
|
489
|
-
break;
|
|
490
|
-
case "CREATE_DELEGATED_EIP712":
|
|
491
|
-
await handleCreateDelegatedEIP712(request);
|
|
492
|
-
break;
|
|
493
|
-
case "DELEGATED_USER_DECRYPT":
|
|
494
|
-
await handleDelegatedUserDecrypt(request);
|
|
495
|
-
break;
|
|
496
|
-
case "REQUEST_ZK_PROOF_VERIFICATION":
|
|
497
|
-
await handleRequestZKProofVerification(request);
|
|
498
|
-
break;
|
|
499
|
-
case "GET_PUBLIC_KEY":
|
|
500
|
-
await handleGetPublicKey(request);
|
|
501
|
-
break;
|
|
502
|
-
case "GET_PUBLIC_PARAMS":
|
|
503
|
-
await handleGetPublicParams(request);
|
|
504
|
-
break;
|
|
505
|
-
default: console.error("[Worker] Unknown request type:", request.type);
|
|
506
|
-
}
|
|
507
|
-
} catch (error) {
|
|
508
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
509
|
-
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
|
|
510
|
-
}
|
|
511
|
-
};
|
|
512
|
-
//#endregion
|
|
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,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function me(e){return{type:`web`,createWorker:t=>new pe({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:e?.logger,thread:e?.threads}),createRelayer:(t,n)=>new ce({chain:t,worker:n,...e})}}function he(){return{type:`cleartext`,createRelayer:e=>{if(!e.executorAddress)throw new t.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new a.t(e)}}}function ge(t){return e.t(t.signer,t.provider,t)}var _e=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,s.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},ve=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return v(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function ye(e){i.N(e,`Stored credentials`),i.P(e.publicKey,`credentials.publicKey`),i.O(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)i.A(typeof t==`string`&&(0,s.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);i.N(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),i.P(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),i.P(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),i.A(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),i.A(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function be(e){ye(e);let t=e;i.A(typeof t.delegatorAddress==`string`&&(0,s.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),i.A(typeof t.delegateAddress==`string`&&(0,s.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),i.A(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),i.A(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,s.getAddress)(e))),r=new Set(e.map(e=>(0,s.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,s.getAddress)(e)))].toSorted()}async function k(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var xe=class{#e;constructor(e){this.#e=e}#t(e){i.N(e,`Session entry`),i.P(e.signature,`session.signature`),i.A(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),i.A(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},A=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new xe(e.sessionStorage),this.crypto=new ve,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:e,contracts:r,createKey:a,createFn:o}){this.emit({type:n.r.CredentialsLoading,contractAddresses:r});try{let t=await this.storage.get(e);if(t){this.assertEncrypted(t);let i=await this.sessionSignatures.get(e);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(e),this.emit({type:n.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(t,i.signature);if(D(a,r))return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:e,credentials:a,requiredContracts:r});this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}if(T(t)){if(E(t.contractAddresses,r)){let i=await this.signForContracts(t,t.contractAddresses);await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(t,i);return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(t,t.contractAddresses),a=await this.decryptCredentials(t,i);return this.#a({key:e,credentials:a,requiredContracts:r})}this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof t.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:n.r.CredentialsCorrupted,error:i.L(r)}),await this.#s(e)}return(!this.#t||this.#n!==a)&&(this.#n=a,this.#t=o().then(e=>(this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:n.r.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:e,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:n.r.CredentialsCreating,contractAddresses:r});try{let t=await i();return await this.persistCredentials(e,t),await this.sessionSignatures.set({key:e,signature:t.signature,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsCreated,contractAddresses:r}),t}catch(e){if(e instanceof t.r)throw e;return n.P(e,a)}}async#a({key:e,credentials:t,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}let i=this.#o({key:e,credentials:t,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:t,requiredContracts:r}){let i=O([...t.contractAddresses,...r]),a=await this.signForContracts(t,i),o={...t,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}};function Se(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var j=class t extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return k((0,s.getAddress)(e),t)}constructor(t){super(t),this.#e=t.relayer,Se(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&t.sessionStorage instanceof e.i&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeFor(e){await this.revokeSession(await t.computeStoreKey(e.address,e.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){ye(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let e=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,s.getAddress)(e)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await t.computeStoreKey(e,n);return this.#n=r,this.#t=i,i}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return k((0,s.getAddress)(e),(0,s.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,s.getAddress)(e),r=O(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,s.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,s.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,s.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,s.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){be(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${(0,s.getAddress)(n)}:${(0,s.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}};function N(e){return(0,s.keccak256)((0,s.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,s.getAddress)(v(e.slice(-40)))}function Ce(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,s.getAddress)(v(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function we(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return v(L(e,t))}function Te(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function V(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function H(e){return e.topics[0]===P.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}:null}function U(e){return e.topics[0]===P.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:null}function Ee(e){let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function De(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Oe(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ce(e.topics[1]),txId:Ce(e.topics[2]),to:F(e.topics[3]),returnVal:we(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ke(e){return Te(e)??V(e)??H(e)??De(e)??U(e)??Oe(e)}function Ae(e){let t=[];for(let n of e){let e=ke(n);e&&t.push(e)}return t}function je(e){for(let t of e){let e=H(t);if(e)return e}return null}function Me(e){for(let t of e){let e=V(t);if(e)return e}return null}const Ne=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,P.UnwrappedStarted],W={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Pe(e){return G(e)??K(e)}function Fe(e){let t=[];for(let n of e){let e=Pe(n);e&&t.push(e)}return t}function Ie(e){for(let t of e){let e=G(t);if(e)return e}return null}function Le(e){for(let t of e){let e=K(t);if(e)return e}return null}const Re=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var ze=class e extends n.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,s.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(i.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,a,o){await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:u,onTransferSubmitted:d}=o??{},f=(0,s.getAddress)(e);c||await this.#i(a);let p,m,h=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:p,inputProof:m}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-h}),q(()=>u?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-h}),e instanceof t.r?e:new r.n(`Failed to encrypt transfer amount`,{cause:e})}if(p.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.b(this.address,f,p[0],m));return this.emit({type:n.r.TransferSubmitted,txHash:e}),q(()=>d?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transfer`,error:i.L(e)}),e instanceof t.r?e:new l(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,a,o,c){await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let u=(0,s.getAddress)(e),d=(0,s.getAddress)(a),f,p,m=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:u}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-m}),q(()=>c?.onEncryptComplete?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-m}),e instanceof t.r?e:new r.n(`Failed to encrypt transferFrom amount`,{cause:e})}if(f.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.x(this.address,u,d,f[0],p));return this.emit({type:n.r.TransferFromSubmitted,txHash:e}),q(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transferFrom`,error:i.L(e)}),e instanceof t.r?e:new l(`TransferFrom transaction failed`,{cause:e})}}async approve(e,r){await this.sdk.requireChainAlignment(`approve`);let a=(0,s.getAddress)(e);try{let e=await this.sdk.signer.writeContract(i.w(this.address,a,r));return this.emit({type:n.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approve`,error:i.L(e)}),e instanceof t.r?e:new c(`Operator approval failed`,{cause:e})}}async isApproved(e,t){return this.sdk.provider.readContract(i.S(this.address,(0,s.getAddress)(t),(0,s.getAddress)(e)))}async shield(e,r){await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await this.sdk.signer.getAddress();o=await this.sdk.provider.readContract(n.d(a,e))}catch(e){throw e instanceof t.r?e:new m(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:i.L(e)})}if(o<e)throw new f(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${a})`,{requested:e,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(e,c===`max`,r);try{let t=r?.to?(0,s.getAddress)(r.to):await this.sdk.signer.getAddress(),a=await this.sdk.signer.writeContract(i._(this.wrapper,t,e));return this.emit({type:n.r.ShieldSubmitted,txHash:a}),q(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`shield`,error:i.L(e)}),e instanceof t.r?e:new l(`Shield transaction failed`,{cause:e})}}async unwrap(e){await this.sdk.requireChainAlignment(`unwrap`);let a=await this.sdk.signer.getAddress(),o,s,c=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:o,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:a}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-c})}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-c}),e instanceof t.r?e:new r.n(`Failed to encrypt unshield amount`,{cause:e})}if(o.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.E(this.address,a,a,o[0],s));return this.emit({type:n.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){await this.sdk.requireChainAlignment(`unwrapAll`);let e=await this.sdk.signer.getAddress(),a=await this.readConfidentialBalanceOf(e);if(n._(a))throw new r.t(`Cannot unshield: balance is zero`);try{let t=await this.sdk.signer.writeContract(i.D(this.address,e,e,a));return this.emit({type:n.r.UnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return q(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return q(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){await this.sdk.requireChainAlignment(`finalizeUnwrap`);let r=await this.sdk.publicDecrypt([e]),a=r.clearValues[e];i.k(a,`finalizeUnwrap: clearValue`);try{let t=await this.sdk.signer.writeContract(i.m(this.wrapper,e,a,r.decryptionProof));return this.emit({type:n.r.FinalizeUnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`finalizeUnwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){await this.sdk.requireChainAlignment(`approveUnderlying`);let r=await this.#n(),a=e??2n**256n-1n;try{let e=this.sdk.signer;if(a>0n){let t=await e.getAddress();await this.sdk.provider.readContract(n.l(r,t,this.wrapper))>0n&&await e.writeContract(n.u(r,this.wrapper,0n))}let t=await e.writeContract(n.u(r,this.wrapper,a));return this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approveUnderlying`,error:i.L(e)}),e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:r}){if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new n.C(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(e),o=this.sdk.signer,c=await o.getAddress();if(a===(0,s.getAddress)(c))throw new n.O(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new n.S(`Delegate address cannot be the same as the contract address (${this.address}).`);let u=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):n.i,f;try{f=await this.getDelegationExpiry({delegatorAddress:c,delegateAddress:a})}catch{f=-1n}if(f===d)throw new n.T(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await o.writeContract(n.a(u,a,this.address,d));return this.emit({type:n.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`delegateDecryption`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){await this.sdk.requireChainAlignment(`revokeDelegation`);let r=(0,s.getAddress)(e),a=this.sdk.signer,o=await a.getAddress(),c=await this.getAclAddress(),u;try{u=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:r})}catch{u=1n}if(u===0n)throw new n.E(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await a.writeContract(n.c(c,r,this.address));return this.emit({type:n.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`revokeDelegation`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,n,r){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await n(e[a]))}catch(n){n instanceof t.r?i.set(e[a].address,n):i.set(e[a].address,new l(r,{cause:n}))}return i}async#i(e){if(e===0n)return;let n;try{n=await this.balanceOf(await this.sdk.signer.getAddress())}catch(e){throw e instanceof t.r?e:new p(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new d(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}async#a(e,r,i){this.emit({type:n.r.UnshieldPhase1Submitted,txHash:e,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof t.r?e:new l(`Failed to get unshield receipt`,{cause:e})}let o=je(a.logs);if(!o)throw new l(`No UnwrapRequested event found in unshield receipt`);this.emit({type:n.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:n.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(e,r,i){let a=await this.#n(),o=this.sdk.signer,s=await o.getAddress(),l=await this.sdk.provider.readContract(n.l(a,s,this.wrapper));if(!(l>=e))try{if(l>0n){let e=await o.writeContract(n.u(a,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let t=r?2n**256n-1n:e,s=await o.writeContract(n.u(a,this.wrapper,t));this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(e){throw e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const J={[o.a.id]:o.a.registryAddress,[o.o.id]:o.o.registryAddress,[o.i.id]:o.i.registryAddress},Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},J,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.provider.getChainId(),n=this.#e[e];if(!n)throw new t.t(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return(0,s.getAddress)(n)}async listPairs(e={}){let n=e.page??1,r=e.pageSize??100,a=e.metadata??!1;if(n<1)throw new t.t(`page must be >= 1, got ${n}`);if(r<1)throw new t.t(`pageSize must be >= 1, got ${r}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(i.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*r),u=l+BigInt(r)>BigInt(c)?BigInt(c):l+BigInt(r);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:r};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(i.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:r};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:r}}async#a(e){let[t,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(n.m(e.tokenAddress)),this.provider.readContract(n.h(e.tokenAddress)),this.provider.readContract(n.f(e.tokenAddress)),this.provider.readContract(n.p(e.tokenAddress)),this.provider.readContract(n.m(e.confidentialTokenAddress)),this.provider.readContract(n.h(e.confidentialTokenAddress)),this.provider.readContract(n.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ct:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.t(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{confidentialTokenAddress:c,isValid:o})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ut:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.n(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{tokenAddress:c,isValid:o})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(i.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(i.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(i.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.t(t,(0,s.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.n(t,(0,s.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.s(t,(0,s.getAddress)(e)))}};const Z=365*86400;async function Q(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var Be=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(t){this.relayer=t.relayer,this.provider=t.provider,this.signer=t.signer,this.storage=t.storage,this.sessionStorage=t.sessionStorage??new e.i,this.cache=new _e(t.storage),this.#t=t.onEvent??function(){};let n={};for(let e of t.chains??[])e.registryAddress&&(n[e.id]=e.registryAddress);Object.assign(n,t.registryAddresses),this.registry=new X({provider:this.provider,registryTTL:t.registryTTL,registryAddresses:n}),this.#e=t.registryTTL;let r={relayer:this.relayer,signer:t.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let e=t.keypairTTL??2592e3;if(e<=0||isNaN(e))throw Error(`keypairTTL must be a positive number (seconds)`);return e>Z?(console.warn(`[zama-sdk] keypairTTL (${e}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):e})(),sessionTTL:t.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new j(r),this.delegatedCredentials=new M(r),this.#r=this.signer.subscribe?.(e=>{this.#i(e)})}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let[t,n]=await Promise.all([this.signer.getChainId(),this.provider.getChainId()]);if(t!==n)throw new u({operation:e,signerChainId:t,providerChainId:n});return t}async#i(e){if(e.previous){let t=e.previous;await Q(`revoke previous identity`,()=>this.credentials.revokeFor(t)),await Q(`clear decrypt cache`,()=>this.cache.clearForRequester(t.address))}let t=e.next?.chainId;t!==void 0&&await Q(`switch relayer chain`,()=>{this.relayer.switchChain(t)});for(let t of this.#n)await Q(`identity listener`,()=>t(e))}createReadonlyToken(e){return new n.t(this,e)}createToken(e,t){return new ze(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let t=e.map(e=>({handle:e.handle,contractAddress:(0,s.getAddress)(e.contractAddress)})),r={},a=[];for(let e of t)n._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),c=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?c.push(e):r[e.handle]=t}if(c.length===0)return r;let l=await this.credentials.allow(...new Set(t.map(e=>e.contractAddress))),u=new Map;for(let e of c){let t=u.get(e.contractAddress);t?t.push(e.handle):u.set(e.contractAddress,[e.handle])}let d=Date.now(),f=c.map(e=>e.handle);try{this.emitEvent({type:n.r.DecryptStart,handles:f}),await n.n([...u.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:l.contractAddresses,privateKey:l.privateKey,publicKey:l.publicKey,signature:l.signature,signerAddress:o,startTimestamp:l.startTimestamp,durationDays:l.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of f){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:n.r.DecryptEnd,durationMs:Date.now()-d,handles:f,result:e}),r}catch(e){throw this.emitEvent({type:n.r.DecryptError,error:i.L(e),durationMs:Date.now()-d,handles:f}),n.v(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw n.v(e,`Public decryption failed`)}}async revokeSession(){let e=await this.signer.getAddress(),t=await this.signer.getChainId();try{await this.credentials.revokeFor({address:e,chainId:t})}finally{await this.cache.clearForRequester(e)}}dispose(){this.#r?.(),this.#r=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}function Ve(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function He(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ue(e,t){return(await We(e,t))?.unwrapTxHash??null}async function We(e,t){return Ve(await e.get($(t)))}async function Ge(e,t){await e.delete($(t))}var Ke=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const qe=new Ke;exports.ACL_TOPICS=Re,exports.AclPausedError=n.y,exports.AclTopics=W,exports.ApprovalFailedError=c,exports.BalanceCheckUnavailableError=p,exports.ChainMismatchError=u,exports.ChromeSessionStorage=Ke,exports.ConfigurationError=t.t,exports.CredentialsManager=j,exports.DecryptCache=_e,exports.DecryptionFailedError=r.t,exports.DefaultRegistryAddresses=J,exports.DelegatedCredentialsManager=M,exports.DelegationContractIsSelfError=n.b,exports.DelegationCooldownError=n.x,exports.DelegationDelegateEqualsContractError=n.S,exports.DelegationExpirationTooSoonError=n.C,exports.DelegationExpiredError=n.w,exports.DelegationExpiryUnchangedError=n.T,exports.DelegationNotFoundError=n.E,exports.DelegationNotPropagatedError=n.D,exports.DelegationSelfNotAllowedError=n.O,exports.ERC20ReadFailedError=m,exports.ERC7984_INTERFACE_ID=i.c,exports.ERC7984_WRAPPER_INTERFACE_ID=i.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=i.u,exports.EncryptionFailedError=r.n,exports.IndexedDBStorage=e.o,exports.InsufficientConfidentialBalanceError=d,exports.InsufficientERC20BalanceError=f,exports.InvalidKeypairError=n.k,exports.KeypairExpiredError=n.A,exports.MemoryStorage=e.i,exports.NoCiphertextError=n.j,exports.ReadonlyToken=n.t,exports.RelayerRequestFailedError=t.n,exports.RelayerWeb=ce,exports.SigningFailedError=n.M,exports.SigningRejectedError=n.N,exports.TOKEN_TOPICS=Ne,exports.Token=ze,exports.Topics=P,exports.TransactionRevertedError=l,exports.WrappersRegistry=X,exports.ZERO_HANDLE=n.g,exports.ZamaError=t.r,exports.ZamaErrorCode=t.i,exports.ZamaSDK=Be,exports.ZamaSDKEvents=n.r,exports.allowanceContract=n.l,exports.anvil=o.t,exports.approveContract=n.u,exports.balanceOfContract=n.d,exports.buildZamaConfig=e.t,exports.chains=o.n,exports.chromeSessionStorage=qe,exports.clearPendingUnshield=Ge,exports.cleartext=he,exports.confidentialBalanceOfContract=i.v,exports.confidentialTotalSupplyContract=i.y,exports.confidentialTransferContract=i.b,exports.confidentialTransferFromContract=i.x,exports.createConfig=ge,exports.decimalsContract=n.f,exports.decodeAclEvent=Pe,exports.decodeAclEvents=Fe,exports.decodeConfidentialTransfer=Te,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=ke,exports.decodeOnChainEvents=Ae,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=U,exports.decodeUnwrapRequested=H,exports.decodeUnwrappedFinalized=Ee,exports.decodeUnwrappedStarted=Oe,exports.decodeWrapped=V,exports.delegateForUserDecryptionContract=n.a,exports.finalizeUnwrapContract=i.m,exports.findDelegatedForUserDecryption=Ie,exports.findRevokedDelegationForUserDecryption=Le,exports.findUnwrapRequested=je,exports.findWrapped=Me,exports.getConfidentialTokenAddressContract=i.t,exports.getDelegationExpiryContract=n.o,exports.getTokenAddressContract=i.n,exports.getTokenPairContract=i.r,exports.getTokenPairsContract=i.i,exports.getTokenPairsLengthContract=i.a,exports.getTokenPairsSliceContract=i.o,exports.hardhat=o.r,exports.hoodi=o.i,exports.indexedDBStorage=e.s,exports.inferredTotalSupplyContract=i.h,exports.isConfidentialTokenContract=i.d,exports.isConfidentialTokenValidContract=i.s,exports.isConfidentialWrapperContract=i.f,exports.isHandleDelegatedContract=n.s,exports.isOperatorContract=i.S,exports.isZeroHandle=n._,exports.loadPendingUnshield=Ue,exports.loadPendingUnshieldRequest=We,exports.mainnet=o.a,exports.matchAclRevert=_,exports.matchZamaError=t.a,exports.memoryStorage=e.a,exports.nameContract=n.m,exports.rateContract=i.C,exports.resolveChainRelayers=e.n,exports.resolveStorage=e.r,exports.revokeDelegationContract=n.c,exports.savePendingUnshield=He,exports.sepolia=o.o,exports.setOperatorContract=i.w,exports.supportsInterfaceContract=i.p,exports.symbolContract=n.h,exports.totalSupplyContract=i.T,exports.underlyingContract=i.g,exports.unwrapContract=i.E,exports.unwrapFromBalanceContract=i.D,exports.web=me,exports.wrapContract=i._;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./encryption.cjs`),r=require(`./signer.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./indexeddb-storage.cjs`),o=require(`./build.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`),l=require(`./wrappers-registry.cjs`);let u=require(`viem`);var d=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},f=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},p=class extends e.r{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.i.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},m=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},h=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},g=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},_=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function ee(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 v={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.x(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.O(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.S(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.T(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.E(`Cannot revoke: no active delegation exists.`,{cause:e})};function y(e){let t=e instanceof Error?e:void 0,n=ee(e);if(n&&n in v)return v[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(v))if(r.includes(e))return n(t);return null}function te(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function b(e){return e.startsWith(`0x`)?e:`0x${e}`}function ne(e){return o.t(e.signer,e.provider,e)}var x=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,u.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,u.getAddress)(e)}:${(0,u.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},re=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 b(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 S(e){s.o(e,`Stored credentials`),s.s(e.publicKey,`credentials.publicKey`),s.t(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)s.r(typeof t==`string`&&(0,u.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);s.o(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),s.s(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),s.s(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),s.r(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),s.r(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function ie(e){S(e);let t=e;s.r(typeof t.delegatorAddress==`string`&&(0,u.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),s.r(typeof t.delegateAddress==`string`&&(0,u.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),s.r(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),s.r(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function C(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function w(e,t){let n=new Set(t.map(e=>(0,u.getAddress)(e))),r=new Set(e.map(e=>(0,u.getAddress)(e)));return n.isSubsetOf(r)}function T(e,t){return C(e)?w(e.contractAddresses,t):!1}function E(e){return[...new Set(e.map(e=>(0,u.getAddress)(e)))].toSorted()}async function ae(...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 oe=class{#e;constructor(e){this.#e=e}#t(e){s.o(e,`Session entry`),s.s(e.signature,`session.signature`),s.r(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),s.r(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}},D=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 oe(e.sessionStorage),this.crypto=new re,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.r.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(T(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(C(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(C(e)){if(w(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:s.u(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!T(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.r.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),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:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.r.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.r)throw n;return t.P(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(w(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(w(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=E([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:s.u(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:s.u(e)})}}};function se(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var O=class e extends D{#e;#t=null;#n=null;static async computeStoreKey(e,t){return ae((0,u.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,se(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof o.i&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=E(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=E(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){S(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,u.getAddress)(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}},k=class e extends D{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return ae((0,u.getAddress)(e),(0,u.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,u.getAddress)(e),r=E(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,u.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,u.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,u.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,u.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){ie(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${(0,u.getAddress)(n)}:${(0,u.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}};function A(e){return(0,u.keccak256)((0,u.toBytes)(e))}const j={ConfidentialTransfer:A(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:A(`Wrapped(address,uint256)`),UnwrapRequested:A(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:A(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:A(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:A(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:A(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:A(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function M(e){return(0,u.getAddress)(b(e.slice(-40)))}function N(e){return BigInt(e)}function P(e){return e}function F(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function I(e,t){return(0,u.getAddress)(b(F(e,t).slice(-40)))}function L(e,t){return BigInt(`0x`+F(e,t))}function ce(e,t){return BigInt(`0x`+F(e,t))!==0n}function R(e,t){return b(F(e,t))}function z(e){return e.topics[0]!==j.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:M(e.topics[1]),to:M(e.topics[2]),encryptedAmountHandle:P(e.topics[3])}}function B(e){return e.topics[0]!==j.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:M(e.topics[1]),amountIn:L(e.data,0)}}function V(e){return e.topics[0]===j.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:M(e.topics[1]),unwrapRequestId:P(e.topics[2]),encryptedAmount:R(e.data,0)}:e.topics[0]===j.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:M(e.topics[1]),encryptedAmount:R(e.data,0)}:null}function H(e){return e.topics[0]===j.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:M(e.topics[1]),unwrapRequestId:P(e.topics[2]),encryptedAmount:R(e.data,0),cleartextAmount:L(e.data,1)}:e.topics[0]===j.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:M(e.topics[1]),encryptedAmount:R(e.data,0),cleartextAmount:L(e.data,1)}:null}function le(e){let t=H(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ue(e){if(e.topics[0]!==j.UnwrapFinalizedLegacy)return null;let t=H(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function U(e){return e.topics[0]!==j.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:N(e.topics[1]),txId:N(e.topics[2]),to:M(e.topics[3]),returnVal:ce(e.data,0),refund:I(e.data,1),requestedAmount:R(e.data,2),burnAmount:R(e.data,3)}}function W(e){return z(e)??B(e)??V(e)??ue(e)??H(e)??U(e)}function de(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function fe(e){for(let t of e){let e=V(t);if(e)return e}return null}function pe(e){for(let t of e){let e=B(t);if(e)return e}return null}const me=[j.ConfidentialTransfer,j.Wrapped,j.UnwrapRequested,j.UnwrapRequestedLegacy,j.UnwrapFinalized,j.UnwrapFinalizedLegacy,j.UnwrappedStarted],G={DelegatedForUserDecryption:A(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:A(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function K(e){return e.topics[0]!==G.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:I(e.data,0),delegationCounter:L(e.data,1),oldExpirationDate:L(e.data,2),newExpirationDate:L(e.data,3)}}function q(e){return e.topics[0]!==G.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:I(e.data,0),delegationCounter:L(e.data,1),oldExpirationDate:L(e.data,2)}}function he(e){return K(e)??q(e)}function ge(e){let t=[];for(let n of e){let e=he(n);e&&t.push(e)}return t}function _e(e){for(let t of e){let e=K(t);if(e)return e}return null}function ve(e){for(let t of e){let e=q(t);if(e)return e}return null}const ye=[G.DelegatedForUserDecryption,G.RevokedDelegationForUserDecryption];var be=class r extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,u.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(l.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(r,i,a){let o=this.sdk.requireSigner(`confidentialTransfer`);await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:d,onTransferSubmitted:p}=a??{},m=(0,u.getAddress)(r);c||await this.#i(i);let h,g,_=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:h,inputProof:g}=await this.sdk.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await o.getAddress()}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-_}),J(()=>d?.())}catch(r){throw this.emit({type:t.r.EncryptError,error:s.u(r),durationMs:Date.now()-_}),r instanceof e.r?r:new n.n(`Failed to encrypt transfer amount`,{cause:r})}if(h.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await o.writeContract(l.b(this.address,m,h[0],g));return this.emit({type:t.r.TransferSubmitted,txHash:e}),J(()=>p?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:s.u(n)}),n instanceof e.r?n:new f(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(r,i,a,o){let c=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,u.getAddress)(r),p=(0,u.getAddress)(i),m,h,g=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:m,inputProof:h}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-g}),J(()=>o?.onEncryptComplete?.())}catch(r){throw this.emit({type:t.r.EncryptError,error:s.u(r),durationMs:Date.now()-g}),r instanceof e.r?r:new n.n(`Failed to encrypt transferFrom amount`,{cause:r})}if(m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(l.x(this.address,d,p,m[0],h));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),J(()=>o?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:s.u(n)}),n instanceof e.r?n:new f(`TransferFrom transaction failed`,{cause:n})}}async approve(n,r){let i=this.sdk.requireSigner(`approve`);await this.sdk.requireChainAlignment(`approve`);let a=(0,u.getAddress)(n);try{let e=await i.writeContract(l.w(this.address,a,r));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:s.u(n)}),n instanceof e.r?n:new d(`Operator approval failed`,{cause:n})}}async isApproved(e,t){return this.sdk.provider.readContract(l.S(this.address,(0,u.getAddress)(t),(0,u.getAddress)(e)))}async shield(n,r){let i=this.sdk.requireSigner(`shield`);await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await i.getAddress();o=await this.sdk.provider.readContract(t.d(a,e))}catch(t){throw t instanceof e.r?t:new _(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:s.u(t)})}if(o<n)throw new h(`Insufficient ERC-20 balance: requested ${n}, available ${o} (token: ${a})`,{requested:n,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(n,c===`max`,r);try{let e=r?.to?(0,u.getAddress)(r.to):await i.getAddress(),a=await i.writeContract(l._(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:a}),J(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:s.u(n)}),n instanceof e.r?n:new f(`Shield transaction failed`,{cause:n})}}async unwrap(r){let i=this.sdk.requireSigner(`unwrap`);await this.sdk.requireChainAlignment(`unwrap`);let a=await i.getAddress(),o,c,u=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:o,inputProof:c}=await this.sdk.relayer.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-u})}catch(r){throw this.emit({type:t.r.EncryptError,error:s.u(r),durationMs:Date.now()-u}),r instanceof e.r?r:new n.n(`Failed to encrypt unshield amount`,{cause:r})}if(o.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await i.writeContract(l.E(this.address,a,a,o[0],c));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`);await this.sdk.requireChainAlignment(`unwrapAll`);let i=await r.getAddress(),a=await this.readConfidentialBalanceOf(i);if(t._(a))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(l.D(this.address,i,i,a));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return J(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return J(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];s.n(a,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(l.m(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`);await this.sdk.requireChainAlignment(`approveUnderlying`);let i=await this.#n(),a=n??2n**256n-1n;try{if(a>0n){let e=await r.getAddress();await this.sdk.provider.readContract(t.l(i,e,this.wrapper))>0n&&await r.writeContract(t.u(i,this.wrapper,0n))}let e=await r.writeContract(t.u(i,this.wrapper,a));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:s.u(n)}),n instanceof e.r?n:new d(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`);if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new t.C(`Expiration date must be at least 1 hour in the future`);let a=(0,u.getAddress)(n),o=await i.getAddress();if(a===(0,u.getAddress)(o))throw new t.O(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.S(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,d;try{d=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:a})}catch{d=-1n}if(d===l)throw new t.T(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=this.sdk.requireSigner(`revokeDelegation`);await this.sdk.requireChainAlignment(`revokeDelegation`);let i=(0,u.getAddress)(n),a=await r.getAddress(),o=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:i})}catch{c=1n}if(c===0n)throw new t.E(`No active delegation found for delegate ${i} on contract ${this.address}.`);try{let e=await r.writeContract(t.c(o,i,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.r?i.set(t[a].address,n):i.set(t[a].address,new f(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{let e=this.sdk.requireSigner(`assertConfidentialBalance`);n=await this.balanceOf(await e.getAddress())}catch(t){throw t instanceof e.r?t:new g(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new m(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new f(`Failed to get unshield receipt`,{cause:t})}let o=fe(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),J(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),J(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(n,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#n(),s=await a.getAddress(),c=await this.sdk.provider.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{if(c>0n){let e=await a.writeContract(t.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,s=await a.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:s}),J(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(t){throw t instanceof e.r?t:new d(`ERC-20 approval failed`,{cause:t})}}};function J(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const xe={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},xe,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,u.getAddress)(n)}async listPairs(t={}){let n=t.page??1,r=t.pageSize??100,i=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(r<1)throw new e.t(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(l.a(a));s=this.#i(o,Number(e))}let c=BigInt((n-1)*r),u=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:n,pageSize:r};let d=`slice:${a}:${c}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(l.o(a,c,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:s,page:n,pageSize:r};let p=`metadata:${a}:${c}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:s,page:n,pageSize:r}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.m(e.tokenAddress)),this.provider.readContract(t.h(e.tokenAddress)),this.provider.readContract(t.f(e.tokenAddress)),this.provider.readContract(t.p(e.tokenAddress)),this.provider.readContract(t.m(e.confidentialTokenAddress)),this.provider.readContract(t.h(e.confidentialTokenAddress)),this.provider.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.t(t,n));return o===u.zeroAddress?this.#i(r,null,Y):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.n(t,n));return o===u.zeroAddress?this.#i(r,null,Y):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(l.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(l.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(l.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.t(t,(0,u.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.n(t,(0,u.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.s(t,(0,u.getAddress)(e)))}};const Z=365*86400;async function Q(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var Se=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 o.i,this.cache=new x(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 X({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n=(()=>{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})();if(e.signer){let t={relayer:this.relayer,signer:e.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:n,sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new O(t),this.delegatedCredentials=new k(t),this.#r=e.signer.subscribe?.(e=>{this.#i(e)})}else this.credentials=void 0,this.delegatedCredentials=void 0}requireSigner(e){if(!this.signer)throw new r.t(e);return this.signer}requireCredentials(e){if(!this.credentials)throw new r.t(e);return this.credentials}requireDelegatedCredentials(e){if(!this.delegatedCredentials)throw new r.t(e);return this.delegatedCredentials}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let t=this.requireSigner(e),[n,r]=await Promise.all([t.getChainId(),this.provider.getChainId()]);if(n!==r)throw new p({operation:e,signerChainId:n,providerChainId:r});return n}async#i(e){let t=this.credentials;if(e.previous&&t){let n=e.previous;await Q(`revoke previous identity`,()=>t.revokeFor(n)),await Q(`clear decrypt cache`,()=>this.cache.clearForRequester(n.address))}let n=e.next?.chainId;if(n!==void 0)try{this.relayer.switchChain(n)}catch(e){console.warn(`[zama-sdk] switch relayer chain failed:`,e);return}await Promise.all(Array.from(this.#n,t=>Q(`identity listener`,()=>t(e))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new be(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.requireCredentials(`allow`).allow(...e)}async userDecrypt(e){let n=this.requireSigner(`userDecrypt`),r=this.requireCredentials(`userDecrypt`);if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let i=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},o=[];for(let e of i)t._(e.handle)?a[e.handle]=0n:o.push(e);if(o.length===0)return a;let c=await n.getAddress(),l=[];for(let e of o){let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?l.push(e):a[e.handle]=t}if(l.length===0)return a;let d=await r.allow(...new Set(i.map(e=>e.contractAddress))),f=new Map;for(let e of l){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=l.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:m}),await t.n([...f.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:d.contractAddresses,privateKey:d.privateKey,publicKey:d.publicKey,signature:d.signature,signerAddress:c,startTimestamp:d.startTimestamp,durationDays:d.durationDays});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),a}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-p,handles:m}),t.v(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.v(e,`Public decryption failed`)}}async revokeSession(){let e=this.requireSigner(`revokeSession`),t=this.requireCredentials(`revokeSession`),n=await e.getAddress(),r=await e.getChainId();try{await t.revokeFor({address:n,chainId:r})}finally{await this.cache.clearForRequester(n)}}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 Ce(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 we(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 Te(e,t){return(await Ee(e,t))?.unwrapTxHash??null}async function Ee(e,t){return Ce(await e.get($(t)))}async function De(e,t){await e.delete($(t))}var Oe=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 ke=new Oe;exports.ACL_TOPICS=ye,exports.AclPausedError=t.y,exports.AclTopics=G,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=g,exports.ChainMismatchError=p,exports.ChromeSessionStorage=Oe,exports.ConfigurationError=e.t,exports.CredentialsManager=O,exports.DecryptCache=x,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=xe,exports.DelegatedCredentialsManager=k,exports.DelegationContractIsSelfError=t.b,exports.DelegationCooldownError=t.x,exports.DelegationDelegateEqualsContractError=t.S,exports.DelegationExpirationTooSoonError=t.C,exports.DelegationExpiredError=t.w,exports.DelegationExpiryUnchangedError=t.T,exports.DelegationNotFoundError=t.E,exports.DelegationNotPropagatedError=t.D,exports.DelegationSelfNotAllowedError=t.O,exports.ERC20ReadFailedError=_,exports.ERC7984_INTERFACE_ID=l.c,exports.ERC7984_WRAPPER_INTERFACE_ID=l.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=l.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=a.t,exports.InsufficientConfidentialBalanceError=m,exports.InsufficientERC20BalanceError=h,exports.InvalidKeypairError=t.k,exports.KeypairExpiredError=t.A,exports.MemoryStorage=o.i,exports.NoCiphertextError=t.j,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerRequiredError=r.t,exports.SigningFailedError=t.M,exports.SigningRejectedError=t.N,exports.TOKEN_TOPICS=me,exports.Token=be,exports.Topics=j,exports.TransactionRevertedError=f,exports.WrappersRegistry=X,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Se,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.anvil=c.t,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.buildZamaConfig=o.t,exports.chains=c.n,exports.chromeSessionStorage=ke,exports.clearPendingUnshield=De,exports.cleartext=te,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=ne,exports.decimalsContract=t.f,exports.decodeAclEvent=he,exports.decodeAclEvents=ge,exports.decodeConfidentialTransfer=z,exports.decodeDelegatedForUserDecryption=K,exports.decodeOnChainEvent=W,exports.decodeOnChainEvents=de,exports.decodeRevokedDelegationForUserDecryption=q,exports.decodeUnwrapFinalized=H,exports.decodeUnwrapRequested=V,exports.decodeUnwrappedFinalized=le,exports.decodeUnwrappedStarted=U,exports.decodeWrapped=B,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=_e,exports.findRevokedDelegationForUserDecryption=ve,exports.findUnwrapRequested=fe,exports.findWrapped=pe,exports.getConfidentialTokenAddressContract=l.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=l.n,exports.getTokenPairContract=l.r,exports.getTokenPairsContract=l.i,exports.getTokenPairsLengthContract=l.a,exports.getTokenPairsSliceContract=l.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=a.n,exports.inferredTotalSupplyContract=l.h,exports.isConfidentialTokenContract=l.d,exports.isConfidentialTokenValidContract=l.s,exports.isConfidentialWrapperContract=l.f,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=l.S,exports.isZeroHandle=t._,exports.loadPendingUnshield=Te,exports.loadPendingUnshieldRequest=Ee,exports.mainnet=c.a,exports.matchAclRevert=y,exports.matchZamaError=e.a,exports.memoryStorage=o.a,exports.nameContract=t.m,exports.rateContract=l.C,exports.resolveChainRelayers=o.n,exports.resolveStorage=o.r,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=we,exports.sepolia=c.o,exports.setOperatorContract=l.w,exports.supportsInterfaceContract=l.p,exports.symbolContract=t.h,exports.totalSupplyContract=l.T,exports.underlyingContract=l.g,exports.unwrapContract=l.E,exports.unwrapFromBalanceContract=l.D,exports.wrapContract=l._;
|
|
515
2
|
//# sourceMappingURL=index.cjs.map
|