@zama-fhe/sdk 3.0.0-alpha.31 → 3.0.0-alpha.32
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/ethers/index.cjs +1 -1
- package/dist/cjs/index.cjs +4 -4
- 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/readonly-token.cjs +1 -1
- package/dist/cjs/readonly-token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/{base-signer-BCNOq8ML.d.ts → base-signer-C-eQd1ki.d.ts} +2 -2
- package/dist/esm/cleartext/index.d.ts +1 -1
- package/dist/esm/{cleartext-BgtYGip4.d.ts → cleartext-CHw-JAUJ.d.ts} +2 -2
- package/dist/esm/ethers/index.d.ts +4 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{index-QEd15Law.d.ts → index-N879Haro.d.ts} +68 -11
- package/dist/esm/index.d.ts +8 -8
- package/dist/esm/index.js +4 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +3 -3
- package/dist/esm/query/index.d.ts +5 -8
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/readonly-token-D089CIKy.js +2 -0
- package/dist/esm/readonly-token-D089CIKy.js.map +1 -0
- package/dist/esm/{relayer-cleartext-BzpqI_BH.d.ts → relayer-cleartext-DSoCe7x-.d.ts} +24 -5
- package/dist/esm/{types-Cq9xaH3t.d.ts → types-BtKjjaFT.d.ts} +2 -2
- package/dist/esm/{types-DF5sdue4.d.ts → types-JKs8fe87.d.ts} +14 -5
- package/dist/esm/{types-COKsQVCF.d.ts → types-Ogv0Iwqi.d.ts} +2 -2
- 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 +2 -2
- package/dist/esm/{wrappers-registry-D5orGELU.js → wrappers-registry-CzD3ObLG.js} +2 -2
- package/dist/esm/{wrappers-registry-D5orGELU.js.map → wrappers-registry-CzD3ObLG.js.map} +1 -1
- package/package.json +1 -1
- package/dist/esm/readonly-token-C9N5Hg1x.js +0 -2
- package/dist/esm/readonly-token-C9N5Hg1x.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../base-signer.cjs`),t=require(`../swallow.cjs`),n=require(`../wrappers-registry.cjs`),r=require(`../eip1193-subscribe.cjs`);let i=require(`viem`),a=require(`ethers`);var o=class{#e;constructor(e){`ethereum`in e?this.#e=new a.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return new a.ethers.Contract(e.address,e.abi,this.#e).getFunction(e.functionName)(...e.args)}async getBlockTimestamp(){let e=await this.#e.getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#e.waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}},s=class extends e.t{#e;#t;#n;#r;#i;constructor(e){super(),`ethereum`in e?(this.#e=new a.BrowserProvider(e.ethereum),this.#n=e.ethereum,this.#r=r.t({provider:e.ethereum,getInitialWalletAccount:()=>this.#l(),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}})):(this.#t=e.signer,this.#r=()=>{},t.t(`refresh wallet account`,async()=>{await this.refreshWalletAccount()}))}requireWalletAccount(t){let n=this.walletAccount.getSnapshot();if(!n&&!this.walletAccount.isReady())throw new e.d(t);if(!n)throw new e.f(t);return n}refreshWalletAccount(){return this.#n?this.#c():this.#t?this.#s(this.#t):Promise.resolve(void 0)}onDispose(){this.#r()}async#a(){if(this.#t)return this.#t;if(!this.#e)throw new e.l(`resolveSigner`);return this.#e.getSigner()}async#o(e){let t=e.provider;if(!t)return;let[n,r]=await Promise.all([e.getAddress(),t.getNetwork()]);return{address:(0,i.getAddress)(n),chainId:Number(r.chainId)}}async signTypedData(e){let t=await this.#a(),{domain:n,types:r,message:a}=e,{EIP712Domain:o,...s}=r,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(n,c,a);if(!(0,i.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#a(),n=new a.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let o=await n.getFunction(e.functionName)(...e.args,r);if(!(0,i.isHex)(o.hash))throw TypeError(`Expected hex string, got: ${o.hash}`);return o.hash}async#s(e){return this.#i??=this.#o(e).then(e=>(this.walletAccount.setSnapshot(e),e)).finally(()=>{this.#i=void 0}),this.#i}async#c(){let e=await this.#l();return this.walletAccount.setSnapshot(e),e}async#l(){let e=this.#n;if(!e)return;let[t,n]=await Promise.all([e.request({method:`eth_accounts`}),e.request({method:`eth_chainId`})]);if(!Array.isArray(t)||typeof t[0]!=`string`)return;let r=Number(n);if(!(!Number.isSafeInteger(r)||r<=0))return{address:(0,i.getAddress)(t[0]),chainId:r}}};function c(t){if(`signer`in t&&t.signer){let n=new s({signer:t.signer});if(!t.signer.provider)throw Error(`createConfig requires a Signer with an attached provider for chain reads`);return e.i(n,new o({provider:t.signer.provider}),t)}return e.i(new s({ethereum:t.ethereum}),`provider`in t&&t.provider?new o({provider:t.provider}):new o({ethereum:t.ethereum}),t)}function l(e){return{to:e.address,data:(0,i.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function u(e,t){let n=await e.call(l(t));if(!(0,i.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,i.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function d(e,t){let n=await e.sendTransaction(l(t));if(!(0,i.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function f(e,t,r){return u(e,n.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../base-signer.cjs`),t=require(`../swallow.cjs`),n=require(`../wrappers-registry.cjs`),r=require(`../eip1193-subscribe.cjs`);let i=require(`viem`),a=require(`ethers`);var o=class{#e;constructor(e){`ethereum`in e?this.#e=new a.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return new a.ethers.Contract(e.address,e.abi,this.#e).getFunction(e.functionName)(...e.args)}async getBlockTimestamp(){let e=await this.#e.getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#e.waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}},s=class extends e.t{#e;#t;#n;#r;#i;constructor(e){super(),`ethereum`in e?(this.#e=new a.BrowserProvider(e.ethereum),this.#n=e.ethereum,this.#r=r.t({provider:e.ethereum,getInitialWalletAccount:()=>this.#l(),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}})):(this.#t=e.signer,this.#r=()=>{},t.t(`refresh wallet account`,async()=>{await this.refreshWalletAccount()}))}requireWalletAccount(t){let n=this.walletAccount.getSnapshot();if(!n&&!this.walletAccount.isReady())throw new e.d(t);if(!n)throw new e.f(t);return n}refreshWalletAccount(){return this.#n?this.#c():this.#t?this.#s(this.#t):Promise.resolve(void 0)}onDispose(){this.#r()}async#a(){if(this.#t)return this.#t;if(!this.#e)throw new e.l(`resolveSigner`);return this.#e.getSigner()}async#o(e){let t=e.provider;if(!t)return;let[n,r]=await Promise.all([e.getAddress(),t.getNetwork()]);return{address:(0,i.getAddress)(n),chainId:Number(r.chainId)}}async signTypedData(e){let t=await this.#a(),{domain:n,types:r,message:a}=e,{EIP712Domain:o,...s}=r,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(n,c,a);if(!(0,i.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#a(),n=new a.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let o=await n.getFunction(e.functionName)(...e.args,r);if(!(0,i.isHex)(o.hash))throw TypeError(`Expected hex string, got: ${o.hash}`);return o.hash}async#s(e){return this.#i??=this.#o(e).then(e=>(this.walletAccount.setSnapshot(e),e)).finally(()=>{this.#i=void 0}),this.#i}async#c(){let e=await this.#l();return this.walletAccount.setSnapshot(e),e}async#l(){let e=this.#n;if(!e)return;let[t,n]=await Promise.all([e.request({method:`eth_accounts`}),e.request({method:`eth_chainId`})]);if(!Array.isArray(t)||typeof t[0]!=`string`)return;let r=Number(n);if(!(!Number.isSafeInteger(r)||r<=0))return{address:(0,i.getAddress)(t[0]),chainId:r}}};function c(t){if(`signer`in t&&t.signer){let n=new s({signer:t.signer});if(!t.signer.provider)throw Error(`createConfig requires a Signer with an attached provider for chain reads`);return e.i(n,new o({provider:t.signer.provider}),t)}return e.i(new s({ethereum:t.ethereum}),`provider`in t&&t.provider?new o({provider:t.provider}):new o({ethereum:t.ethereum}),t)}function l(e){return{to:e.address,data:(0,i.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function u(e,t){let n=await e.call(l(t));if(!(0,i.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,i.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function d(e,t){let n=await e.sendTransaction(l(t));if(!(0,i.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function f(e,t,r){return u(e,n.b(t,r))}function p(e,t){return u(e,n.v(t))}function m(e,t,r){return u(e,n.h(t,r))}function h(e,t,r,i,a){return d(e,n.S(t,r,i,a))}function g(e,t,r,i,a,o){return d(e,n.O(t,r,i,a,o))}function _(e,t,r,i,a){return d(e,n.k(t,r,i,a))}function v(e,t,r,i,a){return d(e,n.g(t,r,i,a))}function y(e,t,r,i){return d(e,n.E(t,r,i))}function b(e,t,r,i){return d(e,n.y(t,r,i))}function x(e,t){return u(e,n.i(t))}function S(e,t){return u(e,n.a(t))}function C(e,t,r,i){return u(e,n.o(t,r,i))}function w(e,t,r){return u(e,n.r(t,r))}function T(e,t,r){return u(e,n.t(t,r))}function E(e,t,r){return u(e,n.n(t,r))}function D(e,t,r){return u(e,n.s(t,r))}exports.EthersProvider=o,exports.EthersSigner=s,Object.defineProperty(exports,`ProviderRpcError`,{enumerable:!0,get:function(){return i.ProviderRpcError}}),exports.createConfig=c,exports.readConfidentialBalanceOfContract=f,exports.readConfidentialTokenAddressContract=T,exports.readIsConfidentialTokenValidContract=D,exports.readSupportsInterfaceContract=m,exports.readTokenAddressContract=E,exports.readTokenPairContract=w,exports.readTokenPairsContract=x,exports.readTokenPairsLengthContract=S,exports.readTokenPairsSliceContract=C,exports.readUnderlyingTokenContract=p,exports.writeConfidentialTransferContract=h,exports.writeFinalizeUnwrapContract=v,exports.writeSetOperatorContract=y,exports.writeUnwrapContract=g,exports.writeUnwrapFromBalanceContract=_,exports.writeWrapContract=b;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./encryption.cjs`),r=require(`./base-signer.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./indexeddb-storage.cjs`),o=require(`./assertions.cjs`),s=require(`./swallow.cjs`),c=require(`./chains.cjs`),l=require(`./wrappers-registry.cjs`);let u=require(`viem`);var d=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},f=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},p=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.i.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},_=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},v=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},ee=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},y=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function te(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const ne={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.b(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.T(`Cannot revoke: no active delegation exists.`,{cause:e})};function b(e){let t=e instanceof Error?e:void 0,n=te(e);if(n&&n in ne)return ne[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(ne))if(r.includes(e))return n(t);return null}function re(r,i,a=!1){if(r instanceof n.t||r instanceof h||r instanceof e.n||r instanceof t.E||r instanceof t.k||r instanceof t.O)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new h(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new t.E(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ie(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function ae(e){return e.startsWith(`0x`)?e:`0x${e}`}function oe(e){return r.i(e.signer,e.provider,e)}var se=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#s(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#s(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#l(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async delete(e,t,n){let r=this.#s(e,t,n);this.#r=this.#r.then(()=>this.#i(r).catch(e=>{console.warn(`[zama-sdk] DecryptCache.delete failed:`,e)})),await this.#r}async#i(e){await this.#e.delete(e).catch(()=>{});let t=await this.#c(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#n,n)}async clearForRequester(e){this.#r=this.#r.then(()=>this.#a(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#a(e){let t=(0,u.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#c(),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.#n,a)}async clearAll(){this.#r=this.#r.then(()=>this.#o().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#o(){let e=await this.#c();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#s(e,t,n){return`${this.#t}:${(0,u.getAddress)(e)}:${(0,u.getAddress)(t)}:${n.toLowerCase()}`}async#c(){return await this.#e.get(this.#n)??[]}async#l(e){let t=await this.#c();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}};function ce(e){return`keypair:${e}`}function x(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function le(e){return`permits-index:${e}`}Object.freeze({status:`aborted`});function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var C=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ue=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const de={};function w(e){return e&&Object.assign(de,e),de}function fe(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function pe(e,t){return typeof t==`bigint`?t.toString():t}function me(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function he(e){return e==null}function ge(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function _e(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const ve=Symbol(`evaluating`);function T(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ve)return r===void 0&&(r=ve,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function E(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function D(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function ye(e){return JSON.stringify(e)}function be(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const xe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Se(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ce=me(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function O(e){if(Se(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Se(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function we(e){return O(e)?{...e}:Array.isArray(e)?[...e]:e}const Te=new Set([`string`,`number`,`symbol`]);function Ee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function k(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function De(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Oe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ke(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return k(e,D(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return E(this,`shape`,e),e},checks:[]}))}function Ae(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return k(e,D(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return E(this,`shape`,r),r},checks:[]}))}function je(e,t){if(!O(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return E(this,`shape`,n),n}}))}function Me(e,t){if(!O(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return E(this,`shape`,n),n}}))}function Ne(e,t){return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return E(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function Pe(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return k(t,D(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return E(this,`shape`,i),i},checks:[]}))}function Fe(e,t,n){return k(t,D(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return E(this,`shape`,i),i}}))}function j(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ie(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Le(e){return typeof e==`string`?e:e?.message}function M(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=Le(e.inst?._zod.def?.error?.(e))??Le(t?.error?.(e))??Le(n.customError?.(e))??Le(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Re(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function N(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const ze=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,pe,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},Be=S(`$ZodError`,ze),Ve=S(`$ZodError`,ze,{Parent:Error});function He(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ue(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}const We=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new C;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>M(e,a,w())));throw xe(t,i?.callee),t}return o.value},Ge=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>M(e,a,w())));throw xe(t,i?.callee),t}return o.value},Ke=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new C;return a.issues.length?{success:!1,error:new(e??Be)(a.issues.map(e=>M(e,i,w())))}:{success:!0,data:a.value}},qe=Ke(Ve),Je=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>M(e,i,w())))}:{success:!0,data:a.value}},Ye=Je(Ve),Xe=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return We(e)(t,n,i)},Ze=e=>(t,n,r)=>We(e)(t,n,r),Qe=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Ge(e)(t,n,i)},$e=e=>async(t,n,r)=>Ge(e)(t,n,r),et=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Ke(e)(t,n,i)},tt=e=>(t,n,r)=>Ke(e)(t,n,r),nt=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Je(e)(t,n,i)},rt=e=>async(t,n,r)=>Je(e)(t,n,r),it=/^[cC][^\s-]{8,}$/,at=/^[0-9a-z]+$/,ot=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,st=/^[0-9a-vA-V]{20}$/,ct=/^[A-Za-z0-9]{27}$/,lt=/^[a-zA-Z0-9_-]{21}$/,ut=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ft=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,pt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function mt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ht=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,_t=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,vt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,yt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bt=/^[A-Za-z0-9_-]*$/,xt=/^\+[1-9]\d{6,14}$/,St=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Ct=RegExp(`^${St}$`);function wt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Tt(e){return RegExp(`^${wt(e)}$`)}function Et(e){let t=wt({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${St}T(?:${r})$`)}const Dt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ot=/^-?\d+$/,kt=/^-?\d+(?:\.\d+)?$/,At=/^[^A-Z]*$/,jt=/^[^a-z]*$/,P=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Mt={number:`number`,bigint:`bigint`,object:`date`},Nt=S(`$ZodCheckLessThan`,(e,t)=>{P.init(e,t);let n=Mt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Pt=S(`$ZodCheckGreaterThan`,(e,t)=>{P.init(e,t);let n=Mt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ft=S(`$ZodCheckMultipleOf`,(e,t)=>{P.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):_e(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),It=S(`$ZodCheckNumberFormat`,(e,t)=>{P.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Oe[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Ot)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Lt=S(`$ZodCheckMaxLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!he(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Re(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Rt=S(`$ZodCheckMinLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!he(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Re(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zt=S(`$ZodCheckLengthEquals`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!he(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Re(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Bt=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;P.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Vt=S(`$ZodCheckRegex`,(e,t)=>{Bt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ht=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=At,Bt.init(e,t)}),Ut=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=jt,Bt.init(e,t)}),Wt=S(`$ZodCheckIncludes`,(e,t)=>{P.init(e,t);let n=Ee(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Gt=S(`$ZodCheckStartsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`^${Ee(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Kt=S(`$ZodCheckEndsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`.*${Ee(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),qt=S(`$ZodCheckOverwrite`,(e,t)=>{P.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Jt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./encryption.cjs`),r=require(`./base-signer.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./indexeddb-storage.cjs`),o=require(`./assertions.cjs`),s=require(`./swallow.cjs`),c=require(`./chains.cjs`),l=require(`./wrappers-registry.cjs`);let u=require(`viem`);var d=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},f=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},p=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.i.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},_=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},v=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},ee=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},y=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function te(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const ne={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.b(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.T(`Cannot revoke: no active delegation exists.`,{cause:e})};function b(e){let t=e instanceof Error?e:void 0,n=te(e);if(n&&n in ne)return ne[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(ne))if(r.includes(e))return n(t);return null}function re(r,i,a=!1){if(r instanceof n.t||r instanceof h||r instanceof e.n||r instanceof t.E||r instanceof t.k||r instanceof t.O)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new h(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new t.E(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ie(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function ae(e){return e.startsWith(`0x`)?e:`0x${e}`}function oe(e){return r.i(e.signer,e.provider,e)}const se=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function ce(e,t,n,r=`0x`){return{address:e,abi:se,functionName:`transferAndCall`,args:[t,n,r]}}var le=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#s(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#s(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#l(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async delete(e,t,n){let r=this.#s(e,t,n);this.#r=this.#r.then(()=>this.#i(r).catch(e=>{console.warn(`[zama-sdk] DecryptCache.delete failed:`,e)})),await this.#r}async#i(e){await this.#e.delete(e).catch(()=>{});let t=await this.#c(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#n,n)}async clearForRequester(e){this.#r=this.#r.then(()=>this.#a(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#a(e){let t=(0,u.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#c(),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.#n,a)}async clearAll(){this.#r=this.#r.then(()=>this.#o().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#o(){let e=await this.#c();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#s(e,t,n){return`${this.#t}:${(0,u.getAddress)(e)}:${(0,u.getAddress)(t)}:${n.toLowerCase()}`}async#c(){return await this.#e.get(this.#n)??[]}async#l(e){let t=await this.#c();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}};function ue(e){return`keypair:${e}`}function x(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function de(e){return`permits-index:${e}`}Object.freeze({status:`aborted`});function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var C=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},fe=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const pe={};function w(e){return e&&Object.assign(pe,e),pe}function me(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function he(e,t){return typeof t==`bigint`?t.toString():t}function ge(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function _e(e){return e==null}function ve(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ye(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const be=Symbol(`evaluating`);function T(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==be)return r===void 0&&(r=be,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function E(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function D(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function xe(e){return JSON.stringify(e)}function Se(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ce=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function we(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Te=ge(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function O(e){if(we(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(we(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Ee(e){return O(e)?{...e}:Array.isArray(e)?[...e]:e}const De=new Set([`string`,`number`,`symbol`]);function Oe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function k(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ke(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Ae={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function je(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return k(e,D(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return E(this,`shape`,e),e},checks:[]}))}function Me(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return k(e,D(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return E(this,`shape`,r),r},checks:[]}))}function Ne(e,t){if(!O(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return E(this,`shape`,n),n}}))}function Pe(e,t){if(!O(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return E(this,`shape`,n),n}}))}function Fe(e,t){return k(e,D(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return E(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function Ie(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return k(t,D(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return E(this,`shape`,i),i},checks:[]}))}function Le(e,t,n){return k(t,D(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return E(this,`shape`,i),i}}))}function j(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Re(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ze(e){return typeof e==`string`?e:e?.message}function M(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=ze(e.inst?._zod.def?.error?.(e))??ze(t?.error?.(e))??ze(n.customError?.(e))??ze(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Be(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function N(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Ve=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,he,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},He=S(`$ZodError`,Ve),Ue=S(`$ZodError`,Ve,{Parent:Error});function We(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ge(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}const Ke=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new C;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>M(e,a,w())));throw Ce(t,i?.callee),t}return o.value},qe=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>M(e,a,w())));throw Ce(t,i?.callee),t}return o.value},Je=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new C;return a.issues.length?{success:!1,error:new(e??He)(a.issues.map(e=>M(e,i,w())))}:{success:!0,data:a.value}},Ye=Je(Ue),Xe=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>M(e,i,w())))}:{success:!0,data:a.value}},Ze=Xe(Ue),Qe=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Ke(e)(t,n,i)},$e=e=>(t,n,r)=>Ke(e)(t,n,r),et=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return qe(e)(t,n,i)},tt=e=>async(t,n,r)=>qe(e)(t,n,r),nt=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Je(e)(t,n,i)},rt=e=>(t,n,r)=>Je(e)(t,n,r),it=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Xe(e)(t,n,i)},at=e=>async(t,n,r)=>Xe(e)(t,n,r),ot=/^[cC][^\s-]{8,}$/,st=/^[0-9a-z]+$/,ct=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lt=/^[0-9a-vA-V]{20}$/,ut=/^[A-Za-z0-9]{27}$/,dt=/^[a-zA-Z0-9_-]{21}$/,ft=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,pt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,mt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ht=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function gt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const _t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,St=/^[A-Za-z0-9_-]*$/,Ct=/^\+[1-9]\d{6,14}$/,wt=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Tt=RegExp(`^${wt}$`);function Et(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Dt(e){return RegExp(`^${Et(e)}$`)}function Ot(e){let t=Et({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${wt}T(?:${r})$`)}const kt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},At=/^-?\d+$/,jt=/^-?\d+(?:\.\d+)?$/,Mt=/^[^A-Z]*$/,Nt=/^[^a-z]*$/,P=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Pt={number:`number`,bigint:`bigint`,object:`date`},Ft=S(`$ZodCheckLessThan`,(e,t)=>{P.init(e,t);let n=Pt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),It=S(`$ZodCheckGreaterThan`,(e,t)=>{P.init(e,t);let n=Pt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lt=S(`$ZodCheckMultipleOf`,(e,t)=>{P.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):ye(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Rt=S(`$ZodCheckNumberFormat`,(e,t)=>{P.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ae[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=At)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),zt=S(`$ZodCheckMaxLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!_e(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Be(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Bt=S(`$ZodCheckMinLength`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!_e(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Be(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vt=S(`$ZodCheckLengthEquals`,(e,t)=>{var n;P.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!_e(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Be(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ht=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;P.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ut=S(`$ZodCheckRegex`,(e,t)=>{Ht.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Wt=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Mt,Ht.init(e,t)}),Gt=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Nt,Ht.init(e,t)}),Kt=S(`$ZodCheckIncludes`,(e,t)=>{P.init(e,t);let n=Oe(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qt=S(`$ZodCheckStartsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`^${Oe(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Jt=S(`$ZodCheckEndsWith`,(e,t)=>{P.init(e,t);let n=RegExp(`.*${Oe(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Yt=S(`$ZodCheckOverwrite`,(e,t)=>{P.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Xt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
2
2
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
3
|
-
`))}};const
|
|
3
|
+
`))}};const Zt={major:4,minor:3,patch:6},F=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zt;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=j(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new C;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=j(e,t))});else{if(e.issues.length===t)continue;r||=j(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(j(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(e=>t(e,r,a))}return t(o,r,a)}}T(e,`~standard`,()=>({validate:t=>{try{let n=Ye(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ze(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Qt=S(`$ZodString`,(e,t)=>{F.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??kt(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),I=S(`$ZodStringFormat`,(e,t)=>{Ht.init(e,t),Qt.init(e,t)}),$t=S(`$ZodGUID`,(e,t)=>{t.pattern??=pt,I.init(e,t)}),en=S(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=mt(e)}else t.pattern??=mt();I.init(e,t)}),tn=S(`$ZodEmail`,(e,t)=>{t.pattern??=ht,I.init(e,t)}),nn=S(`$ZodURL`,(e,t)=>{I.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),rn=S(`$ZodEmoji`,(e,t)=>{t.pattern??=gt(),I.init(e,t)}),an=S(`$ZodNanoID`,(e,t)=>{t.pattern??=dt,I.init(e,t)}),on=S(`$ZodCUID`,(e,t)=>{t.pattern??=ot,I.init(e,t)}),sn=S(`$ZodCUID2`,(e,t)=>{t.pattern??=st,I.init(e,t)}),cn=S(`$ZodULID`,(e,t)=>{t.pattern??=ct,I.init(e,t)}),ln=S(`$ZodXID`,(e,t)=>{t.pattern??=lt,I.init(e,t)}),un=S(`$ZodKSUID`,(e,t)=>{t.pattern??=ut,I.init(e,t)}),dn=S(`$ZodISODateTime`,(e,t)=>{t.pattern??=Ot(t),I.init(e,t)}),fn=S(`$ZodISODate`,(e,t)=>{t.pattern??=Tt,I.init(e,t)}),pn=S(`$ZodISOTime`,(e,t)=>{t.pattern??=Dt(t),I.init(e,t)}),mn=S(`$ZodISODuration`,(e,t)=>{t.pattern??=ft,I.init(e,t)}),hn=S(`$ZodIPv4`,(e,t)=>{t.pattern??=_t,I.init(e,t),e._zod.bag.format=`ipv4`}),gn=S(`$ZodIPv6`,(e,t)=>{t.pattern??=vt,I.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),_n=S(`$ZodCIDRv4`,(e,t)=>{t.pattern??=yt,I.init(e,t)}),vn=S(`$ZodCIDRv6`,(e,t)=>{t.pattern??=bt,I.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function yn(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const bn=S(`$ZodBase64`,(e,t)=>{t.pattern??=xt,I.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{yn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function xn(e){if(!St.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return yn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Sn=S(`$ZodBase64URL`,(e,t)=>{t.pattern??=St,I.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{xn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Cn=S(`$ZodE164`,(e,t)=>{t.pattern??=Ct,I.init(e,t)});function wn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Tn=S(`$ZodJWT`,(e,t)=>{I.init(e,t),e._zod.check=n=>{wn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),En=S(`$ZodNumber`,(e,t)=>{F.init(e,t),e._zod.pattern=e._zod.bag.pattern??jt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Dn=S(`$ZodNumberFormat`,(e,t)=>{Rt.init(e,t),En.init(e,t)}),On=S(`$ZodUnknown`,(e,t)=>{F.init(e,t),e._zod.parse=e=>e}),kn=S(`$ZodNever`,(e,t)=>{F.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function An(e,t,n){e.issues.length&&t.issues.push(...Re(n,e.issues)),t.value[n]=e.value}const jn=S(`$ZodArray`,(e,t)=>{F.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>An(t,n,e))):An(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Mn(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...Re(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Nn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=ke(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Pn(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Mn(e,n,i,t,u))):Mn(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Fn=S(`$ZodObject`,(e,t)=>{if(F.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=ge(()=>Nn(t));T(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=we,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>Mn(n,t,e,s,r))):Mn(i,t,e,s,r)}return i?Pn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),In=S(`$ZodObjectJIT`,(e,t)=>{Fn.init(e,t);let n=e._zod.parse,r=ge(()=>Nn(t)),i=e=>{let t=new Xt([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=xe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=xe(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(`
|
|
4
4
|
if (${n}.issues.length) {
|
|
5
5
|
if (${o} in input) {
|
|
6
6
|
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
@@ -34,7 +34,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
34
34
|
newResult[${o}] = ${n}.value;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Se,s=!de.jitless,c=s&&Ce.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Mn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Fn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!j(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>M(e,r,w())))}),t)}const In=S(`$ZodUnion`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),T(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),T(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),T(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ge(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>Fn(t,i,e,a)):Fn(s,i,e,a)}}),Ln=S(`$ZodIntersection`,(e,t)=>{F.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>zn(e,t,n)):zn(e,i,a)}});function Rn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(O(e)&&O(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Rn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Rn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function zn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),j(e))return e;let o=Rn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const Bn=S(`$ZodEnum`,(e,t)=>{F.init(e,t);let n=fe(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Te.has(typeof e)).map(e=>typeof e==`string`?Ee(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Vn=S(`$ZodTransform`,(e,t)=>{F.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ue(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new C;return n.value=i,n}});function Hn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Un=S(`$ZodOptional`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),T(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ge(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Hn(t,e.value)):Hn(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Wn=S(`$ZodExactOptional`,(e,t)=>{Un.init(e,t),T(e._zod,`values`,()=>t.innerType._zod.values),T(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Gn=S(`$ZodNullable`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.innerType._zod.optin),T(e._zod,`optout`,()=>t.innerType._zod.optout),T(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ge(e.source)}|null)$`):void 0}),T(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Kn=S(`$ZodDefault`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>qn(e,t)):qn(r,t)}});function qn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Jn=S(`$ZodPrefault`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Yn=S(`$ZodNonOptional`,(e,t)=>{F.init(e,t),T(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Xn(t,e)):Xn(i,e)}});function Xn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const Zn=S(`$ZodCatch`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.innerType._zod.optin),T(e._zod,`optout`,()=>t.innerType._zod.optout),T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>M(e,n,w()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>M(e,n,w()))},input:e.value}),e.issues=[]),e)}}),Qn=S(`$ZodPipe`,(e,t)=>{F.init(e,t),T(e._zod,`values`,()=>t.in._zod.values),T(e._zod,`optin`,()=>t.in._zod.optin),T(e._zod,`optout`,()=>t.out._zod.optout),T(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>$n(e,t.in,n)):$n(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>$n(e,t.out,n)):$n(r,t.out,n)}});function $n(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const er=S(`$ZodReadonly`,(e,t)=>{F.init(e,t),T(e._zod,`propValues`,()=>t.innerType._zod.propValues),T(e._zod,`values`,()=>t.innerType._zod.values),T(e._zod,`optin`,()=>t.innerType?._zod?.optin),T(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(tr):tr(r)}});function tr(e){return e.value=Object.freeze(e.value),e}const nr=S(`$ZodCustom`,(e,t)=>{P.init(e,t),F.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>rr(t,n,r,e));rr(i,n,r,e)}});function rr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(N(e))}}var ir,ar=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function or(){return new ar}(ir=globalThis).__zod_globalRegistry??(ir.__zod_globalRegistry=or());const L=globalThis.__zod_globalRegistry;function sr(e,t){return new e({type:`string`,...A(t)})}function cr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...A(t)})}function lr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...A(t)})}function ur(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...A(t)})}function dr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...A(t)})}function fr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...A(t)})}function pr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...A(t)})}function mr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...A(t)})}function hr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...A(t)})}function gr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...A(t)})}function _r(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...A(t)})}function vr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...A(t)})}function yr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...A(t)})}function br(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...A(t)})}function xr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...A(t)})}function Sr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...A(t)})}function Cr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...A(t)})}function wr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...A(t)})}function Tr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...A(t)})}function Er(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...A(t)})}function Dr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...A(t)})}function Or(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...A(t)})}function kr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...A(t)})}function Ar(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...A(t)})}function jr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...A(t)})}function Mr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...A(t)})}function Nr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...A(t)})}function Pr(e,t){return new e({type:`number`,checks:[],...A(t)})}function Fr(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...A(t)})}function Ir(e){return new e({type:`unknown`})}function Lr(e,t){return new e({type:`never`,...A(t)})}function Rr(e,t){return new Nt({check:`less_than`,...A(t),value:e,inclusive:!1})}function zr(e,t){return new Nt({check:`less_than`,...A(t),value:e,inclusive:!0})}function Br(e,t){return new Pt({check:`greater_than`,...A(t),value:e,inclusive:!1})}function Vr(e,t){return new Pt({check:`greater_than`,...A(t),value:e,inclusive:!0})}function Hr(e,t){return new Ft({check:`multiple_of`,...A(t),value:e})}function Ur(e,t){return new Lt({check:`max_length`,...A(t),maximum:e})}function Wr(e,t){return new Rt({check:`min_length`,...A(t),minimum:e})}function Gr(e,t){return new zt({check:`length_equals`,...A(t),length:e})}function Kr(e,t){return new Vt({check:`string_format`,format:`regex`,...A(t),pattern:e})}function qr(e){return new Ht({check:`string_format`,format:`lowercase`,...A(e)})}function Jr(e){return new Ut({check:`string_format`,format:`uppercase`,...A(e)})}function Yr(e,t){return new Wt({check:`string_format`,format:`includes`,...A(t),includes:e})}function Xr(e,t){return new Gt({check:`string_format`,format:`starts_with`,...A(t),prefix:e})}function Zr(e,t){return new Kt({check:`string_format`,format:`ends_with`,...A(t),suffix:e})}function R(e){return new qt({check:`overwrite`,tx:e})}function Qr(e){return R(t=>t.normalize(e))}function $r(){return R(e=>e.trim())}function ei(){return R(e=>e.toLowerCase())}function ti(){return R(e=>e.toUpperCase())}function ni(){return R(e=>be(e))}function ri(e,t,n){return new e({type:`array`,element:t,...A(n)})}function ii(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...A(n)})}function ai(e){let t=oi(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(N(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(N(r))}},e(n.value,n)));return t}function oi(e,t){let n=new P({check:`custom`,...A(t)});return n._zod.check=e,n}function si(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??L,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function z(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,z(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&B(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ci(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
37
|
+
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=we,s=!pe.jitless,c=s&&Te.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Pn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Ln(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!j(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>M(e,r,w())))}),t)}const Rn=S(`$ZodUnion`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),T(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),T(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),T(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ve(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>Ln(t,i,e,a)):Ln(s,i,e,a)}}),zn=S(`$ZodIntersection`,(e,t)=>{F.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Vn(e,t,n)):Vn(e,i,a)}});function Bn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(O(e)&&O(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Bn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Bn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),j(e))return e;let o=Bn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const Hn=S(`$ZodEnum`,(e,t)=>{F.init(e,t);let n=me(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>De.has(typeof e)).map(e=>typeof e==`string`?Oe(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Un=S(`$ZodTransform`,(e,t)=>{F.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new fe(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new C;return n.value=i,n}});function Wn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Gn=S(`$ZodOptional`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),T(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ve(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Wn(t,e.value)):Wn(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Kn=S(`$ZodExactOptional`,(e,t)=>{Gn.init(e,t),T(e._zod,`values`,()=>t.innerType._zod.values),T(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),qn=S(`$ZodNullable`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.innerType._zod.optin),T(e._zod,`optout`,()=>t.innerType._zod.optout),T(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ve(e.source)}|null)$`):void 0}),T(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Jn=S(`$ZodDefault`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Yn(e,t)):Yn(r,t)}});function Yn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Xn=S(`$ZodPrefault`,(e,t)=>{F.init(e,t),e._zod.optin=`optional`,T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Zn=S(`$ZodNonOptional`,(e,t)=>{F.init(e,t),T(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Qn(t,e)):Qn(i,e)}});function Qn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const $n=S(`$ZodCatch`,(e,t)=>{F.init(e,t),T(e._zod,`optin`,()=>t.innerType._zod.optin),T(e._zod,`optout`,()=>t.innerType._zod.optout),T(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>M(e,n,w()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>M(e,n,w()))},input:e.value}),e.issues=[]),e)}}),er=S(`$ZodPipe`,(e,t)=>{F.init(e,t),T(e._zod,`values`,()=>t.in._zod.values),T(e._zod,`optin`,()=>t.in._zod.optin),T(e._zod,`optout`,()=>t.out._zod.optout),T(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>tr(e,t.in,n)):tr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>tr(e,t.out,n)):tr(r,t.out,n)}});function tr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const nr=S(`$ZodReadonly`,(e,t)=>{F.init(e,t),T(e._zod,`propValues`,()=>t.innerType._zod.propValues),T(e._zod,`values`,()=>t.innerType._zod.values),T(e._zod,`optin`,()=>t.innerType?._zod?.optin),T(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(rr):rr(r)}});function rr(e){return e.value=Object.freeze(e.value),e}const ir=S(`$ZodCustom`,(e,t)=>{P.init(e,t),F.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>ar(t,n,r,e));ar(i,n,r,e)}});function ar(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(N(e))}}var or,sr=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function cr(){return new sr}(or=globalThis).__zod_globalRegistry??(or.__zod_globalRegistry=cr());const L=globalThis.__zod_globalRegistry;function lr(e,t){return new e({type:`string`,...A(t)})}function ur(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...A(t)})}function dr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...A(t)})}function fr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...A(t)})}function pr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...A(t)})}function mr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...A(t)})}function hr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...A(t)})}function gr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...A(t)})}function _r(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...A(t)})}function vr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...A(t)})}function yr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...A(t)})}function br(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...A(t)})}function xr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...A(t)})}function Sr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...A(t)})}function Cr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...A(t)})}function wr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...A(t)})}function Tr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...A(t)})}function Er(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...A(t)})}function Dr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...A(t)})}function Or(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...A(t)})}function kr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...A(t)})}function Ar(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...A(t)})}function jr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...A(t)})}function Mr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...A(t)})}function Nr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...A(t)})}function Pr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...A(t)})}function Fr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...A(t)})}function Ir(e,t){return new e({type:`number`,checks:[],...A(t)})}function Lr(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...A(t)})}function Rr(e){return new e({type:`unknown`})}function zr(e,t){return new e({type:`never`,...A(t)})}function Br(e,t){return new Ft({check:`less_than`,...A(t),value:e,inclusive:!1})}function Vr(e,t){return new Ft({check:`less_than`,...A(t),value:e,inclusive:!0})}function Hr(e,t){return new It({check:`greater_than`,...A(t),value:e,inclusive:!1})}function Ur(e,t){return new It({check:`greater_than`,...A(t),value:e,inclusive:!0})}function Wr(e,t){return new Lt({check:`multiple_of`,...A(t),value:e})}function Gr(e,t){return new zt({check:`max_length`,...A(t),maximum:e})}function Kr(e,t){return new Bt({check:`min_length`,...A(t),minimum:e})}function qr(e,t){return new Vt({check:`length_equals`,...A(t),length:e})}function Jr(e,t){return new Ut({check:`string_format`,format:`regex`,...A(t),pattern:e})}function Yr(e){return new Wt({check:`string_format`,format:`lowercase`,...A(e)})}function Xr(e){return new Gt({check:`string_format`,format:`uppercase`,...A(e)})}function Zr(e,t){return new Kt({check:`string_format`,format:`includes`,...A(t),includes:e})}function Qr(e,t){return new qt({check:`string_format`,format:`starts_with`,...A(t),prefix:e})}function $r(e,t){return new Jt({check:`string_format`,format:`ends_with`,...A(t),suffix:e})}function R(e){return new Yt({check:`overwrite`,tx:e})}function ei(e){return R(t=>t.normalize(e))}function ti(){return R(e=>e.trim())}function ni(){return R(e=>e.toLowerCase())}function ri(){return R(e=>e.toUpperCase())}function ii(){return R(e=>Se(e))}function ai(e,t,n){return new e({type:`array`,element:t,...A(n)})}function oi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...A(n)})}function si(e){let t=ci(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(N(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(N(r))}},e(n.value,n)));return t}function ci(e,t){let n=new P({check:`custom`,...A(t)});return n._zod.check=e,n}function li(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??L,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function z(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,z(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&B(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ui(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
38
38
|
|
|
39
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function li(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:di(t,`input`,e.processors),output:di(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function B(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return B(r.element,n);if(r.type===`set`)return B(r.valueType,n);if(r.type===`lazy`)return B(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return B(r.innerType,n);if(r.type===`intersection`)return B(r.left,n)||B(r.right,n);if(r.type===`record`||r.type===`map`)return B(r.keyType,n)||B(r.valueType,n);if(r.type===`pipe`)return B(r.in,n)||B(r.out,n);if(r.type===`object`){for(let e in r.shape)if(B(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(B(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(B(e,n))return!0;return!!(r.rest&&B(r.rest,n))}return!1}const ui=(e,t={})=>n=>{let r=si({...n,processors:t});return z(e,r),ci(r,e),li(r,e)},di=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=si({...i??{},target:a,io:t,processors:n});return z(e,o),ci(o,e),li(o,e)},fi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},pi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},mi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},hi=(e,t,n,r)=>{n.not={}},gi=(e,t,n,r)=>{let i=e._zod.def,a=fe(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},_i=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},vi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},yi=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=z(a.element,t,{...r,path:[...r.path,`items`]})},bi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=z(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=z(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},xi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>z(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Si=(e,t,n,r)=>{let i=e._zod.def,a=z(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=z(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Ci=(e,t,n,r)=>{let i=e._zod.def,a=z(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},wi=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ti=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ei=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Di=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Oi=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;z(a,t,r);let o=t.seen.get(e);o.ref=a},ki=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ai=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ji=S(`ZodISODateTime`,(e,t)=>{ln.init(e,t),U.init(e,t)});function Mi(e){return Ar(ji,e)}const Ni=S(`ZodISODate`,(e,t)=>{un.init(e,t),U.init(e,t)});function Pi(e){return jr(Ni,e)}const Fi=S(`ZodISOTime`,(e,t)=>{dn.init(e,t),U.init(e,t)});function Ii(e){return Mr(Fi,e)}const Li=S(`ZodISODuration`,(e,t)=>{fn.init(e,t),U.init(e,t)});function Ri(e){return Nr(Li,e)}const zi=(e,t)=>{Be.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ue(e,t)},flatten:{value:t=>He(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,pe,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,pe,2)}},isEmpty:{get(){return e.issues.length===0}}})};S(`ZodError`,zi);const V=S(`ZodError`,zi,{Parent:Error}),Bi=We(V),Vi=Ge(V),Hi=Ke(V),Ui=Je(V),Wi=Xe(V),Gi=Ze(V),Ki=Qe(V),qi=$e(V),Ji=et(V),Yi=tt(V),Xi=nt(V),Zi=rt(V),H=S(`ZodType`,(e,t)=>(F.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:di(e,`input`),output:di(e,`output`)}}),e.toJSONSchema=ui(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(D(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>k(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Bi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Hi(e,t,n),e.parseAsync=async(t,n)=>Vi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ui(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Wi(e,t,n),e.decode=(t,n)=>Gi(e,t,n),e.encodeAsync=async(t,n)=>Ki(e,t,n),e.decodeAsync=async(t,n)=>qi(e,t,n),e.safeEncode=(t,n)=>Ji(e,t,n),e.safeDecode=(t,n)=>Yi(e,t,n),e.safeEncodeAsync=async(t,n)=>Xi(e,t,n),e.safeDecodeAsync=async(t,n)=>Zi(e,t,n),e.refine=(t,n)=>e.check(io(t,n)),e.superRefine=t=>e.check(ao(t)),e.overwrite=t=>e.check(R(t)),e.optional=()=>Ba(e),e.exactOptional=()=>Ha(e),e.nullable=()=>Wa(e),e.nullish=()=>Ba(Wa(e)),e.nonoptional=t=>Xa(e,t),e.array=()=>Oa(e),e.or=t=>Ma([e,t]),e.and=t=>Pa(e,t),e.transform=t=>eo(e,Ra(t)),e.default=t=>Ka(e,t),e.prefault=t=>Ja(e,t),e.catch=t=>Qa(e,t),e.pipe=t=>eo(e,t),e.readonly=()=>no(e),e.describe=t=>{let n=e.clone();return L.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return L.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return L.get(e);let n=e.clone();return L.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Qi=S(`_ZodString`,(e,t)=>{Xt.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Kr(...t)),e.includes=(...t)=>e.check(Yr(...t)),e.startsWith=(...t)=>e.check(Xr(...t)),e.endsWith=(...t)=>e.check(Zr(...t)),e.min=(...t)=>e.check(Wr(...t)),e.max=(...t)=>e.check(Ur(...t)),e.length=(...t)=>e.check(Gr(...t)),e.nonempty=(...t)=>e.check(Wr(1,...t)),e.lowercase=t=>e.check(qr(t)),e.uppercase=t=>e.check(Jr(t)),e.trim=()=>e.check($r()),e.normalize=(...t)=>e.check(Qr(...t)),e.toLowerCase=()=>e.check(ei()),e.toUpperCase=()=>e.check(ti()),e.slugify=()=>e.check(ni())}),$i=S(`ZodString`,(e,t)=>{Xt.init(e,t),Qi.init(e,t),e.email=t=>e.check(cr(ta,t)),e.url=t=>e.check(mr(ia,t)),e.jwt=t=>e.check(kr(ya,t)),e.emoji=t=>e.check(hr(aa,t)),e.guid=t=>e.check(lr(na,t)),e.uuid=t=>e.check(ur(ra,t)),e.uuidv4=t=>e.check(dr(ra,t)),e.uuidv6=t=>e.check(fr(ra,t)),e.uuidv7=t=>e.check(pr(ra,t)),e.nanoid=t=>e.check(gr(oa,t)),e.guid=t=>e.check(lr(na,t)),e.cuid=t=>e.check(_r(sa,t)),e.cuid2=t=>e.check(vr(ca,t)),e.ulid=t=>e.check(yr(la,t)),e.base64=t=>e.check(Er(ga,t)),e.base64url=t=>e.check(Dr(_a,t)),e.xid=t=>e.check(br(ua,t)),e.ksuid=t=>e.check(xr(da,t)),e.ipv4=t=>e.check(Sr(fa,t)),e.ipv6=t=>e.check(Cr(pa,t)),e.cidrv4=t=>e.check(wr(ma,t)),e.cidrv6=t=>e.check(Tr(ha,t)),e.e164=t=>e.check(Or(va,t)),e.datetime=t=>e.check(Mi(t)),e.date=t=>e.check(Pi(t)),e.time=t=>e.check(Ii(t)),e.duration=t=>e.check(Ri(t))});function ea(e){return sr($i,e)}const U=S(`ZodStringFormat`,(e,t)=>{I.init(e,t),Qi.init(e,t)}),ta=S(`ZodEmail`,(e,t)=>{$t.init(e,t),U.init(e,t)}),na=S(`ZodGUID`,(e,t)=>{Zt.init(e,t),U.init(e,t)}),ra=S(`ZodUUID`,(e,t)=>{Qt.init(e,t),U.init(e,t)}),ia=S(`ZodURL`,(e,t)=>{en.init(e,t),U.init(e,t)}),aa=S(`ZodEmoji`,(e,t)=>{tn.init(e,t),U.init(e,t)}),oa=S(`ZodNanoID`,(e,t)=>{nn.init(e,t),U.init(e,t)}),sa=S(`ZodCUID`,(e,t)=>{rn.init(e,t),U.init(e,t)}),ca=S(`ZodCUID2`,(e,t)=>{an.init(e,t),U.init(e,t)}),la=S(`ZodULID`,(e,t)=>{on.init(e,t),U.init(e,t)}),ua=S(`ZodXID`,(e,t)=>{sn.init(e,t),U.init(e,t)}),da=S(`ZodKSUID`,(e,t)=>{cn.init(e,t),U.init(e,t)}),fa=S(`ZodIPv4`,(e,t)=>{pn.init(e,t),U.init(e,t)}),pa=S(`ZodIPv6`,(e,t)=>{mn.init(e,t),U.init(e,t)}),ma=S(`ZodCIDRv4`,(e,t)=>{hn.init(e,t),U.init(e,t)}),ha=S(`ZodCIDRv6`,(e,t)=>{gn.init(e,t),U.init(e,t)}),ga=S(`ZodBase64`,(e,t)=>{vn.init(e,t),U.init(e,t)}),_a=S(`ZodBase64URL`,(e,t)=>{bn.init(e,t),U.init(e,t)}),va=S(`ZodE164`,(e,t)=>{xn.init(e,t),U.init(e,t)}),ya=S(`ZodJWT`,(e,t)=>{Cn.init(e,t),U.init(e,t)}),ba=S(`ZodNumber`,(e,t)=>{wn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),e.gt=(t,n)=>e.check(Br(t,n)),e.gte=(t,n)=>e.check(Vr(t,n)),e.min=(t,n)=>e.check(Vr(t,n)),e.lt=(t,n)=>e.check(Rr(t,n)),e.lte=(t,n)=>e.check(zr(t,n)),e.max=(t,n)=>e.check(zr(t,n)),e.int=t=>e.check(Sa(t)),e.safe=t=>e.check(Sa(t)),e.positive=t=>e.check(Br(0,t)),e.nonnegative=t=>e.check(Vr(0,t)),e.negative=t=>e.check(Rr(0,t)),e.nonpositive=t=>e.check(zr(0,t)),e.multipleOf=(t,n)=>e.check(Hr(t,n)),e.step=(t,n)=>e.check(Hr(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function W(e){return Pr(ba,e)}const xa=S(`ZodNumberFormat`,(e,t)=>{Tn.init(e,t),ba.init(e,t)});function Sa(e){return Fr(xa,e)}const Ca=S(`ZodUnknown`,(e,t)=>{En.init(e,t),H.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function wa(){return Ir(Ca)}const Ta=S(`ZodNever`,(e,t)=>{Dn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r)});function Ea(e){return Lr(Ta,e)}const Da=S(`ZodArray`,(e,t)=>{kn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yi(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(Wr(t,n)),e.nonempty=t=>e.check(Wr(1,t)),e.max=(t,n)=>e.check(Ur(t,n)),e.length=(t,n)=>e.check(Gr(t,n)),e.unwrap=()=>e.element});function Oa(e,t){return ri(Da,e,t)}const ka=S(`ZodObject`,(e,t)=>{Pn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bi(e,t,n,r),T(e,`shape`,()=>t.shape),e.keyof=()=>Ia(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wa()}),e.loose=()=>e.clone({...e._zod.def,catchall:wa()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ea()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>je(e,t),e.safeExtend=t=>Me(e,t),e.merge=t=>Ne(e,t),e.pick=t=>ke(e,t),e.omit=t=>Ae(e,t),e.partial=(...t)=>Pe(za,e,t[0]),e.required=(...t)=>Fe(Ya,e,t[0])});function Aa(e,t){return new ka({type:`object`,shape:e??{},...A(t)})}const ja=S(`ZodUnion`,(e,t)=>{In.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r),e.options=t.options});function Ma(e,t){return new ja({type:`union`,options:e,...A(t)})}const Na=S(`ZodIntersection`,(e,t)=>{Ln.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Si(e,t,n,r)});function Pa(e,t){return new Na({type:`intersection`,left:e,right:t})}const Fa=S(`ZodEnum`,(e,t)=>{Bn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Fa({...t,checks:[],...A(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Fa({...t,checks:[],...A(r),entries:i})}});function Ia(e,t){return new Fa({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...A(t)})}const La=S(`ZodTransform`,(e,t)=>{Vn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ue(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(N(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(N(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ra(e){return new La({type:`transform`,transform:e})}const za=S(`ZodOptional`,(e,t)=>{Un.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ba(e){return new za({type:`optional`,innerType:e})}const Va=S(`ZodExactOptional`,(e,t)=>{Wn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ha(e){return new Va({type:`optional`,innerType:e})}const Ua=S(`ZodNullable`,(e,t)=>{Gn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ci(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wa(e){return new Ua({type:`nullable`,innerType:e})}const Ga=S(`ZodDefault`,(e,t)=>{Kn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ka(e,t){return new Ga({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():we(t)}})}const qa=S(`ZodPrefault`,(e,t)=>{Jn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ja(e,t){return new qa({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():we(t)}})}const Ya=S(`ZodNonOptional`,(e,t)=>{Yn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xa(e,t){return new Ya({type:`nonoptional`,innerType:e,...A(t)})}const Za=S(`ZodCatch`,(e,t)=>{Zn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Di(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qa(e,t){return new Za({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const $a=S(`ZodPipe`,(e,t)=>{Qn.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oi(e,t,n,r),e.in=t.in,e.out=t.out});function eo(e,t){return new $a({type:`pipe`,in:e,out:t})}const to=S(`ZodReadonly`,(e,t)=>{er.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ki(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function no(e){return new to({type:`readonly`,innerType:e})}const ro=S(`ZodCustom`,(e,t)=>{nr.init(e,t),H.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r)});function io(e,t={}){return ii(ro,e,t)}function ao(e){return ai(e)}const oo=86400;function so(){return Math.floor(Date.now()/1e3)}function G(e){return(0,u.getAddress)(e)}function co(e){return[...new Set(e.map(G))].toSorted()}const lo=ea().refine(e=>(0,u.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),uo=ea().refine(e=>(0,u.isAddress)(e,{strict:!1}),`expected EVM address`).transform(e=>G(e)),fo=W().finite().int().nonnegative(),po=W().finite().int().positive(),mo=W().finite().int().positive(),ho=W().finite().int().positive(),go=`keypairTTL must be a positive integer number of seconds`,_o=`permitTTL must be a positive integer number of days`,vo=365*oo,yo=W(go).finite(go).int(go).positive(go).max(vo,`keypairTTL must not exceed the fhevm ACL maximum of ${vo}s (365 days)`),bo=W(_o).finite(_o).int(_o).positive(_o),xo=Aa({publicKey:lo,privateKey:lo,createdAt:fo,expiresAt:po}),So=Aa({keypairPublicKey:lo,signerAddress:uo,delegatorAddress:uo,chainId:ho,signedContractAddresses:Oa(uo).max(10),signature:lo,startTimestamp:fo,durationDays:mo}),Co=Oa(So),wo=Oa(ea());var To=class{#e;#t;#n;#r=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl}async readStored(e){let t=ce(e),n=await this.#t.get(t);if(n==null)return null;let r=xo.safeParse(n);if(!r.success)return await s.t(`delete keypair entry`,()=>this.#t.delete(t)),null;let i=r.data;return so()>=i.expiresAt?(await s.t(`delete keypair entry`,()=>this.#t.delete(t)),null):i}async getOrCreate(e){let t=this.#r.get(e);if(t)return t;let n=(async()=>{let t=await this.readStored(e);if(t!==null)return t;let n=await this.#e(),r=so(),i={publicKey:n.publicKey,privateKey:n.privateKey,createdAt:r,expiresAt:r+this.#n},a=ce(e);return await s.t(`persist keypair`,()=>this.#t.set(a,i)),i})().finally(()=>{this.#r.delete(e)});return this.#r.set(e,n),n}async clear(e){let t=ce(e);await s.t(`delete keypair entry`,()=>this.#t.delete(t))}};function Eo(e,t){let n=new Set(e.flatMap(e=>e.signedContractAddresses));return t.filter(e=>!n.has(e))}function Do(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function Oo(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function ko(e,t){let n=new Set(t);return e.filter(e=>!e.signedContractAddresses.some(e=>n.has(e)))}var Ao=class{#e;constructor(e){this.#e=e.storage}async list(e){let t=x(e),n=await this.#e.get(t);if(n==null)return[];let r=Co.safeParse(n);return r.success?r.data:(await this.#i(t),await this.#r(e),[])}async listUsableAndPrune(e,t){let n=await this.list(e),r=Oo(n,t,Math.floor(Date.now()/1e3));if(r.length!==n.length){let t=x(e);r.length===0?(await this.#i(t),await this.#r(e)):await s.t(`update permit entry`,()=>this.#e.set(t,r))}return r}async append(e,t){if(t.length===0)return;let n=t.map(e=>So.parse(e)),r=await this.list(e);await this.#e.set(x(e),[...r,...n]),await this.#n(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=x(e),i=ko(n,t);i.length===0?(await this.#i(r),await this.#r(e)):await this.#e.set(r,i)}async clearAllForSigner(e){let t=le(e),n=await this.#t(t);await Promise.all(n.map(e=>this.#i(e))),await s.t(`delete permit index`,()=>this.#e.delete(t))}async#t(e){let t=await this.#e.get(e);if(t==null)return[];let n=wo.safeParse(t);return n.success?n.data:(await s.t(`delete permit index`,()=>this.#e.delete(e)),[])}async#n(e){let t=le(e.signerAddress),n=x(e),r=await this.#t(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#r(e){let t=le(e.signerAddress),n=x(e),r=await this.#t(t),i=r.filter(e=>e!==n);i.length!==r.length&&(i.length===0?await s.t(`delete permit index`,()=>this.#e.delete(t)):await s.t(`update permit index`,()=>this.#e.set(t,i)))}async#i(e){await s.t(`delete permit entry`,()=>this.#e.delete(e))}};30*oo;var jo=class{#e;#t;#n;#r;#i;constructor(e){this.#e=new To({generator:()=>e.relayer.generateKeypair(),storage:e.storage,ttl:e.keypairTTL}),this.#t=new Ao({storage:e.permitStorage??e.storage}),this.#n=e.relayer,this.#r=e.signer,this.#i=e.permitTTL}async allow(e,t){let n=this.#r.requireWalletAccount(`allow`),r=G(n.address),i=co(e),a=await this.#e.getOrCreate(r);if(i.length===0)return{keypair:a,permits:[]};let o={signerAddress:r,chainId:n.chainId,delegatorAddress:t?G(t):r},c=await this.#t.listUsableAndPrune(o,a.publicKey);for(let e of Do(Eo(c,i))){let t=await this.#a({chunk:e,keypair:a,scope:o});c.push(t),await s.t(`persist permit`,()=>this.#t.append(o,[t]))}let l=new Set(i);return{keypair:a,permits:c.filter(e=>e.signedContractAddresses.some(e=>l.has(e)))}}async isAllowed(e,t){if(e.length===0)return!0;let n=this.#r.walletAccount.getSnapshot();if(!n)return!1;let r=G(n.address),i=await this.#e.readStored(r);if(i===null)return!1;let a={signerAddress:r,chainId:n.chainId,delegatorAddress:t?G(t):r};return Eo(await this.#t.listUsableAndPrune(a,i.publicKey),co(e)).length===0}async revokePermits(e){let t=this.#r.requireWalletAccount(`revokePermits`),n=G(t.address);if(e===void 0){await this.#t.clearAllForSigner(n);return}let r=co(e);if(r.length===0)return;let i=t.chainId;await this.#t.deletePermitsTouching({signerAddress:n,chainId:i,delegatorAddress:n},r)}async clearCredentials(){let e=G(this.#r.requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async handleWalletAccountChange(e,t){let n=e?G(e.address):void 0,r=t?G(t.address):void 0;n!==r&&(n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n)),r&&await s.t(`warm keypair`,async()=>{await this.#e.getOrCreate(r)}))}async#a(n){let{chunk:r,keypair:i,scope:a}=n,o=so(),s=a.delegatorAddress!==a.signerAddress;try{let e=s?await this.#n.createDelegatedUserDecryptEIP712(i.publicKey,r,a.delegatorAddress,o,this.#i):await this.#n.createEIP712(i.publicKey,r,o,this.#i),t=await this.#r.signTypedData(e);return{keypairPublicKey:i.publicKey,signerAddress:a.signerAddress,delegatorAddress:a.delegatorAddress,chainId:a.chainId,signedContractAddresses:r,signature:t,startTimestamp:o,durationDays:this.#i}}catch(n){throw n instanceof e.r?n:t.A(n,`Credential signing failed`)}}};function Mo(e,t){let r=Fo(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return Po(e,r)}function No(e,t){let r=Fo(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...Po(e,r),delegatorAddress:r.delegatorAddress}}function Po(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function Fo(e,t){let n=G(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}async function Io(e){let{provider:n,aclAddress:r,delegatorAddress:i,delegateAddress:a,contractAddress:o}=e,s=await n.readContract(t.o(r,i,a,o));return s===0n?!1:s===t.i?!0:s>await n.getBlockTimestamp()}async function Lo(e){let{provider:t,relayer:n,contractAddresses:r,delegatorAddress:i,delegateAddress:a}=e;if(r.length===0)return new Set;let o=await n.getAclAddress(),s=await Promise.all(r.map(async e=>({contractAddress:e,active:await Io({provider:t,aclAddress:o,delegatorAddress:i,delegateAddress:a,contractAddress:e})}))),c=new Set;for(let{contractAddress:e,active:t}of s)t||c.add(e);return c}function K(e){return(0,u.keccak256)((0,u.toBytes)(e))}const q={ConfidentialTransfer:K(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:K(`Wrapped(address,uint256)`),UnwrapRequested:K(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:K(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:K(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:K(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:K(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:K(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function J(e){return(0,u.getAddress)(ae(e.slice(-40)))}function Ro(e){return BigInt(e)}function zo(e){return e}function Bo(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Vo(e,t){return(0,u.getAddress)(ae(Bo(e,t).slice(-40)))}function Y(e,t){return BigInt(`0x`+Bo(e,t))}function Ho(e,t){return BigInt(`0x`+Bo(e,t))!==0n}function X(e,t){return ae(Bo(e,t))}function Uo(e){return e.topics[0]!==q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:J(e.topics[1]),to:J(e.topics[2]),encryptedAmountHandle:zo(e.topics[3])}}function Wo(e){return e.topics[0]!==q.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:J(e.topics[1]),amountIn:Y(e.data,0)}}function Go(e){return e.topics[0]===q.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:J(e.topics[1]),unwrapRequestId:zo(e.topics[2]),encryptedAmount:X(e.data,0)}:e.topics[0]===q.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:J(e.topics[1]),encryptedAmount:X(e.data,0)}:null}function Z(e){return e.topics[0]===q.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:J(e.topics[1]),unwrapRequestId:zo(e.topics[2]),encryptedAmount:X(e.data,0),cleartextAmount:Y(e.data,1)}:e.topics[0]===q.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:J(e.topics[1]),encryptedAmount:X(e.data,0),cleartextAmount:Y(e.data,1)}:null}function Ko(e){let t=Z(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function qo(e){if(e.topics[0]!==q.UnwrapFinalizedLegacy)return null;let t=Z(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Jo(e){return e.topics[0]!==q.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ro(e.topics[1]),txId:Ro(e.topics[2]),to:J(e.topics[3]),returnVal:Ho(e.data,0),refund:Vo(e.data,1),requestedAmount:X(e.data,2),burnAmount:X(e.data,3)}}function Yo(e){return Uo(e)??Wo(e)??Go(e)??qo(e)??Z(e)??Jo(e)}function Xo(e){let t=[];for(let n of e){let e=Yo(n);e&&t.push(e)}return t}function Zo(e){for(let t of e){let e=Go(t);if(e)return e}return null}function Qo(e){for(let t of e){let e=Wo(t);if(e)return e}return null}const $o=[q.ConfidentialTransfer,q.Wrapped,q.UnwrapRequested,q.UnwrapRequestedLegacy,q.UnwrapFinalized,q.UnwrapFinalizedLegacy,q.UnwrappedStarted],Q={DelegatedForUserDecryption:K(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:K(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function es(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:J(e.topics[1]),delegate:J(e.topics[2]),contractAddress:Vo(e.data,0),delegationCounter:Y(e.data,1),oldExpirationDate:Y(e.data,2),newExpirationDate:Y(e.data,3)}}function ts(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:J(e.topics[1]),delegate:J(e.topics[2]),contractAddress:Vo(e.data,0),delegationCounter:Y(e.data,1),oldExpirationDate:Y(e.data,2)}}function ns(e){return es(e)??ts(e)}function rs(e){let t=[];for(let n of e){let e=ns(n);e&&t.push(e)}return t}function is(e){for(let t of e){let e=es(t);if(e)return e}return null}function as(e){for(let t of e){let e=ts(t);if(e)return e}return null}const os=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];var ss=class r extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,u.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(l.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(r,i,a){let s=this.sdk.requireSigner(`confidentialTransfer`),c=await this.sdk.requireAlignedWalletAccount(`confidentialTransfer`),{skipBalanceCheck:d=!1,onEncryptComplete:p,onTransferSubmitted:m}=a??{},h=(0,u.getAddress)(r);d||await this.#i(i);let{handles:g,inputProof:_}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:(0,u.getAddress)(c.address)});if($(()=>p?.()),g.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await s.writeContract(l.b(this.address,h,g[0],_));return this.emit({type:t.r.TransferSubmitted,txHash:e}),$(()=>m?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:o.s(n)}),n instanceof e.r?n:new f(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(r,i,a,s){let c=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,u.getAddress)(r),p=(0,u.getAddress)(i),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if($(()=>s?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(l.x(this.address,d,p,m[0],h));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),$(()=>s?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:o.s(n)}),n instanceof e.r?n:new f(`TransferFrom transaction failed`,{cause:n})}}async setOperator(n,r){let i=this.sdk.requireSigner(`setOperator`);await this.sdk.requireChainAlignment(`setOperator`);let a=(0,u.getAddress)(n);try{let e=await i.writeContract(l.w(this.address,a,r));return this.emit({type:t.r.SetOperatorSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`setOperator`,error:o.s(n)}),n instanceof e.r?n:new d(`Operator approval failed`,{cause:n})}}async isOperator(e,t){return this.sdk.provider.readContract(l.S(this.address,(0,u.getAddress)(e),(0,u.getAddress)(t)))}async shield(n,r){let i=this.sdk.requireSigner(`shield`),a=await this.sdk.requireAlignedWalletAccount(`shield`),s=await this.#n(),c=(0,u.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t.d(s,c))}catch(t){throw t instanceof e.r?t:new y(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:o.s(t)})}if(d<n)throw new v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${s})`,{requested:n,available:d,token:s});let p=r?.approvalStrategy??`exact`;p!==`skip`&&await this.#o(n,p===`max`,r);try{let e=r?.to?(0,u.getAddress)(r.to):c,a=await i.writeContract(l._(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:a}),$(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:o.s(n)}),n instanceof e.r?n:new f(`Shield transaction failed`,{cause:n})}}async unwrap(r){let i=this.sdk.requireSigner(`unwrap`),a=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrap`)).address),{handles:s,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});if(s.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await i.writeContract(l.E(this.address,a,a,s[0],c));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`),i=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrapAll`)).address),a=await this.readConfidentialBalanceOf(i);if(t._(a))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(l.D(this.address,i,i,a));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return $(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return $(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];o.t(a,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(l.m(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`),i=await this.sdk.requireAlignedWalletAccount(`approveUnderlying`),a=await this.#n(),s=(0,u.getAddress)(i.address),c=n??2n**256n-1n;try{c>0n&&await this.sdk.provider.readContract(t.l(a,s,this.wrapper))>0n&&await r.writeContract(t.u(a,this.wrapper,0n));let e=await r.writeContract(t.u(a,this.wrapper,c));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:o.s(n)}),n instanceof e.r?n:new d(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`),a=await this.sdk.requireAlignedWalletAccount(`delegateDecryption`);if(r&&r.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let s=(0,u.getAddress)(n),c=(0,u.getAddress)(a.address);if(s===(0,u.getAddress)(c))throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===this.address)throw new t.x(`Delegate address cannot be the same as the contract address (${this.address}).`);let l=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,p;try{p=await this.getDelegationExpiry({delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] Token.delegateDecryption: pre-flight expiry check failed:`,e),p=-1n}if(p===d)throw new t.w(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(t.a(l,s,this.address,d));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:o.s(n)}),n instanceof e.r?n:b(n)||new f(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=this.sdk.requireSigner(`revokeDelegation`),i=await this.sdk.requireAlignedWalletAccount(`revokeDelegation`),a=(0,u.getAddress)(n),s=(0,u.getAddress)(i.address),c=await this.getAclAddress(),l;try{l=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch(e){console.warn(`[zama-sdk] Token.revokeDelegation: pre-flight expiry check failed:`,e),l=1n}if(l===0n)throw new t.T(`No active delegation found for delegate ${a} on contract ${this.address}.`);try{let e=await r.writeContract(t.c(c,a,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:o.s(n)}),n instanceof e.r?n:b(n)||new f(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.r?i.set(t[a].address,n):i.set(t[a].address,new f(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{let e=await this.sdk.requireAlignedWalletAccount(`assertConfidentialBalance`);n=await this.balanceOf((0,u.getAddress)(e.address))}catch(t){throw t instanceof e.r?t:new ee(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new _(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new f(`Failed to get unshield receipt`,{cause:t})}let o=Zo(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),$(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),$(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(n,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#n(),s=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`approveUnderlying`)).address),c=await this.sdk.provider.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{if(c>0n){let e=await a.writeContract(t.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,s=await a.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:s}),$(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(t){throw t instanceof e.r?t:new d(`ERC-20 approval failed`,{cause:t})}}};function $(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const cs={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},ls=300*1e3;var us=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},cs,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,u.getAddress)(n)}async listPairs(t={}){let n=t.page??1,r=t.pageSize??100,i=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(r<1)throw new e.t(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(l.a(a));s=this.#i(o,Number(e))}let c=BigInt((n-1)*r),u=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:n,pageSize:r};let d=`slice:${a}:${c}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(l.o(a,c,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:s,page:n,pageSize:r};let p=`metadata:${a}:${c}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?ls:void 0)}return{items:m,total:s,page:n,pageSize:r}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.m(e.tokenAddress)),this.provider.readContract(t.h(e.tokenAddress)),this.provider.readContract(t.f(e.tokenAddress)),this.provider.readContract(t.p(e.tokenAddress)),this.provider.readContract(t.m(e.confidentialTokenAddress)),this.provider.readContract(t.h(e.confidentialTokenAddress)),this.provider.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.t(t,n));return o===u.zeroAddress?this.#i(r,null,ls):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.n(t,n));return o===u.zeroAddress?this.#i(r,null,ls):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(l.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(l.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(l.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.t(t,(0,u.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.n(t,(0,u.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.s(t,(0,u.getAddress)(e)))}},ds=class{relayer;provider;signer;storage;cache;registry;#e;#t;#n=new Set;#r;#i;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.cache=new se(e.storage),this.#t=e.onEvent??function(){};let t={};for(let n of e.chains??[])n.registryAddress&&(t[n.id]=n.registryAddress);Object.assign(t,e.registryAddresses),this.registry=new us({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n=yo.parse(e.keypairTTL??2592e3),r=bo.parse(e.permitTTL??30);if(e.signer){let t=e.signer;this.#r=new jo({relayer:this.relayer,signer:t,keypairTTL:n,permitTTL:r,storage:this.storage,permitStorage:e.permitStorage}),this.#i=t.walletAccount.subscribe(e=>{this.#o(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})})}else this.#r=void 0}requireSigner(e){if(!this.signer)throw new r.l(e);return this.signer}#a(e){if(!this.#r)throw new r.l(e);return this.#r}onWalletAccountChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireAlignedWalletAccount(e){let t=this.requireSigner(e),n;try{n=t.requireWalletAccount(e)}catch(i){if(!(i instanceof r.d)||!t.refreshWalletAccount)throw i;await t.refreshWalletAccount(),n=t.requireWalletAccount(e)}let i=await this.provider.getChainId();if(n.chainId!==i)throw new g({operation:e,signerChainId:n.chainId,providerChainId:i});return n}async requireChainAlignment(e){return(await this.requireAlignedWalletAccount(e)).chainId}async#o(e){let t=e.previous,n=e.next,r=this.#r;r&&await s.t(`credential wallet account change`,()=>r.handleWalletAccountChange(t,n)),t&&await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(t.address));let i=n?.chainId;i!==void 0&&s.t(`switch relayer chain`,()=>this.relayer.switchChain(i)),await Promise.all(Array.from(this.#n,e=>s.t(`wallet account listener`,()=>e({previous:t,next:n}))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new ss(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new us({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){if(e.length===0)return;let t=this.#a(`allow`);await this.requireChainAlignment(`allow`),await t.allow(e)}async allowAs(e,t){if(t.length===0)return;let n=this.#a(`allowAs`);await this.requireChainAlignment(`allowAs`),await n.allow(t,e)}async isAllowed(e){return this.#r?this.#r.isAllowed(e):!1}async isAllowedAs(e,t){return this.#r?this.#r.isAllowed(t,e):!1}async delegateDecryption({contractAddress:n,delegateAddress:r,expirationDate:i}){let a=this.requireSigner(`delegateDecryption`),o=await this.requireAlignedWalletAccount(`delegateDecryption`);if(i&&i.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let s=(0,u.getAddress)(n),c=(0,u.getAddress)(r),l=(0,u.getAddress)(o.address);if(c===l)throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(c===s)throw new t.x(`Delegate address cannot be the same as the contract address (${s}).`);let d=await this.relayer.getAclAddress(),p=i?BigInt(Math.floor(i.getTime()/1e3)):t.i,m;try{m=await this.getDelegationExpiry({contractAddress:s,delegatorAddress:l,delegateAddress:c})}catch(e){console.warn(`[zama-sdk] delegateDecryption: pre-flight expiry check failed:`,e),m=-1n}if(m===p)throw new t.w(`The new expiration date (${p}) is the same as the current one. No on-chain change needed.`);try{let e=await a.writeContract(t.a(d,c,s,p));return{txHash:e,receipt:await this.provider.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:b(t)||new f(`Delegation transaction failed`,{cause:t})}}async revokeDelegation({contractAddress:n,delegateAddress:r}){let i=this.requireSigner(`revokeDelegation`),a=await this.requireAlignedWalletAccount(`revokeDelegation`),o=(0,u.getAddress)(n),s=(0,u.getAddress)(r),c=(0,u.getAddress)(a.address),l=await this.relayer.getAclAddress(),d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] revokeDelegation: pre-flight expiry check failed:`,e),d=1n}if(d===0n)throw new t.T(`No active delegation found for delegate ${s} on contract ${o}.`);try{let e=await i.writeContract(t.c(l,s,o));return{txHash:e,receipt:await this.provider.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:b(t)||new f(`Revoke delegation transaction failed`,{cause:t})}}async isDelegated(e){let n=await this.getDelegationExpiry(e);return n===0n?!1:n===t.i?!0:n>await this.provider.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:n,delegateAddress:r}){let i=await this.relayer.getAclAddress();return this.provider.readContract(t.o(i,(0,u.getAddress)(n),(0,u.getAddress)(r),(0,u.getAddress)(e)))}async userDecrypt(e){let n=this.#a(`userDecrypt`),r=await this.requireAlignedWalletAccount(`userDecrypt`);if(e.length===0)return{};let i=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},s=[];for(let e of i)t._(e.handle)?a[e.handle]=0n:s.push(e);if(s.length===0)return a;let c=(0,u.getAddress)(r.address),l=[];for(let e of s){let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?l.push(e):a[e.handle]=t}if(l.length===0)return a;let d=Array.from(new Set(i.map(e=>e.contractAddress))),f=await n.allow(d),p=new Map;for(let e of l){let t=p.get(e.contractAddress);t?t.push(e.handle):p.set(e.contractAddress,[e.handle])}let m=Date.now(),h=l.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:h}),await t.n([...p.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,...Mo(f,e),signerAddress:c});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of h){let n=a[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-m,handles:h,result:e}),a}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:o.s(e),durationMs:Date.now()-m,handles:h}),re(e,`Failed to decrypt handles`)}}async delegatedUserDecrypt(e,n,r=n){let i=this.#a(`delegatedUserDecrypt`),a=await this.requireAlignedWalletAccount(`delegatedUserDecrypt`);if(e.length===0)return{};let s=(0,u.getAddress)(n),c=(0,u.getAddress)(r),l=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),d={},f=[];for(let e of l)t._(e.handle)?d[e.handle]=0n:f.push(e);if(f.length===0)return d;let p=Array.from(new Set(l.map(e=>e.contractAddress))),m=await i.allow(p,s),h=(0,u.getAddress)(a.address),g=await Lo({provider:this.provider,relayer:this.relayer,contractAddresses:p,delegatorAddress:s,delegateAddress:h}),_=[];for(let e of f){if(g.has(e.contractAddress)){await this.cache.delete(c,e.contractAddress,e.handle),_.push(e);continue}let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?_.push(e):d[e.handle]=t}if(_.length===0)return d;let v=new Map;for(let e of _){let t=v.get(e.contractAddress);t?t.push(e.handle):v.set(e.contractAddress,[e.handle])}let ee=Date.now(),y=_.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:y}),await t.n([...v.entries()].map(([e,t])=>async()=>{let n=await this.relayer.delegatedUserDecrypt({handles:t,contractAddress:e,...No(m,e),delegateAddress:h});for(let[t,r]of Object.entries(n))d[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of y){let n=d[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-ee,handles:y,result:e}),d}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:o.s(e),durationMs:Date.now()-ee,handles:y}),re(e,`Failed to decrypt delegated handles`,!0)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw re(e,`Public decryption failed`)}}async encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:o.s(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}async revokePermits(e){let t=this.#a(`revokePermits`),n=(0,u.getAddress)((await this.requireAlignedWalletAccount(`revokePermits`)).address);try{await t.revokePermits(e)}finally{await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(n))}}async clearCredentials(){let e=this.#a(`clearCredentials`),t=(0,u.getAddress)((await this.requireAlignedWalletAccount(`clearCredentials`)).address);try{await e.clearCredentials()}finally{await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(t))}}dispose(){this.#i?.(),this.#i=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function fs(e){return`zama:pending-unshield:${e}`}function ps(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function ms(e,t,n,r){if(r===void 0){await e.set(fs(t),n);return}await e.set(fs(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function hs(e,t){return(await gs(e,t))?.unwrapTxHash??null}async function gs(e,t){return ps(await e.get(fs(t)))}async function _s(e,t){await e.delete(fs(t))}var vs=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 ys=new vs;exports.ACL_TOPICS=os,exports.AclPausedError=t.v,exports.AclTopics=Q,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=ee,exports.BaseSigner=r.t,exports.ChainMismatchError=g,exports.ChromeSessionStorage=vs,exports.ConfigurationError=e.t,exports.DecryptCache=se,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=cs,exports.DelegationContractIsSelfError=t.y,exports.DelegationCooldownError=t.b,exports.DelegationDelegateEqualsContractError=t.x,exports.DelegationExpirationTooSoonError=t.S,exports.DelegationExpiredError=t.C,exports.DelegationExpiryUnchangedError=t.w,exports.DelegationNotFoundError=t.T,exports.DelegationNotPropagatedError=t.E,exports.DelegationSelfNotAllowedError=t.D,exports.ERC20ReadFailedError=y,exports.ERC7984_INTERFACE_ID=l.c,exports.ERC7984_WRAPPER_INTERFACE_ID=l.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=l.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=a.t,exports.InsufficientConfidentialBalanceError=_,exports.InsufficientERC20BalanceError=v,exports.InvalidKeypairError=m,exports.KeypairExpiredError=p,exports.MemoryStorage=r.s,exports.MutableWalletAccountStore=r.n,exports.NoCiphertextError=h,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=r.l,exports.SignerRequiredError=r.u,exports.SigningFailedError=t.O,exports.SigningRejectedError=t.k,exports.TOKEN_TOPICS=$o,exports.Token=ss,exports.Topics=q,exports.TransactionRevertedError=f,exports.WalletAccountNotReadyError=r.d,exports.WalletNotConnectedError=r.f,exports.WrappersRegistry=us,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=ds,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.anvil=c.t,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.buildZamaConfig=r.i,exports.chains=c.n,exports.chromeSessionStorage=ys,exports.clearPendingUnshield=_s,exports.cleartext=ie,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=oe,exports.createWalletAccountStore=r.r,exports.decimalsContract=t.f,exports.decodeAclEvent=ns,exports.decodeAclEvents=rs,exports.decodeConfidentialTransfer=Uo,exports.decodeDelegatedForUserDecryption=es,exports.decodeOnChainEvent=Yo,exports.decodeOnChainEvents=Xo,exports.decodeRevokedDelegationForUserDecryption=ts,exports.decodeUnwrapFinalized=Z,exports.decodeUnwrapRequested=Go,exports.decodeUnwrappedFinalized=Ko,exports.decodeUnwrappedStarted=Jo,exports.decodeWrapped=Wo,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=is,exports.findRevokedDelegationForUserDecryption=as,exports.findUnwrapRequested=Zo,exports.findWrapped=Qo,exports.getConfidentialTokenAddressContract=l.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=l.n,exports.getTokenPairContract=l.r,exports.getTokenPairsContract=l.i,exports.getTokenPairsLengthContract=l.a,exports.getTokenPairsSliceContract=l.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=a.n,exports.inferredTotalSupplyContract=l.h,exports.isConfidentialTokenContract=l.d,exports.isConfidentialTokenValidContract=l.s,exports.isConfidentialWrapperContract=l.f,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=l.S,exports.isZeroHandle=t._,exports.loadPendingUnshield=hs,exports.loadPendingUnshieldRequest=gs,exports.mainnet=c.a,exports.matchAclRevert=b,exports.matchZamaError=e.a,exports.memoryStorage=r.c,exports.nameContract=t.m,exports.rateContract=l.C,exports.resolveChainRelayers=r.a,exports.resolveStorage=r.o,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=ms,exports.sepolia=c.o,exports.setOperatorContract=l.w,exports.supportsInterfaceContract=l.p,exports.symbolContract=t.h,exports.totalSupplyContract=l.T,exports.underlyingContract=l.g,exports.unwrapContract=l.E,exports.unwrapFromBalanceContract=l.D,exports.wrapContract=l._;
|
|
39
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function di(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:V(t,`input`,e.processors),output:V(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function B(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return B(r.element,n);if(r.type===`set`)return B(r.valueType,n);if(r.type===`lazy`)return B(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return B(r.innerType,n);if(r.type===`intersection`)return B(r.left,n)||B(r.right,n);if(r.type===`record`||r.type===`map`)return B(r.keyType,n)||B(r.valueType,n);if(r.type===`pipe`)return B(r.in,n)||B(r.out,n);if(r.type===`object`){for(let e in r.shape)if(B(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(B(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(B(e,n))return!0;return!!(r.rest&&B(r.rest,n))}return!1}const fi=(e,t={})=>n=>{let r=li({...n,processors:t});return z(e,r),ui(r,e),di(r,e)},V=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=li({...i??{},target:a,io:t,processors:n});return z(e,o),ui(o,e),di(o,e)},pi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},mi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=pi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},hi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},gi=(e,t,n,r)=>{n.not={}},_i=(e,t,n,r)=>{let i=e._zod.def,a=me(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},vi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},yi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},bi=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=z(a.element,t,{...r,path:[...r.path,`items`]})},xi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=z(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=z(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Si=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>z(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ci=(e,t,n,r)=>{let i=e._zod.def,a=z(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=z(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},wi=(e,t,n,r)=>{let i=e._zod.def,a=z(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ti=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ei=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Di=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Oi=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},ki=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;z(a,t,r);let o=t.seen.get(e);o.ref=a},Ai=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ji=(e,t,n,r)=>{let i=e._zod.def;z(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Mi=S(`ZodISODateTime`,(e,t)=>{dn.init(e,t),W.init(e,t)});function Ni(e){return Mr(Mi,e)}const Pi=S(`ZodISODate`,(e,t)=>{fn.init(e,t),W.init(e,t)});function Fi(e){return Nr(Pi,e)}const Ii=S(`ZodISOTime`,(e,t)=>{pn.init(e,t),W.init(e,t)});function Li(e){return Pr(Ii,e)}const Ri=S(`ZodISODuration`,(e,t)=>{mn.init(e,t),W.init(e,t)});function zi(e){return Fr(Ri,e)}const Bi=(e,t)=>{He.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ge(e,t)},flatten:{value:t=>We(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,he,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,he,2)}},isEmpty:{get(){return e.issues.length===0}}})};S(`ZodError`,Bi);const H=S(`ZodError`,Bi,{Parent:Error}),Vi=Ke(H),Hi=qe(H),Ui=Je(H),Wi=Xe(H),Gi=Qe(H),Ki=$e(H),qi=et(H),Ji=tt(H),Yi=nt(H),Xi=rt(H),Zi=it(H),Qi=at(H),U=S(`ZodType`,(e,t)=>(F.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:V(e,`input`),output:V(e,`output`)}}),e.toJSONSchema=fi(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(D(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>k(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Vi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ui(e,t,n),e.parseAsync=async(t,n)=>Hi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Wi(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Gi(e,t,n),e.decode=(t,n)=>Ki(e,t,n),e.encodeAsync=async(t,n)=>qi(e,t,n),e.decodeAsync=async(t,n)=>Ji(e,t,n),e.safeEncode=(t,n)=>Yi(e,t,n),e.safeDecode=(t,n)=>Xi(e,t,n),e.safeEncodeAsync=async(t,n)=>Zi(e,t,n),e.safeDecodeAsync=async(t,n)=>Qi(e,t,n),e.refine=(t,n)=>e.check(ao(t,n)),e.superRefine=t=>e.check(oo(t)),e.overwrite=t=>e.check(R(t)),e.optional=()=>Va(e),e.exactOptional=()=>Ua(e),e.nullable=()=>Ga(e),e.nullish=()=>Va(Ga(e)),e.nonoptional=t=>Za(e,t),e.array=()=>ka(e),e.or=t=>Na([e,t]),e.and=t=>Fa(e,t),e.transform=t=>to(e,za(t)),e.default=t=>qa(e,t),e.prefault=t=>Ya(e,t),e.catch=t=>$a(e,t),e.pipe=t=>to(e,t),e.readonly=()=>ro(e),e.describe=t=>{let n=e.clone();return L.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return L.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return L.get(e);let n=e.clone();return L.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),$i=S(`_ZodString`,(e,t)=>{Qt.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Jr(...t)),e.includes=(...t)=>e.check(Zr(...t)),e.startsWith=(...t)=>e.check(Qr(...t)),e.endsWith=(...t)=>e.check($r(...t)),e.min=(...t)=>e.check(Kr(...t)),e.max=(...t)=>e.check(Gr(...t)),e.length=(...t)=>e.check(qr(...t)),e.nonempty=(...t)=>e.check(Kr(1,...t)),e.lowercase=t=>e.check(Yr(t)),e.uppercase=t=>e.check(Xr(t)),e.trim=()=>e.check(ti()),e.normalize=(...t)=>e.check(ei(...t)),e.toLowerCase=()=>e.check(ni()),e.toUpperCase=()=>e.check(ri()),e.slugify=()=>e.check(ii())}),ea=S(`ZodString`,(e,t)=>{Qt.init(e,t),$i.init(e,t),e.email=t=>e.check(ur(na,t)),e.url=t=>e.check(gr(aa,t)),e.jwt=t=>e.check(jr(ba,t)),e.emoji=t=>e.check(_r(oa,t)),e.guid=t=>e.check(dr(ra,t)),e.uuid=t=>e.check(fr(ia,t)),e.uuidv4=t=>e.check(pr(ia,t)),e.uuidv6=t=>e.check(mr(ia,t)),e.uuidv7=t=>e.check(hr(ia,t)),e.nanoid=t=>e.check(vr(sa,t)),e.guid=t=>e.check(dr(ra,t)),e.cuid=t=>e.check(yr(ca,t)),e.cuid2=t=>e.check(br(la,t)),e.ulid=t=>e.check(xr(ua,t)),e.base64=t=>e.check(Or(_a,t)),e.base64url=t=>e.check(kr(va,t)),e.xid=t=>e.check(Sr(da,t)),e.ksuid=t=>e.check(Cr(fa,t)),e.ipv4=t=>e.check(wr(pa,t)),e.ipv6=t=>e.check(Tr(ma,t)),e.cidrv4=t=>e.check(Er(ha,t)),e.cidrv6=t=>e.check(Dr(ga,t)),e.e164=t=>e.check(Ar(ya,t)),e.datetime=t=>e.check(Ni(t)),e.date=t=>e.check(Fi(t)),e.time=t=>e.check(Li(t)),e.duration=t=>e.check(zi(t))});function ta(e){return lr(ea,e)}const W=S(`ZodStringFormat`,(e,t)=>{I.init(e,t),$i.init(e,t)}),na=S(`ZodEmail`,(e,t)=>{tn.init(e,t),W.init(e,t)}),ra=S(`ZodGUID`,(e,t)=>{$t.init(e,t),W.init(e,t)}),ia=S(`ZodUUID`,(e,t)=>{en.init(e,t),W.init(e,t)}),aa=S(`ZodURL`,(e,t)=>{nn.init(e,t),W.init(e,t)}),oa=S(`ZodEmoji`,(e,t)=>{rn.init(e,t),W.init(e,t)}),sa=S(`ZodNanoID`,(e,t)=>{an.init(e,t),W.init(e,t)}),ca=S(`ZodCUID`,(e,t)=>{on.init(e,t),W.init(e,t)}),la=S(`ZodCUID2`,(e,t)=>{sn.init(e,t),W.init(e,t)}),ua=S(`ZodULID`,(e,t)=>{cn.init(e,t),W.init(e,t)}),da=S(`ZodXID`,(e,t)=>{ln.init(e,t),W.init(e,t)}),fa=S(`ZodKSUID`,(e,t)=>{un.init(e,t),W.init(e,t)}),pa=S(`ZodIPv4`,(e,t)=>{hn.init(e,t),W.init(e,t)}),ma=S(`ZodIPv6`,(e,t)=>{gn.init(e,t),W.init(e,t)}),ha=S(`ZodCIDRv4`,(e,t)=>{_n.init(e,t),W.init(e,t)}),ga=S(`ZodCIDRv6`,(e,t)=>{vn.init(e,t),W.init(e,t)}),_a=S(`ZodBase64`,(e,t)=>{bn.init(e,t),W.init(e,t)}),va=S(`ZodBase64URL`,(e,t)=>{Sn.init(e,t),W.init(e,t)}),ya=S(`ZodE164`,(e,t)=>{Cn.init(e,t),W.init(e,t)}),ba=S(`ZodJWT`,(e,t)=>{Tn.init(e,t),W.init(e,t)}),xa=S(`ZodNumber`,(e,t)=>{En.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r),e.gt=(t,n)=>e.check(Hr(t,n)),e.gte=(t,n)=>e.check(Ur(t,n)),e.min=(t,n)=>e.check(Ur(t,n)),e.lt=(t,n)=>e.check(Br(t,n)),e.lte=(t,n)=>e.check(Vr(t,n)),e.max=(t,n)=>e.check(Vr(t,n)),e.int=t=>e.check(Ca(t)),e.safe=t=>e.check(Ca(t)),e.positive=t=>e.check(Hr(0,t)),e.nonnegative=t=>e.check(Ur(0,t)),e.negative=t=>e.check(Br(0,t)),e.nonpositive=t=>e.check(Vr(0,t)),e.multipleOf=(t,n)=>e.check(Wr(t,n)),e.step=(t,n)=>e.check(Wr(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function G(e){return Ir(xa,e)}const Sa=S(`ZodNumberFormat`,(e,t)=>{Dn.init(e,t),xa.init(e,t)});function Ca(e){return Lr(Sa,e)}const wa=S(`ZodUnknown`,(e,t)=>{On.init(e,t),U.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Ta(){return Rr(wa)}const Ea=S(`ZodNever`,(e,t)=>{kn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r)});function Da(e){return zr(Ea,e)}const Oa=S(`ZodArray`,(e,t)=>{jn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bi(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(Kr(t,n)),e.nonempty=t=>e.check(Kr(1,t)),e.max=(t,n)=>e.check(Gr(t,n)),e.length=(t,n)=>e.check(qr(t,n)),e.unwrap=()=>e.element});function ka(e,t){return ai(Oa,e,t)}const Aa=S(`ZodObject`,(e,t)=>{In.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r),T(e,`shape`,()=>t.shape),e.keyof=()=>La(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ta()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ta()}),e.strict=()=>e.clone({...e._zod.def,catchall:Da()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Ne(e,t),e.safeExtend=t=>Pe(e,t),e.merge=t=>Fe(e,t),e.pick=t=>je(e,t),e.omit=t=>Me(e,t),e.partial=(...t)=>Ie(Ba,e,t[0]),e.required=(...t)=>Le(Xa,e,t[0])});function ja(e,t){return new Aa({type:`object`,shape:e??{},...A(t)})}const Ma=S(`ZodUnion`,(e,t)=>{Rn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Si(e,t,n,r),e.options=t.options});function Na(e,t){return new Ma({type:`union`,options:e,...A(t)})}const Pa=S(`ZodIntersection`,(e,t)=>{zn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ci(e,t,n,r)});function Fa(e,t){return new Pa({type:`intersection`,left:e,right:t})}const Ia=S(`ZodEnum`,(e,t)=>{Hn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ia({...t,checks:[],...A(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ia({...t,checks:[],...A(r),entries:i})}});function La(e,t){return new Ia({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...A(t)})}const Ra=S(`ZodTransform`,(e,t)=>{Un.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new fe(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(N(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(N(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function za(e){return new Ra({type:`transform`,transform:e})}const Ba=S(`ZodOptional`,(e,t)=>{Gn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Va(e){return new Ba({type:`optional`,innerType:e})}const Ha=S(`ZodExactOptional`,(e,t)=>{Kn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ua(e){return new Ha({type:`optional`,innerType:e})}const Wa=S(`ZodNullable`,(e,t)=>{qn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ga(e){return new Wa({type:`nullable`,innerType:e})}const Ka=S(`ZodDefault`,(e,t)=>{Jn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function qa(e,t){return new Ka({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ee(t)}})}const Ja=S(`ZodPrefault`,(e,t)=>{Xn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Di(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ya(e,t){return new Ja({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ee(t)}})}const Xa=S(`ZodNonOptional`,(e,t)=>{Zn.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Za(e,t){return new Xa({type:`nonoptional`,innerType:e,...A(t)})}const Qa=S(`ZodCatch`,(e,t)=>{$n.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function $a(e,t){return new Qa({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const eo=S(`ZodPipe`,(e,t)=>{er.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ki(e,t,n,r),e.in=t.in,e.out=t.out});function to(e,t){return new eo({type:`pipe`,in:e,out:t})}const no=S(`ZodReadonly`,(e,t)=>{nr.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ro(e){return new no({type:`readonly`,innerType:e})}const io=S(`ZodCustom`,(e,t)=>{ir.init(e,t),U.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r)});function ao(e,t={}){return oi(io,e,t)}function oo(e){return si(e)}const so=86400;function co(){return Math.floor(Date.now()/1e3)}function K(e){return(0,u.getAddress)(e)}function lo(e){return[...new Set(e.map(K))].toSorted()}const uo=ta().refine(e=>(0,u.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),fo=ta().refine(e=>(0,u.isAddress)(e,{strict:!1}),`expected EVM address`).transform(e=>K(e)),po=G().finite().int().nonnegative(),mo=G().finite().int().positive(),ho=G().finite().int().positive(),go=G().finite().int().positive(),_o=`keypairTTL must be a positive integer number of seconds`,vo=`permitTTL must be a positive integer number of days`,yo=365*so,bo=G(_o).finite(_o).int(_o).positive(_o).max(yo,`keypairTTL must not exceed the fhevm ACL maximum of ${yo}s (365 days)`),xo=G(vo).finite(vo).int(vo).positive(vo),So=ja({publicKey:uo,privateKey:uo,createdAt:po,expiresAt:mo}),Co=ja({keypairPublicKey:uo,signerAddress:fo,delegatorAddress:fo,chainId:go,signedContractAddresses:ka(fo).max(10),signature:uo,startTimestamp:po,durationDays:ho}),wo=ka(Co),To=ka(ta());var Eo=class{#e;#t;#n;#r=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl}async readStored(e){let t=ue(e),n=await this.#t.get(t);if(n==null)return null;let r=So.safeParse(n);if(!r.success)return await s.t(`delete keypair entry`,()=>this.#t.delete(t)),null;let i=r.data;return co()>=i.expiresAt?(await s.t(`delete keypair entry`,()=>this.#t.delete(t)),null):i}async getOrCreate(e){let t=this.#r.get(e);if(t)return t;let n=(async()=>{let t=await this.readStored(e);if(t!==null)return t;let n=await this.#e(),r=co(),i={publicKey:n.publicKey,privateKey:n.privateKey,createdAt:r,expiresAt:r+this.#n},a=ue(e);return await s.t(`persist keypair`,()=>this.#t.set(a,i)),i})().finally(()=>{this.#r.delete(e)});return this.#r.set(e,n),n}async clear(e){let t=ue(e);await s.t(`delete keypair entry`,()=>this.#t.delete(t))}};function Do(e,t){let n=new Set(e.flatMap(e=>e.signedContractAddresses));return t.filter(e=>!n.has(e))}function Oo(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function ko(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function Ao(e,t){let n=new Set(t);return e.filter(e=>!e.signedContractAddresses.some(e=>n.has(e)))}var jo=class{#e;constructor(e){this.#e=e.storage}async list(e){let t=x(e),n=await this.#e.get(t);if(n==null)return[];let r=wo.safeParse(n);return r.success?r.data:(await this.#i(t),await this.#r(e),[])}async listUsableAndPrune(e,t){let n=await this.list(e),r=ko(n,t,Math.floor(Date.now()/1e3));if(r.length!==n.length){let t=x(e);r.length===0?(await this.#i(t),await this.#r(e)):await s.t(`update permit entry`,()=>this.#e.set(t,r))}return r}async append(e,t){if(t.length===0)return;let n=t.map(e=>Co.parse(e)),r=await this.list(e);await this.#e.set(x(e),[...r,...n]),await this.#n(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=x(e),i=Ao(n,t);i.length===0?(await this.#i(r),await this.#r(e)):await this.#e.set(r,i)}async clearAllForSigner(e){let t=de(e),n=await this.#t(t);await Promise.all(n.map(e=>this.#i(e))),await s.t(`delete permit index`,()=>this.#e.delete(t))}async#t(e){let t=await this.#e.get(e);if(t==null)return[];let n=To.safeParse(t);return n.success?n.data:(await s.t(`delete permit index`,()=>this.#e.delete(e)),[])}async#n(e){let t=de(e.signerAddress),n=x(e),r=await this.#t(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#r(e){let t=de(e.signerAddress),n=x(e),r=await this.#t(t),i=r.filter(e=>e!==n);i.length!==r.length&&(i.length===0?await s.t(`delete permit index`,()=>this.#e.delete(t)):await s.t(`update permit index`,()=>this.#e.set(t,i)))}async#i(e){await s.t(`delete permit entry`,()=>this.#e.delete(e))}};30*so;var Mo=class{#e;#t;#n;#r;#i;constructor(e){this.#e=new Eo({generator:()=>e.relayer.generateKeypair(),storage:e.storage,ttl:e.keypairTTL}),this.#t=new jo({storage:e.permitStorage??e.storage}),this.#n=e.relayer,this.#r=e.signer,this.#i=e.permitTTL}async allow(e,t){let n=this.#r.requireWalletAccount(`allow`),r=K(n.address),i=lo(e),a=await this.#e.getOrCreate(r);if(i.length===0)return{keypair:a,permits:[]};let o={signerAddress:r,chainId:n.chainId,delegatorAddress:t?K(t):r},c=await this.#t.listUsableAndPrune(o,a.publicKey);for(let e of Oo(Do(c,i))){let t=await this.#a({chunk:e,keypair:a,scope:o});c.push(t),await s.t(`persist permit`,()=>this.#t.append(o,[t]))}let l=new Set(i);return{keypair:a,permits:c.filter(e=>e.signedContractAddresses.some(e=>l.has(e)))}}async isAllowed(e,t){if(e.length===0)return!0;let n=this.#r.walletAccount.getSnapshot();if(!n)return!1;let r=K(n.address),i=await this.#e.readStored(r);if(i===null)return!1;let a={signerAddress:r,chainId:n.chainId,delegatorAddress:t?K(t):r};return Do(await this.#t.listUsableAndPrune(a,i.publicKey),lo(e)).length===0}async revokePermits(e){let t=this.#r.requireWalletAccount(`revokePermits`),n=K(t.address);if(e===void 0){await this.#t.clearAllForSigner(n);return}let r=lo(e);if(r.length===0)return;let i=t.chainId;await this.#t.deletePermitsTouching({signerAddress:n,chainId:i,delegatorAddress:n},r)}async clearCredentials(){let e=K(this.#r.requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async handleWalletAccountChange(e,t){let n=e?K(e.address):void 0,r=t?K(t.address):void 0;n!==r&&(n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n)),r&&await s.t(`warm keypair`,async()=>{await this.#e.getOrCreate(r)}))}async#a(n){let{chunk:r,keypair:i,scope:a}=n,o=co(),s=a.delegatorAddress!==a.signerAddress;try{let e=s?await this.#n.createDelegatedUserDecryptEIP712(i.publicKey,r,a.delegatorAddress,o,this.#i):await this.#n.createEIP712(i.publicKey,r,o,this.#i),t=await this.#r.signTypedData(e);return{keypairPublicKey:i.publicKey,signerAddress:a.signerAddress,delegatorAddress:a.delegatorAddress,chainId:a.chainId,signedContractAddresses:r,signature:t,startTimestamp:o,durationDays:this.#i}}catch(n){throw n instanceof e.r?n:t.A(n,`Credential signing failed`)}}};function No(e,t){let r=Io(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return Fo(e,r)}function Po(e,t){let r=Io(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...Fo(e,r),delegatorAddress:r.delegatorAddress}}function Fo(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function Io(e,t){let n=K(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}async function Lo(e){let{provider:n,aclAddress:r,delegatorAddress:i,delegateAddress:a,contractAddress:o}=e,s=await n.readContract(t.o(r,i,a,o));return s===0n?!1:s===t.i?!0:s>await n.getBlockTimestamp()}async function Ro(e){let{provider:t,relayer:n,contractAddresses:r,delegatorAddress:i,delegateAddress:a}=e;if(r.length===0)return new Set;let o=await n.getAclAddress(),s=await Promise.all(r.map(async e=>({contractAddress:e,active:await Lo({provider:t,aclAddress:o,delegatorAddress:i,delegateAddress:a,contractAddress:e})}))),c=new Set;for(let{contractAddress:e,active:t}of s)t||c.add(e);return c}function q(e){return(0,u.keccak256)((0,u.toBytes)(e))}const J={ConfidentialTransfer:q(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:q(`Wrapped(address,uint256)`),UnwrapRequested:q(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:q(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:q(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:q(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:q(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:q(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function Y(e){return(0,u.getAddress)(ae(e.slice(-40)))}function zo(e){return BigInt(e)}function Bo(e){return e}function Vo(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Ho(e,t){return(0,u.getAddress)(ae(Vo(e,t).slice(-40)))}function X(e,t){return BigInt(`0x`+Vo(e,t))}function Uo(e,t){return BigInt(`0x`+Vo(e,t))!==0n}function Z(e,t){return ae(Vo(e,t))}function Wo(e){return e.topics[0]!==J.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:Y(e.topics[1]),to:Y(e.topics[2]),encryptedAmountHandle:Bo(e.topics[3])}}function Go(e){return e.topics[0]!==J.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:Y(e.topics[1]),amountIn:X(e.data,0)}}function Ko(e){return e.topics[0]===J.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:Y(e.topics[1]),unwrapRequestId:Bo(e.topics[2]),encryptedAmount:Z(e.data,0)}:e.topics[0]===J.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:Y(e.topics[1]),encryptedAmount:Z(e.data,0)}:null}function qo(e){return e.topics[0]===J.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:Y(e.topics[1]),unwrapRequestId:Bo(e.topics[2]),encryptedAmount:Z(e.data,0),cleartextAmount:X(e.data,1)}:e.topics[0]===J.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:Y(e.topics[1]),encryptedAmount:Z(e.data,0),cleartextAmount:X(e.data,1)}:null}function Jo(e){let t=qo(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Yo(e){if(e.topics[0]!==J.UnwrapFinalizedLegacy)return null;let t=qo(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Xo(e){return e.topics[0]!==J.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:zo(e.topics[1]),txId:zo(e.topics[2]),to:Y(e.topics[3]),returnVal:Uo(e.data,0),refund:Ho(e.data,1),requestedAmount:Z(e.data,2),burnAmount:Z(e.data,3)}}function Zo(e){return Wo(e)??Go(e)??Ko(e)??Yo(e)??qo(e)??Xo(e)}function Qo(e){let t=[];for(let n of e){let e=Zo(n);e&&t.push(e)}return t}function $o(e){for(let t of e){let e=Ko(t);if(e)return e}return null}function es(e){for(let t of e){let e=Go(t);if(e)return e}return null}const ts=[J.ConfidentialTransfer,J.Wrapped,J.UnwrapRequested,J.UnwrapRequestedLegacy,J.UnwrapFinalized,J.UnwrapFinalizedLegacy,J.UnwrappedStarted],Q={DelegatedForUserDecryption:q(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:q(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function ns(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:Y(e.topics[1]),delegate:Y(e.topics[2]),contractAddress:Ho(e.data,0),delegationCounter:X(e.data,1),oldExpirationDate:X(e.data,2),newExpirationDate:X(e.data,3)}}function rs(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:Y(e.topics[1]),delegate:Y(e.topics[2]),contractAddress:Ho(e.data,0),delegationCounter:X(e.data,1),oldExpirationDate:X(e.data,2)}}function is(e){return ns(e)??rs(e)}function as(e){let t=[];for(let n of e){let e=is(n);e&&t.push(e)}return t}function os(e){for(let t of e){let e=ns(t);if(e)return e}return null}function ss(e){for(let t of e){let e=rs(t);if(e)return e}return null}const cs=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];var ls=class r extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;#n=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,u.getAddress)(n):this.address}async#r(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(l.v(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#r();return this.#n=await this.sdk.provider.readContract(l.m(e)),this.#n}catch{return this.#n=!1,!1}}async confidentialTransfer(r,i,a){let s=this.sdk.requireSigner(`confidentialTransfer`),c=await this.sdk.requireAlignedWalletAccount(`confidentialTransfer`),{skipBalanceCheck:d=!1,onEncryptComplete:p,onTransferSubmitted:m}=a??{},h=(0,u.getAddress)(r);d||await this.#s(i);let{handles:g,inputProof:_}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:(0,u.getAddress)(c.address)});if($(()=>p?.()),g.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await s.writeContract(l.S(this.address,h,g[0],_));return this.emit({type:t.r.TransferSubmitted,txHash:e}),$(()=>m?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:o.s(n)}),n instanceof e.r?n:new f(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(r,i,a,s){let c=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,u.getAddress)(r),p=(0,u.getAddress)(i),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if($(()=>s?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(l.C(this.address,d,p,m[0],h));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),$(()=>s?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:o.s(n)}),n instanceof e.r?n:new f(`TransferFrom transaction failed`,{cause:n})}}async setOperator(n,r){let i=this.sdk.requireSigner(`setOperator`);await this.sdk.requireChainAlignment(`setOperator`);let a=(0,u.getAddress)(n);try{let e=await i.writeContract(l.E(this.address,a,r));return this.emit({type:t.r.SetOperatorSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`setOperator`,error:o.s(n)}),n instanceof e.r?n:new d(`Operator approval failed`,{cause:n})}}async isOperator(e,t){return this.sdk.provider.readContract(l.w(this.address,(0,u.getAddress)(e),(0,u.getAddress)(t)))}async shield(n,r){let i=await this.sdk.requireAlignedWalletAccount(`shield`),a=await this.isPayable(),s=await this.#r(),c=(0,u.getAddress)(i.address),l;try{l=await this.sdk.provider.readContract(t.d(s,c))}catch(t){throw t instanceof e.r?t:new y(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:o.s(t)})}if(l<n)throw new v(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});return a?this.#i(n,s,c,r):this.#a(n,c,r)}async#i(n,r,i,a){let s=this.sdk.requireSigner(`shield`),c=a?.to?(0,u.getAddress)(a.to):i,l=c===i?`0x`:c;try{let e=await s.writeContract(ce(r,this.wrapper,n,l));return this.emit({type:t.r.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`}),$(()=>a?.onShieldSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield:transferAndCall`,error:o.s(n)}),n instanceof e.r?n:new f(`TransferAndCall shield transaction failed`,{cause:n})}}async#a(n,r,i){let a=this.sdk.requireSigner(`shield`),s=i?.approvalStrategy??`exact`;s!==`skip`&&await this.#l(n,s===`max`,i);try{let e=i?.to?(0,u.getAddress)(i.to):r,o=await a.writeContract(l.y(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:o,shieldPath:`approveAndWrap`}),$(()=>i?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.provider.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield:approveAndWrap`,error:o.s(n)}),n instanceof e.r?n:new f(`ApproveAndWrap shield transaction failed`,{cause:n})}}async unwrap(r){let i=this.sdk.requireSigner(`unwrap`),a=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrap`)).address),{handles:s,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});if(s.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await i.writeContract(l.O(this.address,a,a,s[0],c));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`),i=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`unwrapAll`)).address),a=await this.readConfidentialBalanceOf(i);if(t._(a))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(l.k(this.address,i,i,a));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#s(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return $(()=>r?.(c.txHash)),this.#c(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return $(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#c(n.txHash,t,e)}async resumeUnshield(e,t){return this.#c(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];o.t(a,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(l.g(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:o.s(n)}),n instanceof e.r?n:new f(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`),i=await this.sdk.requireAlignedWalletAccount(`approveUnderlying`),a=await this.#r(),s=(0,u.getAddress)(i.address),c=n??2n**256n-1n;try{c>0n&&await this.sdk.provider.readContract(t.l(a,s,this.wrapper))>0n&&await r.writeContract(t.u(a,this.wrapper,0n));let e=await r.writeContract(t.u(a,this.wrapper,c));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:o.s(n)}),n instanceof e.r?n:new d(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`),a=await this.sdk.requireAlignedWalletAccount(`delegateDecryption`);if(r&&r.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let s=(0,u.getAddress)(n),c=(0,u.getAddress)(a.address);if(s===(0,u.getAddress)(c))throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===this.address)throw new t.x(`Delegate address cannot be the same as the contract address (${this.address}).`);let l=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,p;try{p=await this.getDelegationExpiry({delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] Token.delegateDecryption: pre-flight expiry check failed:`,e),p=-1n}if(p===d)throw new t.w(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(t.a(l,s,this.address,d));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:o.s(n)}),n instanceof e.r?n:b(n)||new f(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=this.sdk.requireSigner(`revokeDelegation`),i=await this.sdk.requireAlignedWalletAccount(`revokeDelegation`),a=(0,u.getAddress)(n),s=(0,u.getAddress)(i.address),c=await this.getAclAddress(),l;try{l=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch(e){console.warn(`[zama-sdk] Token.revokeDelegation: pre-flight expiry check failed:`,e),l=1n}if(l===0n)throw new t.T(`No active delegation found for delegate ${a} on contract ${this.address}.`);try{let e=await r.writeContract(t.c(c,a,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:o.s(n)}),n instanceof e.r?n:b(n)||new f(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#o(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#o(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#o(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.r?i.set(t[a].address,n):i.set(t[a].address,new f(r,{cause:n}))}return i}async#s(t){if(t===0n)return;let n;try{let e=await this.sdk.requireAlignedWalletAccount(`assertConfidentialBalance`);n=await this.balanceOf((0,u.getAddress)(e.address))}catch(t){throw t instanceof e.r?t:new ee(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new _(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#c(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new f(`Failed to get unshield receipt`,{cause:t})}let o=$o(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),$(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),$(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#l(n,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#r(),s=(0,u.getAddress)((await this.sdk.requireAlignedWalletAccount(`approveUnderlying`)).address),c=await this.sdk.provider.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{if(c>0n){let e=await a.writeContract(t.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,s=await a.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:s}),$(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(t){throw t instanceof e.r?t:new d(`ERC-20 approval failed`,{cause:t})}}};function $(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const us={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},ds=300*1e3;var fs=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},us,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,u.getAddress)(n)}async listPairs(t={}){let n=t.page??1,r=t.pageSize??100,i=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(r<1)throw new e.t(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(l.a(a));s=this.#i(o,Number(e))}let c=BigInt((n-1)*r),u=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:n,pageSize:r};let d=`slice:${a}:${c}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(l.o(a,c,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:s,page:n,pageSize:r};let p=`metadata:${a}:${c}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?ds:void 0)}return{items:m,total:s,page:n,pageSize:r}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.m(e.tokenAddress)),this.provider.readContract(t.h(e.tokenAddress)),this.provider.readContract(t.f(e.tokenAddress)),this.provider.readContract(t.p(e.tokenAddress)),this.provider.readContract(t.m(e.confidentialTokenAddress)),this.provider.readContract(t.h(e.confidentialTokenAddress)),this.provider.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.t(t,n));return o===u.zeroAddress?this.#i(r,null,ds):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.n(t,n));return o===u.zeroAddress?this.#i(r,null,ds):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(l.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(l.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(l.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.t(t,(0,u.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.n(t,(0,u.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.s(t,(0,u.getAddress)(e)))}},ps=class{relayer;provider;signer;storage;cache;registry;#e;#t;#n=new Set;#r;#i;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.cache=new le(e.storage),this.#t=e.onEvent??function(){};let t={};for(let n of e.chains??[])n.registryAddress&&(t[n.id]=n.registryAddress);Object.assign(t,e.registryAddresses),this.registry=new fs({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n=bo.parse(e.keypairTTL??2592e3),r=xo.parse(e.permitTTL??30);if(e.signer){let t=e.signer;this.#r=new Mo({relayer:this.relayer,signer:t,keypairTTL:n,permitTTL:r,storage:this.storage,permitStorage:e.permitStorage}),this.#i=t.walletAccount.subscribe(e=>{this.#o(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})})}else this.#r=void 0}requireSigner(e){if(!this.signer)throw new r.l(e);return this.signer}#a(e){if(!this.#r)throw new r.l(e);return this.#r}onWalletAccountChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireAlignedWalletAccount(e){let t=this.requireSigner(e),n;try{n=t.requireWalletAccount(e)}catch(i){if(!(i instanceof r.d)||!t.refreshWalletAccount)throw i;await t.refreshWalletAccount(),n=t.requireWalletAccount(e)}let i=await this.provider.getChainId();if(n.chainId!==i)throw new g({operation:e,signerChainId:n.chainId,providerChainId:i});return n}async requireChainAlignment(e){return(await this.requireAlignedWalletAccount(e)).chainId}async#o(e){let t=e.previous,n=e.next,r=this.#r;r&&await s.t(`credential wallet account change`,()=>r.handleWalletAccountChange(t,n)),t&&await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(t.address));let i=n?.chainId;i!==void 0&&s.t(`switch relayer chain`,()=>this.relayer.switchChain(i)),await Promise.all(Array.from(this.#n,e=>s.t(`wallet account listener`,()=>e({previous:t,next:n}))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new ls(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new fs({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){if(e.length===0)return;let t=this.#a(`allow`);await this.requireChainAlignment(`allow`),await t.allow(e)}async allowAs(e,t){if(t.length===0)return;let n=this.#a(`allowAs`);await this.requireChainAlignment(`allowAs`),await n.allow(t,e)}async isAllowed(e){return this.#r?this.#r.isAllowed(e):!1}async isAllowedAs(e,t){return this.#r?this.#r.isAllowed(t,e):!1}async delegateDecryption({contractAddress:n,delegateAddress:r,expirationDate:i}){let a=this.requireSigner(`delegateDecryption`),o=await this.requireAlignedWalletAccount(`delegateDecryption`);if(i&&i.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let s=(0,u.getAddress)(n),c=(0,u.getAddress)(r),l=(0,u.getAddress)(o.address);if(c===l)throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(c===s)throw new t.x(`Delegate address cannot be the same as the contract address (${s}).`);let d=await this.relayer.getAclAddress(),p=i?BigInt(Math.floor(i.getTime()/1e3)):t.i,m;try{m=await this.getDelegationExpiry({contractAddress:s,delegatorAddress:l,delegateAddress:c})}catch(e){console.warn(`[zama-sdk] delegateDecryption: pre-flight expiry check failed:`,e),m=-1n}if(m===p)throw new t.w(`The new expiration date (${p}) is the same as the current one. No on-chain change needed.`);try{let e=await a.writeContract(t.a(d,c,s,p));return{txHash:e,receipt:await this.provider.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:b(t)||new f(`Delegation transaction failed`,{cause:t})}}async revokeDelegation({contractAddress:n,delegateAddress:r}){let i=this.requireSigner(`revokeDelegation`),a=await this.requireAlignedWalletAccount(`revokeDelegation`),o=(0,u.getAddress)(n),s=(0,u.getAddress)(r),c=(0,u.getAddress)(a.address),l=await this.relayer.getAclAddress(),d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] revokeDelegation: pre-flight expiry check failed:`,e),d=1n}if(d===0n)throw new t.T(`No active delegation found for delegate ${s} on contract ${o}.`);try{let e=await i.writeContract(t.c(l,s,o));return{txHash:e,receipt:await this.provider.waitForTransactionReceipt(e)}}catch(t){throw t instanceof e.r?t:b(t)||new f(`Revoke delegation transaction failed`,{cause:t})}}async isDelegated(e){let n=await this.getDelegationExpiry(e);return n===0n?!1:n===t.i?!0:n>await this.provider.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:n,delegateAddress:r}){let i=await this.relayer.getAclAddress();return this.provider.readContract(t.o(i,(0,u.getAddress)(n),(0,u.getAddress)(r),(0,u.getAddress)(e)))}async userDecrypt(e){let n=this.#a(`userDecrypt`),r=await this.requireAlignedWalletAccount(`userDecrypt`);if(e.length===0)return{};let i=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},s=[];for(let e of i)t._(e.handle)?a[e.handle]=0n:s.push(e);if(s.length===0)return a;let c=(0,u.getAddress)(r.address),l=[];for(let e of s){let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?l.push(e):a[e.handle]=t}if(l.length===0)return a;let d=Array.from(new Set(i.map(e=>e.contractAddress))),f=await n.allow(d),p=new Map;for(let e of l){let t=p.get(e.contractAddress);t?t.push(e.handle):p.set(e.contractAddress,[e.handle])}let m=Date.now(),h=l.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:h}),await t.n([...p.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,...No(f,e),signerAddress:c});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of h){let n=a[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-m,handles:h,result:e}),a}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:o.s(e),durationMs:Date.now()-m,handles:h}),re(e,`Failed to decrypt handles`)}}async delegatedUserDecrypt(e,n,r=n){let i=this.#a(`delegatedUserDecrypt`),a=await this.requireAlignedWalletAccount(`delegatedUserDecrypt`);if(e.length===0)return{};let s=(0,u.getAddress)(n),c=(0,u.getAddress)(r),l=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),d={},f=[];for(let e of l)t._(e.handle)?d[e.handle]=0n:f.push(e);if(f.length===0)return d;let p=Array.from(new Set(l.map(e=>e.contractAddress))),m=await i.allow(p,s),h=(0,u.getAddress)(a.address),g=await Ro({provider:this.provider,relayer:this.relayer,contractAddresses:p,delegatorAddress:s,delegateAddress:h}),_=[];for(let e of f){if(g.has(e.contractAddress)){await this.cache.delete(c,e.contractAddress,e.handle),_.push(e);continue}let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?_.push(e):d[e.handle]=t}if(_.length===0)return d;let v=new Map;for(let e of _){let t=v.get(e.contractAddress);t?t.push(e.handle):v.set(e.contractAddress,[e.handle])}let ee=Date.now(),y=_.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:y}),await t.n([...v.entries()].map(([e,t])=>async()=>{let n=await this.relayer.delegatedUserDecrypt({handles:t,contractAddress:e,...Po(m,e),delegateAddress:h});for(let[t,r]of Object.entries(n))d[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of y){let n=d[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-ee,handles:y,result:e}),d}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:o.s(e),durationMs:Date.now()-ee,handles:y}),re(e,`Failed to decrypt delegated handles`,!0)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw re(e,`Public decryption failed`)}}async encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:o.s(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}async revokePermits(e){let t=this.#a(`revokePermits`),n=(0,u.getAddress)((await this.requireAlignedWalletAccount(`revokePermits`)).address);try{await t.revokePermits(e)}finally{await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(n))}}async clearCredentials(){let e=this.#a(`clearCredentials`),t=(0,u.getAddress)((await this.requireAlignedWalletAccount(`clearCredentials`)).address);try{await e.clearCredentials()}finally{await s.t(`clear decrypt cache`,()=>this.cache.clearForRequester(t))}}dispose(){this.#i?.(),this.#i=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function ms(e){return`zama:pending-unshield:${e}`}function hs(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function gs(e,t,n,r){if(r===void 0){await e.set(ms(t),n);return}await e.set(ms(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _s(e,t){return(await vs(e,t))?.unwrapTxHash??null}async function vs(e,t){return hs(await e.get(ms(t)))}async function ys(e,t){await e.delete(ms(t))}var bs=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 xs=new bs;exports.ACL_TOPICS=cs,exports.AclPausedError=t.v,exports.AclTopics=Q,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=ee,exports.BaseSigner=r.t,exports.ChainMismatchError=g,exports.ChromeSessionStorage=bs,exports.ConfigurationError=e.t,exports.DecryptCache=le,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=us,exports.DelegationContractIsSelfError=t.y,exports.DelegationCooldownError=t.b,exports.DelegationDelegateEqualsContractError=t.x,exports.DelegationExpirationTooSoonError=t.S,exports.DelegationExpiredError=t.C,exports.DelegationExpiryUnchangedError=t.w,exports.DelegationNotFoundError=t.T,exports.DelegationNotPropagatedError=t.E,exports.DelegationSelfNotAllowedError=t.D,exports.ERC1363_INTERFACE_ID=l.c,exports.ERC20ReadFailedError=y,exports.ERC7984_INTERFACE_ID=l.l,exports.ERC7984_WRAPPER_INTERFACE_ID=l.u,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=l.d,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=a.t,exports.InsufficientConfidentialBalanceError=_,exports.InsufficientERC20BalanceError=v,exports.InvalidKeypairError=m,exports.KeypairExpiredError=p,exports.MemoryStorage=r.s,exports.MutableWalletAccountStore=r.n,exports.NoCiphertextError=h,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=r.l,exports.SignerRequiredError=r.u,exports.SigningFailedError=t.O,exports.SigningRejectedError=t.k,exports.TOKEN_TOPICS=ts,exports.Token=ls,exports.Topics=J,exports.TransactionRevertedError=f,exports.WalletAccountNotReadyError=r.d,exports.WalletNotConnectedError=r.f,exports.WrappersRegistry=fs,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=ps,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.anvil=c.t,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.buildZamaConfig=r.i,exports.chains=c.n,exports.chromeSessionStorage=xs,exports.clearPendingUnshield=ys,exports.cleartext=ie,exports.confidentialBalanceOfContract=l.b,exports.confidentialTotalSupplyContract=l.x,exports.confidentialTransferContract=l.S,exports.confidentialTransferFromContract=l.C,exports.createConfig=oe,exports.createWalletAccountStore=r.r,exports.decimalsContract=t.f,exports.decodeAclEvent=is,exports.decodeAclEvents=as,exports.decodeConfidentialTransfer=Wo,exports.decodeDelegatedForUserDecryption=ns,exports.decodeOnChainEvent=Zo,exports.decodeOnChainEvents=Qo,exports.decodeRevokedDelegationForUserDecryption=rs,exports.decodeUnwrapFinalized=qo,exports.decodeUnwrapRequested=Ko,exports.decodeUnwrappedFinalized=Jo,exports.decodeUnwrappedStarted=Xo,exports.decodeWrapped=Go,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.g,exports.findDelegatedForUserDecryption=os,exports.findRevokedDelegationForUserDecryption=ss,exports.findUnwrapRequested=$o,exports.findWrapped=es,exports.getConfidentialTokenAddressContract=l.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=l.n,exports.getTokenPairContract=l.r,exports.getTokenPairsContract=l.i,exports.getTokenPairsLengthContract=l.a,exports.getTokenPairsSliceContract=l.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=a.n,exports.inferredTotalSupplyContract=l._,exports.isConfidentialTokenContract=l.f,exports.isConfidentialTokenValidContract=l.s,exports.isConfidentialWrapperContract=l.p,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=l.w,exports.isZeroHandle=t._,exports.loadPendingUnshield=_s,exports.loadPendingUnshieldRequest=vs,exports.mainnet=c.a,exports.matchAclRevert=b,exports.matchZamaError=e.a,exports.memoryStorage=r.c,exports.nameContract=t.m,exports.rateContract=l.T,exports.resolveChainRelayers=r.a,exports.resolveStorage=r.o,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=gs,exports.sepolia=c.o,exports.setOperatorContract=l.E,exports.supportsInterfaceContract=l.h,exports.symbolContract=t.h,exports.totalSupplyContract=l.D,exports.transferAndCallContract=ce,exports.underlyingContract=l.v,exports.unwrapContract=l.O,exports.unwrapFromBalanceContract=l.k,exports.wrapContract=l.y;
|
|
40
40
|
//# sourceMappingURL=index.cjs.map
|