@zama-fhe/sdk 2.3.0-alpha.3 → 2.3.0

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.
Files changed (45) hide show
  1. package/dist/cjs/activity.cjs +1 -1
  2. package/dist/cjs/activity.cjs.map +1 -1
  3. package/dist/cjs/cleartext.cjs +1 -1
  4. package/dist/cjs/cleartext.cjs.map +1 -1
  5. package/dist/cjs/index.cjs +2 -2
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/query/index.cjs +1 -1
  8. package/dist/cjs/query/index.cjs.map +1 -1
  9. package/dist/cjs/relayer.cjs +1 -1
  10. package/dist/cjs/relayer.cjs.map +1 -1
  11. package/dist/esm/{activity-D8okM6NP.d.ts → activity-DTBvolDB.d.ts} +210 -15
  12. package/dist/esm/{activity-DVF6Mxsn.js → activity-b2RsqKHW.js} +2 -2
  13. package/dist/esm/{activity-DVF6Mxsn.js.map → activity-b2RsqKHW.js.map} +1 -1
  14. package/dist/esm/cleartext/index.d.ts +5 -3
  15. package/dist/esm/cleartext/index.js +1 -1
  16. package/dist/esm/{cleartext-BU7SYjBM.js → cleartext-Bzxet3H7.js} +2 -2
  17. package/dist/esm/cleartext-Bzxet3H7.js.map +1 -0
  18. package/dist/esm/{encryption-UaXE1L_W.js → encryption-CmIPBcfP.js} +2 -2
  19. package/dist/esm/{encryption-UaXE1L_W.js.map → encryption-CmIPBcfP.js.map} +1 -1
  20. package/dist/esm/ethers/index.d.ts +2 -2
  21. package/dist/esm/{fhe-artifact-cache-DMw74maw.js → fhe-artifact-cache-CyXna-Br.js} +2 -2
  22. package/dist/esm/{fhe-artifact-cache-DMw74maw.js.map → fhe-artifact-cache-CyXna-Br.js.map} +1 -1
  23. package/dist/esm/{index-C3ELlhM8.d.ts → index-BXdXzzx4.d.ts} +2 -2
  24. package/dist/esm/index.d.ts +8 -129
  25. package/dist/esm/index.js +2 -2
  26. package/dist/esm/index.js.map +1 -1
  27. package/dist/esm/memory-storage-B4_heQa5.js +2 -0
  28. package/dist/esm/memory-storage-B4_heQa5.js.map +1 -0
  29. package/dist/esm/node/index.d.ts +5 -3
  30. package/dist/esm/node/index.js +1 -1
  31. package/dist/esm/node/index.js.map +1 -1
  32. package/dist/esm/query/index.d.ts +10 -18
  33. package/dist/esm/query/index.js +1 -1
  34. package/dist/esm/query/index.js.map +1 -1
  35. package/dist/esm/relayer-C6u3eOlN.js +2 -0
  36. package/dist/esm/relayer-C6u3eOlN.js.map +1 -0
  37. package/dist/esm/{relayer-sdk-Cqx3HnZh.d.ts → relayer-sdk-C_4bkxxH.d.ts} +2 -2
  38. package/dist/esm/{relayer-sdk.types-BhV3n5qO.d.ts → relayer-sdk.types-C9GAgQ7q.d.ts} +23 -2
  39. package/dist/esm/viem/index.d.ts +2 -2
  40. package/package.json +1 -1
  41. package/dist/esm/cleartext-BU7SYjBM.js.map +0 -1
  42. package/dist/esm/memory-storage-BkqO2DFz.js +0 -2
  43. package/dist/esm/memory-storage-BkqO2DFz.js.map +0 -1
  44. package/dist/esm/relayer-DfjPWTBf.js +0 -2
  45. package/dist/esm/relayer-DfjPWTBf.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { A as WriteContractArgs, C as TransactionReceipt, D as ReadContractConfig, E as ReadContractArgs, M as WriteFunctionName, O as ReadContractReturnType, S as RawLog, T as ContractAbi, Y as GenericLogger, _ as DelegatedStoredCredentials, a as EncryptParams, b as GenericSigner, c as NetworkType, d as RelayerWebConfig, f as RelayerWebSecurityConfig, g as UnshieldCallbacks, h as TransferCallbacks, i as EncryptInput, j as WriteContractConfig, k as ReadFunctionName, l as PublicDecryptResult, m as ShieldCallbacks, n as DelegatedUserDecryptParams, o as EncryptResult, p as UserDecryptParams, r as EIP712TypedData, s as Handle, t as ClearValueType, u as RelayerSDKStatus, v as StoredCredentials, w as TransactionResult, x as SignerLifecycleCallbacks, y as GenericStorage } from "./relayer-sdk.types-BhV3n5qO.js";
