@zama-fhe/sdk 3.4.0-alpha.8 → 3.4.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 (73) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/ethers/index.cjs +1 -1
  4. package/dist/cjs/ethers/index.cjs.map +1 -1
  5. package/dist/cjs/fhevm-relayer.cjs +1 -1
  6. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  7. package/dist/cjs/index.cjs +1 -1
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/node/index.cjs.map +1 -1
  10. package/dist/cjs/query/index.cjs +1 -1
  11. package/dist/cjs/query/index.cjs.map +1 -1
  12. package/dist/cjs/relayer.cjs +1 -1
  13. package/dist/cjs/relayer.cjs.map +1 -1
  14. package/dist/cjs/sdk-events.cjs +2 -0
  15. package/dist/cjs/sdk-events.cjs.map +1 -0
  16. package/dist/cjs/token.cjs +1 -1
  17. package/dist/cjs/token.cjs.map +1 -1
  18. package/dist/cjs/viem/index.cjs +1 -1
  19. package/dist/cjs/viem/index.cjs.map +1 -1
  20. package/dist/esm/{base-signer-Ds8CoYy0.d.ts → base-signer-BvL-jMNO.d.ts} +15 -2
  21. package/dist/esm/base-signer-YpkEmlp2.js +2 -0
  22. package/dist/esm/base-signer-YpkEmlp2.js.map +1 -0
  23. package/dist/esm/chains/index.d.ts +1 -1
  24. package/dist/esm/cleartext/index.d.ts +2 -2
  25. package/dist/esm/cleartext/index.js +1 -1
  26. package/dist/esm/{cleartext-_RCZVPOe.d.ts → cleartext-CxlICeUh.d.ts} +2 -2
  27. package/dist/esm/{cleartext-DfX0GUj1.js → cleartext-Qqh5JohW.js} +2 -2
  28. package/dist/esm/{cleartext-DfX0GUj1.js.map → cleartext-Qqh5JohW.js.map} +1 -1
  29. package/dist/esm/ethers/index.d.ts +53 -5
  30. package/dist/esm/ethers/index.js +1 -1
  31. package/dist/esm/ethers/index.js.map +1 -1
  32. package/dist/esm/fhevm-relayer-4Zd4QkKq.js +2 -0
  33. package/dist/esm/fhevm-relayer-4Zd4QkKq.js.map +1 -0
  34. package/dist/esm/{index-C4Hn6K9c.d.ts → index-DLaQtvYu.d.ts} +213 -400
  35. package/dist/esm/index-DNofJMCK.d.ts +61 -0
  36. package/dist/esm/{index-doNE2KoX.d.ts → index-S6_V7aAH.d.ts} +10 -1
  37. package/dist/esm/index.d.ts +8 -8
  38. package/dist/esm/index.js +1 -1
  39. package/dist/esm/index.js.map +1 -1
  40. package/dist/esm/node/index.d.ts +5 -5
  41. package/dist/esm/node/index.js +1 -1
  42. package/dist/esm/node/index.js.map +1 -1
  43. package/dist/esm/query/index.d.ts +143 -9
  44. package/dist/esm/query/index.js +1 -1
  45. package/dist/esm/query/index.js.map +1 -1
  46. package/dist/esm/relayer-BWHOLVcG.js +2 -0
  47. package/dist/esm/relayer-BWHOLVcG.js.map +1 -0
  48. package/dist/esm/sdk-events-D68bJ5jT.js +2 -0
  49. package/dist/esm/sdk-events-D68bJ5jT.js.map +1 -0
  50. package/dist/esm/token-Bn8I7xAu.js +2 -0
  51. package/dist/esm/token-Bn8I7xAu.js.map +1 -0
  52. package/dist/esm/{types-Tk8PiPCk.d.ts → types-BEz-VgR_.d.ts} +6 -3
  53. package/dist/esm/{types-CELdIAFG.d.ts → types-CWPSTRF6.d.ts} +98 -146
  54. package/dist/esm/{types-DlSUyFe2.d.ts → types-Dr7AmEs1.d.ts} +3 -3
  55. package/dist/esm/viem/index.d.ts +34 -5
  56. package/dist/esm/viem/index.js +1 -1
  57. package/dist/esm/viem/index.js.map +1 -1
  58. package/dist/esm/web/index.d.ts +2 -2
  59. package/dist/esm/web/index.js +1 -1
  60. package/package.json +3 -3
  61. package/dist/cjs/wrappers-registry.cjs +0 -2
  62. package/dist/cjs/wrappers-registry.cjs.map +0 -1
  63. package/dist/esm/base-signer-9CqICeQ8.js +0 -2
  64. package/dist/esm/base-signer-9CqICeQ8.js.map +0 -1
  65. package/dist/esm/fhevm-relayer-Bb_-KFJA.js +0 -2
  66. package/dist/esm/fhevm-relayer-Bb_-KFJA.js.map +0 -1
  67. package/dist/esm/index-9Cn2VKDw.d.ts +0 -329
  68. package/dist/esm/relayer-DLlyoabr.js +0 -2
  69. package/dist/esm/relayer-DLlyoabr.js.map +0 -1
  70. package/dist/esm/token-oxpZ2kAk.js +0 -2
  71. package/dist/esm/token-oxpZ2kAk.js.map +0 -1
  72. package/dist/esm/wrappers-registry-B1GuTt5t.js +0 -2
  73. package/dist/esm/wrappers-registry-B1GuTt5t.js.map +0 -1
