@zama-fhe/sdk 3.9.1-beta.2 → 3.9.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/telemetry.cjs +1 -1
- package/dist/esm/base-signer-DUflPI8d.js +2 -0
- package/dist/esm/base-signer-DUflPI8d.js.map +1 -0
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-C0DXenyT.js → cleartext-Dt_G8a-Y.js} +2 -2
- package/dist/esm/{cleartext-C0DXenyT.js.map → cleartext-Dt_G8a-Y.js.map} +1 -1
- package/dist/esm/{decryption-BvvhpFM2.d.ts → decryption-CMNWWt0M.d.ts} +6 -3
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js → fhevm-relayer-BRF_qaSG.js} +2 -2
- package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js.map → fhevm-relayer-BRF_qaSG.js.map} +1 -1
- package/dist/esm/{index-B7M2GEtA.d.ts → index-Dh3aBqpo.d.ts} +1 -1
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/internal/index.d.ts +1 -1
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/query/index.d.ts +2 -2
- package/dist/esm/{telemetry-CW2RgPxb.js → telemetry-DgZG8yT6.js} +2 -2
- package/dist/esm/{telemetry-CW2RgPxb.js.map → telemetry-DgZG8yT6.js.map} +1 -1
- package/dist/esm/vaults/index.d.ts +1 -1
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/web/index.js +1 -1
- package/package.json +1 -1
- package/dist/esm/base-signer-CysprC2L.js +0 -2
- package/dist/esm/base-signer-CysprC2L.js.map +0 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./cleartext.cjs"),t=require("./base-signer.cjs"),n=require("./configs.cjs"),r=require("./alignment.cjs"),i=require("./public-decrypt.cjs"),a=require("./token.cjs"),o=require("./relayer.cjs"),s=require("./encryption.cjs"),c=require("./signing.cjs"),l=require("./fatal-batch.cjs"),u=require("./unshield.cjs"),d=require("./telemetry.cjs"),f=require("./validation.cjs"),p=require("./wrappers-registry.cjs");let m=require("viem"),h=require("zod/mini");function g(e,t){if(e instanceof o.r){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function _(e,t){if(e instanceof o.r)return e;let n=o.s(e),r=o._(e);return n!==void 0||o.g(e)?new o.n(e instanceof Error?e.message:t,n,{cause:e,retryAfter:o.c(e),retryable:r||void 0}):new s.r(t,{cause:e})}const v=[{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 y(e,t,n,r=`0x`){return{address:e,abi:v,functionName:`transferAndCall`,args:[t,n,r]}}const b=[{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 x(e,t,n,r){return{address:e,abi:b,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function S(e,t,n){return{address:e,abi:b,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function ee(e,t,n,r){return{address:e,abi:b,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function te(e,t,n,r,i){return{address:e,abi:b,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const C=2n**64n-1n,w=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ne(e){return t.i(e.signer,e.provider,e)}const T={ConfidentialTransfer:i.n(`ConfidentialTransfer(address,address,bytes32)`),Wrap:i.n(`Wrap(address,uint256,bytes32)`),UnwrapRequested:i.n(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:i.n(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function E(e){return e.topics[0]!==T.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:i.r(e.topics[1]),to:i.r(e.topics[2]),encryptedAmount:i.i(e.topics[3])}}function D(e){return e.topics[0]!==T.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:i.r(e.topics[1]),roundedAmount:i.o(e.data,0),encryptedWrappedAmount:i.s(e.data,1)}}function O(e){return e.topics[0]!==T.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:i.r(e.topics[1]),unwrapRequestId:i.i(e.topics[2]),encryptedAmount:i.s(e.data,0)}}function k(e){return e.topics[0]!==T.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:i.r(e.topics[1]),unwrapRequestId:i.i(e.topics[2]),encryptedAmount:i.s(e.data,0),cleartextAmount:i.o(e.data,1)}}function re(e){return E(e)??D(e)??O(e)??k(e)}function ie(e){let t=[];for(let n of e){let e=re(n);e&&t.push(e)}return t}function A(e){for(let t of e){let e=O(t);if(e)return e}return null}function ae(e){for(let t of e){let e=D(t);if(e)return e}return null}const oe=[T.ConfidentialTransfer,T.Wrap,T.UnwrapRequested,T.UnwrapFinalized],j={DelegatedForUserDecryption:i.n(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:i.n(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function M(e){return e.topics[0]!==j.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:i.r(e.topics[1]),delegate:i.r(e.topics[2]),contractAddress:i.a(e.data,0),delegationCounter:i.o(e.data,1),oldExpirationDate:i.o(e.data,2),newExpirationDate:i.o(e.data,3)}}function N(e){return e.topics[0]!==j.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:i.r(e.topics[1]),delegate:i.r(e.topics[2]),contractAddress:i.a(e.data,0),delegationCounter:i.o(e.data,1),oldExpirationDate:i.o(e.data,2)}}function P(e){return M(e)??N(e)}function se(e){let t=[];for(let n of e){let e=P(n);e&&t.push(e)}return t}function ce(e){for(let t of e){let e=M(t);if(e)return e}return null}function le(e){for(let t of e){let e=N(t);if(e)return e}return null}const ue=[j.DelegatedForUserDecryption,j.RevokedDelegationForUserDecryption];var F=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return r.K(this.#r,e)}#s(e,t){throw this.#a({type:r.B.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await r.n(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await r.n(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await r.t(`revokePermits`,this.#e,this.#t),i=(0,m.getAddress)(n.address);try{await t.revokePermits(e)}finally{await this.#c(i)}}async clear(){let e=this.#o(`clear`),t=await r.t(`clear`,this.#e,this.#t),n=(0,m.getAddress)(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await r.I(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},I=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return r.K(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.t(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.t(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{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)}},L=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 r.K(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),i=await r.t(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,i.address,d.r(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,i){let a=this.#i(`delegatedDecryptValues`),o=await r.t(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,n,d.r(i,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=d.r(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),i={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{r.z(t.clearValues[n],`result.clearValues[${n}]`),i[e]=t.clearValues[n].value}),{clearValues:i,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw i.c(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i,waitForPropagation:a,operation:o}){let s=this.#i(`delegatedBatchDecryptValues`),c=await r.t(`delegatedBatchDecryptValues`,this.#e,this.#t);return s.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:c.address,accountAddress:n,maxConcurrency:i,waitForPropagation:a,operation:o??`delegated-batch-decrypt-values`})}},R=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)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},z=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 de=new z;async function B(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function V(e){return`zama:pending-unshields:${t.d(e)}`}function H(e){return`zama:pending-unshield:${t.d(e)}`}function fe(e){return{version:2,unwrapTxHashes:e}}const pe=h.z.union([t.p,h.z.pipe(h.z.object({version:h.z.literal(1),unwrapTxHash:t.p}),h.z.transform(({unwrapTxHash:e})=>e))]),me=h.z.object({version:h.z.number(),unwrapTxHashes:h.z.optional(h.z.unknown())}),U=(e,t)=>e.toLowerCase()===t.toLowerCase();async function he(e,n,r){let i=await e.get(n);if(i==null)return{hashes:[],writable:!0};let a=me.safeParse(i);if(a.success&&a.data.version!==2)return r?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:a.data.version}),{hashes:[],writable:!1};let o=a.success?a.data.unwrapTxHashes:void 0;if(!Array.isArray(o))return r?.warn(`unreadable pending unshields were dropped`,{value:i}),{hashes:[],writable:!0};let s=o.filter(e=>t.p.safeParse(e).success);return s.length!==o.length&&r?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:o}),{hashes:s,writable:!0}}async function W(e,t,n){let r=await he(e,V(t),n),i=pe.safeParse(await e.get(H(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>U(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function ge(e,t,n){let r=V(t);await(n.length===0?e.delete(r):e.set(r,fe(n)))}const G=/* @__PURE__ */ new WeakMap;function K(e,t){let n=(G.get(e)??Promise.resolve()).then(t);return G.set(e,n.then(()=>{},()=>{})),n}function q(e,t,n,r){return K(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await W(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await ge(e,t,s),o&&await e.delete(H(t))})}async function _e(e,t,n){return(await K(e,()=>W(e,t,n))).hashes}function ve(e,t,n,r){return q(e,t,r,e=>e.some(e=>U(e,n))?e:[...e,n])}function ye(e,t,n,r){return q(e,t,r,e=>e.filter(e=>!U(e,n)))}function J(e,t){let n=(0,m.getAddress)(t);return A(e.filter(e=>e.address===void 0||(0,m.getAddress)(e.address)===n))?.unwrapRequestId}function Y(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:J(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var X=class extends a.t{#e;#t=null;#n=null;#r(e){try{return r.z(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new r.H(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(r.u(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(r.f(t,(0,m.getAddress)(e),this.address))}async shield(e,t){let n=await r.t(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),s=await this.#m(),c=(0,m.getAddress)(n.address),l;try{l=await this.sdk.provider.readContract(r.m(s,c))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:o.C(e)})}if(l<e)throw new a.p(`Insufficient ERC-20 balance: requested ${e}, available ${l} (token: ${s})`,{requested:e,available:l,token:s});return i?this.#i(e,s,c,t):this.#a(e,c,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,m.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:y(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await r.t(`wrap`,this.sdk.signer,this.sdk.provider),i=await this.#m(),s=(0,m.getAddress)(n.address),c;try{c=await this.sdk.provider.readContract(r.m(i,s))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 balance for wrap validation (token: ${i})`,{cause:o.C(e)})}if(c<e)throw new a.p(`Insufficient ERC-20 balance: requested ${e}, available ${c} (token: ${i})`,{requested:e,available:c,token:i});let l;try{l=await this.sdk.provider.readContract(r.f(i,s,this.address))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 allowance for wrap validation (token: ${i})`,{cause:o.C(e)})}if(l<e)throw new a.d(`Insufficient allowance for wrap: requested ${e}, approved ${l}. Call approveUnderlying() first (token: ${i}).`,{requested:e,available:l,token:i});let u=t?.to?(0,m.getAddress)(t.to):s;return this.submitTransaction({operation:`wrap`,config:r.F(this.address,u,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#g(e,i===`max`,n);let a=n?.to?(0,m.getAddress)(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:r.F(this.address,a,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await r.t(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),i=(0,m.getAddress)(t.address),a=e??2n**256n-1n;return a>0n&&await this.sdk.provider.readContract(r.f(n,i,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:r.p(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:r.p(n,this.address,a)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.#o(e,`unshield`,e=>this.#d(e));return r.I(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#h(l.unwrapRequestId,l.txHash,c,s,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return r.I(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await B(this.sdk.provider,e)}catch(e){throw e instanceof o.r?e:new r.X(`Failed to get unwrap receipt`,{cause:e})}let i=Y(n,this.address);if(i===`unknown`)throw new u.n(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(i===`settled`)throw await this.#p(`resumeUnshield`,e),new r.X(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:a}=i;if(await this.#u(a)===`settled`)throw await this.#p(`resumeUnshield`,e),new u.t(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:a});return await r.I(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(a,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await _e(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let i=await r.t(`unwrap`,this.sdk.signer,this.sdk.provider),a=(0,m.getAddress)(i.address),{encryptedValues:o,inputProof:c}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:a},{operation:t}),[l]=o;if(!l)throw new s.r(`Encryption returned no encrypted values`);let u=await this.submitTransaction({operation:`unwrap`,config:r.M(this.address,a,a,l,c),beforeReceipt:n});return{...u,unwrapRequestId:this.#l(u.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await r.t(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=(0,m.getAddress)(t.address),i=await this.readConfidentialBalanceOf(n);if(a.c(i))throw new s.t(`Cannot unshield: balance is zero`);let o=await this.submitTransaction({operation:`unwrapAll`,config:r.N(this.address,n,n,i),beforeReceipt:e});return{...o,unwrapRequestId:this.#l(o.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await r.n(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:a}=await i.t(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:r.T(this.address,e,n,a)})}#l(e){let t=J(e,this.address);if(t===void 0)throw new r.X(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(r.P(this.address,e))===m.zeroAddress?`settled`:`open`}catch{return`unknown`}}#d(e){return ve(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await B(this.sdk.provider,e)}catch{return`unknown`}let n=Y(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await r.I(`${e}: clearPendingUnshield`,()=>ye(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(r.A(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,i,a){this.emit({type:r.B.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:r.B.UnshieldPhase2Started,operationId:n}),r.I(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let o;try{o=await this.#c(e,a)}catch(n){throw u.r(n)||n instanceof r.X&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new u.t(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:r.B.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),r.I(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(o.txHash),this.sdk.logger),await this.#p(`unshield`,t),o}async#g(e,t,n){this.#r(`approveUnderlying`);let i=await this.#m(),a=await r.t(`approveUnderlying`,this.sdk.signer,this.sdk.provider),o=(0,m.getAddress)(a.address),s=await this.sdk.provider.readContract(r.f(i,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:r.p(i,this.address,0n)});let c=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:r.p(i,this.address,c),onSubmitted:n?.onApprovalSubmitted})}};const be=h.z.union([h.z.bigint(),h.z.boolean(),t.f]),xe=h.z.array(h.z.string());var Se=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=be.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,m.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,m.getAddress)(e)}:${(0,m.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=xe.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 Ce(e,t){let n=we(e,t);if(!n)throw new s.t(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function we(e,n){let r=t.d(n);return e.permissions.find(e=>e.contractAddresses.includes(r))}const Te=e=>new Promise(t=>setTimeout(t,e));var Ee=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,m.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,m.getAddress)(t),o=(0,m.getAddress)(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,m.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}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 i.S))throw t;await Te(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:o=!0,operation:s}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,m.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let u=(0,m.getAddress)(r);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,u,{waitForPropagation:o,operation:s});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(l.n(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,m.getAddress)(t)}),{items:c}}}let d=!1,f;if(await a.i(c.map(e=>async()=>{if(!d)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,u,{waitForPropagation:!1,operation:s});this.#d(e,r)}catch(n){if(l.n(n)){d=!0,f??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,m.getAddress)(t)})}}),i),f!==void 0)throw f;return{items:c}}async#o(e,t,n,r){let i=Ce(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&o.m(e.message)&&await this.#t.evictTransportKeyPair(),e}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:s,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,s={spent:!1}){if(e.length===0)return{};let l=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,m.getAddress)(e.contractAddress)})),u={},d=[];for(let e of l)a.c(e.encryptedValue)?u[e.encryptedValue]=0n:d.push(e);if(d.length===0)return u;let f=Array.from(new Set(l.map(e=>e.contractAddress))),p=Array.from(new Set(d.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(p)}catch(e){throw o.y(e)?this.#u(e,`the delegation pre-check`):e}let h=[];for(let e of d){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?h.push(e):u[e.encryptedValue]=n}if(h.length===0)return u;let g=await this.#t.grantPermit(f,t.delegator),_=/* @__PURE__ */ new Map;for(let e of h){let t=_.get(e.contractAddress);t?t.push(e.encryptedValue):_.set(e.contractAddress,[e.encryptedValue])}let v=[];for(let[e,t]of _)for(let n of a.s(t))v.push({contractAddress:e,encryptedValues:n});let y=Date.now(),b=h.map(e=>e.encryptedValue);try{this.#i({type:r.B.DecryptStart,encryptedValues:b});try{await this.#c(t,g,v,u,n)}catch(e){if(!(e instanceof c.l)||s.spent)throw e;let r=g.permissions.map(e=>e.serializedPermit.signature);s.spent=!0;try{g=await this.#t.recoverPermits(f,t.delegator,r)}catch(e){throw e instanceof c.t?new c.l(`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(t,g,v.filter(({encryptedValues:e})=>e.some(e=>u[e]===void 0)),u,n)}let e={};for(let t of b){let n=u[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.B.DecryptEnd,durationMs:Date.now()-y,encryptedValues:b,result:e}),u}catch(e){let n=e instanceof o.r&&e.cause instanceof Error?e.cause:e;throw this.#i({type:r.B.DecryptError,error:o.C(n),durationMs:Date.now()-y,encryptedValues:b}),i.c(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let o=(await a.i(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(o.length>0)throw o.find(e=>e instanceof c.l)??o[0]}async#l(e,t,n,r,a,o){let c;try{c=await this.#o(t,n,r,o)}catch(t){throw i.c(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let i=r[t],o=c[t]?.value;i!==void 0&&o!==void 0&&(a[i]=o,await this.#e.set(e.requesterAddress,n,i,o))}let l=r.filter(e=>a[e]===void 0);if(l.length>0)throw new s.t(`${e.errorMessage}: relayer returned no clear value for ${l.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(l.map(e=>new s.t(`No clear value for handle ${e} on ${n}`)),`${l.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new l.r(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:o.c(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new s.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof o.r?e:i.c(e,t,n)}#p(){throw new s.t(`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 i.h(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new i.m(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new i.p(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new i.C(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new i._(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new i.g(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new i.v(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new i.b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new i.x(`Cannot revoke: no active delegation exists.`,{cause:e})};function De(e){return Object.hasOwn(Z,e)}function Oe(e,t){let n=u.i(e);if(n&&De(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 ke=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:a}){if(a&&a.getTime()<Date.now()+36e5)throw new i.v(`Expiration date must be at least 1 hour in the future`);let o=(0,m.getAddress)(t),s=(0,m.getAddress)(n),c=(0,m.getAddress)(r);if(s===c)throw new i.C(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===(0,m.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new i.g(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(s===o)throw new i._(`Delegate address cannot be the same as the contract address (${o}).`);let l=this.#e.relayer.chain.aclContractAddress,u=a?BigInt(Math.floor(a.getTime()/1e3)):C,d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),d=-1n}if(d===u)throw new i.b(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return o!==(0,m.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:o,delegatorAddress:c,delegateAddress:s}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:o,config:x(l,s,o,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let a=(0,m.getAddress)(t),o=(0,m.getAddress)(n),s=(0,m.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new i.x(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:a,config:S(c,o,a)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=(0,m.getAddress)(e.contractAddress)===w,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:w})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:w});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==C}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===C?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(ee(r,(0,m.getAddress)(t),(0,m.getAddress)(n),(0,m.getAddress)(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await a.n({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof r.X))return;let t=Oe(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof i.x||t instanceof i.y){let n=(0,m.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,m.getAddress)(e),a=(0,m.getAddress)(t),o=(0,m.getAddress)(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:a,delegateAddress:o});if(!s)throw c===0n?new i.x(`No active delegation from ${a} to ${o} for ${r}`):new i.y(`Delegation from ${a} to ${o} for ${r} has expired`)}},Ae=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),i=(0,m.getAddress)(e.contractAddress);try{this.#t({type:r.B.EncryptStart},i);let a=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:r.B.EncryptEnd,durationMs:Date.now()-n},i),a}catch(e){throw this.#t({type:r.B.EncryptError,error:o.C(e),durationMs:Date.now()-n},i),_(e,`Encryption failed`)}}},je=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,i=n?.chainId;i!==void 0&&await r.I(`switch relayer chain`,()=>this.#t.switchChain(i),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>r.I(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await r.I(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await r.I(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const Q=h.z.object({kind:h.z.literal(`ConfidentialTransfer`),from:t.f,token:t.f,to:t.f,amount:h.z.bigint()}),Me=h.z.object({kind:h.z.literal(`ConfidentialTransferFrom`),from:t.f,token:t.f,owner:t.f,to:t.f,amount:h.z.bigint()}),Ne=h.z.object({kind:h.z.literal(`SetOperator`),from:t.f,token:t.f,operator:t.f,until:t.m}),Pe=h.z.object({kind:h.z.literal(`Unwrap`),from:t.f,token:t.f,to:t.f,amount:h.z.bigint()}),Fe=h.z.object({kind:h.z.literal(`UnwrapAll`),from:t.f,token:t.f,to:t.f}),Ie=h.z.object({kind:h.z.literal(`FinalizeUnwrap`),from:t.f,wrapper:t.f,unwrapRequestIdOrAmount:t.p}),Le=h.z.object({kind:h.z.literal(`ApproveUnderlying`),from:t.f,underlying:t.f,spender:t.f,amount:h.z.bigint()}),$=h.z.object({kind:h.z.literal(`Wrap`),from:t.f,wrapper:t.f,to:t.f,amount:h.z.bigint()}),Re=t.p.check(h.z.refine(e=>e===`0x`||(0,m.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`)),ze=h.z.object({kind:h.z.literal(`TransferAndCall`),from:t.f,underlying:t.f,wrapper:t.f,amount:h.z.bigint(),recipientData:h.z.optional(Re)}),Be=h.z.object({kind:h.z.literal(`DelegateDecryption`),from:t.f,contractAddress:t.f,delegateAddress:t.f,expirationDate:h.z.optional(h.z.date())}),Ve=h.z.object({kind:h.z.literal(`RevokeDelegation`),from:t.f,contractAddress:t.f,delegateAddress:t.f});h.z.discriminatedUnion(`kind`,[Q,Me,Ne,Pe,Fe,Ie,Le,$,ze,Be,Ve]);const He=h.z.strictObject({maxFeePerGas:h.z.bigint(),maxPriorityFeePerGas:h.z.bigint()}),Ue=h.z.object({nonce:h.z.optional(h.z.int().check(h.z.nonnegative())),gasLimit:h.z.optional(h.z.bigint()),fees:h.z.optional(He)}),We=h.z.object({address:t.f,abi:h.z.array(h.z.unknown()),functionName:h.z.string(),args:h.z.array(h.z.unknown()),value:h.z.optional(h.z.bigint()),gas:h.z.optional(h.z.bigint())}),Ge=h.z.extend(Ue,{from:t.f,calldata:We});var Ke=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=f.t(Ue,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new o.t(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},s=f.t(Ge,i),c=await this.#e.prepareTransaction(s).catch(t=>{throw a.r(t,`prepare ${e.kind}`)??t}),l=(0,m.parseTransaction)(c),u=(0,m.encodeFunctionData)({abi:s.calldata.abi,functionName:s.calldata.functionName,args:s.calldata.args});if(l.chainId!==r||!l.to||!(0,m.isAddressEqual)(l.to,s.calldata.address)||l.data?.toLowerCase()!==u.toLowerCase()||(l.value??0n)!==(s.calldata.value??0n))throw new o.t(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:c,from:s.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new o.t(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=f.t(Q,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for ConfidentialTransfer`);return r.S(e.token,e.to,i,n)}async#a(e){e=f.t(Me,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for ConfidentialTransferFrom`);return r.w(e.token,e.owner,e.to,i,n)}#o(e){return e=f.t(Ne,e),r.k(e.token,e.operator,e.until)}async#s(e){e=f.t(Pe,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for Unwrap`);return r.M(e.token,e.from,e.to,i,n)}async#c(e){e=f.t(Fe,e);let t=await this.#e.readContract(r.y(e.token,e.from));return r.N(e.token,e.from,e.to,t)}async#l(e){e=f.t(Ie,e);let{value:t,decryptionProof:n}=await i.t(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return r.T(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=f.t(Le,e),r.p(e.underlying,e.spender,e.amount)}#d(e){return e=f.t($,e),r.F(e.wrapper,e.to,e.amount)}#f(e){return e=f.t(ze,e),y(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=f.t(Be,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new i.v(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new i.C(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new i._(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):C;return x(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=f.t(Ve,e),S(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function qe(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new o.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 Je(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new o.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 Ye(e){if(e===void 0)return;let n=f.t(t.l,e);return new t.u(typeof n==`string`?n:new Uint8Array(n))}var Xe=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,n={}){qe(n),Je(n.transportKeyPairDerivationSecret);let r=Ye(n.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 Se(e.storage,this.#i),this.#u=new ke({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let i={};for(let t of e.chains)t.registryAddress&&(i[t.id]=t.registryAddress);this.registry=new t.o({provider:this.provider,registryAddresses:i,registryTTL:e.registryTTL}),this.#n=i,this.#t=e.registryTTL,this.#l=new t.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:r,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new Ee({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Ae({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new je({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Ke({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new F({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new I({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new L({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new R(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}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 t.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,d.r(t,`encrypt`))}createToken(e){return new a.t(this,e)}createWrappedToken(e){return new X(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=ue,exports.AclPausedError=i.p,exports.AclTopics=j,exports.BalanceCheckUnavailableError=a.l,exports.BaseSigner=t.t,exports.ChainMismatchError=r.q,exports.ChromeSessionStorage=z,exports.ConfigurationError=o.t,exports.Decryption=L,exports.DecryptionFailedError=s.t,exports.DefaultRegistryAddresses=t.a,exports.DelegationContractIsSelfError=i.m,exports.DelegationCooldownError=i.h,exports.DelegationDelegateCannotBeWildcardError=i.g,exports.DelegationDelegateEqualsContractError=i._,exports.DelegationExpirationTooSoonError=i.v,exports.DelegationExpiredError=i.y,exports.DelegationExpiryUnchangedError=i.b,exports.DelegationNotFoundError=i.x,exports.DelegationNotPropagatedError=i.S,exports.DelegationSelfNotAllowedError=i.C,exports.Delegations=I,exports.ERC1363_INTERFACE_ID=r.a,exports.ERC20ReadFailedError=a.u,exports.ERC7984_INTERFACE_ID=r.o,exports.ERC7984_WRAPPER_INTERFACE_ID=r.s,exports.EncryptOffloadUnavailableError=s.n,exports.EncryptionFailedError=s.r,exports.HcuBlockLimitExceededError=r.J,exports.HcuTransactionLimitExceededError=r.Y,exports.IndexedDBStorage=t._,exports.InsufficientAllowanceError=a.d,exports.InsufficientConfidentialBalanceError=a.f,exports.InsufficientERC20BalanceError=a.p,exports.InvalidTransportKeyPairError=c.i,exports.KeyWrappingError=c.a,exports.MAX_UINT64=C,exports.MemoryStorage=t.h,exports.MutableWalletAccountStore=t.n,exports.NoCiphertextError=c.o,exports.NotEntitledError=i.w,exports.Offline=R,exports.Permits=F,exports.PreparedPermitChainMismatchError=c.s,exports.PreparedPermitExpiredError=c.c,exports.RelayerRequestFailedError=o.n,exports.RevokedKmsContextError=c.l,exports.RpcRateLimitError=l.r,exports.SignerNotConfiguredError=r.H,exports.SignerRequiredError=r.U,exports.SigningFailedError=c.t,exports.SigningRejectedError=c.n,exports.TOKEN_TOPICS=oe,exports.Token=a.t,exports.Topics=T,exports.TransactionRevertedError=r.X,exports.TransportKeyPairChangedError=c.u,exports.TransportKeyPairExpiredError=c.d,exports.UnshieldAlreadyFinalizedError=u.t,exports.UnwrapNotMinedError=u.n,exports.VaultBatchNotDispatchedError=i.l,exports.VaultBatcherPausedError=i.u,exports.VaultBatcherReadFailedError=i.d,exports.VaultJoinUnconfirmedError=i.f,exports.WILDCARD_CONTRACT=w,exports.WalletAccountNotReadyError=r.W,exports.WalletNotConnectedError=r.G,exports.WrappedToken=X,exports.WrappersRegistry=t.o,exports.ZERO_ENCRYPTED_VALUE=a.o,exports.ZamaError=o.r,exports.ZamaErrorCode=o.i,exports.ZamaSDK=Xe,exports.ZamaSDKEvents=r.B,exports.allowanceContract=r.f,exports.anvil=n.t,exports.approveContract=r.p,exports.balanceOfContract=r.m,exports.bscTestnet=n.n,exports.chains=n.r,exports.chromeSessionStorage=de,exports.cleartext=e.t,exports.confidentialBalanceOfContract=r.y,exports.confidentialTotalSupplyContract=r.b,exports.confidentialTransferAndCallContract=r.x,exports.confidentialTransferContract=r.S,exports.confidentialTransferFromAndCallContract=r.C,exports.confidentialTransferFromContract=r.w,exports.createConfig=ne,exports.createWalletAccountStore=t.r,exports.decimalsContract=r.h,exports.decodeAclEvent=P,exports.decodeAclEvents=se,exports.decodeConfidentialTransfer=E,exports.decodeDelegatedForUserDecryption=M,exports.decodeOnChainEvent=re,exports.decodeOnChainEvents=ie,exports.decodeRevokedDelegationForUserDecryption=N,exports.decodeUnwrapFinalized=k,exports.decodeUnwrapRequested=O,exports.decodeWrap=D,exports.delegateForUserDecryptionContract=x,exports.finalizeUnwrapContract=r.T,exports.findDelegatedForUserDecryption=ce,exports.findRevokedDelegationForUserDecryption=le,exports.findUnwrapRequested=A,exports.findWrap=ae,exports.getConfidentialTokenAddressContract=p.t,exports.getDelegationExpiryContract=ee,exports.getTokenAddressContract=p.n,exports.getTokenPairContract=p.r,exports.getTokenPairsContract=p.i,exports.getTokenPairsLengthContract=p.a,exports.getTokenPairsSliceContract=p.o,exports.hardhat=n.i,exports.hoodi=n.a,exports.indexedDBStorage=t.v,exports.inferredTotalSupplyContract=r.E,exports.isConfidentialTokenContract=r.c,exports.isConfidentialTokenValidContract=p.s,exports.isConfidentialWrapperContract=r.l,exports.isEncryptedValueZero=a.c,exports.isHandleDelegatedContract=te,exports.isOperatorContract=r.D,exports.isRetryable=o.a,exports.mainnet=n.o,exports.matchZamaError=g,exports.memoryStorage=t.g,exports.nameContract=r._,exports.parsePreparedPermit=t.c,exports.polygon=n.s,exports.polygonAmoy=n.c,exports.rateContract=r.O,exports.retryAfterSeconds=o.o,exports.revokeDelegationContract=S,exports.sepolia=n.l,exports.setOperatorContract=r.k,exports.supportsInterfaceContract=r.d,exports.symbolContract=r.v,exports.transferAndCallContract=y,exports.underlyingContract=r.A,exports.unwrapAmountContract=r.j,exports.unwrapContract=r.M,exports.unwrapFromBalanceContract=r.N,exports.unwrapRequesterContract=r.P,exports.wrapContract=r.F,exports.zenithTrexTestnet=n.u;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./cleartext.cjs"),t=require("./base-signer.cjs"),n=require("./configs.cjs"),r=require("./alignment.cjs"),i=require("./public-decrypt.cjs"),a=require("./token.cjs"),o=require("./relayer.cjs"),s=require("./encryption.cjs"),c=require("./signing.cjs"),l=require("./fatal-batch.cjs"),u=require("./unshield.cjs"),d=require("./telemetry.cjs"),f=require("./validation.cjs"),p=require("./wrappers-registry.cjs");let m=require("viem"),h=require("zod/mini");function g(e,t){if(e instanceof o.r){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function _(e,t){if(e instanceof o.r)return e;let n=o.s(e),r=o._(e);return n!==void 0||o.g(e)?new o.n(e instanceof Error?e.message:t,n,{cause:e,retryAfter:o.c(e),retryable:r||void 0}):new s.r(t,{cause:e})}const v=[{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 y(e,t,n,r=`0x`){return{address:e,abi:v,functionName:`transferAndCall`,args:[t,n,r]}}const b=[{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 x(e,t,n,r){return{address:e,abi:b,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function S(e,t,n){return{address:e,abi:b,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function C(e,t,n,r){return{address:e,abi:b,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function ee(e,t,n,r,i){return{address:e,abi:b,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const w=2n**64n-1n,T=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function te(e){return t.i(e.signer,e.provider,e)}const E={ConfidentialTransfer:i.n(`ConfidentialTransfer(address,address,bytes32)`),Wrap:i.n(`Wrap(address,uint256,bytes32)`),UnwrapRequested:i.n(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:i.n(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function D(e){return e.topics[0]!==E.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:i.r(e.topics[1]),to:i.r(e.topics[2]),encryptedAmount:i.i(e.topics[3])}}function O(e){return e.topics[0]!==E.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:i.r(e.topics[1]),roundedAmount:i.o(e.data,0),encryptedWrappedAmount:i.s(e.data,1)}}function k(e){return e.topics[0]!==E.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:i.r(e.topics[1]),unwrapRequestId:i.i(e.topics[2]),encryptedAmount:i.s(e.data,0)}}function ne(e){return e.topics[0]!==E.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:i.r(e.topics[1]),unwrapRequestId:i.i(e.topics[2]),encryptedAmount:i.s(e.data,0),cleartextAmount:i.o(e.data,1)}}function re(e){return D(e)??O(e)??k(e)??ne(e)}function ie(e){let t=[];for(let n of e){let e=re(n);e&&t.push(e)}return t}function ae(e){for(let t of e){let e=k(t);if(e)return e}return null}function oe(e){for(let t of e){let e=O(t);if(e)return e}return null}const se=[E.ConfidentialTransfer,E.Wrap,E.UnwrapRequested,E.UnwrapFinalized],A={DelegatedForUserDecryption:i.n(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:i.n(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function j(e){return e.topics[0]!==A.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:i.r(e.topics[1]),delegate:i.r(e.topics[2]),contractAddress:i.a(e.data,0),delegationCounter:i.o(e.data,1),oldExpirationDate:i.o(e.data,2),newExpirationDate:i.o(e.data,3)}}function M(e){return e.topics[0]!==A.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:i.r(e.topics[1]),delegate:i.r(e.topics[2]),contractAddress:i.a(e.data,0),delegationCounter:i.o(e.data,1),oldExpirationDate:i.o(e.data,2)}}function N(e){return j(e)??M(e)}function ce(e){let t=[];for(let n of e){let e=N(n);e&&t.push(e)}return t}function le(e){for(let t of e){let e=j(t);if(e)return e}return null}function ue(e){for(let t of e){let e=M(t);if(e)return e}return null}const de=[A.DelegatedForUserDecryption,A.RevokedDelegationForUserDecryption];var P=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return r.K(this.#r,e)}#s(e,t){throw this.#a({type:r.B.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await r.n(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await r.n(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await r.t(`revokePermits`,this.#e,this.#t),i=(0,m.getAddress)(n.address);try{await t.revokePermits(e)}finally{await this.#c(i)}}async clear(){let e=this.#o(`clear`),t=await r.t(`clear`,this.#e,this.#t),n=(0,m.getAddress)(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await r.I(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},F=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return r.K(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.t(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.t(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{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)}},I=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 r.K(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),i=await r.t(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,i.address,d.r(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,i){let a=this.#i(`delegatedDecryptValues`),o=await r.t(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,n,d.r(i,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=d.r(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),i={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{r.z(t.clearValues[n],`result.clearValues[${n}]`),i[e]=t.clearValues[n].value}),{clearValues:i,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw i.c(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i,waitForPropagation:a,operation:o}){let s=this.#i(`delegatedBatchDecryptValues`),c=await r.t(`delegatedBatchDecryptValues`,this.#e,this.#t);return s.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:c.address,accountAddress:n,maxConcurrency:i,waitForPropagation:a,operation:o??`delegated-batch-decrypt-values`})}},L=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)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},R=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 fe=new R;async function z(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function B(e){return`zama:pending-unshields:${t.f(e)}`}function V(e){return`zama:pending-unshield:${t.f(e)}`}function pe(e){return{version:2,unwrapTxHashes:e}}const me=h.z.union([t.m,h.z.pipe(h.z.object({version:h.z.literal(1),unwrapTxHash:t.m}),h.z.transform(({unwrapTxHash:e})=>e))]),he=h.z.object({version:h.z.number(),unwrapTxHashes:h.z.optional(h.z.unknown())}),H=(e,t)=>e.toLowerCase()===t.toLowerCase();async function ge(e,n,r){let i=await e.get(n);if(i==null)return{hashes:[],writable:!0};let a=he.safeParse(i);if(a.success&&a.data.version!==2)return r?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:a.data.version}),{hashes:[],writable:!1};let o=a.success?a.data.unwrapTxHashes:void 0;if(!Array.isArray(o))return r?.warn(`unreadable pending unshields were dropped`,{value:i}),{hashes:[],writable:!0};let s=o.filter(e=>t.m.safeParse(e).success);return s.length!==o.length&&r?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:o}),{hashes:s,writable:!0}}async function U(e,t,n){let r=await ge(e,B(t),n),i=me.safeParse(await e.get(V(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>H(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function _e(e,t,n){let r=B(t);await(n.length===0?e.delete(r):e.set(r,pe(n)))}const W=/* @__PURE__ */ new WeakMap;function G(e,t){let n=(W.get(e)??Promise.resolve()).then(t);return W.set(e,n.then(()=>{},()=>{})),n}function K(e,t,n,r){return G(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await U(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await _e(e,t,s),o&&await e.delete(V(t))})}async function ve(e,t,n){return(await G(e,()=>U(e,t,n))).hashes}function ye(e,t,n,r){return K(e,t,r,e=>e.some(e=>H(e,n))?e:[...e,n])}function be(e,t,n,r){return K(e,t,r,e=>e.filter(e=>!H(e,n)))}function q(e,t){let n=(0,m.getAddress)(t);return ae(e.filter(e=>e.address===void 0||(0,m.getAddress)(e.address)===n))?.unwrapRequestId}function J(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:q(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Y=class extends a.t{#e;#t=null;#n=null;#r(e){try{return r.z(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new r.H(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(r.u(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(r.f(t,(0,m.getAddress)(e),this.address))}async shield(e,t){let n=await r.t(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),s=await this.#m(),c=(0,m.getAddress)(n.address),l;try{l=await this.sdk.provider.readContract(r.m(s,c))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:o.C(e)})}if(l<e)throw new a.p(`Insufficient ERC-20 balance: requested ${e}, available ${l} (token: ${s})`,{requested:e,available:l,token:s});return i?this.#i(e,s,c,t):this.#a(e,c,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,m.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:y(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await r.t(`wrap`,this.sdk.signer,this.sdk.provider),i=await this.#m(),s=(0,m.getAddress)(n.address),c;try{c=await this.sdk.provider.readContract(r.m(i,s))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 balance for wrap validation (token: ${i})`,{cause:o.C(e)})}if(c<e)throw new a.p(`Insufficient ERC-20 balance: requested ${e}, available ${c} (token: ${i})`,{requested:e,available:c,token:i});let l;try{l=await this.sdk.provider.readContract(r.f(i,s,this.address))}catch(e){throw e instanceof o.r?e:new a.u(`Could not read ERC-20 allowance for wrap validation (token: ${i})`,{cause:o.C(e)})}if(l<e)throw new a.d(`Insufficient allowance for wrap: requested ${e}, approved ${l}. Call approveUnderlying() first (token: ${i}).`,{requested:e,available:l,token:i});let u=t?.to?(0,m.getAddress)(t.to):s;return this.submitTransaction({operation:`wrap`,config:r.F(this.address,u,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#g(e,i===`max`,n);let a=n?.to?(0,m.getAddress)(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:r.F(this.address,a,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await r.t(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),i=(0,m.getAddress)(t.address),a=e??2n**256n-1n;return a>0n&&await this.sdk.provider.readContract(r.f(n,i,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:r.p(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:r.p(n,this.address,a)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.#o(e,`unshield`,e=>this.#d(e));return r.I(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#h(l.unwrapRequestId,l.txHash,c,s,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return r.I(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await z(this.sdk.provider,e)}catch(e){throw e instanceof o.r?e:new r.X(`Failed to get unwrap receipt`,{cause:e})}let i=J(n,this.address);if(i===`unknown`)throw new u.n(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(i===`settled`)throw await this.#p(`resumeUnshield`,e),new r.X(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:a}=i;if(await this.#u(a)===`settled`)throw await this.#p(`resumeUnshield`,e),new u.t(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:a});return await r.I(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(a,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await ve(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let i=await r.t(`unwrap`,this.sdk.signer,this.sdk.provider),a=(0,m.getAddress)(i.address),{encryptedValues:o,inputProof:c}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:a},{operation:t}),[l]=o;if(!l)throw new s.r(`Encryption returned no encrypted values`);let u=await this.submitTransaction({operation:`unwrap`,config:r.M(this.address,a,a,l,c),beforeReceipt:n});return{...u,unwrapRequestId:this.#l(u.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await r.t(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=(0,m.getAddress)(t.address),i=await this.readConfidentialBalanceOf(n);if(a.c(i))throw new s.t(`Cannot unshield: balance is zero`);let o=await this.submitTransaction({operation:`unwrapAll`,config:r.N(this.address,n,n,i),beforeReceipt:e});return{...o,unwrapRequestId:this.#l(o.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await r.n(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:a}=await i.t(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:r.T(this.address,e,n,a)})}#l(e){let t=q(e,this.address);if(t===void 0)throw new r.X(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(r.P(this.address,e))===m.zeroAddress?`settled`:`open`}catch{return`unknown`}}#d(e){return ye(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await z(this.sdk.provider,e)}catch{return`unknown`}let n=J(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await r.I(`${e}: clearPendingUnshield`,()=>be(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(r.A(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,i,a){this.emit({type:r.B.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:r.B.UnshieldPhase2Started,operationId:n}),r.I(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let o;try{o=await this.#c(e,a)}catch(n){throw u.r(n)||n instanceof r.X&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new u.t(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:r.B.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),r.I(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(o.txHash),this.sdk.logger),await this.#p(`unshield`,t),o}async#g(e,t,n){this.#r(`approveUnderlying`);let i=await this.#m(),a=await r.t(`approveUnderlying`,this.sdk.signer,this.sdk.provider),o=(0,m.getAddress)(a.address),s=await this.sdk.provider.readContract(r.f(i,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:r.p(i,this.address,0n)});let c=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:r.p(i,this.address,c),onSubmitted:n?.onApprovalSubmitted})}};const X=h.z.union([h.z.bigint(),h.z.boolean(),t.p]),xe=h.z.object({value:X,tag:t.m}),Se=h.z.array(h.z.string()),Ce={encode:async(e,t)=>t,decode:async(e,t)=>X.safeParse(t).data??null};function we(e,t){return new TextEncoder().encode(JSON.stringify([e,typeof t,String(t)]))}function Te(e){let n,r=()=>n??=t.d(e);return{async encode(e,t){let n=await crypto.subtle.sign(`HMAC`,await r(),we(e,t));return{value:t,tag:(0,m.toHex)(new Uint8Array(n))}},async decode(e,t){let n=xe.safeParse(t);if(!n.success)return null;let{value:i,tag:a}=n.data;return await crypto.subtle.verify(`HMAC`,await r(),new Uint8Array((0,m.toBytes)(a)),we(e,i))?i:null}}}var Ee=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i;#a=Promise.resolve();constructor(e,t,n){this.#e=e,this.#t=t,this.#i=n?Te(n):Ce}async get(e,t,n){try{let r=this.#l(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=await this.#i.decode(r,i);return a===null&&await this.delete(e,t,n),a}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#l(e,t,n);await this.#e.set(i,await this.#i.encode(i,X.parse(r))),this.#a=this.#a.then(()=>this.#d(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#a}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#l(e,t,n);this.#a=this.#a.then(()=>this.#o(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#a}async clearForRequester(e){this.#a=this.#a.then(()=>this.#s(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#a}async clearAll(){this.#a=this.#a.then(()=>this.#c().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#a}async#o(e){await this.#e.delete(e).catch(()=>{});let t=await this.#u(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#s(e){let t=(0,m.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#u(),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#c(){let e=await this.#u();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#l(e,t,n){return`${this.#n}:${(0,m.getAddress)(e)}:${(0,m.getAddress)(t)}:${n.toLowerCase()}`}async#u(){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#d(e){let t=await this.#u();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function De(e,t){let n=Oe(e,t);if(!n)throw new s.t(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function Oe(e,n){let r=t.f(n);return e.permissions.find(e=>e.contractAddresses.includes(r))}const ke=e=>new Promise(t=>setTimeout(t,e));var Ae=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,m.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,m.getAddress)(t),o=(0,m.getAddress)(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,m.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}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 i.S))throw t;await ke(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:o=!0,operation:s}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,m.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let u=(0,m.getAddress)(r);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,u,{waitForPropagation:o,operation:s});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(l.n(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,m.getAddress)(t)}),{items:c}}}let d=!1,f;if(await a.i(c.map(e=>async()=>{if(!d)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,u,{waitForPropagation:!1,operation:s});this.#d(e,r)}catch(n){if(l.n(n)){d=!0,f??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,m.getAddress)(t)})}}),i),f!==void 0)throw f;return{items:c}}async#o(e,t,n,r){let i=De(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&o.m(e.message)&&await this.#t.evictTransportKeyPair(),e}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:s,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,s={spent:!1}){if(e.length===0)return{};let l=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,m.getAddress)(e.contractAddress)})),u={},d=[];for(let e of l)a.c(e.encryptedValue)?u[e.encryptedValue]=0n:d.push(e);if(d.length===0)return u;let f=Array.from(new Set(l.map(e=>e.contractAddress))),p=Array.from(new Set(d.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(p)}catch(e){throw o.y(e)?this.#u(e,`the delegation pre-check`):e}let h=[];for(let e of d){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?h.push(e):u[e.encryptedValue]=n}if(h.length===0)return u;let g=await this.#t.grantPermit(f,t.delegator),_=/* @__PURE__ */ new Map;for(let e of h){let t=_.get(e.contractAddress);t?t.push(e.encryptedValue):_.set(e.contractAddress,[e.encryptedValue])}let v=[];for(let[e,t]of _)for(let n of a.s(t))v.push({contractAddress:e,encryptedValues:n});let y=Date.now(),b=h.map(e=>e.encryptedValue);try{this.#i({type:r.B.DecryptStart,encryptedValues:b});try{await this.#c(t,g,v,u,n)}catch(e){if(!(e instanceof c.l)||s.spent)throw e;let r=g.permissions.map(e=>e.serializedPermit.signature);s.spent=!0;try{g=await this.#t.recoverPermits(f,t.delegator,r)}catch(e){throw e instanceof c.t?new c.l(`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(t,g,v.filter(({encryptedValues:e})=>e.some(e=>u[e]===void 0)),u,n)}let e={};for(let t of b){let n=u[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.B.DecryptEnd,durationMs:Date.now()-y,encryptedValues:b,result:e}),u}catch(e){let n=e instanceof o.r&&e.cause instanceof Error?e.cause:e;throw this.#i({type:r.B.DecryptError,error:o.C(n),durationMs:Date.now()-y,encryptedValues:b}),i.c(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let o=(await a.i(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(o.length>0)throw o.find(e=>e instanceof c.l)??o[0]}async#l(e,t,n,r,a,o){let c;try{c=await this.#o(t,n,r,o)}catch(t){throw i.c(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let i=r[t],o=c[t]?.value;i!==void 0&&o!==void 0&&(a[i]=o,await this.#e.set(e.requesterAddress,n,i,o))}let l=r.filter(e=>a[e]===void 0);if(l.length>0)throw new s.t(`${e.errorMessage}: relayer returned no clear value for ${l.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(l.map(e=>new s.t(`No clear value for handle ${e} on ${n}`)),`${l.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new l.r(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:o.c(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new s.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof o.r?e:i.c(e,t,n)}#p(){throw new s.t(`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 i.h(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new i.m(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new i.p(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new i.C(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new i._(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new i.g(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new i.v(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new i.b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new i.x(`Cannot revoke: no active delegation exists.`,{cause:e})};function je(e){return Object.hasOwn(Z,e)}function Me(e,t){let n=u.i(e);if(n&&je(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 Ne=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:a}){if(a&&a.getTime()<Date.now()+36e5)throw new i.v(`Expiration date must be at least 1 hour in the future`);let o=(0,m.getAddress)(t),s=(0,m.getAddress)(n),c=(0,m.getAddress)(r);if(s===c)throw new i.C(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===(0,m.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new i.g(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(s===o)throw new i._(`Delegate address cannot be the same as the contract address (${o}).`);let l=this.#e.relayer.chain.aclContractAddress,u=a?BigInt(Math.floor(a.getTime()/1e3)):w,d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),d=-1n}if(d===u)throw new i.b(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return o!==(0,m.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:o,delegatorAddress:c,delegateAddress:s}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:o,config:x(l,s,o,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let a=(0,m.getAddress)(t),o=(0,m.getAddress)(n),s=(0,m.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new i.x(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:a,config:S(c,o,a)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=(0,m.getAddress)(e.contractAddress)===T,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:T})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:T});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==w}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===w?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(C(r,(0,m.getAddress)(t),(0,m.getAddress)(n),(0,m.getAddress)(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await a.n({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof r.X))return;let t=Me(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof i.x||t instanceof i.y){let n=(0,m.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,m.getAddress)(e),a=(0,m.getAddress)(t),o=(0,m.getAddress)(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:a,delegateAddress:o});if(!s)throw c===0n?new i.x(`No active delegation from ${a} to ${o} for ${r}`):new i.y(`Delegation from ${a} to ${o} for ${r} has expired`)}},Pe=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),i=(0,m.getAddress)(e.contractAddress);try{this.#t({type:r.B.EncryptStart},i);let a=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:r.B.EncryptEnd,durationMs:Date.now()-n},i),a}catch(e){throw this.#t({type:r.B.EncryptError,error:o.C(e),durationMs:Date.now()-n},i),_(e,`Encryption failed`)}}},Fe=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,i=n?.chainId;i!==void 0&&await r.I(`switch relayer chain`,()=>this.#t.switchChain(i),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>r.I(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await r.I(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await r.I(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const Ie=h.z.object({kind:h.z.literal(`ConfidentialTransfer`),from:t.p,token:t.p,to:t.p,amount:h.z.bigint()}),Le=h.z.object({kind:h.z.literal(`ConfidentialTransferFrom`),from:t.p,token:t.p,owner:t.p,to:t.p,amount:h.z.bigint()}),Re=h.z.object({kind:h.z.literal(`SetOperator`),from:t.p,token:t.p,operator:t.p,until:t.h}),ze=h.z.object({kind:h.z.literal(`Unwrap`),from:t.p,token:t.p,to:t.p,amount:h.z.bigint()}),Be=h.z.object({kind:h.z.literal(`UnwrapAll`),from:t.p,token:t.p,to:t.p}),Ve=h.z.object({kind:h.z.literal(`FinalizeUnwrap`),from:t.p,wrapper:t.p,unwrapRequestIdOrAmount:t.m}),He=h.z.object({kind:h.z.literal(`ApproveUnderlying`),from:t.p,underlying:t.p,spender:t.p,amount:h.z.bigint()}),Q=h.z.object({kind:h.z.literal(`Wrap`),from:t.p,wrapper:t.p,to:t.p,amount:h.z.bigint()}),Ue=t.m.check(h.z.refine(e=>e===`0x`||(0,m.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`)),We=h.z.object({kind:h.z.literal(`TransferAndCall`),from:t.p,underlying:t.p,wrapper:t.p,amount:h.z.bigint(),recipientData:h.z.optional(Ue)}),Ge=h.z.object({kind:h.z.literal(`DelegateDecryption`),from:t.p,contractAddress:t.p,delegateAddress:t.p,expirationDate:h.z.optional(h.z.date())}),Ke=h.z.object({kind:h.z.literal(`RevokeDelegation`),from:t.p,contractAddress:t.p,delegateAddress:t.p});h.z.discriminatedUnion(`kind`,[Ie,Le,Re,ze,Be,Ve,He,Q,We,Ge,Ke]);const qe=h.z.strictObject({maxFeePerGas:h.z.bigint(),maxPriorityFeePerGas:h.z.bigint()}),$=h.z.object({nonce:h.z.optional(h.z.int().check(h.z.nonnegative())),gasLimit:h.z.optional(h.z.bigint()),fees:h.z.optional(qe)}),Je=h.z.object({address:t.p,abi:h.z.array(h.z.unknown()),functionName:h.z.string(),args:h.z.array(h.z.unknown()),value:h.z.optional(h.z.bigint()),gas:h.z.optional(h.z.bigint())}),Ye=h.z.extend($,{from:t.p,calldata:Je});var Xe=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=f.t($,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new o.t(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},s=f.t(Ye,i),c=await this.#e.prepareTransaction(s).catch(t=>{throw a.r(t,`prepare ${e.kind}`)??t}),l=(0,m.parseTransaction)(c),u=(0,m.encodeFunctionData)({abi:s.calldata.abi,functionName:s.calldata.functionName,args:s.calldata.args});if(l.chainId!==r||!l.to||!(0,m.isAddressEqual)(l.to,s.calldata.address)||l.data?.toLowerCase()!==u.toLowerCase()||(l.value??0n)!==(s.calldata.value??0n))throw new o.t(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:c,from:s.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new o.t(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=f.t(Ie,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for ConfidentialTransfer`);return r.S(e.token,e.to,i,n)}async#a(e){e=f.t(Le,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for ConfidentialTransferFrom`);return r.w(e.token,e.owner,e.to,i,n)}#o(e){return e=f.t(Re,e),r.k(e.token,e.operator,e.until)}async#s(e){e=f.t(ze,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),i=t[0];if(!i)throw new s.r(`Encryption returned no handles for Unwrap`);return r.M(e.token,e.from,e.to,i,n)}async#c(e){e=f.t(Be,e);let t=await this.#e.readContract(r.y(e.token,e.from));return r.N(e.token,e.from,e.to,t)}async#l(e){e=f.t(Ve,e);let{value:t,decryptionProof:n}=await i.t(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return r.T(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=f.t(He,e),r.p(e.underlying,e.spender,e.amount)}#d(e){return e=f.t(Q,e),r.F(e.wrapper,e.to,e.amount)}#f(e){return e=f.t(We,e),y(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=f.t(Ge,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new i.v(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new i.C(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new i._(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):w;return x(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=f.t(Ke,e),S(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Ze(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new o.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 Qe(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new o.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 $e(e){if(e===void 0)return;let n=f.t(t.l,e);return new t.u(typeof n==`string`?n:new Uint8Array(n))}var et=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,n={}){Ze(n),Qe(n.transportKeyPairDerivationSecret);let r=$e(n.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 Ee(e.storage,this.#i,r),this.#u=new Ne({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let i={};for(let t of e.chains)t.registryAddress&&(i[t.id]=t.registryAddress);this.registry=new t.o({provider:this.provider,registryAddresses:i,registryTTL:e.registryTTL}),this.#n=i,this.#t=e.registryTTL,this.#l=new t.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:r,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new Ae({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Pe({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Fe({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Xe({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new P({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new F({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new I({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new L(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}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 t.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,d.r(t,`encrypt`))}createToken(e){return new a.t(this,e)}createWrappedToken(e){return new Y(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=de,exports.AclPausedError=i.p,exports.AclTopics=A,exports.BalanceCheckUnavailableError=a.l,exports.BaseSigner=t.t,exports.ChainMismatchError=r.q,exports.ChromeSessionStorage=R,exports.ConfigurationError=o.t,exports.Decryption=I,exports.DecryptionFailedError=s.t,exports.DefaultRegistryAddresses=t.a,exports.DelegationContractIsSelfError=i.m,exports.DelegationCooldownError=i.h,exports.DelegationDelegateCannotBeWildcardError=i.g,exports.DelegationDelegateEqualsContractError=i._,exports.DelegationExpirationTooSoonError=i.v,exports.DelegationExpiredError=i.y,exports.DelegationExpiryUnchangedError=i.b,exports.DelegationNotFoundError=i.x,exports.DelegationNotPropagatedError=i.S,exports.DelegationSelfNotAllowedError=i.C,exports.Delegations=F,exports.ERC1363_INTERFACE_ID=r.a,exports.ERC20ReadFailedError=a.u,exports.ERC7984_INTERFACE_ID=r.o,exports.ERC7984_WRAPPER_INTERFACE_ID=r.s,exports.EncryptOffloadUnavailableError=s.n,exports.EncryptionFailedError=s.r,exports.HcuBlockLimitExceededError=r.J,exports.HcuTransactionLimitExceededError=r.Y,exports.IndexedDBStorage=t.v,exports.InsufficientAllowanceError=a.d,exports.InsufficientConfidentialBalanceError=a.f,exports.InsufficientERC20BalanceError=a.p,exports.InvalidTransportKeyPairError=c.i,exports.KeyWrappingError=c.a,exports.MAX_UINT64=w,exports.MemoryStorage=t.g,exports.MutableWalletAccountStore=t.n,exports.NoCiphertextError=c.o,exports.NotEntitledError=i.w,exports.Offline=L,exports.Permits=P,exports.PreparedPermitChainMismatchError=c.s,exports.PreparedPermitExpiredError=c.c,exports.RelayerRequestFailedError=o.n,exports.RevokedKmsContextError=c.l,exports.RpcRateLimitError=l.r,exports.SignerNotConfiguredError=r.H,exports.SignerRequiredError=r.U,exports.SigningFailedError=c.t,exports.SigningRejectedError=c.n,exports.TOKEN_TOPICS=se,exports.Token=a.t,exports.Topics=E,exports.TransactionRevertedError=r.X,exports.TransportKeyPairChangedError=c.u,exports.TransportKeyPairExpiredError=c.d,exports.UnshieldAlreadyFinalizedError=u.t,exports.UnwrapNotMinedError=u.n,exports.VaultBatchNotDispatchedError=i.l,exports.VaultBatcherPausedError=i.u,exports.VaultBatcherReadFailedError=i.d,exports.VaultJoinUnconfirmedError=i.f,exports.WILDCARD_CONTRACT=T,exports.WalletAccountNotReadyError=r.W,exports.WalletNotConnectedError=r.G,exports.WrappedToken=Y,exports.WrappersRegistry=t.o,exports.ZERO_ENCRYPTED_VALUE=a.o,exports.ZamaError=o.r,exports.ZamaErrorCode=o.i,exports.ZamaSDK=et,exports.ZamaSDKEvents=r.B,exports.allowanceContract=r.f,exports.anvil=n.t,exports.approveContract=r.p,exports.balanceOfContract=r.m,exports.bscTestnet=n.n,exports.chains=n.r,exports.chromeSessionStorage=fe,exports.cleartext=e.t,exports.confidentialBalanceOfContract=r.y,exports.confidentialTotalSupplyContract=r.b,exports.confidentialTransferAndCallContract=r.x,exports.confidentialTransferContract=r.S,exports.confidentialTransferFromAndCallContract=r.C,exports.confidentialTransferFromContract=r.w,exports.createConfig=te,exports.createWalletAccountStore=t.r,exports.decimalsContract=r.h,exports.decodeAclEvent=N,exports.decodeAclEvents=ce,exports.decodeConfidentialTransfer=D,exports.decodeDelegatedForUserDecryption=j,exports.decodeOnChainEvent=re,exports.decodeOnChainEvents=ie,exports.decodeRevokedDelegationForUserDecryption=M,exports.decodeUnwrapFinalized=ne,exports.decodeUnwrapRequested=k,exports.decodeWrap=O,exports.delegateForUserDecryptionContract=x,exports.finalizeUnwrapContract=r.T,exports.findDelegatedForUserDecryption=le,exports.findRevokedDelegationForUserDecryption=ue,exports.findUnwrapRequested=ae,exports.findWrap=oe,exports.getConfidentialTokenAddressContract=p.t,exports.getDelegationExpiryContract=C,exports.getTokenAddressContract=p.n,exports.getTokenPairContract=p.r,exports.getTokenPairsContract=p.i,exports.getTokenPairsLengthContract=p.a,exports.getTokenPairsSliceContract=p.o,exports.hardhat=n.i,exports.hoodi=n.a,exports.indexedDBStorage=t.y,exports.inferredTotalSupplyContract=r.E,exports.isConfidentialTokenContract=r.c,exports.isConfidentialTokenValidContract=p.s,exports.isConfidentialWrapperContract=r.l,exports.isEncryptedValueZero=a.c,exports.isHandleDelegatedContract=ee,exports.isOperatorContract=r.D,exports.isRetryable=o.a,exports.mainnet=n.o,exports.matchZamaError=g,exports.memoryStorage=t._,exports.nameContract=r._,exports.parsePreparedPermit=t.c,exports.polygon=n.s,exports.polygonAmoy=n.c,exports.rateContract=r.O,exports.retryAfterSeconds=o.o,exports.revokeDelegationContract=S,exports.sepolia=n.l,exports.setOperatorContract=r.k,exports.supportsInterfaceContract=r.d,exports.symbolContract=r.v,exports.transferAndCallContract=y,exports.underlyingContract=r.A,exports.unwrapAmountContract=r.j,exports.unwrapContract=r.M,exports.unwrapFromBalanceContract=r.N,exports.unwrapRequesterContract=r.P,exports.wrapContract=r.F,exports.zenithTrexTestnet=n.u;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|