2
- import { A as balanceOfContract, B as confidentialTransferContract, C as isConfidentialTokenContract, D as wrapperExistsContract, E as getWrapperContract, F as underlyingContract, G as rateContract, H as deploymentCoordinatorContract, I as wrapContract, J as totalSupplyContract, K as setFinalizeUnwrapOperatorContract, L as wrapETHContract, M as nameContract, N as symbolContract, O as allowanceContract, P as finalizeUnwrapContract, R as confidentialBalanceOfContract, S as ERC7984_WRAPPER_INTERFACE_ID, T as supportsInterfaceContract, U as isFinalizeUnwrapOperatorContract, V as confidentialTransferFromContract, W as isOperatorContract, X as unwrapFromBalanceContract, Y as unwrapContract, _ as getBatchTransferFeeContract, a as getTokenAddressContract, b as getWrapFeeContract, c as getTokenPairsLengthContract, d as delegateForUserDecryptionContract, f as getDelegationExpiryContract, g as confidentialBatchTransferContract, h as BatchTransferData, i as getConfidentialTokenAddressContract, j as decimalsContract, k as approveContract, l as getTokenPairsSliceContract, m as revokeDelegationContract, n as TokenWrapperPair, o as getTokenPairContract, p as isHandleDelegatedContract, q as setOperatorContract, r as TokenWrapperPairWithMetadata, s as getTokenPairsContract, t as PaginatedResult, u as isConfidentialTokenValidContract, v as getFeeRecipientContract, w as isConfidentialWrapperContract, x as ERC7984_INTERFACE_ID, y as getUnwrapFeeContract, z as confidentialTotalSupplyContract } from "./index-C3ELlhM8.js";
3
- import { t as RelayerSDK } from "./relayer-sdk-Cqx3HnZh.js";
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-C9GAgQ7q.js";
2
+ import { A as balanceOfContract, B as confidentialTransferContract, C as isConfidentialTokenContract, D as wrapperExistsContract, E as getWrapperContract, F as underlyingContract, G as rateContract, H as deploymentCoordinatorContract, I as wrapContract, J as totalSupplyContract, K as setFinalizeUnwrapOperatorContract, L as wrapETHContract, M as nameContract, N as symbolContract, O as allowanceContract, P as finalizeUnwrapContract, R as confidentialBalanceOfContract, S as ERC7984_WRAPPER_INTERFACE_ID, T as supportsInterfaceContract, U as isFinalizeUnwrapOperatorContract, V as confidentialTransferFromContract, W as isOperatorContract, X as unwrapFromBalanceContract, Y as unwrapContract, _ as getBatchTransferFeeContract, a as getTokenAddressContract, b as getWrapFeeContract, c as getTokenPairsLengthContract, d as delegateForUserDecryptionContract, f as getDelegationExpiryContract, g as confidentialBatchTransferContract, h as BatchTransferData, i as getConfidentialTokenAddressContract, j as decimalsContract, k as approveContract, l as getTokenPairsSliceContract, m as revokeDelegationContract, n as TokenWrapperPair, o as getTokenPairContract, p as isHandleDelegatedContract, q as setOperatorContract, r as TokenWrapperPairWithMetadata, s as getTokenPairsContract, t as PaginatedResult, u as isConfidentialTokenValidContract, v as getFeeRecipientContract, w as isConfidentialWrapperContract, x as ERC7984_INTERFACE_ID, y as getUnwrapFeeContract, z as confidentialTotalSupplyContract } from "./index-BXdXzzx4.js";
3
+ import { t as RelayerSDK } from "./relayer-sdk-C_4bkxxH.js";
4
4
  import { n as MainnetConfig, r as SepoliaConfig, t as HardhatConfig } from "./relayer-utils-BcTAyZOr.js";