@@ -0,0 +1,61 @@
1
+ import "./index-S6_V7aAH.js";
2
+ import { Kt as RelayerOptions, c as GenericStorage, n as RelayerConfig } from "./types-CWPSTRF6.js";
3
+ import "./cleartext-CxlICeUh.js";
4
+ //#region src/node/config.d.ts
5
+ /** Node transport — drives the FHE backend directly on the calling thread. */
6
+ interface NodeRelayerConfig extends RelayerConfig {
7
+ /** Discriminant for the node transport. */
8
+ readonly type: "node";
9
+ }
10
+ /**
11
+ * Node.js transport — drives `@fhevm/sdk` via {@link FhevmRelayer} on the calling thread.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * relayers: {
16
+ * [sepolia.id]: node({ timeout: 5 * 60_000 }),
17
+ * [mainnet.id]: node({ batchRpcCalls: true }),
18
+ * }
19
+ * ```
20
+ */
21
+ declare function node(options?: RelayerOptions): NodeRelayerConfig;
22
+ //#endregion
23
+ //#region src/storage/async-local-storage.d.ts
24
+ /**
25
+ * {@link GenericStorage} backed by Node.js {@link AsyncLocalStorage}.
26
+ *
27
+ * Each async context (e.g. HTTP request) gets its own isolated `Map`,
28
+ * so credentials from one request never leak into another.
29
+ *
30
+ * Call {@link run} to establish a context before using the SDK:
31
+ *
32
+ * ```ts
33
+ * import { asyncLocalStorage } from "@zama-fhe/sdk/node";
34
+ *
35
+ * app.post("/api/transfer", (req, res) => {
36
+ * asyncLocalStorage.run(async () => {
37
+ * const sdk = new ZamaSDK({ relayer, signer, storage: asyncLocalStorage });
38
+ * // credentials are scoped to this request
39
+ * });
40
+ * });
41
+ * ```
42
+ */
43
+ declare class AsyncLocalMapStorage implements GenericStorage {
44
+ #private;
45
+ /** Execute `fn` within an isolated storage context. */
46
+ run<R>(fn: () => R | Promise<R>): R | Promise<R>;
47
+ /**
48
+ * Retrieve a value by key.
49
+ * @returns The stored value, or `null` if the key does not exist.
50
+ */
51
+ get<T = unknown>(key: string): Promise<T | null>;
52
+ /** Store a value under the given key, overwriting any existing entry. */
53
+ set<T = unknown>(key: string, value: T): Promise<void>;
54
+ /** Remove the entry for the given key (no-op if absent). */
55
+ delete(key: string): Promise<void>;
56
+ }
57
+ /** Default singleton for application-wide use. */
58
+ declare const asyncLocalStorage: AsyncLocalMapStorage;
59
+ //#endregion
60
+ export { node as i, asyncLocalStorage as n, NodeRelayerConfig as r, AsyncLocalMapStorage as t };
61
+ //# sourceMappingURL=index-DNofJMCK.d.ts.map
@@ -22,14 +22,23 @@ type FheChainAuth = {
22
22
  * `@zama-fhe/sdk/chains`.
23
23
  */
24
24
  interface FheChain<TId extends number = number> {
25
+ /** EVM chain ID of the host chain. */
25
26
  readonly id: TId;
27
+ /** Chain ID of the FHE gateway serving this chain. */
26
28
  readonly gatewayChainId: number;
29
+ /** Base URL of this chain's relayer endpoint. */
27
30
  readonly relayerUrl: string;
31
+ /** RPC network for host-chain reads — an EIP-1193 provider or an RPC URL. */
28
32
  readonly network: EIP1193Provider | string;
33
+ /** Address of the ACL (access-control list) contract. */
29
34
  readonly aclContractAddress: Address;
35
+ /** Address of the KMS verifier contract. */
30
36
  readonly kmsContractAddress: Address;
37
+ /** Address of the input verifier contract. */
31
38
  readonly inputVerifierContractAddress: Address;
39
+ /** EIP-712 verifying contract address for decryption requests. */
32
40
  readonly verifyingContractAddressDecryption: Address;
41
+ /** EIP-712 verifying contract address for input verification. */
33
42
  readonly verifyingContractAddressInputVerification: Address;
34
43
  /**
35
44
  * Address of the `ConfidentialTokenWrappersRegistry` contract.
@@ -178,4 +187,4 @@ declare const anvil: {
178
187
  declare const chains: Record<number, FheChain>;
179
188
  //#endregion
180
189
  export { hoodi as a, sepolia as c, FheChainAuth as d, hardhat as i, AtLeastOneChain as l, bscTestnet as n, ingenTestnet as o, chains as r, mainnet as s, anvil as t, FheChain as u };
181
- //# sourceMappingURL=index-doNE2KoX.d.ts.map
190
+ //# sourceMappingURL=index-S6_V7aAH.d.ts.map
@@ -1,8 +1,8 @@
1
- import { a as hoodi, c as sepolia, d as FheChainAuth, i as hardhat, l as AtLeastOneChain, n as bscTestnet, o as ingenTestnet, r as chains, s as mainnet, t as anvil, u as FheChain } from "./index-doNE2KoX.js";
2
- import { $ as ShieldPath, A as EncryptEndEvent, At as findRevokedDelegationForUserDecryption, B as TransferSubmittedEvent, Bt as EncryptInput, C as ChainRouter, Ct as decodeOnChainEvent, D as DecryptErrorEvent, Dt as decodeUnwrapRequested, E as DecryptEndEvent, Et as decodeUnwrapFinalized, F as SetOperatorSubmittedEvent, Ft as TransactionResult, G as WrapSubmittedEvent, H as UnshieldPhase2StartedEvent, Ht as EncryptResult, I as ShieldSubmittedEvent, It as ClearValue, J as ZamaSDKEventListener, Jt as TypedValue, K as ZamaSDKEvent, Kt as FhevmRelayerSDK, L as TransactionErrorEvent, Lt as DecryptPublicValuesResult, M as EncryptStartEvent, Mt as findWrap, N as FinalizeUnwrapSubmittedEvent, Nt as RawLog, O as DecryptStartEvent, Ot as decodeWrap, P as RevokeDelegationSubmittedEvent, Pt as TransactionReceipt, Q as ShieldOptions, R as TransactionOperation, Rt as DecryptValuesParameters, S as WriteFunctionName, St as decodeDelegatedForUserDecryption, T as BaseEvent, Tt as decodeRevokedDelegationForUserDecryption, U as UnshieldPhase2SubmittedEvent, Ut as EncryptedValue, V as UnshieldPhase1SubmittedEvent, Vt as EncryptParams, W as UnwrapSubmittedEvent, X as ZamaSDKEvents, Y as ZamaSDKEventType, Z as ApprovalStrategy, _ as ReadContractConfig, _t as UnwrapRequestedEvent, a as ZamaConfigBase, at as TransferCallbacks, b as WriteContractArgs, bt as decodeAclEvents, c as GenericStorage, ct as AclEvent, d as WalletAccount, dt as DelegatedForUserDecryptionEvent, et as TransferOptions, f as WalletAccountChange, ft as OnChainEvent, g as ReadContractArgs, gt as UnwrapFinalizedEvent, h as ContractAbi, ht as Topics, i as ZamaConfig, it as ShieldCallbacks, j as EncryptErrorEvent, jt as findUnwrapRequested, k as DelegationSubmittedEvent, kt as findDelegatedForUserDecryption, l as GenericProvider, lt as AclTopics, m as WalletAccountStore, mt as TOKEN_TOPICS, n as RelayerConfig, nt as UnwrapResult, o as ZamaConfigGeneric, ot as UnshieldCallbacks, p as WalletAccountListener, pt as RevokedDelegationForUserDecryptionEvent, q as ZamaSDKEventInput, rt as WrapOptions, s as GenericLogger, st as ACL_TOPICS, t as CleartextRelayerConfig, tt as UnshieldOptions, u as GenericSigner, ut as ConfidentialTransferEvent, v as ReadContractReturnType, vt as WrapEvent, w as ApproveUnderlyingSubmittedEvent, wt as decodeOnChainEvents, x as WriteContractConfig, xt as decodeConfidentialTransfer, y as ReadFunctionName, yt as decodeAclEvent, z as TransferFromSubmittedEvent, zt as EIP712TypedData } from "./types-CELdIAFG.js";
3
- import { t as cleartext } from "./cleartext-_RCZVPOe.js";
4
- import { t as ZamaConfigEthers } from "./types-DlSUyFe2.js";
5
- import { n as MutableWalletAccountStore, r as createWalletAccountStore, t as BaseSigner } from "./base-signer-Ds8CoYy0.js";
6
- import { $ as DelegationNotFoundError, $t as isOperatorContract, A as SignerNotConfiguredError, At as delegateForUserDecryptionContract, B as ERC20ReadFailedError, Bt as supportsInterfaceContract, C as BatchDecryptItem, Ct as getConfidentialTokenAddressContract, D as TransactionRevertedError, Dt as getTokenPairsLengthContract, E as matchZamaError, Et as getTokenPairsContract, F as NotEntitledError, Ft as ERC1363_INTERFACE_ID, G as EncryptionFailedError, Gt as nameContract, H as InsufficientConfidentialBalanceError, Ht as approveContract, I as ConfigurationError, It as ERC7984_INTERFACE_ID, J as DelegationCooldownError, Jt as confidentialTotalSupplyContract, K as AclPausedError, Kt as symbolContract, L as RelayerRequestFailedError, Lt as ERC7984_WRAPPER_INTERFACE_ID, M as WalletAccountNotReadyError, Mt as isHandleDelegatedContract, N as WalletNotConnectedError, Nt as revokeDelegationContract, O as SigningFailedError, Ot as getTokenPairsSliceContract, P as RpcRateLimitError, Pt as transferAndCallContract, Q as DelegationExpiryUnchangedError, Qt as inferredTotalSupplyContract, R as BalanceCheckUnavailableError, Rt as isConfidentialTokenContract, S as Decryption, St as TokenWrapperPairWithMetadata, T as DelegatedDecryptOptions, Tt as getTokenPairContract, U as InsufficientERC20BalanceError, Ut as balanceOfContract, V as InsufficientAllowanceError, Vt as allowanceContract, W as DecryptionFailedError, Wt as decimalsContract, X as DelegationExpirationTooSoonError, Xt as confidentialTransferFromContract, Y as DelegationDelegateEqualsContractError, Yt as confidentialTransferContract, Z as DelegationExpiredError, Zt as finalizeUnwrapContract, _ as BatchBalancesResult, a as IndexedDBStorage, an as wrapContract, at as ChainMismatchError, b as Permits, bt as PaginatedResult, c as memoryStorage, cn as resolveStorage, ct as isRetryable, d as ZamaSDK, dt as SerializedTransportKeyPair, en as rateContract, et as DelegationNotPropagatedError, f as DefaultRegistryAddresses, ft as StoredTransportKeyPair, g as WrappedToken, h as WrappersRegistryConfig, i as chromeSessionStorage, in as unwrapFromBalanceContract, it as TransportKeyPairExpiredError, j as SignerRequiredError, jt as getDelegationExpiryContract, k as SigningRejectedError, kt as isConfidentialTokenValidContract, l as ZERO_ENCRYPTED_VALUE, ln as createConfig, lt as retryAfterSeconds, m as WrappersRegistry, mt as EncryptedInput, n as Hex, nn as underlyingContract, nt as InvalidTransportKeyPairError, o as indexedDBStorage, on as ResolvedChainRelayer, ot as ZamaError, p as ListPairsOptions, pt as DecryptResult, q as DelegationContractIsSelfError, qt as confidentialBalanceOfContract, r as ChromeSessionStorage, rn as unwrapContract, rt as NoCiphertextError, s as MemoryStorage, sn as resolveChainRelayers, st as ZamaErrorCode, t as Address, tn as setOperatorContract, tt as DelegationSelfNotAllowedError, u as isEncryptedValueZero, ut as Permission, v as BatchDecryptAsOptions, w as BatchDecryptResult, wt as getTokenAddressContract, x as Delegations, xt as TokenWrapperPair, y as Token, z as BalanceErrorDetails, zt as isConfidentialWrapperContract } from "./index-C4Hn6K9c.js";
7
- import { t as ZamaConfigViem } from "./types-Tk8PiPCk.js";
8
- export { ACL_TOPICS, type AclEvent, AclPausedError, AclTopics, type Address, type ApprovalStrategy, type ApproveUnderlyingSubmittedEvent, type AtLeastOneChain, BalanceCheckUnavailableError, type BalanceErrorDetails, type BaseEvent, BaseSigner, type BatchBalancesResult, type BatchDecryptAsOptions, type BatchDecryptItem, type BatchDecryptResult, ChainMismatchError, type ChainRouter, ChromeSessionStorage, type ClearValue, type CleartextRelayerConfig, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type DecryptEndEvent, type DecryptErrorEvent, type EncryptedInput as DecryptInput, type DecryptPublicValuesResult, type DecryptResult, type DecryptStartEvent, type DecryptValuesParameters, Decryption, DecryptionFailedError, DefaultRegistryAddresses, type DelegatedDecryptOptions, type DelegatedForUserDecryptionEvent, DelegationContractIsSelfError, DelegationCooldownError, DelegationDelegateEqualsContractError, DelegationExpirationTooSoonError, DelegationExpiredError, DelegationExpiryUnchangedError, DelegationNotFoundError, DelegationNotPropagatedError, DelegationSelfNotAllowedError, type DelegationSubmittedEvent, Delegations, type EIP712TypedData, ERC1363_INTERFACE_ID, ERC20ReadFailedError, ERC7984_INTERFACE_ID, ERC7984_WRAPPER_INTERFACE_ID, type EncryptEndEvent, type EncryptErrorEvent, type EncryptInput, type EncryptParams, type EncryptResult, type EncryptStartEvent, type EncryptedValue, EncryptionFailedError, type FheChain, type FheChainAuth, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericProvider, type GenericSigner, type GenericStorage, type Hex, IndexedDBStorage, InsufficientAllowanceError, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidTransportKeyPairError, type ListPairsOptions, MemoryStorage, MutableWalletAccountStore, NoCiphertextError, NotEntitledError, type OnChainEvent, type PaginatedResult, type Permission, Permits, type RawLog, type ReadContractArgs, type ReadContractConfig, type ReadContractReturnType, type ReadFunctionName, type RelayerConfig, RelayerRequestFailedError, type FhevmRelayerSDK as RelayerSDK, type ResolvedChainRelayer, type RevokeDelegationSubmittedEvent, type RevokedDelegationForUserDecryptionEvent, RpcRateLimitError, type SerializedTransportKeyPair, type SetOperatorSubmittedEvent, type ShieldCallbacks, type ShieldOptions, type ShieldPath, type ShieldSubmittedEvent, SignerNotConfiguredError, SignerRequiredError, SigningFailedError, SigningRejectedError, type StoredTransportKeyPair, TOKEN_TOPICS, Token, type TokenWrapperPair, type TokenWrapperPairWithMetadata, Topics, type TransactionErrorEvent, type TransactionOperation, type TransactionReceipt, type TransactionResult, TransactionRevertedError, type TransferCallbacks, type TransferFromSubmittedEvent, type TransferOptions, type TransferSubmittedEvent, TransportKeyPairExpiredError, type TypedValue, type UnshieldCallbacks, type UnshieldOptions, type UnshieldPhase1SubmittedEvent, type UnshieldPhase2StartedEvent, type UnshieldPhase2SubmittedEvent, type UnwrapFinalizedEvent, type UnwrapRequestedEvent, type UnwrapResult, type UnwrapSubmittedEvent, type WalletAccount, type WalletAccountChange, type WalletAccountListener, WalletAccountNotReadyError, type WalletAccountStore, WalletNotConnectedError, type WrapEvent, type WrapOptions, type WrapSubmittedEvent, WrappedToken, WrappersRegistry, type WrappersRegistryConfig, type WriteContractArgs, type WriteContractConfig, type WriteFunctionName, ZERO_ENCRYPTED_VALUE, type ZamaConfig, type ZamaConfigBase, type ZamaConfigEthers, type ZamaConfigGeneric, type ZamaConfigViem, ZamaError, ZamaErrorCode, ZamaSDK, type ZamaSDKEvent, type ZamaSDKEventInput, type ZamaSDKEventListener, type ZamaSDKEventType, ZamaSDKEvents, allowanceContract, anvil, approveContract, balanceOfContract, bscTestnet, chains, chromeSessionStorage, cleartext, confidentialBalanceOfContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, createConfig, createWalletAccountStore, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapFinalized, decodeUnwrapRequested, decodeWrap, delegateForUserDecryptionContract, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrap, getConfidentialTokenAddressContract, getDelegationExpiryContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, hardhat, hoodi, indexedDBStorage, inferredTotalSupplyContract, ingenTestnet, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isEncryptedValueZero, isHandleDelegatedContract, isOperatorContract, isRetryable, mainnet, matchZamaError, memoryStorage, nameContract, rateContract, resolveChainRelayers, resolveStorage, retryAfterSeconds, revokeDelegationContract, sepolia, setOperatorContract, supportsInterfaceContract, symbolContract, transferAndCallContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract };
1
+ import { a as hoodi, c as sepolia, d as FheChainAuth, i as hardhat, l as AtLeastOneChain, n as bscTestnet, o as ingenTestnet, r as chains, s as mainnet, t as anvil, u as FheChain } from "./index-S6_V7aAH.js";
2
+ import { $ as UnshieldOptions, A as EncryptErrorEvent, At as findWrap, B as UnshieldPhase1SubmittedEvent, Bt as EncryptResult, C as ApproveUnderlyingSubmittedEvent, Ct as decodeRevokedDelegationForUserDecryption, D as DecryptStartEvent, Dt as findDelegatedForUserDecryption, E as DecryptErrorEvent, Et as decodeWrap, F as ShieldSubmittedEvent, Ft as DecryptPublicValuesResult, G as ZamaSDKEvent, Gt as FhevmRuntimeConfig, H as UnshieldPhase2SubmittedEvent, Ht as FhevmClient, I as TransactionErrorEvent, It as DecryptValuesParameters, J as ZamaSDKEvents, Jt as TypedValue, K as ZamaSDKEventListener, Kt as RelayerOptions, L as TransactionOperation, Lt as EIP712TypedData, M as FinalizeUnwrapSubmittedEvent, Mt as TransactionReceipt, N as RevokeDelegationSubmittedEvent, Nt as TransactionResult, O as DelegationSubmittedEvent, Ot as findRevokedDelegationForUserDecryption, P as SetOperatorSubmittedEvent, Pt as ClearValue, Q as TransferOptions, R as TransferFromSubmittedEvent, Rt as EncryptInput, S as WriteFunctionName, St as decodeOnChainEvents, T as DecryptEndEvent, Tt as decodeUnwrapRequested, U as UnwrapSubmittedEvent, Ut as FhevmClientOptions, V as UnshieldPhase2StartedEvent, Vt as EncryptedValue, W as WrapSubmittedEvent, Wt as FhevmRelayerOptions, X as ShieldOptions, Y as ApprovalStrategy, Z as ShieldPath, _ as ReadContractConfig, _t as decodeAclEvent, a as ZamaConfigBase, at as ACL_TOPICS, b as WriteContractArgs, bt as decodeDelegatedForUserDecryption, c as GenericStorage, ct as ConfidentialTransferEvent, d as WalletAccount, dt as RevokedDelegationForUserDecryptionEvent, et as UnwrapResult, f as WalletAccountChange, ft as TOKEN_TOPICS, g as ReadContractArgs, gt as WrapEvent, h as ContractAbi, ht as UnwrapRequestedEvent, i as ZamaConfig, it as UnshieldCallbacks, j as EncryptStartEvent, jt as RawLog, k as EncryptEndEvent, kt as findUnwrapRequested, l as GenericProvider, lt as DelegatedForUserDecryptionEvent, m as WalletAccountStore, mt as UnwrapFinalizedEvent, n as RelayerConfig, nt as ShieldCallbacks, o as ZamaConfigGeneric, ot as AclEvent, p as WalletAccountListener, pt as Topics, q as ZamaSDKEventType, qt as RelayerSDK, rt as TransferCallbacks, s as GenericLogger, st as AclTopics, t as CleartextRelayerConfig, tt as WrapOptions, u as GenericSigner, ut as OnChainEvent, v as ReadContractReturnType, vt as decodeAclEvents, w as BaseEvent, wt as decodeUnwrapFinalized, x as WriteContractConfig, xt as decodeOnChainEvent, y as ReadFunctionName, yt as decodeConfidentialTransfer, z as TransferSubmittedEvent, zt as EncryptParams } from "./types-CWPSTRF6.js";
3
+ import { t as cleartext } from "./cleartext-CxlICeUh.js";
4
+ import { t as ZamaConfigEthers } from "./types-Dr7AmEs1.js";
5
+ import { n as MutableWalletAccountStore, r as createWalletAccountStore, t as BaseSigner } from "./base-signer-BvL-jMNO.js";
6
+ import { $ as AclPausedError, $t as confidentialTransferContract, A as BatchDecryptResult, At as getTokenPairsContract, B as WalletNotConnectedError, Bt as ERC7984_INTERFACE_ID, C as BatchDecryptAsOptions, D as DelegationStatus, Dt as getConfidentialTokenAddressContract, E as Delegations, Et as TokenWrapperPairWithMetadata, F as SigningFailedError, Ft as getDelegationExpiryContract, G as BalanceCheckUnavailableError, Gt as allowanceContract, H as NotEntitledError, Ht as isConfidentialTokenContract, I as SigningRejectedError, It as isHandleDelegatedContract, J as InsufficientAllowanceError, Jt as decimalsContract, K as BalanceErrorDetails, Kt as approveContract, L as SignerNotConfiguredError, Lt as revokeDelegationContract, M as ErrorForCode, Mt as getTokenPairsSliceContract, N as matchZamaError, Nt as isConfidentialTokenValidContract, O as Decryption, Ot as getTokenAddressContract, P as TransactionRevertedError, Pt as delegateForUserDecryptionContract, Q as EncryptionFailedError, Qt as confidentialTotalSupplyContract, R as SignerRequiredError, Rt as transferAndCallContract, S as BatchBalancesResult, T as Permits, Tt as TokenWrapperPair, U as ConfigurationError, Ut as isConfidentialWrapperContract, V as RpcRateLimitError, Vt as ERC7984_WRAPPER_INTERFACE_ID, W as RelayerRequestFailedError, Wt as supportsInterfaceContract, X as InsufficientERC20BalanceError, Xt as symbolContract, Y as InsufficientConfidentialBalanceError, Yt as nameContract, Z as DecryptionFailedError, Zt as confidentialBalanceOfContract, _ as SerializedPermit, _t as DecryptResult, a as IndexedDBStorage, an as setOperatorContract, at as DelegationExpiryUnchangedError, b as ChecksummedAddress, c as memoryStorage, cn as unwrapFromBalanceContract, ct as DelegationSelfNotAllowedError, d as ZamaSDK, dt as TransportKeyPairExpiredError, en as confidentialTransferFromContract, et as DelegationContractIsSelfError, f as DefaultRegistryAddresses, ft as ChainMismatchError, g as Permission, gt as retryAfterSeconds, h as WrappersRegistryConfig, ht as isRetryable, i as chromeSessionStorage, in as rateContract, it as DelegationExpiredError, j as DelegatedDecryptOptions, jt as getTokenPairsLengthContract, k as BatchDecryptItem, kt as getTokenPairContract, l as ZERO_ENCRYPTED_VALUE, ln as wrapContract, lt as InvalidTransportKeyPairError, m as WrappersRegistry, mt as ZamaErrorCode, n as Hex, nn as inferredTotalSupplyContract, nt as DelegationDelegateEqualsContractError, o as indexedDBStorage, on as underlyingContract, ot as DelegationNotFoundError, p as ListPairsOptions, pt as ZamaError, q as ERC20ReadFailedError, qt as balanceOfContract, r as ChromeSessionStorage, rn as isOperatorContract, rt as DelegationExpirationTooSoonError, s as MemoryStorage, sn as unwrapContract, st as DelegationNotPropagatedError, t as Address, tn as finalizeUnwrapContract, tt as DelegationCooldownError, u as isEncryptedValueZero, un as createConfig, ut as NoCiphertextError, v as SerializedPermitEip712, vt as EncryptedInput, w as Token, wt as PaginatedResult, x as WrappedToken, y as SerializedTransportKeyPair, z as WalletAccountNotReadyError, zt as ERC1363_INTERFACE_ID } from "./index-DLaQtvYu.js";
7
+ import { t as ZamaConfigViem } from "./types-BEz-VgR_.js";
8
+ export { ACL_TOPICS, type AclEvent, AclPausedError, AclTopics, type Address, type ApprovalStrategy, type ApproveUnderlyingSubmittedEvent, type AtLeastOneChain, BalanceCheckUnavailableError, type BalanceErrorDetails, type BaseEvent, BaseSigner, type BatchBalancesResult, type BatchDecryptAsOptions, type BatchDecryptItem, type BatchDecryptResult, ChainMismatchError, type ChecksummedAddress, ChromeSessionStorage, type ClearValue, type CleartextRelayerConfig, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type DecryptEndEvent, type DecryptErrorEvent, type EncryptedInput as DecryptInput, type DecryptPublicValuesResult, type DecryptResult, type DecryptStartEvent, type DecryptValuesParameters, Decryption, DecryptionFailedError, DefaultRegistryAddresses, type DelegatedDecryptOptions, type DelegatedForUserDecryptionEvent, DelegationContractIsSelfError, DelegationCooldownError, DelegationDelegateEqualsContractError, DelegationExpirationTooSoonError, DelegationExpiredError, DelegationExpiryUnchangedError, DelegationNotFoundError, DelegationNotPropagatedError, DelegationSelfNotAllowedError, type DelegationStatus, type DelegationSubmittedEvent, Delegations, type EIP712TypedData, ERC1363_INTERFACE_ID, ERC20ReadFailedError, ERC7984_INTERFACE_ID, ERC7984_WRAPPER_INTERFACE_ID, type EncryptEndEvent, type EncryptErrorEvent, type EncryptInput, type EncryptParams, type EncryptResult, type EncryptStartEvent, type EncryptedValue, EncryptionFailedError, type ErrorForCode, type FheChain, type FheChainAuth, type FhevmClient, type FhevmClientOptions, type FhevmRelayerOptions, type FhevmRuntimeConfig, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericProvider, type GenericSigner, type GenericStorage, type Hex, IndexedDBStorage, InsufficientAllowanceError, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidTransportKeyPairError, type ListPairsOptions, MemoryStorage, MutableWalletAccountStore, NoCiphertextError, NotEntitledError, type OnChainEvent, type PaginatedResult, type Permission, Permits, type RawLog, type ReadContractArgs, type ReadContractConfig, type ReadContractReturnType, type ReadFunctionName, type RelayerConfig, type RelayerOptions, RelayerRequestFailedError, type RelayerSDK, type RevokeDelegationSubmittedEvent, type RevokedDelegationForUserDecryptionEvent, RpcRateLimitError, type SerializedPermit, type SerializedPermitEip712, type SerializedTransportKeyPair, type SetOperatorSubmittedEvent, type ShieldCallbacks, type ShieldOptions, type ShieldPath, type ShieldSubmittedEvent, SignerNotConfiguredError, SignerRequiredError, SigningFailedError, SigningRejectedError, TOKEN_TOPICS, Token, type TokenWrapperPair, type TokenWrapperPairWithMetadata, Topics, type TransactionErrorEvent, type TransactionOperation, type TransactionReceipt, type TransactionResult, TransactionRevertedError, type TransferCallbacks, type TransferFromSubmittedEvent, type TransferOptions, type TransferSubmittedEvent, TransportKeyPairExpiredError, type TypedValue, type UnshieldCallbacks, type UnshieldOptions, type UnshieldPhase1SubmittedEvent, type UnshieldPhase2StartedEvent, type UnshieldPhase2SubmittedEvent, type UnwrapFinalizedEvent, type UnwrapRequestedEvent, type UnwrapResult, type UnwrapSubmittedEvent, type WalletAccount, type WalletAccountChange, type WalletAccountListener, WalletAccountNotReadyError, type WalletAccountStore, WalletNotConnectedError, type WrapEvent, type WrapOptions, type WrapSubmittedEvent, WrappedToken, WrappersRegistry, type WrappersRegistryConfig, type WriteContractArgs, type WriteContractConfig, type WriteFunctionName, ZERO_ENCRYPTED_VALUE, type ZamaConfig, type ZamaConfigBase, type ZamaConfigEthers, type ZamaConfigGeneric, type ZamaConfigViem, ZamaError, ZamaErrorCode, ZamaSDK, type ZamaSDKEvent, type ZamaSDKEventListener, type ZamaSDKEventType, ZamaSDKEvents, allowanceContract, anvil, approveContract, balanceOfContract, bscTestnet, chains, chromeSessionStorage, cleartext, confidentialBalanceOfContract, confidentialTotalSupplyContract, confidentialTransferContract, confidentialTransferFromContract, createConfig, createWalletAccountStore, decimalsContract, decodeAclEvent, decodeAclEvents, decodeConfidentialTransfer, decodeDelegatedForUserDecryption, decodeOnChainEvent, decodeOnChainEvents, decodeRevokedDelegationForUserDecryption, decodeUnwrapFinalized, decodeUnwrapRequested, decodeWrap, delegateForUserDecryptionContract, finalizeUnwrapContract, findDelegatedForUserDecryption, findRevokedDelegationForUserDecryption, findUnwrapRequested, findWrap, getConfidentialTokenAddressContract, getDelegationExpiryContract, getTokenAddressContract, getTokenPairContract, getTokenPairsContract, getTokenPairsLengthContract, getTokenPairsSliceContract, hardhat, hoodi, indexedDBStorage, inferredTotalSupplyContract, ingenTestnet, isConfidentialTokenContract, isConfidentialTokenValidContract, isConfidentialWrapperContract, isEncryptedValueZero, isHandleDelegatedContract, isOperatorContract, isRetryable, mainnet, matchZamaError, memoryStorage, nameContract, rateContract, retryAfterSeconds, revokeDelegationContract, sepolia, setOperatorContract, supportsInterfaceContract, symbolContract, transferAndCallContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract };
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m}from"./relayer-DLlyoabr.js";import{A as h,B as g,C as ee,D as te,F as ne,H as _,I as v,L as y,M as re,N as ie,O as ae,P as oe,R as se,S as ce,T as le,U as ue,V as de,W as fe,_ as pe,a as me,b as he,c as ge,d as _e,f as ve,g as b,h as x,i as ye,j as be,k as xe,l as Se,m as Ce,n as we,o as Te,p as Ee,r as De,s as Oe,t as ke,u as Ae,v as je,x as Me,z as Ne}from"./wrappers-registry-B1GuTt5t.js";import{C as Pe,D as S,E as C,S as w,T,_ as Fe,a as E,b as Ie,c as Le,d as D,f as O,g as Re,h as ze,i as Be,l as Ve,m as He,n as Ue,o as We,p as Ge,r as Ke,s as k,t as A,u as j,v as qe,w as M,x as Je,y as N}from"./token-oxpZ2kAk.js";import{t as Ye}from"./cleartext-DfX0GUj1.js";import{a as Xe,c as Ze,d as Qe,f as $e,g as et,h as tt,i as nt,l as rt,m as it,n as at,o as P,p as ot,r as st,s as ct,t as lt,u as F}from"./base-signer-9CqICeQ8.js";import{a as ut,c as dt,i as ft,n as pt,o as mt,r as ht,s as gt,t as _t}from"./chains-CLv9HEJ_.js";import{getAddress as I,keccak256 as vt,toBytes as yt}from"viem";import{z as L}from"zod/mini";function bt(e,t){if(e instanceof f){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var xt=class extends f{constructor(e,t){super(o.TransportKeyPairExpired,e,t),this.name=`TransportKeyPairExpiredError`}},St=class extends f{constructor(e,t){super(o.InvalidTransportKeyPair,e,t),this.name=`InvalidTransportKeyPairError`}},R=class extends f{constructor(e,t){super(o.NoCiphertext,e,t),this.name=`NoCiphertextError`}},z=class extends f{encryptedValue;contractAddress;account;constructor(e,t){super(o.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},B=class extends f{constructor(e,t){super(o.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},Ct=class extends f{constructor(e,t){super(o.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},V=class extends f{constructor(e,t){super(o.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},H=class extends f{constructor(e,t){super(o.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},U=class extends f{constructor(e,t){super(o.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},wt=class extends f{constructor(e,t){super(o.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Tt=class extends f{constructor(e,t){super(o.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},Et=class extends f{constructor(e,t){super(o.AclPaused,e,t),this.name=`AclPausedError`}},Dt=class extends f{constructor(e,t){super(o.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},W=class extends f{constructor(e,t){super(o.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const Ot=[C,R,l,W,fe,ue,z,M];function G(e,i,o={}){if(Ot.some(t=>e instanceof t))return e;let u=e instanceof Error?e.message:i;if(e instanceof Error&&n(e.message))return o.isDelegated?new W(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new z({encryptedValue:a(e.message)??``,contractAddress:o.contractAddress??``,account:o.account??``},{cause:e});if(s(e))return new M(u,{cause:e,retryAfter:t(e)});let f=p(e);return f===void 0&&c(e)?new M(u,{cause:e,retryAfter:t(e)}):f===400?new R(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):o.isDelegated&&f===500?new W(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):r(e)||f!==void 0?new l(u,f,{cause:e,retryAfter:t(e),retryable:d(e)||void 0}):new C(i,{cause:e})}function kt(e,n){if(e instanceof f)return e;let i=p(e),a=d(e);return i!==void 0||r(e)?new l(e instanceof Error?e.message:n,i,{cause:e,retryAfter:t(e),retryable:a||void 0}):new S(n,{cause:e})}const At=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function jt(e,t,n,r=`0x`){return{address:e,abi:At,functionName:`transferAndCall`,args:[t,n,r]}}function Mt(e){return nt(e.signer,e.provider,e)}function Nt(e){return e.startsWith(`0x`)?e:`0x${e}`}var Pt=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return _(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await j(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,t)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await j(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,r)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{Ve(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw G(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await j(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},Ft=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return _(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await j(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await j(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},It=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return _(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await D(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await D(`grantDelegationPermit`,this.#e,this.#t),await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),n=I((await j(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(n)}}async clear(){let e=this.#a(`clear`),t=I((await j(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await y(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}};const Lt=L.union([L.bigint(),L.boolean(),rt]),Rt=L.array(L.string());var zt=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Lt.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=I(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${I(e)}:${I(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Rt.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function Bt(e,t){let n=Vt(e,t);if(!n)throw new C(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function Vt(e,t){let n=Ze(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Ht=e=>new Promise(t=>setTimeout(t,e));var Ut=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=I(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=I(t),o=I(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:I(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof W))throw t;await Ht(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)}));if(o.length===0)return{items:o};let s=I(r);try{let e=await this.delegatedDecryptValues(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#l(t,e);return{items:o}}catch(e){if(Fe(e))throw e;if(o.length===1){let[n=this.#d()]=o;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:I(t)}),{items:o}}}let c=!1;return await We(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#l(e,r)}catch(n){if(Fe(n))throw c=!0,n;e.error=this.#u(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:I(t)})}}),i),{items:o}}async#o(e,t,n,r){let i=Bt(e,t),a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey}),o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n){if(e.length===0)return{};let r=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:I(e.contractAddress)})),a={},o=[];for(let e of r)E(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(r.map(e=>e.contractAddress))),l=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(l)}catch(e){throw c(e)?this.#c(e,`the delegation pre-check`):e}let u=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):a[e.encryptedValue]=n}if(u.length===0)return a;let d=await t.resolveCredentials(s),p=new Map;for(let e of u){let t=p.get(e.contractAddress);t?t.push(e.encryptedValue):p.set(e.contractAddress,[e.encryptedValue])}let m=[];for(let[e,t]of p)for(let n of Be(t))m.push({contractAddress:e,encryptedValues:n});let h=Date.now(),g=u.map(e=>e.encryptedValue);try{this.#i({type:k.DecryptStart,encryptedValues:g}),await We(m.map(({contractAddress:e,encryptedValues:r})=>async()=>{let i;try{i=await t.decryptContract({credentials:d,contractAddress:e,encryptedValues:r,options:n})}catch(n){throw G(n,t.errorMessage,{isDelegated:t.delegated,contractAddress:e,account:t.aclActorAddress})}for(let n=0;n<r.length;n++){let o=r[n],s=i[n]?.value;o===void 0||s===void 0||(a[o]=s,await this.#e.set(t.requesterAddress,e,o,s))}let o=r.filter(e=>a[e]===void 0);if(o.length>0)throw new C(`${t.errorMessage}: relayer returned no clear value for ${o.length} of ${r.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new C(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of g){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:k.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),a}catch(e){let n=e instanceof f&&e.cause instanceof Error?e.cause:e;throw this.#i({type:k.DecryptError,error:i(n),durationMs:Date.now()-h,encryptedValues:g}),G(e,t.errorMessage,{isDelegated:t.delegated})}}#c(e,n){return new M(`RPC provider rate-limited ${n}; retry with backoff.`,{cause:e,retryAfter:t(e)})}#l(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new C(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#u(e,t,n){return e instanceof f?e:G(e,t,n)}#d(){throw new C(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Wt(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 Gt={AlreadyDelegatedOrRevokedInSameBlock:e=>new Ct(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new Tt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new Et(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new B(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new wt(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new Dt(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new U(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new V(`Cannot revoke: no active delegation exists.`,{cause:e})};function Kt(e){return e in Gt}function qt(e,t){let n=Wt(e);if(n&&Kt(n))return Gt[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Gt))if(r.includes(e))return n(t);return null}var Jt=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new Dt(`Expiration date must be at least 1 hour in the future`);let a=I(t),o=I(n),s=I(r);if(o===s)throw new B(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new wt(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):O,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new U(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:Ge(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=I(t),a=I(n),o=I(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new V(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:Re(s,a,i)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===O?!0:t>await this.#t.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(He(r,I(t),I(n),I(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Ue({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof T))return;let t=qt(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof V||t instanceof H){let n=I(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=I(e),i=I(t),a=I(n),o=await this.getDelegationExpiry({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(o===0n)throw new V(`No active delegation from ${i} to ${a} for ${r}`);if(o!==O&&o<=await this.#t.getBlockTimestamp())throw new H(`Delegation from ${i} to ${a} for ${r} has expired`)}},Yt=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=I(e.contractAddress);try{this.#t({type:k.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:k.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:k.EncryptError,error:i(e),durationMs:Date.now()-n},r),kt(e,`Encryption failed`)}}},Xt=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await y(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await y(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await y(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>y(`wallet account listener`,()=>t(e),this.#i)))}};function K(e){return vt(yt(e))}const q={ConfidentialTransfer:K(`ConfidentialTransfer(address,address,bytes32)`),Wrap:K(`Wrap(address,uint256,bytes32)`),UnwrapRequested:K(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:K(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function J(e){return I(Nt(e.slice(-40)))}function Zt(e){return e}function Qt(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function $t(e,t){return I(Nt(Qt(e,t).slice(-40)))}function Y(e,t){return BigInt(`0x`+Qt(e,t))}function en(e,t){return Nt(Qt(e,t))}function tn(e){return e.topics[0]!==q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:J(e.topics[1]),to:J(e.topics[2]),encryptedAmount:Zt(e.topics[3])}}function nn(e){return e.topics[0]!==q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:J(e.topics[1]),roundedAmount:Y(e.data,0),encryptedWrappedAmount:en(e.data,1)}}function X(e){return e.topics[0]!==q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:J(e.topics[1]),unwrapRequestId:Zt(e.topics[2]),encryptedAmount:en(e.data,0)}}function rn(e){return e.topics[0]!==q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:J(e.topics[1]),unwrapRequestId:Zt(e.topics[2]),encryptedAmount:en(e.data,0),cleartextAmount:Y(e.data,1)}}function an(e){return tn(e)??nn(e)??X(e)??rn(e)}function on(e){let t=[];for(let n of e){let e=an(n);e&&t.push(e)}return t}function sn(e){for(let t of e){let e=X(t);if(e)return e}return null}function cn(e){for(let t of e){let e=nn(t);if(e)return e}return null}const ln=[q.ConfidentialTransfer,q.Wrap,q.UnwrapRequested,q.UnwrapFinalized],Z={DelegatedForUserDecryption:K(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:K(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function un(e){return e.topics[0]!==Z.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:J(e.topics[1]),delegate:J(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:Y(e.data,1),oldExpirationDate:Y(e.data,2),newExpirationDate:Y(e.data,3)}}function Q(e){return e.topics[0]!==Z.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:J(e.topics[1]),delegate:J(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:Y(e.data,1),oldExpirationDate:Y(e.data,2)}}function dn(e){return un(e)??Q(e)}function fn(e){let t=[];for(let n of e){let e=dn(n);e&&t.push(e)}return t}function pn(e){for(let t of e){let e=un(t);if(e)return e}return null}function mn(e){for(let t of e){let e=Q(t);if(e)return e}return null}const hn=[Z.DelegatedForUserDecryption,Z.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${Ze(e)}`}const gn=L.union([L.pipe(F,L.transform(e=>({unwrapTxHash:e}))),L.pipe(L.object({version:L.literal(1),unwrapTxHash:F,unwrapRequestId:L.optional(F)}),L.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function _n(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function vn(e,t){return(await yn(e,t))?.unwrapTxHash??null}async function yn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=gn.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function bn(e,t){await e.delete($(t))}var xn=class extends A{#e;#t=null;#n=null;#r(e){try{return Ve(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new se(e,{cause:t})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(Ee(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#s();return this.sdk.provider.readContract(x(t,I(e),this.address))}async shield(e,t){let n=await j(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),a=await this.#s(),o=I(n.address),s;try{s=await this.sdk.provider.readContract(pe(a,o))}catch(e){throw e instanceof f?e:new N(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:i(e)})}if(s<e)throw new w(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${a})`,{requested:e,available:s,token:a});return r?this.#i(e,a,o,t):this.#a(e,o,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?I(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:jt(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await j(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#s(),a=I(n.address),o;try{o=await this.sdk.provider.readContract(pe(r,a))}catch(e){throw e instanceof f?e:new N(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:i(e)})}if(o<e)throw new w(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${r})`,{requested:e,available:o,token:r});let s;try{s=await this.sdk.provider.readContract(x(r,a,this.address))}catch(e){throw e instanceof f?e:new N(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:i(e)})}if(s<e)throw new Ie(`Insufficient allowance for wrap: requested ${e}, approved ${s}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:s,token:r});let c=t?.to?I(t.to):a;return this.submitTransaction({operation:`wrap`,config:v(this.address,c,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#l(e,r===`max`,n);let i=n?.to?I(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:v(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await j(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#s(),r=I(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(x(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:b(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:b(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return y(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#c(c.unwrapRequestId,c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return y(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#c(n.unwrapRequestId,n.txHash,t,e)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof f?e:new T(`Failed to get unwrap receipt`,{cause:e})}let r=this.#o(n.logs);return this.#c(r,e,crypto.randomUUID(),t)}async getPendingUnshield(){return vn(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let t=I((await j(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:n,inputProof:r}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:t}),[i]=n;if(!i)throw new S(`Encryption returned no encrypted values`);let a=await this.submitTransaction({operation:`unwrap`,config:oe(this.address,t,t,i,r)});return{...a,unwrapRequestId:this.#o(a.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=I((await j(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(E(t))throw new C(`Cannot unshield: balance is zero`);let n=await this.submitTransaction({operation:`unwrapAll`,config:ne(this.address,e,e,t)});return{...n,unwrapRequestId:this.#o(n.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await D(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let t=await this.sdk.decryption.decryptPublicValues([e]),n=t.clearValues[e];return Le(n,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:ae(this.address,e,n,t.decryptionProof)})}#o(e){let t=sn(e);if(!t)throw new T(`No UnwrapRequested event found in unwrap receipt`);return t.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(ie(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,t,n,r){this.emit({type:k.UnshieldPhase1Submitted,txHash:t,operationId:n}),await y(`unshield: savePendingUnshield`,()=>_n(this.sdk.storage,this.address,t),this.sdk.logger),this.emit({type:k.UnshieldPhase2Started,operationId:n}),y(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let i=await this.finalizeUnwrap(e);return this.emit({type:k.UnshieldPhase2Submitted,txHash:i.txHash,operationId:n}),y(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(i.txHash),this.sdk.logger),await y(`unshield: clearPendingUnshield`,()=>bn(this.sdk.storage,this.address),this.sdk.logger),i}async#l(e,t,n){this.#r(`approveUnderlying`);let r=await this.#s(),i=I((await j(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),a=await this.sdk.provider.readContract(x(r,i,this.address));if(a>=e)return;a>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:b(r,this.address,0n)});let o=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:b(r,this.address,o),onSubmitted:n?.onApprovalSubmitted})}},Sn=class{#e;provider;signer;storage;registry;permits;delegations;decryption;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new zt(e.storage,this.#i),this.#u=new Jt({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new P({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,e.signer&&(this.#l=new ct({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),this.#c=new Ut({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Yt({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Xt({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.permits=new It({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new Ft({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new Pt({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c})}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new P({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new A(this,e)}createWrappedToken(e){return new xn(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},Cn=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 wn=new Cn;export{hn as ACL_TOPICS,Et as AclPausedError,Z as AclTopics,qe as BalanceCheckUnavailableError,lt as BaseSigner,Pe as ChainMismatchError,Cn as ChromeSessionStorage,m as ConfigurationError,Pt as Decryption,C as DecryptionFailedError,Xe as DefaultRegistryAddresses,Tt as DelegationContractIsSelfError,Ct as DelegationCooldownError,wt as DelegationDelegateEqualsContractError,Dt as DelegationExpirationTooSoonError,H as DelegationExpiredError,U as DelegationExpiryUnchangedError,V as DelegationNotFoundError,W as DelegationNotPropagatedError,B as DelegationSelfNotAllowedError,Ft as Delegations,ge as ERC1363_INTERFACE_ID,N as ERC20ReadFailedError,Se as ERC7984_INTERFACE_ID,Ae as ERC7984_WRAPPER_INTERFACE_ID,S as EncryptionFailedError,tt as IndexedDBStorage,Ie as InsufficientAllowanceError,Je as InsufficientConfidentialBalanceError,w as InsufficientERC20BalanceError,St as InvalidTransportKeyPairError,ot as MemoryStorage,at as MutableWalletAccountStore,R as NoCiphertextError,z as NotEntitledError,It as Permits,l as RelayerRequestFailedError,M as RpcRateLimitError,se as SignerNotConfiguredError,Ne as SignerRequiredError,ue as SigningFailedError,fe as SigningRejectedError,ln as TOKEN_TOPICS,A as Token,q as Topics,T as TransactionRevertedError,xt as TransportKeyPairExpiredError,g as WalletAccountNotReadyError,de as WalletNotConnectedError,xn as WrappedToken,P as WrappersRegistry,Ke as ZERO_ENCRYPTED_VALUE,f as ZamaError,o as ZamaErrorCode,Sn as ZamaSDK,k as ZamaSDKEvents,x as allowanceContract,_t as anvil,b as approveContract,pe as balanceOfContract,pt as bscTestnet,ht as chains,wn as chromeSessionStorage,Ye as cleartext,ce as confidentialBalanceOfContract,ee as confidentialTotalSupplyContract,le as confidentialTransferContract,te as confidentialTransferFromContract,Mt as createConfig,st as createWalletAccountStore,je as decimalsContract,dn as decodeAclEvent,fn as decodeAclEvents,tn as decodeConfidentialTransfer,un as decodeDelegatedForUserDecryption,an as decodeOnChainEvent,on as decodeOnChainEvents,Q as decodeRevokedDelegationForUserDecryption,rn as decodeUnwrapFinalized,X as decodeUnwrapRequested,nn as decodeWrap,Ge as delegateForUserDecryptionContract,ae as finalizeUnwrapContract,pn as findDelegatedForUserDecryption,mn as findRevokedDelegationForUserDecryption,sn as findUnwrapRequested,cn as findWrap,ke as getConfidentialTokenAddressContract,He as getDelegationExpiryContract,we as getTokenAddressContract,De as getTokenPairContract,ye as getTokenPairsContract,me as getTokenPairsLengthContract,Te as getTokenPairsSliceContract,ft as hardhat,ut as hoodi,et as indexedDBStorage,xe as inferredTotalSupplyContract,mt as ingenTestnet,_e as isConfidentialTokenContract,Oe as isConfidentialTokenValidContract,ve as isConfidentialWrapperContract,E as isEncryptedValueZero,ze as isHandleDelegatedContract,h as isOperatorContract,e as isRetryable,gt as mainnet,bt as matchZamaError,it as memoryStorage,he as nameContract,be as rateContract,Qe as resolveChainRelayers,$e as resolveStorage,u as retryAfterSeconds,Re as revokeDelegationContract,dt as sepolia,re as setOperatorContract,Ce as supportsInterfaceContract,Me as symbolContract,jt as transferAndCallContract,ie as underlyingContract,oe as unwrapContract,ne as unwrapFromBalanceContract,v as wrapContract};
1
+ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as ee}from"./relayer-BWHOLVcG.js";import{A as h,B as te,C as ne,D as re,F as ie,G as ae,H as oe,I as se,J as g,K as ce,L as le,M as ue,N as de,P as fe,R as pe,S as me,T as he,U as ge,V as _e,W as ve,X as ye,Y as _,_ as v,a as be,b as xe,c as Se,d as Ce,f as we,g as Te,h as Ee,i as De,j as Oe,k as ke,l as Ae,m as je,o as Me,p as Ne,r as Pe,s as Fe,t as y,u as Ie,v as b,w as Le,y as x,z as S}from"./sdk-events-D68bJ5jT.js";import{_ as Re,a as ze,b as C,c as Be,d as Ve,f as He,g as w,h as Ue,i as We,l as T,m as Ge,n as Ke,o as E,p as D,r as qe,s as Je,t as O,u as k,v as A,x as j,y as M}from"./token-Bn8I7xAu.js";import{t as Ye}from"./cleartext-Qqh5JohW.js";import{a as Xe,c as Ze,d as Qe,f as $e,i as et,l as tt,m as nt,n as rt,o as N,p as it,r as at,s as ot,t as st,u as P}from"./base-signer-YpkEmlp2.js";import{a as ct,c as lt,i as ut,n as dt,o as ft,r as pt,s as mt,t as ht}from"./chains-CLv9HEJ_.js";import{getAddress as F,keccak256 as gt,toBytes as _t}from"viem";import{z as I}from"zod/mini";function vt(e,t){if(e instanceof p){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var L=class extends p{encryptedValue;contractAddress;account;constructor(e,t){super(s.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},R=class extends p{constructor(e,t){super(s.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},yt=class extends p{constructor(e,t){super(s.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},z=class extends p{constructor(e,t){super(s.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},B=class extends p{constructor(e,t){super(s.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},V=class extends p{constructor(e,t){super(s.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},H=class extends p{constructor(e,t){super(s.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},bt=class extends p{constructor(e,t){super(s.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},xt=class extends p{constructor(e,t){super(s.AclPaused,e,t),this.name=`AclPausedError`}},U=class extends p{constructor(e,t){super(s.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},W=class extends p{constructor(e,t){super(s.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const St=[C,_,u,W,ce,ae,L,A,g];function G(e,t,s={}){if(St.some(t=>e instanceof t))return e;let d=e instanceof Error?e.message:t;if(e instanceof Error&&r(e.message))return new g(e.message,{cause:e});if(e instanceof Error&&i(e.message))return s.isDelegated?new W(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new L({encryptedValue:a(e.message)??``,contractAddress:s.contractAddress??``,account:s.account??``},{cause:e});if(c(e))return new A(d,{cause:e,retryAfter:n(e)});let p=m(e);return p===void 0&&o(e)?new A(d,{cause:e,retryAfter:n(e)}):p===400?new _(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):s.isDelegated&&p===500?new W(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):f(e)||p!==void 0?new u(d,p,{cause:e,retryAfter:n(e),retryable:l(e)||void 0}):new C(t,{cause:e})}function Ct(e,t){if(e instanceof p)return e;let r=m(e),i=l(e);return r!==void 0||f(e)?new u(e instanceof Error?e.message:t,r,{cause:e,retryAfter:n(e),retryable:i||void 0}):new j(t,{cause:e})}const wt=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function Tt(e,t,n,r=`0x`){return{address:e,abi:wt,functionName:`transferAndCall`,args:[t,n,r]}}const K=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function Et(e,t,n,r){return{address:e,abi:K,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function Dt(e,t,n){return{address:e,abi:K,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function Ot(e,t,n,r){return{address:e,abi:K,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function kt(e,t,n,r,i){return{address:e,abi:K,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const At=2n**64n-1n;function jt(e){return et(e.signer,e.provider,e)}function Mt(e){return e.startsWith(`0x`)?e:`0x${e}`}var Nt=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return ve(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await T(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,t)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await T(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,r)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{Be(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw G(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await T(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},Pt=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return ve(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await T(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await T(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},Ft=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return ve(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await k(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await k(`grantDelegationPermit`,this.#e,this.#t),await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),n=F((await T(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(n)}}async clear(){let e=this.#a(`clear`),t=F((await T(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await S(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}};const It=I.union([I.bigint(),I.boolean(),tt]),Lt=I.array(I.string());var Rt=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=It.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=F(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${F(e)}:${F(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Lt.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function zt(e,t){let n=Bt(e,t);if(!n)throw new C(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function Bt(e,t){let n=Ze(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Vt=e=>new Promise(t=>setTimeout(t,e));var Ht=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=F(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=F(t),o=F(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:F(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof W))throw t;await Vt(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:F(e.contractAddress)}));if(o.length===0)return{items:o};let s=F(r);try{let e=await this.delegatedDecryptValues(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#l(t,e);return{items:o}}catch(e){if(Ve(e))throw e;if(o.length===1){let[n=this.#d()]=o;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:F(t)}),{items:o}}}let c=!1;return await qe(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#l(e,r)}catch(n){if(Ve(n))throw c=!0,n;e.error=this.#u(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:F(t)})}}),i),{items:o}}async#o(e,t,n,i){let a=zt(e,t),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&r(e.message)&&await this.#t.evictTransportKeyPair(),e}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:n,contractAddress:t,options:i})}async#s(t,n,r){if(t.length===0)return{};let i=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:F(e.contractAddress)})),a={},s=[];for(let e of i)E(e.encryptedValue)?a[e.encryptedValue]=0n:s.push(e);if(s.length===0)return a;let c=Array.from(new Set(i.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw o(e)?this.#c(e,`the delegation pre-check`):e}let u=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?u.push(e):a[e.encryptedValue]=t}if(u.length===0)return a;let d=await n.resolveCredentials(c),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let m=[];for(let[e,t]of f)for(let n of ze(t))m.push({contractAddress:e,encryptedValues:n});let ee=Date.now(),h=u.map(e=>e.encryptedValue);try{this.#i({type:y.DecryptStart,encryptedValues:h}),await qe(m.map(({contractAddress:e,encryptedValues:t})=>async()=>{let i;try{i=await n.decryptContract({credentials:d,contractAddress:e,encryptedValues:t,options:r})}catch(t){throw G(t,n.errorMessage,{isDelegated:n.delegated,contractAddress:e,account:n.aclActorAddress})}for(let r=0;r<t.length;r++){let o=t[r],s=i[r]?.value;o!==void 0&&s!==void 0&&(a[o]=s,await this.#e.set(n.requesterAddress,e,o,s))}let o=t.filter(e=>a[e]===void 0);if(o.length>0)throw new C(`${n.errorMessage}: relayer returned no clear value for ${o.length} of ${t.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new C(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of h){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:y.DecryptEnd,durationMs:Date.now()-ee,encryptedValues:h,result:e}),a}catch(t){let r=t instanceof p&&t.cause instanceof Error?t.cause:t;throw this.#i({type:y.DecryptError,error:e(r),durationMs:Date.now()-ee,encryptedValues:h}),G(t,n.errorMessage,{isDelegated:n.delegated})}}#c(e,t){return new A(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:n(e)})}#l(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new C(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#u(e,t,n){return e instanceof p?e:G(e,t,n)}#d(){throw new C(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Ut(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 Wt={AlreadyDelegatedOrRevokedInSameBlock:e=>new yt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new bt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new xt(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new R(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new H(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new U(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new V(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new z(`Cannot revoke: no active delegation exists.`,{cause:e})};function Gt(e){return e in Wt}function Kt(e,t){let n=Ut(e);if(n&&Gt(n))return Wt[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Wt))if(r.includes(e))return n(t);return null}var qt=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new U(`Expiration date must be at least 1 hour in the future`);let a=F(t),o=F(n),s=F(r);if(o===s)throw new R(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new H(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):At,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new V(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:Et(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=F(t),a=F(n),o=F(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new z(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:Dt(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===At?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(Ot(r,F(t),F(n),F(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Ke({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof M))return;let t=Kt(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof z||t instanceof B){let n=F(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=F(e),i=F(t),a=F(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new z(`No active delegation from ${i} to ${a} for ${r}`):new B(`Delegation from ${i} to ${a} for ${r} has expired`)}},Jt=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,n){let r=Date.now(),i=F(t.contractAddress);try{this.#t({type:y.EncryptStart},i);let e=await this.#e.relayer.encryptValues({...t,options:n});return this.#t({type:y.EncryptEnd,durationMs:Date.now()-r},i),e}catch(t){throw this.#t({type:y.EncryptError,error:e(t),durationMs:Date.now()-r},i),Ct(t,`Encryption failed`)}}},Yt=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await S(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await S(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await S(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>S(`wallet account listener`,()=>t(e),this.#i)))}};function q(e){return gt(_t(e))}const J={ConfidentialTransfer:q(`ConfidentialTransfer(address,address,bytes32)`),Wrap:q(`Wrap(address,uint256,bytes32)`),UnwrapRequested:q(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:q(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function Y(e){return F(Mt(e.slice(-40)))}function Xt(e){return e}function Zt(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Qt(e,t){return F(Mt(Zt(e,t).slice(-40)))}function X(e,t){return BigInt(`0x`+Zt(e,t))}function $t(e,t){return Mt(Zt(e,t))}function en(e){return e.topics[0]!==J.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:Y(e.topics[1]),to:Y(e.topics[2]),encryptedAmount:Xt(e.topics[3])}}function tn(e){return e.topics[0]!==J.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:Y(e.topics[1]),roundedAmount:X(e.data,0),encryptedWrappedAmount:$t(e.data,1)}}function Z(e){return e.topics[0]!==J.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:Y(e.topics[1]),unwrapRequestId:Xt(e.topics[2]),encryptedAmount:$t(e.data,0)}}function nn(e){return e.topics[0]!==J.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:Y(e.topics[1]),unwrapRequestId:Xt(e.topics[2]),encryptedAmount:$t(e.data,0),cleartextAmount:X(e.data,1)}}function rn(e){return en(e)??tn(e)??Z(e)??nn(e)}function an(e){let t=[];for(let n of e){let e=rn(n);e&&t.push(e)}return t}function on(e){for(let t of e){let e=Z(t);if(e)return e}return null}function sn(e){for(let t of e){let e=tn(t);if(e)return e}return null}const cn=[J.ConfidentialTransfer,J.Wrap,J.UnwrapRequested,J.UnwrapFinalized],Q={DelegatedForUserDecryption:q(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:q(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function ln(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:Y(e.topics[1]),delegate:Y(e.topics[2]),contractAddress:Qt(e.data,0),delegationCounter:X(e.data,1),oldExpirationDate:X(e.data,2),newExpirationDate:X(e.data,3)}}function un(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:Y(e.topics[1]),delegate:Y(e.topics[2]),contractAddress:Qt(e.data,0),delegationCounter:X(e.data,1),oldExpirationDate:X(e.data,2)}}function dn(e){return ln(e)??un(e)}function fn(e){let t=[];for(let n of e){let e=dn(n);e&&t.push(e)}return t}function pn(e){for(let t of e){let e=ln(t);if(e)return e}return null}function mn(e){for(let t of e){let e=un(t);if(e)return e}return null}const hn=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${Ze(e)}`}const gn=I.union([I.pipe(P,I.transform(e=>({unwrapTxHash:e}))),I.pipe(I.object({version:I.literal(1),unwrapTxHash:P,unwrapRequestId:I.optional(P)}),I.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function _n(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function vn(e,t){return(await yn(e,t))?.unwrapTxHash??null}async function yn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=gn.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function bn(e,t){await e.delete($(t))}var xn=class extends O{#e;#t=null;#n=null;#r(e){try{return Be(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new te(e,{cause:t})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(Ee(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#s();return this.sdk.provider.readContract(v(t,F(e),this.address))}async shield(t,n){let r=await T(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),a=await this.#s(),o=F(r.address),s;try{s=await this.sdk.provider.readContract(x(a,o))}catch(t){throw t instanceof p?t:new D(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:e(t)})}if(s<t)throw new w(`Insufficient ERC-20 balance: requested ${t}, available ${s} (token: ${a})`,{requested:t,available:s,token:a});return i?this.#i(t,a,o,n):this.#a(t,o,n)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?F(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:Tt(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(t,n){this.#r(`wrap`);let r=await T(`wrap`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=F(r.address),o;try{o=await this.sdk.provider.readContract(x(i,a))}catch(t){throw t instanceof p?t:new D(`Could not read ERC-20 balance for wrap validation (token: ${i})`,{cause:e(t)})}if(o<t)throw new w(`Insufficient ERC-20 balance: requested ${t}, available ${o} (token: ${i})`,{requested:t,available:o,token:i});let s;try{s=await this.sdk.provider.readContract(v(i,a,this.address))}catch(t){throw t instanceof p?t:new D(`Could not read ERC-20 allowance for wrap validation (token: ${i})`,{cause:e(t)})}if(s<t)throw new Ge(`Insufficient allowance for wrap: requested ${t}, approved ${s}. Call approveUnderlying() first (token: ${i}).`,{requested:t,available:s,token:i});let c=n?.to?F(n.to):a;return this.submitTransaction({operation:`wrap`,config:pe(this.address,c,t),onSubmitted:n?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#l(e,r===`max`,n);let i=n?.to?F(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:pe(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await T(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#s(),r=F(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(v(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:b(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:b(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return S(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#c(c.unwrapRequestId,c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return S(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#c(n.unwrapRequestId,n.txHash,t,e)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof p?e:new M(`Failed to get unwrap receipt`,{cause:e})}let r=this.#o(n.logs);return this.#c(r,e,crypto.randomUUID(),t)}async getPendingUnshield(){return vn(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let t=F((await T(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:n,inputProof:r}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:t}),[i]=n;if(!i)throw new j(`Encryption returned no encrypted values`);let a=await this.submitTransaction({operation:`unwrap`,config:se(this.address,t,t,i,r)});return{...a,unwrapRequestId:this.#o(a.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=F((await T(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(E(t))throw new C(`Cannot unshield: balance is zero`);let n=await this.submitTransaction({operation:`unwrapAll`,config:le(this.address,e,e,t)});return{...n,unwrapRequestId:this.#o(n.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await k(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let t=await this.sdk.decryption.decryptPublicValues([e]),n=t.clearValues[e];return Je(n,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:h(this.address,e,n,t.decryptionProof)})}#o(e){let t=on(e);if(!t)throw new M(`No UnwrapRequested event found in unwrap receipt`);return t.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(ie(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,t,n,r){this.emit({type:y.UnshieldPhase1Submitted,txHash:t,operationId:n}),await S(`unshield: savePendingUnshield`,()=>_n(this.sdk.storage,this.address,t),this.sdk.logger),this.emit({type:y.UnshieldPhase2Started,operationId:n}),S(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let i=await this.finalizeUnwrap(e);return this.emit({type:y.UnshieldPhase2Submitted,txHash:i.txHash,operationId:n}),S(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(i.txHash),this.sdk.logger),await S(`unshield: clearPendingUnshield`,()=>bn(this.sdk.storage,this.address),this.sdk.logger),i}async#l(e,t,n){this.#r(`approveUnderlying`);let r=await this.#s(),i=F((await T(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),a=await this.sdk.provider.readContract(v(r,i,this.address));if(a>=e)return;a>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:b(r,this.address,0n)});let o=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:b(r,this.address,o),onSubmitted:n?.onApprovalSubmitted})}},Sn=class{#e;provider;signer;storage;registry;permits;delegations;decryption;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Rt(e.storage,this.#i),this.#u=new qt({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new N({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,e.signer&&(this.#l=new ot({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),this.#c=new Ht({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Jt({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Yt({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.permits=new Ft({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new Pt({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new Nt({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c})}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new N({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new O(this,e)}createWrappedToken(e){return new xn(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},Cn=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 wn=new Cn;export{hn as ACL_TOPICS,xt as AclPausedError,Q as AclTopics,He as BalanceCheckUnavailableError,st as BaseSigner,Re as ChainMismatchError,Cn as ChromeSessionStorage,ee as ConfigurationError,Nt as Decryption,C as DecryptionFailedError,Xe as DefaultRegistryAddresses,bt as DelegationContractIsSelfError,yt as DelegationCooldownError,H as DelegationDelegateEqualsContractError,U as DelegationExpirationTooSoonError,B as DelegationExpiredError,V as DelegationExpiryUnchangedError,z as DelegationNotFoundError,W as DelegationNotPropagatedError,R as DelegationSelfNotAllowedError,Pt as Delegations,Ie as ERC1363_INTERFACE_ID,D as ERC20ReadFailedError,Ce as ERC7984_INTERFACE_ID,we as ERC7984_WRAPPER_INTERFACE_ID,j as EncryptionFailedError,it as IndexedDBStorage,Ge as InsufficientAllowanceError,Ue as InsufficientConfidentialBalanceError,w as InsufficientERC20BalanceError,g as InvalidTransportKeyPairError,Qe as MemoryStorage,rt as MutableWalletAccountStore,_ as NoCiphertextError,L as NotEntitledError,Ft as Permits,u as RelayerRequestFailedError,A as RpcRateLimitError,te as SignerNotConfiguredError,_e as SignerRequiredError,ae as SigningFailedError,ce as SigningRejectedError,cn as TOKEN_TOPICS,O as Token,J as Topics,M as TransactionRevertedError,ye as TransportKeyPairExpiredError,oe as WalletAccountNotReadyError,ge as WalletNotConnectedError,xn as WrappedToken,N as WrappersRegistry,We as ZERO_ENCRYPTED_VALUE,p as ZamaError,s as ZamaErrorCode,Sn as ZamaSDK,y as ZamaSDKEvents,v as allowanceContract,ht as anvil,b as approveContract,x as balanceOfContract,dt as bscTestnet,pt as chains,wn as chromeSessionStorage,Ye as cleartext,Le as confidentialBalanceOfContract,he as confidentialTotalSupplyContract,re as confidentialTransferContract,ke as confidentialTransferFromContract,jt as createConfig,at as createWalletAccountStore,xe as decimalsContract,dn as decodeAclEvent,fn as decodeAclEvents,en as decodeConfidentialTransfer,ln as decodeDelegatedForUserDecryption,rn as decodeOnChainEvent,an as decodeOnChainEvents,un as decodeRevokedDelegationForUserDecryption,nn as decodeUnwrapFinalized,Z as decodeUnwrapRequested,tn as decodeWrap,Et as delegateForUserDecryptionContract,h as finalizeUnwrapContract,pn as findDelegatedForUserDecryption,mn as findRevokedDelegationForUserDecryption,on as findUnwrapRequested,sn as findWrap,Pe as getConfidentialTokenAddressContract,Ot as getDelegationExpiryContract,De as getTokenAddressContract,be as getTokenPairContract,Me as getTokenPairsContract,Fe as getTokenPairsLengthContract,Se as getTokenPairsSliceContract,ut as hardhat,ct as hoodi,nt as indexedDBStorage,Oe as inferredTotalSupplyContract,ft as ingenTestnet,Ne as isConfidentialTokenContract,Ae as isConfidentialTokenValidContract,je as isConfidentialWrapperContract,E as isEncryptedValueZero,kt as isHandleDelegatedContract,ue as isOperatorContract,t as isRetryable,mt as mainnet,vt as matchZamaError,$e as memoryStorage,me as nameContract,de as rateContract,d as retryAfterSeconds,Dt as revokeDelegationContract,lt as sepolia,fe as setOperatorContract,Te as supportsInterfaceContract,ne as symbolContract,Tt as transferAndCallContract,ie as underlyingContract,se as unwrapContract,le as unwrapFromBalanceContract,pe as wrapContract};
2
2
  //# sourceMappingURL=index.js.map