@zama-fhe/sdk 3.0.0-alpha.26 → 3.0.0-alpha.27

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.
@@ -1,2 +1,2 @@
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`}},ee=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function te(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 _={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 v(e){let t=e instanceof Error?e:void 0,n=te(e);if(n&&n in _)return _[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(_))if(r.includes(e))return n(t);return null}function ne(){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 y(e){return e.startsWith(`0x`)?e:`0x${e}`}function re(e){return o.t(e.signer,e.provider,e)}var ie=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))}},ae=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 y(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 oe(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 se(e){oe(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 b(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function x(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 S(e,t){return b(e)?x(e.contractAddresses,t):!1}function C(e){return[...new Set(e.map(e=>(0,u.getAddress)(e)))].toSorted()}async function w(...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 ce=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}},T=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 ce(e.sessionStorage),this.crypto=new ae,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(S(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(b(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(b(e)){if(x(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),!S(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),S(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(x(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(x(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=C([...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 le(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 E=class e extends T{#e;#t=null;#n=null;static async computeStoreKey(e,t){return w((0,u.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,le(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=C(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=C(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){oe(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}},ue=class e extends T{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return w((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=C(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){se(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 D(e){return(0,u.keccak256)((0,u.toBytes)(e))}const O={ConfidentialTransfer:D(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:D(`Wrapped(address,uint256)`),UnwrapRequested:D(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:D(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:D(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:D(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:D(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:D(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function k(e){return(0,u.getAddress)(y(e.slice(-40)))}function de(e){return BigInt(e)}function A(e){return e}function j(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function M(e,t){return(0,u.getAddress)(y(j(e,t).slice(-40)))}function N(e,t){return BigInt(`0x`+j(e,t))}function fe(e,t){return BigInt(`0x`+j(e,t))!==0n}function P(e,t){return y(j(e,t))}function F(e){return e.topics[0]!==O.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:k(e.topics[1]),to:k(e.topics[2]),encryptedAmountHandle:A(e.topics[3])}}function I(e){return e.topics[0]!==O.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:k(e.topics[1]),amountIn:N(e.data,0)}}function L(e){return e.topics[0]===O.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:k(e.topics[1]),unwrapRequestId:A(e.topics[2]),encryptedAmount:P(e.data,0)}:e.topics[0]===O.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:k(e.topics[1]),encryptedAmount:P(e.data,0)}:null}function R(e){return e.topics[0]===O.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:k(e.topics[1]),unwrapRequestId:A(e.topics[2]),encryptedAmount:P(e.data,0),cleartextAmount:N(e.data,1)}:e.topics[0]===O.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:k(e.topics[1]),encryptedAmount:P(e.data,0),cleartextAmount:N(e.data,1)}:null}function pe(e){let t=R(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function me(e){if(e.topics[0]!==O.UnwrapFinalizedLegacy)return null;let t=R(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function z(e){return e.topics[0]!==O.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:de(e.topics[1]),txId:de(e.topics[2]),to:k(e.topics[3]),returnVal:fe(e.data,0),refund:M(e.data,1),requestedAmount:P(e.data,2),burnAmount:P(e.data,3)}}function B(e){return F(e)??I(e)??L(e)??me(e)??R(e)??z(e)}function he(e){let t=[];for(let n of e){let e=B(n);e&&t.push(e)}return t}function V(e){for(let t of e){let e=L(t);if(e)return e}return null}function ge(e){for(let t of e){let e=I(t);if(e)return e}return null}const _e=[O.ConfidentialTransfer,O.Wrapped,O.UnwrapRequested,O.UnwrapRequestedLegacy,O.UnwrapFinalized,O.UnwrapFinalizedLegacy,O.UnwrappedStarted],H={DelegatedForUserDecryption:D(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:D(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function U(e){return e.topics[0]!==H.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:k(e.topics[1]),delegate:k(e.topics[2]),contractAddress:M(e.data,0),delegationCounter:N(e.data,1),oldExpirationDate:N(e.data,2),newExpirationDate:N(e.data,3)}}function W(e){return e.topics[0]!==H.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:k(e.topics[1]),delegate:k(e.topics[2]),contractAddress:M(e.data,0),delegationCounter:N(e.data,1),oldExpirationDate:N(e.data,2)}}function G(e){return U(e)??W(e)}function ve(e){let t=[];for(let n of e){let e=G(n);e&&t.push(e)}return t}function ye(e){for(let t of e){let e=U(t);if(e)return e}return null}function be(e){for(let t of e){let e=W(t);if(e)return e}return null}const xe=[H.DelegatedForUserDecryption,H.RevokedDelegationForUserDecryption];var Se=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{handles:h,inputProof:g}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await o.getAddress()});if(K(()=>d?.()),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}),K(()=>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),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if(K(()=>o?.onEncryptComplete?.()),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}),K(()=>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 ee(`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}),K(()=>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(),{handles:o,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});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 K(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return K(()=>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:v(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:v(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=V(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),K(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),K(()=>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}),K(()=>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 K(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const q={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},J=300*1e3;var Y=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},q,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?J: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,J):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,J):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 X=365*86400;async function Z(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var Ce=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 ie(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 Y({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>X?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${X}s); capping to ${X}s.`),X):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 E(t),this.delegatedCredentials=new ue(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 Z(`revoke previous identity`,()=>t.revokeFor(n)),await Z(`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=>Z(`identity listener`,()=>t(e))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new Se(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 Y({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 encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:s.u(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}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 Q(e){return`zama:pending-unshield:${e}`}function we(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 Te(e,t,n,r){if(r===void 0){await e.set(Q(t),n);return}await e.set(Q(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ee(e,t){return(await De(e,t))?.unwrapTxHash??null}async function De(e,t){return we(await e.get(Q(t)))}async function Oe(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const ke=new $;exports.ACL_TOPICS=xe,exports.AclPausedError=t.y,exports.AclTopics=H,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=g,exports.ChainMismatchError=p,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=E,exports.DecryptCache=ie,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=q,exports.DelegatedCredentialsManager=ue,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=ee,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=_e,exports.Token=Se,exports.Topics=O,exports.TransactionRevertedError=f,exports.WrappersRegistry=Y,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Ce,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=Oe,exports.cleartext=ne,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=re,exports.decimalsContract=t.f,exports.decodeAclEvent=G,exports.decodeAclEvents=ve,exports.decodeConfidentialTransfer=F,exports.decodeDelegatedForUserDecryption=U,exports.decodeOnChainEvent=B,exports.decodeOnChainEvents=he,exports.decodeRevokedDelegationForUserDecryption=W,exports.decodeUnwrapFinalized=R,exports.decodeUnwrapRequested=L,exports.decodeUnwrappedFinalized=pe,exports.decodeUnwrappedStarted=z,exports.decodeWrapped=I,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=ye,exports.findRevokedDelegationForUserDecryption=be,exports.findUnwrapRequested=V,exports.findWrapped=ge,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=Ee,exports.loadPendingUnshieldRequest=De,exports.mainnet=c.a,exports.matchAclRevert=v,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=Te,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._;
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{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=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}},ee=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}},te=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}},ne=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 re(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.b(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.T(`Cannot revoke: no active delegation exists.`,{cause:e})};function y(e){let t=e instanceof Error?e:void 0,n=re(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 b(r,i,a=!1){if(r instanceof n.t||r instanceof h||r instanceof e.n||r instanceof t.E||r instanceof t.k||r instanceof t.O)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new h(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new t.E(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ie(){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 x(e){return e.startsWith(`0x`)?e:`0x${e}`}function ae(e){return o.t(e.signer,e.provider,e)}var S=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))}},oe=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 x(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 C(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 se(e){C(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 w(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function T(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 E(e,t){return w(e)?T(e.contractAddresses,t):!1}function D(e){return[...new Set(e.map(e=>(0,u.getAddress)(e)))].toSorted()}async function O(...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 ce=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}},le=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 ce(e.sessionStorage),this.crypto=new oe,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(E(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(w(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(w(e)){if(T(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),!E(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),E(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.A(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(T(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(T(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=D([...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 ue(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 de=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t){return O((0,u.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ue(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=D(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=D(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){C(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}},fe=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return O((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=D(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){se(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 k(e){return(0,u.keccak256)((0,u.toBytes)(e))}const A={ConfidentialTransfer:k(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:k(`Wrapped(address,uint256)`),UnwrapRequested:k(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:k(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:k(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:k(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function j(e){return(0,u.getAddress)(x(e.slice(-40)))}function pe(e){return BigInt(e)}function M(e){return e}function N(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function P(e,t){return(0,u.getAddress)(x(N(e,t).slice(-40)))}function F(e,t){return BigInt(`0x`+N(e,t))}function me(e,t){return BigInt(`0x`+N(e,t))!==0n}function I(e,t){return x(N(e,t))}function L(e){return e.topics[0]!==A.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:j(e.topics[1]),to:j(e.topics[2]),encryptedAmountHandle:M(e.topics[3])}}function R(e){return e.topics[0]!==A.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:j(e.topics[1]),amountIn:F(e.data,0)}}function z(e){return e.topics[0]===A.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0)}:e.topics[0]===A.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0)}:null}function B(e){return e.topics[0]===A.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:e.topics[0]===A.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:null}function he(e){let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ge(e){if(e.topics[0]!==A.UnwrapFinalizedLegacy)return null;let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function V(e){return e.topics[0]!==A.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:pe(e.topics[1]),txId:pe(e.topics[2]),to:j(e.topics[3]),returnVal:me(e.data,0),refund:P(e.data,1),requestedAmount:I(e.data,2),burnAmount:I(e.data,3)}}function H(e){return L(e)??R(e)??z(e)??ge(e)??B(e)??V(e)}function _e(e){let t=[];for(let n of e){let e=H(n);e&&t.push(e)}return t}function U(e){for(let t of e){let e=z(t);if(e)return e}return null}function ve(e){for(let t of e){let e=R(t);if(e)return e}return null}const ye=[A.ConfidentialTransfer,A.Wrapped,A.UnwrapRequested,A.UnwrapRequestedLegacy,A.UnwrapFinalized,A.UnwrapFinalizedLegacy,A.UnwrappedStarted],W={DelegatedForUserDecryption:k(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:k(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function be(e){return G(e)??K(e)}function xe(e){let t=[];for(let n of e){let e=be(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=G(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=K(t);if(e)return e}return null}const we=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var Te=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{handles:h,inputProof:g}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await o.getAddress()});if(q(()=>d?.()),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}),q(()=>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),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if(q(()=>o?.onEncryptComplete?.()),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}),q(()=>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 te(`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}),q(()=>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(),{handles:o,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});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 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(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.S(`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.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.x(`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.w(`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.T(`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 ne(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new ee(`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=U(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>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}),q(()=>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 q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ee={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},J=300*1e3;var Y=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},Ee,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?J: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,J):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,J):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 X=365*86400;async function Z(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var De=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 S(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 Y({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>X?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${X}s); capping to ${X}s.`),X):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 de(t),this.delegatedCredentials=new fe(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 g({operation:e,signerChainId:n,providerChainId:r});return n}async#i(e){let t=this.credentials;if(e.previous&&t){let n=e.previous;await Z(`revoke previous identity`,()=>t.revokeFor(n)),await Z(`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=>Z(`identity listener`,()=>t(e))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new Te(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 Y({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}),b(e,`Failed to decrypt handles`)}}async delegatedUserDecrypt(e,n,r=n){this.requireSigner(`delegatedUserDecrypt`);let i=this.requireDelegatedCredentials(`delegatedUserDecrypt`);if(await this.requireChainAlignment(`delegatedUserDecrypt`),e.length===0)return{};let a=(0,u.getAddress)(n),o=(0,u.getAddress)(r),c=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),l={},d=[];for(let e of c)t._(e.handle)?l[e.handle]=0n:d.push(e);if(d.length===0)return l;let f=[];for(let e of d){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?f.push(e):l[e.handle]=t}if(f.length===0)return l;let p=await i.allow(a,...new Set(c.map(e=>e.contractAddress))),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.handle):m.set(e.contractAddress,[e.handle])}let h=Date.now(),g=f.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:g}),await t.n([...m.entries()].map(([e,t])=>async()=>{let n=await this.relayer.delegatedUserDecrypt({handles:t,contractAddress:e,signedContractAddresses:p.contractAddresses,privateKey:p.privateKey,publicKey:p.publicKey,signature:p.signature,delegatorAddress:p.delegatorAddress,delegateAddress:p.delegateAddress,startTimestamp:p.startTimestamp,durationDays:p.durationDays});for(let[t,r]of Object.entries(n))l[t]=r,await this.cache.set(o,e,t,r)}),5);let e={};for(let t of g){let n=l[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-h,handles:g,result:e}),l}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-h,handles:g}),b(e,`Failed to decrypt delegated handles`,!0)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw b(e,`Public decryption failed`)}}async encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:s.u(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}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 Q(e){return`zama:pending-unshield:${e}`}function Oe(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 ke(e,t,n,r){if(r===void 0){await e.set(Q(t),n);return}await e.set(Q(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ae(e,t){return(await je(e,t))?.unwrapTxHash??null}async function je(e,t){return Oe(await e.get(Q(t)))}async function Me(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Ne=new $;exports.ACL_TOPICS=we,exports.AclPausedError=t.v,exports.AclTopics=W,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=ne,exports.ChainMismatchError=g,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=de,exports.DecryptCache=S,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=Ee,exports.DelegatedCredentialsManager=fe,exports.DelegationContractIsSelfError=t.y,exports.DelegationCooldownError=t.b,exports.DelegationDelegateEqualsContractError=t.x,exports.DelegationExpirationTooSoonError=t.S,exports.DelegationExpiredError=t.C,exports.DelegationExpiryUnchangedError=t.w,exports.DelegationNotFoundError=t.T,exports.DelegationNotPropagatedError=t.E,exports.DelegationSelfNotAllowedError=t.D,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=ee,exports.InsufficientERC20BalanceError=te,exports.InvalidKeypairError=m,exports.KeypairExpiredError=p,exports.MemoryStorage=o.i,exports.NoCiphertextError=h,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerRequiredError=r.t,exports.SigningFailedError=t.O,exports.SigningRejectedError=t.k,exports.TOKEN_TOPICS=ye,exports.Token=Te,exports.Topics=A,exports.TransactionRevertedError=f,exports.WrappersRegistry=Y,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=De,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=Ne,exports.clearPendingUnshield=Me,exports.cleartext=ie,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=ae,exports.decimalsContract=t.f,exports.decodeAclEvent=be,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=L,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=H,exports.decodeOnChainEvents=_e,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=B,exports.decodeUnwrapRequested=z,exports.decodeUnwrappedFinalized=he,exports.decodeUnwrappedStarted=V,exports.decodeWrapped=R,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=U,exports.findWrapped=ve,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=Ae,exports.loadPendingUnshieldRequest=je,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=ke,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._;
2
2
  //# sourceMappingURL=index.cjs.map