5
- import { $ as ZERO_HANDLE, A as decodeUnwrapRequested, At as UnshieldPhase1SubmittedEvent, B as DefaultRegistryAddresses, C as decodeAclEvent, Ct as FinalizeUnwrapSubmittedEvent, D as decodeOnChainEvent, Dt as TransactionErrorEvent, E as decodeDelegatedForUserDecryption, Et as ShieldSubmittedEvent, F as findRevokedDelegationForUserDecryption, Ft as ZamaSDKEventInput, G as TokenConfig, H as WrappersRegistry, I as findUnwrapRequested, It as ZamaSDKEventListener, J as matchZamaError, K as ZamaError, L as findWrapped, Lt as ZamaSDKEventType, M as decodeUnwrappedStarted, Mt as UnshieldPhase2SubmittedEvent, N as decodeWrapped, Nt as UnwrapSubmittedEvent, O as decodeOnChainEvents, Ot as TransferFromSubmittedEvent, P as findDelegatedForUserDecryption, Pt as ZamaSDKEvent, Q as ReadonlyTokenConfig, R as ZamaSDK, Rt as ZamaSDKEvents, S as WrappedEvent, St as EncryptStartEvent, T as decodeConfidentialTransfer, Tt as SessionExpiredEvent, U as WrappersRegistryConfig, V as ListPairsOptions, W as Token, X as BatchDecryptOptions, Y as BatchDecryptAsOptions, Z as ReadonlyToken, _ as TOKEN_TOPICS, _t as DecryptErrorEvent, a as ActivityType, at as ApproveUnderlyingSubmittedEvent, b as UnwrappedFinalizedEvent, bt as EncryptEndEvent, c as parseActivityFeed, ct as CredentialsCachedEvent, d as AclEvent, dt as CredentialsCreatingEvent, et as DelegatedCredentialsManager, f as AclTopics, ft as CredentialsExpiredEvent, g as RevokedDelegationForUserDecryptionEvent, gt as DecryptEndEvent, h as OnChainEvent, ht as CredentialsRevokedEvent, i as ActivityLogMetadata, it as ApproveSubmittedEvent, j as decodeUnwrappedFinalized, jt as UnshieldPhase2StartedEvent, k as decodeRevokedDelegationForUserDecryption, kt as TransferSubmittedEvent, l as sortByBlockNumber, lt as CredentialsCorruptedEvent, m as DelegatedForUserDecryptionEvent, mt as CredentialsPersistFailedEvent, n as ActivityDirection, nt as CredentialsManager, o as applyDecryptedValues, ot as BaseEvent, p as ConfidentialTransferEvent, pt as CredentialsLoadingEvent, q as ZamaErrorCode, r as ActivityItem, rt as CredentialsManagerConfig, s as extractEncryptedHandles, st as CredentialsAllowedEvent, t as ActivityAmount, tt as DelegatedCredentialsManagerConfig, u as ACL_TOPICS, ut as CredentialsCreatedEvent, v as Topics, vt as DecryptStartEvent, w as decodeAclEvents, wt as RevokeDelegationSubmittedEvent, x as UnwrappedStartedEvent, xt as EncryptErrorEvent, y as UnwrapRequestedEvent, yt as DelegationSubmittedEvent, z as ZamaSDKConfig } from "./activity-D8okM6NP.js";
5
+ import { $ as DelegationContractIsSelfError, $t as ShieldSubmittedEvent, A as decodeUnwrapRequested, At as CredentialsManagerConfig, B as DefaultRegistryAddresses, Bt as CredentialsLoadingEvent, C as decodeAclEvent, Ct as BatchDecryptOptions, D as decodeOnChainEvent, Dt as DelegatedCredentialsManager, E as decodeDelegatedForUserDecryption, Et as ZERO_HANDLE, F as findRevokedDelegationForUserDecryption, Ft as CredentialsCachedEvent, G as TokenConfig, Gt as DecryptStartEvent, H as WrappersRegistry, Ht as CredentialsRevokedEvent, I as findUnwrapRequested, It as CredentialsCorruptedEvent, J as BalanceErrorDetails, Jt as EncryptErrorEvent, K as matchAclRevert, Kt as DelegationSubmittedEvent, L as findWrapped, Lt as CredentialsCreatedEvent, M as decodeUnwrappedStarted, Mt as ApproveUnderlyingSubmittedEvent, N as decodeWrapped, Nt as BaseEvent, O as decodeOnChainEvents, Ot as DelegatedCredentialsManagerConfig, P as findDelegatedForUserDecryption, Pt as CredentialsAllowedEvent, Q as AclPausedError, Qt as SessionExpiredEvent, R as ZamaSDK, Rt as CredentialsCreatingEvent, S as WrappedEvent, St as BatchDecryptAsOptions, T as decodeConfidentialTransfer, Tt as ReadonlyTokenConfig, U as WrappersRegistryConfig, Ut as DecryptEndEvent, V as ListPairsOptions, Vt as CredentialsPersistFailedEvent, W as Token, Wt as DecryptErrorEvent, X as InsufficientConfidentialBalanceError, Xt as FinalizeUnwrapSubmittedEvent, Y as ERC20ReadFailedError, Yt as EncryptStartEvent, Z as InsufficientERC20BalanceError, Zt as RevokeDelegationSubmittedEvent, _ as TOKEN_TOPICS, _t as SigningFailedError, a as ActivityType, an as UnshieldPhase2SubmittedEvent, at as DelegationNotFoundError, b as UnwrappedFinalizedEvent, bt as ZamaErrorCode, c as parseActivityFeed, cn as ZamaSDKEventInput, ct as ConfigurationError, d as AclEvent, dn as ZamaSDKEvents, dt as KeypairExpiredError, en as TransactionErrorEvent, et as DelegationCooldownError, f as AclTopics, ft as NoCiphertextError, g as RevokedDelegationForUserDecryptionEvent, gt as EncryptionFailedError, h as OnChainEvent, ht as DecryptionFailedError, i as ActivityLogMetadata, in as UnshieldPhase2StartedEvent, it as DelegationExpiryUnchangedError, j as decodeUnwrappedFinalized, jt as ApproveSubmittedEvent, k as decodeRevokedDelegationForUserDecryption, kt as CredentialsManager, l as sortByBlockNumber, ln as ZamaSDKEventListener, lt as RelayerRequestFailedError, m as DelegatedForUserDecryptionEvent, mt as TransactionRevertedError, n as ActivityDirection, nn as TransferSubmittedEvent, nt as DelegationExpirationTooSoonError, o as applyDecryptedValues, on as UnwrapSubmittedEvent, ot as DelegationNotPropagatedError, p as ConfidentialTransferEvent, pt as ApprovalFailedError, q as BalanceCheckUnavailableError, qt as EncryptEndEvent, r as ActivityItem, rn as UnshieldPhase1SubmittedEvent, rt as DelegationExpiredError, s as extractEncryptedHandles, sn as ZamaSDKEvent, st as DelegationSelfNotAllowedError, t as ActivityAmount, tn as TransferFromSubmittedEvent, tt as DelegationDelegateEqualsContractError, u as ACL_TOPICS, un as ZamaSDKEventType, ut as InvalidKeypairError, v as Topics, vt as SigningRejectedError, w as decodeAclEvents, wt as ReadonlyToken, x as UnwrappedStartedEvent, xt as matchZamaError, y as UnwrapRequestedEvent, yt as ZamaError, z as ZamaSDKConfig, zt as CredentialsExpiredEvent } from "./activity-DTBvolDB.js";
6
6
  import { Address, Address as Address$1, Hex, Hex as Hex$1 } from "viem";
7
7
  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";
8
8
 
