@zama-fhe/sdk 3.7.0-beta.1 → 3.7.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{S as e,_ as t,a as n,b as r,c as i,d as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,v as ee}from"./relayer-CVKO9GmQ.js";import{A as g,B as _,C as te,D as v,E as ne,F as re,G as y,I as ie,J as b,K as ae,L as oe,M as x,O as se,P as ce,R as S,S as le,T as ue,U as C,V as de,W as fe,X as pe,Y as me,a as he,b as ge,c as _e,d as ve,g as ye,h as be,i as xe,j as w,k as Se,l as T,m as Ce,n as we,p as Te,q as Ee,r as De,s as Oe,t as ke,u as Ae,v as E,w as je,x as D,z as O}from"./erc165-DbMOt-s6.js";import{n as Me,r as k,t as A}from"./encryption-BKoalB4o.js";import{_ as j,a as M,c as Ne,d as Pe,f as Fe,g as Ie,h as Le,l as Re,m as ze,n as Be,o as Ve,p as He,r as Ue,s as We,t as Ge,u as Ke}from"./token-CRJ8eCr7.js";import{C as qe,T as Je,_ as Ye,a as Xe,c as Ze,d as Qe,f as $e,g as et,h as tt,i as nt,l as rt,m as it,n as at,o as ot,p as st,r as ct,s as lt,t as ut,u as dt,v as ft,w as pt,y as mt}from"./wrapped-token-BOtzaSAY.js";import{t as ht}from"./cleartext-iE4sWgSP.js";import{a as gt,c as _t,d as vt,f as yt,i as bt,l as xt,n as St,o as N,p as Ct,r as wt,s as Tt,t as Et,u as Dt}from"./base-signer-D5Cwv7yb.js";import{n as P,r as Ot,s as kt,t as At}from"./primitives-Cym-3HKa.js";import{t as F}from"./validation-BRu06AM_.js";import{a as jt,i as Mt,n as Nt,o as Pt,r as Ft,s as It,t as Lt}from"./wrappers-registry-Cm3JJeqx.js";import{a as Rt,c as zt,i as Bt,l as Vt,n as Ht,o as Ut,r as Wt,s as Gt,t as Kt,u as qt}from"./chains-ByyCdrrd.js";import{r as Jt,t as Yt}from"./assertions-Ca1ePdRJ.js";import{getAddress as I,size as Xt}from"viem";import{z as L}from"zod/mini";function Zt(e,t){if(e instanceof p){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var R=class extends p{encryptedValue;contractAddress;account;constructor(e,t){super(c.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},z=class extends p{constructor(e,t){super(c.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},B=class extends p{constructor(e,t){super(c.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},V=class extends p{constructor(e,t){super(c.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},H=class extends p{constructor(e,t){super(c.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},U=class extends p{constructor(e,t){super(c.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},W=class extends p{constructor(e,t){super(c.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Qt=class extends p{constructor(e,t){super(c.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},$t=class extends p{constructor(e,t){super(c.AclPaused,e,t),this.name=`AclPausedError`}},G=class extends p{constructor(e,t){super(c.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},K=class extends p{constructor(e,t){super(c.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const en=[A,y,u,K,de,_,R,j,C,b];function q(e,n,c={}){if(en.some(t=>e instanceof t))return e;let d=e instanceof Error?e.message:n;if(e instanceof Error&&f(e.message))return new C(e.message,{cause:e});if(t(e))return new b(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&l(e.message))return c.isDelegated?new K(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new R({encryptedValue:r(e.message)??``,contractAddress:c.contractAddress??``,account:c.account??``},{cause:e});if(a(e))return new j(d,{cause:e,retryAfter:i(e)});let p=m(e);return p===void 0&&ee(e)?new j(d,{cause:e,retryAfter:i(e)}):p===400?new y(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):c.isDelegated&&p===500?new K(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):s(e)||p!==void 0?new u(d,p,{cause:e,retryAfter:i(e),retryable:o(e)||void 0}):new A(n,{cause:e})}function tn(e,t){if(e instanceof p)return e;let n=m(e),r=o(e);return n!==void 0||s(e)?new u(e instanceof Error?e.message:t,n,{cause:e,retryAfter:i(e),retryable:r||void 0}):new k(t,{cause:e})}const J=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function Y(e,t,n,r){return{address:e,abi:J,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function X(e,t,n){return{address:e,abi:J,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function nn(e,t,n,r){return{address:e,abi:J,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function rn(e,t,n,r,i){return{address:e,abi:J,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const Z=2n**64n-1n;function an(e){return bt(e.signer,e.provider,e)}var on=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return S(this.#r,e)}#s(e,t){throw this.#a({type:x.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await Ve(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await Ve(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}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 warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){let n;try{n=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await n.registerPermit(e,t),await this.#c(e.signerAddress)}async revokePermits(e){let t=this.#o(`revokePermits`),n=I((await M(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=I((await M(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await w(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},sn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return S(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await M(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await M(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},cn=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return S(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await M(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,t)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await M(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,r)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{Jt(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw q(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await M(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},ln=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}},un=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 dn=new un,fn=L.union([L.bigint(),L.boolean(),P]),pn=L.array(L.string());var mn=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=fn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=I(e),n=`${this.#n}:${t}:`,r=await this.#l(),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.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${I(e)}:${I(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=pn.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function hn(e,t){let n=gn(e,t);if(!n)throw new A(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function gn(e,t){let n=At(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const _n=e=>new Promise(t=>setTimeout(t,e));var vn=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=I(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=I(t),o=I(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:I(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof K))throw t;await _n(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)}));if(o.length===0)return{items:o};let s=I(r);try{let e=await this.delegatedDecryptValues(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#d(t,e);return{items:o}}catch(e){if(Ke(e))throw e;if(o.length===1){let[n=this.#p()]=o;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:I(t)}),{items:o}}}let c=!1,l;if(await Ue(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#d(e,r)}catch(n){if(Ke(n)){c=!0,l??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:I(t)})}}),i),l!==void 0)throw l;return{items:o}}async#o(e,t,n,r){let i=hn(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&f(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(t,n,r,i={spent:!1}){if(t.length===0)return{};let a=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)})),o={},s=[];for(let e of a)Re(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw ee(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?u.push(e):o[e.encryptedValue]=t}if(u.length===0)return o;let d=await this.#t.grantPermit(c,n.delegator),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 m=[];for(let[e,t]of f)for(let n of Ne(t))m.push({contractAddress:e,encryptedValues:n});let h=Date.now(),g=u.map(e=>e.encryptedValue);try{this.#i({type:x.DecryptStart,encryptedValues:g});try{await this.#c(n,d,m,o,r)}catch(e){if(!(e instanceof b)||i.spent)throw e;let t=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,n.delegator,t)}catch(e){throw e instanceof _?new b(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(n,d,m.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,r)}let e={};for(let t of g){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:x.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),o}catch(t){let r=t instanceof p&&t.cause instanceof Error?t.cause:t;throw this.#i({type:x.DecryptError,error:e(r),durationMs:Date.now()-h,encryptedValues:g}),q(t,n.errorMessage,{isDelegated:n.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await Ue(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof b)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw q(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new A(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new A(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new j(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:i(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new A(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof p?e:q(e,t,n)}#p(){throw new A(`Batch delegated decryption invariant failed: missing item`)}async#m(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}};const Q={AlreadyDelegatedOrRevokedInSameBlock:e=>new B(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new Qt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new $t(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new z(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new W(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new G(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new U(`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 yn(e){return Object.hasOwn(Q,e)}function bn(e,t){let n=Je(e);if(n&&yn(n))return Q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Q))if(r.includes(e))return n(t);return null}var xn=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new G(`Expiration date must be at least 1 hour in the future`);let a=I(t),o=I(n),s=I(r);if(o===s)throw new z(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new W(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):Z,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new U(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:Y(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=I(t),a=I(n),o=I(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new V(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:X(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===Z?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(nn(r,I(t),I(n),I(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Be({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof O))return;let t=bn(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 V||t instanceof H){let n=I(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=I(e),i=I(t),a=I(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new V(`No active delegation from ${i} to ${a} for ${r}`):new H(`Delegation from ${i} to ${a} for ${r} has expired`)}},Sn=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,n){let r=Date.now(),i=I(t.contractAddress);try{this.#t({type:x.EncryptStart},i);let e=await this.#e.relayer.encryptValues({...t,options:n});return this.#t({type:x.EncryptEnd,durationMs:Date.now()-r},i),e}catch(t){throw this.#t({type:x.EncryptError,error:e(t),durationMs:Date.now()-r},i),tn(t,`Encryption failed`)}}},Cn=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await w(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await w(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await w(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>w(`wallet account listener`,()=>t(e),this.#i)))}};const $=L.object({kind:L.literal(`ConfidentialTransfer`),from:P,token:P,to:P,amount:L.bigint()}),wn=L.object({kind:L.literal(`ConfidentialTransferFrom`),from:P,token:P,owner:P,to:P,amount:L.bigint()}),Tn=L.object({kind:L.literal(`SetOperator`),from:P,token:P,operator:P,until:kt}),En=L.object({kind:L.literal(`Unwrap`),from:P,token:P,to:P,amount:L.bigint()}),Dn=L.object({kind:L.literal(`UnwrapAll`),from:P,token:P,to:P}),On=L.object({kind:L.literal(`FinalizeUnwrap`),from:P,wrapper:P,unwrapRequestIdOrAmount:Ot}),kn=L.object({kind:L.literal(`ApproveUnderlying`),from:P,underlying:P,spender:P,amount:L.bigint()}),An=L.object({kind:L.literal(`Wrap`),from:P,wrapper:P,to:P,amount:L.bigint()}),jn=Ot.check(L.refine(e=>e===`0x`||Xt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),Mn=L.object({kind:L.literal(`TransferAndCall`),from:P,underlying:P,wrapper:P,amount:L.bigint(),recipientData:L.optional(jn)}),Nn=L.object({kind:L.literal(`DelegateDecryption`),from:P,contractAddress:P,delegateAddress:P,expirationDate:L.optional(L.date())}),Pn=L.object({kind:L.literal(`RevokeDelegation`),from:P,contractAddress:P,delegateAddress:P});L.discriminatedUnion(`kind`,[$,wn,Tn,En,Dn,On,kn,An,Mn,Nn,Pn]);const Fn=L.strictObject({maxFeePerGas:L.bigint(),maxPriorityFeePerGas:L.bigint()}),In=L.object({nonce:L.optional(L.int().check(L.nonnegative())),gasLimit:L.optional(L.bigint()),fees:L.optional(Fn)}),Ln=L.object({address:P,abi:L.array(L.unknown()),functionName:L.string(),args:L.array(L.unknown()),value:L.optional(L.bigint()),gas:L.optional(L.bigint())}),Rn=L.extend(In,{from:P,calldata:Ln});var zn=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=F(In,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new h(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i=F(Rn,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new h(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=F($,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for ConfidentialTransfer`);return E(e.token,e.to,r,n)}async#a(e){e=F(wn,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for ConfidentialTransferFrom`);return ge(e.token,e.owner,e.to,r,n)}#o(e){return e=F(Tn,e),ue(e.token,e.operator,e.until)}async#s(e){e=F(En,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for Unwrap`);return v(e.token,e.from,e.to,r,n)}async#c(e){e=F(Dn,e);let t=await this.#e.readContract(be(e.token,e.from));return se(e.token,e.from,e.to,t)}async#l(e){e=F(On,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw q(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return Yt(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),D(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=F(kn,e),T(e.underlying,e.spender,e.amount)}#d(e){return e=F(An,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=F(Mn,e),qe(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=F(Nn,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new G(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new z(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new W(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):Z;return Y(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=F(Pn,e),X(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Bn(e){if(!(!Object.hasOwn(e,`transportKeyPairDerivationSecret`)||e.transportKeyPairDerivationSecret!==void 0))throw new h(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Vn(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof t!=`function`))throw new h(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function Hn(e){if(e===void 0)return;let t=F(_t,e);return new xt(typeof t==`string`?t:new Uint8Array(t))}var Un=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Bn(t),Vn(t.transportKeyPairDerivationSecret);let n=Hn(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new mn(e.storage,this.#i),this.#u=new xn({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new N({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new Tt({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new vn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Sn({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Cn({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new zn({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new on({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new sn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new cn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new ln(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new N({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new Ge(this,e)}createWrappedToken(e){return new ut(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{at as ACL_TOPICS,$t as AclPausedError,ct as AclTopics,Pe as BalanceCheckUnavailableError,Et as BaseSigner,Ie as ChainMismatchError,un as ChromeSessionStorage,h as ConfigurationError,cn as Decryption,A as DecryptionFailedError,gt as DefaultRegistryAddresses,Qt as DelegationContractIsSelfError,B as DelegationCooldownError,W as DelegationDelegateEqualsContractError,G as DelegationExpirationTooSoonError,H as DelegationExpiredError,U as DelegationExpiryUnchangedError,V as DelegationNotFoundError,K as DelegationNotPropagatedError,z as DelegationSelfNotAllowedError,sn as Delegations,ke as ERC1363_INTERFACE_ID,Fe as ERC20ReadFailedError,we as ERC7984_INTERFACE_ID,De as ERC7984_WRAPPER_INTERFACE_ID,Me as EncryptOffloadUnavailableError,k as EncryptionFailedError,yt as IndexedDBStorage,He as InsufficientAllowanceError,ze as InsufficientConfidentialBalanceError,Le as InsufficientERC20BalanceError,C as InvalidTransportKeyPairError,fe as KeyWrappingError,Dt as MemoryStorage,St as MutableWalletAccountStore,y as NoCiphertextError,R as NotEntitledError,ln as Offline,on as Permits,ae as PreparedPermitChainMismatchError,Ee as PreparedPermitExpiredError,u as RelayerRequestFailedError,b as RevokedKmsContextError,j as RpcRateLimitError,ce as SignerNotConfiguredError,re as SignerRequiredError,_ as SigningFailedError,de as SigningRejectedError,nt as TOKEN_TOPICS,Ge as Token,Xe as Topics,O as TransactionRevertedError,me as TransportKeyPairChangedError,pe as TransportKeyPairExpiredError,pt as UnshieldAlreadyFinalizedError,ie as WalletAccountNotReadyError,oe as WalletNotConnectedError,ut as WrappedToken,N as WrappersRegistry,We as ZERO_ENCRYPTED_VALUE,p as ZamaError,c as ZamaErrorCode,Un as ZamaSDK,x as ZamaSDKEvents,_e as allowanceContract,Kt as anvil,T as approveContract,Ae as balanceOfContract,Ht as bscTestnet,Wt as chains,dn as chromeSessionStorage,ht as cleartext,be as confidentialBalanceOfContract,ye as confidentialTotalSupplyContract,E as confidentialTransferContract,ge as confidentialTransferFromContract,an as createConfig,wt as createWalletAccountStore,ve as decimalsContract,ot as decodeAclEvent,lt as decodeAclEvents,Ze as decodeConfidentialTransfer,rt as decodeDelegatedForUserDecryption,dt as decodeOnChainEvent,Qe as decodeOnChainEvents,$e as decodeRevokedDelegationForUserDecryption,st as decodeUnwrapFinalized,it as decodeUnwrapRequested,tt as decodeWrap,Y as delegateForUserDecryptionContract,D as finalizeUnwrapContract,et as findDelegatedForUserDecryption,Ye as findRevokedDelegationForUserDecryption,ft as findUnwrapRequested,mt as findWrap,Lt as getConfidentialTokenAddressContract,nn as getDelegationExpiryContract,Nt as getTokenAddressContract,Ft as getTokenPairContract,Mt as getTokenPairsContract,jt as getTokenPairsLengthContract,Pt as getTokenPairsSliceContract,Bt as hardhat,Rt as hoodi,Ct as indexedDBStorage,le as inferredTotalSupplyContract,Ut as ingenTestnet,xe as isConfidentialTokenContract,It as isConfidentialTokenValidContract,he as isConfidentialWrapperContract,Re as isEncryptedValueZero,rn as isHandleDelegatedContract,te as isOperatorContract,n as isRetryable,Gt as mainnet,Zt as matchZamaError,vt as memoryStorage,Te as nameContract,zt as polygon,Vt as polygonAmoy,je as rateContract,d as retryAfterSeconds,X as revokeDelegationContract,qt as sepolia,ue as setOperatorContract,Oe as supportsInterfaceContract,Ce as symbolContract,qe as transferAndCallContract,ne as underlyingContract,v as unwrapContract,se as unwrapFromBalanceContract,Se as unwrapRequesterContract,g as wrapContract};
1
+ import{S as e,_ as t,a as n,b as r,c as i,d as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,v as ee}from"./relayer-CVKO9GmQ.js";import{A as g,B as _,C as te,D as v,E as ne,F as re,G as y,I as ie,J as b,K as ae,L as oe,M as x,O as se,P as ce,R as S,S as le,T as ue,U as C,V as de,W as fe,X as pe,Y as me,a as he,b as ge,c as _e,d as ve,g as ye,h as be,i as xe,j as w,k as Se,l as T,m as Ce,n as we,p as Te,q as Ee,r as De,s as Oe,t as ke,u as Ae,v as E,w as je,x as D,z as O}from"./erc165-DbMOt-s6.js";import{n as Me,r as k,t as A}from"./encryption-BKoalB4o.js";import{_ as j,a as M,c as Ne,d as Pe,f as Fe,g as Ie,h as Le,l as Re,m as ze,n as Be,o as Ve,p as He,r as Ue,s as We,t as Ge,u as Ke}from"./token-CRJ8eCr7.js";import{C as qe,T as Je,_ as Ye,a as Xe,c as Ze,d as Qe,f as $e,g as et,h as tt,i as nt,l as rt,m as it,n as at,o as ot,p as st,r as ct,s as lt,t as ut,u as dt,v as ft,w as pt,y as mt}from"./wrapped-token-BOtzaSAY.js";import{t as ht}from"./cleartext-PCpNqRGV.js";import{a as gt,c as _t,d as vt,f as yt,i as bt,l as xt,n as St,o as N,p as Ct,r as wt,s as Tt,t as Et,u as Dt}from"./base-signer-D5Cwv7yb.js";import{n as P,r as Ot,s as kt,t as At}from"./primitives-Cym-3HKa.js";import{t as F}from"./validation-BRu06AM_.js";import{a as jt,i as Mt,n as Nt,o as Pt,r as Ft,s as It,t as Lt}from"./wrappers-registry-Cm3JJeqx.js";import{a as Rt,c as zt,i as Bt,l as Vt,n as Ht,o as Ut,r as Wt,s as Gt,t as Kt,u as qt}from"./chains-ByyCdrrd.js";import{r as Jt,t as Yt}from"./assertions-Ca1ePdRJ.js";import{getAddress as I,size as Xt}from"viem";import{z as L}from"zod/mini";function Zt(e,t){if(e instanceof p){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var R=class extends p{encryptedValue;contractAddress;account;constructor(e,t){super(c.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},z=class extends p{constructor(e,t){super(c.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},B=class extends p{constructor(e,t){super(c.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},V=class extends p{constructor(e,t){super(c.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},H=class extends p{constructor(e,t){super(c.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},U=class extends p{constructor(e,t){super(c.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},W=class extends p{constructor(e,t){super(c.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Qt=class extends p{constructor(e,t){super(c.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},$t=class extends p{constructor(e,t){super(c.AclPaused,e,t),this.name=`AclPausedError`}},G=class extends p{constructor(e,t){super(c.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},K=class extends p{constructor(e,t){super(c.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const en=[A,y,u,K,de,_,R,j,C,b];function q(e,n,c={}){if(en.some(t=>e instanceof t))return e;let d=e instanceof Error?e.message:n;if(e instanceof Error&&f(e.message))return new C(e.message,{cause:e});if(t(e))return new b(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&l(e.message))return c.isDelegated?new K(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new R({encryptedValue:r(e.message)??``,contractAddress:c.contractAddress??``,account:c.account??``},{cause:e});if(a(e))return new j(d,{cause:e,retryAfter:i(e)});let p=m(e);return p===void 0&&ee(e)?new j(d,{cause:e,retryAfter:i(e)}):p===400?new y(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):c.isDelegated&&p===500?new K(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):s(e)||p!==void 0?new u(d,p,{cause:e,retryAfter:i(e),retryable:o(e)||void 0}):new A(n,{cause:e})}function tn(e,t){if(e instanceof p)return e;let n=m(e),r=o(e);return n!==void 0||s(e)?new u(e instanceof Error?e.message:t,n,{cause:e,retryAfter:i(e),retryable:r||void 0}):new k(t,{cause:e})}const J=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function Y(e,t,n,r){return{address:e,abi:J,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function X(e,t,n){return{address:e,abi:J,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function nn(e,t,n,r){return{address:e,abi:J,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function rn(e,t,n,r,i){return{address:e,abi:J,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const Z=2n**64n-1n;function an(e){return bt(e.signer,e.provider,e)}var on=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return S(this.#r,e)}#s(e,t){throw this.#a({type:x.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await Ve(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await Ve(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}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 warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){let n;try{n=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await n.registerPermit(e,t),await this.#c(e.signerAddress)}async revokePermits(e){let t=this.#o(`revokePermits`),n=I((await M(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=I((await M(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await w(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},sn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return S(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await M(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await M(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},cn=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return S(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await M(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,t)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await M(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,r)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{Jt(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw q(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await M(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},ln=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}},un=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 dn=new un,fn=L.union([L.bigint(),L.boolean(),P]),pn=L.array(L.string());var mn=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=fn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=I(e),n=`${this.#n}:${t}:`,r=await this.#l(),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.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${I(e)}:${I(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=pn.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function hn(e,t){let n=gn(e,t);if(!n)throw new A(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function gn(e,t){let n=At(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const _n=e=>new Promise(t=>setTimeout(t,e));var vn=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=I(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=I(t),o=I(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:I(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof K))throw t;await _n(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)}));if(o.length===0)return{items:o};let s=I(r);try{let e=await this.delegatedDecryptValues(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#d(t,e);return{items:o}}catch(e){if(Ke(e))throw e;if(o.length===1){let[n=this.#p()]=o;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:I(t)}),{items:o}}}let c=!1,l;if(await Ue(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#d(e,r)}catch(n){if(Ke(n)){c=!0,l??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:I(t)})}}),i),l!==void 0)throw l;return{items:o}}async#o(e,t,n,r){let i=hn(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&f(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(t,n,r,i={spent:!1}){if(t.length===0)return{};let a=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)})),o={},s=[];for(let e of a)Re(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw ee(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?u.push(e):o[e.encryptedValue]=t}if(u.length===0)return o;let d=await this.#t.grantPermit(c,n.delegator),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 m=[];for(let[e,t]of f)for(let n of Ne(t))m.push({contractAddress:e,encryptedValues:n});let h=Date.now(),g=u.map(e=>e.encryptedValue);try{this.#i({type:x.DecryptStart,encryptedValues:g});try{await this.#c(n,d,m,o,r)}catch(e){if(!(e instanceof b)||i.spent)throw e;let t=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,n.delegator,t)}catch(e){throw e instanceof _?new b(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(n,d,m.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,r)}let e={};for(let t of g){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:x.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),o}catch(t){let r=t instanceof p&&t.cause instanceof Error?t.cause:t;throw this.#i({type:x.DecryptError,error:e(r),durationMs:Date.now()-h,encryptedValues:g}),q(t,n.errorMessage,{isDelegated:n.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await Ue(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof b)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw q(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new A(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new A(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new j(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:i(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new A(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof p?e:q(e,t,n)}#p(){throw new A(`Batch delegated decryption invariant failed: missing item`)}async#m(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}};const Q={AlreadyDelegatedOrRevokedInSameBlock:e=>new B(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new Qt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new $t(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new z(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new W(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new G(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new U(`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 yn(e){return Object.hasOwn(Q,e)}function bn(e,t){let n=Je(e);if(n&&yn(n))return Q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Q))if(r.includes(e))return n(t);return null}var xn=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new G(`Expiration date must be at least 1 hour in the future`);let a=I(t),o=I(n),s=I(r);if(o===s)throw new z(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new W(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):Z,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new U(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:Y(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=I(t),a=I(n),o=I(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new V(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:X(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===Z?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(nn(r,I(t),I(n),I(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Be({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof O))return;let t=bn(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 V||t instanceof H){let n=I(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=I(e),i=I(t),a=I(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new V(`No active delegation from ${i} to ${a} for ${r}`):new H(`Delegation from ${i} to ${a} for ${r} has expired`)}},Sn=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,n){let r=Date.now(),i=I(t.contractAddress);try{this.#t({type:x.EncryptStart},i);let e=await this.#e.relayer.encryptValues({...t,options:n});return this.#t({type:x.EncryptEnd,durationMs:Date.now()-r},i),e}catch(t){throw this.#t({type:x.EncryptError,error:e(t),durationMs:Date.now()-r},i),tn(t,`Encryption failed`)}}},Cn=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await w(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await w(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await w(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>w(`wallet account listener`,()=>t(e),this.#i)))}};const $=L.object({kind:L.literal(`ConfidentialTransfer`),from:P,token:P,to:P,amount:L.bigint()}),wn=L.object({kind:L.literal(`ConfidentialTransferFrom`),from:P,token:P,owner:P,to:P,amount:L.bigint()}),Tn=L.object({kind:L.literal(`SetOperator`),from:P,token:P,operator:P,until:kt}),En=L.object({kind:L.literal(`Unwrap`),from:P,token:P,to:P,amount:L.bigint()}),Dn=L.object({kind:L.literal(`UnwrapAll`),from:P,token:P,to:P}),On=L.object({kind:L.literal(`FinalizeUnwrap`),from:P,wrapper:P,unwrapRequestIdOrAmount:Ot}),kn=L.object({kind:L.literal(`ApproveUnderlying`),from:P,underlying:P,spender:P,amount:L.bigint()}),An=L.object({kind:L.literal(`Wrap`),from:P,wrapper:P,to:P,amount:L.bigint()}),jn=Ot.check(L.refine(e=>e===`0x`||Xt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),Mn=L.object({kind:L.literal(`TransferAndCall`),from:P,underlying:P,wrapper:P,amount:L.bigint(),recipientData:L.optional(jn)}),Nn=L.object({kind:L.literal(`DelegateDecryption`),from:P,contractAddress:P,delegateAddress:P,expirationDate:L.optional(L.date())}),Pn=L.object({kind:L.literal(`RevokeDelegation`),from:P,contractAddress:P,delegateAddress:P});L.discriminatedUnion(`kind`,[$,wn,Tn,En,Dn,On,kn,An,Mn,Nn,Pn]);const Fn=L.strictObject({maxFeePerGas:L.bigint(),maxPriorityFeePerGas:L.bigint()}),In=L.object({nonce:L.optional(L.int().check(L.nonnegative())),gasLimit:L.optional(L.bigint()),fees:L.optional(Fn)}),Ln=L.object({address:P,abi:L.array(L.unknown()),functionName:L.string(),args:L.array(L.unknown()),value:L.optional(L.bigint()),gas:L.optional(L.bigint())}),Rn=L.extend(In,{from:P,calldata:Ln});var zn=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=F(In,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new h(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i=F(Rn,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new h(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=F($,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for ConfidentialTransfer`);return E(e.token,e.to,r,n)}async#a(e){e=F(wn,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for ConfidentialTransferFrom`);return ge(e.token,e.owner,e.to,r,n)}#o(e){return e=F(Tn,e),ue(e.token,e.operator,e.until)}async#s(e){e=F(En,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),r=t[0];if(!r)throw new k(`Encryption returned no handles for Unwrap`);return v(e.token,e.from,e.to,r,n)}async#c(e){e=F(Dn,e);let t=await this.#e.readContract(be(e.token,e.from));return se(e.token,e.from,e.to,t)}async#l(e){e=F(On,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw q(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return Yt(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),D(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=F(kn,e),T(e.underlying,e.spender,e.amount)}#d(e){return e=F(An,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=F(Mn,e),qe(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=F(Nn,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new G(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new z(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new W(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):Z;return Y(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=F(Pn,e),X(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Bn(e){if(!(!Object.hasOwn(e,`transportKeyPairDerivationSecret`)||e.transportKeyPairDerivationSecret!==void 0))throw new h(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Vn(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof t!=`function`))throw new h(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function Hn(e){if(e===void 0)return;let t=F(_t,e);return new xt(typeof t==`string`?t:new Uint8Array(t))}var Un=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Bn(t),Vn(t.transportKeyPairDerivationSecret);let n=Hn(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new mn(e.storage,this.#i),this.#u=new xn({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new N({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new Tt({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new vn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Sn({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Cn({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new zn({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new on({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new sn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new cn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new ln(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new N({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new Ge(this,e)}createWrappedToken(e){return new ut(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{at as ACL_TOPICS,$t as AclPausedError,ct as AclTopics,Pe as BalanceCheckUnavailableError,Et as BaseSigner,Ie as ChainMismatchError,un as ChromeSessionStorage,h as ConfigurationError,cn as Decryption,A as DecryptionFailedError,gt as DefaultRegistryAddresses,Qt as DelegationContractIsSelfError,B as DelegationCooldownError,W as DelegationDelegateEqualsContractError,G as DelegationExpirationTooSoonError,H as DelegationExpiredError,U as DelegationExpiryUnchangedError,V as DelegationNotFoundError,K as DelegationNotPropagatedError,z as DelegationSelfNotAllowedError,sn as Delegations,ke as ERC1363_INTERFACE_ID,Fe as ERC20ReadFailedError,we as ERC7984_INTERFACE_ID,De as ERC7984_WRAPPER_INTERFACE_ID,Me as EncryptOffloadUnavailableError,k as EncryptionFailedError,yt as IndexedDBStorage,He as InsufficientAllowanceError,ze as InsufficientConfidentialBalanceError,Le as InsufficientERC20BalanceError,C as InvalidTransportKeyPairError,fe as KeyWrappingError,Dt as MemoryStorage,St as MutableWalletAccountStore,y as NoCiphertextError,R as NotEntitledError,ln as Offline,on as Permits,ae as PreparedPermitChainMismatchError,Ee as PreparedPermitExpiredError,u as RelayerRequestFailedError,b as RevokedKmsContextError,j as RpcRateLimitError,ce as SignerNotConfiguredError,re as SignerRequiredError,_ as SigningFailedError,de as SigningRejectedError,nt as TOKEN_TOPICS,Ge as Token,Xe as Topics,O as TransactionRevertedError,me as TransportKeyPairChangedError,pe as TransportKeyPairExpiredError,pt as UnshieldAlreadyFinalizedError,ie as WalletAccountNotReadyError,oe as WalletNotConnectedError,ut as WrappedToken,N as WrappersRegistry,We as ZERO_ENCRYPTED_VALUE,p as ZamaError,c as ZamaErrorCode,Un as ZamaSDK,x as ZamaSDKEvents,_e as allowanceContract,Kt as anvil,T as approveContract,Ae as balanceOfContract,Ht as bscTestnet,Wt as chains,dn as chromeSessionStorage,ht as cleartext,be as confidentialBalanceOfContract,ye as confidentialTotalSupplyContract,E as confidentialTransferContract,ge as confidentialTransferFromContract,an as createConfig,wt as createWalletAccountStore,ve as decimalsContract,ot as decodeAclEvent,lt as decodeAclEvents,Ze as decodeConfidentialTransfer,rt as decodeDelegatedForUserDecryption,dt as decodeOnChainEvent,Qe as decodeOnChainEvents,$e as decodeRevokedDelegationForUserDecryption,st as decodeUnwrapFinalized,it as decodeUnwrapRequested,tt as decodeWrap,Y as delegateForUserDecryptionContract,D as finalizeUnwrapContract,et as findDelegatedForUserDecryption,Ye as findRevokedDelegationForUserDecryption,ft as findUnwrapRequested,mt as findWrap,Lt as getConfidentialTokenAddressContract,nn as getDelegationExpiryContract,Nt as getTokenAddressContract,Ft as getTokenPairContract,Mt as getTokenPairsContract,jt as getTokenPairsLengthContract,Pt as getTokenPairsSliceContract,Bt as hardhat,Rt as hoodi,Ct as indexedDBStorage,le as inferredTotalSupplyContract,Ut as ingenTestnet,xe as isConfidentialTokenContract,It as isConfidentialTokenValidContract,he as isConfidentialWrapperContract,Re as isEncryptedValueZero,rn as isHandleDelegatedContract,te as isOperatorContract,n as isRetryable,Gt as mainnet,Zt as matchZamaError,vt as memoryStorage,Te as nameContract,zt as polygon,Vt as polygonAmoy,je as rateContract,d as retryAfterSeconds,X as revokeDelegationContract,qt as sepolia,ue as setOperatorContract,Oe as supportsInterfaceContract,Ce as symbolContract,qe as transferAndCallContract,ne as underlyingContract,v as unwrapContract,se as unwrapFromBalanceContract,Se as unwrapRequesterContract,g as wrapContract};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{t as e}from"../fhevm-relayer-Cm-ZR1vP.js";import{t}from"../cleartext-iE4sWgSP.js";import{a as n,c as r,i,l as a,n as o,o as s,r as c,s as l,t as u,u as d}from"../chains-ByyCdrrd.js";import{AsyncLocalStorage as f}from"node:async_hooks";function p(t){return{type:`node`,createRelayer:(n,r)=>new e({chain:n,options:t,logger:r})}}var m=class{#e=new f;run(e){return this.#e.run(new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const h=new m;export{m as AsyncLocalMapStorage,u as anvil,h as asyncLocalStorage,o as bscTestnet,c as chains,t as cleartext,i as hardhat,n as hoodi,s as ingenTestnet,l as mainnet,p as node,r as polygon,a as polygonAmoy,d as sepolia};
1
+ import{t as e}from"../fhevm-relayer-CtrnKjJf.js";import{t}from"../cleartext-PCpNqRGV.js";import{a as n,c as r,i,l as a,n as o,o as s,r as c,s as l,t as u,u as d}from"../chains-ByyCdrrd.js";import{AsyncLocalStorage as f}from"node:async_hooks";function p(t){return{type:`node`,createRelayer:(n,r)=>new e({chain:n,options:t,logger:r})}}var m=class{#e=new f;run(e){return this.#e.run(new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const h=new m;export{m as AsyncLocalMapStorage,u as anvil,h as asyncLocalStorage,o as bscTestnet,c as chains,t as cleartext,i as hardhat,n as hoodi,s as ingenTestnet,l as mainnet,p as node,r as polygon,a as polygonAmoy,d as sepolia};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"../fhevm-relayer-Cm-ZR1vP.js";import{t as n}from"../validation-BRu06AM_.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n)=>new t({chain:e,options:s,offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
1
+ import{n as e,t}from"../fhevm-relayer-CtrnKjJf.js";import{t as n}from"../validation-BRu06AM_.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n)=>new t({chain:e,options:s,offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zama-fhe/sdk",
3
- "version": "3.7.0-beta.1",
3
+ "version": "3.7.0-beta.2",
4
4
  "description": "TypeScript SDK for Zama fhEVM confidential smart contracts",
5
5
  "keywords": [
6
6
  "blockchain",
@@ -188,7 +188,7 @@
188
188
  "devDependencies": {
189
189
  "@dfns/sdk": "^0.8.20",
190
190
  "@dfns/sdk-keysigner": "^0.8.20",
191
- "@tanstack/query-core": "^5.102.2",
191
+ "@tanstack/query-core": "^5.103.1",
192
192
  "comlink": "^4.4.2"
193
193
  },
194
194
  "peerDependencies": {