@zama-fhe/sdk 3.6.0-alpha.2 → 3.6.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/cjs/index.cjs +1 -1
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs/relayer.cjs +1 -1
  4. package/dist/cjs/relayer.cjs.map +1 -1
  5. package/dist/esm/{base-signer-D_QaiSoN.js → base-signer-CXvLkK3R.js} +2 -2
  6. package/dist/esm/{base-signer-D_QaiSoN.js.map → base-signer-CXvLkK3R.js.map} +1 -1
  7. package/dist/esm/cleartext/index.js +1 -1
  8. package/dist/esm/{cleartext-k9Y1Tm-f.js → cleartext-D8A7LXSP.js} +2 -2
  9. package/dist/esm/{cleartext-k9Y1Tm-f.js.map → cleartext-D8A7LXSP.js.map} +1 -1
  10. package/dist/esm/ethers/index.js +1 -1
  11. package/dist/esm/{fhevm-relayer-DmHNrp7a.js → fhevm-relayer-CKucZJeZ.js} +2 -2
  12. package/dist/esm/{fhevm-relayer-DmHNrp7a.js.map → fhevm-relayer-CKucZJeZ.js.map} +1 -1
  13. package/dist/esm/{index-Bbw4NHwj.d.ts → index-0FEn0eUO.d.ts} +23 -4
  14. package/dist/esm/index.d.ts +2 -2
  15. package/dist/esm/index.js +1 -1
  16. package/dist/esm/index.js.map +1 -1
  17. package/dist/esm/node/index.js +1 -1
  18. package/dist/esm/query/index.d.ts +1 -1
  19. package/dist/esm/query/index.js +1 -1
  20. package/dist/esm/{relayer-DuYi7i8G.js → relayer-gGSbmpjI.js} +2 -2
  21. package/dist/esm/{relayer-DuYi7i8G.js.map → relayer-gGSbmpjI.js.map} +1 -1
  22. package/dist/esm/{sdk-events-SP61DfHG.js → sdk-events-ByzD-Gre.js} +2 -2
  23. package/dist/esm/{sdk-events-SP61DfHG.js.map → sdk-events-ByzD-Gre.js.map} +1 -1
  24. package/dist/esm/{token-DyEqTiFr.js → token-ORmGSfIF.js} +2 -2
  25. package/dist/esm/{token-DyEqTiFr.js.map → token-ORmGSfIF.js.map} +1 -1
  26. package/dist/esm/viem/index.js +1 -1
  27. package/dist/esm/web/index.js +1 -1
  28. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},v=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const ee=[n._,t.lt,e.n,b,t.at,t.it,u,n.g,t.st,t.ft,t.ht];function x(r,i,a={}){if(ee.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.st(r.message,{cause:r});if(e.h(r))return new t.ft(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:r});if(r instanceof Error&&e._(r.message))return new t.ht(`This account's stored permit for this scope is a wildcard (V2) permit, but the connected relayer does not yet support unified decryption (/v3/user-decrypt). Grant a specific-contract permit instead (sdk.permits.grantPermit([...])), or retry once the relayer upgrades.`,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new b(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e.y(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.g(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.lt(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new b(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function te(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const ne=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function S(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}const C=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function w(e,t,n,r){return{address:e,abi:C,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function T(e,t,n){return{address:e,abi:C,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function re(e,t,n,r){return{address:e,abi:C,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function ie(e,t,n,r,i){return{address:e,abi:C,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const E=2n**64n-1n;function ae(e){return i.i(e.signer,e.provider,e)}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}function O(e){return(0,s.keccak256)((0,s.toBytes)(e))}const k={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function A(e){return(0,s.getAddress)(D(e.slice(-40)))}function j(e){return e}function M(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function N(e,t){return(0,s.getAddress)(D(M(e,t).slice(-40)))}function P(e,t){return BigInt(`0x`+M(e,t))}function F(e,t){return D(M(e,t))}function oe(e){return e.topics[0]!==k.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:j(e.topics[3])}}function I(e){return e.topics[0]!==k.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:F(e.data,1)}}function L(e){return e.topics[0]!==k.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0)}}function R(e){return e.topics[0]!==k.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0),cleartextAmount:P(e.data,1)}}function z(e){return oe(e)??I(e)??L(e)??R(e)}function se(e){let t=[];for(let n of e){let e=z(n);e&&t.push(e)}return t}function B(e){for(let t of e){let e=L(t);if(e)return e}return null}function ce(e){for(let t of e){let e=I(t);if(e)return e}return null}const le=[k.ConfidentialTransfer,k.Wrap,k.UnwrapRequested,k.UnwrapFinalized],V={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function H(e){return e.topics[0]!==V.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function U(e){return e.topics[0]!==V.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function W(e){return H(e)??U(e)}function ue(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function de(e){for(let t of e){let e=H(t);if(e)return e}return null}function fe(e){for(let t of e){let e=U(t);if(e)return e}return null}const pe=[V.DelegatedForUserDecryption,V.RevokedDelegationForUserDecryption];var G=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.nt(this.#r,e)}async grantPermit(e){if(Array.isArray(e)&&e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(Array.isArray(t)&&t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){await this.#a(`registerPermit`).registerPermit(e,t),await this.#o(e.signerAddress)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.W(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},K=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.nt(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},q=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.nt(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw x(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},J=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}},Y=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const me=new Y;function X(e){return`zama:pending-unshield:${t.G(e)}`}const he=c.z.union([c.z.pipe(t.q,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:t.q,unwrapRequestId:c.z.optional(t.q)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function ge(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _e(e,t){return(await ve(e,t))?.unwrapTxHash??null}async function ve(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=he.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ye(e,t){await e.delete(X(t))}var be=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.Q(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#s(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.b(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:S(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#s(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e.b(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e.b(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.W(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.W(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.rt(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);return this.#c(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){return _e(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=B(e);if(!n)throw new t.rt(`No UnwrapRequested event found in unwrap receipt`);return n.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.W(`unshield: savePendingUnshield`,()=>ge(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.W(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.W(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.W(`unshield: clearPendingUnshield`,()=>ye(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const xe=c.z.union([c.z.bigint(),c.z.boolean(),t.K]),Se=c.z.array(c.z.string());var Ce=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=xe.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Se.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function we(e,t){let r=Te(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function Te(e,n){let r=t.G(n);return e.permissions.find(e=>i.c(e,r))}const Ee=e=>new Promise(t=>setTimeout(t,e));var De=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,c))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof b))throw t;await Ee(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1,d;if(await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#d(e,n)}catch(r){if(n.l(r)){u=!0,d??=r;return}e.error=this.#f(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(t,n,r,i){let a=we(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a,o={spent:!1}){if(r.length===0)return{};let c=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),l={},u=[];for(let e of c)n.c(e.encryptedValue)?l[e.encryptedValue]=0n:u.push(e);if(u.length===0)return l;let d=Array.from(new Set(c.map(e=>e.contractAddress))),f=Array.from(new Set(u.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(f)}catch(t){throw e.g(t)?this.#u(t,`the delegation pre-check`):t}let p=[];for(let e of u){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?p.push(e):l[e.encryptedValue]=t}if(p.length===0)return l;let m=await this.#t.grantPermit(d,i.delegator),h=new Map;for(let e of p){let t=h.get(e.contractAddress);t?t.push(e.encryptedValue):h.set(e.contractAddress,[e.encryptedValue])}let g=[];for(let[e,t]of h)for(let r of n.s(t))g.push({contractAddress:e,encryptedValues:r});let _=Date.now(),v=p.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:v});try{await this.#c(i,m,g,l,a)}catch(e){if(!(e instanceof t.ft)||o.spent)throw e;let n=m.permissions.map(e=>e.serializedPermit.signature);o.spent=!0;try{m=await this.#t.recoverPermits(d,i.delegator,n)}catch(e){throw e instanceof t.it?new t.ft(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(i,m,g.filter(({encryptedValues:e})=>e.some(e=>l[e]===void 0)),l,a)}let e={};for(let t of v){let n=l[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-_,encryptedValues:v,result:e}),l}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e.b(r),durationMs:Date.now()-_,encryptedValues:v}),x(n,i.errorMessage,{isDelegated:i.delegator!==void 0})}}async#c(e,r,i,a,o){let s=(await n.r(i.map(({contractAddress:t,encryptedValues:n})=>async()=>{try{await this.#l(e,r,t,n,a,o);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(s.length>0)throw s.find(e=>e instanceof t.ft)??s[0]}async#l(e,t,r,i,a,o){let s;try{s=await this.#o(t,r,i,o)}catch(t){throw x(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:r,account:e.delegator??e.requesterAddress})}for(let t=0;t<i.length;t++){let n=i[t],o=s[t]?.value;n!==void 0&&o!==void 0&&(a[n]=o,await this.#e.set(e.requesterAddress,r,n,o))}let c=i.filter(e=>a[e]===void 0);if(c.length>0)throw new n._(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${i.length} handle(s) on ${r}`,{cause:AggregateError(c.map(e=>new n._(`No clear value for handle ${e} on ${r}`)),`${c.length} handle(s) missing a clear value on ${r}`)})}#u(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#d(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#f(t,n,r){return t instanceof e.r?t:x(t,n,r)}#p(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Oe(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const Z={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new _(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new y(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function ke(e){return Object.hasOwn(Z,e)}function Ae(e,t){let n=Oe(e);if(n&&ke(n))return Z[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Z))if(r.includes(e))return n(t);return null}var je=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):E,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:w(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:T(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===E?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(re(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof t.rt))return;let n=Ae(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Me=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e.b(n),durationMs:Date.now()-i},a),te(n,`Encryption failed`)}}},Ne=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.W(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.W(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.W(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.W(`wallet account listener`,()=>n(e),this.#i)))}};const Pe=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:t.K,token:t.K,to:t.K,amount:c.z.bigint()}),Fe=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:t.K,token:t.K,owner:t.K,to:t.K,amount:c.z.bigint()}),Ie=c.z.object({kind:c.z.literal(`SetOperator`),from:t.K,token:t.K,operator:t.K,until:t.Z}),Le=c.z.object({kind:c.z.literal(`Unwrap`),from:t.K,token:t.K,to:t.K,amount:c.z.bigint()}),Re=c.z.object({kind:c.z.literal(`UnwrapAll`),from:t.K,token:t.K,to:t.K}),Q=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:t.K,wrapper:t.K,unwrapRequestIdOrAmount:t.q}),ze=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:t.K,underlying:t.K,spender:t.K,amount:c.z.bigint()}),Be=c.z.object({kind:c.z.literal(`Wrap`),from:t.K,wrapper:t.K,to:t.K,amount:c.z.bigint()}),Ve=t.q.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),He=c.z.object({kind:c.z.literal(`TransferAndCall`),from:t.K,underlying:t.K,wrapper:t.K,amount:c.z.bigint(),recipientData:c.z.optional(Ve)}),Ue=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:t.K,contractAddress:t.K,delegateAddress:t.K,expirationDate:c.z.optional(c.z.date())}),We=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:t.K,contractAddress:t.K,delegateAddress:t.K});c.z.discriminatedUnion(`kind`,[Pe,Fe,Ie,Le,Re,Q,ze,Be,He,Ue,We]);const Ge=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),$=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Ge)}),Ke=c.z.object({address:t.K,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),qe=c.z.extend($,{from:t.K,calldata:Ke});var Je=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.d($,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.d(qe,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.d(Pe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.d(Fe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.d(Ie,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.d(Le,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.d(Re,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.d(Q,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw x(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.d(ze,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.d(Be,e),t.R(e.wrapper,e.to,e.amount)}#f(e){return e=i.d(He,e),S(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.d(Ue,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new y(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):E;return w(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.d(We,e),T(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Ye(t){if(!(!Object.hasOwn(t,`transportKeyPairDerivationSecret`)||t.transportKeyPairDerivationSecret!==void 0))throw new e.t(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Xe(t){if(t===void 0)return;let{importScripts:n}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof n!=`function`))throw new e.t(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function Ze(e){if(e===void 0)return;let t=i.d(i.l,e);return new i.u(typeof t==`string`?t:new Uint8Array(t))}var Qe=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Ye(t),Xe(t.transportKeyPairDerivationSecret);let n=Ze(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Ce(e.storage,this.#i),this.#u=new je({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new De({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Me({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Ne({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Je({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new G({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new K({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new q({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new J(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new be(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=pe,exports.AclPausedError=v,exports.AclTopics=V,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=Y,exports.ConfigurationError=e.t,exports.Decryption=q,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=_,exports.DelegationCooldownError=f,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=y,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=b,exports.DelegationSelfNotAllowedError=d,exports.Delegations=K,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i.m,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.st,exports.KeyWrappingError=t.ct,exports.MemoryStorage=i.f,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.lt,exports.NotEntitledError=u,exports.Offline=J,exports.Permits=G,exports.PreparedPermitChainMismatchError=t.ut,exports.PreparedPermitExpiredError=t.dt,exports.RelayerRequestFailedError=e.n,exports.RevokedKmsContextError=t.ft,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.Q,exports.SignerRequiredError=t.$,exports.SigningFailedError=t.it,exports.SigningRejectedError=t.at,exports.TOKEN_TOPICS=le,exports.Token=n.t,exports.Topics=k,exports.TransactionRevertedError=t.rt,exports.TransportKeyPairChangedError=t.pt,exports.TransportKeyPairExpiredError=t.mt,exports.UnifiedDecryptionUnsupportedError=t.ht,exports.UnifiedPermitNotSupportedError=t.gt,exports.WILDCARD_PERMIT=t.B,exports.WalletAccountNotReadyError=t.et,exports.WalletNotConnectedError=t.tt,exports.WrappedToken=be,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Qe,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=me,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ae,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=W,exports.decodeAclEvents=ue,exports.decodeConfidentialTransfer=oe,exports.decodeDelegatedForUserDecryption=H,exports.decodeOnChainEvent=z,exports.decodeOnChainEvents=se,exports.decodeRevokedDelegationForUserDecryption=U,exports.decodeUnwrapFinalized=R,exports.decodeUnwrapRequested=L,exports.decodeWrap=I,exports.delegateForUserDecryptionContract=w,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=de,exports.findRevokedDelegationForUserDecryption=fe,exports.findUnwrapRequested=B,exports.findWrap=ce,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=re,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.h,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=ie,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.p,exports.nameContract=t.S,exports.polygon=a.c,exports.polygonAmoy=a.l,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=T,exports.sepolia=a.u,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=S,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateCannotBeWildcard,t,n),this.name=`DelegationDelegateCannotBeWildcardError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},y=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const ee=[n._,t.lt,e.n,x,t.at,t.it,u,n.g,t.st,t.ft,t.ht];function S(r,i,a={}){if(ee.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.st(r.message,{cause:r});if(e.h(r))return new t.ft(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:r});if(r instanceof Error&&e._(r.message))return new t.ht(`This account's stored permit for this scope is a wildcard (V2) permit, but the connected relayer does not yet support unified decryption (/v3/user-decrypt). Grant a specific-contract permit instead (sdk.permits.grantPermit([...])), or retry once the relayer upgrades.`,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new x(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e.y(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.g(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.lt(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new x(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function te(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const ne=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function C(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}const w=[{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 T(e,t,n,r){return{address:e,abi:w,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function E(e,t,n){return{address:e,abi:w,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function D(e,t,n,r){return{address:e,abi:w,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function re(e,t,n,r,i){return{address:e,abi:w,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const O=2n**64n-1n,k=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ie(e){return i.i(e.signer,e.provider,e)}function A(e){return e.startsWith(`0x`)?e:`0x${e}`}function j(e){return(0,s.keccak256)((0,s.toBytes)(e))}const M={ConfidentialTransfer:j(`ConfidentialTransfer(address,address,bytes32)`),Wrap:j(`Wrap(address,uint256,bytes32)`),UnwrapRequested:j(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:j(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function N(e){return(0,s.getAddress)(A(e.slice(-40)))}function P(e){return e}function F(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function ae(e,t){return(0,s.getAddress)(A(F(e,t).slice(-40)))}function I(e,t){return BigInt(`0x`+F(e,t))}function L(e,t){return A(F(e,t))}function R(e){return e.topics[0]!==M.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:N(e.topics[1]),to:N(e.topics[2]),encryptedAmount:P(e.topics[3])}}function z(e){return e.topics[0]!==M.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:N(e.topics[1]),roundedAmount:I(e.data,0),encryptedWrappedAmount:L(e.data,1)}}function B(e){return e.topics[0]!==M.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:N(e.topics[1]),unwrapRequestId:P(e.topics[2]),encryptedAmount:L(e.data,0)}}function V(e){return e.topics[0]!==M.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:N(e.topics[1]),unwrapRequestId:P(e.topics[2]),encryptedAmount:L(e.data,0),cleartextAmount:I(e.data,1)}}function H(e){return R(e)??z(e)??B(e)??V(e)}function oe(e){let t=[];for(let n of e){let e=H(n);e&&t.push(e)}return t}function U(e){for(let t of e){let e=B(t);if(e)return e}return null}function se(e){for(let t of e){let e=z(t);if(e)return e}return null}const ce=[M.ConfidentialTransfer,M.Wrap,M.UnwrapRequested,M.UnwrapFinalized],W={DelegatedForUserDecryption:j(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:j(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:N(e.topics[1]),delegate:N(e.topics[2]),contractAddress:ae(e.data,0),delegationCounter:I(e.data,1),oldExpirationDate:I(e.data,2),newExpirationDate:I(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:N(e.topics[1]),delegate:N(e.topics[2]),contractAddress:ae(e.data,0),delegationCounter:I(e.data,1),oldExpirationDate:I(e.data,2)}}function q(e){return G(e)??K(e)}function le(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function ue(e){for(let t of e){let e=G(t);if(e)return e}return null}function de(e){for(let t of e){let e=K(t);if(e)return e}return null}const fe=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var J=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.nt(this.#r,e)}async grantPermit(e){if(Array.isArray(e)&&e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(Array.isArray(t)&&t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async registerPermit(e,t){await this.#a(`registerPermit`).registerPermit(e,t),await this.#o(e.signerAddress)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.W(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Y=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.nt(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},X=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.nt(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw S(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},pe=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)}},me=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 he=new me;function Z(e){return`zama:pending-unshield:${t.G(e)}`}const ge=c.z.union([c.z.pipe(t.q,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:t.q,unwrapRequestId:c.z.optional(t.q)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function _e(e,t,n,r){if(r===void 0){await e.set(Z(t),n);return}await e.set(Z(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function ve(e,t){return(await ye(e,t))?.unwrapTxHash??null}async function ye(e,t){let n=Z(t),r=await e.get(n);if(r==null)return null;let i=ge.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function be(e,t){await e.delete(Z(t))}var xe=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.Q(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#s(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.b(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:C(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#s(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e.b(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e.b(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.W(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.W(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.rt(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);return this.#c(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){return ve(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=U(e);if(!n)throw new t.rt(`No UnwrapRequested event found in unwrap receipt`);return n.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.W(`unshield: savePendingUnshield`,()=>_e(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.W(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.W(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.W(`unshield: clearPendingUnshield`,()=>be(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const Se=c.z.union([c.z.bigint(),c.z.boolean(),t.K]),Ce=c.z.array(c.z.string());var we=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=Se.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Ce.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 Te(e,t){let r=Ee(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function Ee(e,n){let r=t.G(n);return e.permissions.find(e=>i.c(e,r))}const De=e=>new Promise(t=>setTimeout(t,e));var Oe=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},void 0,c))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof x))throw t;await De(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1,d;if(await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#d(e,n)}catch(r){if(n.l(r)){u=!0,d??=r;return}e.error=this.#f(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(t,n,r,i){let a=Te(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a,o={spent:!1}){if(r.length===0)return{};let c=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),l={},u=[];for(let e of c)n.c(e.encryptedValue)?l[e.encryptedValue]=0n:u.push(e);if(u.length===0)return l;let d=Array.from(new Set(c.map(e=>e.contractAddress))),f=Array.from(new Set(u.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(f)}catch(t){throw e.g(t)?this.#u(t,`the delegation pre-check`):t}let p=[];for(let e of u){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?p.push(e):l[e.encryptedValue]=t}if(p.length===0)return l;let m=await this.#t.grantPermit(d,i.delegator),h=new Map;for(let e of p){let t=h.get(e.contractAddress);t?t.push(e.encryptedValue):h.set(e.contractAddress,[e.encryptedValue])}let g=[];for(let[e,t]of h)for(let r of n.s(t))g.push({contractAddress:e,encryptedValues:r});let _=Date.now(),v=p.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:v});try{await this.#c(i,m,g,l,a)}catch(e){if(!(e instanceof t.ft)||o.spent)throw e;let n=m.permissions.map(e=>e.serializedPermit.signature);o.spent=!0;try{m=await this.#t.recoverPermits(d,i.delegator,n)}catch(e){throw e instanceof t.it?new t.ft(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(i,m,g.filter(({encryptedValues:e})=>e.some(e=>l[e]===void 0)),l,a)}let e={};for(let t of v){let n=l[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-_,encryptedValues:v,result:e}),l}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e.b(r),durationMs:Date.now()-_,encryptedValues:v}),S(n,i.errorMessage,{isDelegated:i.delegator!==void 0})}}async#c(e,r,i,a,o){let s=(await n.r(i.map(({contractAddress:t,encryptedValues:n})=>async()=>{try{await this.#l(e,r,t,n,a,o);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(s.length>0)throw s.find(e=>e instanceof t.ft)??s[0]}async#l(e,t,r,i,a,o){let s;try{s=await this.#o(t,r,i,o)}catch(t){throw S(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:r,account:e.delegator??e.requesterAddress})}for(let t=0;t<i.length;t++){let n=i[t],o=s[t]?.value;n!==void 0&&o!==void 0&&(a[n]=o,await this.#e.set(e.requesterAddress,r,n,o))}let c=i.filter(e=>a[e]===void 0);if(c.length>0)throw new n._(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${i.length} handle(s) on ${r}`,{cause:AggregateError(c.map(e=>new n._(`No clear value for handle ${e} on ${r}`)),`${c.length} handle(s) missing a clear value on ${r}`)})}#u(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#d(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#f(t,n,r){return t instanceof e.r?t:S(t,n,r)}#p(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function ke(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const Q={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new v(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new _(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new b(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function Ae(e){return Object.hasOwn(Q,e)}function je(e,t){let n=ke(e);if(n&&Ae(n))return Q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Q))if(r.includes(e))return n(t);return null}var Me=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===(0,s.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new _(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):O,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return a!==(0,s.getAddress)(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:c,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:T(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:E(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=(0,s.getAddress)(e.contractAddress)===k,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:k})]),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:k});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!==O}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===O?{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(D(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#s({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof t.rt))return;let n=je(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Ne=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e.b(n),durationMs:Date.now()-i},a),te(n,`Encryption failed`)}}},Pe=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.W(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.W(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.W(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.W(`wallet account listener`,()=>n(e),this.#i)))}};const Fe=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:t.K,token:t.K,to:t.K,amount:c.z.bigint()}),Ie=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:t.K,token:t.K,owner:t.K,to:t.K,amount:c.z.bigint()}),Le=c.z.object({kind:c.z.literal(`SetOperator`),from:t.K,token:t.K,operator:t.K,until:t.Z}),Re=c.z.object({kind:c.z.literal(`Unwrap`),from:t.K,token:t.K,to:t.K,amount:c.z.bigint()}),ze=c.z.object({kind:c.z.literal(`UnwrapAll`),from:t.K,token:t.K,to:t.K}),Be=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:t.K,wrapper:t.K,unwrapRequestIdOrAmount:t.q}),Ve=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:t.K,underlying:t.K,spender:t.K,amount:c.z.bigint()}),$=c.z.object({kind:c.z.literal(`Wrap`),from:t.K,wrapper:t.K,to:t.K,amount:c.z.bigint()}),He=t.q.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),Ue=c.z.object({kind:c.z.literal(`TransferAndCall`),from:t.K,underlying:t.K,wrapper:t.K,amount:c.z.bigint(),recipientData:c.z.optional(He)}),We=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:t.K,contractAddress:t.K,delegateAddress:t.K,expirationDate:c.z.optional(c.z.date())}),Ge=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:t.K,contractAddress:t.K,delegateAddress:t.K});c.z.discriminatedUnion(`kind`,[Fe,Ie,Le,Re,ze,Be,Ve,$,Ue,We,Ge]);const Ke=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),qe=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Ke)}),Je=c.z.object({address:t.K,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),Ye=c.z.extend(qe,{from:t.K,calldata:Je});var Xe=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.d(qe,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.d(Ye,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.d(Fe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.d(Ie,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.d(Le,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.d(Re,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.d(ze,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.d(Be,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw S(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.d(Ve,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.d($,e),t.R(e.wrapper,e.to,e.amount)}#f(e){return e=i.d(Ue,e),C(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.d(We,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):O;return T(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.d(Ge,e),E(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Ze(t){if(!(!Object.hasOwn(t,`transportKeyPairDerivationSecret`)||t.transportKeyPairDerivationSecret!==void 0))throw new e.t(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Qe(t){if(t===void 0)return;let{importScripts:n}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof n!=`function`))throw new e.t(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function $e(e){if(e===void 0)return;let t=i.d(i.l,e);return new i.u(typeof t==`string`?t:new Uint8Array(t))}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,t={}){Ze(t),Qe(t.transportKeyPairDerivationSecret);let n=$e(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new we(e.storage,this.#i),this.#u=new Me({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new Oe({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Ne({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Pe({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,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 J({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new Y({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new X({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new pe(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new xe(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=fe,exports.AclPausedError=y,exports.AclTopics=W,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=me,exports.ConfigurationError=e.t,exports.Decryption=X,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=v,exports.DelegationCooldownError=f,exports.DelegationDelegateCannotBeWildcardError=_,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=b,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=x,exports.DelegationSelfNotAllowedError=d,exports.Delegations=Y,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i.m,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.st,exports.KeyWrappingError=t.ct,exports.MAX_UINT64=O,exports.MemoryStorage=i.f,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.lt,exports.NotEntitledError=u,exports.Offline=pe,exports.Permits=J,exports.PreparedPermitChainMismatchError=t.ut,exports.PreparedPermitExpiredError=t.dt,exports.RelayerRequestFailedError=e.n,exports.RevokedKmsContextError=t.ft,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.Q,exports.SignerRequiredError=t.$,exports.SigningFailedError=t.it,exports.SigningRejectedError=t.at,exports.TOKEN_TOPICS=ce,exports.Token=n.t,exports.Topics=M,exports.TransactionRevertedError=t.rt,exports.TransportKeyPairChangedError=t.pt,exports.TransportKeyPairExpiredError=t.mt,exports.UnifiedDecryptionUnsupportedError=t.ht,exports.UnifiedPermitNotSupportedError=t.gt,exports.WILDCARD_CONTRACT=k,exports.WILDCARD_PERMIT=t.B,exports.WalletAccountNotReadyError=t.et,exports.WalletNotConnectedError=t.tt,exports.WrappedToken=xe,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=et,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=he,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ie,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=q,exports.decodeAclEvents=le,exports.decodeConfidentialTransfer=R,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=H,exports.decodeOnChainEvents=oe,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=V,exports.decodeUnwrapRequested=B,exports.decodeWrap=z,exports.delegateForUserDecryptionContract=T,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=ue,exports.findRevokedDelegationForUserDecryption=de,exports.findUnwrapRequested=U,exports.findWrap=se,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=D,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.h,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=re,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.p,exports.nameContract=t.S,exports.polygon=a.c,exports.polygonAmoy=a.l,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=E,exports.sepolia=a.u,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=C,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
2
2
  //# sourceMappingURL=index.cjs.map