@@ -31,7 +31,7 @@ import { FheTypeName, FhevmInstanceConfig, InputProofBytesType, InputProofBytesT
31
31
  * is cleared, and a fresh worker is created for the new chain — all within
32
32
  * the `#ensureLock` critical section.
33
33
  */
34
- declare class RelayerWeb implements RelayerSDK {
34
+ declare class RelayerWeb implements RelayerSDK, Disposable {
35
35
  #private;
36
36
  constructor(config: RelayerWebConfig);
37
37
  /** Current WASM initialization status. */
@@ -43,6 +43,8 @@ declare class RelayerWeb implements RelayerSDK {
43
43
  * Call this when the SDK is no longer needed.
44
44
  */
45
45
  terminate(): void;
46
+ /** Calls {@link terminate}, shutting down the Web Worker. */
47
+ [Symbol.dispose](): void;
46
48
  /**
47
49
  * Generate a keypair for FHE operations.
48
50
  */
@@ -98,129 +100,6 @@ declare class RelayerWeb implements RelayerSDK {
98
100
  getAclAddress(): Promise<Address$1>;
99
101
  }
100
102
  //#endregion
101
- //#region src/errors/signing.d.ts
102
- /** User rejected the wallet signature prompt. */
103
- declare class SigningRejectedError extends ZamaError {
104
- constructor(message: string, options?: ErrorOptions);
105
- }
106
- /** Wallet signature failed for a reason other than rejection. */
107
- declare class SigningFailedError extends ZamaError {
108
- constructor(message: string, options?: ErrorOptions);
109
- }
110
- //#endregion
111
- //#region src/errors/encryption.d.ts
112
- /** FHE encryption failed. */
113
- declare class EncryptionFailedError extends ZamaError {
114
- constructor(message: string, options?: ErrorOptions);
115
- }
116
- /** FHE decryption failed. */
117
- declare class DecryptionFailedError extends ZamaError {
118
- constructor(message: string, options?: ErrorOptions);
119
- }
120
- //#endregion
121
- //#region src/errors/transaction.d.ts
122
- /** ERC-20 approval transaction failed. */
123
- declare class ApprovalFailedError extends ZamaError {
124
- constructor(message: string, options?: ErrorOptions);
125
- }
126
- /** On-chain transaction reverted. */
127
- declare class TransactionRevertedError extends ZamaError {
128
- constructor(message: string, options?: ErrorOptions);
129
- }
130
- //#endregion
131
- //#region src/errors/credential.d.ts
132
- /** FHE keypair has expired and needs regeneration. */
133
- declare class KeypairExpiredError extends ZamaError {
134
- constructor(message: string, options?: ErrorOptions);
135
- }
136
- /** Relayer rejected FHE keypair (stale, expired, or malformed). */
137
- declare class InvalidKeypairError extends ZamaError {
138
- constructor(message: string, options?: ErrorOptions);
139
- }
140
- /** No FHE ciphertext exists for this account (never shielded). */
141
- declare class NoCiphertextError extends ZamaError {
142
- constructor(message: string, options?: ErrorOptions);
143
- }
144
- //#endregion
145
- //#region src/errors/relayer.d.ts
146
- /** Relayer HTTP request failed. */
147
- declare class RelayerRequestFailedError extends ZamaError {
148
- /** HTTP status code from the relayer, if available. */
149
- readonly statusCode: number | undefined;
150
- constructor(message: string, statusCode?: number, options?: ErrorOptions);
151
- }
152
- /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */
153
- declare class ConfigurationError extends ZamaError {
154
- constructor(message: string, options?: ErrorOptions);
155
- }
156
- //#endregion
157
- //#region src/errors/delegation.d.ts
158
- /** Delegation cannot target self (delegate === msg.sender). */
159
- declare class DelegationSelfNotAllowedError extends ZamaError {
160
- constructor(message: string, options?: ErrorOptions);
161
- }
162
- /** Only one delegate/revoke per (delegator, delegate, contract) per block. */
163
- declare class DelegationCooldownError extends ZamaError {
164
- constructor(message: string, options?: ErrorOptions);
165
- }
166
- /** No active delegation found for this (delegator, delegate, contract) tuple. */
167
- declare class DelegationNotFoundError extends ZamaError {
168
- constructor(message: string, options?: ErrorOptions);
169
- }
170
- /** The delegation has expired. */
171
- declare class DelegationExpiredError extends ZamaError {
172
- constructor(message: string, options?: ErrorOptions);
173
- }
174
- /** The new expiration date equals the current one. */
175
- declare class DelegationExpiryUnchangedError extends ZamaError {
176
- constructor(message: string, options?: ErrorOptions);
177
- }
178
- /** Delegate address cannot be the contract address. */
179
- declare class DelegationDelegateEqualsContractError extends ZamaError {
180
- constructor(message: string, options?: ErrorOptions);
181
- }
182
- /** Contract address cannot be the sender address. */
183
- declare class DelegationContractIsSelfError extends ZamaError {
184
- constructor(message: string, options?: ErrorOptions);
185
- }
186
- /** The ACL contract is paused. */
187
- declare class AclPausedError extends ZamaError {
188
- constructor(message: string, options?: ErrorOptions);
189
- }
190
- /** Expiration date is too soon (must be at least 1 hour in the future). */
191
- declare class DelegationExpirationTooSoonError extends ZamaError {
192
- constructor(message: string, options?: ErrorOptions);
193
- }
194
- /**
195
- * Delegation exists on L1 but hasn't propagated to the gateway yet.
196
- *
197
- * After calling `delegateForUserDecryption()`, the delegation is recorded on-chain
198
- * immediately. However, the gateway (deployed on Arbitrum) must sync this state
199
- * via cross-chain event propagation, which typically takes 1–2 minutes.
200
- *
201
- * Calling `decryptBalanceAs` during this window will fail because the gateway's
202
- * `isHandleDelegatedForUserDecryption()` check reads from its own synced copy
203
- * of the ACL state, which hasn't been updated yet.
204
- *
205
- * **Note:** This error is raised as a best-effort heuristic — when a delegated
206
- * decryption receives an HTTP 500 from the relayer, the most likely cause is a
207
- * propagation delay. However, the same status code can occur if the gateway or
208
- * relayer experiences an unrelated internal error.
209
- */
210
- declare class DelegationNotPropagatedError extends ZamaError {
211
- constructor(message: string, options?: ErrorOptions);
212
- }
213
- //#endregion
214
- //#region src/errors/acl-revert.d.ts
215
- /**
216
- * Map known ACL Solidity revert error names to typed ZamaError subclasses.
217
- * Prefers viem's structured `error.cause.data.errorName` when available,
218
- * falling back to string-includes matching on the error message.
219
- * Returns `null` if the revert reason is not recognized.
220
- * @public
221
- */
222
- declare function matchAclRevert(error: unknown): ZamaError | null;
223
- //#endregion
224
103
  //#region src/token/pending-unshield.d.ts
225
104
  /**
226
105
  * Persist the unwrap tx hash so an interrupted unshield can be resumed later
@@ -294,5 +173,5 @@ declare class ChromeSessionStorage implements GenericStorage {
294
173
  /** Default singleton for application-wide use. */
295
174
  declare const chromeSessionStorage: ChromeSessionStorage;
296
175
  //#endregion
297
- export { ACL_TOPICS, type AclEvent, AclPausedError, AclTopics, type ActivityAmount, type ActivityDirection, type ActivityItem, type ActivityLogMetadata, type ActivityType, type Address, ApprovalFailedError, type ApproveSubmittedEvent, type ApproveUnderlyingSubmittedEvent, type BaseEvent, type BatchDecryptAsOptions, type BatchDecryptOptions, type BatchTransferData, 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, 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, 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, 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 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 TransferSubmittedEvent, type UnshieldCallbacks, 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, confidentialBatchTransferContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapRequested, decodeUnwrappedFinalized, decodeUnwrappedStarted, decodeWrapped, delegateForUserDecryptionContract, deploymentCoordinatorContract, extractEncryptedHandles, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrapped, getBatchTransferFeeContract, getConfidentialTokenAddressContract, getDelegationExpiryContract, getFeeRecipientContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, getUnwrapFeeContract, getWrapFeeContract, getWrapperContract, indexedDBStorage, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isFinalizeUnwrapOperatorContract, isHandleDelegatedContract, isOperatorContract, loadPendingUnshield, matchAclRevert, matchZamaError, memoryStorage, nameContract, parseActivityFeed, rateContract, revokeDelegationContract, savePendingUnshield, setFinalizeUnwrapOperatorContract, setOperatorContract, sortByBlockNumber, supportsInterfaceContract, symbolContract, totalSupplyContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract, wrapETHContract, wrapperExistsContract };
176
+ 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, type BatchTransferData, 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, 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, confidentialBatchTransferContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapRequested, decodeUnwrappedFinalized, decodeUnwrappedStarted, decodeWrapped, delegateForUserDecryptionContract, deploymentCoordinatorContract, extractEncryptedHandles, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrapped, getBatchTransferFeeContract, getConfidentialTokenAddressContract, getDelegationExpiryContract, getFeeRecipientContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, getUnwrapFeeContract, getWrapFeeContract, getWrapperContract, indexedDBStorage, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isFinalizeUnwrapOperatorContract, isHandleDelegatedContract, isOperatorContract, loadPendingUnshield, matchAclRevert, matchZamaError, memoryStorage, nameContract, parseActivityFeed, rateContract, revokeDelegationContract, savePendingUnshield, setFinalizeUnwrapOperatorContract, setOperatorContract, sortByBlockNumber, supportsInterfaceContract, symbolContract, totalSupplyContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract, wrapETHContract, wrapperExistsContract };
298
177
  //# 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-DfjPWTBf.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 ee,J as m,K as te,L as ne,M as re,N as h,O as g,P as ie,Q as _,R as v,S as y,T as ae,U as b,V as x,W as S,X as oe,Y as C,Z as w,_ as se,a as ce,at as le,b as ue,c as de,d as fe,et as T,f as pe,g as me,h as he,i as ge,it 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 E,r as Ee,rt as De,s as Oe,t as ke,tt as Ae,u as je,v as Me,w as D,x as Ne,y as Pe,z as O}from"./activity-DVF6Mxsn.js";import{n as k,t as A}from"./encryption-UaXE1L_W.js";import{n as Fe,t as Ie}from"./fhe-artifact-cache-DMw74maw.js";import{a as Le,r as Re,s as ze}from"./assertions-Dty7Quc0.js";import{n as Be,r as j,t as Ve}from"./memory-storage-BkqO2DFz.js";import{a as He,i as M,n as Ue,o as N,r as P,t as F}from"./relayer-utils-BeoTNDM4.js";import{C as We,D as Ge,E as Ke,O as qe,S as Je,T as Ye,_ as Xe,a as I,b as Ze,c as Qe,d as $e,f as et,g as tt,h as nt,i as rt,k as L,l as it,m as R,n as z,o as B,p as V,r as at,s as H,t as U,u as ot,v as st,w as ct,x as lt,y as ut}from"./wrappers-registry-DqPr_JG2.js";import{n as dt,r as ft,t as pt}from"./transfer-batcher-BXIo7hnu.js";import{n as mt}from"./cleartext-BU7SYjBM.js";import{getAddress as W,hexToBigInt as ht}from"viem";var G=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},K=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}};function gt(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 q={AlreadyDelegatedOrRevokedInSameBlock:e=>new E(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new te(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new f(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new T(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new m(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new _(`Cannot revoke: no active delegation exists.`,{cause:e})};function J(e){let t=e instanceof Error?e:void 0,n=gt(e);if(n&&n in q)return q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(q))if(r.includes(e))return n(t);return null}var Y=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 _t=new Y;function vt(e){try{return Le(e,`runtime`),ze(e,`id`,`runtime.id`),Re(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function yt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(Le(t,`ns`),vt(t.runtime))return t.runtime}catch{continue}}var bt=`(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,D as l,E as u,F as d,G as f,H as p,I as ee,J as m,K as te,L as ne,M as re,N as ie,O as h,P as g,Q as _,R as ae,S as v,T as oe,U as se,V as ce,W as y,X as b,Y as x,Z as le,_ as ue,a as de,at as fe,b as pe,c as me,d as he,et as ge,f as _e,g as ve,h as ye,i as be,it as xe,j as Se,k as S,l as Ce,m as we,n as Te,nt as Ee,o as De,ot as Oe,p as ke,q as C,r as Ae,rt as je,s as Me,t as Ne,tt as w,u as Pe,v as Fe,w as T,x as Ie,y as Le,z as E}from"./activity-b2RsqKHW.js";import{n as D,t as O}from"./encryption-CmIPBcfP.js";import{n as Re,t as ze}from"./fhe-artifact-cache-CyXna-Br.js";import{a as k,r as Be,s as Ve}from"./assertions-Dty7Quc0.js";import{i as A,n as He,t as Ue}from"./memory-storage-B4_heQa5.js";import{a as We,i as j,n as Ge,o as M,r as N,t as P}from"./relayer-utils-BeoTNDM4.js";import{C as Ke,D as qe,E as Je,O as Ye,S as Xe,T as Ze,_ as Qe,a as F,b as $e,c as et,d as tt,f as nt,g as rt,h as it,i as at,k as ot,l as st,m as ct,n as I,o as L,p as lt,r as ut,s as R,t as z,u as dt,v as ft,w as pt,x as mt,y as ht}from"./wrappers-registry-DqPr_JG2.js";import{n as gt,r as _t,t as vt}from"./transfer-batcher-BXIo7hnu.js";import{n as yt}from"./cleartext-Bzxet3H7.js";import{getAddress as B,hexToBigInt as bt}from"viem";var V=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},H=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},U=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}},W=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`}},xt=class extends r{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function St(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 m(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new C(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new te(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new w(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new b(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new _(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new a(`Cannot revoke: no active delegation exists.`,{cause:e})};function q(e){let t=e instanceof Error?e:void 0,n=St(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 Ct=new J;function wt(e){try{return k(e,`runtime`),Ve(e,`id`,`runtime.id`),Be(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function Tt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(k(t,`ns`),wt(t.runtime))return t.runtime}catch{continue}}var Et=class extends Re{constructor(e){super(e,e.logger)}createWorker(){let e=Tt();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-DfjPWTBf.js";import{$ as a,A as o
511
511
  };
512
512
  //#endregion
513
513
  })();
