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