@zama-fhe/sdk 3.0.0-alpha.33 → 3.0.0-alpha.34

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(`./base-signer.cjs`),i=require(`./readonly-token.cjs`),a=require(`./relayer-cleartext.cjs`),o=require(`./validation.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`);let l=require(`viem`);var u=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},d=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},f=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},p=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},m=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},h=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}},g=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},C=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},w=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},T=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}},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}},E=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}},te=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},D=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function ne(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 O={AlreadyDelegatedOrRevokedInSameBlock:e=>new _(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new S(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new C(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new g(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new w(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new v(`Cannot revoke: no active delegation exists.`,{cause:e})};function k(e){let t=e instanceof Error?e:void 0,n=ne(e);if(n&&n in O)return O[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(O))if(r.includes(e))return n(t);return null}function A(r,i,a=!1){if(r instanceof n.t||r instanceof m||r instanceof e.n||r instanceof T||r instanceof t.R||r instanceof t.L)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new m(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new T(`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 re(){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 a.t(t)}}}function j(e){return e.startsWith(`0x`)?e:`0x${e}`}const ie=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function M(e,t,n,r=`0x`){return{address:e,abi:ie,functionName:`transferAndCall`,args:[t,n,r]}}function ae(e){return r.i(e.signer,e.provider,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)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,l.getAddress)(j(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)(j(R(e,t).slice(-40)))}function B(e,t){return BigInt(`0x`+R(e,t))}function oe(e,t){return BigInt(`0x`+R(e,t))!==0n}function V(e,t){return j(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)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:V(e.data,0)}:null}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)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:V(e.data,0),cleartextAmount:B(e.data,1)}:null}function se(e){let t=G(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ce(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=G(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}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:oe(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)??ce(e)??G(e)??K(e)}function le(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 ue(e){for(let t of e){let e=U(t);if(e)return e}return null}const de=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,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 fe(e){return X(e)??Z(e)}function pe(e){let t=[];for(let n of e){let e=fe(n);e&&t.push(e)}return t}function me(e){for(let t of e){let e=X(t);if(e)return e}return null}function he(e){for(let t of e){let e=Z(t);if(e)return e}return null}const ge=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];var _e=class r extends i.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;#n=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,l.getAddress)(n):this.address}async#r(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#r();return this.#n=await this.sdk.provider.readContract(t.m(e)),this.#n}catch{return this.#n=!1,!1}}async confidentialTransfer(r,a,o){let c=this.sdk.requireSigner(`confidentialTransfer`),u=await this.sdk.requireAlignedWalletAccount(`confidentialTransfer`),{skipBalanceCheck:f=!1,onEncryptComplete:p,onTransferSubmitted:m}=o??{},h=(0,l.getAddress)(r);f||await this.#s(a);let{handles:g,inputProof:_}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:(0,l.getAddress)(u.address)});if(Q(()=>p?.()),g.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(t.k(this.address,h,g[0],_));return this.emit({type:i.r.TransferSubmitted,txHash:e}),Q(()=>m?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`transfer`,error:s.s(t)}),t instanceof e.r?t:new d(`Transfer transaction failed`,{cause:t})}}async confidentialTransferFrom(r,a,o,c){let u=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let f=(0,l.getAddress)(r),p=(0,l.getAddress)(a),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:f});if(Q(()=>c?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await u.writeContract(t.A(this.address,f,p,m[0],h));return this.emit({type:i.r.TransferFromSubmitted,txHash:e}),Q(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`transferFrom`,error:s.s(t)}),t instanceof e.r?t:new d(`TransferFrom transaction failed`,{cause:t})}}async setOperator(n,r){let a=this.sdk.requireSigner(`setOperator`);await this.sdk.requireChainAlignment(`setOperator`);let o=(0,l.getAddress)(n);try{let e=await a.writeContract(t.N(this.address,o,r));return this.emit({type:i.r.SetOperatorSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`setOperator`,error:s.s(t)}),t instanceof e.r?t:new u(`Operator approval failed`,{cause:t})}}async isOperator(e,n){return this.sdk.provider.readContract(t.j(this.address,(0,l.getAddress)(e),(0,l.getAddress)(n)))}async shield(n,r){let i=await this.sdk.requireAlignedWalletAccount(`shield`),a=await this.isPayable(),o=await this.#r(),c=(0,l.getAddress)(i.address),u;try{u=await this.sdk.provider.readContract(t.v(o,c))}catch(t){throw t instanceof e.r?t:new D(`Could not read ERC-20 balance for shield validation (token: ${o})`,{cause:s.s(t)})}if(u<n)throw new E(`Insufficient ERC-20 balance: requested ${n}, available ${u} (token: ${o})`,{requested:n,available:u,token:o});return a?this.#i(n,o,c,r):this.#a(n,c,r)}async#i(t,n,r,a){let o=this.sdk.requireSigner(`shield`),c=a?.to?(0,l.getAddress)(a.to):r,u=c===r?`0x`:c;try{let e=await o.writeContract(M(n,this.wrapper,t,u));return this.emit({type:i.r.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`}),Q(()=>a?.onShieldSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`shield:transferAndCall`,error:s.s(t)}),t instanceof e.r?t:new d(`TransferAndCall shield transaction failed`,{cause:t})}}async#a(n,r,a){let o=this.sdk.requireSigner(`shield`),c=a?.approvalStrategy??`exact`;c!==`skip`&&await this.#l(n,c===`max`,a);try{let e=a?.to?(0,l.getAddress)(a.to):r,s=await o.writeContract(t.E(this.wrapper,e,n));return this.emit({type:i.r.ShieldSubmitted,txHash:s,shieldPath:`approveAndWrap`}),Q(()=>a?.onShieldSubmitted?.(s)),{txHash:s,receipt:await this.sdk.provider.waitForTransactionReceipt(s)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`shield:approveAndWrap`,error:s.s(t)}),t instanceof e.r?t:new d(`ApproveAndWrap shield transaction failed`,{cause:t})}}async unwrap(r){let a=this.sdk.requireSigner(`unwrap`),o=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrap`)).address),{handles:c,inputProof:u}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:o});if(c.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await a.writeContract(t.F(this.address,o,o,c[0],u));return this.emit({type:i.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`unwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Unshield transaction failed`,{cause:t})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`),a=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrapAll`)).address),o=await this.readConfidentialBalanceOf(a);if(i.u(o))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(t.I(this.address,a,a,o));return this.emit({type:i.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`unwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Unshield-all transaction failed`,{cause:t})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#s(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Q(()=>r?.(c.txHash)),this.#c(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Q(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#c(n.txHash,t,e)}async resumeUnshield(e,t){return this.#c(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let a=await this.sdk.publicDecrypt([n]),o=a.clearValues[n];s.t(o,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(t.C(this.wrapper,n,o,a.decryptionProof));return this.emit({type:i.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`finalizeUnwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Failed to finalize unshield`,{cause:t})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`),a=await this.sdk.requireAlignedWalletAccount(`approveUnderlying`),o=await this.#r(),c=(0,l.getAddress)(a.address),d=n??2n**256n-1n;try{d>0n&&await this.sdk.provider.readContract(t.g(o,c,this.wrapper))>0n&&await r.writeContract(t._(o,this.wrapper,0n));let e=await r.writeContract(t._(o,this.wrapper,d));return this.emit({type:i.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.r.TransactionError,operation:`approveUnderlying`,error:s.s(t)}),t instanceof e.r?t:new u(`ERC-20 approval failed`,{cause:t})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){return this.sdk.delegateDecryption({contractAddress:this.address,delegateAddress:e,expirationDate:t})}async revokeDelegation({delegateAddress:e}){return this.sdk.revokeDelegation({contractAddress:this.address,delegateAddress:e})}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#o(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#o(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#o(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 d(r,{cause:n}))}return i}async#s(t){if(t===0n)return;let n;try{let e=await this.sdk.requireAlignedWalletAccount(`assertConfidentialBalance`);n=await this.balanceOf((0,l.getAddress)(e.address))}catch(t){throw t instanceof e.r?t:new te(`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#c(t,n,r){this.emit({type:i.r.UnshieldPhase1Submitted,txHash:t,operationId:n});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(t)}catch(t){throw t instanceof e.r?t:new d(`Failed to get unshield receipt`,{cause:t})}let o=J(a.logs);if(!o)throw new d(`No UnwrapRequested event found in unshield receipt`);this.emit({type:i.r.UnshieldPhase2Started,operationId:n}),Q(()=>r?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:i.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:n}),Q(()=>r?.onFinalizeSubmitted?.(s.txHash)),s}async#l(n,r,a){let o=this.sdk.requireSigner(`approveUnderlying`),s=await this.#r(),c=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`approveUnderlying`)).address),d=await this.sdk.provider.readContract(t.g(s,c,this.wrapper));if(!(d>=n))try{if(d>0n){let e=await o.writeContract(t._(s,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,c=await o.writeContract(t._(s,this.wrapper,e));this.emit({type:i.r.ApproveUnderlyingSubmitted,txHash:c}),Q(()=>a?.onApprovalSubmitted?.(c)),await this.sdk.provider.waitForTransactionReceipt(c)}catch(t){throw t instanceof e.r?t:new u(`ERC-20 approval failed`,{cause:t})}}};function Q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const ve=o.f([o.a(),o.o(),r.p]),ye=o.i(o.d());var be=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=ve.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=ye.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 xe(e,t){let r=we(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return Ce(e,r)}function Se(e,t){let r=we(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...Ce(e,r),delegatorAddress:r.delegatorAddress}}function Ce(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function we(e,t){let n=r.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}var Te=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.allow(e),decryptContract:async({credentials:e,contractAddress:t,contractHandles:r})=>this.#r.userDecrypt({handles:r,contractAddress:t,...xe(e,t),signerAddress:n}),errorMessage:`Failed to decrypt handles`})}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.allow(e,i),validate:e=>this.#l(e,{delegatorAddress:i,delegateAddress:a}),decryptContract:async({credentials:e,contractAddress:t,contractHandles:n})=>this.#r.delegatedUserDecrypt({handles:n,contractAddress:t,...Se(e,t),delegateAddress:a}),errorMessage:`Failed to decrypt delegated handles`,delegated:!0})}async delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:a=5}){let o=e.map(e=>({handle:e.handle,contractAddress:(0,l.getAddress)(e.contractAddress)}));if(o.length===0)return{items:o};let s=(0,l.getAddress)(r);try{let e=await this.delegatedUserDecrypt(o.map(({handle:e,contractAddress:t})=>({handle:e,contractAddress:t})),t,n,s);for(let t of o)this.#o(t,e);return{items:o}}catch(e){if(i.d(e))throw e;if(o.length===1){let[t=this.#c()]=o;return t.error=this.#s(e,`Failed to decrypt delegated handles`,!0),{items:o}}}return await i.n(o.map(e=>async()=>{try{let r=await this.delegatedUserDecrypt([{handle:e.handle,contractAddress:e.contractAddress}],t,n,s);this.#o(e,r)}catch(t){if(i.d(t))throw t;e.error=this.#s(t,`Failed to decrypt delegated handles`,!0)}}),a),{items:o}}async#a(e,t){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,l.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)i.u(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;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.handle);n===null?u.push(e):r[e.handle]=n}if(u.length===0)return r;let d=await t.resolveCredentials(o),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=u.map(e=>e.handle);try{this.#i({type:i.r.DecryptStart,handles:m}),await i.n([...f.entries()].map(([e,n])=>async()=>{let i=await t.decryptContract({credentials:d,contractAddress:e,contractHandles:n});for(let[n,a]of Object.entries(i))r[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of m){let n=r[t];n!==void 0&&(e[t]=n)}return this.#i({type:i.r.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),r}catch(e){throw this.#i({type:i.r.DecryptError,error:s.s(e),durationMs:Date.now()-p,handles:m}),A(e,t.errorMessage,t.delegated)}}#o(e,t){let r=t[e.handle];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for handle ${e.handle} on contract ${e.contractAddress}`);return}e.value=r}#s(t,n,r=!1){return t instanceof e.r?t:A(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}},Ee=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:r,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new w(`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)(r);if(s===c)throw new g(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new x(`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)):i.i,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 b(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#r(e,i.a(u,s,o,d),`Delegation transaction failed`,i.r.DelegationSubmitted,o)}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=(0,l.getAddress)(r),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 v(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#r(e,i.c(c,o,a),`Revoke delegation transaction failed`,i.r.RevokeDelegationSubmitted,a)}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===i.i?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=await this.#t.getAclAddress();return this.#e.readContract(i.o(r,(0,l.getAddress)(t),(0,l.getAddress)(n),(0,l.getAddress)(e)))}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 v||t instanceof y){let n=(0,l.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,l.getAddress)(e),a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:r,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new v(`No active delegation from ${a} to ${o} for ${r}`);if(s!==i.i&&s<=await this.#e.getBlockTimestamp())throw new y(`Delegation from ${a} to ${o} for ${r} has expired`)}async#r(t,n,r,a,o){try{let e=await t.writeContract(n);return a===i.r.DelegationSubmitted?this.#n({type:i.r.DelegationSubmitted,txHash:e},o):this.#n({type:i.r.RevokeDelegationSubmitted,txHash:e},o),{txHash:e,receipt:await this.#e.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:k(t)||new d(r,{cause:t})}}},De=class{relayer;provider;signer;storage;registry;#e;#t;#n=new Set;#r;#i;#a;#o;#s;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=new be(e.storage),this.#t=e.onEvent??function(){},this.#a=new Ee({provider:this.provider,relayer:this.relayer,emitEvent:(e,t)=>this.emitEvent(e,t)});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);if(this.registry=new r.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#e=e.registryTTL,e.signer){let t=e.signer;this.#i=new r.d({relayer:this.relayer,signer:t,keypairTTL:e.keypairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage}),this.#o=new Te({cache:this.#r,credentialService:this.#i,delegationService:this.#a,relayer:this.relayer,emitEvent:e=>this.emitEvent(e)}),this.#s=t.walletAccount.subscribe(e=>{this.#u(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})})}else this.#i=void 0,this.#o=void 0}requireSigner(e){if(!this.signer)throw new r.g(e);return this.signer}#c(e){if(!this.#i)throw new r.g(e);return this.#i}#l(e){if(!this.#o)throw new r.g(e);return this.#o}onWalletAccountChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireAlignedWalletAccount(e){let t=this.requireSigner(e),n;try{n=t.requireWalletAccount(e)}catch(i){if(!(i instanceof r.v)||!t.refreshWalletAccount)throw i;await t.refreshWalletAccount(),n=t.requireWalletAccount(e)}let i=await this.provider.getChainId();if(n.chainId!==i)throw new h({operation:e,signerChainId:n.chainId,providerChainId:i});return n}async requireChainAlignment(e){return(await this.requireAlignedWalletAccount(e)).chainId}async#u(e){let t=e.previous,n=e.next,i=this.#i;i&&await r.h(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n)),t&&await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(t.address));let a=n?.chainId;a!==void 0&&r.h(`switch relayer chain`,()=>this.relayer.switchChain(a)),await Promise.all(Array.from(this.#n,e=>r.h(`wallet account listener`,()=>e({previous:t,next:n}))))}createReadonlyToken(e){return new i.t(this,e)}createToken(e,t){return new _e(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 r.o({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){if(e.length===0)return;let t=this.#c(`allow`);await this.requireChainAlignment(`allow`),await t.allow(e)}async allowAs(e,t){if(t.length===0)return;let n=this.#c(`allowAs`);await this.requireChainAlignment(`allowAs`),await n.allow(t,e)}async isAllowed(e){return this.#i?this.#i.isAllowed(e):!1}async isAllowedAs(e,t){return this.#i?this.#i.isAllowed(t,e):!1}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.requireSigner(`delegateDecryption`),i=await this.requireAlignedWalletAccount(`delegateDecryption`);return this.#a.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.requireSigner(`revokeDelegation`),r=await this.requireAlignedWalletAccount(`revokeDelegation`);return this.#a.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isDelegated(e){return this.#a.isDelegated(e)}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){return this.#a.getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n})}async userDecrypt(e){let t=this.#l(`userDecrypt`),n=await this.requireAlignedWalletAccount(`userDecrypt`);return t.userDecrypt(e,n.address)}async delegatedUserDecrypt(e,t,n=t){let r=this.#l(`delegatedUserDecrypt`),i=await this.requireAlignedWalletAccount(`delegatedUserDecrypt`);return r.delegatedUserDecrypt(e,t,i.address,n)}async delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r}){let i=this.#l(`delegatedBatchDecryptHandlesAs`),a=await this.requireAlignedWalletAccount(`delegatedBatchDecryptHandlesAs`);return i.delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,delegateAddress:a.address,accountAddress:n,maxConcurrency:r})}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw A(e,`Public decryption failed`)}}async encrypt(t){let r=Date.now();try{this.emitEvent({type:i.r.EncryptStart},t.contractAddress);let e=await this.relayer.encrypt(t);return this.emitEvent({type:i.r.EncryptEnd,durationMs:Date.now()-r},t.contractAddress),e}catch(a){throw this.emitEvent({type:i.r.EncryptError,error:s.s(a),durationMs:Date.now()-r},t.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}async revokePermits(e){let t=this.#c(`revokePermits`),n=(0,l.getAddress)((await this.requireAlignedWalletAccount(`revokePermits`)).address);try{await t.revokePermits(e)}finally{await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(n))}}async clearCredentials(){let e=this.#c(`clearCredentials`),t=(0,l.getAddress)((await this.requireAlignedWalletAccount(`clearCredentials`)).address);try{await e.clearCredentials()}finally{await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(t))}}dispose(){this.#s?.(),this.#s=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${r.f(e)}`}const Oe=o.f([r.m.transform(e=>({unwrapTxHash:e})),o.l({version:o.s(1),unwrapTxHash:r.m,unwrapRequestId:r.m.optional()}).transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t}))]);async function ke(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 Ae(e,t){return(await je(e,t))?.unwrapTxHash??null}async function je(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Oe.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Me(e,t){await e.delete($(t))}var Ne=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 Pe=new Ne;exports.ACL_TOPICS=ge,exports.AclPausedError=C,exports.AclTopics=Y,exports.ApprovalFailedError=u,exports.BalanceCheckUnavailableError=te,exports.BaseSigner=r.t,exports.ChainMismatchError=h,exports.ChromeSessionStorage=Ne,exports.ConfigurationError=e.t,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=r.a,exports.DelegationContractIsSelfError=S,exports.DelegationCooldownError=_,exports.DelegationDelegateEqualsContractError=x,exports.DelegationExpirationTooSoonError=w,exports.DelegationExpiredError=y,exports.DelegationExpiryUnchangedError=b,exports.DelegationNotFoundError=v,exports.DelegationNotPropagatedError=T,exports.DelegationSelfNotAllowedError=g,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=D,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=t.d,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=o.n,exports.InsufficientConfidentialBalanceError=ee,exports.InsufficientERC20BalanceError=E,exports.InvalidKeypairError=p,exports.KeypairExpiredError=f,exports.MemoryStorage=r.l,exports.MutableWalletAccountStore=r.n,exports.NoCiphertextError=m,exports.ReadonlyToken=i.t,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=r.g,exports.SignerRequiredError=r._,exports.SigningFailedError=t.L,exports.SigningRejectedError=t.R,exports.TOKEN_TOPICS=de,exports.Token=_e,exports.Topics=P,exports.TransactionRevertedError=d,exports.WalletAccountNotReadyError=r.v,exports.WalletNotConnectedError=r.y,exports.WrappersRegistry=r.o,exports.ZERO_HANDLE=i.l,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=De,exports.ZamaSDKEvents=i.r,exports.allowanceContract=t.g,exports.anvil=c.t,exports.approveContract=t._,exports.balanceOfContract=t.v,exports.chains=c.n,exports.chromeSessionStorage=Pe,exports.clearPendingUnshield=Me,exports.cleartext=re,exports.confidentialBalanceOfContract=t.D,exports.confidentialTotalSupplyContract=t.O,exports.confidentialTransferContract=t.k,exports.confidentialTransferFromContract=t.A,exports.createConfig=ae,exports.createWalletAccountStore=r.r,exports.decimalsContract=t.y,exports.decodeAclEvent=fe,exports.decodeAclEvents=pe,exports.decodeConfidentialTransfer=H,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=le,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=G,exports.decodeUnwrapRequested=W,exports.decodeUnwrappedFinalized=se,exports.decodeUnwrappedStarted=K,exports.decodeWrapped=U,exports.delegateForUserDecryptionContract=i.a,exports.finalizeUnwrapContract=t.C,exports.findDelegatedForUserDecryption=me,exports.findRevokedDelegationForUserDecryption=he,exports.findUnwrapRequested=J,exports.findWrapped=ue,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=i.o,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.w,exports.isConfidentialTokenContract=t.f,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.p,exports.isHandleDelegatedContract=i.s,exports.isOperatorContract=t.j,exports.isZeroHandle=i.u,exports.loadPendingUnshield=Ae,exports.loadPendingUnshieldRequest=je,exports.mainnet=c.a,exports.matchAclRevert=k,exports.matchZamaError=e.a,exports.memoryStorage=r.u,exports.nameContract=t.x,exports.rateContract=t.M,exports.resolveChainRelayers=r.s,exports.resolveStorage=r.c,exports.revokeDelegationContract=i.c,exports.savePendingUnshield=ke,exports.sepolia=c.o,exports.setOperatorContract=t.N,exports.supportsInterfaceContract=t.h,exports.symbolContract=t.S,exports.totalSupplyContract=t.P,exports.transferAndCallContract=M,exports.underlyingContract=t.T,exports.unwrapContract=t.F,exports.unwrapFromBalanceContract=t.I,exports.wrapContract=t.E;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./wrappers-registry.cjs`),n=require(`./encryption.cjs`),r=require(`./base-signer.cjs`),i=require(`./sdk-events.cjs`),a=require(`./relayer-cleartext.cjs`),o=require(`./validation.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`);let l=require(`viem`);var u=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},d=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},f=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},p=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},m=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},h=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}},g=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},C=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},w=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},T=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}},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}},E=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}},D=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},te=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function ne(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 O={AlreadyDelegatedOrRevokedInSameBlock:e=>new _(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new S(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new C(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new g(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new w(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new v(`Cannot revoke: no active delegation exists.`,{cause:e})};function k(e){let t=e instanceof Error?e:void 0,n=ne(e);if(n&&n in O)return O[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(O))if(r.includes(e))return n(t);return null}function A(r,i,a=!1){if(r instanceof n.t||r instanceof m||r instanceof e.n||r instanceof T||r instanceof t.R||r instanceof t.L)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new m(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new T(`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 re(){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 a.t(t)}}}function j(e){return e.startsWith(`0x`)?e:`0x${e}`}const ie=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function M(e,t,n,r=`0x`){return{address:e,abi:ie,functionName:`transferAndCall`,args:[t,n,r]}}function ae(e){return r.i(e.signer,e.provider,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)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,l.getAddress)(j(e.slice(-40)))}function oe(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,l.getAddress)(j(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function se(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return j(L(e,t))}function V(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function H(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function U(e){return e.topics[0]===P.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}:null}function W(e){return e.topics[0]===P.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:null}function ce(e){let t=W(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function le(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=W(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function G(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:oe(e.topics[1]),txId:oe(e.topics[2]),to:F(e.topics[3]),returnVal:se(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function K(e){return V(e)??H(e)??U(e)??le(e)??W(e)??G(e)}function ue(e){let t=[];for(let n of e){let e=K(n);e&&t.push(e)}return t}function q(e){for(let t of e){let e=U(t);if(e)return e}return null}function de(e){for(let t of e){let e=H(t);if(e)return e}return null}const fe=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,P.UnwrappedStarted],J={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Y(e){return e.topics[0]!==J.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function X(e){return e.topics[0]!==J.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function pe(e){return Y(e)??X(e)}function me(e){let t=[];for(let n of e){let e=pe(n);e&&t.push(e)}return t}function he(e){for(let t of e){let e=Y(t);if(e)return e}return null}function ge(e){for(let t of e){let e=X(t);if(e)return e}return null}const _e=[J.DelegatedForUserDecryption,J.RevokedDelegationForUserDecryption];var ve=class r extends i.n{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;#n=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,l.getAddress)(n):this.address}async#r(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#r();return this.#n=await this.sdk.provider.readContract(t.m(e)),this.#n}catch{return this.#n=!1,!1}}async confidentialTransfer(r,a,o){let c=this.sdk.requireSigner(`confidentialTransfer`),u=await this.sdk.requireAlignedWalletAccount(`confidentialTransfer`),{skipBalanceCheck:f=!1,onEncryptComplete:p,onTransferSubmitted:m}=o??{},h=(0,l.getAddress)(r);f||await this.#s(a);let{handles:g,inputProof:_}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:(0,l.getAddress)(u.address)});if(Z(()=>p?.()),g.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(t.k(this.address,h,g[0],_));return this.emit({type:i.t.TransferSubmitted,txHash:e}),Z(()=>m?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`transfer`,error:s.s(t)}),t instanceof e.r?t:new d(`Transfer transaction failed`,{cause:t})}}async confidentialTransferFrom(r,a,o,c){let u=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let f=(0,l.getAddress)(r),p=(0,l.getAddress)(a),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:f});if(Z(()=>c?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await u.writeContract(t.A(this.address,f,p,m[0],h));return this.emit({type:i.t.TransferFromSubmitted,txHash:e}),Z(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`transferFrom`,error:s.s(t)}),t instanceof e.r?t:new d(`TransferFrom transaction failed`,{cause:t})}}async setOperator(n,r){let a=this.sdk.requireSigner(`setOperator`);await this.sdk.requireChainAlignment(`setOperator`);let o=(0,l.getAddress)(n);try{let e=await a.writeContract(t.N(this.address,o,r));return this.emit({type:i.t.SetOperatorSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`setOperator`,error:s.s(t)}),t instanceof e.r?t:new u(`Operator approval failed`,{cause:t})}}async isOperator(e,n){return this.sdk.provider.readContract(t.j(this.address,(0,l.getAddress)(e),(0,l.getAddress)(n)))}async shield(n,r){let i=await this.sdk.requireAlignedWalletAccount(`shield`),a=await this.isPayable(),o=await this.#r(),c=(0,l.getAddress)(i.address),u;try{u=await this.sdk.provider.readContract(t.v(o,c))}catch(t){throw t instanceof e.r?t:new te(`Could not read ERC-20 balance for shield validation (token: ${o})`,{cause:s.s(t)})}if(u<n)throw new E(`Insufficient ERC-20 balance: requested ${n}, available ${u} (token: ${o})`,{requested:n,available:u,token:o});return a?this.#i(n,o,c,r):this.#a(n,c,r)}async#i(t,n,r,a){let o=this.sdk.requireSigner(`shield`),c=a?.to?(0,l.getAddress)(a.to):r,u=c===r?`0x`:c;try{let e=await o.writeContract(M(n,this.wrapper,t,u));return this.emit({type:i.t.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`}),Z(()=>a?.onShieldSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`shield:transferAndCall`,error:s.s(t)}),t instanceof e.r?t:new d(`TransferAndCall shield transaction failed`,{cause:t})}}async#a(n,r,a){let o=this.sdk.requireSigner(`shield`),c=a?.approvalStrategy??`exact`;c!==`skip`&&await this.#l(n,c===`max`,a);try{let e=a?.to?(0,l.getAddress)(a.to):r,s=await o.writeContract(t.E(this.wrapper,e,n));return this.emit({type:i.t.ShieldSubmitted,txHash:s,shieldPath:`approveAndWrap`}),Z(()=>a?.onShieldSubmitted?.(s)),{txHash:s,receipt:await this.sdk.provider.waitForTransactionReceipt(s)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`shield:approveAndWrap`,error:s.s(t)}),t instanceof e.r?t:new d(`ApproveAndWrap shield transaction failed`,{cause:t})}}async unwrap(r){let a=this.sdk.requireSigner(`unwrap`),o=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrap`)).address),{handles:c,inputProof:u}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:o});if(c.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await a.writeContract(t.F(this.address,o,o,c[0],u));return this.emit({type:i.t.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`unwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Unshield transaction failed`,{cause:t})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`),a=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrapAll`)).address),o=await this.readConfidentialBalanceOf(a);if(i.u(o))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(t.I(this.address,a,a,o));return this.emit({type:i.t.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`unwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Unshield-all transaction failed`,{cause:t})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#s(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Z(()=>r?.(c.txHash)),this.#c(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Z(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#c(n.txHash,t,e)}async resumeUnshield(e,t){return this.#c(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let a=await this.sdk.publicDecrypt([n]),o=a.clearValues[n];s.t(o,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(t.C(this.wrapper,n,o,a.decryptionProof));return this.emit({type:i.t.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`finalizeUnwrap`,error:s.s(t)}),t instanceof e.r?t:new d(`Failed to finalize unshield`,{cause:t})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`),a=await this.sdk.requireAlignedWalletAccount(`approveUnderlying`),o=await this.#r(),c=(0,l.getAddress)(a.address),d=n??2n**256n-1n;try{d>0n&&await this.sdk.provider.readContract(t.g(o,c,this.wrapper))>0n&&await r.writeContract(t._(o,this.wrapper,0n));let e=await r.writeContract(t._(o,this.wrapper,d));return this.emit({type:i.t.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(t){throw this.emit({type:i.t.TransactionError,operation:`approveUnderlying`,error:s.s(t)}),t instanceof e.r?t:new u(`ERC-20 approval failed`,{cause:t})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){return this.sdk.delegateDecryption({contractAddress:this.address,delegateAddress:e,expirationDate:t})}async revokeDelegation({delegateAddress:e}){return this.sdk.revokeDelegation({contractAddress:this.address,delegateAddress:e})}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#o(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#o(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#o(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 d(r,{cause:n}))}return i}async#s(t){if(t===0n)return;let n;try{let e=await this.sdk.requireAlignedWalletAccount(`assertConfidentialBalance`);n=await this.balanceOf((0,l.getAddress)(e.address))}catch(t){throw t instanceof e.r?t:new D(`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#c(t,n,r){this.emit({type:i.t.UnshieldPhase1Submitted,txHash:t,operationId:n});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(t)}catch(t){throw t instanceof e.r?t:new d(`Failed to get unshield receipt`,{cause:t})}let o=q(a.logs);if(!o)throw new d(`No UnwrapRequested event found in unshield receipt`);this.emit({type:i.t.UnshieldPhase2Started,operationId:n}),Z(()=>r?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:i.t.UnshieldPhase2Submitted,txHash:s.txHash,operationId:n}),Z(()=>r?.onFinalizeSubmitted?.(s.txHash)),s}async#l(n,r,a){let o=this.sdk.requireSigner(`approveUnderlying`),s=await this.#r(),c=(0,l.getAddress)((await this.sdk.requireAlignedWalletAccount(`approveUnderlying`)).address),d=await this.sdk.provider.readContract(t.g(s,c,this.wrapper));if(!(d>=n))try{if(d>0n){let e=await o.writeContract(t._(s,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,c=await o.writeContract(t._(s,this.wrapper,e));this.emit({type:i.t.ApproveUnderlyingSubmitted,txHash:c}),Z(()=>a?.onApprovalSubmitted?.(c)),await this.sdk.provider.waitForTransactionReceipt(c)}catch(t){throw t instanceof e.r?t:new u(`ERC-20 approval failed`,{cause:t})}}};function Z(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const ye=o.f([o.a(),o.o(),r.p]),be=o.i(o.d());var xe=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=ye.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=be.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 Se(e,t){let r=Te(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return we(e,r)}function Ce(e,t){let r=Te(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...we(e,r),delegatorAddress:r.delegatorAddress}}function we(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function Te(e,t){let n=r.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}var Ee=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.allow(e),decryptContract:async({credentials:e,contractAddress:t,contractHandles:r})=>this.#r.userDecrypt({handles:r,contractAddress:t,...Se(e,t),signerAddress:n}),errorMessage:`Failed to decrypt handles`})}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.allow(e,i),validate:e=>this.#l(e,{delegatorAddress:i,delegateAddress:a}),decryptContract:async({credentials:e,contractAddress:t,contractHandles:n})=>this.#r.delegatedUserDecrypt({handles:n,contractAddress:t,...Ce(e,t),delegateAddress:a}),errorMessage:`Failed to decrypt delegated handles`,delegated:!0})}async delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:a=5}){let o=e.map(e=>({handle:e.handle,contractAddress:(0,l.getAddress)(e.contractAddress)}));if(o.length===0)return{items:o};let s=(0,l.getAddress)(r);try{let e=await this.delegatedUserDecrypt(o.map(({handle:e,contractAddress:t})=>({handle:e,contractAddress:t})),t,n,s);for(let t of o)this.#o(t,e);return{items:o}}catch(e){if(i.d(e))throw e;if(o.length===1){let[t=this.#c()]=o;return t.error=this.#s(e,`Failed to decrypt delegated handles`,!0),{items:o}}}return await i.r(o.map(e=>async()=>{try{let r=await this.delegatedUserDecrypt([{handle:e.handle,contractAddress:e.contractAddress}],t,n,s);this.#o(e,r)}catch(t){if(i.d(t))throw t;e.error=this.#s(t,`Failed to decrypt delegated handles`,!0)}}),a),{items:o}}async#a(e,t){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,l.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)i.u(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;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.handle);n===null?u.push(e):r[e.handle]=n}if(u.length===0)return r;let d=await t.resolveCredentials(o),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=u.map(e=>e.handle);try{this.#i({type:i.t.DecryptStart,handles:m}),await i.r([...f.entries()].map(([e,n])=>async()=>{let i=await t.decryptContract({credentials:d,contractAddress:e,contractHandles:n});for(let[n,a]of Object.entries(i))r[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of m){let n=r[t];n!==void 0&&(e[t]=n)}return this.#i({type:i.t.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),r}catch(e){throw this.#i({type:i.t.DecryptError,error:s.s(e),durationMs:Date.now()-p,handles:m}),A(e,t.errorMessage,t.delegated)}}#o(e,t){let r=t[e.handle];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for handle ${e.handle} on contract ${e.contractAddress}`);return}e.value=r}#s(t,n,r=!1){return t instanceof e.r?t:A(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}},De=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:r,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new w(`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)(r);if(s===c)throw new g(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new x(`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)):i.i,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 b(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#r(e,i.a(u,s,o,d),`Delegation transaction failed`,i.t.DelegationSubmitted,o)}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=(0,l.getAddress)(r),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 v(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#r(e,i.c(c,o,a),`Revoke delegation transaction failed`,i.t.RevokeDelegationSubmitted,a)}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===i.i?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=await this.#t.getAclAddress();return this.#e.readContract(i.o(r,(0,l.getAddress)(t),(0,l.getAddress)(n),(0,l.getAddress)(e)))}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 v||t instanceof y){let n=(0,l.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,l.getAddress)(e),a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:r,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new v(`No active delegation from ${a} to ${o} for ${r}`);if(s!==i.i&&s<=await this.#e.getBlockTimestamp())throw new y(`Delegation from ${a} to ${o} for ${r} has expired`)}async#r(t,n,r,a,o){try{let e=await t.writeContract(n);return a===i.t.DelegationSubmitted?this.#n({type:i.t.DelegationSubmitted,txHash:e},o):this.#n({type:i.t.RevokeDelegationSubmitted,txHash:e},o),{txHash:e,receipt:await this.#e.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:k(t)||new d(r,{cause:t})}}},Oe=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(t){let r=Date.now();try{this.#t({type:i.t.EncryptStart},t.contractAddress);let e=await this.#e.encrypt(t);return this.#t({type:i.t.EncryptEnd,durationMs:Date.now()-r},t.contractAddress),e}catch(a){throw this.#t({type:i.t.EncryptError,error:s.s(a),durationMs:Date.now()-r},t.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}},ke=class{relayer;provider;signer;storage;registry;#e;#t;#n=new Set;#r;#i;#a;#o;#s;#c;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=new xe(e.storage),this.#t=e.onEvent??function(){},this.#a=new De({provider:this.provider,relayer:this.relayer,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.#s=new Oe({relayer:this.relayer,emitEvent:(e,t)=>this.emitEvent(e,t)});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);if(this.registry=new r.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#e=e.registryTTL,e.signer){let t=e.signer;this.#i=new r.d({relayer:this.relayer,signer:t,keypairTTL:e.keypairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage}),this.#o=new Ee({cache:this.#r,credentialService:this.#i,delegationService:this.#a,relayer:this.relayer,emitEvent:e=>this.emitEvent(e)}),this.#c=t.walletAccount.subscribe(e=>{this.#d(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})})}else this.#i=void 0,this.#o=void 0}requireSigner(e){if(!this.signer)throw new r.g(e);return this.signer}#l(e){if(!this.#i)throw new r.g(e);return this.#i}#u(e){if(!this.#o)throw new r.g(e);return this.#o}onWalletAccountChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireAlignedWalletAccount(e){let t=this.requireSigner(e),n;try{n=t.requireWalletAccount(e)}catch(i){if(!(i instanceof r.v)||!t.refreshWalletAccount)throw i;await t.refreshWalletAccount(),n=t.requireWalletAccount(e)}let i=await this.provider.getChainId();if(n.chainId!==i)throw new h({operation:e,signerChainId:n.chainId,providerChainId:i});return n}async requireChainAlignment(e){return(await this.requireAlignedWalletAccount(e)).chainId}async#d(e){let t=e.previous,n=e.next,i=this.#i;i&&await r.h(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n)),t&&await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(t.address));let a=n?.chainId;a!==void 0&&r.h(`switch relayer chain`,()=>this.relayer.switchChain(a)),await Promise.all(Array.from(this.#n,e=>r.h(`wallet account listener`,()=>e({previous:t,next:n}))))}createReadonlyToken(e){return new i.n(this,e)}createToken(e,t){return new ve(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 r.o({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){if(e.length===0)return;let t=this.#l(`allow`);await this.requireChainAlignment(`allow`),await t.allow(e)}async allowAs(e,t){if(t.length===0)return;let n=this.#l(`allowAs`);await this.requireChainAlignment(`allowAs`),await n.allow(t,e)}async isAllowed(e){return this.#i?this.#i.isAllowed(e):!1}async isAllowedAs(e,t){return this.#i?this.#i.isAllowed(t,e):!1}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.requireSigner(`delegateDecryption`),i=await this.requireAlignedWalletAccount(`delegateDecryption`);return this.#a.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.requireSigner(`revokeDelegation`),r=await this.requireAlignedWalletAccount(`revokeDelegation`);return this.#a.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isDelegated(e){return this.#a.isDelegated(e)}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){return this.#a.getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n})}async userDecrypt(e){let t=this.#u(`userDecrypt`),n=await this.requireAlignedWalletAccount(`userDecrypt`);return t.userDecrypt(e,n.address)}async delegatedUserDecrypt(e,t,n=t){let r=this.#u(`delegatedUserDecrypt`),i=await this.requireAlignedWalletAccount(`delegatedUserDecrypt`);return r.delegatedUserDecrypt(e,t,i.address,n)}async delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r}){let i=this.#u(`delegatedBatchDecryptHandlesAs`),a=await this.requireAlignedWalletAccount(`delegatedBatchDecryptHandlesAs`);return i.delegatedBatchDecryptHandlesAs({handles:e,delegatorAddress:t,delegateAddress:a.address,accountAddress:n,maxConcurrency:r})}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw A(e,`Public decryption failed`)}}async encrypt(e){return this.#s.encrypt(e)}async revokePermits(e){let t=this.#l(`revokePermits`),n=(0,l.getAddress)((await this.requireAlignedWalletAccount(`revokePermits`)).address);try{await t.revokePermits(e)}finally{await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(n))}}async clearCredentials(){let e=this.#l(`clearCredentials`),t=(0,l.getAddress)((await this.requireAlignedWalletAccount(`clearCredentials`)).address);try{await e.clearCredentials()}finally{await r.h(`clear decrypt cache`,()=>this.#r.clearForRequester(t))}}dispose(){this.#c?.(),this.#c=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${r.f(e)}`}const Ae=o.f([r.m.transform(e=>({unwrapTxHash:e})),o.l({version:o.s(1),unwrapTxHash:r.m,unwrapRequestId:r.m.optional()}).transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t}))]);async function je(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 Me(e,t){return(await Ne(e,t))?.unwrapTxHash??null}async function Ne(e,t){let n=Q(t),r=await e.get(n);if(r==null)return null;let i=Ae.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Pe(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Fe=new $;exports.ACL_TOPICS=_e,exports.AclPausedError=C,exports.AclTopics=J,exports.ApprovalFailedError=u,exports.BalanceCheckUnavailableError=D,exports.BaseSigner=r.t,exports.ChainMismatchError=h,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=r.a,exports.DelegationContractIsSelfError=S,exports.DelegationCooldownError=_,exports.DelegationDelegateEqualsContractError=x,exports.DelegationExpirationTooSoonError=w,exports.DelegationExpiredError=y,exports.DelegationExpiryUnchangedError=b,exports.DelegationNotFoundError=v,exports.DelegationNotPropagatedError=T,exports.DelegationSelfNotAllowedError=g,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=te,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=t.d,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=o.n,exports.InsufficientConfidentialBalanceError=ee,exports.InsufficientERC20BalanceError=E,exports.InvalidKeypairError=p,exports.KeypairExpiredError=f,exports.MemoryStorage=r.l,exports.MutableWalletAccountStore=r.n,exports.NoCiphertextError=m,exports.ReadonlyToken=i.n,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=r.g,exports.SignerRequiredError=r._,exports.SigningFailedError=t.L,exports.SigningRejectedError=t.R,exports.TOKEN_TOPICS=fe,exports.Token=ve,exports.Topics=P,exports.TransactionRevertedError=d,exports.WalletAccountNotReadyError=r.v,exports.WalletNotConnectedError=r.y,exports.WrappersRegistry=r.o,exports.ZERO_HANDLE=i.l,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=ke,exports.ZamaSDKEvents=i.t,exports.allowanceContract=t.g,exports.anvil=c.t,exports.approveContract=t._,exports.balanceOfContract=t.v,exports.chains=c.n,exports.chromeSessionStorage=Fe,exports.clearPendingUnshield=Pe,exports.cleartext=re,exports.confidentialBalanceOfContract=t.D,exports.confidentialTotalSupplyContract=t.O,exports.confidentialTransferContract=t.k,exports.confidentialTransferFromContract=t.A,exports.createConfig=ae,exports.createWalletAccountStore=r.r,exports.decimalsContract=t.y,exports.decodeAclEvent=pe,exports.decodeAclEvents=me,exports.decodeConfidentialTransfer=V,exports.decodeDelegatedForUserDecryption=Y,exports.decodeOnChainEvent=K,exports.decodeOnChainEvents=ue,exports.decodeRevokedDelegationForUserDecryption=X,exports.decodeUnwrapFinalized=W,exports.decodeUnwrapRequested=U,exports.decodeUnwrappedFinalized=ce,exports.decodeUnwrappedStarted=G,exports.decodeWrapped=H,exports.delegateForUserDecryptionContract=i.a,exports.finalizeUnwrapContract=t.C,exports.findDelegatedForUserDecryption=he,exports.findRevokedDelegationForUserDecryption=ge,exports.findUnwrapRequested=q,exports.findWrapped=de,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=i.o,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.w,exports.isConfidentialTokenContract=t.f,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.p,exports.isHandleDelegatedContract=i.s,exports.isOperatorContract=t.j,exports.isZeroHandle=i.u,exports.loadPendingUnshield=Me,exports.loadPendingUnshieldRequest=Ne,exports.mainnet=c.a,exports.matchAclRevert=k,exports.matchZamaError=e.a,exports.memoryStorage=r.u,exports.nameContract=t.x,exports.rateContract=t.M,exports.resolveChainRelayers=r.s,exports.resolveStorage=r.c,exports.revokeDelegationContract=i.c,exports.savePendingUnshield=je,exports.sepolia=c.o,exports.setOperatorContract=t.N,exports.supportsInterfaceContract=t.h,exports.symbolContract=t.S,exports.totalSupplyContract=t.P,exports.transferAndCallContract=M,exports.underlyingContract=t.T,exports.unwrapContract=t.F,exports.unwrapFromBalanceContract=t.I,exports.wrapContract=t.E;
2
2
  //# sourceMappingURL=index.cjs.map