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