@zama-fhe/sdk 3.1.0-alpha.7 → 3.1.0-alpha.9

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("./wrappers-registry.cjs"),n=require("./encryption.cjs"),r=require("./token.cjs"),i=require("./relayer-cleartext.cjs"),a=require("./base-signer.cjs"),o=require("./validation.cjs"),s=require("./assertions.cjs"),c=require("./chains.cjs");let l=require("viem"),u=require("zod/mini");var d=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},f=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},p=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},x=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},C=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function w(r,i,a=!1){if(r instanceof n.t||r instanceof p||r instanceof e.n||r instanceof C||r instanceof t.H||r instanceof t.V)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new p(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new C(`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 ee(){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 T(e){return e.startsWith(`0x`)?e:`0x${e}`}const te=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function E(e,t,n,r=`0x`){return{address:e,abi:te,functionName:`transferAndCall`,args:[t,n,r]}}function ne(e){return a.i(e.signer,e.provider,e)}var D=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return t.B(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await r.s(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t){let i=this.#i(`delegatedDecryptValues`),a=await r.s(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedUserDecrypt(e,t,a.address,n)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw w(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await r.s(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:i})}},O=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.B(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.s(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.s(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},k=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService}#i(e){return t.B(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#i(`grantPermit`);await r.c(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#i(`grantDelegationPermit`);await r.c(`grantDelegationPermit`,this.#e,this.#t),await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmKeypair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmKeypair(t.address)}async revokePermits(e){let n=this.#i(`revokePermits`),i=(0,l.getAddress)((await r.s(`revokePermits`,this.#e,this.#t)).address);try{await n.revokePermits(e)}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(i))}}async clear(){let e=this.#i(`clear`),n=(0,l.getAddress)((await r.s(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n))}}};const re=u.z.union([u.z.bigint(),u.z.boolean(),a.p]),ie=u.z.array(u.z.string());var ae=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.#s(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=re.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return console.warn(`[zama-sdk] CachingService.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#s(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#l(i).catch(e=>{console.warn(`[zama-sdk] CachingService index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] CachingService.set failed:`,e)}}async delete(e,t,n){let r=this.#s(e,t,n);this.#r=this.#r.then(()=>this.#i(r).catch(e=>{console.warn(`[zama-sdk] CachingService.delete failed:`,e)})),await this.#r}async clearForRequester(e){this.#r=this.#r.then(()=>this.#a(e).catch(e=>{console.warn(`[zama-sdk] CachingService.clearForRequester failed:`,e)})),await this.#r}async clearAll(){this.#r=this.#r.then(()=>this.#o().catch(e=>{console.warn(`[zama-sdk] CachingService.clearAll failed:`,e)})),await this.#r}async#i(e){await this.#e.delete(e).catch(()=>{});let t=await this.#c(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#n,n)}async#a(e){let t=(0,l.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#c(),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#o(){let e=await this.#c();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#s(e,t,n){return`${this.#t}:${(0,l.getAddress)(e)}:${(0,l.getAddress)(t)}:${n.toLowerCase()}`}async#c(){let e=await this.#e.get(this.#n);if(e===null)return[];let t=ie.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#n).catch(()=>{}),[])}async#l(e){let t=await this.#c();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}};function oe(e,t){let r=j(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return A(e,r)}function se(e,t){let r=j(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...A(e,r),delegatorAddress:r.delegatorAddress}}function A(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function j(e,t){let n=a.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}var ce=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=(0,l.getAddress)(t);return this.#a(e,{requesterAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...oe(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r){let i=(0,l.getAddress)(t),a=(0,l.getAddress)(n);return this.#a(e,{requesterAddress:(0,l.getAddress)(r),resolveCredentials:e=>this.#t.grantPermit(e,i),validate:e=>this.#l(e,{delegatorAddress:i,delegateAddress:a}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...se(e,t),delegateAddress:a}),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0})}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)}));if(o.length===0)return{items:o};let s=(0,l.getAddress)(i);try{let e=await this.delegatedUserDecrypt(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s);for(let t of o)this.#o(t,e);return{items:o}}catch(e){if(r.m(e))throw e;if(o.length===1){let[t=this.#c()]=o;return t.error=this.#s(e,`Failed to decrypt delegated encrypted values`,!0),{items:o}}}return await r.a(o.map(e=>async()=>{try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s);this.#o(e,r)}catch(t){if(r.m(t))throw t;e.error=this.#s(t,`Failed to decrypt delegated encrypted values`,!0)}}),a),{items:o}}async#a(e,t){if(e.length===0)return{};let n=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)})),i={},a=[];for(let e of n)r.i(e.encryptedValue)?i[e.encryptedValue]=0n:a.push(e);if(a.length===0)return i;let o=Array.from(new Set(n.map(e=>e.contractAddress))),c=Array.from(new Set(a.map(e=>e.contractAddress)));t.validate&&await t.validate(c);let u=[];for(let e of a){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):i[e.encryptedValue]=n}if(u.length===0)return i;let d=await t.resolveCredentials(o),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let p=Date.now(),m=u.map(e=>e.encryptedValue);try{this.#i({type:r.o.DecryptStart,encryptedValues:m}),await r.a([...f.entries()].map(([e,n])=>async()=>{let r=await t.decryptContract({credentials:d,contractAddress:e,encryptedValues:n});for(let[n,a]of Object.entries(r))i[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of m){let n=i[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.o.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),i}catch(e){throw this.#i({type:r.o.DecryptError,error:s.s(e),durationMs:Date.now()-p,encryptedValues:m}),w(e,t.errorMessage,t.delegated)}}#o(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#s(t,n,r=!1){return t instanceof e.r?t:w(t,n,r)}#c(){throw new n.t(`Batch delegated decryption invariant failed: missing item`)}async#l(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function le(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 M={AlreadyDelegatedOrRevokedInSameBlock:e=>new h(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new x(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new m(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new y(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new v(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new g(`Cannot revoke: no active delegation exists.`,{cause:e})};function ue(e){return e in M}function de(e,t){let n=le(e);if(n&&ue(n))return M[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(M))if(r.includes(e))return n(t);return null}var fe=class{#e;#t;#n;constructor({provider:e,relayer:t,emitEvent:n=()=>{}}){this.#e=e,this.#t=t,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new S(`Expiration date must be at least 1 hour in the future`);let o=(0,l.getAddress)(t),s=(0,l.getAddress)(n),c=(0,l.getAddress)(i);if(s===c)throw new m(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new y(`Delegate address cannot be the same as the contract address (${o}).`);let u=await this.#t.getAclAddress(),d=a?BigInt(Math.floor(a.getTime()/1e3)):r.l,f;try{f=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] delegateDecryption: pre-flight expiry check failed:`,e),f=-1n}if(f===d)throw new v(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#r({operation:`delegateDecryption`,signer:e,contractAddress:t,config:r.u(u,s,o,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=(0,l.getAddress)(i),c=await this.#t.getAclAddress(),u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){console.warn(`[zama-sdk] revokeDelegation: pre-flight expiry check failed:`,e),u=1n}if(u===0n)throw new g(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#r({operation:`revokeDelegation`,signer:e,contractAddress:t,config:r.p(c,o,a)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===r.l?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=await this.#t.getAclAddress();return this.#e.readContract(r.d(i,(0,l.getAddress)(t),(0,l.getAddress)(n),(0,l.getAddress)(e)))}async#r({operation:e,signer:t,contractAddress:n,config:i}){try{return await r.n({operation:e,signer:t,provider:this.#e,config:i,emit:e=>this.#n(e,n)})}catch(e){throw this.#i(e),e}}#i(e){if(!(e instanceof r.b))return;let t=de(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof g||t instanceof _){let n=(0,l.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let i=(0,l.getAddress)(e),a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new g(`No active delegation from ${a} to ${o} for ${i}`);if(s!==r.l&&s<=await this.#e.getBlockTimestamp())throw new _(`Delegation from ${a} to ${o} for ${i} has expired`)}},pe=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(t){let i=Date.now();try{this.#t({type:r.o.EncryptStart},t.contractAddress);let e=await this.#e.encrypt(t);return this.#t({type:r.o.EncryptEnd,durationMs:Date.now()-i},t.contractAddress),e}catch(a){throw this.#t({type:r.o.EncryptError,error:s.s(a),durationMs:Date.now()-i},t.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}},me=class{#e;#t;#n;#r;#i=new Set;#a;constructor(e){this.#e=e.signer,this.#t=e.relayer,this.#n=e.cachingService,this.#r=e.credentialService,this.#e&&(this.#a=this.#e.walletAccount.subscribe(e=>{this.#o(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})}))}onWalletAccountChange(e){return this.#i.add(e),()=>{this.#i.delete(e)}}dispose(){this.#a?.(),this.#a=void 0,this.#i.clear()}async#o(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.F(`switch relayer chain`,()=>this.#t.switchChain(i));let a=this.#r;a&&await t.F(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r)),n&&await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address)),await Promise.all(Array.from(this.#i,n=>t.F(`wallet account listener`,()=>n(e))))}};function N(e){return(0,l.keccak256)((0,l.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,l.getAddress)(T(e.slice(-40)))}function I(e){return BigInt(e)}function L(e){return e}function R(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function z(e,t){return(0,l.getAddress)(T(R(e,t).slice(-40)))}function B(e,t){return BigInt(`0x`+R(e,t))}function he(e,t){return BigInt(`0x`+R(e,t))!==0n}function V(e,t){return T(R(e,t))}function H(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:L(e.topics[3])}}function U(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:B(e.data,0)}}function W(e){return e.topics[0]!==P.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0)}}function G(e){return e.topics[0]!==P.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0),cleartextAmount:B(e.data,1)}}function K(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:I(e.topics[1]),txId:I(e.topics[2]),to:F(e.topics[3]),returnVal:he(e.data,0),refund:z(e.data,1),requestedAmount:V(e.data,2),burnAmount:V(e.data,3)}}function q(e){return H(e)??U(e)??W(e)??G(e)??K(e)}function ge(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=W(t);if(e)return e}return null}function _e(e){for(let t of e){let e=U(t);if(e)return e}return null}const ve=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapFinalized,P.UnwrappedStarted],Y={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2),newExpirationDate:B(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2)}}function Q(e){return X(e)??Z(e)}function ye(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function be(e){for(let t of e){let e=X(t);if(e)return e}return null}function xe(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Se=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];var Ce=class extends r.t{#e;#t=null;#n=null;#r(e){try{return s.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.I(e,{cause:n})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#o();return this.sdk.provider.readContract(t.h(n,(0,l.getAddress)(e),this.address))}async shield(n,i){let a=await r.s(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#o(),u=(0,l.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t._(c,u))}catch(t){throw t instanceof e.r?t:new r.g(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:s.s(t)})}if(d<n)throw new r.v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${c})`,{requested:n,available:d,token:c});return o?this.#i(n,c,u,i):this.#a(n,u,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,l.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:E(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#c(e,i===`max`,r);let a=r?.to?(0,l.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.T(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#o(),a=(0,l.getAddress)(n.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.F(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash)),this.#s(l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.F(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash)),this.#s(r.txHash,n,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async unwrap(e){this.#r(`unwrap`);let i=(0,l.getAddress)((await r.s(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[s]=a;if(!s)throw new n.n(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:t.N(this.address,i,i,s,o)})}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,l.getAddress)((await r.s(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.i(i))throw new n.t(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:t.P(this.address,e,e,i)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.c(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e]),i=n.clearValues[e];return s.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.S(this.address,e,i,n.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.w(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(n,i,a){this.emit({type:r.o.UnshieldPhase1Submitted,txHash:n,operationId:i});let o;try{o=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new r.b(`Failed to get unshield receipt`,{cause:t})}let s=J(o.logs);if(!s)throw new r.b(`No UnwrapRequested event found in unshield receipt`);this.emit({type:r.o.UnshieldPhase2Started,operationId:i}),t.F(`unshield: onFinalizing`,()=>a?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId??s.encryptedAmount);return this.emit({type:r.o.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),t.F(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(c.txHash)),c}async#c(e,n,i){this.#r(`approveUnderlying`);let a=await this.#o(),o=(0,l.getAddress)((await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),s=await this.sdk.provider.readContract(t.h(a,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let c=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,c),onSubmitted:i?.onApprovalSubmitted})}},we=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#t=e.onEvent??function(){},this.#n=new ae(e.storage),this.#s=new fe({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new a.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#e=e.registryTTL,e.signer&&(this.#o=new a.d({relayer:this.relayer,signer:e.signer,keypairTTL:e.keypairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage}),this.#a=new ce({cache:this.#n,credentialService:this.#o,delegationService:this.#s,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#i=new pe({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#r=new me({signer:e.signer,relayer:this.relayer,cachingService:this.#n,credentialService:this.#o}),this.permits=new k({signer:this.signer,provider:this.provider,cachingService:this.#n,credentialService:this.#o}),this.delegations=new O({signer:this.signer,provider:this.provider,delegationService:this.#s}),this.decryption=new D({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#a})}onWalletAccountChange(e){return this.#r.onWalletAccountChange(e)}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 a.o({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async encrypt(e){return this.#i.encrypt(e)}createToken(e){return new r.t(this,e)}createWrappedToken(e){return new Ce(this,e)}dispose(){this.#r.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${a.f(e)}`}const Te=u.z.union([u.z.pipe(a.m,u.z.transform(e=>({unwrapTxHash:e}))),u.z.pipe(u.z.object({version:u.z.literal(1),unwrapTxHash:a.m,unwrapRequestId:u.z.optional(a.m)}),u.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Ee(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function De(e,t){return(await Oe(e,t))?.unwrapTxHash??null}async function Oe(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Te.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ke(e,t){await e.delete($(t))}var Ae=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 je=new Ae;exports.ACL_TOPICS=Se,exports.AclPausedError=x,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=r.h,exports.BaseSigner=a.t,exports.ChainMismatchError=r.y,exports.ChromeSessionStorage=Ae,exports.ConfigurationError=e.t,exports.Decryption=D,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=a.a,exports.DelegationContractIsSelfError=b,exports.DelegationCooldownError=h,exports.DelegationDelegateEqualsContractError=y,exports.DelegationExpirationTooSoonError=S,exports.DelegationExpiredError=_,exports.DelegationExpiryUnchangedError=v,exports.DelegationNotFoundError=g,exports.DelegationNotPropagatedError=C,exports.DelegationSelfNotAllowedError=m,exports.Delegations=O,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=r.g,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=o.n,exports.InsufficientConfidentialBalanceError=r._,exports.InsufficientERC20BalanceError=r.v,exports.InvalidKeypairError=f,exports.KeypairExpiredError=d,exports.MemoryStorage=a.l,exports.MutableWalletAccountStore=a.n,exports.NoCiphertextError=p,exports.Permits=k,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=t.I,exports.SignerRequiredError=t.L,exports.SigningFailedError=t.V,exports.SigningRejectedError=t.H,exports.TOKEN_TOPICS=ve,exports.Token=r.t,exports.Topics=P,exports.TransactionRevertedError=r.b,exports.WalletAccountNotReadyError=t.R,exports.WalletNotConnectedError=t.z,exports.WrappedToken=Ce,exports.WrappersRegistry=a.o,exports.ZERO_ENCRYPTED_VALUE=r.r,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=we,exports.ZamaSDKEvents=r.o,exports.allowanceContract=t.h,exports.anvil=c.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.chains=c.n,exports.chromeSessionStorage=je,exports.clearPendingUnshield=ke,exports.cleartext=ee,exports.confidentialBalanceOfContract=t.E,exports.confidentialTotalSupplyContract=t.D,exports.confidentialTransferContract=t.O,exports.confidentialTransferFromContract=t.k,exports.createConfig=ne,exports.createWalletAccountStore=a.r,exports.decimalsContract=t.v,exports.decodeAclEvent=Q,exports.decodeAclEvents=ye,exports.decodeConfidentialTransfer=H,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=ge,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=G,exports.decodeUnwrapRequested=W,exports.decodeUnwrappedStarted=K,exports.decodeWrapped=U,exports.delegateForUserDecryptionContract=r.u,exports.finalizeUnwrapContract=t.S,exports.findDelegatedForUserDecryption=be,exports.findRevokedDelegationForUserDecryption=xe,exports.findUnwrapRequested=J,exports.findWrapped=_e,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=r.d,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=o.r,exports.inferredTotalSupplyContract=t.C,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isEncryptedValueZero=r.i,exports.isHandleDelegatedContract=r.f,exports.isOperatorContract=t.A,exports.loadPendingUnshield=De,exports.loadPendingUnshieldRequest=Oe,exports.mainnet=c.a,exports.matchZamaError=e.a,exports.memoryStorage=a.u,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=a.s,exports.resolveStorage=a.c,exports.revokeDelegationContract=r.p,exports.savePendingUnshield=Ee,exports.sepolia=c.o,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=E,exports.underlyingContract=t.w,exports.unwrapContract=t.N,exports.unwrapFromBalanceContract=t.P,exports.wrapContract=t.T;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./encryption.cjs"),r=require("./token.cjs"),i=require("./relayer-cleartext.cjs"),a=require("./base-signer.cjs"),o=require("./validation.cjs"),s=require("./assertions.cjs"),c=require("./chains.cjs");let l=require("viem"),u=require("zod/mini");var d=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},f=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},p=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},x=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},C=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function w(r,i,a=!1){if(r instanceof n.t||r instanceof p||r instanceof e.n||r instanceof C||r instanceof t.H||r instanceof t.V)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new p(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new C(`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 ee(){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 T(e){return e.startsWith(`0x`)?e:`0x${e}`}const te=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function E(e,t,n,r=`0x`){return{address:e,abi:te,functionName:`transferAndCall`,args:[t,n,r]}}function ne(e){return a.i(e.signer,e.provider,e)}var D=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return t.B(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await r.s(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t){let i=this.#i(`delegatedDecryptValues`),a=await r.s(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedUserDecrypt(e,t,a.address,n)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw w(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await r.s(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:i})}},O=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.B(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.s(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.s(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},k=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService}#i(e){return t.B(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#i(`grantPermit`);await r.c(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#i(`grantDelegationPermit`);await r.c(`grantDelegationPermit`,this.#e,this.#t),await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmKeypair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmKeypair(t.address)}async revokePermits(e){let n=this.#i(`revokePermits`),i=(0,l.getAddress)((await r.s(`revokePermits`,this.#e,this.#t)).address);try{await n.revokePermits(e)}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(i))}}async clear(){let e=this.#i(`clear`),n=(0,l.getAddress)((await r.s(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n))}}};const re=u.z.union([u.z.bigint(),u.z.boolean(),a.p]),ie=u.z.array(u.z.string());var ae=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.#s(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=re.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return console.warn(`[zama-sdk] CachingService.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#s(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#l(i).catch(e=>{console.warn(`[zama-sdk] CachingService index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] CachingService.set failed:`,e)}}async delete(e,t,n){let r=this.#s(e,t,n);this.#r=this.#r.then(()=>this.#i(r).catch(e=>{console.warn(`[zama-sdk] CachingService.delete failed:`,e)})),await this.#r}async clearForRequester(e){this.#r=this.#r.then(()=>this.#a(e).catch(e=>{console.warn(`[zama-sdk] CachingService.clearForRequester failed:`,e)})),await this.#r}async clearAll(){this.#r=this.#r.then(()=>this.#o().catch(e=>{console.warn(`[zama-sdk] CachingService.clearAll failed:`,e)})),await this.#r}async#i(e){await this.#e.delete(e).catch(()=>{});let t=await this.#c(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#n,n)}async#a(e){let t=(0,l.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#c(),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#o(){let e=await this.#c();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#s(e,t,n){return`${this.#t}:${(0,l.getAddress)(e)}:${(0,l.getAddress)(t)}:${n.toLowerCase()}`}async#c(){let e=await this.#e.get(this.#n);if(e===null)return[];let t=ie.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#n).catch(()=>{}),[])}async#l(e){let t=await this.#c();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}};function oe(e,t){let r=j(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return A(e,r)}function se(e,t){let r=j(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...A(e,r),delegatorAddress:r.delegatorAddress}}function A(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function j(e,t){let n=a.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}var ce=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=(0,l.getAddress)(t);return this.#a(e,{requesterAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...oe(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r){let i=(0,l.getAddress)(t),a=(0,l.getAddress)(n);return this.#a(e,{requesterAddress:(0,l.getAddress)(r),resolveCredentials:e=>this.#t.grantPermit(e,i),validate:e=>this.#l(e,{delegatorAddress:i,delegateAddress:a}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...se(e,t),delegateAddress:a}),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0})}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)}));if(o.length===0)return{items:o};let s=(0,l.getAddress)(i);try{let e=await this.delegatedUserDecrypt(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s);for(let t of o)this.#o(t,e);return{items:o}}catch(e){if(r.m(e))throw e;if(o.length===1){let[t=this.#c()]=o;return t.error=this.#s(e,`Failed to decrypt delegated encrypted values`,!0),{items:o}}}return await r.a(o.map(e=>async()=>{try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s);this.#o(e,r)}catch(t){if(r.m(t))throw t;e.error=this.#s(t,`Failed to decrypt delegated encrypted values`,!0)}}),a),{items:o}}async#a(e,t){if(e.length===0)return{};let n=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)})),i={},a=[];for(let e of n)r.i(e.encryptedValue)?i[e.encryptedValue]=0n:a.push(e);if(a.length===0)return i;let o=Array.from(new Set(n.map(e=>e.contractAddress))),c=Array.from(new Set(a.map(e=>e.contractAddress)));t.validate&&await t.validate(c);let u=[];for(let e of a){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):i[e.encryptedValue]=n}if(u.length===0)return i;let d=await t.resolveCredentials(o),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let p=Date.now(),m=u.map(e=>e.encryptedValue);try{this.#i({type:r.o.DecryptStart,encryptedValues:m}),await r.a([...f.entries()].map(([e,n])=>async()=>{let r=await t.decryptContract({credentials:d,contractAddress:e,encryptedValues:n});for(let[n,a]of Object.entries(r))i[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of m){let n=i[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.o.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),i}catch(e){throw this.#i({type:r.o.DecryptError,error:s.s(e),durationMs:Date.now()-p,encryptedValues:m}),w(e,t.errorMessage,t.delegated)}}#o(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#s(t,n,r=!1){return t instanceof e.r?t:w(t,n,r)}#c(){throw new n.t(`Batch delegated decryption invariant failed: missing item`)}async#l(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function le(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 M={AlreadyDelegatedOrRevokedInSameBlock:e=>new h(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new x(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new m(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new y(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new v(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new g(`Cannot revoke: no active delegation exists.`,{cause:e})};function ue(e){return e in M}function de(e,t){let n=le(e);if(n&&ue(n))return M[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(M))if(r.includes(e))return n(t);return null}var fe=class{#e;#t;#n;constructor({provider:e,relayer:t,emitEvent:n=()=>{}}){this.#e=e,this.#t=t,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new S(`Expiration date must be at least 1 hour in the future`);let o=(0,l.getAddress)(t),s=(0,l.getAddress)(n),c=(0,l.getAddress)(i);if(s===c)throw new m(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new y(`Delegate address cannot be the same as the contract address (${o}).`);let u=await this.#t.getAclAddress(),d=a?BigInt(Math.floor(a.getTime()/1e3)):r.l,f;try{f=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] delegateDecryption: pre-flight expiry check failed:`,e),f=-1n}if(f===d)throw new v(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#r({operation:`delegateDecryption`,signer:e,contractAddress:t,config:r.u(u,s,o,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=(0,l.getAddress)(i),c=await this.#t.getAclAddress(),u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){console.warn(`[zama-sdk] revokeDelegation: pre-flight expiry check failed:`,e),u=1n}if(u===0n)throw new g(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#r({operation:`revokeDelegation`,signer:e,contractAddress:t,config:r.p(c,o,a)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===r.l?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=await this.#t.getAclAddress();return this.#e.readContract(r.d(i,(0,l.getAddress)(t),(0,l.getAddress)(n),(0,l.getAddress)(e)))}async#r({operation:e,signer:t,contractAddress:n,config:i}){try{return await r.n({operation:e,signer:t,provider:this.#e,config:i,emit:e=>this.#n(e,n)})}catch(e){throw this.#i(e),e}}#i(e){if(!(e instanceof r.b))return;let t=de(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof g||t instanceof _){let n=(0,l.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let i=(0,l.getAddress)(e),a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new g(`No active delegation from ${a} to ${o} for ${i}`);if(s!==r.l&&s<=await this.#e.getBlockTimestamp())throw new _(`Delegation from ${a} to ${o} for ${i} has expired`)}},pe=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(t){let i=Date.now();try{this.#t({type:r.o.EncryptStart},t.contractAddress);let e=await this.#e.encrypt(t);return this.#t({type:r.o.EncryptEnd,durationMs:Date.now()-i},t.contractAddress),e}catch(a){throw this.#t({type:r.o.EncryptError,error:s.s(a),durationMs:Date.now()-i},t.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}},me=class{#e;#t;#n;#r;#i=new Set;#a;constructor(e){this.#e=e.signer,this.#t=e.relayer,this.#n=e.cachingService,this.#r=e.credentialService,this.#e&&(this.#a=this.#e.walletAccount.subscribe(e=>{this.#o(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})}))}onWalletAccountChange(e){return this.#i.add(e),()=>{this.#i.delete(e)}}dispose(){this.#a?.(),this.#a=void 0,this.#i.clear()}async#o(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.F(`switch relayer chain`,()=>this.#t.switchChain(i));let a=this.#r;a&&await t.F(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r)),n&&await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address)),await Promise.all(Array.from(this.#i,n=>t.F(`wallet account listener`,()=>n(e))))}};function N(e){return(0,l.keccak256)((0,l.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,l.getAddress)(T(e.slice(-40)))}function I(e){return BigInt(e)}function L(e){return e}function R(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function z(e,t){return(0,l.getAddress)(T(R(e,t).slice(-40)))}function B(e,t){return BigInt(`0x`+R(e,t))}function he(e,t){return BigInt(`0x`+R(e,t))!==0n}function V(e,t){return T(R(e,t))}function H(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmount:L(e.topics[3])}}function U(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:B(e.data,0)}}function W(e){return e.topics[0]!==P.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0)}}function G(e){return e.topics[0]!==P.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0),cleartextAmount:B(e.data,1)}}function K(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:I(e.topics[1]),txId:I(e.topics[2]),to:F(e.topics[3]),returnVal:he(e.data,0),refund:z(e.data,1),requestedAmount:V(e.data,2),burnAmount:V(e.data,3)}}function q(e){return H(e)??U(e)??W(e)??G(e)??K(e)}function ge(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=W(t);if(e)return e}return null}function _e(e){for(let t of e){let e=U(t);if(e)return e}return null}const ve=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapFinalized,P.UnwrappedStarted],Y={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2),newExpirationDate:B(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2)}}function Q(e){return X(e)??Z(e)}function ye(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function be(e){for(let t of e){let e=X(t);if(e)return e}return null}function xe(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Se=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];var Ce=class extends r.t{#e;#t=null;#n=null;#r(e){try{return s.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.I(e,{cause:n})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#o();return this.sdk.provider.readContract(t.h(n,(0,l.getAddress)(e),this.address))}async shield(n,i){let a=await r.s(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#o(),u=(0,l.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t._(c,u))}catch(t){throw t instanceof e.r?t:new r.g(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:s.s(t)})}if(d<n)throw new r.v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${c})`,{requested:n,available:d,token:c});return o?this.#i(n,c,u,i):this.#a(n,u,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,l.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:E(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#c(e,i===`max`,r);let a=r?.to?(0,l.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.T(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#o(),a=(0,l.getAddress)(n.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.F(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash)),this.#s(l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.F(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash)),this.#s(r.txHash,n,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async unwrap(e){this.#r(`unwrap`);let i=(0,l.getAddress)((await r.s(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[s]=a;if(!s)throw new n.n(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:t.N(this.address,i,i,s,o)})}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,l.getAddress)((await r.s(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.i(i))throw new n.t(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:t.P(this.address,e,e,i)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.c(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e]),i=n.clearValues[e];return s.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.S(this.address,e,i,n.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.w(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(n,i,a){this.emit({type:r.o.UnshieldPhase1Submitted,txHash:n,operationId:i});let o;try{o=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new r.b(`Failed to get unshield receipt`,{cause:t})}let s=J(o.logs);if(!s)throw new r.b(`No UnwrapRequested event found in unshield receipt`);this.emit({type:r.o.UnshieldPhase2Started,operationId:i}),t.F(`unshield: onFinalizing`,()=>a?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId??s.encryptedAmount);return this.emit({type:r.o.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),t.F(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(c.txHash)),c}async#c(e,n,i){this.#r(`approveUnderlying`);let a=await this.#o(),o=(0,l.getAddress)((await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),s=await this.sdk.provider.readContract(t.h(a,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let c=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,c),onSubmitted:i?.onApprovalSubmitted})}},we=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#t=e.onEvent??function(){},this.#n=new ae(e.storage),this.#s=new fe({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new a.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#e=e.registryTTL,e.signer&&(this.#o=new a.d({relayer:this.relayer,signer:e.signer,keypairTTL:e.keypairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage}),this.#a=new ce({cache:this.#n,credentialService:this.#o,delegationService:this.#s,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#i=new pe({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#r=new me({signer:e.signer,relayer:this.relayer,cachingService:this.#n,credentialService:this.#o}),this.permits=new k({signer:this.signer,provider:this.provider,cachingService:this.#n,credentialService:this.#o}),this.delegations=new O({signer:this.signer,provider:this.provider,delegationService:this.#s}),this.decryption=new D({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#a})}onWalletAccountChange(e){return this.#r.onWalletAccountChange(e)}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 a.o({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async encrypt(e){return this.#i.encrypt(e)}createToken(e){return new r.t(this,e)}createWrappedToken(e){return new Ce(this,e)}dispose(){this.#r.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${a.f(e)}`}const Te=u.z.union([u.z.pipe(a.m,u.z.transform(e=>({unwrapTxHash:e}))),u.z.pipe(u.z.object({version:u.z.literal(1),unwrapTxHash:a.m,unwrapRequestId:u.z.optional(a.m)}),u.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Ee(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function De(e,t){return(await Oe(e,t))?.unwrapTxHash??null}async function Oe(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Te.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ke(e,t){await e.delete($(t))}var Ae=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 je=new Ae;exports.ACL_TOPICS=Se,exports.AclPausedError=x,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=r.h,exports.BaseSigner=a.t,exports.ChainMismatchError=r.y,exports.ChromeSessionStorage=Ae,exports.ConfigurationError=e.t,exports.Decryption=D,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=a.a,exports.DelegationContractIsSelfError=b,exports.DelegationCooldownError=h,exports.DelegationDelegateEqualsContractError=y,exports.DelegationExpirationTooSoonError=S,exports.DelegationExpiredError=_,exports.DelegationExpiryUnchangedError=v,exports.DelegationNotFoundError=g,exports.DelegationNotPropagatedError=C,exports.DelegationSelfNotAllowedError=m,exports.Delegations=O,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=r.g,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=o.n,exports.InsufficientConfidentialBalanceError=r._,exports.InsufficientERC20BalanceError=r.v,exports.InvalidKeypairError=f,exports.KeypairExpiredError=d,exports.MemoryStorage=a.l,exports.MutableWalletAccountStore=a.n,exports.NoCiphertextError=p,exports.Permits=k,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=t.I,exports.SignerRequiredError=t.L,exports.SigningFailedError=t.V,exports.SigningRejectedError=t.H,exports.TOKEN_TOPICS=ve,exports.Token=r.t,exports.Topics=P,exports.TransactionRevertedError=r.b,exports.WalletAccountNotReadyError=t.R,exports.WalletNotConnectedError=t.z,exports.WrappedToken=Ce,exports.WrappersRegistry=a.o,exports.ZERO_ENCRYPTED_VALUE=r.r,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=we,exports.ZamaSDKEvents=r.o,exports.allowanceContract=t.h,exports.anvil=c.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.chains=c.n,exports.chromeSessionStorage=je,exports.clearPendingUnshield=ke,exports.cleartext=ee,exports.confidentialBalanceOfContract=t.E,exports.confidentialTotalSupplyContract=t.D,exports.confidentialTransferContract=t.O,exports.confidentialTransferFromContract=t.k,exports.createConfig=ne,exports.createWalletAccountStore=a.r,exports.decimalsContract=t.v,exports.decodeAclEvent=Q,exports.decodeAclEvents=ye,exports.decodeConfidentialTransfer=H,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=ge,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=G,exports.decodeUnwrapRequested=W,exports.decodeUnwrappedStarted=K,exports.decodeWrapped=U,exports.delegateForUserDecryptionContract=r.u,exports.finalizeUnwrapContract=t.S,exports.findDelegatedForUserDecryption=be,exports.findRevokedDelegationForUserDecryption=xe,exports.findUnwrapRequested=J,exports.findWrapped=_e,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=r.d,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=o.r,exports.inferredTotalSupplyContract=t.C,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isEncryptedValueZero=r.i,exports.isHandleDelegatedContract=r.f,exports.isOperatorContract=t.A,exports.loadPendingUnshield=De,exports.loadPendingUnshieldRequest=Oe,exports.mainnet=c.a,exports.matchZamaError=e.a,exports.memoryStorage=a.u,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=a.s,exports.resolveStorage=a.c,exports.revokeDelegationContract=r.p,exports.savePendingUnshield=Ee,exports.sepolia=c.o,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=E,exports.underlyingContract=t.w,exports.unwrapContract=t.N,exports.unwrapFromBalanceContract=t.P,exports.wrapContract=t.T;
2
2
  //# sourceMappingURL=index.cjs.map