@zama-fhe/sdk 2.4.0 → 2.5.0-alpha.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.
@@ -1,2 +1,2 @@
1
- import{S as e,T as t,a as n,f as r,g as i,h as a,i as o,m as s,n as c,o as l,p as u,r as d,s as f,t as p,v as m,w as h}from"../wrappers-registry-BAz8Adry.js";import{t as g}from"../eip1193-subscribe-Cl_wlVuQ.js";import{ProviderRpcError as _,decodeFunctionResult as v,encodeFunctionData as y,getAddress as b,isHex as x}from"viem";import{BrowserProvider as S,ethers as C}from"ethers";var w=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new S(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return b(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:n,types:r,message:i}=e,{EIP712Domain:a,...o}=r,s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,[...t]])),c=await t.signTypedData(n,s,i);if(!x(c))throw TypeError(`Expected hex string, got: ${c}`);return c}async writeContract(e){let t=await this.#r(),n=new C.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n[e.functionName](...e.args,r);if(!x(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async readContract(e){let t=this.#i();return new C.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#i().waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}subscribe(e){return g(this.#n,()=>this.getAddress(),e)}};function T(e){return{to:e.address,data:y({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function E(e,t){let n=await e.call(T(t));if(!x(n))throw TypeError(`Expected hex string, got: ${n}`);return v({abi:t.abi,functionName:t.functionName,data:n})}async function D(e,t){let n=await e.sendTransaction(T(t));if(!x(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function O(e,t,n){return E(e,i(t,n))}function k(e,t){return E(e,s(t))}function A(e,t,n){return E(e,r(t,n))}function j(e,t,n,r,i){return D(e,m(t,n,r,i))}function M(e,t,n,r,i,a){return D(e,h(t,n,r,i,a))}function N(e,n,r,i,a){return D(e,t(n,r,i,a))}function P(e,t,n,r,i){return D(e,u(t,n,r,i))}function F(t,n,r,i){return D(t,e(n,r,i))}function I(e,t,n,r){return D(e,a(t,n,r))}function L(e,t){return E(e,o(t))}function R(e,t){return E(e,n(t))}function z(e,t,n,r){return E(e,l(t,n,r))}function B(e,t,n){return E(e,d(t,n))}function V(e,t,n){return E(e,p(t,n))}function H(e,t,n){return E(e,c(t,n))}function U(e,t,n){return E(e,f(t,n))}export{w as EthersSigner,_ as ProviderRpcError,O as readConfidentialBalanceOfContract,V as readConfidentialTokenAddressContract,U as readIsConfidentialTokenValidContract,A as readSupportsInterfaceContract,H as readTokenAddressContract,B as readTokenPairContract,L as readTokenPairsContract,R as readTokenPairsLengthContract,z as readTokenPairsSliceContract,k as readUnderlyingTokenContract,j as writeConfidentialTransferContract,P as writeFinalizeUnwrapContract,F as writeSetOperatorContract,M as writeUnwrapContract,N as writeUnwrapFromBalanceContract,I as writeWrapContract};
1
+ import{C as e,E as t,S as n,T as r,a as i,f as a,h as o,i as s,n as c,o as l,p as u,r as d,s as f,t as p,x as m,y as h}from"../wrappers-registry-DO0729Zi.js";import{t as g}from"../eip1193-subscribe-Cl_wlVuQ.js";import{ProviderRpcError as _,decodeFunctionResult as v,encodeFunctionData as y,getAddress as b,isHex as x}from"viem";import{BrowserProvider as S,ethers as C}from"ethers";var w=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new S(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return b(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:n,types:r,message:i}=e,{EIP712Domain:a,...o}=r,s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,[...t]])),c=await t.signTypedData(n,s,i);if(!x(c))throw TypeError(`Expected hex string, got: ${c}`);return c}async writeContract(e){let t=await this.#r(),n=new C.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n[e.functionName](...e.args,r);if(!x(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async readContract(e){let t=this.#i();return new C.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#i().waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}subscribe(e){return g(this.#n,()=>this.getAddress(),e)}};function T(e){return{to:e.address,data:y({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function E(e,t){let n=await e.call(T(t));if(!x(n))throw TypeError(`Expected hex string, got: ${n}`);return v({abi:t.abi,functionName:t.functionName,data:n})}async function D(e,t){let n=await e.sendTransaction(T(t));if(!x(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function O(e,t,n){return E(e,u(t,n))}function k(e,t){return E(e,r(t))}function A(e,t,n){return E(e,a(t,n))}function j(e,t,n,r,i){return D(e,o(t,n,r,i))}function M(e,t,n,r,i,a){return D(e,m(t,n,r,i,a))}function N(e,t,r,i,a){return D(e,n(t,r,i,a))}function P(t,n,r,i,a){return D(t,e(n,r,i,a))}function F(e,t,n,r){return D(e,h(t,n,r))}function I(e,n,r,i){return D(e,t(n,r,i))}function L(e,t){return E(e,s(t))}function R(e,t){return E(e,i(t))}function z(e,t,n,r){return E(e,l(t,n,r))}function B(e,t,n){return E(e,d(t,n))}function V(e,t,n){return E(e,p(t,n))}function H(e,t,n){return E(e,c(t,n))}function U(e,t,n){return E(e,f(t,n))}export{w as EthersSigner,_ as ProviderRpcError,O as readConfidentialBalanceOfContract,V as readConfidentialTokenAddressContract,U as readIsConfidentialTokenValidContract,A as readSupportsInterfaceContract,H as readTokenAddressContract,B as readTokenPairContract,L as readTokenPairsContract,R as readTokenPairsLengthContract,z as readTokenPairsSliceContract,k as readUnderlyingTokenContract,j as writeConfidentialTransferContract,P as writeFinalizeUnwrapContract,F as writeSetOperatorContract,M as writeUnwrapContract,N as writeUnwrapFromBalanceContract,I as writeWrapContract};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import { A as ReadContractConfig, C as GenericSigner, D as TransactionResult, E as TransactionReceipt, F as WriteFunctionName, M as ReadFunctionName, N as WriteContractArgs, O as ContractAbi, P as WriteContractConfig, Q as GenericLogger, S as GenericStorage, T as RawLog, _ as ShieldCallbacks, a as EncryptParams, b as DelegatedStoredCredentials, c as NetworkType, d as RelayerWebConfig, f as RelayerWebSecurityConfig, g as UnshieldOptions, h as TransferOptions, i as EncryptInput, j as ReadContractReturnType, k as ReadContractArgs, l as PublicDecryptResult, m as ShieldOptions, n as DelegatedUserDecryptParams, o as EncryptResult, p as UserDecryptParams, r as EIP712TypedData, s as Handle, t as ClearValueType, u as RelayerSDKStatus, v as TransferCallbacks, w as SignerLifecycleCallbacks, x as StoredCredentials, y as UnshieldCallbacks } from "./relayer-sdk.types-CGfXwKcB.js";
2
2
  import { t as RelayerSDK } from "./relayer-sdk-DPqytEbO.js";
3
3
  import { n as MainnetConfig, r as SepoliaConfig, t as HardhatConfig } from "./relayer-utils-iSPis4x-.js";
4
- import { $ as AclPausedError, $n as isOperatorContract, $t as DecryptStartEvent, A as decodeUnwrapRequested, An as isConfidentialTokenValidContract, B as ZamaSDKConfig, Bn as allowanceContract, Bt as ApproveUnderlyingSubmittedEvent, C as decodeAclEvent, Cn as TokenWrapperPairWithMetadata, Ct as BatchDecryptAsOptions, D as decodeOnChainEvent, Dn as getTokenPairsContract, Dt as ZERO_HANDLE, E as decodeDelegatedForUserDecryption, En as getTokenPairContract, Et as ReadonlyTokenConfig, F as findRevokedDelegationForUserDecryption, Fn as ERC7984_INTERFACE_ID, Ft as DelegatedCredentialsManager, G as Token, Gn as symbolContract, Gt as CredentialsCreatedEvent, H as ListPairsOptions, Hn as balanceOfContract, Ht as CredentialsAllowedEvent, I as findUnwrapRequested, In as ERC7984_WRAPPER_INTERFACE_ID, It as DelegatedCredentialsManagerConfig, J as BalanceCheckUnavailableError, Jn as wrapContract, Jt as CredentialsLoadingEvent, K as TokenConfig, Kn as finalizeUnwrapContract, Kt as CredentialsCreatingEvent, L as findWrapped, Ln as isConfidentialTokenContract, Lt as CredentialsManager, M as decodeUnwrappedStarted, Mn as getDelegationExpiryContract, N as decodeWrapped, Nn as isHandleDelegatedContract, O as decodeOnChainEvents, On as getTokenPairsLengthContract, P as findDelegatedForUserDecryption, Pn as revokeDelegationContract, Q as InsufficientERC20BalanceError, Qn as confidentialTransferFromContract, Qt as DecryptErrorEvent, R as DecryptOptions, Rn as isConfidentialWrapperContract, Rt as CredentialsManagerConfig, S as WrappedEvent, Sn as TokenWrapperPair, St as matchZamaError, T as decodeConfidentialTransfer, Tn as getTokenAddressContract, Tt as ReadonlyToken, U as WrappersRegistry, Un as decimalsContract, Ut as CredentialsCachedEvent, V as DefaultRegistryAddresses, Vn as approveContract, Vt as BaseEvent, W as WrappersRegistryConfig, Wn as nameContract, Wt as CredentialsCorruptedEvent, X as ERC20ReadFailedError, Xn as confidentialTotalSupplyContract, Xt as CredentialsRevokedEvent, Y as BalanceErrorDetails, Yn as confidentialBalanceOfContract, Yt as CredentialsPersistFailedEvent, Z as InsufficientConfidentialBalanceError, Zn as confidentialTransferContract, Zt as DecryptEndEvent, _ as TOKEN_TOPICS, _n as ZamaSDKEventListener, _t as EncryptionFailedError, a as ActivityType, an as RevokeDelegationSubmittedEvent, at as DelegationExpiryUnchangedError, b as UnwrappedFinalizedEvent, bn as DecryptCache, bt as ZamaError, c as parseActivityFeed, cn as TransactionErrorEvent, ct as DelegationSelfNotAllowedError, d as AclEvent, dn as UnshieldPhase1SubmittedEvent, dt as InvalidKeypairError, en as DelegationSubmittedEvent, er as rateContract, et as DelegationContractIsSelfError, f as AclTopics, fn as UnshieldPhase2StartedEvent, ft as KeypairExpiredError, g as RevokedDelegationForUserDecryptionEvent, gn as ZamaSDKEventInput, gt as DecryptionFailedError, h as OnChainEvent, hn as ZamaSDKEvent, ht as TransactionRevertedError, i as ActivityLogMetadata, in as FinalizeUnwrapSubmittedEvent, ir as unwrapFromBalanceContract, it as DelegationExpiredError, j as decodeUnwrappedFinalized, jn as delegateForUserDecryptionContract, k as decodeRevokedDelegationForUserDecryption, kn as getTokenPairsSliceContract, l as sortByBlockNumber, ln as TransferFromSubmittedEvent, lt as ConfigurationError, m as DelegatedForUserDecryptionEvent, mn as UnwrapSubmittedEvent, mt as ApprovalFailedError, n as ActivityDirection, nn as EncryptErrorEvent, nr as totalSupplyContract, nt as DelegationDelegateEqualsContractError, o as applyDecryptedValues, on as SessionExpiredEvent, ot as DelegationNotFoundError, p as ConfidentialTransferEvent, pn as UnshieldPhase2SubmittedEvent, pt as NoCiphertextError, q as matchAclRevert, qn as underlyingContract, qt as CredentialsExpiredEvent, r as ActivityItem, rn as EncryptStartEvent, rr as unwrapContract, rt as DelegationExpirationTooSoonError, s as extractEncryptedHandles, sn as ShieldSubmittedEvent, st as DelegationNotPropagatedError, t as ActivityAmount, tn as EncryptEndEvent, tr as setOperatorContract, tt as DelegationCooldownError, u as ACL_TOPICS, un as TransferSubmittedEvent, ut as RelayerRequestFailedError, v as Topics, vn as ZamaSDKEventType, vt as SigningFailedError, w as decodeAclEvents, wn as getConfidentialTokenAddressContract, wt as BatchDecryptOptions, x as UnwrappedStartedEvent, xn as PaginatedResult, xt as ZamaErrorCode, y as UnwrapRequestedEvent, yn as ZamaSDKEvents, yt as SigningRejectedError, z as ZamaSDK, zn as supportsInterfaceContract, zt as ApproveSubmittedEvent } from "./activity-CAZLy9Lp.js";
4
+ import { $ as DelegationContractIsSelfError, $n as isOperatorContract, $t as DelegationSubmittedEvent, A as decodeUnwrapRequested, An as delegateForUserDecryptionContract, B as DefaultRegistryAddresses, Bn as approveContract, Bt as BaseEvent, C as decodeAclEvent, Cn as getConfidentialTokenAddressContract, Ct as BatchDecryptOptions, D as decodeOnChainEvent, Dn as getTokenPairsLengthContract, E as decodeDelegatedForUserDecryption, En as getTokenPairsContract, Et as ZERO_HANDLE, F as findRevokedDelegationForUserDecryption, Fn as ERC7984_WRAPPER_INTERFACE_ID, Ft as DelegatedCredentialsManagerConfig, G as TokenConfig, Gn as finalizeUnwrapContract, Gt as CredentialsCreatingEvent, H as WrappersRegistry, Hn as decimalsContract, Ht as CredentialsCachedEvent, I as findUnwrapRequested, In as isConfidentialTokenContract, It as CredentialsManager, J as BalanceErrorDetails, Jn as wrapContract, Jt as CredentialsPersistFailedEvent, K as matchAclRevert, Kn as inferredTotalSupplyContract, Kt as CredentialsExpiredEvent, L as findWrapped, Ln as isConfidentialWrapperContract, Lt as CredentialsManagerConfig, M as decodeUnwrappedStarted, Mn as isHandleDelegatedContract, N as decodeWrapped, Nn as revokeDelegationContract, O as decodeOnChainEvents, On as getTokenPairsSliceContract, P as findDelegatedForUserDecryption, Pn as ERC7984_INTERFACE_ID, Pt as DelegatedCredentialsManager, Q as AclPausedError, Qn as confidentialTransferFromContract, Qt as DecryptStartEvent, R as ZamaSDK, Rn as supportsInterfaceContract, Rt as ApproveSubmittedEvent, S as WrappedEvent, Sn as TokenWrapperPairWithMetadata, St as BatchDecryptAsOptions, T as decodeConfidentialTransfer, Tn as getTokenPairContract, Tt as ReadonlyTokenConfig, U as WrappersRegistryConfig, Un as nameContract, Ut as CredentialsCorruptedEvent, V as ListPairsOptions, Vn as balanceOfContract, Vt as CredentialsAllowedEvent, W as Token, Wn as symbolContract, Wt as CredentialsCreatedEvent, X as InsufficientConfidentialBalanceError, Xn as confidentialTotalSupplyContract, Xt as DecryptEndEvent, Y as ERC20ReadFailedError, Yn as confidentialBalanceOfContract, Yt as CredentialsRevokedEvent, Z as InsufficientERC20BalanceError, Zn as confidentialTransferContract, Zt as DecryptErrorEvent, _ as TOKEN_TOPICS, _n as ZamaSDKEventType, _t as SigningFailedError, a as ActivityType, an as SessionExpiredEvent, at as DelegationNotFoundError, b as UnwrappedFinalizedEvent, bn as PaginatedResult, bt as ZamaErrorCode, c as parseActivityFeed, cn as TransferFromSubmittedEvent, ct as ConfigurationError, d as AclEvent, dn as UnshieldPhase2StartedEvent, dt as KeypairExpiredError, en as EncryptEndEvent, er as rateContract, et as DelegationCooldownError, f as AclTopics, fn as UnshieldPhase2SubmittedEvent, ft as NoCiphertextError, g as RevokedDelegationForUserDecryptionEvent, gn as ZamaSDKEventListener, gt as EncryptionFailedError, h as OnChainEvent, hn as ZamaSDKEventInput, ht as DecryptionFailedError, i as ActivityLogMetadata, in as RevokeDelegationSubmittedEvent, ir as unwrapFromBalanceContract, it as DelegationExpiryUnchangedError, j as decodeUnwrappedFinalized, jn as getDelegationExpiryContract, k as decodeRevokedDelegationForUserDecryption, kn as isConfidentialTokenValidContract, l as sortByBlockNumber, ln as TransferSubmittedEvent, lt as RelayerRequestFailedError, m as DelegatedForUserDecryptionEvent, mn as ZamaSDKEvent, mt as TransactionRevertedError, n as ActivityDirection, nn as EncryptStartEvent, nr as totalSupplyContract, nt as DelegationExpirationTooSoonError, o as applyDecryptedValues, on as ShieldSubmittedEvent, ot as DelegationNotPropagatedError, p as ConfidentialTransferEvent, pn as UnwrapSubmittedEvent, pt as ApprovalFailedError, q as BalanceCheckUnavailableError, qn as underlyingContract, qt as CredentialsLoadingEvent, r as ActivityItem, rn as FinalizeUnwrapSubmittedEvent, rr as unwrapContract, rt as DelegationExpiredError, s as extractEncryptedHandles, sn as TransactionErrorEvent, st as DelegationSelfNotAllowedError, t as ActivityAmount, tn as EncryptErrorEvent, tr as setOperatorContract, tt as DelegationDelegateEqualsContractError, u as ACL_TOPICS, un as UnshieldPhase1SubmittedEvent, ut as InvalidKeypairError, v as Topics, vn as ZamaSDKEvents, vt as SigningRejectedError, w as decodeAclEvents, wn as getTokenAddressContract, wt as ReadonlyToken, x as UnwrappedStartedEvent, xn as TokenWrapperPair, xt as matchZamaError, y as UnwrapRequestedEvent, yn as DecryptCache, yt as ZamaError, z as ZamaSDKConfig, zn as allowanceContract, zt as ApproveUnderlyingSubmittedEvent } from "./activity-DySBgT7m.js";
5
5
  import { Address, Address as Address$1, Hex, Hex as Hex$1 } from "viem";
6
6
  import { FheTypeName, FhevmInstanceConfig, InputProofBytesType, InputProofBytesType as InputProofBytesType$1, KeypairType, KeypairType as KeypairType$1, KmsDelegatedUserDecryptEIP712Type, KmsDelegatedUserDecryptEIP712Type as KmsDelegatedUserDecryptEIP712Type$1, ZKProofLike, ZKProofLike as ZKProofLike$1 } from "@zama-fhe/relayer-sdk/bundle";
7
7
 
@@ -172,5 +172,5 @@ declare class ChromeSessionStorage implements GenericStorage {
172
172
  /** Default singleton for application-wide use. */
173
173
  declare const chromeSessionStorage: ChromeSessionStorage;
174
174
  //#endregion
175
- export { ACL_TOPICS, type AclEvent, AclPausedError, AclTopics, type ActivityAmount, type ActivityDirection, type ActivityItem, type ActivityLogMetadata, type ActivityType, type Address, ApprovalFailedError, type ApproveSubmittedEvent, type ApproveUnderlyingSubmittedEvent, BalanceCheckUnavailableError, type BalanceErrorDetails, type BaseEvent, type BatchDecryptAsOptions, type BatchDecryptOptions, ChromeSessionStorage, type ClearValueType, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type CredentialsAllowedEvent, type CredentialsCachedEvent, type CredentialsCorruptedEvent, type CredentialsCreatedEvent, type CredentialsCreatingEvent, type CredentialsExpiredEvent, type CredentialsLoadingEvent, CredentialsManager, type CredentialsManagerConfig, type CredentialsPersistFailedEvent, type CredentialsRevokedEvent, DecryptCache, type DecryptEndEvent, type DecryptErrorEvent, type DecryptOptions, type DecryptStartEvent, DecryptionFailedError, DefaultRegistryAddresses, DelegatedCredentialsManager, type DelegatedCredentialsManagerConfig, type DelegatedForUserDecryptionEvent, type DelegatedStoredCredentials, type DelegatedUserDecryptParams, DelegationContractIsSelfError, DelegationCooldownError, DelegationDelegateEqualsContractError, DelegationExpirationTooSoonError, DelegationExpiredError, DelegationExpiryUnchangedError, DelegationNotFoundError, DelegationNotPropagatedError, DelegationSelfNotAllowedError, type DelegationSubmittedEvent, type EIP712TypedData, ERC20ReadFailedError, ERC7984_INTERFACE_ID, ERC7984_WRAPPER_INTERFACE_ID, type EncryptEndEvent, type EncryptErrorEvent, type EncryptInput, type EncryptParams, type EncryptResult, type EncryptStartEvent, EncryptionFailedError, type FheTypeName, type FhevmInstanceConfig, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericSigner, type GenericStorage, type Handle, HardhatConfig, type Hex, IndexedDBStorage, type InputProofBytesType, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidKeypairError, KeypairExpiredError, type KeypairType, type KmsDelegatedUserDecryptEIP712Type, type ListPairsOptions, MainnetConfig, MemoryStorage, type NetworkType, NoCiphertextError, type OnChainEvent, type PaginatedResult, type PublicDecryptResult, type RawLog, type ReadContractArgs, type ReadContractConfig, type ReadContractReturnType, type ReadFunctionName, ReadonlyToken, type ReadonlyTokenConfig, RelayerRequestFailedError, type RelayerSDK, type RelayerSDKStatus, RelayerWeb, type RelayerWebConfig, type RelayerWebSecurityConfig, type RevokeDelegationSubmittedEvent, type RevokedDelegationForUserDecryptionEvent, SepoliaConfig, type SessionExpiredEvent, type ShieldCallbacks, type ShieldOptions, type ShieldSubmittedEvent, type SignerLifecycleCallbacks, SigningFailedError, SigningRejectedError, type StoredCredentials, TOKEN_TOPICS, Token, type TokenConfig, type TokenWrapperPair, type TokenWrapperPairWithMetadata, Topics, type TransactionErrorEvent, type TransactionReceipt, type TransactionResult, TransactionRevertedError, type TransferCallbacks, type TransferFromSubmittedEvent, type TransferOptions, type TransferSubmittedEvent, type UnshieldCallbacks, type UnshieldOptions, type UnshieldPhase1SubmittedEvent, type UnshieldPhase2StartedEvent, type UnshieldPhase2SubmittedEvent, type UnwrapRequestedEvent, type UnwrapSubmittedEvent, type UnwrappedFinalizedEvent, type UnwrappedStartedEvent, type UserDecryptParams, type WrappedEvent, WrappersRegistry, type WrappersRegistryConfig, type WriteContractArgs, type WriteContractConfig, type WriteFunctionName, ZERO_HANDLE, type ZKProofLike, ZamaError, ZamaErrorCode, ZamaSDK, type ZamaSDKConfig, type ZamaSDKEvent, type ZamaSDKEventInput, type ZamaSDKEventListener, type ZamaSDKEventType, ZamaSDKEvents, allowanceContract, applyDecryptedValues, approveContract, balanceOfContract, chromeSessionStorage, clearPendingUnshield, confidentialBalanceOfContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapRequested, decodeUnwrappedFinalized, decodeUnwrappedStarted, decodeWrapped, delegateForUserDecryptionContract, extractEncryptedHandles, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrapped, getConfidentialTokenAddressContract, getDelegationExpiryContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, indexedDBStorage, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isHandleDelegatedContract, isOperatorContract, loadPendingUnshield, matchAclRevert, matchZamaError, memoryStorage, nameContract, parseActivityFeed, rateContract, revokeDelegationContract, savePendingUnshield, setOperatorContract, sortByBlockNumber, supportsInterfaceContract, symbolContract, totalSupplyContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract };
175
+ export { ACL_TOPICS, type AclEvent, AclPausedError, AclTopics, type ActivityAmount, type ActivityDirection, type ActivityItem, type ActivityLogMetadata, type ActivityType, type Address, ApprovalFailedError, type ApproveSubmittedEvent, type ApproveUnderlyingSubmittedEvent, BalanceCheckUnavailableError, type BalanceErrorDetails, type BaseEvent, type BatchDecryptAsOptions, type BatchDecryptOptions, ChromeSessionStorage, type ClearValueType, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type CredentialsAllowedEvent, type CredentialsCachedEvent, type CredentialsCorruptedEvent, type CredentialsCreatedEvent, type CredentialsCreatingEvent, type CredentialsExpiredEvent, type CredentialsLoadingEvent, CredentialsManager, type CredentialsManagerConfig, type CredentialsPersistFailedEvent, type CredentialsRevokedEvent, DecryptCache, type DecryptEndEvent, type DecryptErrorEvent, type DecryptStartEvent, DecryptionFailedError, DefaultRegistryAddresses, DelegatedCredentialsManager, type DelegatedCredentialsManagerConfig, type DelegatedForUserDecryptionEvent, type DelegatedStoredCredentials, type DelegatedUserDecryptParams, DelegationContractIsSelfError, DelegationCooldownError, DelegationDelegateEqualsContractError, DelegationExpirationTooSoonError, DelegationExpiredError, DelegationExpiryUnchangedError, DelegationNotFoundError, DelegationNotPropagatedError, DelegationSelfNotAllowedError, type DelegationSubmittedEvent, type EIP712TypedData, ERC20ReadFailedError, ERC7984_INTERFACE_ID, ERC7984_WRAPPER_INTERFACE_ID, type EncryptEndEvent, type EncryptErrorEvent, type EncryptInput, type EncryptParams, type EncryptResult, type EncryptStartEvent, EncryptionFailedError, type FheTypeName, type FhevmInstanceConfig, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericSigner, type GenericStorage, type Handle, HardhatConfig, type Hex, IndexedDBStorage, type InputProofBytesType, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidKeypairError, KeypairExpiredError, type KeypairType, type KmsDelegatedUserDecryptEIP712Type, type ListPairsOptions, MainnetConfig, MemoryStorage, type NetworkType, NoCiphertextError, type OnChainEvent, type PaginatedResult, type PublicDecryptResult, type RawLog, type ReadContractArgs, type ReadContractConfig, type ReadContractReturnType, type ReadFunctionName, ReadonlyToken, type ReadonlyTokenConfig, RelayerRequestFailedError, type RelayerSDK, type RelayerSDKStatus, RelayerWeb, type RelayerWebConfig, type RelayerWebSecurityConfig, type RevokeDelegationSubmittedEvent, type RevokedDelegationForUserDecryptionEvent, SepoliaConfig, type SessionExpiredEvent, type ShieldCallbacks, type ShieldOptions, type ShieldSubmittedEvent, type SignerLifecycleCallbacks, SigningFailedError, SigningRejectedError, type StoredCredentials, TOKEN_TOPICS, Token, type TokenConfig, type TokenWrapperPair, type TokenWrapperPairWithMetadata, Topics, type TransactionErrorEvent, type TransactionReceipt, type TransactionResult, TransactionRevertedError, type TransferCallbacks, type TransferFromSubmittedEvent, type TransferOptions, type TransferSubmittedEvent, type UnshieldCallbacks, type UnshieldOptions, type UnshieldPhase1SubmittedEvent, type UnshieldPhase2StartedEvent, type UnshieldPhase2SubmittedEvent, type UnwrapRequestedEvent, type UnwrapSubmittedEvent, type UnwrappedFinalizedEvent, type UnwrappedStartedEvent, type UserDecryptParams, type WrappedEvent, WrappersRegistry, type WrappersRegistryConfig, type WriteContractArgs, type WriteContractConfig, type WriteFunctionName, ZERO_HANDLE, type ZKProofLike, ZamaError, ZamaErrorCode, ZamaSDK, type ZamaSDKConfig, type ZamaSDKEvent, type ZamaSDKEventInput, type ZamaSDKEventListener, type ZamaSDKEventType, ZamaSDKEvents, allowanceContract, applyDecryptedValues, approveContract, balanceOfContract, chromeSessionStorage, clearPendingUnshield, confidentialBalanceOfContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapRequested, decodeUnwrappedFinalized, decodeUnwrappedStarted, decodeWrapped, delegateForUserDecryptionContract, extractEncryptedHandles, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrapped, getConfidentialTokenAddressContract, getDelegationExpiryContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, indexedDBStorage, inferredTotalSupplyContract, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isHandleDelegatedContract, isOperatorContract, loadPendingUnshield, matchAclRevert, matchZamaError, memoryStorage, nameContract, parseActivityFeed, rateContract, revokeDelegationContract, savePendingUnshield, setOperatorContract, sortByBlockNumber, supportsInterfaceContract, symbolContract, totalSupplyContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract };
176
176
  //# sourceMappingURL=index.d.ts.map
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{$ as a,A as o,B as s,C as c,D as l,E as u,F as d,G as f,H as p,I as m,J as h,K as g,L as ee,M as te,N as ne,O as _,P as re,Q as ie,R as v,S as y,T as ae,U as b,V as x,W as oe,X as se,Y as S,Z as C,_ as ce,a as le,b as ue,c as de,d as fe,et as pe,f as me,g as he,h as ge,i as _e,j as ve,k as ye,l as be,m as xe,n as Se,nt as Ce,o as we,p as Te,q as Ee,r as De,s as Oe,t as ke,tt as Ae,u as je,v as Me,w,x as Ne,y as Pe,z as Fe}from"./activity-CCD_CGXh.js";import{n as T,t as E}from"./encryption-CmIPBcfP.js";import{n as Ie,t as Le}from"./fhe-artifact-cache-COPNqOc2.js";import{c as Re,i as ze,o as D}from"./assertions-BARApuMj.js";import{i as O,n as Be,t as k}from"./memory-storage-B4_heQa5.js";import{a as Ve,i as A,n as He,o as j,r as M,t as N}from"./relayer-utils-BeoTNDM4.js";import{C as Ue,S as We,T as Ge,_ as Ke,a as P,b as qe,c as Je,d as Ye,f as Xe,g as Ze,h as Qe,i as $e,l as et,m as tt,n as F,o as I,p as nt,r as rt,s as L,t as R,u as it,v as at,w as ot,x as st,y as ct}from"./wrappers-registry-BAz8Adry.js";import{n as lt}from"./cleartext-Cs28cTsa.js";import{getAddress as z,hexToBigInt as ut}from"viem";var B=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},V=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},H=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},dt=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},U=class extends r{constructor(e,n){super(t.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},ft=class extends r{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function pt(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 W={AlreadyDelegatedOrRevokedInSameBlock:e=>new oe(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new p(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new C(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new f(`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 h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new S(`Cannot revoke: no active delegation exists.`,{cause:e})};function G(e){let t=e instanceof Error?e:void 0,n=pt(e);if(n&&n in W)return W[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(W))if(r.includes(e))return n(t);return null}var K=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{console.warn(`IndexedDB "${this.#n}" closing due to version change from another tab`),this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const mt=new K;function ht(e){try{return D(e,`runtime`),Re(e,`id`,`runtime.id`),ze(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function gt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(D(t,`ns`),ht(t.runtime))return t.runtime}catch{continue}}var _t=class extends Ie{constructor(e){super(e,e.logger)}createWorker(){let e=gt();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
1
+ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{$ as a,A as o,B as s,C as c,E as l,F as u,G as d,H as f,I as p,J as ee,K as te,L as ne,M as m,N as re,P as ie,Q as ae,R as h,S as g,T as oe,U as se,V as _,W as v,X as y,Y as ce,Z as b,_ as le,a as ue,at as de,b as fe,c as pe,d as me,et as x,f as he,g as ge,h as _e,i as ve,it as ye,j as S,l as be,m as xe,n as Se,nt as C,o as Ce,ot as we,p as Te,q as w,r as Ee,rt as De,s as Oe,st as ke,t as Ae,tt as je,u as Me,v as Ne,w as T,x as Pe,y as Fe,z as E}from"./activity-CxGHb_3-.js";import{n as D,t as O}from"./encryption-CmIPBcfP.js";import{n as Ie,t as Le}from"./fhe-artifact-cache-COPNqOc2.js";import{c as Re,i as ze,o as k}from"./assertions-BARApuMj.js";import{i as A,n as Be,t as Ve}from"./memory-storage-B4_heQa5.js";import{a as He,i as j,n as Ue,o as M,r as N,t as P}from"./relayer-utils-BeoTNDM4.js";import{C as We,E as Ge,S as Ke,T as F,_ as qe,a as I,b as Je,c as Ye,d as Xe,f as Ze,g as Qe,h as $e,i as et,l as tt,m as nt,n as L,o as R,p as rt,r as it,s as z,t as B,u as at,v as ot,w as st,x as ct,y as lt}from"./wrappers-registry-DO0729Zi.js";import{n as ut}from"./cleartext-Cs28cTsa.js";import{getAddress as V,hexToBigInt as dt}from"viem";var H=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},U=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},W=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},ft=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},G=class extends r{constructor(e,n){super(t.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},pt=class extends r{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function mt(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 K={AlreadyDelegatedOrRevokedInSameBlock:e=>new ce(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new ee(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new w(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new C(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new y(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new b(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new a(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new x(`Cannot revoke: no active delegation exists.`,{cause:e})};function q(e){let t=e instanceof Error?e:void 0,n=mt(e);if(n&&n in K)return K[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(K))if(r.includes(e))return n(t);return null}var J=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{console.warn(`IndexedDB "${this.#n}" closing due to version change from another tab`),this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const ht=new J;function gt(e){try{return k(e,`runtime`),Re(e,`id`,`runtime.id`),ze(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function _t(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(k(t,`ns`),gt(t.runtime))return t.runtime}catch{continue}}var vt=class extends Ie{constructor(e){super(e,e.logger)}createWorker(){let e=_t();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
2
2
  //#region src/utils/assertions.ts
3
3
  function assertNonNullable(value, context) {
4
4
  if (value === null || value === void 0) throw new TypeError(\`\${context} must not be null or undefined\`);
@@ -511,5 +511,5 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{$ as a,A as o
511
511
  };
512
512
  //#endregion
513
513
  })();
514
- `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},vt=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},N[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new K(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},N[e],this.#l.transports[e]);this.#a=new Le({storage:this.#o,chainId:e,relayerUrl:t.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new _t(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:Ve(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return j(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return j(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return j(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return j(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return j(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let e=await this.#l.getChainId(),t=Object.assign({},N[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},q=class e extends w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?z(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(tt(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=z(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:_.EncryptStart}),{handles:c,inputProof:l}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:_.EncryptEnd,durationMs:Date.now()-u}),J(()=>a?.())}catch(e){throw this.emit({type:_.EncryptError,error:O(e),durationMs:Date.now()-u}),e instanceof r?e:new T(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new T(`Encryption returned no handles`);try{let e=await this.signer.writeContract(at(this.address,s,c[0],l));return this.emit({type:_.TransferSubmitted,txHash:e}),J(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`transfer`,error:O(e)}),e instanceof r?e:new V(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=z(e),o=z(t),s,c,l=Date.now();try{this.emit({type:_.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:_.EncryptEnd,durationMs:Date.now()-l}),J(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:_.EncryptError,error:O(e),durationMs:Date.now()-l}),e instanceof r?e:new T(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new T(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ct(this.address,a,o,s[0],c));return this.emit({type:_.TransferFromSubmitted,txHash:e}),J(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`transferFrom`,error:O(e)}),e instanceof r?e:new V(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=z(e);try{let e=await this.signer.writeContract(We(this.address,n,t));return this.emit({type:_.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`approve`,error:O(e)}),e instanceof r?e:new B(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=z(e),r=t?z(t):await this.signer.getAddress();return this.signer.readContract(qe(this.address,r,n))}async shield(e,t){let n=await this.#n(),i;try{let e=await this.signer.getAddress();i=await this.signer.readContract(ee(n,e))}catch(e){throw e instanceof r?e:new ft(`Could not read ERC-20 balance for shield validation (token: ${n})`,{cause:O(e)})}if(i<e)throw new dt(`Insufficient ERC-20 balance: requested ${e}, available ${i} (token: ${n})`,{requested:e,available:i,token:n});let a=t?.approvalStrategy??`exact`;a!==`skip`&&await this.#o(e,a===`max`,t);try{let n=t?.to?z(t.to):await this.signer.getAddress(),r=await this.signer.writeContract(Qe(this.wrapper,n,e));return this.emit({type:_.ShieldSubmitted,txHash:r}),J(()=>t?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:_.TransactionError,operation:`shield`,error:O(e)}),e instanceof r?e:new V(`Shield transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:_.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:_.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:_.EncryptError,error:O(e),durationMs:Date.now()-a}),e instanceof r?e:new T(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new T(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ot(this.address,t,t,n[0],i));return this.emit({type:_.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`unwrap`,error:O(e)}),e instanceof r?e:new V(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new E(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(Ge(this.address,e,e,t));return this.emit({type:_.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:_.TransactionError,operation:`unwrap`,error:O(e)}),e instanceof r?e:new V(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return J(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return J(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:_.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:_.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=ut(r.abiEncodedClearValues)}catch(e){throw new E(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(e){throw this.emit({type:_.DecryptError,error:O(e),durationMs:Date.now()-i}),e instanceof r?e:new E(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(nt(this.wrapper,e,t,n));return this.emit({type:_.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:_.TransactionError,operation:`finalizeUnwrap`,error:O(e)}),e instanceof r?e:new V(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(d(t,e,this.wrapper))>0n&&await this.signer.writeContract(m(t,this.wrapper,0n))}let e=await this.signer.writeContract(m(t,this.wrapper,n));return this.emit({type:_.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`approveUnderlying`,error:O(e)}),e instanceof r?e:new B(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new g(`Expiration date must be at least 1 hour in the future`);let n=z(e),i=await this.signer.getAddress();if(n===z(i))throw new C(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new f(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):o,c;try{c=await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})}catch{c=-1n}if(c===s)throw new h(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(ve(a,n,this.address,s));return this.emit({type:_.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`delegateDecryption`,error:O(e)}),e instanceof r?e:G(e)||new V(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=z(e),n=await this.signer.getAddress(),i=await this.getAclAddress(),a;try{a=await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})}catch{a=1n}if(a===0n)throw new S(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(re(i,t,this.address));return this.emit({type:_.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:_.TransactionError,operation:`revokeDelegation`,error:O(e)}),e instanceof r?e:G(e)||new V(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new V(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t,n;try{t=await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t)}catch(e){throw e instanceof r?e:new U(`Could not read confidential balance handle (token: ${this.address})`,{cause:O(e)})}if(this.isZeroHandle(n))throw new H(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await this.cache.get(t,this.address,n);if(typeof i==`bigint`){if(i<e)throw new H(`Insufficient confidential balance: requested ${e}, available ${i} (token: ${this.address})`,{requested:e,available:i,token:this.address});return}let a;try{a=await this.isAllowed()}catch(e){throw e instanceof r?e:new U(`Could not check credential status for balance validation (token: ${this.address})`,{cause:e})}if(!a)throw new U(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let o;try{o=await this.decryptBalance(n,t)}catch(e){throw e instanceof r?e:new U(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:e})}if(o<e)throw new H(`Insufficient confidential balance: requested ${e}, available ${o} (token: ${this.address})`,{requested:e,available:o,token:this.address})}async#a(e,t,n){this.emit({type:_.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new V(`Failed to get unshield receipt`,{cause:e})}let a=y(i.logs);if(!a)throw new V(`No UnwrapRequested event found in unshield receipt`);this.emit({type:_.UnshieldPhase2Started,operationId:t}),J(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:_.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),J(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(d(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(m(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(m(i,this.wrapper,r));this.emit({type:_.ApproveUnderlyingSubmitted,txHash:a}),J(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new B(`ERC-20 approval failed`,{cause:e})}}};function J(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const yt={[M.chainId]:M.registryAddress,[A.chainId]:A.registryAddress,[lt.chainId]:lt.registryAddress},Y=300*1e3;var X=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},yt,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return z(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(P(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(I(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?Y:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,c]=await Promise.all([this.signer.readContract(s(e.tokenAddress)),this.signer.readContract(x(e.tokenAddress)),this.signer.readContract(v(e.tokenAddress)),this.signer.readContract(Fe(e.tokenAddress)),this.signer.readContract(s(e.confidentialTokenAddress)),this.signer.readContract(x(e.confidentialTokenAddress)),this.signer.readContract(v(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=z(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(R(t,n));if(!a)return this.#i(r,null,Y);let s=await this.signer.readContract(L(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=z(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(F(t,n));if(!a)return this.#i(r,null,Y);let s=await this.signer.readContract(L(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract($e(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(P(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(I(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(rt(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(R(t,z(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(F(t,z(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(L(t,z(e)))}};const Z=365*86400;var bt=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new k,this.cache=new ye(e.storage),this.#t=e.onEvent??function(){},this.registry=new X({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Z?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new l(t),this.delegatedCredentials=new u(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:_.TransactionError,operation:e,error:O(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=z(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await l.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new w({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,cache:this.cache,address:z(e),onEvent:this.#t})}createToken(e,t){return new q({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,cache:this.cache,address:z(e),wrapper:t?z(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new X({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async userDecrypt(e,t){let{onCredentialsReady:n=()=>{},onDecrypted:r=()=>{}}=t??{};if(e.length===0)return{};let i=await this.signer.getAddress(),a={},o=[];for(let t of e){let e=z(t.contractAddress),n=await this.cache.get(i,e,t.handle);n===null?o.push({handle:t.handle,contractAddress:e}):a[t.handle]=n}if(o.length===0)return r(a),a;let s=[...new Set(o.map(e=>e.contractAddress))],c=await this.credentials.allow(...s);n();let l=new Map;for(let e of o){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}for(let[e,t]of l){let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:i,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(i,e,t,r)}return r(a),a}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await l.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function xt(e,t,n){await e.set(Q(t),n)}async function St(e,t){return e.get(Q(t))}async function Ct(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 wt=new $;export{le as ACL_TOPICS,p as AclPausedError,we as AclTopics,B as ApprovalFailedError,U as BalanceCheckUnavailableError,$ as ChromeSessionStorage,i as ConfigurationError,l as CredentialsManager,ye as DecryptCache,E as DecryptionFailedError,yt as DefaultRegistryAddresses,u as DelegatedCredentialsManager,b as DelegationContractIsSelfError,oe as DelegationCooldownError,f as DelegationDelegateEqualsContractError,g as DelegationExpirationTooSoonError,Ee as DelegationExpiredError,h as DelegationExpiryUnchangedError,S as DelegationNotFoundError,se as DelegationNotPropagatedError,C as DelegationSelfNotAllowedError,ft as ERC20ReadFailedError,Je as ERC7984_INTERFACE_ID,et as ERC7984_WRAPPER_INTERFACE_ID,T as EncryptionFailedError,He as HardhatConfig,K as IndexedDBStorage,H as InsufficientConfidentialBalanceError,dt as InsufficientERC20BalanceError,ie as InvalidKeypairError,a as KeypairExpiredError,M as MainnetConfig,k as MemoryStorage,pe as NoCiphertextError,w as ReadonlyToken,n as RelayerRequestFailedError,vt as RelayerWeb,A as SepoliaConfig,Ae as SigningFailedError,Ce as SigningRejectedError,Oe as TOKEN_TOPICS,q as Token,de as Topics,V as TransactionRevertedError,X as WrappersRegistry,ae as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,bt as ZamaSDK,_ as ZamaSDKEvents,d as allowanceContract,ke as applyDecryptedValues,m as approveContract,ee as balanceOfContract,wt as chromeSessionStorage,Ct as clearPendingUnshield,Ze as confidentialBalanceOfContract,Ke as confidentialTotalSupplyContract,at as confidentialTransferContract,ct as confidentialTransferFromContract,v as decimalsContract,be as decodeAclEvent,je as decodeAclEvents,fe as decodeConfidentialTransfer,me as decodeDelegatedForUserDecryption,Te as decodeOnChainEvent,xe as decodeOnChainEvents,ge as decodeRevokedDelegationForUserDecryption,he as decodeUnwrapRequested,ce as decodeUnwrappedFinalized,Me as decodeUnwrappedStarted,Pe as decodeWrapped,ve as delegateForUserDecryptionContract,Se as extractEncryptedHandles,nt as finalizeUnwrapContract,ue as findDelegatedForUserDecryption,Ne as findRevokedDelegationForUserDecryption,y as findUnwrapRequested,c as findWrapped,R as getConfidentialTokenAddressContract,te as getDelegationExpiryContract,F as getTokenAddressContract,rt as getTokenPairContract,$e as getTokenPairsContract,P as getTokenPairsLengthContract,I as getTokenPairsSliceContract,mt as indexedDBStorage,it as isConfidentialTokenContract,L as isConfidentialTokenValidContract,Ye as isConfidentialWrapperContract,ne as isHandleDelegatedContract,qe as isOperatorContract,St as loadPendingUnshield,G as matchAclRevert,e as matchZamaError,Be as memoryStorage,s as nameContract,De as parseActivityFeed,st as rateContract,re as revokeDelegationContract,xt as savePendingUnshield,We as setOperatorContract,_e as sortByBlockNumber,Xe as supportsInterfaceContract,x as symbolContract,Ue as totalSupplyContract,tt as underlyingContract,ot as unwrapContract,Ge as unwrapFromBalanceContract,Qe as wrapContract};
514
+ `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},yt=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},P[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new J(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},P[e],this.#l.transports[e]);this.#a=new Le({storage:this.#o,chainId:e,relayerUrl:t.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new vt(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:He(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return M(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return M(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return M(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let e=await this.#l.getChainId(),t=Object.assign({},P[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},bt=class e extends T{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?V(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(F(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=V(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:m.EncryptStart}),{handles:c,inputProof:l}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:m.EncryptEnd,durationMs:Date.now()-u}),Y(()=>a?.())}catch(e){throw this.emit({type:m.EncryptError,error:A(e),durationMs:Date.now()-u}),e instanceof r?e:new D(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract($e(this.address,s,c[0],l));return this.emit({type:m.TransferSubmitted,txHash:e}),Y(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new U(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=V(e),o=V(t),s,c,l=Date.now();try{this.emit({type:m.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:m.EncryptEnd,durationMs:Date.now()-l}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:m.EncryptError,error:A(e),durationMs:Date.now()-l}),e instanceof r?e:new D(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Qe(this.address,a,o,s[0],c));return this.emit({type:m.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new U(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=V(e);try{let e=await this.signer.writeContract(lt(this.address,n,t));return this.emit({type:m.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`approve`,error:A(e)}),e instanceof r?e:new H(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=V(e),r=t?V(t):await this.signer.getAddress();return this.signer.readContract(qe(this.address,r,n))}async shield(e,t){let n=await this.#n(),i;try{let e=await this.signer.getAddress();i=await this.signer.readContract(_(n,e))}catch(e){throw e instanceof r?e:new pt(`Could not read ERC-20 balance for shield validation (token: ${n})`,{cause:A(e)})}if(i<e)throw new ft(`Insufficient ERC-20 balance: requested ${e}, available ${i} (token: ${n})`,{requested:e,available:i,token:n});let a=t?.approvalStrategy??`exact`;a!==`skip`&&await this.#o(e,a===`max`,t);try{let n=t?.to?V(t.to):await this.signer.getAddress(),r=await this.signer.writeContract(Ge(this.wrapper,n,e));return this.emit({type:m.ShieldSubmitted,txHash:r}),Y(()=>t?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:m.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new U(`Shield transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:m.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:m.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:m.EncryptError,error:A(e),durationMs:Date.now()-a}),e instanceof r?e:new D(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ct(this.address,t,t,n[0],i));return this.emit({type:m.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new U(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new O(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(Ke(this.address,e,e,t));return this.emit({type:m.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:m.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new U(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Y(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:m.DecryptStart,handles:[e]});let r=await this.relayer.publicDecrypt([e]);this.emit({type:m.DecryptEnd,durationMs:Date.now()-i,handles:[e],result:r.clearValues}),n=r.decryptionProof;try{t=dt(r.abiEncodedClearValues)}catch(e){throw new O(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(t){throw this.emit({type:m.DecryptError,error:A(t),durationMs:Date.now()-i,handles:[e]}),t instanceof r?t:new O(`Failed to finalize unshield`,{cause:t})}try{let r=await this.signer.writeContract(We(this.wrapper,e,t,n));return this.emit({type:m.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:m.TransactionError,operation:`finalizeUnwrap`,error:A(e)}),e instanceof r?e:new U(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(E(t,e,this.wrapper))>0n&&await this.signer.writeContract(s(t,this.wrapper,0n))}let e=await this.signer.writeContract(s(t,this.wrapper,n));return this.emit({type:m.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`approveUnderlying`,error:A(e)}),e instanceof r?e:new H(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);let n=V(e),i=await this.signer.getAddress();if(n===V(i))throw new C(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new y(`Delegate address cannot be the same as the contract address (${this.address}).`);let o=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):ie,c;try{c=await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})}catch{c=-1n}if(c===s)throw new a(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(u(o,n,this.address,s));return this.emit({type:m.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`delegateDecryption`,error:A(e)}),e instanceof r?e:q(e)||new U(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=V(e),n=await this.signer.getAddress(),i=await this.getAclAddress(),a;try{a=await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})}catch{a=1n}if(a===0n)throw new x(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(h(i,t,this.address));return this.emit({type:m.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:m.TransactionError,operation:`revokeDelegation`,error:A(e)}),e instanceof r?e:q(e)||new U(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new U(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t,n;try{t=await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t)}catch(e){throw e instanceof r?e:new G(`Could not read confidential balance handle (token: ${this.address})`,{cause:A(e)})}if(this.isZeroHandle(n))throw new W(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await this.cache.get(t,this.address,n);if(typeof i==`bigint`){if(i<e)throw new W(`Insufficient confidential balance: requested ${e}, available ${i} (token: ${this.address})`,{requested:e,available:i,token:this.address});return}let a;try{a=await this.isAllowed()}catch(e){throw e instanceof r?e:new G(`Could not check credential status for balance validation (token: ${this.address})`,{cause:e})}if(!a)throw new G(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let o;try{o=await this.decryptBalance(n,t)}catch(e){throw e instanceof r?e:new G(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:e})}if(o<e)throw new W(`Insufficient confidential balance: requested ${e}, available ${o} (token: ${this.address})`,{requested:e,available:o,token:this.address})}async#a(e,t,n){this.emit({type:m.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new U(`Failed to get unshield receipt`,{cause:e})}let a=g(i.logs);if(!a)throw new U(`No UnwrapRequested event found in unshield receipt`);this.emit({type:m.UnshieldPhase2Started,operationId:t}),Y(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:m.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),Y(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(E(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(s(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(s(i,this.wrapper,r));this.emit({type:m.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new H(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const xt={[N.chainId]:N.registryAddress,[j.chainId]:j.registryAddress,[ut.chainId]:ut.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},xt,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return V(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(I(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(R(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?X:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(v(e.tokenAddress)),this.signer.readContract(d(e.tokenAddress)),this.signer.readContract(f(e.tokenAddress)),this.signer.readContract(se(e.tokenAddress)),this.signer.readContract(v(e.confidentialTokenAddress)),this.signer.readContract(d(e.confidentialTokenAddress)),this.signer.readContract(f(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=V(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(B(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(z(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=V(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(L(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(z(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(et(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(I(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(R(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(it(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(B(t,V(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(L(t,V(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,V(e)))}};const Q=365*86400;var St=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new Ve,this.cache=new re(e.storage),this.#t=e.onEvent??function(){},this.registry=new Z({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Q?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Q}s); capping to ${Q}s.`),Q):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new S(t),this.delegatedCredentials=new o(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:m.TransactionError,operation:e,error:A(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=V(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await S.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new T({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,cache:this.cache,address:V(e),onEvent:this.#t})}createToken(e,t){return new bt({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,cache:this.cache,address:V(e),wrapper:t?V(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Z({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let t=e.map(e=>({handle:e.handle,contractAddress:V(e.contractAddress)})),n={},r=[];for(let e of t)e.handle===`0x0000000000000000000000000000000000000000000000000000000000000000`?n[e.handle]=0n:r.push(e);if(r.length===0)return n;let i=await this.signer.getAddress(),a=[];for(let e of r){let t=await this.cache.get(i,e.contractAddress,e.handle);t===null?a.push(e):n[e.handle]=t}if(a.length===0)return n;let o=[...new Set(t.map(e=>e.contractAddress))],s=await this.credentials.allow(...o),c=new Map;for(let e of a){let t=c.get(e.contractAddress);t?t.push(e.handle):c.set(e.contractAddress,[e.handle])}let u=Date.now(),d=a.map(e=>e.handle);this.#t({type:m.DecryptStart,timestamp:u,handles:d});try{return await l([...c.entries()].map(([e,t])=>async()=>{let r=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:s.contractAddresses,privateKey:s.privateKey,publicKey:s.publicKey,signature:s.signature,signerAddress:i,startTimestamp:s.startTimestamp,durationDays:s.durationDays});for(let[t,a]of Object.entries(r))n[t]=a,await this.cache.set(i,e,t,a)}),5),this.#t({type:m.DecryptEnd,durationMs:Date.now()-u,timestamp:Date.now(),handles:d,result:n}),n}catch(e){throw this.#t({type:m.DecryptError,error:A(e),durationMs:Date.now()-u,timestamp:Date.now(),handles:d}),te(e,`Failed to decrypt handles`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await S.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}async function Ct(e,t,n){await e.set($(t),n)}async function wt(e,t){return e.get($(t))}async function Tt(e,t){await e.delete($(t))}var Et=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 Dt=new Et;export{ue as ACL_TOPICS,w as AclPausedError,Ce as AclTopics,H as ApprovalFailedError,G as BalanceCheckUnavailableError,Et as ChromeSessionStorage,i as ConfigurationError,S as CredentialsManager,re as DecryptCache,O as DecryptionFailedError,xt as DefaultRegistryAddresses,o as DelegatedCredentialsManager,ee as DelegationContractIsSelfError,ce as DelegationCooldownError,y as DelegationDelegateEqualsContractError,b as DelegationExpirationTooSoonError,ae as DelegationExpiredError,a as DelegationExpiryUnchangedError,x as DelegationNotFoundError,je as DelegationNotPropagatedError,C as DelegationSelfNotAllowedError,pt as ERC20ReadFailedError,Ye as ERC7984_INTERFACE_ID,tt as ERC7984_WRAPPER_INTERFACE_ID,D as EncryptionFailedError,Ue as HardhatConfig,J as IndexedDBStorage,W as InsufficientConfidentialBalanceError,ft as InsufficientERC20BalanceError,De as InvalidKeypairError,ye as KeypairExpiredError,N as MainnetConfig,Ve as MemoryStorage,de as NoCiphertextError,T as ReadonlyToken,n as RelayerRequestFailedError,yt as RelayerWeb,j as SepoliaConfig,we as SigningFailedError,ke as SigningRejectedError,Oe as TOKEN_TOPICS,bt as Token,pe as Topics,U as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,St as ZamaSDK,m as ZamaSDKEvents,E as allowanceContract,Ae as applyDecryptedValues,s as approveContract,_ as balanceOfContract,Dt as chromeSessionStorage,Tt as clearPendingUnshield,rt as confidentialBalanceOfContract,nt as confidentialTotalSupplyContract,$e as confidentialTransferContract,Qe as confidentialTransferFromContract,f as decimalsContract,be as decodeAclEvent,Me as decodeAclEvents,me as decodeConfidentialTransfer,he as decodeDelegatedForUserDecryption,Te as decodeOnChainEvent,xe as decodeOnChainEvents,_e as decodeRevokedDelegationForUserDecryption,ge as decodeUnwrapRequested,le as decodeUnwrappedFinalized,Ne as decodeUnwrappedStarted,Fe as decodeWrapped,u as delegateForUserDecryptionContract,Se as extractEncryptedHandles,We as finalizeUnwrapContract,fe as findDelegatedForUserDecryption,Pe as findRevokedDelegationForUserDecryption,g as findUnwrapRequested,c as findWrapped,B as getConfidentialTokenAddressContract,p as getDelegationExpiryContract,L as getTokenAddressContract,it as getTokenPairContract,et as getTokenPairsContract,I as getTokenPairsLengthContract,R as getTokenPairsSliceContract,ht as indexedDBStorage,st as inferredTotalSupplyContract,at as isConfidentialTokenContract,z as isConfidentialTokenValidContract,Xe as isConfidentialWrapperContract,ne as isHandleDelegatedContract,qe as isOperatorContract,wt as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,Be as memoryStorage,v as nameContract,Ee as parseActivityFeed,ot as rateContract,h as revokeDelegationContract,Ct as savePendingUnshield,lt as setOperatorContract,ve as sortByBlockNumber,Ze as supportsInterfaceContract,d as symbolContract,Je as totalSupplyContract,F as underlyingContract,ct as unwrapContract,Ke as unwrapFromBalanceContract,Ge as wrapContract};
515
515
  //# sourceMappingURL=index.js.map