@zama-fhe/sdk 2.3.0 → 2.3.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/{activity-DTBvolDB.d.ts → activity-Bsd0ZxK7.d.ts} +2 -34
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +1 -1
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1712,33 +1712,6 @@ declare class ZamaSDK {
|
|
|
1712
1712
|
* ```
|
|
1713
1713
|
*/
|
|
1714
1714
|
createWrappersRegistry(registryAddresses?: Record<number, Address>): WrappersRegistry;
|
|
1715
|
-
/**
|
|
1716
|
-
* Pre-authorize FHE credentials for one or more contract addresses.
|
|
1717
|
-
* A single wallet signature covers all addresses, so subsequent decrypt
|
|
1718
|
-
* operations on any of these contracts reuse cached credentials.
|
|
1719
|
-
*
|
|
1720
|
-
* @param contractAddresses - Contract addresses to authorize.
|
|
1721
|
-
*
|
|
1722
|
-
* @example
|
|
1723
|
-
* ```ts
|
|
1724
|
-
* await sdk.allow("0xContractA", "0xContractB");
|
|
1725
|
-
* ```
|
|
1726
|
-
*/
|
|
1727
|
-
allow(...contractAddresses: Address[]): Promise<void>;
|
|
1728
|
-
/**
|
|
1729
|
-
* Revoke the session signature for the current signer.
|
|
1730
|
-
* The next decrypt operation will require a fresh wallet signature.
|
|
1731
|
-
*
|
|
1732
|
-
* @param contractAddresses - Optional addresses included in the
|
|
1733
|
-
* `credentials:revoked` event for observability.
|
|
1734
|
-
*
|
|
1735
|
-
* @example
|
|
1736
|
-
* ```ts
|
|
1737
|
-
* wallet.on("disconnect", () => sdk.revoke());
|
|
1738
|
-
* await sdk.revoke("0xContractA", "0xContractB");
|
|
1739
|
-
* ```
|
|
1740
|
-
*/
|
|
1741
|
-
revoke(...contractAddresses: Address[]): Promise<void>;
|
|
1742
1715
|
/**
|
|
1743
1716
|
* Revoke the session signature for the current signer without requiring
|
|
1744
1717
|
* contract addresses. Uses the tracked identity when available (safe during
|
|
@@ -1750,11 +1723,6 @@ declare class ZamaSDK {
|
|
|
1750
1723
|
* ```
|
|
1751
1724
|
*/
|
|
1752
1725
|
revokeSession(): Promise<void>;
|
|
1753
|
-
/**
|
|
1754
|
-
* Whether a session signature is currently cached for the connected wallet.
|
|
1755
|
-
* Use this to check if decrypt operations can proceed without a wallet prompt.
|
|
1756
|
-
*/
|
|
1757
|
-
isAllowed(): Promise<boolean>;
|
|
1758
1726
|
/**
|
|
1759
1727
|
* Unsubscribe from signer lifecycle events without terminating the relayer.
|
|
1760
1728
|
* Call this when the SDK instance is being replaced but the relayer is shared
|
|
@@ -1775,7 +1743,7 @@ declare class ZamaSDK {
|
|
|
1775
1743
|
* ```ts
|
|
1776
1744
|
* {
|
|
1777
1745
|
* using sdk = new ZamaSDK({ relayer, signer, storage });
|
|
1778
|
-
* await sdk.allow(cUSDT);
|
|
1746
|
+
* await sdk.credentials.allow(cUSDT);
|
|
1779
1747
|
* const balance = await sdk.createReadonlyToken(cUSDT).balanceOf();
|
|
1780
1748
|
* } // sdk.terminate() called automatically here
|
|
1781
1749
|
* ```
|
|
@@ -2088,4 +2056,4 @@ declare function applyDecryptedValues(items: readonly ActivityItem[], decryptedM
|
|
|
2088
2056
|
declare function sortByBlockNumber(items: readonly ActivityItem[]): ActivityItem[];
|
|
2089
2057
|
//#endregion
|
|
2090
2058
|
export { DelegationContractIsSelfError as $, ShieldSubmittedEvent as $t, decodeUnwrapRequested as A, CredentialsManagerConfig as At, DefaultRegistryAddresses as B, CredentialsLoadingEvent as Bt, decodeAclEvent as C, BatchDecryptOptions as Ct, decodeOnChainEvent as D, DelegatedCredentialsManager as Dt, decodeDelegatedForUserDecryption as E, ZERO_HANDLE as Et, findRevokedDelegationForUserDecryption as F, CredentialsCachedEvent as Ft, TokenConfig as G, DecryptStartEvent as Gt, WrappersRegistry as H, CredentialsRevokedEvent as Ht, findUnwrapRequested as I, CredentialsCorruptedEvent as It, BalanceErrorDetails as J, EncryptErrorEvent as Jt, matchAclRevert as K, DelegationSubmittedEvent as Kt, findWrapped as L, CredentialsCreatedEvent as Lt, decodeUnwrappedStarted as M, ApproveUnderlyingSubmittedEvent as Mt, decodeWrapped as N, BaseEvent as Nt, decodeOnChainEvents as O, DelegatedCredentialsManagerConfig as Ot, findDelegatedForUserDecryption as P, CredentialsAllowedEvent as Pt, AclPausedError as Q, SessionExpiredEvent as Qt, ZamaSDK as R, CredentialsCreatingEvent as Rt, WrappedEvent as S, BatchDecryptAsOptions as St, decodeConfidentialTransfer as T, ReadonlyTokenConfig as Tt, WrappersRegistryConfig as U, DecryptEndEvent as Ut, ListPairsOptions as V, CredentialsPersistFailedEvent as Vt, Token as W, DecryptErrorEvent as Wt, InsufficientConfidentialBalanceError as X, FinalizeUnwrapSubmittedEvent as Xt, ERC20ReadFailedError as Y, EncryptStartEvent as Yt, InsufficientERC20BalanceError as Z, RevokeDelegationSubmittedEvent as Zt, TOKEN_TOPICS as _, SigningFailedError as _t, ActivityType as a, UnshieldPhase2SubmittedEvent as an, DelegationNotFoundError as at, UnwrappedFinalizedEvent as b, ZamaErrorCode as bt, parseActivityFeed as c, ZamaSDKEventInput as cn, ConfigurationError as ct, AclEvent as d, ZamaSDKEvents as dn, KeypairExpiredError as dt, TransactionErrorEvent as en, DelegationCooldownError as et, AclTopics as f, NoCiphertextError as ft, RevokedDelegationForUserDecryptionEvent as g, EncryptionFailedError as gt, OnChainEvent as h, DecryptionFailedError as ht, ActivityLogMetadata as i, UnshieldPhase2StartedEvent as in, DelegationExpiryUnchangedError as it, decodeUnwrappedFinalized as j, ApproveSubmittedEvent as jt, decodeRevokedDelegationForUserDecryption as k, CredentialsManager as kt, sortByBlockNumber as l, ZamaSDKEventListener as ln, RelayerRequestFailedError as lt, DelegatedForUserDecryptionEvent as m, TransactionRevertedError as mt, ActivityDirection as n, TransferSubmittedEvent as nn, DelegationExpirationTooSoonError as nt, applyDecryptedValues as o, UnwrapSubmittedEvent as on, DelegationNotPropagatedError as ot, ConfidentialTransferEvent as p, ApprovalFailedError as pt, BalanceCheckUnavailableError as q, EncryptEndEvent as qt, ActivityItem as r, UnshieldPhase1SubmittedEvent as rn, DelegationExpiredError as rt, extractEncryptedHandles as s, ZamaSDKEvent as sn, DelegationSelfNotAllowedError as st, ActivityAmount as t, TransferFromSubmittedEvent as tn, DelegationDelegateEqualsContractError as tt, ACL_TOPICS as u, ZamaSDKEventType as un, InvalidKeypairError as ut, Topics as v, SigningRejectedError as vt, decodeAclEvents as w, ReadonlyToken as wt, UnwrappedStartedEvent as x, matchZamaError as xt, UnwrapRequestedEvent as y, ZamaError as yt, ZamaSDKConfig as z, CredentialsExpiredEvent as zt };
|
|
2091
|
-
//# sourceMappingURL=activity-
|
|
2059
|
+
//# sourceMappingURL=activity-Bsd0ZxK7.d.ts.map
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { A as ReadContractConfig, C as GenericSigner, D as TransactionResult, E
|
|
|
2
2
|
import { A as balanceOfContract, B as confidentialTransferContract, C as isConfidentialTokenContract, D as wrapperExistsContract, E as getWrapperContract, F as underlyingContract, G as rateContract, H as deploymentCoordinatorContract, I as wrapContract, J as totalSupplyContract, K as setFinalizeUnwrapOperatorContract, L as wrapETHContract, M as nameContract, N as symbolContract, O as allowanceContract, P as finalizeUnwrapContract, R as confidentialBalanceOfContract, S as ERC7984_WRAPPER_INTERFACE_ID, T as supportsInterfaceContract, U as isFinalizeUnwrapOperatorContract, V as confidentialTransferFromContract, W as isOperatorContract, X as unwrapFromBalanceContract, Y as unwrapContract, _ as getBatchTransferFeeContract, a as getTokenAddressContract, b as getWrapFeeContract, c as getTokenPairsLengthContract, d as delegateForUserDecryptionContract, f as getDelegationExpiryContract, g as confidentialBatchTransferContract, h as BatchTransferData, i as getConfidentialTokenAddressContract, j as decimalsContract, k as approveContract, l as getTokenPairsSliceContract, m as revokeDelegationContract, n as TokenWrapperPair, o as getTokenPairContract, p as isHandleDelegatedContract, q as setOperatorContract, r as TokenWrapperPairWithMetadata, s as getTokenPairsContract, t as PaginatedResult, u as isConfidentialTokenValidContract, v as getFeeRecipientContract, w as isConfidentialWrapperContract, x as ERC7984_INTERFACE_ID, y as getUnwrapFeeContract, z as confidentialTotalSupplyContract } from "./index-BXdXzzx4.js";
|
|
3
3
|
import { t as RelayerSDK } from "./relayer-sdk-C_4bkxxH.js";
|
|
4
4
|
import { n as MainnetConfig, r as SepoliaConfig, t as HardhatConfig } from "./relayer-utils-BcTAyZOr.js";
|
|
5
|
-
import { $ as DelegationContractIsSelfError, $t as ShieldSubmittedEvent, A as decodeUnwrapRequested, At as CredentialsManagerConfig, B as DefaultRegistryAddresses, Bt as CredentialsLoadingEvent, C as decodeAclEvent, Ct as BatchDecryptOptions, D as decodeOnChainEvent, Dt as DelegatedCredentialsManager, E as decodeDelegatedForUserDecryption, Et as ZERO_HANDLE, F as findRevokedDelegationForUserDecryption, Ft as CredentialsCachedEvent, G as TokenConfig, Gt as DecryptStartEvent, H as WrappersRegistry, Ht as CredentialsRevokedEvent, I as findUnwrapRequested, It as CredentialsCorruptedEvent, J as BalanceErrorDetails, Jt as EncryptErrorEvent, K as matchAclRevert, Kt as DelegationSubmittedEvent, L as findWrapped, Lt as CredentialsCreatedEvent, M as decodeUnwrappedStarted, Mt as ApproveUnderlyingSubmittedEvent, N as decodeWrapped, Nt as BaseEvent, O as decodeOnChainEvents, Ot as DelegatedCredentialsManagerConfig, P as findDelegatedForUserDecryption, Pt as CredentialsAllowedEvent, Q as AclPausedError, Qt as SessionExpiredEvent, R as ZamaSDK, Rt as CredentialsCreatingEvent, S as WrappedEvent, St as BatchDecryptAsOptions, T as decodeConfidentialTransfer, Tt as ReadonlyTokenConfig, U as WrappersRegistryConfig, Ut as DecryptEndEvent, V as ListPairsOptions, Vt as CredentialsPersistFailedEvent, W as Token, Wt as DecryptErrorEvent, X as InsufficientConfidentialBalanceError, Xt as FinalizeUnwrapSubmittedEvent, Y as ERC20ReadFailedError, Yt as EncryptStartEvent, Z as InsufficientERC20BalanceError, Zt as RevokeDelegationSubmittedEvent, _ as TOKEN_TOPICS, _t as SigningFailedError, a as ActivityType, an as UnshieldPhase2SubmittedEvent, at as DelegationNotFoundError, b as UnwrappedFinalizedEvent, bt as ZamaErrorCode, c as parseActivityFeed, cn as ZamaSDKEventInput, ct as ConfigurationError, d as AclEvent, dn as ZamaSDKEvents, dt as KeypairExpiredError, en as TransactionErrorEvent, et as DelegationCooldownError, f as AclTopics, ft as NoCiphertextError, g as RevokedDelegationForUserDecryptionEvent, gt as EncryptionFailedError, h as OnChainEvent, ht as DecryptionFailedError, i as ActivityLogMetadata, in as UnshieldPhase2StartedEvent, it as DelegationExpiryUnchangedError, j as decodeUnwrappedFinalized, jt as ApproveSubmittedEvent, k as decodeRevokedDelegationForUserDecryption, kt as CredentialsManager, l as sortByBlockNumber, ln as ZamaSDKEventListener, lt as RelayerRequestFailedError, m as DelegatedForUserDecryptionEvent, mt as TransactionRevertedError, n as ActivityDirection, nn as TransferSubmittedEvent, nt as DelegationExpirationTooSoonError, o as applyDecryptedValues, on as UnwrapSubmittedEvent, ot as DelegationNotPropagatedError, p as ConfidentialTransferEvent, pt as ApprovalFailedError, q as BalanceCheckUnavailableError, qt as EncryptEndEvent, r as ActivityItem, rn as UnshieldPhase1SubmittedEvent, rt as DelegationExpiredError, s as extractEncryptedHandles, sn as ZamaSDKEvent, st as DelegationSelfNotAllowedError, t as ActivityAmount, tn as TransferFromSubmittedEvent, tt as DelegationDelegateEqualsContractError, u as ACL_TOPICS, un as ZamaSDKEventType, ut as InvalidKeypairError, v as Topics, vt as SigningRejectedError, w as decodeAclEvents, wt as ReadonlyToken, x as UnwrappedStartedEvent, xt as matchZamaError, y as UnwrapRequestedEvent, yt as ZamaError, z as ZamaSDKConfig, zt as CredentialsExpiredEvent } from "./activity-
|
|
5
|
+
import { $ as DelegationContractIsSelfError, $t as ShieldSubmittedEvent, A as decodeUnwrapRequested, At as CredentialsManagerConfig, B as DefaultRegistryAddresses, Bt as CredentialsLoadingEvent, C as decodeAclEvent, Ct as BatchDecryptOptions, D as decodeOnChainEvent, Dt as DelegatedCredentialsManager, E as decodeDelegatedForUserDecryption, Et as ZERO_HANDLE, F as findRevokedDelegationForUserDecryption, Ft as CredentialsCachedEvent, G as TokenConfig, Gt as DecryptStartEvent, H as WrappersRegistry, Ht as CredentialsRevokedEvent, I as findUnwrapRequested, It as CredentialsCorruptedEvent, J as BalanceErrorDetails, Jt as EncryptErrorEvent, K as matchAclRevert, Kt as DelegationSubmittedEvent, L as findWrapped, Lt as CredentialsCreatedEvent, M as decodeUnwrappedStarted, Mt as ApproveUnderlyingSubmittedEvent, N as decodeWrapped, Nt as BaseEvent, O as decodeOnChainEvents, Ot as DelegatedCredentialsManagerConfig, P as findDelegatedForUserDecryption, Pt as CredentialsAllowedEvent, Q as AclPausedError, Qt as SessionExpiredEvent, R as ZamaSDK, Rt as CredentialsCreatingEvent, S as WrappedEvent, St as BatchDecryptAsOptions, T as decodeConfidentialTransfer, Tt as ReadonlyTokenConfig, U as WrappersRegistryConfig, Ut as DecryptEndEvent, V as ListPairsOptions, Vt as CredentialsPersistFailedEvent, W as Token, Wt as DecryptErrorEvent, X as InsufficientConfidentialBalanceError, Xt as FinalizeUnwrapSubmittedEvent, Y as ERC20ReadFailedError, Yt as EncryptStartEvent, Z as InsufficientERC20BalanceError, Zt as RevokeDelegationSubmittedEvent, _ as TOKEN_TOPICS, _t as SigningFailedError, a as ActivityType, an as UnshieldPhase2SubmittedEvent, at as DelegationNotFoundError, b as UnwrappedFinalizedEvent, bt as ZamaErrorCode, c as parseActivityFeed, cn as ZamaSDKEventInput, ct as ConfigurationError, d as AclEvent, dn as ZamaSDKEvents, dt as KeypairExpiredError, en as TransactionErrorEvent, et as DelegationCooldownError, f as AclTopics, ft as NoCiphertextError, g as RevokedDelegationForUserDecryptionEvent, gt as EncryptionFailedError, h as OnChainEvent, ht as DecryptionFailedError, i as ActivityLogMetadata, in as UnshieldPhase2StartedEvent, it as DelegationExpiryUnchangedError, j as decodeUnwrappedFinalized, jt as ApproveSubmittedEvent, k as decodeRevokedDelegationForUserDecryption, kt as CredentialsManager, l as sortByBlockNumber, ln as ZamaSDKEventListener, lt as RelayerRequestFailedError, m as DelegatedForUserDecryptionEvent, mt as TransactionRevertedError, n as ActivityDirection, nn as TransferSubmittedEvent, nt as DelegationExpirationTooSoonError, o as applyDecryptedValues, on as UnwrapSubmittedEvent, ot as DelegationNotPropagatedError, p as ConfidentialTransferEvent, pt as ApprovalFailedError, q as BalanceCheckUnavailableError, qt as EncryptEndEvent, r as ActivityItem, rn as UnshieldPhase1SubmittedEvent, rt as DelegationExpiredError, s as extractEncryptedHandles, sn as ZamaSDKEvent, st as DelegationSelfNotAllowedError, t as ActivityAmount, tn as TransferFromSubmittedEvent, tt as DelegationDelegateEqualsContractError, u as ACL_TOPICS, un as ZamaSDKEventType, ut as InvalidKeypairError, v as Topics, vt as SigningRejectedError, w as decodeAclEvents, wt as ReadonlyToken, x as UnwrappedStartedEvent, xt as matchZamaError, y as UnwrapRequestedEvent, yt as ZamaError, z as ZamaSDKConfig, zt as CredentialsExpiredEvent } from "./activity-Bsd0ZxK7.js";
|
|
6
6
|
import { Address, Address as Address$1, Hex, Hex as Hex$1 } from "viem";
|
|
7
7
|
import { FheTypeName, FhevmInstanceConfig, InputProofBytesType, InputProofBytesType as InputProofBytesType$1, KeypairType, KeypairType as KeypairType$1, KmsDelegatedUserDecryptEIP712Type, KmsDelegatedUserDecryptEIP712Type as KmsDelegatedUserDecryptEIP712Type$1, ZKProofLike, ZKProofLike as ZKProofLike$1 } from "@zama-fhe/relayer-sdk/bundle";
|
|
8
8
|
|
package/dist/esm/index.js
CHANGED
|
@@ -511,5 +511,5 @@ import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{$ as a,A as o
|
|
|
511
511
|
};
|
|
512
512
|
//#endregion
|
|
513
513
|
})();
|
|
514
|
-
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},Dt=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},P[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new J(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},P[e],this.#l.transports[e]);this.#a=new ze({storage:this.#o,chainId:e,relayerUrl:t.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new Et(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:We(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return M(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return M(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return M(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let e=await this.#l.getChainId(),t=Object.assign({},P[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},Ot=class e extends T{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?B(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(ct(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=B(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:S.EncryptStart}),{handles:c,inputProof:l}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-u}),Y(()=>a?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-u}),e instanceof r?e:new D(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ht(this.address,s,c[0],l));return this.emit({type:S.TransferSubmitted,txHash:e}),Y(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new H(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=B(e),o=B(t),s,c,l=Date.now();try{this.emit({type:S.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-l}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-l}),e instanceof r?e:new D(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract($e(this.address,a,o,s[0],c));return this.emit({type:S.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new H(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=B(e);try{let e=await this.signer.writeContract(Je(this.address,n,t));return this.emit({type:S.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approve`,error:A(e)}),e instanceof r?e:new V(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=B(e),r=t?B(t):await this.signer.getAddress();return this.signer.readContract(Ke(this.address,r,n))}async shield(t,n){let i=await this.#n();if(i===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let a;try{let e=await this.signer.getAddress();a=await this.signer.readContract(ce(i,e))}catch(e){throw e instanceof r?e:new xt(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:A(e)})}if(a<t)throw new W(`Insufficient ERC-20 balance: requested ${t}, available ${a} (token: ${i})`,{requested:t,available:a,token:i});let o=n?.approvalStrategy??`exact`;o!==`skip`&&await this.#o(t,o===`max`,n);try{let e=n?.to?B(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(it(this.wrapper,e,t));return this.emit({type:S.ShieldSubmitted,txHash:r}),Y(()=>n?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new H(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(rt(this.wrapper,n,e,t??e));return this.emit({type:S.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shieldETH`,error:A(e)}),e instanceof r?e:new H(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:S.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-a}),e instanceof r?e:new D(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Ye(this.address,t,t,n[0],i));return this.emit({type:S.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new O(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(ot(this.address,e,e,t));return this.emit({type:S.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Y(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:S.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:S.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=bt(r.abiEncodedClearValues)}catch(e){throw new O(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(e){throw this.emit({type:S.DecryptError,error:A(e),durationMs:Date.now()-i}),e instanceof r?e:new O(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(lt(this.wrapper,e,t,n));return this.emit({type:S.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`finalizeUnwrap`,error:A(e)}),e instanceof r?e:new H(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(E(t,e,this.wrapper))>0n&&await this.signer.writeContract(s(t,this.wrapper,0n))}let e=await this.signer.writeContract(s(t,this.wrapper,n));return this.emit({type:S.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approveUnderlying`,error:A(e)}),e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);let n=B(e),i=await this.signer.getAddress();if(n===B(i))throw new w(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new x(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):o;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new _(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(Se(a,n,this.address,s));return this.emit({type:S.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`delegateDecryption`,error:A(e)}),e instanceof r?e:q(e)||new H(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=B(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new a(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(g(i,t,this.address));return this.emit({type:S.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`revokeDelegation`,error:A(e)}),e instanceof r?e:q(e)||new H(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new H(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t,n;try{t=await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t)}catch(e){throw e instanceof r?e:new G(`Could not read confidential balance handle (token: ${this.address})`,{cause:A(e)})}if(this.isZeroHandle(n))throw new U(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await u({storage:this.storage,tokenAddress:this.address,owner:t,handle:n});if(i!==null){if(i<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${i} (token: ${this.address})`,{requested:e,available:i,token:this.address});return}let a;try{a=await this.isAllowed()}catch(e){throw e instanceof r?e:new G(`Could not check credential status for balance validation (token: ${this.address})`,{cause:e})}if(!a)throw new G(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let o;try{o=await this.decryptBalance(n,t)}catch(e){throw e instanceof r?e:new G(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:e})}if(o<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${o} (token: ${this.address})`,{requested:e,available:o,token:this.address})}async#a(e,t,n){this.emit({type:S.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new H(`Failed to get unshield receipt`,{cause:e})}let a=v(i.logs);if(!a)throw new H(`No UnwrapRequested event found in unshield receipt`);this.emit({type:S.UnshieldPhase2Started,operationId:t}),Y(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:S.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),Y(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(E(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(s(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(s(i,this.wrapper,r));this.emit({type:S.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const kt={[N.chainId]:N.registryAddress,[j.chainId]:j.registryAddress,[yt.chainId]:yt.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},kt,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return B(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(F(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(L(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?X:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(y(e.tokenAddress)),this.signer.readContract(f(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(se(e.tokenAddress)),this.signer.readContract(y(e.confidentialTokenAddress)),this.signer.readContract(f(e.confidentialTokenAddress)),this.signer.readContract(p(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(I(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(at(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(F(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(L(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(ut(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,B(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(I(t,B(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(R(t,B(e)))}},At=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new Ue,this.#t=e.onEvent??function(){},this.registry=new Z({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new h(t),this.delegatedCredentials=new l(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:S.TransactionError,operation:e,error:A(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=B(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await h.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new T({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),onEvent:this.#t})}createToken(e,t){return new Ot({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),wrapper:t?B(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Z({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await h.computeStoreKey(e,t);await this.credentials.revokeByKey(n)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function jt(e,t,n){await e.set(Q(t),n)}async function Mt(e,t){return e.get(Q(t))}async function Nt(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Pt=new $;export{de as ACL_TOPICS,te as AclPausedError,De as AclTopics,V as ApprovalFailedError,G as BalanceCheckUnavailableError,$ as ChromeSessionStorage,i as ConfigurationError,h as CredentialsManager,O as DecryptionFailedError,kt as DefaultRegistryAddresses,l as DelegatedCredentialsManager,C as DelegationContractIsSelfError,m as DelegationCooldownError,x as DelegationDelegateEqualsContractError,b as DelegationExpirationTooSoonError,le as DelegationExpiredError,_ as DelegationExpiryUnchangedError,a as DelegationNotFoundError,ge as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,xt as ERC20ReadFailedError,et as ERC7984_INTERFACE_ID,st as ERC7984_WRAPPER_INTERFACE_ID,D as EncryptionFailedError,Ge as HardhatConfig,J as IndexedDBStorage,U as InsufficientConfidentialBalanceError,W as InsufficientERC20BalanceError,Ee as InvalidKeypairError,je as KeypairExpiredError,N as MainnetConfig,Ue as MemoryStorage,xe as NoCiphertextError,T as ReadonlyToken,n as RelayerRequestFailedError,Dt as RelayerWeb,j as SepoliaConfig,fe as SigningFailedError,Oe as SigningRejectedError,Me as TOKEN_TOPICS,Ot as Token,me as Topics,H as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,At as ZamaSDK,S as ZamaSDKEvents,E as allowanceContract,Ne as applyDecryptedValues,s as approveContract,ce as balanceOfContract,Pt as chromeSessionStorage,Nt as clearPendingUnshield,Qe as confidentialBalanceOfContract,vt as confidentialBatchTransferContract,ft as confidentialTotalSupplyContract,ht as confidentialTransferContract,$e as confidentialTransferFromContract,p as decimalsContract,Ce as decodeAclEvent,Pe as decodeAclEvents,he as decodeConfidentialTransfer,_e as decodeDelegatedForUserDecryption,ke as decodeOnChainEvent,we as decodeOnChainEvents,ye as decodeRevokedDelegationForUserDecryption,ve as decodeUnwrapRequested,ue as decodeUnwrappedFinalized,Fe as decodeUnwrappedStarted,Le as decodeWrapped,Se as delegateForUserDecryptionContract,mt as deploymentCoordinatorContract,Te as extractEncryptedHandles,lt as finalizeUnwrapContract,pe as findDelegatedForUserDecryption,Ie as findRevokedDelegationForUserDecryption,v as findUnwrapRequested,c as findWrapped,d as getBatchTransferFeeContract,z as getConfidentialTokenAddressContract,re as getDelegationExpiryContract,ee as getFeeRecipientContract,I as getTokenAddressContract,ut as getTokenPairContract,at as getTokenPairsContract,F as getTokenPairsLengthContract,L as getTokenPairsSliceContract,ne as getUnwrapFeeContract,ae as getWrapFeeContract,gt as getWrapperContract,Ct as indexedDBStorage,dt as isConfidentialTokenContract,R as isConfidentialTokenValidContract,tt as isConfidentialWrapperContract,Xe as isFinalizeUnwrapOperatorContract,ie as isHandleDelegatedContract,Ke as isOperatorContract,Mt as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,He as memoryStorage,y as nameContract,Ae as parseActivityFeed,pt as rateContract,g as revokeDelegationContract,jt as savePendingUnshield,Ze as setFinalizeUnwrapOperatorContract,Je as setOperatorContract,be as sortByBlockNumber,nt as supportsInterfaceContract,f as symbolContract,qe as totalSupplyContract,ct as underlyingContract,Ye as unwrapContract,ot as unwrapFromBalanceContract,it as wrapContract,rt as wrapETHContract,_t as wrapperExistsContract};
|
|
514
|
+
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},Dt=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},P[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new J(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},P[e],this.#l.transports[e]);this.#a=new ze({storage:this.#o,chainId:e,relayerUrl:t.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new Et(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:We(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return M(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return M(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return M(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let e=await this.#l.getChainId(),t=Object.assign({},P[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},Ot=class e extends T{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?B(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(ct(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=B(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:S.EncryptStart}),{handles:c,inputProof:l}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-u}),Y(()=>a?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-u}),e instanceof r?e:new D(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ht(this.address,s,c[0],l));return this.emit({type:S.TransferSubmitted,txHash:e}),Y(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new H(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=B(e),o=B(t),s,c,l=Date.now();try{this.emit({type:S.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-l}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-l}),e instanceof r?e:new D(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract($e(this.address,a,o,s[0],c));return this.emit({type:S.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new H(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=B(e);try{let e=await this.signer.writeContract(Je(this.address,n,t));return this.emit({type:S.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approve`,error:A(e)}),e instanceof r?e:new V(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=B(e),r=t?B(t):await this.signer.getAddress();return this.signer.readContract(Ke(this.address,r,n))}async shield(t,n){let i=await this.#n();if(i===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let a;try{let e=await this.signer.getAddress();a=await this.signer.readContract(ce(i,e))}catch(e){throw e instanceof r?e:new xt(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:A(e)})}if(a<t)throw new W(`Insufficient ERC-20 balance: requested ${t}, available ${a} (token: ${i})`,{requested:t,available:a,token:i});let o=n?.approvalStrategy??`exact`;o!==`skip`&&await this.#o(t,o===`max`,n);try{let e=n?.to?B(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(it(this.wrapper,e,t));return this.emit({type:S.ShieldSubmitted,txHash:r}),Y(()=>n?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new H(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(rt(this.wrapper,n,e,t??e));return this.emit({type:S.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shieldETH`,error:A(e)}),e instanceof r?e:new H(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:S.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-a}),e instanceof r?e:new D(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Ye(this.address,t,t,n[0],i));return this.emit({type:S.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new O(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(ot(this.address,e,e,t));return this.emit({type:S.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Y(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:S.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:S.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=bt(r.abiEncodedClearValues)}catch(e){throw new O(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(e){throw this.emit({type:S.DecryptError,error:A(e),durationMs:Date.now()-i}),e instanceof r?e:new O(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(lt(this.wrapper,e,t,n));return this.emit({type:S.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`finalizeUnwrap`,error:A(e)}),e instanceof r?e:new H(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(E(t,e,this.wrapper))>0n&&await this.signer.writeContract(s(t,this.wrapper,0n))}let e=await this.signer.writeContract(s(t,this.wrapper,n));return this.emit({type:S.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approveUnderlying`,error:A(e)}),e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);let n=B(e),i=await this.signer.getAddress();if(n===B(i))throw new w(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new x(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):o;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new _(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(Se(a,n,this.address,s));return this.emit({type:S.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`delegateDecryption`,error:A(e)}),e instanceof r?e:q(e)||new H(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=B(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new a(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(g(i,t,this.address));return this.emit({type:S.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`revokeDelegation`,error:A(e)}),e instanceof r?e:q(e)||new H(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new H(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t,n;try{t=await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t)}catch(e){throw e instanceof r?e:new G(`Could not read confidential balance handle (token: ${this.address})`,{cause:A(e)})}if(this.isZeroHandle(n))throw new U(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await u({storage:this.storage,tokenAddress:this.address,owner:t,handle:n});if(i!==null){if(i<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${i} (token: ${this.address})`,{requested:e,available:i,token:this.address});return}let a;try{a=await this.isAllowed()}catch(e){throw e instanceof r?e:new G(`Could not check credential status for balance validation (token: ${this.address})`,{cause:e})}if(!a)throw new G(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let o;try{o=await this.decryptBalance(n,t)}catch(e){throw e instanceof r?e:new G(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:e})}if(o<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${o} (token: ${this.address})`,{requested:e,available:o,token:this.address})}async#a(e,t,n){this.emit({type:S.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new H(`Failed to get unshield receipt`,{cause:e})}let a=v(i.logs);if(!a)throw new H(`No UnwrapRequested event found in unshield receipt`);this.emit({type:S.UnshieldPhase2Started,operationId:t}),Y(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:S.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),Y(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(E(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(s(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(s(i,this.wrapper,r));this.emit({type:S.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const kt={[N.chainId]:N.registryAddress,[j.chainId]:j.registryAddress,[yt.chainId]:yt.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},kt,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return B(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(F(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(L(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?X:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(y(e.tokenAddress)),this.signer.readContract(f(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(se(e.tokenAddress)),this.signer.readContract(y(e.confidentialTokenAddress)),this.signer.readContract(f(e.confidentialTokenAddress)),this.signer.readContract(p(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(I(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(at(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(F(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(L(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(ut(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,B(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(I(t,B(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(R(t,B(e)))}},At=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new Ue,this.#t=e.onEvent??function(){},this.registry=new Z({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new h(t),this.delegatedCredentials=new l(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:S.TransactionError,operation:e,error:A(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=B(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await h.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new T({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),onEvent:this.#t})}createToken(e,t){return new Ot({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),wrapper:t?B(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Z({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await h.computeStoreKey(e,t);await this.credentials.revokeByKey(n)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function jt(e,t,n){await e.set(Q(t),n)}async function Mt(e,t){return e.get(Q(t))}async function Nt(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Pt=new $;export{de as ACL_TOPICS,te as AclPausedError,De as AclTopics,V as ApprovalFailedError,G as BalanceCheckUnavailableError,$ as ChromeSessionStorage,i as ConfigurationError,h as CredentialsManager,O as DecryptionFailedError,kt as DefaultRegistryAddresses,l as DelegatedCredentialsManager,C as DelegationContractIsSelfError,m as DelegationCooldownError,x as DelegationDelegateEqualsContractError,b as DelegationExpirationTooSoonError,le as DelegationExpiredError,_ as DelegationExpiryUnchangedError,a as DelegationNotFoundError,ge as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,xt as ERC20ReadFailedError,et as ERC7984_INTERFACE_ID,st as ERC7984_WRAPPER_INTERFACE_ID,D as EncryptionFailedError,Ge as HardhatConfig,J as IndexedDBStorage,U as InsufficientConfidentialBalanceError,W as InsufficientERC20BalanceError,Ee as InvalidKeypairError,je as KeypairExpiredError,N as MainnetConfig,Ue as MemoryStorage,xe as NoCiphertextError,T as ReadonlyToken,n as RelayerRequestFailedError,Dt as RelayerWeb,j as SepoliaConfig,fe as SigningFailedError,Oe as SigningRejectedError,Me as TOKEN_TOPICS,Ot as Token,me as Topics,H as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,At as ZamaSDK,S as ZamaSDKEvents,E as allowanceContract,Ne as applyDecryptedValues,s as approveContract,ce as balanceOfContract,Pt as chromeSessionStorage,Nt as clearPendingUnshield,Qe as confidentialBalanceOfContract,vt as confidentialBatchTransferContract,ft as confidentialTotalSupplyContract,ht as confidentialTransferContract,$e as confidentialTransferFromContract,p as decimalsContract,Ce as decodeAclEvent,Pe as decodeAclEvents,he as decodeConfidentialTransfer,_e as decodeDelegatedForUserDecryption,ke as decodeOnChainEvent,we as decodeOnChainEvents,ye as decodeRevokedDelegationForUserDecryption,ve as decodeUnwrapRequested,ue as decodeUnwrappedFinalized,Fe as decodeUnwrappedStarted,Le as decodeWrapped,Se as delegateForUserDecryptionContract,mt as deploymentCoordinatorContract,Te as extractEncryptedHandles,lt as finalizeUnwrapContract,pe as findDelegatedForUserDecryption,Ie as findRevokedDelegationForUserDecryption,v as findUnwrapRequested,c as findWrapped,d as getBatchTransferFeeContract,z as getConfidentialTokenAddressContract,re as getDelegationExpiryContract,ee as getFeeRecipientContract,I as getTokenAddressContract,ut as getTokenPairContract,at as getTokenPairsContract,F as getTokenPairsLengthContract,L as getTokenPairsSliceContract,ne as getUnwrapFeeContract,ae as getWrapFeeContract,gt as getWrapperContract,Ct as indexedDBStorage,dt as isConfidentialTokenContract,R as isConfidentialTokenValidContract,tt as isConfidentialWrapperContract,Xe as isFinalizeUnwrapOperatorContract,ie as isHandleDelegatedContract,Ke as isOperatorContract,Mt as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,He as memoryStorage,y as nameContract,Ae as parseActivityFeed,pt as rateContract,g as revokeDelegationContract,jt as savePendingUnshield,Ze as setFinalizeUnwrapOperatorContract,Je as setOperatorContract,be as sortByBlockNumber,nt as supportsInterfaceContract,f as symbolContract,qe as totalSupplyContract,ct as underlyingContract,Ye as unwrapContract,ot as unwrapFromBalanceContract,it as wrapContract,rt as wrapETHContract,_t as wrapperExistsContract};
|
|
515
515
|
//# sourceMappingURL=index.js.map
|