@zama-fhe/sdk 3.5.1 → 3.5.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/ethers/index.cjs +1 -1
  4. package/dist/cjs/ethers/index.cjs.map +1 -1
  5. package/dist/cjs/fhevm-relayer.cjs +1 -1
  6. package/dist/cjs/index.cjs +1 -1
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/relayer.cjs +1 -1
  9. package/dist/cjs/relayer.cjs.map +1 -1
  10. package/dist/cjs/sdk-events.cjs +1 -1
  11. package/dist/cjs/sdk-events.cjs.map +1 -1
  12. package/dist/cjs/token.cjs +1 -1
  13. package/dist/cjs/viem/index.cjs +1 -1
  14. package/dist/esm/base-signer-BK-hbCF0.js +2 -0
  15. package/dist/esm/{base-signer-GatxEuGN.js.map → base-signer-BK-hbCF0.js.map} +1 -1
  16. package/dist/esm/{base-signer-DttMQOKx.d.ts → base-signer-Ds1OunIh.d.ts} +2 -2
  17. package/dist/esm/cleartext/index.d.ts +2 -2
  18. package/dist/esm/cleartext/index.js +1 -1
  19. package/dist/esm/{cleartext-BwzD7uJa.js → cleartext-B4_UCmwb.js} +2 -2
  20. package/dist/esm/{cleartext-BwzD7uJa.js.map → cleartext-B4_UCmwb.js.map} +1 -1
  21. package/dist/esm/{cleartext-Di1DDxqa.d.ts → cleartext-uK68IeOj.d.ts} +2 -2
  22. package/dist/esm/ethers/index.d.ts +3 -3
  23. package/dist/esm/ethers/index.js +1 -1
  24. package/dist/esm/ethers/index.js.map +1 -1
  25. package/dist/esm/{fhevm-relayer-CTwFyl0v.js → fhevm-relayer-b4VMx_9M.js} +2 -2
  26. package/dist/esm/{fhevm-relayer-CTwFyl0v.js.map → fhevm-relayer-b4VMx_9M.js.map} +1 -1
  27. package/dist/esm/{index-C4xKY5Fw.d.ts → index-BLbMNvb7.d.ts} +3 -3
  28. package/dist/esm/{index-COrLsVKC.d.ts → index-Cjzgb5qJ.d.ts} +5828 -4207
  29. package/dist/esm/index.d.ts +98 -7
  30. package/dist/esm/index.js +1 -1
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/node/index.d.ts +3 -3
  33. package/dist/esm/node/index.js +1 -1
  34. package/dist/esm/query/index.d.ts +3 -536
  35. package/dist/esm/query/index.js +1 -1
  36. package/dist/esm/{relayer-DC1OKWzW.js → relayer-_oKZItq7.js} +2 -2
  37. package/dist/esm/{relayer-DC1OKWzW.js.map → relayer-_oKZItq7.js.map} +1 -1
  38. package/dist/esm/sdk-events-Bxw_ZfyZ.js +2 -0
  39. package/dist/esm/sdk-events-Bxw_ZfyZ.js.map +1 -0
  40. package/dist/esm/{token-DOYtYc7P.js → token-DTHiLih_.js} +2 -2
  41. package/dist/esm/{token-DOYtYc7P.js.map → token-DTHiLih_.js.map} +1 -1
  42. package/dist/esm/{types-CuDiV0Wy.d.ts → types-D2Wc2kuN.d.ts} +4 -2
  43. package/dist/esm/{types-BxJzdNur.d.ts → types-DSLyoJuI.d.ts} +2 -2
  44. package/dist/esm/{types-BSRyQBTx.d.ts → types-kAGT-Vls.d.ts} +2 -2
  45. package/dist/esm/viem/index.d.ts +3 -3
  46. package/dist/esm/viem/index.js +1 -1
  47. package/dist/esm/web/index.d.ts +1 -1
  48. package/dist/esm/web/index.js +1 -1
  49. package/package.json +2 -2
  50. package/dist/esm/base-signer-GatxEuGN.js +0 -2
  51. package/dist/esm/sdk-events-B1sUunjZ.js +0 -2
  52. package/dist/esm/sdk-events-B1sUunjZ.js.map +0 -1
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../relayer.cjs"),t=require("../sdk-events.cjs"),n=require("../base-signer.cjs"),r=require("../assertions.cjs"),i=require("../eip1193-subscribe.cjs");let a=require("viem"),o=require("ethers");function s(e){return{to:e.address,data:(0,a.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function c(e,t){let n=await e.call(s(t));if(!(0,a.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,a.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function l(e,t){let n=await e.sendTransaction(s(t));if(!(0,a.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function u(e,n,r){return c(e,t.w(n,r))}function d(e,n){return c(e,t.F(n))}function f(e,n,r){return c(e,t.g(n,r))}function p(e,n,r,i,a){return l(e,t.D(n,r,i,a))}function m(e,n,r,i,a,o){return l(e,t.I(n,r,i,a,o))}function h(e,n,r,i,a){return l(e,t.L(n,r,i,a))}function g(e,n,r,i,a){return l(e,t.A(n,r,i,a))}function _(e,n,r,i){return l(e,t.P(n,r,i))}function v(e,n,r,i){return l(e,t.R(n,r,i))}function y(e,n){return c(e,t.o(n))}function b(e,n){return c(e,t.s(n))}function x(e,n,r,i){return c(e,t.c(n,r,i))}function S(e,n,r){return c(e,t.a(n,r))}function C(e,n,r){return c(e,t.r(n,r))}function w(e,n,r){return c(e,t.i(n,r))}function T(e,n,r){return c(e,t.l(n,r))}var E=class{#e;constructor(e){`ethereum`in e?this.#e=new o.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return c(this.#e,{address:e.address,abi:e.abi,functionName:e.functionName,args:e.args})}async getBlockTimestamp(){let t=await this.#e.getBlock(`latest`);if(!t)throw new e.t(`EthersProvider.getBlockTimestamp: failed to fetch latest block`);if(t.timestamp===null)throw new e.t(`EthersProvider.getBlockTimestamp: latest block has no timestamp`);return BigInt(t.timestamp)}async waitForTransactionReceipt(e){let n=await this.#e.waitForTransaction(e);if(!n)throw new t.G(`EthersProvider.waitForTransactionReceipt: no receipt found for tx ${e}. The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.`);return{logs:n.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}async prepareTransaction(n){let{from:i,calldata:a}=n,s=new o.ethers.Interface(a.abi),c=[];s.forEachFunction(e=>{e.name===a.functionName&&c.push(e)});let l=a.args.length,u=c.length===1?c[0]:c.find(e=>e.inputs.length===l);if(!u)throw Error(`Function ${a.functionName}(${l} args) not found in ABI`);let d=s.encodeFunctionData(u,a.args);r.n(d,`data`);let f=a.value??0n,p=this.#e.getNetwork(),m=n.nonce===void 0?this.#e.getTransactionCount(i,`pending`):Promise.resolve(n.nonce),h=n.gasLimit===void 0?a.gas??this.#e.estimateGas({from:i,to:a.address,data:d,value:f}).catch(e=>{throw new t.G(`EthersProvider.prepareTransaction: gas estimation reverted for ${a.functionName} on ${a.address}`,{cause:e})}):Promise.resolve(n.gasLimit),g=n.fees??this.#e.getFeeData(),[_,v,y,b]=await Promise.all([p,m,h,g]),x=b.maxFeePerGas,S=b.maxPriorityFeePerGas;if(x===null||S===null)throw new e.t(`EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). The connected chain may not support EIP-1559 type-2 transactions.`);return o.Transaction.from({type:2,chainId:Number(_.chainId),nonce:v,to:a.address,data:d,value:f,gasLimit:y,maxFeePerGas:x,maxPriorityFeePerGas:S}).unsignedSerialized}},D=class extends n.t{#e;#t;#n;#r;#i;constructor(e){super(),`ethereum`in e?(this.#e=new o.BrowserProvider(e.ethereum),this.#n=e.ethereum,this.#r=i.t({provider:e.ethereum,getInitialWalletAccount:()=>this.#l(),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}})):(this.#t=e.signer,this.#r=()=>{},t.z(`refresh wallet account`,async()=>{await this.refreshWalletAccount()}))}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n&&!this.walletAccount.isReady())throw new t.H(e);if(!n)throw new t.U(e);return n}refreshWalletAccount(){return this.#n?this.#c():this.#t?this.#s(this.#t):Promise.resolve(void 0)}onDispose(){this.#r()}async#a(){if(this.#t)return this.#t;if(!this.#e)throw new t.B(`resolveSigner`);return this.#e.getSigner()}async#o(e){let t=e.provider;if(!t)return;let[n,r]=await Promise.all([e.getAddress(),t.getNetwork()]);return{address:(0,a.getAddress)(n),chainId:Number(r.chainId)}}async signTypedData(e){let t=await this.#a(),{domain:n,types:r,message:i}=e,{EIP712Domain:o,...s}=r,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(n,c,i);if(!(0,a.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#a(),n=new o.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n.getFunction(e.functionName)(...e.args,r);if(!(0,a.isHex)(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async#s(e){return this.#i??=this.#o(e).then(e=>(this.walletAccount.setSnapshot(e),e)).finally(()=>{this.#i=void 0}),this.#i}async#c(){let e=await this.#l();return this.walletAccount.setSnapshot(e),e}async#l(){let e=this.#n;if(!e)return;let[t,n]=await Promise.all([e.request({method:`eth_accounts`}),e.request({method:`eth_chainId`})]);if(!Array.isArray(t)||typeof t[0]!=`string`)return;let r=Number(n);if(!(!Number.isSafeInteger(r)||r<=0))return{address:(0,a.getAddress)(t[0]),chainId:r}}};function O(e){if(`signer`in e&&e.signer){let t=new D({signer:e.signer});if(!e.signer.provider)throw Error(`createConfig requires a Signer with an attached provider for chain reads`);return n.i(t,new E({provider:e.signer.provider}),e)}return n.i(new D({ethereum:e.ethereum}),`provider`in e&&e.provider?new E({provider:e.provider}):new E({ethereum:e.ethereum}),e)}exports.BaseSigner=n.t,exports.EthersProvider=E,exports.EthersSigner=D,Object.defineProperty(exports,"ProviderRpcError",{enumerable:!0,get:function(){return a.ProviderRpcError}}),exports.ZamaSDKEvents=t.t,exports.createConfig=O,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../relayer.cjs"),t=require("../sdk-events.cjs"),n=require("../base-signer.cjs"),r=require("../assertions.cjs"),i=require("../eip1193-subscribe.cjs");let a=require("viem"),o=require("ethers");function s(e){return{to:e.address,data:(0,a.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function c(e,t){let n=await e.call(s(t));if(!(0,a.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,a.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function l(e,t){let n=await e.sendTransaction(s(t));if(!(0,a.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function u(e,n,r){return c(e,t.w(n,r))}function d(e,n){return c(e,t.F(n))}function f(e,n,r){return c(e,t.g(n,r))}function p(e,n,r,i,a){return l(e,t.D(n,r,i,a))}function m(e,n,r,i,a,o){return l(e,t.I(n,r,i,a,o))}function h(e,n,r,i,a){return l(e,t.L(n,r,i,a))}function g(e,n,r,i,a){return l(e,t.A(n,r,i,a))}function _(e,n,r,i){return l(e,t.P(n,r,i))}function v(e,n,r,i){return l(e,t.z(n,r,i))}function y(e,n){return c(e,t.o(n))}function b(e,n){return c(e,t.s(n))}function x(e,n,r,i){return c(e,t.c(n,r,i))}function S(e,n,r){return c(e,t.a(n,r))}function C(e,n,r){return c(e,t.r(n,r))}function w(e,n,r){return c(e,t.i(n,r))}function T(e,n,r){return c(e,t.l(n,r))}var E=class{#e;constructor(e){`ethereum`in e?this.#e=new o.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return c(this.#e,{address:e.address,abi:e.abi,functionName:e.functionName,args:e.args})}async getBlockTimestamp(){let t=await this.#e.getBlock(`latest`);if(!t)throw new e.t(`EthersProvider.getBlockTimestamp: failed to fetch latest block`);if(t.timestamp===null)throw new e.t(`EthersProvider.getBlockTimestamp: latest block has no timestamp`);return BigInt(t.timestamp)}async waitForTransactionReceipt(e){let n=await this.#e.waitForTransaction(e);if(!n)throw new t.K(`EthersProvider.waitForTransactionReceipt: no receipt found for tx ${e}. The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.`);return{logs:n.logs.map(e=>({address:e.address,topics:e.topics.filter(e=>e!==null),data:e.data}))}}async prepareTransaction(n){let{from:i,calldata:a}=n,s=new o.ethers.Interface(a.abi),c=[];s.forEachFunction(e=>{e.name===a.functionName&&c.push(e)});let l=a.args.length,u=c.length===1?c[0]:c.find(e=>e.inputs.length===l);if(!u)throw Error(`Function ${a.functionName}(${l} args) not found in ABI`);let d=s.encodeFunctionData(u,a.args);r.n(d,`data`);let f=a.value??0n,p=this.#e.getNetwork(),m=n.nonce===void 0?this.#e.getTransactionCount(i,`pending`):Promise.resolve(n.nonce),h=n.gasLimit===void 0?a.gas??this.#e.estimateGas({from:i,to:a.address,data:d,value:f}).catch(e=>{throw new t.K(`EthersProvider.prepareTransaction: gas estimation reverted for ${a.functionName} on ${a.address}`,{cause:e})}):Promise.resolve(n.gasLimit),g=n.fees??this.#e.getFeeData(),[_,v,y,b]=await Promise.all([p,m,h,g]),x=b.maxFeePerGas,S=b.maxPriorityFeePerGas;if(x===null||S===null)throw new e.t(`EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). The connected chain may not support EIP-1559 type-2 transactions.`);return o.Transaction.from({type:2,chainId:Number(_.chainId),nonce:v,to:a.address,data:d,value:f,gasLimit:y,maxFeePerGas:x,maxPriorityFeePerGas:S}).unsignedSerialized}},D=class extends n.t{#e;#t;#n;#r;#i;constructor(e){super(),`ethereum`in e?(this.#e=new o.BrowserProvider(e.ethereum),this.#n=e.ethereum,this.#r=i.t({provider:e.ethereum,getInitialWalletAccount:()=>this.#l(),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}})):(this.#t=e.signer,this.#r=()=>{},t.B(`refresh wallet account`,async()=>{await this.refreshWalletAccount()}))}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n&&!this.walletAccount.isReady())throw new t.U(e);if(!n)throw new t.W(e);return n}refreshWalletAccount(){return this.#n?this.#c():this.#t?this.#s(this.#t):Promise.resolve(void 0)}onDispose(){this.#r()}async#a(){if(this.#t)return this.#t;if(!this.#e)throw new t.V(`resolveSigner`);return this.#e.getSigner()}async#o(e){let t=e.provider;if(!t)return;let[n,r]=await Promise.all([e.getAddress(),t.getNetwork()]);return{address:(0,a.getAddress)(n),chainId:Number(r.chainId)}}async signTypedData(e){let t=await this.#a(),{domain:n,types:r,message:i}=e,{EIP712Domain:o,...s}=r,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(n,c,i);if(!(0,a.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#a(),n=new o.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n.getFunction(e.functionName)(...e.args,r);if(!(0,a.isHex)(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async#s(e){return this.#i??=this.#o(e).then(e=>(this.walletAccount.setSnapshot(e),e)).finally(()=>{this.#i=void 0}),this.#i}async#c(){let e=await this.#l();return this.walletAccount.setSnapshot(e),e}async#l(){let e=this.#n;if(!e)return;let[t,n]=await Promise.all([e.request({method:`eth_accounts`}),e.request({method:`eth_chainId`})]);if(!Array.isArray(t)||typeof t[0]!=`string`)return;let r=Number(n);if(!(!Number.isSafeInteger(r)||r<=0))return{address:(0,a.getAddress)(t[0]),chainId:r}}};function O(e){if(`signer`in e&&e.signer){let t=new D({signer:e.signer});if(!e.signer.provider)throw Error(`createConfig requires a Signer with an attached provider for chain reads`);return n.i(t,new E({provider:e.signer.provider}),e)}return n.i(new D({ethereum:e.ethereum}),`provider`in e&&e.provider?new E({provider:e.provider}):new E({ethereum:e.ethereum}),e)}exports.BaseSigner=n.t,exports.EthersProvider=E,exports.EthersSigner=D,Object.defineProperty(exports,"ProviderRpcError",{enumerable:!0,get:function(){return a.ProviderRpcError}}),exports.ZamaSDKEvents=t.t,exports.createConfig=O,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract","#readProvider","BrowserProvider","ConfigurationError","TransactionRevertedError","Transaction","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig"],"sources":["../../../src/ethers/contracts.ts","../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts"],"sourcesContent":["import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\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\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\n/** Minimal transaction request accepted by the ethers contract helpers. */\nexport interface EthersTransactionRequest {\n /** Target contract address. */\n to: Address;\n /** ABI-encoded call data. */\n data: Hex;\n /** Optional gas limit for the transaction. */\n gasLimit?: bigint;\n /** Optional native-token value to send with the call, in wei. */\n value?: bigint;\n}\n\n/** Minimal transaction response returned by an {@link EthersTransactionSigner}. */\nexport interface EthersTransactionResponse {\n /** Hash of the submitted transaction. */\n hash: string;\n}\n\n/** Minimal read-only ethers provider shape used by the read contract helpers. */\nexport interface EthersCallProvider {\n /** Performs an `eth_call` and resolves to the raw hex return data. */\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\n/** Minimal ethers signer shape used by the write contract helpers. */\nexport interface EthersTransactionSigner extends EthersCallProvider {\n /** Signs and broadcasts a transaction, resolving to the transaction response. */\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\n/**\n * Performs an `eth_call` through an ethers provider and decodes the result with viem, so every\n * ethers-backed read — the generic {@link EthersProvider.readContract} and the pre-built\n * `readXxxContract` helpers alike — produces viem-identical shapes (small ints as `number`, named\n * tuples as keyed objects, empty output as `undefined`). ethers is the transport only; viem owns\n * encoding and decoding.\n *\n * @internal\n */\nexport async function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via an ethers provider. */\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via an ethers provider. */\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via an ethers provider. */\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via an ethers signer. */\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\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 an ethers signer. */\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via an ethers signer. */\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via an ethers signer. */\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via an ethers signer. */\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via an ethers signer. */\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via an ethers provider. */\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via an ethers provider. */\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via an ethers provider. */\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via an ethers provider. */\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via an ethers provider. */\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via an ethers provider. */\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via an ethers provider. */\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n","import { ethers, BrowserProvider, Transaction } from \"ethers\";\nimport type {\n Abi,\n Address,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport { ConfigurationError, TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { assertHex } from \"../utils/assertions\";\nimport { ethersRead } from \"./contracts\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n /**\n * Execute a read-only call and return the decoded result.\n *\n * ethers is the transport only: the call goes out over `provider.call`, and viem does the\n * encoding and decoding (via {@link ethersRead}). That keeps the result identical to\n * `ViemProvider` — the return-type contract both providers implement — rather than re-deriving\n * viem's decoding rules (small ints as `number`, named tuples as keyed objects, empty output as\n * `undefined`) from ethers' own decoded values.\n */\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 return ethersRead(this.#readProvider, {\n address: config.address,\n abi: config.abi as readonly unknown[],\n functionName: config.functionName,\n args: config.args as readonly unknown[],\n });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: failed to fetch latest block\",\n );\n }\n if (block.timestamp === null) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: latest block has no timestamp\",\n );\n }\n return BigInt(block.timestamp);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new TransactionRevertedError(\n `EthersProvider.waitForTransactionReceipt: no receipt found for tx ${hash}. ` +\n \"The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.\",\n );\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\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 iface = new ethers.Interface(calldata.abi as unknown as ethers.InterfaceAbi);\n // Resolve overloaded ABI entries by name + arity. ethers'\n // `getFunction(key, values)` allows for an \"overrides\" object as the\n // last arg, so a 2-arg fragment still matches a 3-value call and\n // overloads like ERC-7984 `confidentialTransfer(address,bytes32)` vs\n // `confidentialTransfer(address,bytes32,bytes)` aren't disambiguated.\n const candidates: ethers.FunctionFragment[] = [];\n iface.forEachFunction((frag) => {\n if (frag.name === calldata.functionName) {\n candidates.push(frag);\n }\n });\n const argLength = (calldata.args as readonly unknown[]).length;\n const fragment =\n candidates.length === 1\n ? candidates[0]\n : candidates.find((frag) => frag.inputs.length === argLength);\n if (!fragment) {\n throw new Error(`Function ${calldata.functionName}(${argLength} args) not found in ABI`);\n }\n const data = iface.encodeFunctionData(fragment, calldata.args as readonly unknown[]);\n assertHex(data, \"data\");\n\n const value = calldata.value ?? 0n;\n // Wrap estimateGas — pre-flight revert is the high-value failure mode.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const networkPromise = this.#readProvider.getNetwork();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#readProvider.getTransactionCount(from, \"pending\");\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#readProvider\n .estimateGas({ from, to: calldata.address, data, value })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `EthersProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName as string} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feeDataPromise = args.fees ?? this.#readProvider.getFeeData();\n const [network, nonce, gasLimit, feeData] = await Promise.all([\n networkPromise,\n noncePromise,\n gasPromise,\n feeDataPromise,\n ]);\n const maxFeePerGas = feeData.maxFeePerGas;\n const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n if (maxFeePerGas === null || maxPriorityFeePerGas === null) {\n throw new ConfigurationError(\n \"EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). \" +\n \"The connected chain may not support EIP-1559 type-2 transactions.\",\n );\n }\n const tx = Transaction.from({\n type: 2,\n chainId: Number(network.chainId),\n nonce,\n to: calldata.address,\n data,\n value,\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n });\n return tx.unsignedSerialized as Hex;\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} 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 { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n /**\n * Return the connected wallet account, or throw {@link WalletAccountNotReadyError}\n * while the initial async lookup is pending, or {@link WalletNotConnectedError}\n * when no wallet is connected.\n */\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Re-fetch the wallet account from the provider or signer and update `walletAccount`. */\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\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 signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n"],"mappings":"mRAqEA,SAAS,EAAqB,EAA4D,CACxF,MAAO,CACL,GAAI,EAAO,QACX,MAAA,EAAA,EAAA,mBAAA,CAAyB,CACvB,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,KAAM,EAAO,IACf,CAAC,EACD,GAAI,EAAO,MAAQ,IAAA,GAAuC,CAAC,EAA5B,CAAE,SAAU,EAAO,GAAI,EACtD,GAAI,EAAO,QAAU,IAAA,GAAsC,CAAC,EAA3B,CAAE,MAAO,EAAO,KAAM,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CACvC,IAAM,EAAS,IAAI,EAAa,CAAE,OAAQ,EAAO,MAAO,CAAC,EACzD,GAAI,CAAC,EAAO,OAAO,SACjB,MAAU,MAAM,0EAA0E,EAG5F,OAAOe,EAAAA,EAAgB,EAAQ,IADV,EAAe,CAAE,SAAU,EAAO,OAAO,QAAS,CACjC,EAAG,CAAM,CACjD,CAOA,OAAOA,EAAAA,EAAgB,IALJ,EAAa,CAAE,SAAU,EAAO,QAAS,CAKhC,EAH1B,aAAc,GAAU,EAAO,SAC3B,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EAChD,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EACb,CAAM,CACjD"}
1
+ {"version":3,"file":"index.cjs","names":["confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract","#readProvider","BrowserProvider","ConfigurationError","TransactionRevertedError","Transaction","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig"],"sources":["../../../src/ethers/contracts.ts","../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts"],"sourcesContent":["import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\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\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\n/** Minimal transaction request accepted by the ethers contract helpers. */\nexport interface EthersTransactionRequest {\n /** Target contract address. */\n to: Address;\n /** ABI-encoded call data. */\n data: Hex;\n /** Optional gas limit for the transaction. */\n gasLimit?: bigint;\n /** Optional native-token value to send with the call, in wei. */\n value?: bigint;\n}\n\n/** Minimal transaction response returned by an {@link EthersTransactionSigner}. */\nexport interface EthersTransactionResponse {\n /** Hash of the submitted transaction. */\n hash: string;\n}\n\n/** Minimal read-only ethers provider shape used by the read contract helpers. */\nexport interface EthersCallProvider {\n /** Performs an `eth_call` and resolves to the raw hex return data. */\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\n/** Minimal ethers signer shape used by the write contract helpers. */\nexport interface EthersTransactionSigner extends EthersCallProvider {\n /** Signs and broadcasts a transaction, resolving to the transaction response. */\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\n/**\n * Performs an `eth_call` through an ethers provider and decodes the result with viem, so every\n * ethers-backed read — the generic {@link EthersProvider.readContract} and the pre-built\n * `readXxxContract` helpers alike — produces viem-identical shapes (small ints as `number`, named\n * tuples as keyed objects, empty output as `undefined`). ethers is the transport only; viem owns\n * encoding and decoding.\n *\n * @internal\n */\nexport async function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via an ethers provider. */\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via an ethers provider. */\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via an ethers provider. */\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via an ethers signer. */\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\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 an ethers signer. */\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via an ethers signer. */\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via an ethers signer. */\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via an ethers signer. */\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via an ethers signer. */\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via an ethers provider. */\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via an ethers provider. */\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via an ethers provider. */\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via an ethers provider. */\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via an ethers provider. */\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via an ethers provider. */\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via an ethers provider. */\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n","import { ethers, BrowserProvider, Transaction } from \"ethers\";\nimport type {\n Abi,\n Address,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport { ConfigurationError, TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { assertHex } from \"../utils/assertions\";\nimport { ethersRead } from \"./contracts\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n /**\n * Execute a read-only call and return the decoded result.\n *\n * ethers is the transport only: the call goes out over `provider.call`, and viem does the\n * encoding and decoding (via {@link ethersRead}). That keeps the result identical to\n * `ViemProvider` — the return-type contract both providers implement — rather than re-deriving\n * viem's decoding rules (small ints as `number`, named tuples as keyed objects, empty output as\n * `undefined`) from ethers' own decoded values.\n */\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 return ethersRead(this.#readProvider, {\n address: config.address,\n abi: config.abi as readonly unknown[],\n functionName: config.functionName,\n args: config.args as readonly unknown[],\n });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: failed to fetch latest block\",\n );\n }\n if (block.timestamp === null) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: latest block has no timestamp\",\n );\n }\n return BigInt(block.timestamp);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new TransactionRevertedError(\n `EthersProvider.waitForTransactionReceipt: no receipt found for tx ${hash}. ` +\n \"The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.\",\n );\n }\n return {\n logs: receipt.logs.map((log) => ({\n address: log.address as Hex,\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\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 iface = new ethers.Interface(calldata.abi as unknown as ethers.InterfaceAbi);\n // Resolve overloaded ABI entries by name + arity. ethers'\n // `getFunction(key, values)` allows for an \"overrides\" object as the\n // last arg, so a 2-arg fragment still matches a 3-value call and\n // overloads like ERC-7984 `confidentialTransfer(address,bytes32)` vs\n // `confidentialTransfer(address,bytes32,bytes)` aren't disambiguated.\n const candidates: ethers.FunctionFragment[] = [];\n iface.forEachFunction((frag) => {\n if (frag.name === calldata.functionName) {\n candidates.push(frag);\n }\n });\n const argLength = (calldata.args as readonly unknown[]).length;\n const fragment =\n candidates.length === 1\n ? candidates[0]\n : candidates.find((frag) => frag.inputs.length === argLength);\n if (!fragment) {\n throw new Error(`Function ${calldata.functionName}(${argLength} args) not found in ABI`);\n }\n const data = iface.encodeFunctionData(fragment, calldata.args as readonly unknown[]);\n assertHex(data, \"data\");\n\n const value = calldata.value ?? 0n;\n // Wrap estimateGas — pre-flight revert is the high-value failure mode.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const networkPromise = this.#readProvider.getNetwork();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#readProvider.getTransactionCount(from, \"pending\");\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#readProvider\n .estimateGas({ from, to: calldata.address, data, value })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `EthersProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName as string} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feeDataPromise = args.fees ?? this.#readProvider.getFeeData();\n const [network, nonce, gasLimit, feeData] = await Promise.all([\n networkPromise,\n noncePromise,\n gasPromise,\n feeDataPromise,\n ]);\n const maxFeePerGas = feeData.maxFeePerGas;\n const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n if (maxFeePerGas === null || maxPriorityFeePerGas === null) {\n throw new ConfigurationError(\n \"EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). \" +\n \"The connected chain may not support EIP-1559 type-2 transactions.\",\n );\n }\n const tx = Transaction.from({\n type: 2,\n chainId: Number(network.chainId),\n nonce,\n to: calldata.address,\n data,\n value,\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n });\n return tx.unsignedSerialized as Hex;\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} 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 { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n /**\n * Return the connected wallet account, or throw {@link WalletAccountNotReadyError}\n * while the initial async lookup is pending, or {@link WalletNotConnectedError}\n * when no wallet is connected.\n */\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Re-fetch the wallet account from the provider or signer and update `walletAccount`. */\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\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 signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n"],"mappings":"mRAqEA,SAAS,EAAqB,EAA4D,CACxF,MAAO,CACL,GAAI,EAAO,QACX,MAAA,EAAA,EAAA,mBAAA,CAAyB,CACvB,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,KAAM,EAAO,IACf,CAAC,EACD,GAAI,EAAO,MAAQ,IAAA,GAAuC,CAAC,EAA5B,CAAE,SAAU,EAAO,GAAI,EACtD,GAAI,EAAO,QAAU,IAAA,GAAsC,CAAC,EAA3B,CAAE,MAAO,EAAO,KAAM,CACzD,CACF,CAWA,eAAsB,EACpB,EACA,EACY,CACZ,IAAM,EAAO,MAAM,EAAS,KAAK,EAAqB,CAAM,CAAC,EAC7D,GAAI,EAAA,EAAA,EAAA,MAAA,CAAO,CAAI,EACb,MAAU,UAAU,6BAA6B,GAAM,EAEzD,OAAA,EAAA,EAAA,qBAAA,CAA4B,CAC1B,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,MACF,CAAC,CACH,CAEA,eAAe,EACb,EACA,EACc,CACd,IAAM,EAAK,MAAM,EAAO,gBAAgB,EAAqB,CAAM,CAAC,EACpE,GAAI,EAAA,EAAA,EAAA,MAAA,CAAO,EAAG,IAAI,EAChB,MA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AAS,CAAC,EACb,CAAM,CACjD"}
@@ -1,2 +1,2 @@
1
- const e=require("./relayer.cjs");let t=require("@fhevm/sdk/actions/base"),n=require("@fhevm/sdk/viem"),r=require("@fhevm/sdk/viem/cleartext"),i=require("viem");function a(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}var o=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:t,debug:o,batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}=e.options??{},d=this.#e.auth?s(this.#e.auth):void 0,f={publicClient:(0,i.createPublicClient)({transport:typeof this.#e.network==`string`?(0,i.http)(this.#e.network):(0,i.custom)(this.#e.network)}),chain:a(this.#e),options:{batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}};e.cleartext?(this.#t=(0,r.createFhevmCleartextBaseClient)(f),this.#n=(0,r.createFhevmCleartextDecryptClient)(f),this.#r=(0,r.createFhevmCleartextEncryptClient)(f)):(this.#t=(0,n.createFhevmBaseClient)(f),this.#n=(0,n.createFhevmDecryptClient)(f),this.#r=(0,n.createFhevmEncryptClient)(f)),this.#i={...d!==void 0&&{auth:d},...t!==void 0&&{timeout:t},...o!==void 0&&{debug:o}}}get chain(){return this.#e}#o=()=>(this.#a??=this.#t.fetchFheEncryptionKeyBytes({options:this.#i}).then(()=>this.#r.init()),this.#a);decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#o(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#o(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#o(),this.#r.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,t.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function s(t){let n=t.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:t.value,header:t.header};case`ApiKeyCookie`:return{type:n,value:t.value,cookie:t.cookie};case`BearerToken`:return{type:n,token:t.token};default:throw new e.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
1
+ const e=require("./relayer.cjs");let t=require("viem"),n=require("@fhevm/sdk/actions/base"),r=require("@fhevm/sdk/viem"),i=require("@fhevm/sdk/viem/cleartext");function a(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}var o=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:n,debug:o,batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}=e.options??{},d=this.#e.auth?s(this.#e.auth):void 0,f={publicClient:(0,t.createPublicClient)({transport:typeof this.#e.network==`string`?(0,t.http)(this.#e.network):(0,t.custom)(this.#e.network)}),chain:a(this.#e),options:{batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}};e.cleartext?(this.#t=(0,i.createFhevmCleartextBaseClient)(f),this.#n=(0,i.createFhevmCleartextDecryptClient)(f),this.#r=(0,i.createFhevmCleartextEncryptClient)(f)):(this.#t=(0,r.createFhevmBaseClient)(f),this.#n=(0,r.createFhevmDecryptClient)(f),this.#r=(0,r.createFhevmEncryptClient)(f)),this.#i={...d!==void 0&&{auth:d},...n!==void 0&&{timeout:n},...o!==void 0&&{debug:o}}}get chain(){return this.#e}#o=()=>(this.#a??=this.#t.fetchFheEncryptionKeyBytes({options:this.#i}).then(()=>this.#r.init()),this.#a);decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#o(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#o(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#o(),this.#r.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,n.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function s(t){let n=t.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:t.value,header:t.header};case`ApiKeyCookie`:return{type:n,value:t.value,cookie:t.cookie};case`BearerToken`:return{type:n,token:t.token};default:throw new e.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
2
  //# sourceMappingURL=fhevm-relayer.cjs.map
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},v=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const ee=[n._,t.Z,e.n,b,t.q,t.K,u,n.g,t.Y,t.et];function x(r,i,a={}){if(ee.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.Y(r.message,{cause:r});if(e.h(r))return new t.et(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new b(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e._(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.g(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.Z(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new b(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function te(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const ne=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function S(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}const C=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function w(e,t,n,r){return{address:e,abi:C,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function T(e,t,n){return{address:e,abi:C,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function re(e,t,n,r){return{address:e,abi:C,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function ie(e,t,n,r,i){return{address:e,abi:C,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const E=2n**64n-1n;function ae(e){return i.i(e.signer,e.provider,e)}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}function O(e){return(0,s.keccak256)((0,s.toBytes)(e))}const k={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function A(e){return(0,s.getAddress)(D(e.slice(-40)))}function j(e){return e}function M(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function N(e,t){return(0,s.getAddress)(D(M(e,t).slice(-40)))}function P(e,t){return BigInt(`0x`+M(e,t))}function F(e,t){return D(M(e,t))}function oe(e){return e.topics[0]!==k.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:j(e.topics[3])}}function I(e){return e.topics[0]!==k.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:F(e.data,1)}}function L(e){return e.topics[0]!==k.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0)}}function R(e){return e.topics[0]!==k.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0),cleartextAmount:P(e.data,1)}}function z(e){return oe(e)??I(e)??L(e)??R(e)}function se(e){let t=[];for(let n of e){let e=z(n);e&&t.push(e)}return t}function B(e){for(let t of e){let e=L(t);if(e)return e}return null}function ce(e){for(let t of e){let e=I(t);if(e)return e}return null}const le=[k.ConfidentialTransfer,k.Wrap,k.UnwrapRequested,k.UnwrapFinalized],V={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function H(e){return e.topics[0]!==V.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function U(e){return e.topics[0]!==V.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function W(e){return H(e)??U(e)}function ue(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function de(e){for(let t of e){let e=H(t);if(e)return e}return null}function fe(e){for(let t of e){let e=U(t);if(e)return e}return null}const pe=[V.DelegatedForUserDecryption,V.RevokedDelegationForUserDecryption];var G=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.W(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){await this.#a(`registerPermit`).registerPermit(e,t),await this.#o(e.signerAddress)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},K=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.W(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},q=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.W(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw x(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},J=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}},Y=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const me=new Y;function X(e){return`zama:pending-unshield:${i.d(e)}`}const he=c.z.union([c.z.pipe(i.p,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:i.p,unwrapRequestId:c.z.optional(i.p)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function ge(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _e(e,t){return(await ve(e,t))?.unwrapTxHash??null}async function ve(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=he.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ye(e,t){await e.delete(X(t))}var be=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.B(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#s(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.v(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:S(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#s(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e.v(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e.v(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.z(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.z(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.G(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);return this.#c(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){return _e(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=B(e);if(!n)throw new t.G(`No UnwrapRequested event found in unwrap receipt`);return n.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.z(`unshield: savePendingUnshield`,()=>ge(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.z(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.z(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.z(`unshield: clearPendingUnshield`,()=>ye(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const xe=c.z.union([c.z.bigint(),c.z.boolean(),i.f]),Se=c.z.array(c.z.string());var Ce=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=xe.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Se.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function we(e,t){let r=Te(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function Te(e,t){let n=i.d(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Ee=e=>new Promise(t=>setTimeout(t,e));var De=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,c))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof b))throw t;await Ee(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1,d;if(await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#d(e,n)}catch(r){if(n.l(r)){u=!0,d??=r;return}e.error=this.#f(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(t,n,r,i){let a=we(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a,o={spent:!1}){if(r.length===0)return{};let c=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),l={},u=[];for(let e of c)n.c(e.encryptedValue)?l[e.encryptedValue]=0n:u.push(e);if(u.length===0)return l;let d=Array.from(new Set(c.map(e=>e.contractAddress))),f=Array.from(new Set(u.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(f)}catch(t){throw e.g(t)?this.#u(t,`the delegation pre-check`):t}let p=[];for(let e of u){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?p.push(e):l[e.encryptedValue]=t}if(p.length===0)return l;let m=await this.#t.grantPermit(d,i.delegator),h=new Map;for(let e of p){let t=h.get(e.contractAddress);t?t.push(e.encryptedValue):h.set(e.contractAddress,[e.encryptedValue])}let g=[];for(let[e,t]of h)for(let r of n.s(t))g.push({contractAddress:e,encryptedValues:r});let _=Date.now(),v=p.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:v});try{await this.#c(i,m,g,l,a)}catch(e){if(!(e instanceof t.et)||o.spent)throw e;let n=m.permissions.map(e=>e.serializedPermit.signature);o.spent=!0;try{m=await this.#t.recoverPermits(d,i.delegator,n)}catch(e){throw e instanceof t.K?new t.et(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(i,m,g.filter(({encryptedValues:e})=>e.some(e=>l[e]===void 0)),l,a)}let e={};for(let t of v){let n=l[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-_,encryptedValues:v,result:e}),l}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e.v(r),durationMs:Date.now()-_,encryptedValues:v}),x(n,i.errorMessage,{isDelegated:i.delegator!==void 0})}}async#c(e,r,i,a,o){let s=(await n.r(i.map(({contractAddress:t,encryptedValues:n})=>async()=>{try{await this.#l(e,r,t,n,a,o);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(s.length>0)throw s.find(e=>e instanceof t.et)??s[0]}async#l(e,t,r,i,a,o){let s;try{s=await this.#o(t,r,i,o)}catch(t){throw x(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:r,account:e.delegator??e.requesterAddress})}for(let t=0;t<i.length;t++){let n=i[t],o=s[t]?.value;n!==void 0&&o!==void 0&&(a[n]=o,await this.#e.set(e.requesterAddress,r,n,o))}let c=i.filter(e=>a[e]===void 0);if(c.length>0)throw new n._(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${i.length} handle(s) on ${r}`,{cause:AggregateError(c.map(e=>new n._(`No clear value for handle ${e} on ${r}`)),`${c.length} handle(s) missing a clear value on ${r}`)})}#u(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#d(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#f(t,n,r){return t instanceof e.r?t:x(t,n,r)}#p(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Oe(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const Z={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new _(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new y(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function ke(e){return Object.hasOwn(Z,e)}function Ae(e,t){let n=Oe(e);if(n&&ke(n))return Z[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Z))if(r.includes(e))return n(t);return null}var je=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):E,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:w(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:T(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===E?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(re(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof t.G))return;let n=Ae(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Me=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e.v(n),durationMs:Date.now()-i},a),te(n,`Encryption failed`)}}},Ne=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.z(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.z(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.z(`wallet account listener`,()=>n(e),this.#i)))}};const Pe=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:i.f,token:i.f,to:i.f,amount:c.z.bigint()}),Fe=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:i.f,token:i.f,owner:i.f,to:i.f,amount:c.z.bigint()}),Ie=c.z.object({kind:c.z.literal(`SetOperator`),from:i.f,token:i.f,operator:i.f,until:i.m}),Le=c.z.object({kind:c.z.literal(`Unwrap`),from:i.f,token:i.f,to:i.f,amount:c.z.bigint()}),Re=c.z.object({kind:c.z.literal(`UnwrapAll`),from:i.f,token:i.f,to:i.f}),Q=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:i.f,wrapper:i.f,unwrapRequestIdOrAmount:i.p}),ze=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:i.f,underlying:i.f,spender:i.f,amount:c.z.bigint()}),Be=c.z.object({kind:c.z.literal(`Wrap`),from:i.f,wrapper:i.f,to:i.f,amount:c.z.bigint()}),Ve=i.p.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),He=c.z.object({kind:c.z.literal(`TransferAndCall`),from:i.f,underlying:i.f,wrapper:i.f,amount:c.z.bigint(),recipientData:c.z.optional(Ve)}),Ue=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:i.f,contractAddress:i.f,delegateAddress:i.f,expirationDate:c.z.optional(c.z.date())}),We=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:i.f,contractAddress:i.f,delegateAddress:i.f});c.z.discriminatedUnion(`kind`,[Pe,Fe,Ie,Le,Re,Q,ze,Be,He,Ue,We]);const Ge=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),$=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Ge)}),Ke=c.z.object({address:i.f,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),qe=c.z.extend($,{from:i.f,calldata:Ke});var Je=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.u($,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.u(qe,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.u(Pe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.u(Fe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.u(Ie,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.u(Le,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.u(Re,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.u(Q,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw x(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.u(ze,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.u(Be,e),t.R(e.wrapper,e.to,e.amount)}#f(e){return e=i.u(He,e),S(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.u(Ue,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):E;return w(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.u(We,e),T(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Ye(t){if(!(!Object.hasOwn(t,`transportKeyPairDerivationSecret`)||t.transportKeyPairDerivationSecret!==void 0))throw new e.t(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Xe(t){if(t===void 0)return;let{importScripts:n}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof n!=`function`))throw new e.t(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function Ze(e){if(e===void 0)return;let t=i.u(i.c,e);return new i.l(typeof t==`string`?t:new Uint8Array(t))}var Qe=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Ye(t),Xe(t.transportKeyPairDerivationSecret);let n=Ze(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Ce(e.storage,this.#i),this.#u=new je({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new De({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Me({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Ne({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Je({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new G({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new K({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new q({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new J(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new be(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=pe,exports.AclPausedError=v,exports.AclTopics=V,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=Y,exports.ConfigurationError=e.t,exports.Decryption=q,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=_,exports.DelegationCooldownError=f,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=y,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=b,exports.DelegationSelfNotAllowedError=d,exports.Delegations=K,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i._,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.Y,exports.KeyWrappingError=t.X,exports.MemoryStorage=i.h,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.Z,exports.NotEntitledError=u,exports.Offline=J,exports.Permits=G,exports.PreparedPermitChainMismatchError=t.Q,exports.PreparedPermitExpiredError=t.$,exports.RelayerRequestFailedError=e.n,exports.RevokedKmsContextError=t.et,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.B,exports.SignerRequiredError=t.V,exports.SigningFailedError=t.K,exports.SigningRejectedError=t.q,exports.TOKEN_TOPICS=le,exports.Token=n.t,exports.Topics=k,exports.TransactionRevertedError=t.G,exports.TransportKeyPairChangedError=t.tt,exports.TransportKeyPairExpiredError=t.nt,exports.WalletAccountNotReadyError=t.H,exports.WalletNotConnectedError=t.U,exports.WrappedToken=be,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Qe,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=me,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ae,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=W,exports.decodeAclEvents=ue,exports.decodeConfidentialTransfer=oe,exports.decodeDelegatedForUserDecryption=H,exports.decodeOnChainEvent=z,exports.decodeOnChainEvents=se,exports.decodeRevokedDelegationForUserDecryption=U,exports.decodeUnwrapFinalized=R,exports.decodeUnwrapRequested=L,exports.decodeWrap=I,exports.delegateForUserDecryptionContract=w,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=de,exports.findRevokedDelegationForUserDecryption=fe,exports.findUnwrapRequested=B,exports.findWrap=ce,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=re,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.v,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=ie,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.g,exports.nameContract=t.S,exports.polygon=a.c,exports.polygonAmoy=a.l,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=T,exports.sepolia=a.u,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=S,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},v=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function ee(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var x=class extends e.r{unwrapTxHash;unwrapRequestId;constructor(t,n,r){super(e.i.UnshieldAlreadyFinalized,t,r),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=n.unwrapTxHash,this.unwrapRequestId=n.unwrapRequestId}};const S=`InvalidUnwrapRequest`,te=(0,s.keccak256)((0,s.toBytes)(`${S}(bytes32)`)).slice(0,10);function ne(e){for(let t=e;t instanceof Error;t=t.cause)if(ee(t)===S||t.message.includes(S)||t.message.includes(te))return!0;return!1}const re=[n._,t.Q,e.n,b,t.J,t.q,u,n.g,t.X,t.tt];function C(r,i,a={}){if(re.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.X(r.message,{cause:r});if(e.h(r))return new t.tt(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new b(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e._(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.g(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.Q(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new b(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function ie(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const ae=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function w(e,t,n,r=`0x`){return{address:e,abi:ae,functionName:`transferAndCall`,args:[t,n,r]}}const T=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function E(e,t,n,r){return{address:e,abi:T,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function D(e,t,n){return{address:e,abi:T,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function oe(e,t,n,r){return{address:e,abi:T,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function se(e,t,n,r,i){return{address:e,abi:T,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const O=2n**64n-1n;function ce(e){return i.i(e.signer,e.provider,e)}function k(e){return e.startsWith(`0x`)?e:`0x${e}`}function A(e){return(0,s.keccak256)((0,s.toBytes)(e))}const j={ConfidentialTransfer:A(`ConfidentialTransfer(address,address,bytes32)`),Wrap:A(`Wrap(address,uint256,bytes32)`),UnwrapRequested:A(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:A(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function M(e){return(0,s.getAddress)(k(e.slice(-40)))}function N(e){return e}function P(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function le(e,t){return(0,s.getAddress)(k(P(e,t).slice(-40)))}function F(e,t){return BigInt(`0x`+P(e,t))}function I(e,t){return k(P(e,t))}function L(e){return e.topics[0]!==j.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:M(e.topics[1]),to:M(e.topics[2]),encryptedAmount:N(e.topics[3])}}function R(e){return e.topics[0]!==j.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:M(e.topics[1]),roundedAmount:F(e.data,0),encryptedWrappedAmount:I(e.data,1)}}function z(e){return e.topics[0]!==j.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:M(e.topics[1]),unwrapRequestId:N(e.topics[2]),encryptedAmount:I(e.data,0)}}function B(e){return e.topics[0]!==j.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:M(e.topics[1]),unwrapRequestId:N(e.topics[2]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}}function V(e){return L(e)??R(e)??z(e)??B(e)}function ue(e){let t=[];for(let n of e){let e=V(n);e&&t.push(e)}return t}function H(e){for(let t of e){let e=z(t);if(e)return e}return null}function de(e){for(let t of e){let e=R(t);if(e)return e}return null}const fe=[j.ConfidentialTransfer,j.Wrap,j.UnwrapRequested,j.UnwrapFinalized],U={DelegatedForUserDecryption:A(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:A(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function W(e){return e.topics[0]!==U.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:le(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function G(e){return e.topics[0]!==U.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:le(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function K(e){return W(e)??G(e)}function pe(e){let t=[];for(let n of e){let e=K(n);e&&t.push(e)}return t}function me(e){for(let t of e){let e=W(t);if(e)return e}return null}function he(e){for(let t of e){let e=G(t);if(e)return e}return null}const ge=[U.DelegatedForUserDecryption,U.RevokedDelegationForUserDecryption];var q=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.G(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){await this.#a(`registerPermit`).registerPermit(e,t),await this.#o(e.signerAddress)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.B(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},J=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.G(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},Y=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.G(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw C(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},_e=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}},ve=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const ye=new ve;function X(e){return`zama:pending-unshield:${i.d(e)}`}const be=c.z.union([c.z.pipe(i.p,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:i.p,unwrapRequestId:c.z.optional(i.p)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function xe(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Se(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=be.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Ce(e,t){await e.delete(X(t))}var we=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.V(e,{cause:n})}}async underlying(){return this.#u()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#u();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#u();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#u(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.v(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:w(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#u(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e.v(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e.v(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.z(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#f(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.z(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#u(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.B(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#d(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.B(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#d(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.K(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);if(await this.#s(a))throw await this.#l(`resumeUnshield`),new x(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:n,unwrapRequestId:a});return this.#d(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){let e=await Se(this.sdk.storage,this.address);return e?await this.#c(e)?(await this.#l(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=H(e.filter(e=>e.address===void 0||(0,s.getAddress)(e.address)===this.address));if(!n)throw new t.K(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return n.unwrapRequestId}async#s(e){try{return await this.sdk.provider.readContract(t.R(this.address,e))===s.zeroAddress}catch{return!1}}async#c(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#o(n.logs)}catch{return!1}return this.#s(t)}async#l(e){await t.B(`${e}: clearPendingUnshield`,()=>Ce(this.sdk.storage,this.address),this.sdk.logger)}async#u(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#d(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.B(`unshield: savePendingUnshield`,()=>xe(this.sdk.storage,this.address,n,e),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.B(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.finalizeUnwrap(e)}catch(t){throw ne(t)?(await this.#l(`unshield`),new x(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:n,unwrapRequestId:e},{cause:t})):t}return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.B(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#l(`unshield`),a}async#f(e,r,i){this.#r(`approveUnderlying`);let a=await this.#u(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const Te=c.z.union([c.z.bigint(),c.z.boolean(),i.f]),Ee=c.z.array(c.z.string());var De=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Te.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Ee.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function Oe(e,t){let r=ke(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function ke(e,t){let n=i.d(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Ae=e=>new Promise(t=>setTimeout(t,e));var je=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,c))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof b))throw t;await Ae(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1,d;if(await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#d(e,n)}catch(r){if(n.l(r)){u=!0,d??=r;return}e.error=this.#f(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(t,n,r,i){let a=Oe(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a,o={spent:!1}){if(r.length===0)return{};let c=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),l={},u=[];for(let e of c)n.c(e.encryptedValue)?l[e.encryptedValue]=0n:u.push(e);if(u.length===0)return l;let d=Array.from(new Set(c.map(e=>e.contractAddress))),f=Array.from(new Set(u.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(f)}catch(t){throw e.g(t)?this.#u(t,`the delegation pre-check`):t}let p=[];for(let e of u){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?p.push(e):l[e.encryptedValue]=t}if(p.length===0)return l;let m=await this.#t.grantPermit(d,i.delegator),h=new Map;for(let e of p){let t=h.get(e.contractAddress);t?t.push(e.encryptedValue):h.set(e.contractAddress,[e.encryptedValue])}let g=[];for(let[e,t]of h)for(let r of n.s(t))g.push({contractAddress:e,encryptedValues:r});let _=Date.now(),v=p.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:v});try{await this.#c(i,m,g,l,a)}catch(e){if(!(e instanceof t.tt)||o.spent)throw e;let n=m.permissions.map(e=>e.serializedPermit.signature);o.spent=!0;try{m=await this.#t.recoverPermits(d,i.delegator,n)}catch(e){throw e instanceof t.q?new t.tt(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(i,m,g.filter(({encryptedValues:e})=>e.some(e=>l[e]===void 0)),l,a)}let e={};for(let t of v){let n=l[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-_,encryptedValues:v,result:e}),l}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e.v(r),durationMs:Date.now()-_,encryptedValues:v}),C(n,i.errorMessage,{isDelegated:i.delegator!==void 0})}}async#c(e,r,i,a,o){let s=(await n.r(i.map(({contractAddress:t,encryptedValues:n})=>async()=>{try{await this.#l(e,r,t,n,a,o);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(s.length>0)throw s.find(e=>e instanceof t.tt)??s[0]}async#l(e,t,r,i,a,o){let s;try{s=await this.#o(t,r,i,o)}catch(t){throw C(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:r,account:e.delegator??e.requesterAddress})}for(let t=0;t<i.length;t++){let n=i[t],o=s[t]?.value;n!==void 0&&o!==void 0&&(a[n]=o,await this.#e.set(e.requesterAddress,r,n,o))}let c=i.filter(e=>a[e]===void 0);if(c.length>0)throw new n._(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${i.length} handle(s) on ${r}`,{cause:AggregateError(c.map(e=>new n._(`No clear value for handle ${e} on ${r}`)),`${c.length} handle(s) missing a clear value on ${r}`)})}#u(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#d(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#f(t,n,r){return t instanceof e.r?t:C(t,n,r)}#p(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const Z={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new _(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new y(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function Me(e){return Object.hasOwn(Z,e)}function Ne(e,t){let n=ee(e);if(n&&Me(n))return Z[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Z))if(r.includes(e))return n(t);return null}var Pe=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):O,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:E(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:D(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===O?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(oe(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof t.K))return;let n=Ne(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Fe=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e.v(n),durationMs:Date.now()-i},a),ie(n,`Encryption failed`)}}},Ie=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.B(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.B(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.B(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.B(`wallet account listener`,()=>n(e),this.#i)))}};const Le=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:i.f,token:i.f,to:i.f,amount:c.z.bigint()}),Re=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:i.f,token:i.f,owner:i.f,to:i.f,amount:c.z.bigint()}),ze=c.z.object({kind:c.z.literal(`SetOperator`),from:i.f,token:i.f,operator:i.f,until:i.m}),Be=c.z.object({kind:c.z.literal(`Unwrap`),from:i.f,token:i.f,to:i.f,amount:c.z.bigint()}),Ve=c.z.object({kind:c.z.literal(`UnwrapAll`),from:i.f,token:i.f,to:i.f}),He=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:i.f,wrapper:i.f,unwrapRequestIdOrAmount:i.p}),Q=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:i.f,underlying:i.f,spender:i.f,amount:c.z.bigint()}),Ue=c.z.object({kind:c.z.literal(`Wrap`),from:i.f,wrapper:i.f,to:i.f,amount:c.z.bigint()}),We=i.p.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),Ge=c.z.object({kind:c.z.literal(`TransferAndCall`),from:i.f,underlying:i.f,wrapper:i.f,amount:c.z.bigint(),recipientData:c.z.optional(We)}),Ke=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:i.f,contractAddress:i.f,delegateAddress:i.f,expirationDate:c.z.optional(c.z.date())}),qe=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:i.f,contractAddress:i.f,delegateAddress:i.f});c.z.discriminatedUnion(`kind`,[Le,Re,ze,Be,Ve,He,Q,Ue,Ge,Ke,qe]);const Je=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),$=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Je)}),Ye=c.z.object({address:i.f,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),Xe=c.z.extend($,{from:i.f,calldata:Ye});var Ze=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.u($,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.u(Xe,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.u(Le,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.u(Re,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.u(ze,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.u(Be,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.u(Ve,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.u(He,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw C(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.u(Q,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.u(Ue,e),t.z(e.wrapper,e.to,e.amount)}#f(e){return e=i.u(Ge,e),w(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.u(Ke,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):O;return E(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.u(qe,e),D(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Qe(t){if(!(!Object.hasOwn(t,`transportKeyPairDerivationSecret`)||t.transportKeyPairDerivationSecret!==void 0))throw new e.t(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function $e(t){if(t===void 0)return;let{importScripts:n}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof n!=`function`))throw new e.t(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function et(e){if(e===void 0)return;let t=i.u(i.c,e);return new i.l(typeof t==`string`?t:new Uint8Array(t))}var tt=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Qe(t),$e(t.transportKeyPairDerivationSecret);let n=et(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new De(e.storage,this.#i),this.#u=new Pe({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new je({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Fe({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Ie({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Ze({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new q({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new J({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new Y({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new _e(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new we(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=ge,exports.AclPausedError=v,exports.AclTopics=U,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=ve,exports.ConfigurationError=e.t,exports.Decryption=Y,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=_,exports.DelegationCooldownError=f,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=y,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=b,exports.DelegationSelfNotAllowedError=d,exports.Delegations=J,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i._,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.X,exports.KeyWrappingError=t.Z,exports.MemoryStorage=i.h,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.Q,exports.NotEntitledError=u,exports.Offline=_e,exports.Permits=q,exports.PreparedPermitChainMismatchError=t.$,exports.PreparedPermitExpiredError=t.et,exports.RelayerRequestFailedError=e.n,exports.RevokedKmsContextError=t.tt,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.V,exports.SignerRequiredError=t.H,exports.SigningFailedError=t.q,exports.SigningRejectedError=t.J,exports.TOKEN_TOPICS=fe,exports.Token=n.t,exports.Topics=j,exports.TransactionRevertedError=t.K,exports.TransportKeyPairChangedError=t.nt,exports.TransportKeyPairExpiredError=t.rt,exports.UnshieldAlreadyFinalizedError=x,exports.WalletAccountNotReadyError=t.U,exports.WalletNotConnectedError=t.W,exports.WrappedToken=we,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=tt,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=ye,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ce,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=K,exports.decodeAclEvents=pe,exports.decodeConfidentialTransfer=L,exports.decodeDelegatedForUserDecryption=W,exports.decodeOnChainEvent=V,exports.decodeOnChainEvents=ue,exports.decodeRevokedDelegationForUserDecryption=G,exports.decodeUnwrapFinalized=B,exports.decodeUnwrapRequested=z,exports.decodeWrap=R,exports.delegateForUserDecryptionContract=E,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=me,exports.findRevokedDelegationForUserDecryption=he,exports.findUnwrapRequested=H,exports.findWrap=de,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=oe,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.v,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=se,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.g,exports.nameContract=t.S,exports.polygon=a.c,exports.polygonAmoy=a.l,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=D,exports.sepolia=a.u,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=w,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.unwrapRequesterContract=t.R,exports.wrapContract=t.z;
2
2
  //# sourceMappingURL=index.cjs.map