514
- `,xt=class extends Fe{constructor(e){super(e,e.logger)}createWorker(){let e=yt();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([bt],{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})}},St=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({},F[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 Y(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},F[e],this.#l.transports[e]);this.#a=new Ie({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 xt(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}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 N(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 N(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return N(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 N(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return N(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({},F[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},Ct=class e extends D{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?W(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(R(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 i=W(e),a,o,s=Date.now();try{this.emit({type:g.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-s}),X(()=>n?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-s}),e instanceof r?e:new k(`Failed to encrypt transfer amount`,{cause:e})}if(a.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ut(this.address,i,a[0],o));return this.emit({type:g.TransferSubmitted,txHash:e}),X(()=>n?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:j(e)}),e instanceof r?e:new K(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=W(e),o=W(t),s,c,l=Date.now();try{this.emit({type:g.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-l}),X(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-l}),e instanceof r?e:new k(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Ze(this.address,a,o,s[0],c));return this.emit({type:g.TransferFromSubmitted,txHash:e}),X(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:j(e)}),e instanceof r?e:new K(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=W(e);try{let e=await this.signer.writeContract(Ke(this.address,n,t));return this.emit({type:g.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approve`,error:j(e)}),e instanceof r?e:new G(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=W(e),r=t?W(t):await this.signer.getAddress();return this.signer.readContract(We(this.address,r,n))}async shield(t,n){if(await this.#n()===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#a(t,i===`max`,n?.callbacks);try{let e=n?.to?W(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(nt(this.wrapper,e,t));return this.emit({type:g.ShieldSubmitted,txHash:r}),X(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:j(e)}),e instanceof r?e:new K(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(tt(this.wrapper,n,e,t??e));return this.emit({type:g.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shieldETH`,error:j(e)}),e instanceof r?e:new K(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:g.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-a}),e instanceof r?e:new k(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(qe(this.address,t,t,n[0],i));return this.emit({type:g.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:j(e)}),e instanceof r?e:new K(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new A(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(L(this.address,e,e,t));return this.emit({type:g.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:j(e)}),e instanceof r?e:new K(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let n=crypto.randomUUID(),r=await this.unwrap(e);return X(()=>t?.onUnwrapSubmitted?.(r.txHash)),this.#i(r.txHash,t,n)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return X(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#i(n.txHash,e,t)}async resumeUnshield(e,t){return this.#i(e,t,crypto.randomUUID())}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:g.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:g.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=ht(r.abiEncodedClearValues)}catch{throw new A(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:g.DecryptError,error:j(e),durationMs:Date.now()-i}),e instanceof r?e:new A(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(V(this.wrapper,e,t,n));return this.emit({type:g.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`finalizeUnwrap`,error:j(e)}),e instanceof r?e:new K(`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(v(t,e,this.wrapper))>0n&&await this.signer.writeContract(O(t,this.wrapper,0n))}let e=await this.signer.writeContract(O(t,this.wrapper,n));return this.emit({type:g.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approveUnderlying`,error:j(e)}),e instanceof r?e:new G(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new C(`Expiration date must be at least 1 hour in the future`);let n=W(e),i=await this.signer.getAddress();if(n===W(i))throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new m(`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)):ye;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new w(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(o(a,n,this.address,s));return this.emit({type:g.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`delegateDecryption`,error:j(e)}),e instanceof r?e:J(e)||new K(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=W(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new _(`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:g.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`revokeDelegation`,error:j(e)}),e instanceof r?e:J(e)||new K(`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,a=await Promise.allSettled(e.map(t));for(let t=0;t<e.length;t++){let o=a[t];if(o.status===`fulfilled`)i.set(e[t].address,o.value);else{let a=o.reason instanceof r?o.reason:new K(n,{cause:o.reason});i.set(e[t].address,a)}}return i}async#i(e,t,n){this.emit({type:g.UnshieldPhase1Submitted,txHash:e,operationId:n});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new K(`Failed to get unshield receipt`,{cause:e})}let a=y(i.logs);if(!a)throw new K(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:n}),X(()=>t?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:g.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),X(()=>t?.onFinalizeSubmitted?.(o.txHash)),o}async#a(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(v(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(O(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(O(i,this.wrapper,r));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:a}),X(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new G(`ERC-20 approval failed`,{cause:e})}}};function X(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const wt={[P.chainId]:P.registryAddress,[M.chainId]:M.registryAddress,[mt.chainId]:mt.registryAddress},Z=300*1e3;var Q=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},wt,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 W(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(B(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?Z: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(b(e.tokenAddress)),this.signer.readContract(S(e.tokenAddress)),this.signer.readContract(x(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(b(e.confidentialTokenAddress)),this.signer.readContract(S(e.confidentialTokenAddress)),this.signer.readContract(x(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=W(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(U(t,n));if(!a)return this.#i(r,null,Z);let s=await this.signer.readContract(H(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=W(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,Z);let s=await this.signer.readContract(H(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(rt(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(B(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(at(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(U(t,W(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,W(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(H(t,W(e)))}},Tt=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;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.#t=e.onEvent??function(){},this.registry=new Q({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)throw Error(`keypairTTL must be a positive number (seconds)`);return 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:g.TransactionError,operation:e,error:j(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=W(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),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 D({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:W(e),onEvent:this.#t})}createToken(e,t){return new Ct({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:W(e),wrapper:t?W(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Q({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}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)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}};function $(e){return`zama:pending-unshield:${e}`}async function Et(e,t,n){await e.set($(t),n)}async function Dt(e,t){return e.get($(t))}async function Ot(e,t){await e.delete($(t))}var kt=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 At=new kt;export{ce as ACL_TOPICS,f as AclPausedError,we as AclTopics,G as ApprovalFailedError,kt as ChromeSessionStorage,i as ConfigurationError,l as CredentialsManager,A as DecryptionFailedError,wt as DefaultRegistryAddresses,u as DelegatedCredentialsManager,te as DelegationContractIsSelfError,E as DelegationCooldownError,m as DelegationDelegateEqualsContractError,C as DelegationExpirationTooSoonError,oe as DelegationExpiredError,w as DelegationExpiryUnchangedError,_ as DelegationNotFoundError,a as DelegationNotPropagatedError,T as DelegationSelfNotAllowedError,Qe as ERC7984_INTERFACE_ID,it as ERC7984_WRAPPER_INTERFACE_ID,k as EncryptionFailedError,Ue as HardhatConfig,Y as IndexedDBStorage,Ae as InvalidKeypairError,Ce as KeypairExpiredError,P as MainnetConfig,Ve as MemoryStorage,De as NoCiphertextError,D as ReadonlyToken,n as RelayerRequestFailedError,St as RelayerWeb,M as SepoliaConfig,_e as SigningFailedError,le as SigningRejectedError,Oe as TOKEN_TOPICS,Ct as Token,de as Topics,K as TransactionRevertedError,Q as WrappersRegistry,ae as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,Tt as ZamaSDK,g as ZamaSDKEvents,v as allowanceContract,ke as applyDecryptedValues,O as approveContract,s as balanceOfContract,At as chromeSessionStorage,Ot as clearPendingUnshield,Xe as confidentialBalanceOfContract,pt as confidentialBatchTransferContract,st as confidentialTotalSupplyContract,ut as confidentialTransferContract,Ze as confidentialTransferFromContract,x as decimalsContract,be as decodeAclEvent,je as decodeAclEvents,fe as decodeConfidentialTransfer,pe as decodeDelegatedForUserDecryption,Te as decodeOnChainEvent,xe as decodeOnChainEvents,he as decodeRevokedDelegationForUserDecryption,me as decodeUnwrapRequested,se as decodeUnwrappedFinalized,Me as decodeUnwrappedStarted,Pe as decodeWrapped,o as delegateForUserDecryptionContract,lt as deploymentCoordinatorContract,Se as extractEncryptedHandles,V as finalizeUnwrapContract,ue as findDelegatedForUserDecryption,Ne as findRevokedDelegationForUserDecryption,y as findUnwrapRequested,c as findWrapped,ie as getBatchTransferFeeContract,U as getConfidentialTokenAddressContract,ve as getDelegationExpiryContract,d as getFeeRecipientContract,z as getTokenAddressContract,at as getTokenPairContract,rt as getTokenPairsContract,I as getTokenPairsLengthContract,B as getTokenPairsSliceContract,ee as getUnwrapFeeContract,ne as getWrapFeeContract,dt as getWrapperContract,_t as indexedDBStorage,ot as isConfidentialTokenContract,H as isConfidentialTokenValidContract,$e as isConfidentialWrapperContract,Je as isFinalizeUnwrapOperatorContract,re as isHandleDelegatedContract,We as isOperatorContract,Dt as loadPendingUnshield,J as matchAclRevert,e as matchZamaError,Be as memoryStorage,b as nameContract,Ee as parseActivityFeed,ct as rateContract,h as revokeDelegationContract,Et as savePendingUnshield,Ye as setFinalizeUnwrapOperatorContract,Ke as setOperatorContract,ge as sortByBlockNumber,et as supportsInterfaceContract,S as symbolContract,Ge as totalSupplyContract,R as underlyingContract,qe as unwrapContract,L as unwrapFromBalanceContract,nt as wrapContract,tt as wrapETHContract,ft as wrapperExistsContract};
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})}},Dt=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 ze({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 Et(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:We(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}},Ot=class e extends T{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?B(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(ct(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=B(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:S.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:S.EncryptEnd,durationMs:Date.now()-u}),Y(()=>a?.())}catch(e){throw this.emit({type:S.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(ht(this.address,s,c[0],l));return this.emit({type:S.TransferSubmitted,txHash:e}),Y(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new H(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=B(e),o=B(t),s,c,l=Date.now();try{this.emit({type:S.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-l}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:S.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($e(this.address,a,o,s[0],c));return this.emit({type:S.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new H(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=B(e);try{let e=await this.signer.writeContract(Je(this.address,n,t));return this.emit({type:S.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approve`,error:A(e)}),e instanceof r?e:new V(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=B(e),r=t?B(t):await this.signer.getAddress();return this.signer.readContract(Ke(this.address,r,n))}async shield(t,n){let i=await this.#n();if(i===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let a;try{let e=await this.signer.getAddress();a=await this.signer.readContract(ce(i,e))}catch(e){throw e instanceof r?e:new xt(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:A(e)})}if(a<t)throw new W(`Insufficient ERC-20 balance: requested ${t}, available ${a} (token: ${i})`,{requested:t,available:a,token:i});let o=n?.approvalStrategy??`exact`;o!==`skip`&&await this.#o(t,o===`max`,n);try{let e=n?.to?B(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(it(this.wrapper,e,t));return this.emit({type:S.ShieldSubmitted,txHash:r}),Y(()=>n?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new H(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(rt(this.wrapper,n,e,t??e));return this.emit({type:S.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shieldETH`,error:A(e)}),e instanceof r?e:new H(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:S.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:S.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(Ye(this.address,t,t,n[0],i));return this.emit({type:S.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`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(ot(this.address,e,e,t));return this.emit({type:S.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`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:S.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:S.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=bt(r.abiEncodedClearValues)}catch(e){throw new O(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(e){throw this.emit({type:S.DecryptError,error:A(e),durationMs:Date.now()-i}),e instanceof r?e:new O(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(lt(this.wrapper,e,t,n));return this.emit({type:S.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`finalizeUnwrap`,error:A(e)}),e instanceof r?e:new H(`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:S.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approveUnderlying`,error:A(e)}),e instanceof r?e:new V(`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=B(e),i=await this.signer.getAddress();if(n===B(i))throw new w(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new x(`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;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new _(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(Se(a,n,this.address,s));return this.emit({type:S.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`delegateDecryption`,error:A(e)}),e instanceof r?e:q(e)||new H(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=B(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new a(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(g(i,t,this.address));return this.emit({type:S.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`revokeDelegation`,error:A(e)}),e instanceof r?e:q(e)||new H(`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 H(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 U(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await u({storage:this.storage,tokenAddress:this.address,owner:t,handle:n});if(i!==null){if(i<e)throw new U(`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 U(`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:S.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new H(`Failed to get unshield receipt`,{cause:e})}let a=v(i.logs);if(!a)throw new H(`No UnwrapRequested event found in unshield receipt`);this.emit({type:S.UnshieldPhase2Started,operationId:t}),Y(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:S.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:S.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const kt={[N.chainId]:N.registryAddress,[j.chainId]:j.registryAddress,[yt.chainId]:yt.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},kt,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 B(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(F(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(L(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(y(e.tokenAddress)),this.signer.readContract(f(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(se(e.tokenAddress)),this.signer.readContract(y(e.confidentialTokenAddress)),this.signer.readContract(f(e.confidentialTokenAddress)),this.signer.readContract(p(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=B(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(I(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(at(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(F(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(L(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(ut(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,B(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(I(t,B(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(R(t,B(e)))}},At=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;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 Ue,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)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new h(t),this.delegatedCredentials=new l(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:S.TransactionError,operation:e,error:A(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=B(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),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 h.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,address:B(e),onEvent:this.#t})}createToken(e,t){return new Ot({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),wrapper:t?B(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Z({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await h.computeStoreKey(e,t);await this.credentials.revokeByKey(n)}async isAllowed(){return this.credentials.isAllowed()}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 jt(e,t,n){await e.set(Q(t),n)}async function Mt(e,t){return e.get(Q(t))}async function Nt(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 Pt=new $;export{de as ACL_TOPICS,te as AclPausedError,De as AclTopics,V as ApprovalFailedError,G as BalanceCheckUnavailableError,$ as ChromeSessionStorage,i as ConfigurationError,h as CredentialsManager,O as DecryptionFailedError,kt as DefaultRegistryAddresses,l as DelegatedCredentialsManager,C as DelegationContractIsSelfError,m as DelegationCooldownError,x as DelegationDelegateEqualsContractError,b as DelegationExpirationTooSoonError,le as DelegationExpiredError,_ as DelegationExpiryUnchangedError,a as DelegationNotFoundError,ge as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,xt as ERC20ReadFailedError,et as ERC7984_INTERFACE_ID,st as ERC7984_WRAPPER_INTERFACE_ID,D as EncryptionFailedError,Ge as HardhatConfig,J as IndexedDBStorage,U as InsufficientConfidentialBalanceError,W as InsufficientERC20BalanceError,Ee as InvalidKeypairError,je as KeypairExpiredError,N as MainnetConfig,Ue as MemoryStorage,xe as NoCiphertextError,T as ReadonlyToken,n as RelayerRequestFailedError,Dt as RelayerWeb,j as SepoliaConfig,fe as SigningFailedError,Oe as SigningRejectedError,Me as TOKEN_TOPICS,Ot as Token,me as Topics,H as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,At as ZamaSDK,S as ZamaSDKEvents,E as allowanceContract,Ne as applyDecryptedValues,s as approveContract,ce as balanceOfContract,Pt as chromeSessionStorage,Nt as clearPendingUnshield,Qe as confidentialBalanceOfContract,vt as confidentialBatchTransferContract,ft as confidentialTotalSupplyContract,ht as confidentialTransferContract,$e as confidentialTransferFromContract,p as decimalsContract,Ce as decodeAclEvent,Pe as decodeAclEvents,he as decodeConfidentialTransfer,_e as decodeDelegatedForUserDecryption,ke as decodeOnChainEvent,we as decodeOnChainEvents,ye as decodeRevokedDelegationForUserDecryption,ve as decodeUnwrapRequested,ue as decodeUnwrappedFinalized,Fe as decodeUnwrappedStarted,Le as decodeWrapped,Se as delegateForUserDecryptionContract,mt as deploymentCoordinatorContract,Te as extractEncryptedHandles,lt as finalizeUnwrapContract,pe as findDelegatedForUserDecryption,Ie as findRevokedDelegationForUserDecryption,v as findUnwrapRequested,c as findWrapped,d as getBatchTransferFeeContract,z as getConfidentialTokenAddressContract,re as getDelegationExpiryContract,ee as getFeeRecipientContract,I as getTokenAddressContract,ut as getTokenPairContract,at as getTokenPairsContract,F as getTokenPairsLengthContract,L as getTokenPairsSliceContract,ne as getUnwrapFeeContract,ae as getWrapFeeContract,gt as getWrapperContract,Ct as indexedDBStorage,dt as isConfidentialTokenContract,R as isConfidentialTokenValidContract,tt as isConfidentialWrapperContract,Xe as isFinalizeUnwrapOperatorContract,ie as isHandleDelegatedContract,Ke as isOperatorContract,Mt as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,He as memoryStorage,y as nameContract,Ae as parseActivityFeed,pt as rateContract,g as revokeDelegationContract,jt as savePendingUnshield,Ze as setFinalizeUnwrapOperatorContract,Je as setOperatorContract,be as sortByBlockNumber,nt as supportsInterfaceContract,f as symbolContract,qe as totalSupplyContract,ct as underlyingContract,Ye as unwrapContract,ot as unwrapFromBalanceContract,it as wrapContract,rt as wrapETHContract,_t as wrapperExistsContract};
515
515
  //# sourceMappingURL=index.js.map