@zama-fhe/sdk 3.3.0-alpha.8 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/esm/{index-DBchRNlE.d.ts → index-C1Mtc8Rw.d.ts} +27 -43
- package/dist/esm/index.d.ts +11 -7
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +17 -2
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/package.json +54 -52
|
@@ -18567,6 +18567,12 @@ declare const zamaQueryKeys: {
|
|
|
18567
18567
|
readonly tokenAddress: `0x${string}`;
|
|
18568
18568
|
}];
|
|
18569
18569
|
};
|
|
18570
|
+
readonly pendingUnshield: {
|
|
18571
|
+
readonly all: readonly ["zama.pendingUnshield"];
|
|
18572
|
+
readonly token: (tokenAddress: Address) => readonly ["zama.pendingUnshield", {
|
|
18573
|
+
readonly tokenAddress: `0x${string}`;
|
|
18574
|
+
}];
|
|
18575
|
+
};
|
|
18570
18576
|
readonly hasPermit: {
|
|
18571
18577
|
readonly all: readonly ["zama.hasPermit"];
|
|
18572
18578
|
readonly scope: (contractAddresses: Address[], walletAccount?: WalletAccount) => readonly ["zama.hasPermit", {
|
|
@@ -20196,6 +20202,25 @@ declare class WrappedToken extends Token {
|
|
|
20196
20202
|
* ```
|
|
20197
20203
|
*/
|
|
20198
20204
|
resumeUnshield(unwrapTxHash: Hex, callbacks?: UnshieldCallbacks): Promise<TransactionResult>;
|
|
20205
|
+
/**
|
|
20206
|
+
* Return the unwrap tx hash of an unshield that was interrupted between its
|
|
20207
|
+
* two phases, or `null` if none is pending for this wrapper.
|
|
20208
|
+
*
|
|
20209
|
+
* The SDK persists this automatically when {@link unshield}/{@link unshieldAll}
|
|
20210
|
+
* submit phase 1, and clears it once phase 2 finalizes. Use the returned hash
|
|
20211
|
+
* to surface a "resume" affordance, then pass it to {@link resumeUnshield}.
|
|
20212
|
+
* Resuming is intentionally caller-driven — auto-resuming on load would fire a
|
|
20213
|
+
* wallet transaction unprompted.
|
|
20214
|
+
*
|
|
20215
|
+
* @returns The pending unwrap tx hash, or `null`.
|
|
20216
|
+
*
|
|
20217
|
+
* @example
|
|
20218
|
+
* ```ts
|
|
20219
|
+
* const unwrapTxHash = await wrappedToken.getPendingUnshield();
|
|
20220
|
+
* if (unwrapTxHash) await wrappedToken.resumeUnshield(unwrapTxHash);
|
|
20221
|
+
* ```
|
|
20222
|
+
*/
|
|
20223
|
+
getPendingUnshield(): Promise<Hex | null>;
|
|
20199
20224
|
/**
|
|
20200
20225
|
* Request an unwrap for a specific amount. Encrypts the amount first.
|
|
20201
20226
|
* Call {@link finalizeUnwrap} after the request is processed on-chain.
|
|
@@ -20607,46 +20632,5 @@ declare class ZamaSDK {
|
|
|
20607
20632
|
[Symbol.dispose](): void;
|
|
20608
20633
|
}
|
|
20609
20634
|
//#endregion
|
|
20610
|
-
|
|
20611
|
-
|
|
20612
|
-
* Persisted state for an in-progress unshield request.
|
|
20613
|
-
* Used to resume an interrupted unshield after page reload.
|
|
20614
|
-
*/
|
|
20615
|
-
interface PendingUnshieldRequest {
|
|
20616
|
-
/** Transaction hash of the original unwrap call. */
|
|
20617
|
-
readonly unwrapTxHash: Hex;
|
|
20618
|
-
/**
|
|
20619
|
-
* Request identifier from the `UnwrapRequested` event.
|
|
20620
|
-
* Always populated for entries persisted by this SDK version; pass it as
|
|
20621
|
-
* `unwrapRequestId` to `finalizeUnwrap`. Absent only when re-loading a
|
|
20622
|
-
* pending unshield serialized by an older SDK version that did not
|
|
20623
|
-
* record this field — in that case pass the `encryptedAmount` from the
|
|
20624
|
-
* `UnwrapRequested` event to `finalizeUnwrap` instead.
|
|
20625
|
-
*/
|
|
20626
|
-
readonly unwrapRequestId?: EncryptedValue;
|
|
20627
|
-
}
|
|
20628
|
-
/**
|
|
20629
|
-
* Persist the unwrap tx hash so an interrupted unshield can be resumed later
|
|
20630
|
-
* (e.g. after a page reload).
|
|
20631
|
-
*/
|
|
20632
|
-
declare function savePendingUnshield(storage: GenericStorage, wrapperAddress: Address, unwrapTxHash: Hex, unwrapRequestId?: EncryptedValue): Promise<void>;
|
|
20633
|
-
/**
|
|
20634
|
-
* Load a previously saved unwrap tx hash, or `null` if none exists.
|
|
20635
|
-
*/
|
|
20636
|
-
declare function loadPendingUnshield(storage: GenericStorage, wrapperAddress: Address): Promise<Hex | null>;
|
|
20637
|
-
/**
|
|
20638
|
-
* Load a previously saved unwrap request, including `unwrapRequestId` when available.
|
|
20639
|
-
*
|
|
20640
|
-
* `resumeUnshield()` only needs `unwrapTxHash`: it reloads the transaction receipt and
|
|
20641
|
-
* rediscovers the right finalize input from the emitted `UnwrapRequested` event.
|
|
20642
|
-
* Use `unwrapRequestId` directly only for custom flows that call `finalizeUnwrap()`
|
|
20643
|
-
* without reloading the original unwrap receipt.
|
|
20644
|
-
*/
|
|
20645
|
-
declare function loadPendingUnshieldRequest(storage: GenericStorage, wrapperAddress: Address): Promise<PendingUnshieldRequest | null>;
|
|
20646
|
-
/**
|
|
20647
|
-
* Clear the saved unwrap tx hash after a successful finalization.
|
|
20648
|
-
*/
|
|
20649
|
-
declare function clearPendingUnshield(storage: GenericStorage, wrapperAddress: Address): Promise<void>;
|
|
20650
|
-
//#endregion
|
|
20651
|
-
export { NoCiphertextError as $, resolveStorage as $t, WalletNotConnectedError as A, isConfidentialWrapperContract as At, DecryptionFailedError as B, confidentialTransferContract as Bt, WorkerTimeoutError as C, isHandleDelegatedContract as Ct, SignerNotConfiguredError as D, ERC7984_INTERFACE_ID as Dt, SigningRejectedError as E, ERC1363_INTERFACE_ID as Et, BalanceCheckUnavailableError as F, decimalsContract as Ft, DelegationDelegateEqualsContractError as G, rateContract as Gt, AclPausedError as H, finalizeUnwrapContract as Ht, BalanceErrorDetails as I, nameContract as It, DelegationExpiryUnchangedError as J, unwrapContract as Jt, DelegationExpirationTooSoonError as K, setOperatorContract as Kt, ERC20ReadFailedError as L, symbolContract as Lt, NotEntitledError as M, allowanceContract as Mt, ConfigurationError as N, approveContract as Nt, SignerRequiredError as O, ERC7984_WRAPPER_INTERFACE_ID as Ot, RelayerRequestFailedError as P, balanceOfContract as Pt, InvalidTransportKeyPairError as Q, resolveChainRelayers as Qt, InsufficientConfidentialBalanceError as R, confidentialBalanceOfContract as Rt, WorkerRecycledError as S, getDelegationExpiryContract as St, SigningFailedError as T, transferAndCallContract as Tt, DelegationContractIsSelfError as U, inferredTotalSupplyContract as Ut, EncryptionFailedError as V, confidentialTransferFromContract as Vt, DelegationCooldownError as W, isOperatorContract as Wt, DelegationNotPropagatedError as X, wrapContract as Xt, DelegationNotFoundError as Y, unwrapFromBalanceContract as Yt, DelegationSelfNotAllowedError as Z, ResolvedChainRelayer as Zt, Decryption as _, getTokenPairsContract as _t, savePendingUnshield as a, EncryptedInput as at, DelegatedDecryptOptions as b, isConfidentialTokenValidContract as bt, ListPairsOptions as c, zamaQueryKeys as ct, WrappedToken as d, PaginatedResult as dt, createConfig as en, TransportKeyPairExpiredError as et, BatchBalancesResult as f, TokenWrapperPair as ft, Delegations as g, getTokenPairContract as gt, Permits as h, getTokenAddressContract as ht, loadPendingUnshieldRequest as i, DecryptResult as it, RpcRateLimitError as j, supportsInterfaceContract as jt, WalletAccountNotReadyError as k, isConfidentialTokenContract as kt, WrappersRegistry as l, MutationFactoryOptions as lt, Token as m, getConfidentialTokenAddressContract as mt, clearPendingUnshield as n, ZamaError as nt, ZamaSDK as o, decryptValuesQueryOptions as ot, BatchDecryptAsOptions as p, TokenWrapperPairWithMetadata as pt, DelegationExpiredError as q, underlyingContract as qt, loadPendingUnshield as r, ZamaErrorCode as rt, DefaultRegistryAddresses as s, SignerQueryContext as st, PendingUnshieldRequest as t, ChainMismatchError as tt, WrappersRegistryConfig as u, QueryFactoryOptions as ut, BatchDecryptItem as v, getTokenPairsLengthContract as vt, TransactionRevertedError as w, revokeDelegationContract as wt, matchZamaError as x, delegateForUserDecryptionContract as xt, BatchDecryptResult as y, getTokenPairsSliceContract as yt, InsufficientERC20BalanceError as z, confidentialTotalSupplyContract as zt };
|
|
20652
|
-
//# sourceMappingURL=index-DBchRNlE.d.ts.map
|
|
20635
|
+
export { DecryptResult as $, BalanceCheckUnavailableError as A, decimalsContract as At, DelegationDelegateEqualsContractError as B, rateContract as Bt, SignerRequiredError as C, ERC7984_WRAPPER_INTERFACE_ID as Ct, NotEntitledError as D, allowanceContract as Dt, RpcRateLimitError as E, supportsInterfaceContract as Et, DecryptionFailedError as F, confidentialTransferContract as Ft, DelegationNotPropagatedError as G, wrapContract as Gt, DelegationExpiredError as H, underlyingContract as Ht, EncryptionFailedError as I, confidentialTransferFromContract as It, NoCiphertextError as J, resolveStorage as Jt, DelegationSelfNotAllowedError as K, ResolvedChainRelayer as Kt, AclPausedError as L, finalizeUnwrapContract as Lt, ERC20ReadFailedError as M, symbolContract as Mt, InsufficientConfidentialBalanceError as N, confidentialBalanceOfContract as Nt, ConfigurationError as O, approveContract as Ot, InsufficientERC20BalanceError as P, confidentialTotalSupplyContract as Pt, ZamaErrorCode as Q, DelegationContractIsSelfError as R, inferredTotalSupplyContract as Rt, SignerNotConfiguredError as S, ERC7984_INTERFACE_ID as St, WalletNotConnectedError as T, isConfidentialWrapperContract as Tt, DelegationExpiryUnchangedError as U, unwrapContract as Ut, DelegationExpirationTooSoonError as V, setOperatorContract as Vt, DelegationNotFoundError as W, unwrapFromBalanceContract as Wt, ChainMismatchError as X, TransportKeyPairExpiredError as Y, createConfig as Yt, ZamaError as Z, WorkerRecycledError as _, getDelegationExpiryContract as _t, WrappersRegistryConfig as a, QueryFactoryOptions as at, SigningFailedError as b, transferAndCallContract as bt, BatchDecryptAsOptions as c, TokenWrapperPairWithMetadata as ct, Delegations as d, getTokenPairContract as dt, EncryptedInput as et, Decryption as f, getTokenPairsContract as ft, matchZamaError as g, delegateForUserDecryptionContract as gt, DelegatedDecryptOptions as h, isConfidentialTokenValidContract as ht, WrappersRegistry as i, MutationFactoryOptions as it, BalanceErrorDetails as j, nameContract as jt, RelayerRequestFailedError as k, balanceOfContract as kt, Token as l, getConfidentialTokenAddressContract as lt, BatchDecryptResult as m, getTokenPairsSliceContract as mt, DefaultRegistryAddresses as n, SignerQueryContext as nt, WrappedToken as o, PaginatedResult as ot, BatchDecryptItem as p, getTokenPairsLengthContract as pt, InvalidTransportKeyPairError as q, resolveChainRelayers as qt, ListPairsOptions as r, zamaQueryKeys as rt, BatchBalancesResult as s, TokenWrapperPair as st, ZamaSDK as t, decryptValuesQueryOptions as tt, Permits as u, getTokenAddressContract as ut, WorkerTimeoutError as v, isHandleDelegatedContract as vt, WalletAccountNotReadyError as w, isConfidentialTokenContract as wt, SigningRejectedError as x, ERC1363_INTERFACE_ID as xt, TransactionRevertedError as y, revokeDelegationContract as yt, DelegationCooldownError as z, isOperatorContract as zt };
|
|
20636
|
+
//# sourceMappingURL=index-C1Mtc8Rw.d.ts.map
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { $ as decodeDelegatedForUserDecryption, A as UnshieldPhase2StartedEvent,
|
|
|
5
5
|
import { t as ZamaConfigEthers } from "./types-OHIaPwCy.js";
|
|
6
6
|
import { n as MutableWalletAccountStore, r as createWalletAccountStore, t as BaseSigner } from "./base-signer-C3Wc5oi9.js";
|
|
7
7
|
import { t as cleartext } from "./cleartext-DAkOTlrE.js";
|
|
8
|
-
import { $ as
|
|
8
|
+
import { $ as DecryptResult, A as BalanceCheckUnavailableError, At as decimalsContract, B as DelegationDelegateEqualsContractError, Bt as rateContract, C as SignerRequiredError, Ct as ERC7984_WRAPPER_INTERFACE_ID, D as NotEntitledError, Dt as allowanceContract, E as RpcRateLimitError, Et as supportsInterfaceContract, F as DecryptionFailedError, Ft as confidentialTransferContract, G as DelegationNotPropagatedError, Gt as wrapContract, H as DelegationExpiredError, Ht as underlyingContract, I as EncryptionFailedError, It as confidentialTransferFromContract, J as NoCiphertextError, Jt as resolveStorage, K as DelegationSelfNotAllowedError, Kt as ResolvedChainRelayer, L as AclPausedError, Lt as finalizeUnwrapContract, M as ERC20ReadFailedError, Mt as symbolContract, N as InsufficientConfidentialBalanceError, Nt as confidentialBalanceOfContract, O as ConfigurationError, Ot as approveContract, P as InsufficientERC20BalanceError, Pt as confidentialTotalSupplyContract, Q as ZamaErrorCode, R as DelegationContractIsSelfError, Rt as inferredTotalSupplyContract, S as SignerNotConfiguredError, St as ERC7984_INTERFACE_ID, T as WalletNotConnectedError, Tt as isConfidentialWrapperContract, U as DelegationExpiryUnchangedError, Ut as unwrapContract, V as DelegationExpirationTooSoonError, Vt as setOperatorContract, W as DelegationNotFoundError, Wt as unwrapFromBalanceContract, X as ChainMismatchError, Y as TransportKeyPairExpiredError, Yt as createConfig, Z as ZamaError, _ as WorkerRecycledError, _t as getDelegationExpiryContract, a as WrappersRegistryConfig, b as SigningFailedError, bt as transferAndCallContract, c as BatchDecryptAsOptions, ct as TokenWrapperPairWithMetadata, d as Delegations, dt as getTokenPairContract, et as EncryptedInput, f as Decryption, ft as getTokenPairsContract, g as matchZamaError, gt as delegateForUserDecryptionContract, h as DelegatedDecryptOptions, ht as isConfidentialTokenValidContract, i as WrappersRegistry, j as BalanceErrorDetails, jt as nameContract, k as RelayerRequestFailedError, kt as balanceOfContract, l as Token, lt as getConfidentialTokenAddressContract, m as BatchDecryptResult, mt as getTokenPairsSliceContract, n as DefaultRegistryAddresses, o as WrappedToken, ot as PaginatedResult, p as BatchDecryptItem, pt as getTokenPairsLengthContract, q as InvalidTransportKeyPairError, qt as resolveChainRelayers, r as ListPairsOptions, s as BatchBalancesResult, st as TokenWrapperPair, t as ZamaSDK, u as Permits, ut as getTokenAddressContract, v as WorkerTimeoutError, vt as isHandleDelegatedContract, w as WalletAccountNotReadyError, wt as isConfidentialTokenContract, x as SigningRejectedError, xt as ERC1363_INTERFACE_ID, y as TransactionRevertedError, yt as revokeDelegationContract, z as DelegationCooldownError, zt as isOperatorContract } from "./index-C1Mtc8Rw.js";
|
|
9
9
|
import { t as ZamaConfigViem } from "./types-piBsdTIP.js";
|
|
10
10
|
import { Address, Hex } from "viem";
|
|
11
11
|
import { FheTypeName, FhevmInstanceConfig, InputProofBytesType, KmsDelegatedUserDecryptEIP712Type as KmsDelegatedDecryptEIP712Type, ZKProofLike } from "@zama-fhe/relayer-sdk/bundle";
|
|
@@ -58,13 +58,17 @@ declare const indexedDBStorage: IndexedDBStorage;
|
|
|
58
58
|
* @example
|
|
59
59
|
* ```ts
|
|
60
60
|
* import { ZamaSDK, indexedDBStorage, chromeSessionStorage } from "@zama-fhe/sdk";
|
|
61
|
+
* import { createConfig } from "@zama-fhe/sdk/viem";
|
|
61
62
|
*
|
|
62
|
-
* const
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
63
|
+
* const config = createConfig({
|
|
64
|
+
* chains: [mySepolia],
|
|
65
|
+
* publicClient,
|
|
66
|
+
* walletClient,
|
|
67
|
+
* relayers: { [mySepolia.id]: web() },
|
|
68
|
+
* storage: indexedDBStorage, // encrypted transport key pair — persistent
|
|
69
|
+
* permitStorage: chromeSessionStorage, // signed permits — ephemeral
|
|
67
70
|
* });
|
|
71
|
+
* const sdk = new ZamaSDK(config);
|
|
68
72
|
* ```
|
|
69
73
|
*/
|
|
70
74
|
declare class ChromeSessionStorage implements GenericStorage {
|
|
@@ -75,5 +79,5 @@ declare class ChromeSessionStorage implements GenericStorage {
|
|
|
75
79
|
/** Default singleton for application-wide use. */
|
|
76
80
|
declare const chromeSessionStorage: ChromeSessionStorage;
|
|
77
81
|
//#endregion
|
|
78
|
-
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, ChromeSessionStorage, type ClearValue, type CleartextRelayerConfig, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type DecryptEndEvent, type DecryptErrorEvent, type EncryptedInput as DecryptInput, type PublicDecryptResult as DecryptPublicValuesResult, type DecryptResult, type DecryptStartEvent, type UserDecryptParams as DecryptValuesParams, Decryption, DecryptionFailedError, DefaultRegistryAddresses, type DelegatedDecryptOptions, type DelegatedUserDecryptParams as DelegatedDecryptValuesParams, 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 FheEncryptionKey, type FheTypeName, type FhevmInstanceConfig, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericProvider, type GenericSigner, type GenericStorage, type Hex, IndexedDBStorage, type InputProofBytesType, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidTransportKeyPairError, type KmsDelegatedDecryptEIP712Type, type ListPairsOptions, MemoryStorage, MutableWalletAccountStore, type NetworkType, NoCiphertextError, NotEntitledError, type OnChainEvent, type PaginatedResult, type
|
|
82
|
+
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, ChromeSessionStorage, type ClearValue, type CleartextRelayerConfig, type ConfidentialTransferEvent, ConfigurationError, type ContractAbi, type DecryptEndEvent, type DecryptErrorEvent, type EncryptedInput as DecryptInput, type PublicDecryptResult as DecryptPublicValuesResult, type DecryptResult, type DecryptStartEvent, type UserDecryptParams as DecryptValuesParams, Decryption, DecryptionFailedError, DefaultRegistryAddresses, type DelegatedDecryptOptions, type DelegatedUserDecryptParams as DelegatedDecryptValuesParams, 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 FheEncryptionKey, type FheTypeName, type FhevmInstanceConfig, type FinalizeUnwrapSubmittedEvent, type GenericLogger, type GenericProvider, type GenericSigner, type GenericStorage, type Hex, IndexedDBStorage, type InputProofBytesType, InsufficientConfidentialBalanceError, InsufficientERC20BalanceError, InvalidTransportKeyPairError, type KmsDelegatedDecryptEIP712Type, type ListPairsOptions, MemoryStorage, MutableWalletAccountStore, type NetworkType, NoCiphertextError, NotEntitledError, type OnChainEvent, type PaginatedResult, type Permission, Permits, type PublicParamsData, type RawLog, type ReadContractArgs, type ReadContractConfig, type ReadContractReturnType, type ReadFunctionName, type RelayerConfig, type RelayerDispatcher, RelayerRequestFailedError, type RelayerSDK, type RelayerSDKStatus, type ResolvedChainRelayer, type RevokeDelegationSubmittedEvent, type RevokedDelegationForUserDecryptionEvent, RpcRateLimitError, 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, type TransportKeyPair, TransportKeyPairExpiredError, type UnshieldCallbacks, type UnshieldOptions, type UnshieldPhase1SubmittedEvent, type UnshieldPhase2StartedEvent, type UnshieldPhase2SubmittedEvent, type UnwrapFinalizedEvent, type UnwrapRequestedEvent, type UnwrapSubmittedEvent, type WalletAccount, type WalletAccountChange, type WalletAccountListener, WalletAccountNotReadyError, type WalletAccountStore, WalletNotConnectedError, type WorkerLike, WorkerRecycledError, WorkerTimeoutError, type WrapEvent, WrappedToken, WrappersRegistry, type WrappersRegistryConfig, type WriteContractArgs, type WriteContractConfig, type WriteFunctionName, ZERO_ENCRYPTED_VALUE, type ZKProofLike, 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, mainnet, matchZamaError, memoryStorage, nameContract, rateContract, resolveChainRelayers, resolveStorage, revokeDelegationContract, sepolia, setOperatorContract, supportsInterfaceContract, symbolContract, transferAndCallContract, underlyingContract, unwrapContract, unwrapFromBalanceContract, wrapContract };
|
|
79
83
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./relayer-eavK5bfZ.js";import{A as i,B as a,C as o,D as s,F as c,H as l,I as u,L as d,M as f,N as ee,O as te,P as ne,R as re,S as ie,T as ae,U as oe,V as se,W as ce,_ as le,a as ue,b as de,c as fe,d as pe,f as me,g as p,h as m,i as he,j as ge,k as _e,l as ve,m as ye,n as be,o as xe,p as Se,r as Ce,s as we,t as Te,u as Ee,v as De,x as Oe,z as ke}from"./wrappers-registry-C1oK8Bi6.js";import{n as h,t as g}from"./encryption-x4Z_Icqk.js";import{_ as Ae,a as je,b as _,c as Me,d as Ne,f as Pe,g as Fe,h as Ie,i as v,l as y,m as Le,n as Re,o as b,p as ze,r as Be,s as x,t as S,u as Ve,v as He,x as C,y as Ue}from"./token-Bt33g0zQ.js";import{n as w}from"./relayer-cleartext-Bp6jtxDd.js";import{n as We,t as Ge}from"./timeout-CNVfiaJD.js";import{_ as T,c as Ke,f as qe,h as Je,i as Ye,l as E,m as Xe,t as Ze,u as Qe}from"./assertions-zYseN5Xz.js";import{t as $e}from"./cleartext-rTWFctyd.js";import{a as et,c as tt,d as nt,f as D,i as rt,l as it,n as at,o as O,r as ot,s as st,t as ct,u as lt}from"./base-signer-DjytqPkd.js";import{n as ut,t as dt}from"./indexeddb-storage-Mi-fCWN3.js";import{n as ft,t as pt}from"./memory-storage-fp9RY5BQ.js";import{t as k}from"./hex-A72GrTf9.js";import{a as mt,c as ht,i as gt,n as _t,o as vt,r as yt,s as bt,t as xt}from"./chains-CXcO1DBP.js";import{getAddress as A,keccak256 as St,toBytes as Ct}from"viem";import{z as j}from"zod/mini";function wt(e,t){if(e instanceof n){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Tt=class extends n{constructor(t,n){super(e.TransportKeyPairExpired,t,n),this.name=`TransportKeyPairExpiredError`}},Et=class extends n{constructor(t,n){super(e.InvalidTransportKeyPair,t,n),this.name=`InvalidTransportKeyPairError`}},Dt=class extends n{constructor(t,n){super(e.NoCiphertext,t,n),this.name=`NoCiphertextError`}},M=class extends n{constructor(t,n){super(e.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},Ot=class extends n{constructor(t,n){super(e.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},N=class extends n{constructor(t,n){super(e.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},P=class extends n{constructor(t,n){super(e.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},F=class extends n{constructor(t,n){super(e.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},I=class extends n{constructor(t,n){super(e.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},kt=class extends n{constructor(t,n){super(e.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},At=class extends n{constructor(t,n){super(e.AclPaused,t,n),this.name=`AclPausedError`}},L=class extends n{constructor(t,n){super(e.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},R=class extends n{constructor(t,n){super(e.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function z(e,n,r={}){if(e instanceof g||e instanceof Dt||e instanceof t||e instanceof R||e instanceof ce||e instanceof oe||e instanceof w||e instanceof _||e instanceof We||e instanceof Ge)return e;let i=e instanceof Error?e.message:n;if(e instanceof Error&&qe(e.message))return r.isDelegated?new R(`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 w({encryptedValue:Je(e.message)??``,contractAddress:r.contractAddress??``,account:r.account??``},{cause:e});if(Qe(e))return new _(i,{cause:e,retryAfter:E(e)});let a=Ke(e);return a===void 0&&Xe(e)?new _(i,{cause:e,retryAfter:E(e)}):a===400?new Dt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):r.isDelegated&&a===500?new R(`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}):a===void 0?new g(n,{cause:e}):new t(i,a,{cause:e,retryAfter:E(e)})}function jt(e,r){if(e instanceof n)return e;let i=Ke(e);return i===void 0?new h(r,{cause:e}):new t(e instanceof Error?e.message:r,i,{cause:e,retryAfter:E(e)})}const Mt=[{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 Nt(e,t,n,r=`0x`){return{address:e,abi:Mt,functionName:`transferAndCall`,args:[t,n,r]}}function Pt(e){return rt(e.signer,e.provider,e)}var Ft=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return l(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await x(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await x(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedUserDecrypt(e,t,a.address,n,r)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw z(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await x(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},It=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return l(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await x(`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 x(`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)}},Lt=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 l(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await Me(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await Me(`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=A((await x(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await d(`clear decrypt cache`,()=>this.#n.clearForRequester(n),this.#i)}}async clear(){let e=this.#a(`clear`),t=A((await x(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await d(`clear decrypt cache`,()=>this.#n.clearForRequester(t),this.#i)}}};const Rt=j.union([j.bigint(),j.boolean(),nt]),zt=j.array(j.string());var Bt=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=Rt.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=A(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}:${A(e)}:${A(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=zt.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 Vt(e,t){let n=Wt(e,t);if(!n)throw new g(`No permit covers contract ${t} after allow()`);return Ut(e,n)}function Ht(e,t){let n=Wt(e,t);if(!n)throw new g(`No delegated permit covers contract ${t} after allow()`);return{...Ut(e,n),delegatorAddress:n.delegatorAddress}}function Ut(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function Wt(e,t){let n=lt(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}const Gt=e=>new Promise(t=>setTimeout(t,e));var Kt=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=A(t);return this.#o(e,{requesterAddress:n,aclActorAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...Vt(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r,i){let a=A(t),o=A(n);return this.#a(i?.waitForPropagation??!0,()=>this.#o(e,{requesterAddress:A(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#d(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...Ht(e,t),delegateAddress:o}),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 R))throw t;await Gt(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:A(e.contractAddress)}));if(o.length===0)return{items:o};let s=A(r);try{let e=await this.delegatedUserDecrypt(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#c(t,e);return{items:o}}catch(e){if(Le(e))throw e;if(o.length===1){let[n=this.#u()]=o;return n.error=this.#l(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:A(t)}),{items:o}}}let c=!1;return await je(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#c(e,r)}catch(n){if(Le(n))throw c=!0,n;e.error=this.#l(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:A(t)})}}),i),{items:o}}async#o(e,t){if(e.length===0)return{};let r=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:A(e.contractAddress)})),i={},a=[];for(let e of r)v(e.encryptedValue)?i[e.encryptedValue]=0n:a.push(e);if(a.length===0)return i;let o=Array.from(new Set(r.map(e=>e.contractAddress))),s=Array.from(new Set(a.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(s)}catch(e){throw Xe(e)?this.#s(e,`the delegation pre-check`):e}let c=[];for(let e of a){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?c.push(e):i[e.encryptedValue]=n}if(c.length===0)return i;let l=await t.resolveCredentials(o),u=new Map;for(let e of c){let t=u.get(e.contractAddress);t?t.push(e.encryptedValue):u.set(e.contractAddress,[e.encryptedValue])}let d=Date.now(),f=c.map(e=>e.encryptedValue);try{this.#i({type:b.DecryptStart,encryptedValues:f}),await je([...u.entries()].map(([e,n])=>async()=>{let r;try{r=await t.decryptContract({credentials:l,contractAddress:e,encryptedValues:n})}catch(n){throw z(n,t.errorMessage,{isDelegated:t.delegated,contractAddress:e,account:t.aclActorAddress})}for(let[n,a]of Object.entries(r))i[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of f){let n=i[t];n!==void 0&&(e[t]=n)}return this.#i({type:b.DecryptEnd,durationMs:Date.now()-d,encryptedValues:f,result:e}),i}catch(e){let r=e instanceof n&&e.cause instanceof Error?e.cause:e;throw this.#i({type:b.DecryptError,error:T(r),durationMs:Date.now()-d,encryptedValues:f}),z(e,t.errorMessage,{isDelegated:t.delegated})}}#s(e,t){return new _(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:E(e)})}#c(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new g(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#l(e,t,r){return e instanceof n?e:z(e,t,r)}#u(){throw new g(`Batch delegated decryption invariant failed: missing item`)}async#d(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 qt(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 B={AlreadyDelegatedOrRevokedInSameBlock:e=>new Ot(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new kt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new At(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new M(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new I(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new L(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new F(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new N(`Cannot revoke: no active delegation exists.`,{cause:e})};function Jt(e){return e in B}function Yt(e,t){let n=qt(e);if(n&&Jt(n))return B[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(B))if(r.includes(e))return n(t);return null}var Xt=class{#e;#t;#n;#r;constructor({provider:e,relayer:t,emitEvent:n=()=>{},logger:r}){this.#e=e,this.#t=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 L(`Expiration date must be at least 1 hour in the future`);let a=A(t),o=A(n),s=A(r);if(o===s)throw new M(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new I(`Delegate address cannot be the same as the contract address (${a}).`);let c=await this.#t.getAclAddress(),l=i?BigInt(Math.floor(i.getTime()/1e3)):y,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 F(`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:Ve(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=A(t),a=A(n),o=A(r),s=await this.#t.getAclAddress(),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 N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:ze(s,a,i)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===y?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=await this.#t.getAclAddress();return this.#e.readContract(Ne(r,A(t),A(n),A(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Re({operation:e,signer:t,provider:this.#e,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof C))return;let t=Yt(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 N||t instanceof P){let n=A(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=A(e),i=A(t),a=A(n),o=await this.getDelegationExpiry({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(o===0n)throw new N(`No active delegation from ${i} to ${a} for ${r}`);if(o!==y&&o<=await this.#e.getBlockTimestamp())throw new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},Zt=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(e){let t=Date.now();try{this.#t({type:b.EncryptStart},e.contractAddress);let n=await this.#e.encrypt(e);return this.#t({type:b.EncryptEnd,durationMs:Date.now()-t},e.contractAddress),n}catch(n){throw this.#t({type:b.EncryptError,error:T(n),durationMs:Date.now()-t},e.contractAddress),jt(n,`Encryption failed`)}}},Qt=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.relayer,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 d(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await d(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await d(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>d(`wallet account listener`,()=>t(e),this.#i)))}};function V(e){return St(Ct(e))}const H={ConfidentialTransfer:V(`ConfidentialTransfer(address,address,bytes32)`),Wrap:V(`Wrap(address,uint256,bytes32)`),UnwrapRequested:V(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:V(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function U(e){return A(k(e.slice(-40)))}function W(e){return e}function G(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 A(k(G(e,t).slice(-40)))}function K(e,t){return BigInt(`0x`+G(e,t))}function q(e,t){return k(G(e,t))}function en(e){return e.topics[0]!==H.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:U(e.topics[1]),to:U(e.topics[2]),encryptedAmount:W(e.topics[3])}}function J(e){return e.topics[0]!==H.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:U(e.topics[1]),roundedAmount:K(e.data,0),encryptedWrappedAmount:q(e.data,1)}}function Y(e){return e.topics[0]!==H.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:U(e.topics[1]),unwrapRequestId:W(e.topics[2]),encryptedAmount:q(e.data,0)}}function tn(e){return e.topics[0]!==H.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:U(e.topics[1]),unwrapRequestId:W(e.topics[2]),encryptedAmount:q(e.data,0),cleartextAmount:K(e.data,1)}}function nn(e){return en(e)??J(e)??Y(e)??tn(e)}function rn(e){let t=[];for(let n of e){let e=nn(n);e&&t.push(e)}return t}function an(e){for(let t of e){let e=Y(t);if(e)return e}return null}function on(e){for(let t of e){let e=J(t);if(e)return e}return null}const sn=[H.ConfidentialTransfer,H.Wrap,H.UnwrapRequested,H.UnwrapFinalized],X={DelegatedForUserDecryption:V(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:V(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Z(e){return e.topics[0]!==X.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:K(e.data,1),oldExpirationDate:K(e.data,2),newExpirationDate:K(e.data,3)}}function Q(e){return e.topics[0]!==X.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:K(e.data,1),oldExpirationDate:K(e.data,2)}}function cn(e){return Z(e)??Q(e)}function ln(e){let t=[];for(let n of e){let e=cn(n);e&&t.push(e)}return t}function un(e){for(let t of e){let e=Z(t);if(e)return e}return null}function dn(e){for(let t of e){let e=Q(t);if(e)return e}return null}const fn=[X.DelegatedForUserDecryption,X.RevokedDelegationForUserDecryption];var pn=class extends S{#e;#t=null;#n=null;#r(e){try{return Ye(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new re(e,{cause:t})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(Se(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#o();return this.sdk.provider.readContract(m(t,A(e),this.address))}async shield(e,t){let r=await x(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),a=await this.#o(),o=A(r.address),s;try{s=await this.sdk.provider.readContract(le(a,o))}catch(e){throw e instanceof n?e:new Fe(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:T(e)})}if(s<e)throw new He(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${a})`,{requested:e,available:s,token:a});return i?this.#i(e,a,o,t):this.#a(e,o,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?A(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:Nt(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#c(e,r===`max`,n);let i=n?.to?A(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:u(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await x(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#o(),r=A(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(m(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:p(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:p(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 d(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#s(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return d(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#s(n.txHash,t,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async unwrap(e){this.#r(`unwrap`);let t=A((await x(`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 h(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:ne(this.address,t,t,i,r)})}async unwrapAll(){this.#r(`unwrapAll`);let e=A((await x(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(v(t))throw new g(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:c(this.address,e,e,t)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await Me(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let t=await this.sdk.decryption.decryptPublicValues([e]),n=t.clearValues[e];return Ze(n,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:te(this.address,e,n,t.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(ee(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(e,t,r){this.emit({type:b.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof n?e:new C(`Failed to get unshield receipt`,{cause:e})}let a=an(i.logs);if(!a)throw new C(`No UnwrapRequested event found in unshield receipt`);this.emit({type:b.UnshieldPhase2Started,operationId:t}),d(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let o=await this.finalizeUnwrap(a.unwrapRequestId??a.encryptedAmount);return this.emit({type:b.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),d(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(o.txHash),this.sdk.logger),o}async#c(e,t,n){this.#r(`approveUnderlying`);let r=await this.#o(),i=A((await x(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),a=await this.sdk.provider.readContract(m(r,i,this.address));if(a>=e)return;a>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:p(r,this.address,0n)});let o=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:p(r,this.address,o),onSubmitted:n?.onApprovalSubmitted})}},mn=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#n=e.onEvent??function(){},this.#r=e.logger,this.#i=new Bt(e.storage,this.#r),this.#l=new Xt({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this),logger:this.#r});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new O({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#t=t,this.#e=e.registryTTL,e.signer&&(this.#c=new it({relayer:this.relayer,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage,logger:this.#r}),this.#s=new Kt({cache:this.#i,credentialService:this.#c,delegationService:this.#l,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#o=new Zt({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#a=new Qt({signer:e.signer,relayer:this.relayer,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.permits=new Lt({signer:this.signer,provider:this.provider,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.delegations=new It({signer:this.signer,provider:this.provider,delegationService:this.#l}),this.decryption=new Ft({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#s})}onWalletAccountChange(e){return this.#a.onWalletAccountChange(e)}get logger(){return this.#r}emitEvent(e,t){try{this.#n({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#r.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new O({provider:this.provider,registryAddresses:{...this.#t,...e},registryTTL:this.#e})}async encrypt(e){return this.#o.encrypt(e)}createToken(e){return new S(this,e)}createWrappedToken(e){return new pn(this,e)}dispose(){this.#a.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${lt(e)}`}const hn=j.union([j.pipe(D,j.transform(e=>({unwrapTxHash:e}))),j.pipe(j.object({version:j.literal(1),unwrapTxHash:D,unwrapRequestId:j.optional(D)}),j.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function gn(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 _n(e,t){return(await vn(e,t))?.unwrapTxHash??null}async function vn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=hn.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function yn(e,t){await e.delete($(t))}var bn=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 xn=new bn;export{fn as ACL_TOPICS,At as AclPausedError,X as AclTopics,Ie as BalanceCheckUnavailableError,ct as BaseSigner,Ue as ChainMismatchError,bn as ChromeSessionStorage,r as ConfigurationError,Ft as Decryption,g as DecryptionFailedError,et as DefaultRegistryAddresses,kt as DelegationContractIsSelfError,Ot as DelegationCooldownError,I as DelegationDelegateEqualsContractError,L as DelegationExpirationTooSoonError,P as DelegationExpiredError,F as DelegationExpiryUnchangedError,N as DelegationNotFoundError,R as DelegationNotPropagatedError,M as DelegationSelfNotAllowedError,It as Delegations,fe as ERC1363_INTERFACE_ID,Fe as ERC20ReadFailedError,ve as ERC7984_INTERFACE_ID,Ee as ERC7984_WRAPPER_INTERFACE_ID,h as EncryptionFailedError,dt as IndexedDBStorage,Ae as InsufficientConfidentialBalanceError,He as InsufficientERC20BalanceError,Et as InvalidTransportKeyPairError,pt as MemoryStorage,at as MutableWalletAccountStore,Dt as NoCiphertextError,w as NotEntitledError,Lt as Permits,t as RelayerRequestFailedError,_ as RpcRateLimitError,re as SignerNotConfiguredError,ke as SignerRequiredError,oe as SigningFailedError,ce as SigningRejectedError,sn as TOKEN_TOPICS,S as Token,H as Topics,C as TransactionRevertedError,Tt as TransportKeyPairExpiredError,a as WalletAccountNotReadyError,se as WalletNotConnectedError,Ge as WorkerRecycledError,We as WorkerTimeoutError,pn as WrappedToken,O as WrappersRegistry,Be as ZERO_ENCRYPTED_VALUE,n as ZamaError,e as ZamaErrorCode,mn as ZamaSDK,b as ZamaSDKEvents,m as allowanceContract,xt as anvil,p as approveContract,le as balanceOfContract,_t as bscTestnet,yt as chains,xn as chromeSessionStorage,yn as clearPendingUnshield,$e as cleartext,ie as confidentialBalanceOfContract,o as confidentialTotalSupplyContract,ae as confidentialTransferContract,s as confidentialTransferFromContract,Pt as createConfig,ot as createWalletAccountStore,De as decimalsContract,cn as decodeAclEvent,ln as decodeAclEvents,en as decodeConfidentialTransfer,Z as decodeDelegatedForUserDecryption,nn as decodeOnChainEvent,rn as decodeOnChainEvents,Q as decodeRevokedDelegationForUserDecryption,tn as decodeUnwrapFinalized,Y as decodeUnwrapRequested,J as decodeWrap,Ve as delegateForUserDecryptionContract,te as finalizeUnwrapContract,un as findDelegatedForUserDecryption,dn as findRevokedDelegationForUserDecryption,an as findUnwrapRequested,on as findWrap,Te as getConfidentialTokenAddressContract,Ne as getDelegationExpiryContract,be as getTokenAddressContract,Ce as getTokenPairContract,he as getTokenPairsContract,ue as getTokenPairsLengthContract,xe as getTokenPairsSliceContract,gt as hardhat,mt as hoodi,ut as indexedDBStorage,_e as inferredTotalSupplyContract,vt as ingenTestnet,pe as isConfidentialTokenContract,we as isConfidentialTokenValidContract,me as isConfidentialWrapperContract,v as isEncryptedValueZero,Pe as isHandleDelegatedContract,i as isOperatorContract,_n as loadPendingUnshield,vn as loadPendingUnshieldRequest,bt as mainnet,wt as matchZamaError,ft as memoryStorage,de as nameContract,ge as rateContract,st as resolveChainRelayers,tt as resolveStorage,ze as revokeDelegationContract,gn as savePendingUnshield,ht as sepolia,f as setOperatorContract,ye as supportsInterfaceContract,Oe as symbolContract,Nt as transferAndCallContract,ee as underlyingContract,ne as unwrapContract,c as unwrapFromBalanceContract,u as wrapContract};
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./relayer-eavK5bfZ.js";import{A as i,B as a,C as o,D as s,F as c,H as l,I as u,L as d,M as f,N as ee,O as te,P as ne,R as re,S as ie,T as ae,U as oe,V as se,W as ce,_ as le,a as ue,b as de,c as fe,d as pe,f as me,g as p,h as m,i as he,j as ge,k as _e,l as ve,m as ye,n as be,o as xe,p as Se,r as Ce,s as we,t as Te,u as Ee,v as De,x as Oe,z as ke}from"./wrappers-registry-C1oK8Bi6.js";import{n as h,t as g}from"./encryption-x4Z_Icqk.js";import{_ as Ae,a as je,b as _,c as Me,d as Ne,f as Pe,g as Fe,h as Ie,i as v,l as y,m as Le,n as Re,o as b,p as ze,r as Be,s as x,t as S,u as Ve,v as He,x as C,y as Ue}from"./token-Bt33g0zQ.js";import{n as w}from"./relayer-cleartext-Bp6jtxDd.js";import{n as We,t as Ge}from"./timeout-CNVfiaJD.js";import{_ as T,c as Ke,f as qe,h as Je,i as Ye,l as E,m as Xe,t as Ze,u as Qe}from"./assertions-zYseN5Xz.js";import{t as $e}from"./cleartext-rTWFctyd.js";import{a as et,c as tt,d as nt,f as D,i as rt,l as it,n as at,o as O,r as ot,s as st,t as ct,u as lt}from"./base-signer-DjytqPkd.js";import{n as ut,t as dt}from"./indexeddb-storage-Mi-fCWN3.js";import{n as ft,t as pt}from"./memory-storage-fp9RY5BQ.js";import{t as k}from"./hex-A72GrTf9.js";import{a as mt,c as ht,i as gt,n as _t,o as vt,r as yt,s as bt,t as xt}from"./chains-CXcO1DBP.js";import{getAddress as A,keccak256 as St,toBytes as Ct}from"viem";import{z as j}from"zod/mini";function wt(e,t){if(e instanceof n){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Tt=class extends n{constructor(t,n){super(e.TransportKeyPairExpired,t,n),this.name=`TransportKeyPairExpiredError`}},Et=class extends n{constructor(t,n){super(e.InvalidTransportKeyPair,t,n),this.name=`InvalidTransportKeyPairError`}},Dt=class extends n{constructor(t,n){super(e.NoCiphertext,t,n),this.name=`NoCiphertextError`}},M=class extends n{constructor(t,n){super(e.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},Ot=class extends n{constructor(t,n){super(e.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},N=class extends n{constructor(t,n){super(e.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},P=class extends n{constructor(t,n){super(e.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},F=class extends n{constructor(t,n){super(e.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},I=class extends n{constructor(t,n){super(e.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},kt=class extends n{constructor(t,n){super(e.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},At=class extends n{constructor(t,n){super(e.AclPaused,t,n),this.name=`AclPausedError`}},L=class extends n{constructor(t,n){super(e.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},R=class extends n{constructor(t,n){super(e.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function z(e,n,r={}){if(e instanceof g||e instanceof Dt||e instanceof t||e instanceof R||e instanceof ce||e instanceof oe||e instanceof w||e instanceof _||e instanceof We||e instanceof Ge)return e;let i=e instanceof Error?e.message:n;if(e instanceof Error&&qe(e.message))return r.isDelegated?new R(`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 w({encryptedValue:Je(e.message)??``,contractAddress:r.contractAddress??``,account:r.account??``},{cause:e});if(Qe(e))return new _(i,{cause:e,retryAfter:E(e)});let a=Ke(e);return a===void 0&&Xe(e)?new _(i,{cause:e,retryAfter:E(e)}):a===400?new Dt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):r.isDelegated&&a===500?new R(`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}):a===void 0?new g(n,{cause:e}):new t(i,a,{cause:e,retryAfter:E(e)})}function jt(e,r){if(e instanceof n)return e;let i=Ke(e);return i===void 0?new h(r,{cause:e}):new t(e instanceof Error?e.message:r,i,{cause:e,retryAfter:E(e)})}const Mt=[{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 Nt(e,t,n,r=`0x`){return{address:e,abi:Mt,functionName:`transferAndCall`,args:[t,n,r]}}function Pt(e){return rt(e.signer,e.provider,e)}var Ft=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return l(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await x(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await x(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedUserDecrypt(e,t,a.address,n,r)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw z(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i}){let a=this.#i(`delegatedBatchDecryptValues`),o=await x(`delegatedBatchDecryptValues`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i})}},It=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return l(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await x(`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 x(`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)}},Lt=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 l(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await Me(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await Me(`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=A((await x(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await d(`clear decrypt cache`,()=>this.#n.clearForRequester(n),this.#i)}}async clear(){let e=this.#a(`clear`),t=A((await x(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await d(`clear decrypt cache`,()=>this.#n.clearForRequester(t),this.#i)}}};const Rt=j.union([j.bigint(),j.boolean(),nt]),zt=j.array(j.string());var Bt=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=Rt.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=A(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}:${A(e)}:${A(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=zt.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 Vt(e,t){let n=Wt(e,t);if(!n)throw new g(`No permit covers contract ${t} after allow()`);return Ut(e,n)}function Ht(e,t){let n=Wt(e,t);if(!n)throw new g(`No delegated permit covers contract ${t} after allow()`);return{...Ut(e,n),delegatorAddress:n.delegatorAddress}}function Ut(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function Wt(e,t){let n=lt(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}const Gt=e=>new Promise(t=>setTimeout(t,e));var Kt=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=A(t);return this.#o(e,{requesterAddress:n,aclActorAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...Vt(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r,i){let a=A(t),o=A(n);return this.#a(i?.waitForPropagation??!0,()=>this.#o(e,{requesterAddress:A(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#d(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...Ht(e,t),delegateAddress:o}),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 R))throw t;await Gt(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:A(e.contractAddress)}));if(o.length===0)return{items:o};let s=A(r);try{let e=await this.delegatedUserDecrypt(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s,{waitForPropagation:a});for(let t of o)this.#c(t,e);return{items:o}}catch(e){if(Le(e))throw e;if(o.length===1){let[n=this.#u()]=o;return n.error=this.#l(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:A(t)}),{items:o}}}let c=!1;return await je(o.map(e=>async()=>{if(!c)try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s,{waitForPropagation:!1});this.#c(e,r)}catch(n){if(Le(n))throw c=!0,n;e.error=this.#l(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:A(t)})}}),i),{items:o}}async#o(e,t){if(e.length===0)return{};let r=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:A(e.contractAddress)})),i={},a=[];for(let e of r)v(e.encryptedValue)?i[e.encryptedValue]=0n:a.push(e);if(a.length===0)return i;let o=Array.from(new Set(r.map(e=>e.contractAddress))),s=Array.from(new Set(a.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(s)}catch(e){throw Xe(e)?this.#s(e,`the delegation pre-check`):e}let c=[];for(let e of a){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?c.push(e):i[e.encryptedValue]=n}if(c.length===0)return i;let l=await t.resolveCredentials(o),u=new Map;for(let e of c){let t=u.get(e.contractAddress);t?t.push(e.encryptedValue):u.set(e.contractAddress,[e.encryptedValue])}let d=Date.now(),f=c.map(e=>e.encryptedValue);try{this.#i({type:b.DecryptStart,encryptedValues:f}),await je([...u.entries()].map(([e,n])=>async()=>{let r;try{r=await t.decryptContract({credentials:l,contractAddress:e,encryptedValues:n})}catch(n){throw z(n,t.errorMessage,{isDelegated:t.delegated,contractAddress:e,account:t.aclActorAddress})}for(let[n,a]of Object.entries(r))i[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of f){let n=i[t];n!==void 0&&(e[t]=n)}return this.#i({type:b.DecryptEnd,durationMs:Date.now()-d,encryptedValues:f,result:e}),i}catch(e){let r=e instanceof n&&e.cause instanceof Error?e.cause:e;throw this.#i({type:b.DecryptError,error:T(r),durationMs:Date.now()-d,encryptedValues:f}),z(e,t.errorMessage,{isDelegated:t.delegated})}}#s(e,t){return new _(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:E(e)})}#c(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new g(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#l(e,t,r){return e instanceof n?e:z(e,t,r)}#u(){throw new g(`Batch delegated decryption invariant failed: missing item`)}async#d(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 qt(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 B={AlreadyDelegatedOrRevokedInSameBlock:e=>new Ot(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new kt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new At(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new M(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new I(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new L(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new F(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new N(`Cannot revoke: no active delegation exists.`,{cause:e})};function Jt(e){return e in B}function Yt(e,t){let n=qt(e);if(n&&Jt(n))return B[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(B))if(r.includes(e))return n(t);return null}var Xt=class{#e;#t;#n;#r;constructor({provider:e,relayer:t,emitEvent:n=()=>{},logger:r}){this.#e=e,this.#t=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 L(`Expiration date must be at least 1 hour in the future`);let a=A(t),o=A(n),s=A(r);if(o===s)throw new M(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new I(`Delegate address cannot be the same as the contract address (${a}).`);let c=await this.#t.getAclAddress(),l=i?BigInt(Math.floor(i.getTime()/1e3)):y,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 F(`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:Ve(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=A(t),a=A(n),o=A(r),s=await this.#t.getAclAddress(),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 N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:ze(s,a,i)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===y?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=await this.#t.getAclAddress();return this.#e.readContract(Ne(r,A(t),A(n),A(e)))}async#i({operation:e,signer:t,contractAddress:n,config:r}){try{return await Re({operation:e,signer:t,provider:this.#e,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof C))return;let t=Yt(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 N||t instanceof P){let n=A(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=A(e),i=A(t),a=A(n),o=await this.getDelegationExpiry({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(o===0n)throw new N(`No active delegation from ${i} to ${a} for ${r}`);if(o!==y&&o<=await this.#e.getBlockTimestamp())throw new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},Zt=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(e){let t=Date.now();try{this.#t({type:b.EncryptStart},e.contractAddress);let n=await this.#e.encrypt(e);return this.#t({type:b.EncryptEnd,durationMs:Date.now()-t},e.contractAddress),n}catch(n){throw this.#t({type:b.EncryptError,error:T(n),durationMs:Date.now()-t},e.contractAddress),jt(n,`Encryption failed`)}}},Qt=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.relayer,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 d(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await d(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await d(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>d(`wallet account listener`,()=>t(e),this.#i)))}};function V(e){return St(Ct(e))}const H={ConfidentialTransfer:V(`ConfidentialTransfer(address,address,bytes32)`),Wrap:V(`Wrap(address,uint256,bytes32)`),UnwrapRequested:V(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:V(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function U(e){return A(k(e.slice(-40)))}function W(e){return e}function G(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 A(k(G(e,t).slice(-40)))}function K(e,t){return BigInt(`0x`+G(e,t))}function q(e,t){return k(G(e,t))}function en(e){return e.topics[0]!==H.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:U(e.topics[1]),to:U(e.topics[2]),encryptedAmount:W(e.topics[3])}}function J(e){return e.topics[0]!==H.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:U(e.topics[1]),roundedAmount:K(e.data,0),encryptedWrappedAmount:q(e.data,1)}}function Y(e){return e.topics[0]!==H.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:U(e.topics[1]),unwrapRequestId:W(e.topics[2]),encryptedAmount:q(e.data,0)}}function tn(e){return e.topics[0]!==H.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:U(e.topics[1]),unwrapRequestId:W(e.topics[2]),encryptedAmount:q(e.data,0),cleartextAmount:K(e.data,1)}}function nn(e){return en(e)??J(e)??Y(e)??tn(e)}function rn(e){let t=[];for(let n of e){let e=nn(n);e&&t.push(e)}return t}function an(e){for(let t of e){let e=Y(t);if(e)return e}return null}function on(e){for(let t of e){let e=J(t);if(e)return e}return null}const sn=[H.ConfidentialTransfer,H.Wrap,H.UnwrapRequested,H.UnwrapFinalized],X={DelegatedForUserDecryption:V(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:V(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Z(e){return e.topics[0]!==X.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:K(e.data,1),oldExpirationDate:K(e.data,2),newExpirationDate:K(e.data,3)}}function Q(e){return e.topics[0]!==X.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:U(e.topics[1]),delegate:U(e.topics[2]),contractAddress:$t(e.data,0),delegationCounter:K(e.data,1),oldExpirationDate:K(e.data,2)}}function cn(e){return Z(e)??Q(e)}function ln(e){let t=[];for(let n of e){let e=cn(n);e&&t.push(e)}return t}function un(e){for(let t of e){let e=Z(t);if(e)return e}return null}function dn(e){for(let t of e){let e=Q(t);if(e)return e}return null}const fn=[X.DelegatedForUserDecryption,X.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${lt(e)}`}const pn=j.union([j.pipe(D,j.transform(e=>({unwrapTxHash:e}))),j.pipe(j.object({version:j.literal(1),unwrapTxHash:D,unwrapRequestId:j.optional(D)}),j.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function mn(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 hn(e,t){return(await gn(e,t))?.unwrapTxHash??null}async function gn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=pn.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function _n(e,t){await e.delete($(t))}var vn=class extends S{#e;#t=null;#n=null;#r(e){try{return Ye(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new re(e,{cause:t})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(Se(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#o();return this.sdk.provider.readContract(m(t,A(e),this.address))}async shield(e,t){let r=await x(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),a=await this.#o(),o=A(r.address),s;try{s=await this.sdk.provider.readContract(le(a,o))}catch(e){throw e instanceof n?e:new Fe(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:T(e)})}if(s<e)throw new He(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${a})`,{requested:e,available:s,token:a});return i?this.#i(e,a,o,t):this.#a(e,o,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?A(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:Nt(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#c(e,r===`max`,n);let i=n?.to?A(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:u(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await x(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#o(),r=A(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(m(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:p(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:p(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 d(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#s(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return d(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#s(n.txHash,t,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async getPendingUnshield(){return hn(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let t=A((await x(`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 h(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:ne(this.address,t,t,i,r)})}async unwrapAll(){this.#r(`unwrapAll`);let e=A((await x(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(v(t))throw new g(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:c(this.address,e,e,t)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await Me(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let t=await this.sdk.decryption.decryptPublicValues([e]),n=t.clearValues[e];return Ze(n,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:te(this.address,e,n,t.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(ee(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(e,t,r){this.emit({type:b.UnshieldPhase1Submitted,txHash:e,operationId:t}),await d(`unshield: savePendingUnshield`,()=>mn(this.sdk.storage,this.address,e),this.sdk.logger);let i;try{i=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof n?e:new C(`Failed to get unshield receipt`,{cause:e})}let a=an(i.logs);if(!a)throw new C(`No UnwrapRequested event found in unshield receipt`);this.emit({type:b.UnshieldPhase2Started,operationId:t}),d(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let o=await this.finalizeUnwrap(a.unwrapRequestId??a.encryptedAmount);return this.emit({type:b.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),d(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(o.txHash),this.sdk.logger),await d(`unshield: clearPendingUnshield`,()=>_n(this.sdk.storage,this.address),this.sdk.logger),o}async#c(e,t,n){this.#r(`approveUnderlying`);let r=await this.#o(),i=A((await x(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),a=await this.sdk.provider.readContract(m(r,i,this.address));if(a>=e)return;a>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:p(r,this.address,0n)});let o=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:p(r,this.address,o),onSubmitted:n?.onApprovalSubmitted})}},yn=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#n=e.onEvent??function(){},this.#r=e.logger,this.#i=new Bt(e.storage,this.#r),this.#l=new Xt({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this),logger:this.#r});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new O({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#t=t,this.#e=e.registryTTL,e.signer&&(this.#c=new it({relayer:this.relayer,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage,logger:this.#r}),this.#s=new Kt({cache:this.#i,credentialService:this.#c,delegationService:this.#l,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#o=new Zt({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#a=new Qt({signer:e.signer,relayer:this.relayer,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.permits=new Lt({signer:this.signer,provider:this.provider,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.delegations=new It({signer:this.signer,provider:this.provider,delegationService:this.#l}),this.decryption=new Ft({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#s})}onWalletAccountChange(e){return this.#a.onWalletAccountChange(e)}get logger(){return this.#r}emitEvent(e,t){try{this.#n({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#r.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new O({provider:this.provider,registryAddresses:{...this.#t,...e},registryTTL:this.#e})}async encrypt(e){return this.#o.encrypt(e)}createToken(e){return new S(this,e)}createWrappedToken(e){return new vn(this,e)}dispose(){this.#a.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},bn=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 xn=new bn;export{fn as ACL_TOPICS,At as AclPausedError,X as AclTopics,Ie as BalanceCheckUnavailableError,ct as BaseSigner,Ue as ChainMismatchError,bn as ChromeSessionStorage,r as ConfigurationError,Ft as Decryption,g as DecryptionFailedError,et as DefaultRegistryAddresses,kt as DelegationContractIsSelfError,Ot as DelegationCooldownError,I as DelegationDelegateEqualsContractError,L as DelegationExpirationTooSoonError,P as DelegationExpiredError,F as DelegationExpiryUnchangedError,N as DelegationNotFoundError,R as DelegationNotPropagatedError,M as DelegationSelfNotAllowedError,It as Delegations,fe as ERC1363_INTERFACE_ID,Fe as ERC20ReadFailedError,ve as ERC7984_INTERFACE_ID,Ee as ERC7984_WRAPPER_INTERFACE_ID,h as EncryptionFailedError,dt as IndexedDBStorage,Ae as InsufficientConfidentialBalanceError,He as InsufficientERC20BalanceError,Et as InvalidTransportKeyPairError,pt as MemoryStorage,at as MutableWalletAccountStore,Dt as NoCiphertextError,w as NotEntitledError,Lt as Permits,t as RelayerRequestFailedError,_ as RpcRateLimitError,re as SignerNotConfiguredError,ke as SignerRequiredError,oe as SigningFailedError,ce as SigningRejectedError,sn as TOKEN_TOPICS,S as Token,H as Topics,C as TransactionRevertedError,Tt as TransportKeyPairExpiredError,a as WalletAccountNotReadyError,se as WalletNotConnectedError,Ge as WorkerRecycledError,We as WorkerTimeoutError,vn as WrappedToken,O as WrappersRegistry,Be as ZERO_ENCRYPTED_VALUE,n as ZamaError,e as ZamaErrorCode,yn as ZamaSDK,b as ZamaSDKEvents,m as allowanceContract,xt as anvil,p as approveContract,le as balanceOfContract,_t as bscTestnet,yt as chains,xn as chromeSessionStorage,$e as cleartext,ie as confidentialBalanceOfContract,o as confidentialTotalSupplyContract,ae as confidentialTransferContract,s as confidentialTransferFromContract,Pt as createConfig,ot as createWalletAccountStore,De as decimalsContract,cn as decodeAclEvent,ln as decodeAclEvents,en as decodeConfidentialTransfer,Z as decodeDelegatedForUserDecryption,nn as decodeOnChainEvent,rn as decodeOnChainEvents,Q as decodeRevokedDelegationForUserDecryption,tn as decodeUnwrapFinalized,Y as decodeUnwrapRequested,J as decodeWrap,Ve as delegateForUserDecryptionContract,te as finalizeUnwrapContract,un as findDelegatedForUserDecryption,dn as findRevokedDelegationForUserDecryption,an as findUnwrapRequested,on as findWrap,Te as getConfidentialTokenAddressContract,Ne as getDelegationExpiryContract,be as getTokenAddressContract,Ce as getTokenPairContract,he as getTokenPairsContract,ue as getTokenPairsLengthContract,xe as getTokenPairsSliceContract,gt as hardhat,mt as hoodi,ut as indexedDBStorage,_e as inferredTotalSupplyContract,vt as ingenTestnet,pe as isConfidentialTokenContract,we as isConfidentialTokenValidContract,me as isConfidentialWrapperContract,v as isEncryptedValueZero,Pe as isHandleDelegatedContract,i as isOperatorContract,bt as mainnet,wt as matchZamaError,ft as memoryStorage,de as nameContract,ge as rateContract,st as resolveChainRelayers,tt as resolveStorage,ze as revokeDelegationContract,ht as sepolia,f as setOperatorContract,ye as supportsInterfaceContract,Oe as symbolContract,Nt as transferAndCallContract,ee as underlyingContract,ne as unwrapContract,c as unwrapFromBalanceContract,u as wrapContract};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|