@zama-fhe/sdk 3.8.0 → 3.9.0-beta.10
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/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/chains/index.cjs +1 -1
- package/dist/cjs/configs.cjs +2 -0
- package/dist/cjs/configs.cjs.map +1 -0
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/fhevm-relayer.cjs +2 -2
- package/dist/cjs/fhevm-relayer.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/log-decoding.cjs +1 -1
- package/dist/cjs/log-decoding.cjs.map +1 -1
- package/dist/cjs/node/index.cjs +1 -1
- package/dist/cjs/node/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/telemetry.cjs +1 -1
- package/dist/cjs/telemetry.cjs.map +1 -1
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/cjs/vaults/index.cjs +1 -1
- package/dist/cjs/vaults/index.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/esm/{alignment-o-YIndFR.js → alignment-D1cVCzw8.js} +2 -2
- package/dist/esm/{alignment-o-YIndFR.js.map → alignment-D1cVCzw8.js.map} +1 -1
- package/dist/esm/{base-signer-nenGJU9U.d.ts → base-signer-DuHym9wR.d.ts} +1 -1
- package/dist/esm/base-signer-eT-iTgjT.js +2 -0
- package/dist/esm/base-signer-eT-iTgjT.js.map +1 -0
- package/dist/esm/chains/index.d.ts +2 -2
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/cleartext/index.d.ts +2 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-3QqBsH3R.js → cleartext-BhD0SJFe.js} +2 -2
- package/dist/esm/{cleartext-3QqBsH3R.js.map → cleartext-BhD0SJFe.js.map} +1 -1
- package/dist/esm/{cleartext-BLMLdKFh.d.ts → cleartext-DydTYxOw.d.ts} +1 -1
- package/dist/esm/configs-C65OaOKz.js +2 -0
- package/dist/esm/configs-C65OaOKz.js.map +1 -0
- package/dist/esm/{decryption-Cp8calaa.d.ts → decryption-DVfeQvb9.d.ts} +63 -24
- package/dist/esm/{encrypt-worker-client-CkEIA0Tp.d.ts → encrypt-worker-client-BJJbrdZB.d.ts} +1 -1
- package/dist/esm/encrypt.worker.js +45 -45
- package/dist/esm/{encryption-BT886Jlj.js → encryption-QHaWnnx-.js} +2 -2
- package/dist/esm/{encryption-BT886Jlj.js.map → encryption-QHaWnnx-.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +6 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{fatal-batch-BYeHrf0V.js → fatal-batch-CI0ESPnd.js} +2 -2
- package/dist/esm/{fatal-batch-BYeHrf0V.js.map → fatal-batch-CI0ESPnd.js.map} +1 -1
- package/dist/esm/fhevm-relayer-DDTrSUpu.js +8 -0
- package/dist/esm/fhevm-relayer-DDTrSUpu.js.map +1 -0
- package/dist/esm/{index-ClNBSbRy.d.ts → index-8R-9woWN.d.ts} +3 -3
- package/dist/esm/{index-CI6f4jxt.d.ts → index-BL2fvV8e.d.ts} +6 -6
- package/dist/esm/{index-ZTcD9b_z.d.ts → index-O1xwLjWX.d.ts} +63 -1
- package/dist/esm/index.d.ts +9 -9
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/internal/index.d.ts +4 -4
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/log-decoding-Cl4zZCe8.js +2 -0
- package/dist/esm/log-decoding-Cl4zZCe8.js.map +1 -0
- package/dist/esm/node/index.d.ts +4 -4
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +6 -6
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-Cki3j_Ba.js +2 -0
- package/dist/esm/relayer-Cki3j_Ba.js.map +1 -0
- package/dist/esm/{signing-CVEOw21I.js → signing-DX-xyved.js} +2 -2
- package/dist/esm/{signing-CVEOw21I.js.map → signing-DX-xyved.js.map} +1 -1
- package/dist/esm/telemetry-CbuDJ12K.js +2 -0
- package/dist/esm/telemetry-CbuDJ12K.js.map +1 -0
- package/dist/esm/token-DnriE-3y.js +2 -0
- package/dist/esm/token-DnriE-3y.js.map +1 -0
- package/dist/esm/{types-D253qkvB.d.ts → types-D1kIafm6.d.ts} +2 -2
- package/dist/esm/{types-Ubeo72FV.d.ts → types-NmMfCGuC.d.ts} +7 -1
- package/dist/esm/{types-DH06Ap0n.d.ts → types-gKZ_zPFn.d.ts} +2 -2
- package/dist/esm/{validation-CZfDLOUh.js → validation-BLmG7UVk.js} +2 -2
- package/dist/esm/{validation-CZfDLOUh.js.map → validation-BLmG7UVk.js.map} +1 -1
- package/dist/esm/vaults/index.d.ts +53 -18
- package/dist/esm/vaults/index.js +1 -1
- package/dist/esm/vaults/index.js.map +1 -1
- package/dist/esm/viem/index.d.ts +6 -4
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +2 -2
- package/dist/esm/web/index.js +1 -1
- package/package.json +2 -2
- package/dist/cjs/chains.cjs +0 -2
- package/dist/cjs/chains.cjs.map +0 -1
- package/dist/esm/base-signer-D8-tyO9l.js +0 -2
- package/dist/esm/base-signer-D8-tyO9l.js.map +0 -1
- package/dist/esm/chains-BQXSxIwU.js +0 -2
- package/dist/esm/chains-BQXSxIwU.js.map +0 -1
- package/dist/esm/fhevm-relayer-D0Uio0ls.js +0 -8
- package/dist/esm/fhevm-relayer-D0Uio0ls.js.map +0 -1
- package/dist/esm/log-decoding-ZthqwHOv.js +0 -2
- package/dist/esm/log-decoding-ZthqwHOv.js.map +0 -1
- package/dist/esm/relayer-nWfQAlo7.js +0 -2
- package/dist/esm/relayer-nWfQAlo7.js.map +0 -1
- package/dist/esm/telemetry-r8qLB6-r.js +0 -2
- package/dist/esm/telemetry-r8qLB6-r.js.map +0 -1
- package/dist/esm/token-AXsOIUDB.js +0 -2
- package/dist/esm/token-AXsOIUDB.js.map +0 -1
package/dist/esm/viem/index.d.ts
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @packageDocumentation
|
|
6
6
|
*/
|
|
7
|
-
import { t as ZamaConfigViem } from "../types-
|
|
8
|
-
import { $ as RevokeDelegationSubmittedEvent, $t as RawLog, A as WalletAccountListener, B as WriteFunctionName, D as GenericSigner, F as ReadContractConfig, G as DecryptStartEvent, H as BaseEvent, I as ReadContractReturnType, J as EncryptErrorEvent, K as DelegationSubmittedEvent, L as ReadFunctionName, M as ContractAbi, N as MulticallReturnType, O as WalletAccount, P as ReadContractArgs, Q as PermitOperation, R as WriteContractArgs, U as DecryptEndEvent, V as ApproveUnderlyingSubmittedEvent, W as DecryptErrorEvent, X as FinalizeUnwrapSubmittedEvent, Y as EncryptStartEvent, Z as PermitErrorEvent, a as ZamaConfigBase, an as EIP712TypedData, at as TransferSubmittedEvent, c as GenericStorage, ct as UnshieldPhase2SubmittedEvent, en as TransactionReceipt, et as SetOperatorSubmittedEvent, ft as WrapSubmittedEvent, gt as ZamaSDKEvents, ht as ZamaSDKEventType, i as ZamaConfig, it as TransferFromSubmittedEvent, j as WalletAccountStore, k as WalletAccountChange, l as GenericProvider, ln as EncryptedValue, lt as UnwrapSubmittedEvent, mt as ZamaSDKEventListener, n as RelayerConfig, nn as ClearValue, nt as TransactionErrorEvent, ot as UnshieldPhase1SubmittedEvent, pn as FhevmRuntimeConfig, pt as ZamaSDKEvent, q as EncryptEndEvent, rt as TransactionOperation, s as GenericLogger, st as UnshieldPhase2StartedEvent, tt as ShieldSubmittedEvent, yt as ShieldPath, z as WriteContractConfig } from "../types-
|
|
9
|
-
import { d as AtLeastOneChain, f as FheChain, p as FheChainAuth } from "../index-
|
|
10
|
-
import { n as MutableWalletAccountStore, t as BaseSigner } from "../base-signer-
|
|
7
|
+
import { t as ZamaConfigViem } from "../types-D1kIafm6.js";
|
|
8
|
+
import { $ as RevokeDelegationSubmittedEvent, $t as RawLog, A as WalletAccountListener, B as WriteFunctionName, D as GenericSigner, F as ReadContractConfig, G as DecryptStartEvent, H as BaseEvent, I as ReadContractReturnType, J as EncryptErrorEvent, K as DelegationSubmittedEvent, L as ReadFunctionName, M as ContractAbi, N as MulticallReturnType, O as WalletAccount, P as ReadContractArgs, Q as PermitOperation, R as WriteContractArgs, U as DecryptEndEvent, V as ApproveUnderlyingSubmittedEvent, W as DecryptErrorEvent, X as FinalizeUnwrapSubmittedEvent, Y as EncryptStartEvent, Z as PermitErrorEvent, a as ZamaConfigBase, an as EIP712TypedData, at as TransferSubmittedEvent, c as GenericStorage, ct as UnshieldPhase2SubmittedEvent, en as TransactionReceipt, et as SetOperatorSubmittedEvent, ft as WrapSubmittedEvent, gt as ZamaSDKEvents, ht as ZamaSDKEventType, i as ZamaConfig, it as TransferFromSubmittedEvent, j as WalletAccountStore, k as WalletAccountChange, l as GenericProvider, ln as EncryptedValue, lt as UnwrapSubmittedEvent, mt as ZamaSDKEventListener, n as RelayerConfig, nn as ClearValue, nt as TransactionErrorEvent, ot as UnshieldPhase1SubmittedEvent, pn as FhevmRuntimeConfig, pt as ZamaSDKEvent, q as EncryptEndEvent, rt as TransactionOperation, s as GenericLogger, st as UnshieldPhase2StartedEvent, tt as ShieldSubmittedEvent, yt as ShieldPath, z as WriteContractConfig } from "../types-NmMfCGuC.js";
|
|
9
|
+
import { d as AtLeastOneChain, f as FheChain, p as FheChainAuth } from "../index-O1xwLjWX.js";
|
|
10
|
+
import { n as MutableWalletAccountStore, t as BaseSigner } from "../base-signer-DuHym9wR.js";
|
|
11
11
|
import { Abi, Address, ContractFunctionArgs, ContractFunctionName, ContractFunctionReturnType, EIP1193Provider, Hex, Hex as Hex$1, PublicClient, WalletClient } from "viem";
|
|
12
12
|
/** Create a {@link ZamaConfig} from viem clients. */
|
|
13
13
|
export declare function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(params: ZamaConfigViem<TChains>): ZamaConfig;
|
|
@@ -79,6 +79,8 @@ export declare class ViemProvider implements GenericProvider {
|
|
|
79
79
|
}): Promise<MulticallReturnType<TCalls>>;
|
|
80
80
|
/** Wait for a transaction to be mined and return its receipt. */
|
|
81
81
|
waitForTransactionReceipt(hash: Hex$1): Promise<TransactionReceipt>;
|
|
82
|
+
/** Return the receipt of a mined transaction, or `null` when it is not mined. */
|
|
83
|
+
getTransactionReceipt(hash: Hex$1): Promise<TransactionReceipt | null>;
|
|
82
84
|
/** Return the latest block timestamp in seconds. */
|
|
83
85
|
getBlockTimestamp(chainId?: number): Promise<bigint>;
|
|
84
86
|
/** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */
|
package/dist/esm/viem/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-
|
|
1
|
+
import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-D1cVCzw8.js";import{i as p,t as m}from"../base-signer-eT-iTgjT.js";import{t as h}from"../eip1193-subscribe-DxAQh8dY.js";import{t as g}from"../typed-data-eAgGr9V-.js";import{a as _,i as v,n as y,o as b,r as x,s as S,t as C}from"../wrappers-registry-Cm3JJeqx.js";import{TransactionReceiptNotFoundError as w,encodeFunctionData as T,getAddress as E,serializeTransaction as D}from"viem";var O=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){let{chainId:t,...n}=e;return await d(`ViemProvider`,t,()=>this.getChainId()),this.#e.readContract(n)}async multicall(e){return await d(`ViemProvider`,e.chainId,()=>this.getChainId()),await this.#e.multicall({contracts:e.calls.map(({chainId:e,...t})=>t),allowFailure:!1,deployless:this.#e.chain?.contracts?.multicall3===void 0})}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getTransactionReceipt(e){try{return await this.#e.getTransactionReceipt({hash:e})}catch(e){if(e instanceof w)return null;throw e}}async getBlockTimestamp(e){return await d(`ViemProvider`,e,()=>this.getChainId()),(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=T({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),a=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),o=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new c(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),s=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,a,o,s]);return D({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function k(e){if(e.account&&e.chain)return{address:E(e.account.address),chainId:e.chain.id}}var A=class extends m{#e;#t;#n;constructor(e){super(k(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new r(e);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`);return t.signTypedData({account:n,...g(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?h({provider:this.#t,getInitialWalletAccount:()=>k(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function j(e){let t=new A({walletClient:e.walletClient,ethereum:e.ethereum}),n=new O({publicClient:e.publicClient});return p(t,n,e)}function M(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function N(e,t,n){return e.readContract(f(t,n))}function P(t,n){return t.readContract(e(n))}function F(e,t,n){return e.readContract(l(t,n))}function I(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...o(t,n,r,i)})}function L(e,t,n,r,a,o){return e.writeContract({chain:e.chain,account:M(e),...i(t,n,r,a,o)})}function R(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...a(t,n,r,i)})}function z(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...s(t,n,r,i)})}function B(e,t,n,r){return e.writeContract({chain:e.chain,account:M(e),...u(t,n,r)})}function V(e,t,r,i){return e.writeContract({chain:e.chain,account:M(e),...n(t,r,i)})}function H(e,t){return e.readContract(v(t))}function U(e,t){return e.readContract(_(t))}function W(e,t,n,r){return e.readContract(b(t,n,r))}function G(e,t,n){return e.readContract(x(t,n))}function K(e,t,n){return e.readContract(C(t,n))}function q(e,t,n){return e.readContract(y(t,n))}function J(e,t,n){return e.readContract(S(t,n))}export{m as BaseSigner,O as ViemProvider,A as ViemSigner,t as ZamaSDKEvents,j as createConfig,N as readConfidentialBalanceOfContract,K as readConfidentialTokenAddressContract,J as readIsConfidentialTokenValidContract,F as readSupportsInterfaceContract,q as readTokenAddressContract,G as readTokenPairContract,H as readTokenPairsContract,U as readTokenPairsLengthContract,W as readTokenPairsSliceContract,P as readUnderlyingTokenContract,I as writeConfidentialTransferContract,z as writeFinalizeUnwrapContract,B as writeSetOperatorContract,L as writeUnwrapContract,R as writeUnwrapFromBalanceContract,V as writeWrapContract};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["underlyingContract","ZamaSDKEvents","wrapContract","WalletNotConnectedError","unwrapContract","unwrapFromBalanceContract","confidentialTransferContract","finalizeUnwrapContract","TransactionRevertedError","supportsInterfaceContract","setOperatorContract","requireReadChain","confidentialBalanceOfContract","buildZamaConfig","BaseSigner","eip1193Subscribe","toViemTypedData","getTokenPairsLengthContract","getTokenPairsContract","getTokenAddressContract","getTokenPairsSliceContract","getTokenPairContract","isConfidentialTokenValidContract","getConfidentialTokenAddressContract","ViemProvider","#publicClient","config","call","chainId","params","_","args","data","encodeFunctionData","calldata","chainIdPromise","noncePromise","from","gasPromise","error","feesPromise","nonce","gas","fees","serializeTransaction","walletAccountFromWalletClient","walletClient","getAddress","ViemSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","operation","#requireAccount","typedData","next","createConfig","signer","provider","requireAccount","client","readConfidentialBalanceOfContract","tokenAddress","userAddress","readUnderlyingTokenContract","wrapperAddress","readSupportsInterfaceContract","interfaceId","writeConfidentialTransferContract","to","encryptedAmount","inputProof","writeUnwrapContract","encryptedErc20","writeUnwrapFromBalanceContract","encryptedBalance","writeFinalizeUnwrapContract","wrapper","unwrapRequestId","unwrapAmountCleartext","decryptionProof","writeSetOperatorContract","operator","until","writeWrapContract","amount","readTokenPairsContract","registry","readTokenPairsLengthContract","readTokenPairsSliceContract","fromIndex","toIndex","readTokenPairContract","index","readConfidentialTokenAddressContract","readTokenAddressContract","confidentialTokenAddress","readIsConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n MulticallReturnType,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { requireReadChain } from \"../utils/alignment\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const { chainId, ...call } = config;\n await requireReadChain(\"ViemProvider\", chainId, () => this.getChainId());\n return this.#publicClient.readContract(call as typeof config);\n }\n\n /**\n * Run many reads in one Multicall3 call. On a chain whose viem definition\n * names no Multicall3, such as a local Hardhat node, the call carries its code.\n */\n async multicall<const TCalls extends readonly ReadContractConfig[]>(params: {\n readonly calls: TCalls;\n readonly chainId?: number;\n }): Promise<MulticallReturnType<TCalls>> {\n await requireReadChain(\"ViemProvider\", params.chainId, () => this.getChainId());\n const results = await this.#publicClient.multicall({\n contracts: params.calls.map(({ chainId: _, ...call }) => call) as never,\n allowFailure: false,\n deployless: this.#publicClient.chain?.contracts?.multicall3 === undefined,\n });\n return results as MulticallReturnType<TCalls>;\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(chainId?: number): Promise<bigint> {\n await requireReadChain(\"ViemProvider\", chainId, () => this.getChainId());\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { toViemTypedData } from \"./typed-data\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n return walletClient.signTypedData({ account, ...toViemTypedData(typedData) });\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"A,6cA2CA,IAAawB,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKC,GAAgBC,EAAO,YA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F,CAGA,SAAgBiC,EACd,EACA,EACA,EACA,CACA,OAAOnC,EAAO,aAAa1C,EAAwBqE,EAAUS,CAAwB,CAAC,CACxF,CAGA,SAAgBC,EACd,EACA,EACA,EACA,CACA,OAAOrC,EAAO,aAAavC,EAAiCkE,EAAUS,CAAwB,CAAC,CACjG,C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["underlyingContract","ZamaSDKEvents","wrapContract","WalletNotConnectedError","unwrapContract","unwrapFromBalanceContract","confidentialTransferContract","finalizeUnwrapContract","TransactionRevertedError","supportsInterfaceContract","setOperatorContract","requireReadChain","confidentialBalanceOfContract","buildZamaConfig","BaseSigner","eip1193Subscribe","toViemTypedData","getTokenPairsLengthContract","getTokenPairsContract","getTokenAddressContract","getTokenPairsSliceContract","getTokenPairContract","isConfidentialTokenValidContract","getConfidentialTokenAddressContract","ViemProvider","#publicClient","config","call","chainId","params","_","error","TransactionReceiptNotFoundError","args","data","encodeFunctionData","calldata","chainIdPromise","noncePromise","from","gasPromise","feesPromise","nonce","gas","fees","serializeTransaction","walletAccountFromWalletClient","walletClient","getAddress","ViemSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","operation","#requireAccount","typedData","next","createConfig","signer","provider","requireAccount","client","readConfidentialBalanceOfContract","tokenAddress","userAddress","readUnderlyingTokenContract","wrapperAddress","readSupportsInterfaceContract","interfaceId","writeConfidentialTransferContract","to","encryptedAmount","inputProof","writeUnwrapContract","encryptedErc20","writeUnwrapFromBalanceContract","encryptedBalance","writeFinalizeUnwrapContract","wrapper","unwrapRequestId","unwrapAmountCleartext","decryptionProof","writeSetOperatorContract","operator","until","writeWrapContract","amount","readTokenPairsContract","registry","readTokenPairsLengthContract","readTokenPairsSliceContract","fromIndex","toIndex","readTokenPairContract","index","readConfidentialTokenAddressContract","readTokenAddressContract","confidentialTokenAddress","readIsConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n TransactionReceiptNotFoundError,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n MulticallReturnType,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { requireReadChain } from \"../utils/alignment\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const { chainId, ...call } = config;\n await requireReadChain(\"ViemProvider\", chainId, () => this.getChainId());\n return this.#publicClient.readContract(call as typeof config);\n }\n\n /**\n * Run many reads in one Multicall3 call. On a chain whose viem definition\n * names no Multicall3, such as a local Hardhat node, the call carries its code.\n */\n async multicall<const TCalls extends readonly ReadContractConfig[]>(params: {\n readonly calls: TCalls;\n readonly chainId?: number;\n }): Promise<MulticallReturnType<TCalls>> {\n await requireReadChain(\"ViemProvider\", params.chainId, () => this.getChainId());\n const results = await this.#publicClient.multicall({\n contracts: params.calls.map(({ chainId: _, ...call }) => call) as never,\n allowFailure: false,\n deployless: this.#publicClient.chain?.contracts?.multicall3 === undefined,\n });\n return results as MulticallReturnType<TCalls>;\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the receipt of a mined transaction, or `null` when it is not mined. */\n async getTransactionReceipt(hash: Hex): Promise<TransactionReceipt | null> {\n try {\n return await this.#publicClient.getTransactionReceipt({ hash });\n } catch (error) {\n if (error instanceof TransactionReceiptNotFoundError) {\n return null;\n }\n throw error;\n }\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(chainId?: number): Promise<bigint> {\n await requireReadChain(\"ViemProvider\", chainId, () => this.getChainId());\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { toViemTypedData } from \"./typed-data\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n return walletClient.signTypedData({ account, ...toViemTypedData(typedData) });\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"A,kfA4CA,IAAawB,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKC,GAAgBC,EAAO,YAC9B,CAGA,MAAM,YAA8B,CAClC,OAAO,KAAKD,GAAc,WAAW,CACvC,CAGA,MAAM,aAKJ,EACkF,CAClF,GAAM,CAAE,UAAS,GAAGE,GAASD,EAE7B,OADA,MAAMf,EAAiB,eAAgBiB,MAAe,KAAK,WAAW,CAAC,EAChE,KAAKH,GAAc,aAAaE,CAAqB,CAC9D,CAMA,MAAM,UAA8D,EAG3B,CAOvC,OANA,MAAMhB,EAAiB,eAAgBkB,EAAO,YAAe,KAAK,WAAW,CAAC,EAMvE,MALe,KAAKJ,GAAc,UAAU,CACjD,UAAWI,EAAO,MAAM,KAAK,CAAE,QAASC,EAAG,GAAGH,KAAWA,CAAI,EAC7D,aAAc,GACd,WAAY,KAAKF,GAAc,OAAO,WAAW,aAAe,IAAA,EAClE,CAAC,CAEH,CAGA,MAAM,0BAA0B,EAAwC,CACtE,OAAO,KAAKA,GAAc,0BAA0B,CAAE,MAAK,CAAC,CAC9D,CAGA,MAAM,sBAAsB,EAA+C,CACzE,GAAI,CACF,OAAO,MAAM,KAAKA,GAAc,sBAAsB,CAAE,MAAK,CAAC,CAChE,OAASM,EAAO,CACd,GAAIA,aAAiBC,EACnB,OAAO,KAET,MAAMD,CACR,CACF,CAGA,MAAM,kBAAkB,EAAmC,CA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AOxB,EAAO,cAAc,CAC1B,MAAOA,EAAO,MACd,QAASD,EAAeC,CAAM,EAC9B,GAAG5D,EAAaiE,EAAgBI,EAAIgB,CAAM,CAC5C,CAAC,CACH,CAKA,SAAgBC,EAAuB,EAAsB,EAAmB,CAC9E,OAAO1B,EAAO,aAAa5C,EAAsBuE,CAAQ,CAAC,CAC5D,CAGA,SAAgBC,EAA6B,EAAsB,EAAmB,CACpF,OAAO5B,EAAO,aAAa7C,EAA4BwE,CAAQ,CAAC,CAClE,CAGA,SAAgBE,EACd,EACA,EACA,EACA,EACA,CACA,OAAO7B,EAAO,aAAa1C,EAA2BqE,EAAUG,EAAWC,CAAO,CAAC,CACrF,CAGA,SAAgBC,EAAsB,EAAsB,EAAmB,EAAe,CAC5F,OAAOhC,EAAO,aAAazC,EAAqBoE,EAAUM,CAAK,CAAC,CAClE,CAGA,SAAgBC,EACd,EACA,EACA,EACA,CACA,OAAOlC,EAAO,aAAavC,EAAoCkE,EAAUzB,CAAY,CAAC,CACxF,CAGA,SAAgBiC,EACd,EACA,EACA,EACA,CACA,OAAOnC,EAAO,aAAa3C,EAAwBsE,EAAUS,CAAwB,CAAC,CACxF,CAGA,SAAgBC,EACd,EACA,EACA,EACA,CACA,OAAOrC,EAAO,aAAaxC,EAAiCmE,EAAUS,CAAwB,CAAC,CACjG,C"}
|
package/dist/esm/web/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*
|
|
8
8
|
* @packageDocumentation
|
|
9
9
|
*/
|
|
10
|
-
import { dn as FhevmClientOptions, fn as FhevmRelayerOptions, mn as RelayerOptions, n as RelayerConfig, pn as FhevmRuntimeConfig, r as WebRelayerConfig } from "../types-
|
|
11
|
-
import { t as EncryptWorkerTimeouts } from "../encrypt-worker-client-
|
|
10
|
+
import { dn as FhevmClientOptions, fn as FhevmRelayerOptions, mn as RelayerOptions, n as RelayerConfig, pn as FhevmRuntimeConfig, r as WebRelayerConfig } from "../types-NmMfCGuC.js";
|
|
11
|
+
import { t as EncryptWorkerTimeouts } from "../encrypt-worker-client-BJJbrdZB.js";
|
|
12
12
|
/** {@link RelayerOptions} plus the web-only encryption offload switches. */
|
|
13
13
|
interface WebRelayerOptions extends RelayerOptions {
|
|
14
14
|
/**
|
package/dist/esm/web/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e,t}from"../fhevm-relayer-
|
|
1
|
+
import{r as e,t}from"../fhevm-relayer-DDTrSUpu.js";import{t as n}from"../validation-BLmG7UVk.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n,r)=>new t({chain:e,options:s,telemetry:r&&{state:r,runtime:`web`,mode:r.mode},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zama-fhe/sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.9.0-beta.10",
|
|
4
4
|
"description": "TypeScript SDK for Zama fhEVM confidential smart contracts",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"blockchain",
|
|
@@ -195,7 +195,7 @@
|
|
|
195
195
|
"api-report:check": "api-extractor run -c api-extractor.json && api-extractor run -c api-extractor.web.json && api-extractor run -c api-extractor.viem.json && api-extractor run -c api-extractor.ethers.json && api-extractor run -c api-extractor.node.json && api-extractor run -c api-extractor.query.json && api-extractor run -c api-extractor.vaults.json"
|
|
196
196
|
},
|
|
197
197
|
"dependencies": {
|
|
198
|
-
"@fhevm/sdk": "0.13.
|
|
198
|
+
"@fhevm/sdk": "0.13.9",
|
|
199
199
|
"viem": ">=2",
|
|
200
200
|
"zod": ">=4"
|
|
201
201
|
},
|
package/dist/cjs/chains.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=Object.freeze({id:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`,vaultRouterAddress:`0x11c6Acfd368DDFAB97d15649eB8043C0197fac4C`}),t=Object.freeze({id:137,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://polygon-bor-rpc.publicnode.com`,aclContractAddress:`0x6737F17e31cf26a1b62fb0362acC5a16CB156F49`,kmsContractAddress:`0x14e609595474874Dd6b6128376E336EfADfdBE37`,inputVerifierContractAddress:`0xf40BD204B035522EaAc8E5afAdc55113Acac96ca`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xc8908569868758dAF814B5a8b96bBc44D1653d54`}),n=Object.freeze({id:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`,vaultRouterAddress:`0xD5BBFF95F3401aeC3B111664F6b72EdAe73814e8`}),r=Object.freeze({id:80002,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://polygon-amoy-bor-rpc.publicnode.com`,aclContractAddress:`0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985`,kmsContractAddress:`0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041`,inputVerifierContractAddress:`0x6e5A7D8b0c645467Cba7e62D6624917085118631`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:void 0}),i=Object.freeze({id:560048,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.hoodi.ethpandaops.io`,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,kmsContractAddress:`0x822BE20679CfAfdc352F05dEdfe12a07E912212e`,inputVerifierContractAddress:`0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`}),a=Object.freeze({id:936486,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.testnet.t-rex.zenith.network`,aclContractAddress:`0x061AAc7aAACc98d8e30459d4D858DaB9b6F3bd23`,kmsContractAddress:`0x85fBA21840059cB7E2E5BB7Fa2c5b2A324Ea7a7D`,inputVerifierContractAddress:`0xE90965601D10D42D3d88486b47b0Caf12C5C9fDe`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0xde2e3948d35ef9C406A7317eAF332F3c2786a566`,executorAddress:`0x6C5036A4ad55DBA8007ae82c4e9C123F143e53ab`}),o=Object.freeze({id:97,gatewayChainId:10901,relayerUrl:``,network:`https://bsc-testnet.bnbchain.org`,aclContractAddress:`0x52470e945521E247Cb4754088a836Dc4b838AFBE`,kmsContractAddress:`0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F`,inputVerifierContractAddress:`0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC`,executorAddress:`0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54`}),s=Object.freeze({id:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`}),c=s,l=Object.freeze({[e.id]:e,[t.id]:t,[n.id]:n,[r.id]:r,[i.id]:i,[a.id]:a,[o.id]:o,[s.id]:s});Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return a}});
|
|
2
|
-
//# sourceMappingURL=chains.cjs.map
|
package/dist/cjs/chains.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chains.cjs","names":["mainnet","polygon","sepolia","polygonAmoy","hoodi","zenithTrexTestnet","bscTestnet","hardhat","anvil","chains"],"sources":["../../src/chains/configs.ts"],"sourcesContent":["import type { FheChain } from \"./types\";\n\n/**\n * Mainnet network configuration (chainId 1).\n */\nexport const mainnet = Object.freeze({\n id: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n vaultRouterAddress: \"0x11c6Acfd368DDFAB97d15649eB8043C0197fac4C\",\n} as const satisfies FheChain);\n\n/**\n * Polygon mainnet network configuration (chainId 137).\n */\nexport const polygon = Object.freeze({\n id: 137,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://polygon-bor-rpc.publicnode.com\",\n aclContractAddress: \"0x6737F17e31cf26a1b62fb0362acC5a16CB156F49\",\n kmsContractAddress: \"0x14e609595474874Dd6b6128376E336EfADfdBE37\",\n inputVerifierContractAddress: \"0xf40BD204B035522EaAc8E5afAdc55113Acac96ca\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xc8908569868758dAF814B5a8b96bBc44D1653d54\",\n} as const satisfies FheChain);\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n */\nexport const sepolia = Object.freeze({\n id: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n vaultRouterAddress: \"0xD5BBFF95F3401aeC3B111664F6b72EdAe73814e8\",\n} as const satisfies FheChain);\n\n/**\n * Polygon Amoy testnet network configuration (chainId 80002).\n *\n * Ships without a wrappers registry: set `registryAddress` to your own\n * deployment to use token operations.\n */\nexport const polygonAmoy = Object.freeze({\n id: 80002,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://polygon-amoy-bor-rpc.publicnode.com\",\n aclContractAddress: \"0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985\",\n kmsContractAddress: \"0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041\",\n inputVerifierContractAddress: \"0x6e5A7D8b0c645467Cba7e62D6624917085118631\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: undefined,\n} as const satisfies FheChain);\n\n/**\n * Hoodi testnet configuration (chainId 560048).\n *\n * Hoodi does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const hoodi = Object.freeze({\n id: 560048,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.hoodi.ethpandaops.io\",\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n kmsContractAddress: \"0x822BE20679CfAfdc352F05dEdfe12a07E912212e\",\n inputVerifierContractAddress: \"0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n} as const satisfies FheChain);\n\n/**\n * T-Rex Zenith testnet configuration (chainId 936486).\n *\n * T-Rex's testnet instance on Zenith EVM (Reth execution, Canton-mediated\n * finality) — a separate chain from Zenith's shared testnet (chainId 936485).\n * It does not have full FHE infrastructure — use with `cleartext()` transport.\n */\nexport const zenithTrexTestnet = Object.freeze({\n id: 936486,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.testnet.t-rex.zenith.network\",\n aclContractAddress: \"0x061AAc7aAACc98d8e30459d4D858DaB9b6F3bd23\",\n kmsContractAddress: \"0x85fBA21840059cB7E2E5BB7Fa2c5b2A324Ea7a7D\",\n inputVerifierContractAddress: \"0xE90965601D10D42D3d88486b47b0Caf12C5C9fDe\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0xde2e3948d35ef9C406A7317eAF332F3c2786a566\",\n executorAddress: \"0x6C5036A4ad55DBA8007ae82c4e9C123F143e53ab\",\n} as const satisfies FheChain);\n\n/**\n * BNB Smart Chain testnet configuration (chainId 97, Chapel).\n *\n * BSC testnet does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const bscTestnet = Object.freeze({\n id: 97,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://bsc-testnet.bnbchain.org\",\n aclContractAddress: \"0x52470e945521E247Cb4754088a836Dc4b838AFBE\",\n kmsContractAddress: \"0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F\",\n inputVerifierContractAddress: \"0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC\",\n executorAddress: \"0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54\",\n} as const satisfies FheChain);\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n */\nexport const hardhat = Object.freeze({\n id: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} as const satisfies FheChain);\n\n/** Alias for {@link hardhat}. */\nexport const anvil = hardhat;\n\n/**\n * Built-in chain configurations keyed by chain ID.\n */\nexport const chains: Record<number, FheChain> = Object.freeze({\n [mainnet.id]: mainnet,\n [polygon.id]: polygon,\n [sepolia.id]: sepolia,\n [polygonAmoy.id]: polygonAmoy,\n [hoodi.id]: hoodi,\n [zenithTrexTestnet.id]: zenithTrexTestnet,\n [bscTestnet.id]: bscTestnet,\n [hardhat.id]: hardhat,\n});\n"],"mappings":"AAKA,MAAaA,EAAU,OAAO,OAAO,CACnC,GAAI,EACJ,eAAgB,OAChB,WAAY,mCACZ,QAAS,sCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CACjB,mBAAoB,4CACtB,CAA6B,EAKhBC,EAAU,OAAO,OAAO,CACnC,GAAI,IACJ,eAAgB,OAChB,WAAY,mCACZ,QAAS,yCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,4CACnB,CAA6B,EAKhBC,EAAU,OAAO,OAAO,CACnC,GAAI,SACJ,eAAgB,MAChB,WAAY,mCACZ,QAAS,8CACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3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ChBC,EAAQ,IAAKA,CAChB,CAAC,E"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{m as e,r as t,t as n}from"./relayer-nWfQAlo7.js";import{a as r,c as i,r as a,s as o,u as s}from"./signing-CVEOw21I.js";import{B as c,G as l,H as u,I as d,_ as f,g as p,h as m,v as h,z as g}from"./alignment-o-YIndFR.js";import{o as _,t as v}from"./telemetry-r8qLB6-r.js";import{t as y}from"./validation-CZfDLOUh.js";import{a as ee,i as te,n as ne,o as re,r as ie,s as ae,t as b}from"./wrappers-registry-Cm3JJeqx.js";import{a as x,l as S,n as C,o as w,s as T,u as oe}from"./chains-BQXSxIwU.js";import{getAddress as E,isAddress as se,isHex as ce,toBytes as D,toHex as O,zeroAddress as le}from"viem";import{hasFhevmRuntimeConfig as ue,setFhevmRuntimeConfig as de}from"@fhevm/sdk/viem";import{z as k}from"zod/mini";var A=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??/* @__PURE__ */ Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const fe=new A;var j=class{#e=/* @__PURE__ */ new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const pe=new j;function me(){return typeof window<`u`?new A(`CredentialStore`):new j}function he(e=me(),t=e){return{storage:e,permitStorage:t}}function ge(e,t,r){let i=e.map(e=>e.id),a=[...new Set(i.filter((e,t)=>i.indexOf(e)!==t))];if(a.length>0)throw new n(`Duplicate chain id(s) [${a.join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`);let o=Object.keys(t).map(Number).filter(e=>!i.includes(e));o.length>0&&r.warn(`Relayer entries for chain(s) [${o.join(`, `)}] are ignored: those chains are not in the chains array. Add the chain config to use them, or drop the relayer entries.`);let s=/* @__PURE__ */ new Map;for(let r of e){let e=t[r.id];if(!e)throw new n(`Chain ${r.id} has no relayer configured. Add a relayer entry: relayers: { [${r.id}]: web() }`);s.set(r.id,{chain:r,relayerConfig:e})}return s}var _e=class{#e;#t;#n;constructor(e,t,r,i){if(e.length===0)throw new n(`At least one chain is required.`);this.#e=new Map(e.map(e=>[e.id,e])),this.#n=e[0].id;let a=/* @__PURE__ */ new Map;for(let[n,{relayerConfig:o,chain:s}]of ge(e,t,r))a.set(n,o.createRelayer(s,r,i));this.#t=a}get chains(){return[...this.#e.values()]}get chain(){let e=this.#e.get(this.#n);if(e===void 0)throw new n(`Chain ${this.#n} is not configured. Add it to the chains array.`);return e}switchChain(e){this.#n=e}dispose(){for(let e of new Set(this.#t.values()))e.dispose?.()}get relayer(){let e=this.#t.get(this.chain.id);if(e===void 0)throw new n(`No relayer configured for chain ${this.#n}. Add it to the relayers object.`);return e}};function M(e){return E(e)}const N=k.custom(e=>typeof e==`string`&&ce(e,{strict:!0}),`expected 0x-prefixed hex string`),ve=k.custom(e=>typeof e==`string`&&se(e,{strict:!1}),`expected EVM address`),P=k.pipe(ve,k.transform(M)),F=k.int().check(k.nonnegative()),I=k.int().check(k.positive()),ye=k.int().check(k.nonnegative()),be=k.int().check(k.positive());k.int().check(k.positive());const L={version:1,info:`zama-sdk-keypair-wrapping-v1`,ivLengthBytes:12,tagLengthBytes:16};function R(e){return new Uint8Array(e)}function xe(e){return R(new TextEncoder().encode(JSON.stringify([e.publicKey,e.createdAt,e.expiresAt,e.tkmsVersion??null])))}function Se(e){return typeof e==`string`?new TextEncoder().encode(e):R(e)}var Ce=class{#e;#t;constructor(e){this.#e=e}async baseKey(){return this.#t??=this.#n(this.#e),this.#t}async#n(e){let t=Se(e),n=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return t.fill(0),e instanceof Uint8Array&&e.fill(0),this.#e=void 0,n}};async function we(e,t){let n=await e.baseKey();return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:new TextEncoder().encode(t),info:new TextEncoder().encode(L.info)},n,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function Te(e,t,n,r){let i=await we(t,n),a=crypto.getRandomValues(new Uint8Array(L.ivLengthBytes)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a,additionalData:xe(r)},i,R(D(e)));return{wrappedPrivateKey:O(new Uint8Array(o)),iv:O(a)}}async function Ee(e,t,n,r){let i=await we(t,n),a=await crypto.subtle.decrypt({name:`AES-GCM`,iv:R(D(e.iv)),additionalData:xe(r)},i,R(D(e.wrappedPrivateKey)));return O(new Uint8Array(a))}function De(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`OperationError`}const z=86400;function B(){return Math.floor(Date.now()/1e3)}function V(e){return[...new Set(e.map(M))].sort()}function Oe(e){let{chainId:t}=e.domain;return typeof t==`bigint`?{...e,domain:{...e.domain,chainId:t.toString()}}:e}const ke=`transportKeyPairTTL must be a positive integer number of seconds`,Ae=`permitTTL must be a positive integer number of days`,je=`transportKeyPairScope must be a non-empty string`,H=`transportKeyPairDerivationSecret must be a Uint8Array of at least 32 bytes or a string of at least 64 characters (256 bits of entropy): source it from a CSPRNG or secrets manager, not a human-memorable passphrase`,Me=365*z,Ne=k.int({error:ke}).check(k.positive({error:ke}),k.maximum(Me,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${Me}s (365 days)`)),Pe=k.int({error:Ae}).check(k.positive({error:Ae}),k.maximum(365,`permitTTL must not exceed the V1 permit maximum of 365 days`)),Fe=k.string({error:je}).check(k.minLength(1,je)),Ie=k.union([k.string({error:H}).check(k.minLength(64,H)),k.instanceof(Uint8Array,{error:H}).check(k.refine(e=>e.byteLength>=32,{error:H}))],{error:H}),Le=k.object({publicKey:N,privateKey:N,createdAt:F,expiresAt:I,tkmsVersion:k.optional(k.string())}),U=k.object({domain:k.record(k.string(),k.unknown()),primaryType:k.optional(k.string()),types:k.record(k.string(),k.array(k.object({name:k.string(),type:k.string()}))),message:k.record(k.string(),k.unknown())}),W=k.object({version:k.int().check(k.positive()),eip712:U,signature:N,signerAddress:P}),G=k.object({keypairPublicKey:N,contractAddresses:k.array(P).check(k.maxLength(10)),serializedPermit:W,startTimestamp:F,durationDays:be}),Re=k.array(G),ze=k.array(k.string()),Be=k.object({version:k.literal(1),eip712:U,signerAddress:P}),Ve=`iv must be a ${L.ivLengthBytes}-byte hex string`,He=`wrappedPrivateKey must be a whole number of bytes and at least ${L.tagLengthBytes} bytes (the AES-GCM authentication tag)`;function Ue(e){return(e.length-2)/2}const We=k.object({wrappingVersion:k.literal(L.version,{error:`wrappingVersion must be a wrapping scheme this SDK can read`}),publicKey:N,wrappedPrivateKey:N.check(k.refine(e=>e.length%2==0&&Ue(e)>=L.tagLengthBytes,{error:He})),iv:N.check(k.refine(e=>Ue(e)===L.ivLengthBytes,{error:Ve})),createdAt:F,expiresAt:I,tkmsVersion:k.optional(k.string())});function Ge(e){let t={publicKey:e.publicKey,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(t.tkmsVersion=e.tkmsVersion),t}const K={version:L.version,schema:We,async encode(e,t,n){let{wrappedPrivateKey:r,iv:i}=await Te(e.privateKey,t,n,Ge(e)),a={wrappingVersion:L.version,publicKey:e.publicKey,wrappedPrivateKey:r,iv:i,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(a.tkmsVersion=e.tkmsVersion),a},async decode(e,t,n){let r=await Ee({wrappedPrivateKey:e.wrappedPrivateKey,iv:e.iv},t,n,Ge(e)),i={publicKey:e.publicKey,privateKey:r,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(i.tkmsVersion=e.tkmsVersion),i}},Ke=/* @__PURE__ */ new Map([[K.version,K]]),qe=K;function Je(e){let t=e;return t.wrappingVersion!==void 0||t.wrappedPrivateKey!==void 0&&t.iv!==void 0}function Ye(e){if(typeof e!=`object`||!e||!Je(e)){let t=Le.safeParse(e);return t.success?{kind:`plaintext`,keyPair:t.data}:{kind:`unrecognized`}}let t=e.wrappingVersion,n=typeof t==`number`?Ke.get(t):void 0;if(n===void 0)return{kind:`unsupported-version`,version:t};let r=n.schema.safeParse(e);if(!r.success)return{kind:`corrupt-wrapped`};let i=r.data;return{kind:`wrapped`,expiresAt:i.expiresAt,decode:(e,t)=>n.decode(i,e,t)}}function Xe(e,t,n){return qe.encode(e,t,n)}function Ze(e){return`keypair:${e}`}function q(e){return`keypair:scope:${e}`}function J(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function Y(e){return`permits-index:${e}`}function Qe(e){return`scope:${e}`}function $e(e,t){return{"wrapped-without-secret":`Transport key pair for scope "${t}" is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Every instance sharing this scope must use the same transportKeyPairDerivationSecret; once they do, call permits.revokeTransportKeyPair() to rotate the entry.`,"unwrapped-under-secret":`Transport key pair for scope "${t}" is stored unwrapped, but this instance is configured with a transportKeyPairDerivationSecret. A peer instance sharing this scope is running without the secret: configure the same transportKeyPairDerivationSecret everywhere, then call permits.revokeTransportKeyPair() to migrate the scope to a wrapped entry.`,"unwrap-failed":`Transport key pair for scope "${t}" failed to unwrap. This usually means another instance created it with a different transportKeyPairDerivationSecret: every instance sharing this scope must use the same secret. It can also mean the stored entry is corrupted.`,"corrupt-wrapped":`Transport key pair for scope "${t}" is wrapped but structurally invalid: the stored iv or ciphertext is not a shape this wrapping scheme can produce. This usually means the stored entry is corrupted, or instances sharing this scope are running mismatched wrapping-scheme versions.`}[e]}const et={"unwrapped-under-secret":`unwrapped transport key pair entry found while a transportKeyPairDerivationSecret is configured`,"unwrap-failed":`transport key pair entry failed to unwrap (wrong transportKeyPairDerivationSecret?)`,"corrupt-wrapped":`structurally invalid wrapped transport key pair entry`};function tt(e,t){let n=typeof e==`number`?`wrappingVersion ${e}`:`no wrappingVersion this build recognizes`;return`Transport key pair ${t===void 0?`for this signer`:`for scope "${t}"`} was written under a wrapping scheme this SDK build cannot read (${n}). The entry is preserved instead of regenerated, since an instance that understands the scheme may still be using it: ${t===void 0?`run a build that supports it, or call permits.clear() to discard the entry deliberately`:`run a build that supports it everywhere, or call permits.revokeTransportKeyPair() to rotate the scope`}.`}var nt=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Map;#s=/* @__PURE__ */ new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger,this.#i=e.scope,this.#a=e.derivationSecret}#c(e){return this.#i===void 0?`signer:${e}`:Qe(this.#i)}#l(e){return this.#i===void 0?Ze(e):q(this.#i)}async readStored(e){return this.#u(this.#l(e),this.#c(e))}async#u(e,t){let n=await this.#t.get(e);if(n==null)return null;let i=Ye(n);if(i.kind===`unsupported-version`)throw this.#f(e,tt(i.version,this.#i));if(i.kind===`unrecognized`)return await this.#m(e,`malformed transport key pair entry`),null;let a=this.#a;if(a===void 0)return i.kind===`plaintext`?await this.#p(e,i.keyPair.expiresAt)?null:i.keyPair:this.#d(e,`wrapped-without-secret`);if(i.kind===`plaintext`)return this.#d(e,`unwrapped-under-secret`);if(i.kind===`corrupt-wrapped`)return this.#d(e,`corrupt-wrapped`);if(await this.#p(e,i.expiresAt))return null;try{return await i.decode(a,t)}catch(t){if(!De(t))throw this.#r.error(`transport key pair unwrap failed unexpectedly`,{key:e,error:t}),new r(`Transport key pair unwrap failed unexpectedly.`,{cause:t});return this.#d(e,`unwrap-failed`,t)}}async#d(e,t,n){if(this.#i!==void 0)throw this.#f(e,$e(t,this.#i),n);if(t===`wrapped-without-secret`)throw this.#f(e,`Transport key pair for this signer is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Configure the same transportKeyPairDerivationSecret the entry was written with. To downgrade to plaintext at rest on purpose, discard the stored entry first by calling permits.clear(), then run without the secret.`,n);let r=et[t];return this.#r.warn(r,{key:e}),await this.#m(e,r),null}#f(e,t,n){return this.#r.error(t,{key:e}),new r(t,{cause:n})}async#p(e,t){return B()<t?!1:(await this.#m(e,`expired transport key pair entry`),!0)}async#m(e,t){this.#r.debug(`discarding transport key pair entry`,{key:e,reason:t}),await d(`delete transport key pair entry`,()=>this.#t.delete(e),this.#r)}async getOrCreate(e,t){return this.#h(this.#l(e),this.#c(e),{strict:t?.strict})}async#h(e,t,n){let i=n?.strict??!1,a=`${e}::${i}`,o=this.#o.get(a);if(o)return o;let c=this.#s.get(e)??0,l=(async()=>{let n=await this.#u(e,t);if(n!==null)return n;let a=await this.#e(),o=B(),l=o+this.#n,u={publicKey:a.publicKey,privateKey:a.privateKey,createdAt:o,expiresAt:l};a.tkmsVersion&&(u.tkmsVersion=a.tkmsVersion);let f=u;if(this.#a!==void 0)try{f=await Xe(u,this.#a,t)}catch(t){let n=`Failed to wrap the transport private key for at-rest storage.`;throw this.#r.error(n,{key:e,error:t}),new r(n,{cause:t})}if((this.#s.get(e)??0)===c)i?await this.#t.set(e,f):await d(`persist transport key pair`,()=>this.#t.set(e,f),this.#r);else if(i)throw new s(`The transport key pair was rotated while it was being generated, so the freshly generated key pair could not be persisted. Retry.`);return u})().finally(()=>{this.#o.delete(a)});return this.#o.set(a,l),l}async clear(e){let t=Ze(e);await d(`delete transport key pair entry`,()=>this.#t.delete(t),this.#r)}async evict(e){let t=this.#l(e);await d(`evict transport key pair entry`,()=>this.#t.delete(t),this.#r)}async clearScope(){if(this.#i===void 0)return;let e=q(this.#i);this.#s.set(e,(this.#s.get(e)??0)+1),await this.#t.delete(e)}async warmScope(){this.#i!==void 0&&await this.#h(q(this.#i),Qe(this.#i),{strict:!0})}};function rt(e){return y(Be,e)}function it(e,t){let n=new Set(e.flatMap(e=>e.contractAddresses));return t.filter(e=>!n.has(e))}function at(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function ot(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function st(e,t){let n=new Set(t);return e.filter(e=>!e.contractAddresses.some(e=>n.has(e)))}function X(e,t){return[.../* @__PURE__ */ new Set([...e,...t])].sort()}function ct(e,t,n){let r=new Set(n),i=e.filter(e=>(/* @__PURE__ */ new Set([...e.contractAddresses,...t])).size<=10);if(i.length===0)return null;function a(e){return e.contractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var lt=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=J(e),n=await this.#e.get(t);if(n==null)return[];let r=Re.safeParse(n);return r.success?r.data:(await this.clearScope(e),[])}async listUsableAndPrune(e,t){let n=await this.list(e),r=ot(n,t,Math.floor(Date.now()/1e3));return r.length!==n.length&&(r.length===0?await this.clearScope(e):await d(`update permit entry`,()=>this.#e.set(J(e),r),this.#t)),r}async append(e,t){if(t.length===0)return;let n=t.map(e=>G.parse(e)),r=await this.list(e);await this.#e.set(J(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=G.parse(n),i=(await this.list(e)).filter(e=>e.serializedPermit.signature!==t);await this.#e.set(J(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=st(n,t);r.length===0?await this.clearScope(e):await this.#e.set(J(e),r)}async clearScope(e){await this.#a(J(e)),await this.#i(e)}async clearAllForSigner(e){let t=Y(e),n=await this.#n(t);await Promise.all(n.map(e=>this.#a(e))),await d(`delete permit index`,()=>this.#e.delete(t),this.#t)}async#n(e){let t=await this.#e.get(e);if(t==null)return[];let n=ze.safeParse(t);return n.success?n.data:(await d(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=Y(e.signerAddress),n=J(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let t=Y(e.signerAddress),n=J(e),r=await this.#n(t),i=r.filter(e=>e!==n);i.length!==r.length&&(i.length===0?await d(`delete permit index`,()=>this.#e.delete(t),this.#t):await d(`update permit index`,()=>this.#e.set(t,i),this.#t))}async#a(e){await d(`delete permit entry`,()=>this.#e.delete(e),this.#t)}};async function ut(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=await n();return e.set(t,i),i}var dt=class{#e;#t;#n;#r;#i;#a;#o;#s;#c=/* @__PURE__ */ new Map;constructor(e){this.#e=new nt({generator:async()=>{let t=e.router.relayer,n=await t.generateTransportKeyPair();return t.serializeTransportKeyPair({transportKeyPair:n})},storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger,scope:e.scope,derivationSecret:e.derivationSecret}),this.#t=new lt({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.router,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger,this.#o=e.emitEvent,this.#s=e.scope}#l(e){if(!this.#r)throw new u(e);return this.#r}#u(e,t,n=``){let r=a(t,{operation:e});return n&&(r.message=n+r.message),this.#o({type:c.PermitError,operation:e,error:r}),r}async grantPermit(e,t){let n=t===void 0?`grantPermit`:`grantDelegationPermit`,r,i,a;try{r=M(this.#l(`grantPermit`).requireWalletAccount(`grantPermit`).address),i=V(e),a=this.#f(r,t)}catch(e){throw this.#u(n,e)}let o=await this.#e.getOrCreate(r);if(i.length===0)return{keypair:o,permissions:[]};let s;try{s=await this.#t.listUsableAndPrune(a,o.publicKey)}catch(e){throw this.#u(n,e)}let c=it(s,i);if(c.length>0){let e=ct(s,c,i);if(e!==null){let t=X(e.contractAddresses,c),n=await this.#p({chunk:t,keypair:o,scope:a});await d(`replace permit`,()=>this.#t.replace(a,e.serializedPermit.signature,n),this.#a),s[s.indexOf(e)]=n}else for(let e of at(c)){let t=await this.#p({chunk:e,keypair:o,scope:a});s.push(t),await d(`persist permit`,()=>this.#t.append(a,[t]),this.#a)}}let l=new Set(i);return{keypair:o,permissions:s.filter(e=>e.contractAddresses.some(e=>l.has(e)))}}async preparePermit(e){let t=V(e.contracts).length;if(t>10)throw new n(`preparePermit: request.contracts must not exceed 10 addresses (got ${t}). Use batchPreparePermits to split them across permits.`);let[r]=await this.batchPreparePermits(e);return g(r,`batchPreparePermits result`),r}async batchPreparePermits(e){let t=M(e.signer),r=V(e.contracts);if(r.length===0)throw new n(`request.contracts must not be empty.`);let i=e.delegator?M(e.delegator):void 0;if(i!==void 0&&i===t)throw new n(`request.delegator must differ from request.signer: self-delegation is not allowed.`);let a=e.durationDays===void 0?this.#i:y(Pe,e.durationDays),o=this.#n.relayer,s=await this.#e.getOrCreate(t,{strict:!0}),c=await o.parseTransportKeyPair(s),l=B();return Promise.all(at(r).map(async e=>({version:1,eip712:Oe(U.parse(await o.createUnsignedLegacyDecryptionPermitEip712({transportKeyPair:c,contractAddresses:e,startTimestamp:l,durationSeconds:a*z,...i&&{delegatorAddress:i}}))),signerAddress:t})))}async batchRegisterPermits(e){if(e.length===0)throw new n(`permits must not be empty.`);let t={relayer:this.#n.relayer,activeChainId:this.#n.chain.id,storedKeyPairs:/* @__PURE__ */ new Map,transportKeyPairs:/* @__PURE__ */ new Map},r=[];for(let[n,{prepared:i,signature:a}]of e.entries()){let o=e.length>1?`permits[${n}]: `:``;r.push(await this.#d(i,a,t,o))}for(let{scope:e,permission:t}of r)await d(`replace permit`,()=>this.#t.replace(e,t.serializedPermit.signature,t),this.#a)}async#d(e,t,{relayer:r,activeChainId:a,storedKeyPairs:c,transportKeyPairs:l},u){let d;try{d=rt(e)}catch(e){throw this.#u(`registerPermit`,e,u)}let{domain:f,message:p}=d.eip712,m=Number(f.chainId);if(m!==a)throw this.#u(`registerPermit`,new o({preparedChainId:m,activeChainId:a}),u);let h=Number(p.startTimestamp),g=Number(p.durationDays);if(B()>=h+g*86400)throw this.#u(`registerPermit`,new i(`registerPermit: the prepared permit's validity window (starting ${h}, ${g}d) has already elapsed. Prepare the permit again.`),u);let _=d.signerAddress,v=await ut(c,_,()=>this.#e.readStored(_));if(v===null||v.publicKey!==p.publicKey)throw new s(`${u}registerPermit: the transport key pair changed since the permit was prepared. Prepare it again to rebind the signature request to the current key pair.`);try{let e=await ut(l,_,()=>r.parseTransportKeyPair(v)),i=await r.parseSignedDecryptionPermit({serializedPermit:{version:d.version,eip712:d.eip712,signature:t,signerAddress:_},transportKeyPair:e});if(i.version!==1)throw new n(`registerPermit: expected a V1 signed permit, got version ${i.version}.`);let o=y(W,await r.serializeSignedDecryptionPermit({signedPermit:i})),s={keypairPublicKey:v.publicKey,contractAddresses:V(i.eip712.message.contractAddresses),serializedPermit:o,startTimestamp:Number(i.eip712.message.startTimestamp),durationDays:Number(i.eip712.message.durationDays)};return{scope:{signerAddress:_,chainId:a,delegatorAddress:M(i.encryptedDataOwnerAddress)},permission:s}}catch(e){throw this.#u(`registerPermit`,e,u)}}async hasPermit(e,t){if(e.length===0)return!0;let n=this.#r?.walletAccount.getSnapshot();if(!n)return!1;let i=M(n.address),a;try{a=await this.#e.readStored(i)}catch(e){if(!(e instanceof r))throw e;return!1}if(a===null)return!1;let o=this.#f(i,t);return it(await this.#t.listUsableAndPrune(o,a.publicKey),V(e)).length===0}async revokePermits(e){let t=M(this.#l(`revokePermits`).requireWalletAccount(`revokePermits`).address);if(e===void 0){await this.#t.clearAllForSigner(t);return}let n=V(e);n.length!==0&&await this.#t.deletePermitsTouching(this.#f(t),n)}#f(e,t){return{signerAddress:e,chainId:this.#n.chain.id,delegatorAddress:t?M(t):e}}async clearCredentials(){let e=M(this.#l(`clearCredentials`).requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async revokeTransportKeyPair(e){if(this.#s===void 0)throw new n(`revokeTransportKeyPair() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to revoke.`);if(e!==this.#s)throw new n(`revokeTransportKeyPair("${e}") does not match the configured scope ("${this.#s}").`);await this.#e.clearScope()}async warmTransportKeyPair(e){await this.#e.getOrCreate(M(e))}async warmTransportKeyPairScope(e){if(this.#s===void 0)throw new n(`warmTransportKeyPairScope() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to warm.`);if(e!==this.#s)throw new n(`warmTransportKeyPairScope("${e}") does not match the configured scope ("${this.#s}").`);await this.#e.warmScope()}async handleWalletAccountChange(e,t){let n=e?M(e.address):void 0;n!==(t?M(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#p(n){let{chunk:r,keypair:i,scope:a}=n,o=B(),s=a.delegatorAddress!==a.signerAddress,c=this.#n.relayer;try{let e={transportKeyPair:await c.parseTransportKeyPair(i),contractAddresses:r,startTimestamp:o,durationSeconds:this.#i*z,signerAddress:a.signerAddress,signer:this.#l(`signPermit`)},t=s?await c.signDecryptionPermit({...e,delegatorAddress:a.delegatorAddress}):await c.signDecryptionPermit(e),n=y(W,await c.serializeSignedDecryptionPermit({signedPermit:t}));return{keypairPublicKey:i.publicKey,contractAddresses:r,serializedPermit:n,startTimestamp:o,durationDays:this.#i}}catch(n){let r=s?`grantDelegationPermit`:`grantPermit`;throw!(n instanceof t)&&n instanceof Error&&e(n.message)&&await this.#e.evict(a.signerAddress),this.#u(r,n)}}async evictTransportKeyPair(){let e=this.#r?.walletAccount.getSnapshot();e&&await this.#e.evict(M(e.address))}async recoverPermits(e,t,n){let r=this.#l(`recoverPermits`).requireWalletAccount(`recoverPermits`),i=this.#f(M(r.address),t),a=J(i),o=this.#c.get(a);if(o)return await o,this.grantPermit(e,t);let s=await this.#m(i),c=this.#c.get(a);if(c)return await c,this.grantPermit(e,t);if(s===null)return this.grantPermit(e,t);let l=new Set(n??[]);if(l.size>0&&!s.some(e=>l.has(e.serializedPermit.signature)))return this.grantPermit(e,t);let u=s.filter(e=>!l.has(e.serializedPermit.signature)),d=s.flatMap(e=>e.contractAddresses),f=this.#h(i,d,e,u,t).finally(()=>{this.#c.delete(a)});return this.#c.set(a,f),await f,this.grantPermit(e,t)}async#m(e){try{return await this.#t.list(e)}catch(e){return this.#a.warn(`read permits for recovery failed`,{error:e}),null}}async#h(e,t,n,r,i){await d(`evict revoked permits`,()=>this.#t.clearScope(e),this.#a);try{await this.grantPermit(X(t,V(n)),i)}catch(t){throw r.length>0&&await d(`restore surviving permits`,async()=>{let t=await this.#t.list(e),n=new Set(t.map(e=>e.serializedPermit.signature)),i=r.filter(e=>!n.has(e.serializedPermit.signature));i.length>0&&await this.#t.append(e,i)},this.#a),t}}},ft=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}warnAlways(e){console.warn(`${this.#t} ${e}`),this.warn(e)}};const pt={[w.id]:w.registryAddress,[T.id]:T.registryAddress,[S.id]:S.registryAddress,[x.id]:x.registryAddress,[oe.id]:oe.registryAddress,[C.id]:C.registryAddress},mt=k.record(k.string().check(k.regex(/^\d+$/,`expected numeric chain id key`)),P),Z=ye,Q=3e5;var ht=class{provider;#e;#t;#n=/* @__PURE__ */ new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},pt,y(k.optional(mt),e.registryAddresses)),this.#t=y(Z,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);else 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.provider.getChainId(),t=this.#e[e];if(!t)throw new n(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return E(t)}async listPairs(e={}){let t=e.page??1,r=e.pageSize??100,i=e.metadata??!1;if(t<1)throw new n(`page must be >= 1, got ${t}`);if(r<1)throw new n(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(ee(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*r),l=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:r};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.provider.readContract(re(a,c,l));d=this.#i(u,[...e])}if(!i)return{items:d,total:s,page:t,pageSize:r};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?Q:void 0)}return{items:p,total:s,page:t,pageSize:r}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.provider.readContract(f(e.tokenAddress)),this.provider.readContract(h(e.tokenAddress)),this.provider.readContract(m(e.tokenAddress)),this.provider.readContract(p(e.tokenAddress)),this.provider.readContract(f(e.confidentialTokenAddress)),this.provider.readContract(h(e.confidentialTokenAddress)),this.provider.readContract(m(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=E(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(b(t,n));return o===le?this.#i(r,null,Q):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=E(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(ne(t,n));return o===le?this.#i(r,null,Q):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(te(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(ee(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(re(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(ie(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(b(t,E(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(ne(t,E(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(ae(t,E(e)))}};function gt(e,t,n){let r=new ft(n.logger),i=n.logger,a={wasmAssetLoadMode:`auto`,moduleVersions:`auto`,logger:{error:(e,t)=>i?.error(e,{cause:t}),warn:e=>i?.warn(e),debug:e=>i?.debug(e)},...n.runtime};if(ue()){let e=`runtime configuration is already set and cannot be changed.`;n.runtime===void 0?r.debug(e):r.warn(e)}else de(a),_(a);let{storage:o,permitStorage:s}=he(n.storage,n.permitStorage),c=v(n.telemetry)??`header`,l=c===`off`?void 0:{layer:`core`,mode:c},u=new _e(n.chains,n.relayers,r,l);return{chains:n.chains,router:u,provider:t,signer:e,storage:o,permitStorage:s,transportKeyPairTTL:y(Ne,n.transportKeyPairTTL??2592e3),permitTTL:y(Pe,n.permitTTL??30),clearCredentialsOnWalletChange:n.clearCredentialsOnWalletChange??!0,transportKeyPairScope:n.transportKeyPairScope===void 0?void 0:y(Fe,n.transportKeyPairScope),registryTTL:y(Z,n.registryTTL??86400),logger:r,onEvent:n.onEvent,telemetry:l}}function _t(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=/* @__PURE__ */ new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;_t(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function vt(e){return new $(e)}var yt=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let t=this.walletAccount.getSnapshot();if(!t)throw new l(e);return t}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};export{A as _,pt as a,rt as c,M as d,P as f,pe as g,j as h,gt as i,Ie as l,F as m,$ as n,ht as o,N as p,vt as r,dt as s,yt as t,Ce as u,fe as v};
|
|
2
|
-
//# sourceMappingURL=base-signer-D8-tyO9l.js.map
|