@hashgraphonline/hashinal-wc 2.0.10 → 2.0.12

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.
@@ -463,7 +463,7 @@ NPM Registry: https://www.npmjs.com/package/@reown/appkit`}},PresetsUtil={Networ
463
463
  `},hexToRgb(Fs){const Ps=parseInt(Fs,16),Hs=Ps>>16&255,Ws=Ps>>8&255,Zs=Ps&255;return[Hs,Ws,Zs]},tintColor(Fs,Ps){const[Hs,Ws,Zs]=Fs,zs=Math.round(Hs+(255-Hs)*Ps),Ys=Math.round(Ws+(255-Ws)*Ps),Va=Math.round(Zs+(255-Zs)*Ps);return[zs,Ys,Va]},isNumber(Fs){return{number:/^[0-9]+$/u}.number.test(Fs)},getColorTheme(Fs){return Fs||(typeof window<"u"&&window.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark")},splitBalance(Fs){const Ps=Fs.split(".");return Ps.length===2?[Ps[0],Ps[1]]:["0","00"]},roundNumber(Fs,Ps,Hs){return Fs.toString().length>=Ps?Number(Fs).toFixed(Hs):Fs},cssDurationToNumber(Fs){return Fs.endsWith("s")?Number(Fs.replace("s",""))*1e3:Fs.endsWith("ms")?Number(Fs.replace("ms","")):0},maskInput({value:Fs,decimals:Ps,integers:Hs}){if(Fs=Fs.replace(",","."),Fs===DECIMAL_POINT)return`0${DECIMAL_POINT}`;const[Ws="",Zs]=Fs.split(DECIMAL_POINT).map(qs=>qs.replace(/[^0-9]/gu,"")),zs=Hs?Ws.substring(0,Hs):Ws,Ys=zs.length===2?String(Number(zs)):zs,Va=typeof Ps=="number"?Zs?.substring(0,Ps):Zs,Xs=typeof Ps!="number"||Ps>0;return(typeof Va=="string"&&Xs?[Ys,Va].join(DECIMAL_POINT):Ys)??""},capitalize(Fs){return Fs?Fs.charAt(0).toUpperCase()+Fs.slice(1):""}},FLOAT_FIXED_VALUE=3,GAS_FEE_THRESHOLD=.1,plusTypes=["receive","deposit","borrow","claim"],minusTypes=["withdraw","repay","burn"],TransactionUtil={getTransactionGroupTitle(Fs,Ps){const Hs=DateUtil.getYear(),Ws=DateUtil.getMonthNameByIndex(Ps);return Fs===Hs?Ws:`${Ws} ${Fs}`},getTransactionImages(Fs){const[Ps]=Fs;return Fs?.length>1?Fs.map(Ws=>this.getTransactionImage(Ws)):[this.getTransactionImage(Ps)]},getTransactionImage(Fs){return{type:TransactionUtil.getTransactionTransferTokenType(Fs),url:TransactionUtil.getTransactionImageURL(Fs)}},getTransactionImageURL(Fs){let Ps;const Hs=!!Fs?.nft_info,Ws=!!Fs?.fungible_info;return Fs&&Hs?Ps=Fs?.nft_info?.content?.preview?.url:Fs&&Ws&&(Ps=Fs?.fungible_info?.icon?.url),Ps},getTransactionTransferTokenType(Fs){if(Fs?.fungible_info)return"FUNGIBLE";if(Fs?.nft_info)return"NFT"},getTransactionDescriptions(Fs,Ps){const Hs=Fs?.metadata?.operationType,Ws=Ps||Fs?.transfers,Zs=Ws?.length>0,zs=Ws?.length>1,Ys=Zs&&Ws?.every(Mc=>!!Mc?.fungible_info),[Va,Xs]=Ws;let Ma=this.getTransferDescription(Va),qs=this.getTransferDescription(Xs);if(!Zs)return(Hs==="send"||Hs==="receive")&&Ys?(Ma=UiHelperUtil.getTruncateString({string:Fs?.metadata.sentFrom,charsStart:4,charsEnd:6,truncate:"middle"}),qs=UiHelperUtil.getTruncateString({string:Fs?.metadata.sentTo,charsStart:4,charsEnd:6,truncate:"middle"}),[Ma,qs]):[Fs.metadata.status];if(zs)return Ws.map(Mc=>this.getTransferDescription(Mc));let Js="";return plusTypes.includes(Hs)?Js="+":minusTypes.includes(Hs)&&(Js="-"),Ma=Js.concat(Ma),[Ma]},getTransferDescription(Fs){let Ps="";return Fs&&(Fs?.nft_info?Ps=Fs?.nft_info?.name||"-":Fs?.fungible_info&&(Ps=this.getFungibleTransferDescription(Fs)||"-")),Ps},getFungibleTransferDescription(Fs){return Fs?[this.getQuantityFixedValue(Fs?.quantity.numeric),Fs?.fungible_info?.symbol].join(" ").trim():null},mergeTransfers(Fs){if(Fs?.length<=1)return Fs;const Hs=this.filterGasFeeTransfers(Fs).reduce((Zs,zs)=>{const Ys=zs?.fungible_info?.name,Va=Zs.find(({fungible_info:Xs,direction:Ma})=>Ys&&Ys===Xs?.name&&Ma===zs.direction);if(Va){const Xs=Number(Va.quantity.numeric)+Number(zs.quantity.numeric);Va.quantity.numeric=Xs.toString(),Va.value=(Va.value||0)+(zs.value||0)}else Zs.push(zs);return Zs},[]);let Ws=Hs;return Hs.length>2&&(Ws=Hs.sort((Zs,zs)=>(zs.value||0)-(Zs.value||0)).slice(0,2)),Ws=Ws.sort((Zs,zs)=>Zs.direction==="out"&&zs.direction==="in"?-1:Zs.direction==="in"&&zs.direction==="out"?1:0),Ws},filterGasFeeTransfers(Fs){const Ps=Fs.reduce((Ws,Zs)=>{const zs=Zs?.fungible_info?.name;return zs&&(Ws[zs]||(Ws[zs]=[]),Ws[zs].push(Zs)),Ws},{}),Hs=[];return Object.values(Ps).forEach(Ws=>{if(Ws.length===1){const Zs=Ws[0];Zs&&Hs.push(Zs)}else{const Zs=Ws.filter(Ys=>Ys.direction==="in"),zs=Ws.filter(Ys=>Ys.direction==="out");if(Zs.length===1&&zs.length===1){const Ys=Zs[0],Va=zs[0];let Xs=!1;if(Ys&&Va){const Ma=Number(Ys.quantity.numeric),qs=Number(Va.quantity.numeric);qs<Ma*GAS_FEE_THRESHOLD?(Hs.push(Ys),Xs=!0):Ma<qs*GAS_FEE_THRESHOLD&&(Hs.push(Va),Xs=!0)}Xs||Hs.push(...Ws)}else{const Ys=this.filterGasFeesFromTokenGroup(Ws);Hs.push(...Ys)}}}),Fs.forEach(Ws=>{Ws?.fungible_info?.name||Hs.push(Ws)}),Hs},filterGasFeesFromTokenGroup(Fs){if(Fs.length<=1)return Fs;const Ps=Fs.map(Va=>Number(Va.quantity.numeric)),Hs=Math.max(...Ps),Ws=Math.min(...Ps),Zs=.01;if(Ws<Hs*Zs)return Fs.filter(Xs=>Number(Xs.quantity.numeric)>=Hs*Zs);const zs=Fs.filter(Va=>Va.direction==="in"),Ys=Fs.filter(Va=>Va.direction==="out");if(zs.length===1&&Ys.length===1){const Va=zs[0],Xs=Ys[0];if(Va&&Xs){const Ma=Number(Va.quantity.numeric),qs=Number(Xs.quantity.numeric);if(qs<Ma*GAS_FEE_THRESHOLD)return[Va];if(Ma<qs*GAS_FEE_THRESHOLD)return[Xs]}}return Fs},getQuantityFixedValue(Fs){return Fs?parseFloat(Fs).toFixed(FLOAT_FIXED_VALUE):null}};function standardCustomElement(Fs,Ps){const{kind:Hs,elements:Ws}=Ps;return{kind:Hs,elements:Ws,finisher(Zs){customElements.get(Fs)||customElements.define(Fs,Zs)}}}function legacyCustomElement(Fs,Ps){return customElements.get(Fs)||customElements.define(Fs,Ps),Ps}function customElement(Fs){return function(Hs){return typeof Hs=="function"?legacyCustomElement(Fs,Hs):standardCustomElement(Fs,Hs)}}const WcConstantsUtil={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class UniversalAdapter extends AdapterBlueprint{async setUniversalProvider(Ps){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new WalletConnectConnector({provider:Ps,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(Ps){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(Ps.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(Ps){console.warn("UniversalAdapter:disconnect - error",Ps)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:Ps}){const Ws=this.provider?.session?.namespaces?.[Ps]?.accounts?.map(Zs=>{const[,,zs]=Zs.split(":");return zs}).filter((Zs,zs,Ys)=>Ys.indexOf(Zs)===zs)||[];return Promise.resolve({accounts:Ws.map(Zs=>CoreHelperUtil.createAccount(Ps,Zs,Ps==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(Ps){if(!(Ps.caipNetwork&&ConstantsUtil$2.BALANCE_SUPPORTED_CHAINS.includes(Ps.caipNetwork?.chainNamespace))||Ps.caipNetwork?.testnet)return{balance:"0.00",symbol:Ps.caipNetwork?.nativeCurrency.symbol||""};const Ws=ChainController.getAccountData();if(Ws?.balanceLoading&&Ps.chainId===ChainController.state.activeCaipNetwork?.id)return{balance:Ws?.balance||"0.00",symbol:Ws?.balanceSymbol||""};const zs=(await ChainController.fetchTokenBalance()).find(Ys=>Ys.chainId===`${Ps.caipNetwork?.chainNamespace}:${Ps.chainId}`&&Ys.symbol===Ps.caipNetwork?.nativeCurrency.symbol);return{balance:zs?.quantity.numeric||"0.00",symbol:zs?.symbol||Ps.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(Ps){const{provider:Hs,message:Ws,address:Zs}=Ps;if(!Hs)throw new Error("UniversalAdapter:signMessage - provider is undefined");let zs="";return ChainController.state.activeCaipNetwork?.chainNamespace===ConstantsUtil$3.CHAIN.SOLANA?zs=(await Hs.request({method:"solana_signMessage",params:{message:bs58.encode(new TextEncoder().encode(Ws)),pubkey:Zs}},ChainController.state.activeCaipNetwork?.caipNetworkId)).signature:zs=await Hs.request({method:"personal_sign",params:[Ws,Zs]},ChainController.state.activeCaipNetwork?.caipNetworkId),{signature:zs}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(Ps){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(Ps){const{caipNetwork:Hs}=Ps,Ws=this.getWalletConnectConnector();if(Hs.chainNamespace===ConstantsUtil$3.CHAIN.EVM)try{await Ws.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:toHex$1(Hs.id)}]})}catch(Zs){if(Zs.code===WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||Zs.code===WcConstantsUtil.ERROR_INVALID_CHAIN_ID||Zs.code===WcConstantsUtil.ERROR_CODE_DEFAULT||Zs?.data?.originalError?.code===WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await Ws.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:toHex$1(Hs.id),rpcUrls:[Hs?.rpcUrls.chainDefault?.http],chainName:Hs.name,nativeCurrency:Hs.nativeCurrency,blockExplorerUrls:[Hs.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}Ws.provider.setDefaultChain(Hs.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(Ws=>Ws.type==="WALLET_CONNECT")?.provider}}const FEATURE_KEYS=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],featureConfig={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return!!Fs.isEnabled&&Ps.includes("email")},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.email:!!Fs},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps.filter(Hs=>Hs!=="email"):!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.socials:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.socials:!1:Fs},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps:!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.swaps:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.swaps:!1:Fs},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps:!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.onramp:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.onramp:!1:Fs},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.activity:!!Fs},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.reownBranding:!!Fs},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>Fs.isEnabled&&(Fs.config??[]),processFallback:Fs=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>typeof Fs>"u"?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!Fs}},ConfigUtil={localSettingsOverridden:new Set,getApiConfig(Fs,Ps){return Ps?.find(Hs=>Hs.id===Fs)},addWarning(Fs,Ps){if(Fs!==void 0){const Hs=featureConfig[Ps],Ws=Hs.isLegacy?`"features.${Hs.localFeatureName}" (now "${Ps}")`:`"features.${Ps}"`;this.localSettingsOverridden.add(Ws)}},processFeature(Fs,Ps,Hs,Ws,Zs){const zs=featureConfig[Fs],Ys=Ps[zs.localFeatureName];if(Zs&&!zs.isAvailableOnBasic)return!1;if(Ws){const Va=this.getApiConfig(zs.apiFeatureName,Hs);return Va?.config===null?this.processFallbackFeature(Fs,Ys):Va?.config?(Ys!==void 0&&this.addWarning(Ys,Fs),this.processApiFeature(Fs,Va)):!1}return this.processFallbackFeature(Fs,Ys)},processApiFeature(Fs,Ps){return featureConfig[Fs].processApi(Ps)},processFallbackFeature(Fs,Ps){return featureConfig[Fs].processFallback(Ps)},async fetchRemoteFeatures(Fs){const Ps=Fs.basic??!1,Hs=Fs.features||{};this.localSettingsOverridden.clear();let Ws=null,Zs=!1;try{Ws=await ApiController.fetchProjectConfig(),Zs=Ws!=null}catch(Ys){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",Ys)}const zs=Zs&&!Ps?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES:ConstantsUtil$2.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const Ys of FEATURE_KEYS){const Va=this.processFeature(Ys,Hs,Ws,Zs,Ps);Object.assign(zs,{[Ys]:Va})}}catch(Ys){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",Ys),ConstantsUtil$2.DEFAULT_REMOTE_FEATURES}if(Zs&&this.localSettingsOverridden.size>0){const Ys=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;AlertController.open({debugMessage:ErrorUtil.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(Ys)},"warning")}return zs}};class AppKitBaseClient{constructor(Ps){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(Hs,Ws)=>{if(Hs){const Zs=ChainController.getCaipNetworks(Hs)?.find(Va=>Va.id===Ws);if(Zs)return Zs;const zs=ChainController.getNetworkData(Hs)?.caipNetwork;return zs||ChainController.getRequestedCaipNetworks(Hs).filter(Va=>Va.chainNamespace===Hs)?.[0]}return ChainController.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const Hs=this.getCaipNetwork();if(Hs)return Hs.id},this.getCaipNetworks=Hs=>ChainController.getCaipNetworks(Hs),this.getActiveChainNamespace=()=>ChainController.state.activeChain,this.setRequestedCaipNetworks=(Hs,Ws)=>{ChainController.setRequestedCaipNetworks(Hs,Ws)},this.getApprovedCaipNetworkIds=()=>ChainController.getAllApprovedCaipNetworkIds(),this.getCaipAddress=Hs=>ChainController.state.activeChain===Hs||!Hs?ChainController.state.activeCaipAddress:ChainController.state.chains.get(Hs)?.accountState?.caipAddress,this.setClientId=Hs=>{BlockchainApiController.setClientId(Hs)},this.getProvider=Hs=>ProviderController.getProvider(Hs),this.getProviderType=Hs=>ProviderController.getProviderId(Hs),this.getPreferredAccountType=Hs=>getPreferredAccountType(Hs),this.setCaipAddress=(Hs,Ws,Zs=!1)=>{ChainController.setAccountProp("caipAddress",Hs,Ws,Zs),ChainController.setAccountProp("address",CoreHelperUtil.getPlainAddress(Hs),Ws,Zs)},this.setBalance=(Hs,Ws,Zs)=>{ChainController.setAccountProp("balance",Hs,Zs),ChainController.setAccountProp("balanceSymbol",Ws,Zs)},this.setProfileName=(Hs,Ws)=>{ChainController.setAccountProp("profileName",Hs,Ws)},this.setProfileImage=(Hs,Ws)=>{ChainController.setAccountProp("profileImage",Hs,Ws)},this.setUser=(Hs,Ws)=>{ChainController.setAccountProp("user",Hs,Ws)},this.resetAccount=Hs=>{ChainController.resetAccount(Hs)},this.setCaipNetwork=Hs=>{ChainController.setActiveCaipNetwork(Hs)},this.setCaipNetworkOfNamespace=(Hs,Ws)=>{ChainController.setChainNetworkData(Ws,{caipNetwork:Hs})},this.setStatus=(Hs,Ws)=>{ChainController.setAccountProp("status",Hs,Ws),ConnectorController.isConnected()?StorageUtil.setConnectionStatus("connected"):StorageUtil.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=Hs=>ChainController.getAccountData(Hs)?.address,this.setConnectors=Hs=>{const Ws=[...ConnectorController.state.allConnectors,...Hs];ConnectorController.setConnectors(Ws)},this.setConnections=(Hs,Ws)=>{StorageUtil.setConnections(Hs,Ws),ConnectionController.setConnections(Hs,Ws)},this.fetchIdentity=Hs=>BlockchainApiController.fetchIdentity(Hs),this.getReownName=Hs=>EnsController.getNamesForAddress(Hs),this.getConnectors=()=>ConnectorController.getConnectors(),this.getConnectorImage=Hs=>AssetUtil.getConnectorImage(Hs),this.getConnections=Hs=>this.remoteFeatures.multiWallet?ConnectionControllerUtil.getConnectionsData(Hs).connections:(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=Hs=>this.remoteFeatures.multiWallet?ConnectionControllerUtil.getConnectionsData(Hs).recentConnections:(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async Hs=>{if(!this.remoteFeatures.multiWallet){AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await ConnectionController.switchConnection(Hs)},this.deleteConnection=Hs=>{if(!this.remoteFeatures.multiWallet){AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}StorageUtil.deleteAddressFromConnection(Hs),ConnectionController.syncStorageConnections()},this.setConnectedWalletInfo=(Hs,Ws)=>{const Zs=ProviderController.getProviderId(Ws),zs=Hs?{...Hs,type:Zs}:void 0;ChainController.setAccountProp("connectedWalletInfo",zs,Ws)},this.getIsConnectedState=()=>!!ChainController.state.activeCaipAddress,this.addAddressLabel=(Hs,Ws,Zs)=>{const zs=ChainController.getAccountData(Zs)?.addressLabels||{};ChainController.setAccountProp("addressLabels",{...zs,[Hs]:Ws},Zs)},this.removeAddressLabel=(Hs,Ws)=>{const Zs=ChainController.getAccountData(Ws)?.addressLabels||{};ChainController.setAccountProp("addressLabels",{...Zs,[Hs]:void 0},Ws)},this.getAddress=Hs=>{const Ws=Hs||ChainController.state.activeChain;return ChainController.getAccountData(Ws)?.address},this.resetNetwork=Hs=>{ChainController.resetNetwork(Hs)},this.addConnector=Hs=>{ConnectorController.addConnector(Hs)},this.resetWcConnection=()=>{ConnectionController.resetWcConnection()},this.setAddressExplorerUrl=(Hs,Ws)=>{ChainController.setAccountProp("addressExplorerUrl",Hs,Ws)},this.setSmartAccountDeployed=(Hs,Ws)=>{ChainController.setAccountProp("smartAccountDeployed",Hs,Ws)},this.setPreferredAccountType=(Hs,Ws)=>{ChainController.setAccountProp("preferredAccountType",Hs,Ws)},this.setEIP6963Enabled=Hs=>{OptionsController.setEIP6963Enabled(Hs)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=Ps,this.version=Ps.sdkVersion,this.caipNetworks=this.extendCaipNetworks(Ps),this.chainNamespaces=this.getChainNamespacesSet(Ps.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(Ps),this.chainAdapters=this.createAdapters(Ps.adapters),this.readyPromise=this.initialize(Ps),SemVerUtils.checkSDKVersion(Ps.sdkVersion)}getChainNamespacesSet(Ps,Hs){const Ws=Ps?.map(zs=>zs.namespace).filter(zs=>!!zs);if(Ws?.length)return[...new Set(Ws)];const Zs=Hs?.map(zs=>zs.chainNamespace);return[...new Set(Zs)]}async initialize(Ps){if(this.initializeProjectSettings(Ps),this.initControllers(Ps),await this.initChainAdapters(),this.sendInitializeEvent(Ps),OptionsController.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await ConfigUtil.fetchRemoteFeatures(Ps),OptionsController.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&OnRampController.setOnrampProviders(this.remoteFeatures.onramp),(OptionsController.state.remoteFeatures?.email||Array.isArray(OptionsController.state.remoteFeatures?.socials)&&OptionsController.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),OptionsController.state.features?.reownAuthentication||OptionsController.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:Hs}=await Promise.resolve().then(()=>features),Ws=OptionsController.state.siwx;Ws instanceof Hs||(Ws&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),OptionsController.setSIWX(new Hs))}}async openSend(Ps){const Hs=Ps.namespace||ChainController.state.activeChain,Ws=this.getCaipAddress(Hs),Zs=this.getCaipNetwork(Hs)?.id;if(!Ws)throw new Error("openSend: caipAddress not found");if(Zs?.toString()!==Ps.chainId.toString()){const zs=ChainController.getCaipNetworkById(Ps.chainId,Hs);if(!zs)throw new Error(`openSend: caipNetwork with chainId ${Ps.chainId} not found`);await this.switchNetwork(zs,{throwOnFailure:!0})}try{const zs=TokenUtil.getTokenSymbolByAddress(Ps.assetAddress);zs&&await ApiController.fetchTokenImages([zs])}catch{}return await ModalController.open({view:"WalletSend",data:{send:Ps}}),new Promise((zs,Ys)=>{const Va=SendController.subscribeKey("hash",qs=>{qs&&(Ma(),zs({hash:qs}))}),Xs=ModalController.subscribe(qs=>{qs.open||(Ma(),Ys(new Error("Modal closed")))}),Ma=this.createCleanupHandler([Va,Xs])})}toModalOptions(){function Ps(Ws){return Ws?.view==="Swap"}function Hs(Ws){return Ws?.view==="WalletSend"}return{isSwap:Ps,isSend:Hs}}async checkAllowedOrigins(){try{const Ps=await ApiController.fetchAllowedOrigins();if(!CoreHelperUtil.isClient())return;const Hs=window.location.origin;WcHelpersUtil.isOriginAllowed(Hs,Ps,ConstantsUtil$3.DEFAULT_ALLOWED_ANCESTORS)||AlertController.open(ErrorUtil.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(Ps){if(!(Ps instanceof Error))return;switch(Ps.message){case"RATE_LIMITED":AlertController.open(ErrorUtil.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const Hs=Ps.cause instanceof Error?Ps.cause:Ps;AlertController.open({displayMessage:ErrorUtil.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:ErrorUtil.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(Hs.message)},"error");break}}}}createCleanupHandler(Ps){return()=>{Ps.forEach(Hs=>{try{Hs()}catch{}})}}sendInitializeEvent(Ps){const{...Hs}=Ps;delete Hs.adapters,delete Hs.universalProvider,EventsController.sendEvent({type:"track",event:"INITIALIZE",properties:{...Hs,networks:Ps.networks.map(Ws=>Ws.id),siweConfig:{options:Ps.siweConfig?.options||{}}}})}initControllers(Ps){this.initializeOptionsController(Ps),this.initializeChainController(Ps),this.initializeThemeController(Ps),this.initializeConnectionController(Ps),this.initializeConnectorController()}initAdapterController(){AdapterController.initialize(this.chainAdapters)}initializeThemeController(Ps){Ps.themeMode&&ThemeController.setThemeMode(Ps.themeMode),Ps.themeVariables&&ThemeController.setThemeVariables(Ps.themeVariables)}initializeChainController(Ps){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");ChainController.initialize(Ps.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const Hs=this.getDefaultNetwork();Hs&&ChainController.setActiveCaipNetwork(Hs)}initializeConnectionController(Ps){ConnectionController.initialize(Ps.adapters??[]),ConnectionController.setWcBasic(Ps.basic??!1)}initializeConnectorController(){ConnectorController.initialize(this.chainNamespaces)}initializeProjectSettings(Ps){OptionsController.setProjectId(Ps.projectId),OptionsController.setSdkVersion(Ps.sdkVersion)}initializeOptionsController(Ps){OptionsController.setDebug(Ps.debug!==!1),OptionsController.setEnableWalletGuide(Ps.enableWalletGuide!==!1),OptionsController.setEnableWallets(Ps.enableWallets!==!1),OptionsController.setEIP6963Enabled(Ps.enableEIP6963!==!1),OptionsController.setEnableNetworkSwitch(Ps.enableNetworkSwitch!==!1),OptionsController.setEnableReconnect(Ps.enableReconnect!==!1),OptionsController.setEnableMobileFullScreen(Ps.enableMobileFullScreen===!0),OptionsController.setCoinbasePreference(Ps.coinbasePreference),OptionsController.setEnableAuthLogger(Ps.enableAuthLogger!==!1),OptionsController.setCustomRpcUrls(Ps.customRpcUrls),OptionsController.setEnableEmbedded(Ps.enableEmbedded),OptionsController.setAllWallets(Ps.allWallets),OptionsController.setIncludeWalletIds(Ps.includeWalletIds),OptionsController.setExcludeWalletIds(Ps.excludeWalletIds),OptionsController.setFeaturedWalletIds(Ps.featuredWalletIds),OptionsController.setTokens(Ps.tokens),OptionsController.setTermsConditionsUrl(Ps.termsConditionsUrl),OptionsController.setPrivacyPolicyUrl(Ps.privacyPolicyUrl),OptionsController.setCustomWallets(Ps.customWallets),OptionsController.setFeatures(Ps.features),OptionsController.setAllowUnsupportedChain(Ps.allowUnsupportedChain),OptionsController.setUniversalProviderConfigOverride(Ps.universalProviderConfigOverride),OptionsController.setPreferUniversalLinks(Ps.experimental_preferUniversalLinks),OptionsController.setDefaultAccountTypes(Ps.defaultAccountTypes);const Hs=this.getDefaultMetaData();if(!Ps.metadata&&Hs&&(Ps.metadata=Hs),OptionsController.setMetadata(Ps.metadata),OptionsController.setDisableAppend(Ps.disableAppend),OptionsController.setEnableEmbedded(Ps.enableEmbedded),OptionsController.setSIWX(Ps.siwx),this.features=OptionsController.state.features??{},!Ps.projectId){AlertController.open(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(Ps.adapters?.find(Zs=>Zs.namespace===ConstantsUtil$3.CHAIN.EVM)&&Ps.siweConfig){if(Ps.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");OptionsController.setSIWX(Ps.siweConfig.mapToSIWX())}}getDefaultMetaData(){return CoreHelperUtil.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(Ps){const Hs=this.getActiveChainNamespace();if(Hs){const Ws=CaipNetworksUtil.getUnsupportedNetwork(`${Hs}:${Ps}`);ChainController.setActiveCaipNetwork(Ws)}}getDefaultNetwork(){return CaipNetworksUtil.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(Ps,Hs){return CaipNetworksUtil.extendCaipNetwork(Ps,{customNetworkImageUrls:Hs.chainImages,projectId:Hs.projectId})}extendCaipNetworks(Ps){return CaipNetworksUtil.extendCaipNetworks(Ps.networks,{customNetworkImageUrls:Ps.chainImages,customRpcUrls:Ps.customRpcUrls,projectId:Ps.projectId})}extendDefaultCaipNetwork(Ps){const Hs=Ps.networks.find(Zs=>Zs.id===Ps.defaultNetwork?.id);return Hs?CaipNetworksUtil.extendCaipNetwork(Hs,{customNetworkImageUrls:Ps.chainImages,customRpcUrls:Ps.customRpcUrls,projectId:Ps.projectId}):void 0}async disconnectConnector(Ps,Hs){try{this.setLoading(!0,Ps);let Ws={connections:[]};const Zs=this.getAdapter(Ps);return(ChainController.state.chains.get(Ps)?.accountState?.caipAddress||!OptionsController.state.enableReconnect)&&Zs?.disconnect&&(Ws=await Zs.disconnect({id:Hs})),this.setLoading(!1,Ps),Ws}catch(Ws){throw this.setLoading(!1,Ps),new Error(`Failed to disconnect chains: ${Ws.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const Ps=ChainController.state.activeChain,Hs=this.getAdapter(Ps),Ws=this.getCaipNetwork(Ps)?.id,Zs=ConnectionController.getConnections(Ps),zs=this.remoteFeatures.multiWallet,Ys=Zs.length>0;if(!Hs)throw new Error("Adapter not found");const Va=await Hs.connectWalletConnect(Ws);(!Ys||!zs)&&this.close(),this.setClientId(Va?.clientId||null),StorageUtil.setConnectedNamespaces([...ChainController.state.chains.keys()]),await this.syncWalletConnectAccount(),await SIWXUtil.initializeIfEnabled()},connectExternal:async Ps=>{const Hs=await this.onConnectExternal(Ps);return await this.connectInactiveNamespaces(Ps,Hs),Hs?{address:Hs.address}:void 0},reconnectExternal:async({id:Ps,info:Hs,type:Ws,provider:Zs})=>{const zs=ChainController.state.activeChain,Ys=this.getAdapter(zs);if(!zs)throw new Error("reconnectExternal: namespace not found");if(!Ys)throw new Error("reconnectExternal: adapter not found");Ys?.reconnect&&(await Ys?.reconnect({id:Ps,info:Hs,type:Ws,provider:Zs,chainId:this.getCaipNetwork()?.id}),StorageUtil.addConnectedNamespace(zs),this.syncConnectedWalletInfo(zs))},disconnectConnector:async Ps=>{await this.disconnectConnector(Ps.namespace,Ps.id)},disconnect:async Ps=>{const{id:Hs,chainNamespace:Ws,initialDisconnect:Zs}=Ps||{},zs=Ws||ChainController.state.activeChain,Ys=ConnectorController.getConnectorId(zs),Va=Hs===ConstantsUtil$3.CONNECTOR_ID.AUTH||Ys===ConstantsUtil$3.CONNECTOR_ID.AUTH,Xs=Hs===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT||Ys===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;try{const Ma=Array.from(ChainController.state.chains.keys());let qs=Ws?[Ws]:Ma;(Xs||Va)&&(qs=Ma);const Js=qs.map(async Vc=>{const Dc=ConnectorController.getConnectorId(Vc),sl=Hs||Dc,ll=await this.disconnectConnector(Vc,sl);ll&&(Va&&StorageUtil.deleteConnectedSocialProvider(),ll.connections.forEach(hl=>{StorageUtil.addDisconnectedConnectorId(hl.connectorId,Vc)})),Zs&&this.onDisconnectNamespace({chainNamespace:Vc,closeModal:!1})}),Mc=await Promise.allSettled(Js);SendController.resetSend(),ConnectionController.resetWcConnection(),SIWXUtil.getSIWX()?.signOutOnDisconnect&&await SIWXUtil.clearSessions(),ConnectorController.setFilterByNamespace(void 0),ConnectionController.syncStorageConnections();const ol=Mc.filter(Vc=>Vc.status==="rejected");if(ol.length>0)throw new Error(ol.map(Vc=>Vc.reason.message).join(", "));EventsController.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:Ws||"all"}})}catch(Ma){throw new Error(`Failed to disconnect chains: ${Ma.message}`)}},checkInstalled:Ps=>Ps?Ps.some(Hs=>!!window.ethereum?.[String(Hs)]):!!window.ethereum,signMessage:async Ps=>{const Hs=ChainController.state.activeChain,Ws=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("signMessage: namespace not found");if(!Ws)throw new Error("signMessage: adapter not found");const Zs=this.getAddress(Hs);if(!Zs)throw new Error("signMessage: address not found");return(await Ws?.signMessage({message:Ps,address:Zs,provider:ProviderController.getProvider(Hs)}))?.signature||""},sendTransaction:async Ps=>{const Hs=Ps.chainNamespace;if(!Hs)throw new Error("sendTransaction: namespace not found");if(ConstantsUtil$2.SEND_SUPPORTED_NAMESPACES.includes(Hs)){const Ws=this.getAdapter(Hs);if(!Ws)throw new Error("sendTransaction: adapter not found");const Zs=ProviderController.getProvider(Hs);return(await Ws?.sendTransaction({...Ps,caipNetwork:this.getCaipNetwork(),provider:Zs}))?.hash||""}return""},estimateGas:async Ps=>{const Hs=Ps.chainNamespace;if(Hs===ConstantsUtil$3.CHAIN.EVM){const Ws=this.getAdapter(Hs);if(!Ws)throw new Error("estimateGas: adapter is required but got undefined");const Zs=ProviderController.getProvider(Hs),zs=this.getCaipNetwork();if(!zs)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await Ws?.estimateGas({...Ps,provider:Zs,caipNetwork:zs}))?.gas||0n}return 0n},getEnsAvatar:async()=>{const Ps=ChainController.state.activeChain;if(!Ps)throw new Error("getEnsAvatar: namespace is required but got undefined");const Hs=this.getAddress(Ps);if(!Hs)throw new Error("getEnsAvatar: address not found");return await this.syncIdentity({address:Hs,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:Ps}),ChainController.getAccountData()?.profileImage||!1},getEnsAddress:async Ps=>await WcHelpersUtil.resolveReownName(Ps),writeContract:async Ps=>{const Hs=ChainController.state.activeChain,Ws=this.getAdapter(Hs);if(!Hs)throw new Error("writeContract: namespace is required but got undefined");if(!Ws)throw new Error("writeContract: adapter is required but got undefined");const Zs=this.getCaipNetwork(),zs=this.getCaipAddress(),Ys=ProviderController.getProvider(Hs);if(!Zs||!zs)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await Ws?.writeContract({...Ps,caipNetwork:Zs,provider:Ys,caipAddress:zs}))?.hash},parseUnits:(Ps,Hs)=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("parseUnits: adapter is required but got undefined");return Ws?.parseUnits({value:Ps,decimals:Hs})??0n},formatUnits:(Ps,Hs)=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("formatUnits: adapter is required but got undefined");return Ws?.formatUnits({value:Ps,decimals:Hs})??"0"},getCapabilities:async Ps=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("getCapabilities: adapter is required but got undefined");return await Hs?.getCapabilities(Ps)},grantPermissions:async Ps=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("grantPermissions: adapter is required but got undefined");return await Hs?.grantPermissions(Ps)},revokePermissions:async Ps=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("revokePermissions: adapter is required but got undefined");return Hs?.revokePermissions?await Hs.revokePermissions(Ps):"0x"},walletGetAssets:async Ps=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("walletGetAssets: adapter is required but got undefined");return await Hs?.walletGetAssets(Ps)??{}},updateBalance:Ps=>{const Hs=this.getAddress(Ps),Ws=this.getCaipNetwork(Ps);!Ws||!Hs||this.updateNativeBalance(Hs,Ws?.id,Ps)}},ConnectionController.setClient(this.connectionControllerClient)}async onConnectExternal(Ps){const Hs=ChainController.state.activeChain,Ws=Ps.chain||Hs,Zs=this.getAdapter(Ws);let zs=!0;if(Ps.type===ConstantsUtil$1.CONNECTOR_TYPE_AUTH&&ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(Js=>ConnectorController.getConnectorId(Js)===ConstantsUtil$3.CONNECTOR_ID.AUTH)&&Ps.chain!==Hs&&(zs=!1),Ps.chain&&Ps.chain!==Hs&&!Ps.caipNetwork){const Ma=this.getCaipNetworks().find(qs=>qs.chainNamespace===Ps.chain);Ma&&zs&&this.setCaipNetwork(Ma)}if(!Ws)throw new Error("connectExternal: namespace not found");if(!Zs)throw new Error("connectExternal: adapter not found");const Ys=this.getCaipNetwork(Ws),Va=Ps.caipNetwork||Ys,Xs=await Zs.connect({id:Ps.id,address:Ps.address,info:Ps.info,type:Ps.type,provider:Ps.provider,socialUri:Ps.socialUri,chainId:Ps.caipNetwork?.id||Ys?.id,rpcUrl:Ps.caipNetwork?.rpcUrls?.default?.http?.[0]||Ys?.rpcUrls?.default?.http?.[0]});if(Xs)return StorageUtil.addConnectedNamespace(Ws),this.syncProvider({...Xs,chainNamespace:Ws}),this.setStatus("connected",Ws),this.syncConnectedWalletInfo(Ws),StorageUtil.removeDisconnectedConnectorId(Ps.id,Ws),{address:Xs.address,connectedCaipNetwork:Va}}async connectInactiveNamespaces(Ps,Hs){const Ws=Ps.type===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,Zs=HelpersUtil$1.getOtherAuthNamespaces(Hs?.connectedCaipNetwork?.chainNamespace),zs=ChainController.state.activeCaipNetwork,Ys=this.getAdapter(zs?.chainNamespace);Ws&&(await Promise.all(Zs.map(async Va=>{try{const Xs=ProviderController.getProvider(Va),Ma=this.getCaipNetwork(Va);await this.getAdapter(Va)?.connect({...Ps,provider:Xs,socialUri:void 0,chainId:Ma?.id,rpcUrl:Ma?.rpcUrls?.default?.http?.[0]})&&(StorageUtil.addConnectedNamespace(Va),StorageUtil.removeDisconnectedConnectorId(Ps.id,Va),this.setStatus("connected",Va),this.syncConnectedWalletInfo(Va))}catch(Xs){AlertController.warn(ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(Va,Xs instanceof Error?Xs.message:void 0),ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),zs&&await Ys?.switchNetwork({caipNetwork:zs}))}getApprovedCaipNetworksData(){if(ProviderController.getProviderId(ChainController.state.activeChain)===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT){const Hs=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(Hs)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(Ps){const Hs=Ps.chainNamespace;if(this.getAddressByChainNamespace(Ps.chainNamespace)){const Zs=ProviderController.getProviderId(Hs);if(Ps.chainNamespace===ChainController.state.activeChain)await this.getAdapter(Hs)?.switchNetwork({caipNetwork:Ps});else if(this.setCaipNetwork(Ps),Zs===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const zs=this.getAddressByChainNamespace(Hs);zs&&this.syncAccount({address:zs,chainId:Ps.id,chainNamespace:Hs})}}else this.setCaipNetwork(Ps)}getChainsFromNamespaces(Ps={}){return Object.values(Ps).flatMap(Hs=>{const Ws=Hs.chains||[],Zs=Hs.accounts.map(zs=>{const{chainId:Ys,chainNamespace:Va}=ParseUtil.parseCaipAddress(zs);return`${Va}:${Ys}`});return Array.from(new Set([...Ws,...Zs]))})}createAdapters(Ps){return this.createClients(),this.chainNamespaces.reduce((Hs,Ws)=>{const Zs=Ps?.find(zs=>zs.namespace===Ws);return Zs?(Zs.construct({namespace:Ws,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:zs})=>zs===Ws)}),Hs[Ws]=Zs):Hs[Ws]=new UniversalAdapter({namespace:Ws,networks:this.getCaipNetworks()}),Hs},{})}async initChainAdapter(Ps){this.onConnectors(Ps),this.listenAdapter(Ps);const Hs=this.getAdapter(Ps);if(!Hs)throw new Error("adapter not found");await Hs.syncConnectors(),await this.createUniversalProviderForAdapter(Ps)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async Ps=>{await this.initChainAdapter(Ps)})),this.initAdapterController()}onConnectors(Ps){this.getAdapter(Ps)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(Ps){const Hs=this.getAdapter(Ps);if(!Hs)return;const Ws=StorageUtil.getConnectionStatus();OptionsController.state.enableReconnect===!1?this.setStatus("disconnected",Ps):Ws==="connected"?this.setStatus("connecting",Ps):Ws==="disconnected"?(StorageUtil.clearAddressCache(),this.setStatus(Ws,Ps)):this.setStatus(Ws,Ps),Hs.on("switchNetwork",({address:Zs,chainId:zs})=>{const Ys=this.getCaipNetworks().find(Ma=>Ma.id.toString()===zs.toString()||Ma.caipNetworkId.toString()===zs.toString()),Va=ChainController.state.activeChain===Ps,Xs=ChainController.state.chains.get(Ps)?.accountState?.address;if(Ys){const Ma=Va&&Zs?Zs:Xs;Ma&&this.syncAccount({address:Ma,chainId:Ys.id,chainNamespace:Ps})}else this.setUnsupportedNetwork(zs)}),Hs.on("disconnect",()=>{const Zs=this.remoteFeatures.multiWallet,zs=Array.from(ConnectionController.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:Ps,closeModal:!Zs||zs.length===0})}),Hs.on("connections",Zs=>{this.setConnections(Zs,Ps)}),Hs.on("pendingTransactions",()=>{const Zs=this.getAddress(Ps),zs=ChainController.state.activeCaipNetwork;!Zs||!zs?.id||this.updateNativeBalance(Zs,zs.id,zs.chainNamespace)}),Hs.on("accountChanged",({address:Zs,chainId:zs,connector:Ys})=>{this.handlePreviousConnectorConnection(Ys);const Va=ChainController.state.activeChain===Ps;Ys?.provider&&(this.syncProvider({id:Ys.id,type:Ys.type,provider:Ys?.provider,chainNamespace:Ps}),this.syncConnectedWalletInfo(Ps));const Xs=ChainController.getNetworkData(Ps)?.caipNetwork?.id,Ma=zs||Xs;Va&&Ma?this.syncAccount({address:Zs,chainId:Ma,chainNamespace:Ps}):!Va&&Ma?(this.syncAccountInfo(Zs,Ma,Ps),this.syncBalance({address:Zs,chainId:Ma,chainNamespace:Ps})):this.syncAccountInfo(Zs,zs,Ps),StorageUtil.addConnectedNamespace(Ps)})}async handlePreviousConnectorConnection(Ps){const Hs=Ps?.chain,Ws=Ps?.id,Zs=ConnectorController.getConnectorId(Hs),zs=OptionsController.state.remoteFeatures?.multiWallet,Va=Hs&&Ws&&Zs&&Zs!==Ws&&!zs;try{Va&&await ConnectionController.disconnect({id:Zs,namespace:Hs})}catch(Xs){console.warn("Error disconnecting previous connector",Xs)}}async createUniversalProviderForAdapter(Ps){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[Ps]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(Ps=>this.syncNamespaceConnection(Ps)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(Ps=>ConnectionController.disconnect({namespace:Ps,initialDisconnect:!0})))}catch(Ps){console.error("Error disconnecting existing connections:",Ps)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const Ps=this.getAddress();this.getCaipAddress()||StorageUtil.deleteRecentWallet();const Hs=StorageUtil.getRecentWallet();EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:Ps,properties:{method:CoreHelperUtil.isMobile()?"mobile":"qrcode",name:Hs?.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:Hs?.order}})}async syncNamespaceConnection(Ps){try{Ps===ConstantsUtil$3.CHAIN.EVM&&CoreHelperUtil.isSafeApp()&&ConnectorController.setConnectorId(ConstantsUtil$3.CONNECTOR_ID.SAFE,Ps);const Hs=ConnectorController.getConnectorId(Ps);switch(this.setStatus("connecting",Ps),Hs){case ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case ConstantsUtil$3.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(Ps)}}catch(Hs){console.warn("AppKit couldn't sync existing connection",Hs),this.setStatus("disconnected",Ps)}}onDisconnectNamespace(Ps){const{chainNamespace:Hs,closeModal:Ws}=Ps||{};ChainController.resetAccount(Hs),ChainController.resetNetwork(Hs),StorageUtil.removeConnectedNamespace(Hs);const Zs=Array.from(ChainController.state.chains.keys());(Hs?[Hs]:Zs).forEach(Ys=>StorageUtil.addDisconnectedConnectorId(ConnectorController.getConnectorId(Ys)||"",Ys)),ConnectorController.removeConnectorId(Hs),ProviderController.resetChain(Hs),this.setUser(null,Hs),this.setStatus("disconnected",Hs),this.setConnectedWalletInfo(null,Hs),Ws!==!1&&ModalController.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(Ps=>{const Hs=this.getAdapter(Ps),Ws=this.getCaipAddress(Ps),Zs=this.getCaipNetwork(Ps);return Hs?.syncConnections({connectToFirstConnector:!Ws,caipNetwork:Zs})}))}async syncAdapterConnection(Ps){const Hs=this.getAdapter(Ps),Ws=this.getCaipNetwork(Ps),Zs=ConnectorController.getConnectorId(Ps),Ys=ConnectorController.getConnectors(Ps).find(Va=>Va.id===Zs);try{if(!Hs||!Ys)throw new Error(`Adapter or connector not found for namespace ${Ps}`);if(!Ws?.id)throw new Error("CaipNetwork not found");const Va=await Hs?.syncConnection({namespace:Ps,id:Ys.id,chainId:Ws.id,rpcUrl:Ws?.rpcUrls?.default?.http?.[0]});Va?(this.syncProvider({...Va,chainNamespace:Ps}),await this.syncAccount({...Va,chainNamespace:Ps}),this.setStatus("connected",Ps),EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:Va.address,properties:{method:"browser",name:Ys.info?.name||Ys.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:void 0}})):this.setStatus("disconnected",Ps)}catch{this.onDisconnectNamespace({chainNamespace:Ps,closeModal:!1})}}async syncWalletConnectAccount(){const Ps=Object.keys(this.universalProvider?.session?.namespaces||{}),Hs=this.chainNamespaces.map(async Ws=>{const Zs=this.getAdapter(Ws);if(!Zs)return;const zs=this.universalProvider?.session?.namespaces?.[Ws]?.accounts||[],Ys=ChainController.state.activeCaipNetwork?.id,Va=zs.find(Ma=>{const{chainId:qs}=ParseUtil.parseCaipAddress(Ma);return qs===Ys?.toString()})||zs[0];if(Va){const Ma=ParseUtil.validateCaipAddress(Va),{chainId:qs,address:Js}=ParseUtil.parseCaipAddress(Ma);if(ProviderController.setProviderId(Ws,ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&ChainController.state.activeCaipNetwork&&Zs.namespace!==ConstantsUtil$3.CHAIN.EVM){const Mc=Zs.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:ChainController.state.activeCaipNetwork});ProviderController.setProvider(Ws,Mc)}else ProviderController.setProvider(Ws,this.universalProvider);ConnectorController.setConnectorId(ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT,Ws),StorageUtil.addConnectedNamespace(Ws),await this.syncAccount({address:Js,chainId:qs,chainNamespace:Ws})}else Ps.includes(Ws)&&this.setStatus("disconnected",Ws);const Xs=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(Ws),ChainController.setApprovedCaipNetworksData(Ws,{approvedCaipNetworkIds:Xs.approvedCaipNetworkIds,supportsAllNetworks:Xs.supportsAllNetworks})});await Promise.all(Hs)}syncProvider({type:Ps,provider:Hs,id:Ws,chainNamespace:Zs}){ProviderController.setProviderId(Zs,Ps),ProviderController.setProvider(Zs,Hs),ConnectorController.setConnectorId(Ws,Zs)}async syncAccount(Ps){const Hs=Ps.chainNamespace===ChainController.state.activeChain,Ws=ChainController.getCaipNetworkByNamespace(Ps.chainNamespace,Ps.chainId),{address:Zs,chainId:zs,chainNamespace:Ys}=Ps,{chainId:Va}=StorageUtil.getActiveNetworkProps(),Xs=Ws?.id||Va,Ma=ChainController.state.activeCaipNetwork?.name===ConstantsUtil$3.UNSUPPORTED_NETWORK_NAME,qs=ChainController.getNetworkProp("supportsAllNetworks",Ys);if(this.setStatus("connected",Ys),!(Ma&&!qs)&&Xs){let Js=this.getCaipNetworks().find(Dc=>Dc.id.toString()===Xs.toString()),Mc=this.getCaipNetworks().find(Dc=>Dc.chainNamespace===Ys);if(!qs&&!Js&&!Mc){const Dc=this.getApprovedCaipNetworkIds()||[],sl=Dc.find(hl=>ParseUtil.parseCaipNetworkId(hl)?.chainId===Xs.toString()),ll=Dc.find(hl=>ParseUtil.parseCaipNetworkId(hl)?.chainNamespace===Ys);Js=this.getCaipNetworks().find(hl=>hl.caipNetworkId===sl),Mc=this.getCaipNetworks().find(hl=>hl.caipNetworkId===ll||"deprecatedCaipNetworkId"in hl&&hl.deprecatedCaipNetworkId===ll)}const ol=Js||Mc;ol?.chainNamespace===ChainController.state.activeChain?OptionsController.state.enableNetworkSwitch&&!OptionsController.state.allowUnsupportedChain&&ChainController.state.activeCaipNetwork?.name===ConstantsUtil$3.UNSUPPORTED_NETWORK_NAME?ChainController.showUnsupportedChainUI():this.setCaipNetwork(ol):Hs||Ws&&this.setCaipNetworkOfNamespace(Ws,Ys),this.syncConnectedWalletInfo(Ys);const Vc=this.getAddress(Ys);HelpersUtil$1.isLowerCaseMatch(Zs,Vc)||this.syncAccountInfo(Zs,ol?.id,Ys),Hs?await this.syncBalance({address:Zs,chainId:ol?.id,chainNamespace:Ys}):await this.syncBalance({address:Zs,chainId:Ws?.id,chainNamespace:Ys}),this.syncIdentity({address:Zs,chainId:zs,chainNamespace:Ys})}}async syncAccountInfo(Ps,Hs,Ws){const Zs=this.getCaipAddress(Ws),zs=Hs||Zs?.split(":")[1];if(!zs)return;const Ys=`${Ws}:${zs}:${Ps}`;this.setCaipAddress(Ys,Ws,!0),await this.syncIdentity({address:Ps,chainId:zs,chainNamespace:Ws})}async syncReownName(Ps,Hs){try{const Ws=await this.getReownName(Ps);if(Ws[0]){const Zs=Ws[0];this.setProfileName(Zs.name,Hs)}else this.setProfileName(null,Hs)}catch{this.setProfileName(null,Hs)}}syncConnectedWalletInfo(Ps){const Hs=ConnectorController.getConnectorId(Ps),Ws=ProviderController.getProviderId(Ps);if(Ws===ConstantsUtil$1.CONNECTOR_TYPE_ANNOUNCED||Ws===ConstantsUtil$1.CONNECTOR_TYPE_INJECTED){if(Hs){const zs=this.getConnectors().find(Ys=>{const Va=Ys.id===Hs,Xs=Ys.info?.rdns===Hs,Ma=Ys.connectors?.some(qs=>qs.id===Hs||qs.info?.rdns===Hs);return Va||Xs||!!Ma});if(zs){const{info:Ys,name:Va,imageUrl:Xs}=zs,Ma=Xs||this.getConnectorImage(zs);this.setConnectedWalletInfo({name:Va,icon:Ma,...Ys},Ps)}}}else if(Ws===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT){const Zs=ProviderController.getProvider(Ps);Zs?.session&&this.setConnectedWalletInfo({...Zs.session.peer.metadata,name:Zs.session.peer.metadata.name,icon:Zs.session.peer.metadata.icons?.[0]},Ps)}else if(Hs&&(Hs===ConstantsUtil$3.CONNECTOR_ID.COINBASE_SDK||Hs===ConstantsUtil$3.CONNECTOR_ID.COINBASE)){const Zs=this.getConnectors().find(Xs=>Xs.id===Hs),zs=Zs?.name||"Coinbase Wallet",Ys=Zs?.imageUrl||this.getConnectorImage(Zs),Va=Zs?.info;this.setConnectedWalletInfo({...Va,name:zs,icon:Ys},Ps)}}async syncBalance(Ps){!NetworkUtil$1.getNetworksByNamespace(this.getCaipNetworks(),Ps.chainNamespace).find(Ws=>Ws.id.toString()===Ps.chainId?.toString())||!Ps.chainId||await this.updateNativeBalance(Ps.address,Ps.chainId,Ps.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(Ps,Hs,Ws){const Zs=this.getAdapter(Ws),zs=ChainController.getCaipNetworkByNamespace(Ws,Hs);if(Zs){const Ys=await Zs.getBalance({address:Ps,chainId:Hs,caipNetwork:zs,tokens:this.options.tokens});return this.setBalance(Ys.balance,Ys.symbol,Ws),Ys}}async initializeUniversalAdapter(){const Ps=LoggerUtil.createLogger((Ws,...Zs)=>{Ws&&this.handleAlertError(Ws),console.error(...Zs)}),Hs={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:Ps};OptionsController.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await N$4.init(Hs),OptionsController.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(Ps=>{WcHelpersUtil.listenWcProvider({universalProvider:this.universalProvider,namespace:Ps,onDisplayUri:Hs=>{ConnectionController.setUri(Hs)},onConnect:Hs=>{const{address:Ws}=CoreHelperUtil.getAccount(Hs[0]);ConnectionController.finalizeWcConnection(Ws)},onDisconnect:()=>{ChainController.state.noAdapters&&this.resetAccount(Ps),ConnectionController.resetWcConnection()},onChainChanged:Hs=>{const Ws=ChainController.state.activeChain,Zs=Ws&&ConnectorController.state.activeConnectorIds[Ws]===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;if(Ws===Ps&&(ChainController.state.noAdapters||Zs)){const zs=this.getCaipNetworks().find(Va=>Va.id.toString()===Hs.toString()||Va.caipNetworkId.toString()===Hs.toString()),Ys=this.getCaipNetwork();if(!zs){this.setUnsupportedNetwork(Hs);return}Ys?.id.toString()!==zs?.id.toString()&&Ys?.chainNamespace===zs?.chainNamespace&&this.setCaipNetwork(zs)}},onAccountsChanged:Hs=>{const Ws=ChainController.state.activeChain,Zs=Ws&&ConnectorController.state.activeConnectorIds[Ws]===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;if(Ws===Ps&&(ChainController.state.noAdapters||Zs)){const zs=Hs?.[0];zs&&this.syncAccount({address:zs.address,chainId:zs.chainId,chainNamespace:zs.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&CoreHelperUtil.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(Ps){EventsController.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:Ps instanceof Error?Ps.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",Ps)}return this.universalProvider}getDisabledCaipNetworks(){const Ps=ChainController.getAllApprovedCaipNetworkIds(),Hs=ChainController.getAllRequestedCaipNetworks();return CoreHelperUtil.sortRequestedNetworks(Ps,Hs).filter(Zs=>ChainController.isCaipNetworkDisabled(Zs))}handleAlertError(Ps){const Hs=Object.entries(ErrorUtil.UniversalProviderErrors).find(([,{message:Va}])=>Ps.message.includes(Va)),[Ws,Zs]=Hs??[],{message:zs,alertErrorKey:Ys}=Zs??{};if(Ws&&zs&&!this.reportedAlertErrors[Ws]){const Va=ErrorUtil.ALERT_ERRORS[Ys];Va&&(AlertController.open(Va,"error"),this.reportedAlertErrors[Ws]=!0)}}getAdapter(Ps){if(Ps)return this.chainAdapters?.[Ps]}createAdapter(Ps){if(!Ps)return;const Hs=Ps.namespace;if(!Hs)return;this.createClients();const Ws=Ps;Ws.namespace=Hs,Ws.construct({namespace:Hs,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:Zs})=>Zs===Hs)}),this.chainNamespaces.includes(Hs)||this.chainNamespaces.push(Hs),this.chainAdapters&&(this.chainAdapters[Hs]=Ws)}async open(Ps){await this.injectModalUi(),Ps?.uri&&ConnectionController.setUri(Ps.uri);const{isSwap:Hs,isSend:Ws}=this.toModalOptions();return Hs(Ps)?ModalController.open({...Ps,data:{swap:Ps.arguments}}):Ws(Ps)&&Ps.arguments?this.openSend(Ps.arguments):ModalController.open(Ps)}async close(){await this.injectModalUi(),ModalController.close()}setLoading(Ps,Hs){ModalController.setLoading(Ps,Hs)}async disconnect(Ps){await ConnectionController.disconnect({namespace:Ps})}getSIWX(){return OptionsController.state.siwx}getError(){return""}getChainId(){return ChainController.state.activeCaipNetwork?.id}async switchNetwork(Ps,{throwOnFailure:Hs=!1}={}){const Ws=this.getCaipNetworks().find(Zs=>Zs.id===Ps.id);if(!Ws){AlertController.open(ErrorUtil.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await ChainController.switchActiveNetwork(Ws,{throwOnFailure:Hs})}getWalletProvider(){return ChainController.state.activeChain?ProviderController.state.providers[ChainController.state.activeChain]:null}getWalletProviderType(){return ProviderController.getProviderId(ChainController.state.activeChain)}subscribeProviders(Ps){return ProviderController.subscribeProviders(Ps)}getThemeMode(){return ThemeController.state.themeMode}getThemeVariables(){return ThemeController.state.themeVariables}setThemeMode(Ps){ThemeController.setThemeMode(Ps),setColorTheme(ThemeController.state.themeMode)}setTermsConditionsUrl(Ps){OptionsController.setTermsConditionsUrl(Ps)}setPrivacyPolicyUrl(Ps){OptionsController.setPrivacyPolicyUrl(Ps)}setThemeVariables(Ps){ThemeController.setThemeVariables(Ps),setThemeVariables(ThemeController.state.themeVariables)}subscribeTheme(Ps){return ThemeController.subscribe(Ps)}subscribeConnections(Ps){return this.remoteFeatures.multiWallet?ConnectionController.subscribe(Ps):(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(Ps){return Ps?ChainController.state.chains.get(Ps)?.accountState?.connectedWalletInfo:ChainController.getAccountData()?.connectedWalletInfo}getAccount(Ps){const Hs=Ps||ChainController.state.activeChain,Ws=ConnectorController.getAuthConnector(Hs),Zs=ChainController.getAccountData(Hs),zs=StorageUtil.getConnectedConnectorId(ChainController.state.activeChain),Ys=ConnectionController.getConnections(Hs);if(!Hs)throw new Error("AppKit:getAccount - namespace is required");const Va=Ys.flatMap(Xs=>Xs.accounts.map(({address:Ma,type:qs,publicKey:Js})=>CoreHelperUtil.createAccount(Hs,Ma,qs||"eoa",Js)));if(Zs)return{allAccounts:Va,caipAddress:Zs.caipAddress,address:CoreHelperUtil.getPlainAddress(Zs.caipAddress),isConnected:!!Zs.caipAddress,status:Zs.status,embeddedWalletInfo:Ws&&zs===ConstantsUtil$3.CONNECTOR_ID.AUTH?{user:Zs.user?{...Zs.user,username:StorageUtil.getConnectedSocialUsername()}:void 0,authProvider:Zs.socialProvider||"email",accountType:getPreferredAccountType(Hs),isSmartAccountDeployed:!!Zs.smartAccountDeployed}:void 0}}subscribeAccount(Ps,Hs){const Ws=()=>{const Zs=this.getAccount(Hs);Zs&&Ps(Zs)};Hs?ChainController.subscribeChainProp("accountState",Ws,Hs):ChainController.subscribe(Ws),ConnectorController.subscribe(Ws)}subscribeNetwork(Ps){return ChainController.subscribe(({activeCaipNetwork:Hs})=>{Ps({caipNetwork:Hs,chainId:Hs?.id,caipNetworkId:Hs?.caipNetworkId})})}subscribeWalletInfo(Ps,Hs){return Hs?ChainController.subscribeChainProp("accountState",Ws=>Ps(Ws?.connectedWalletInfo),Hs):ChainController.subscribeChainProp("accountState",Ws=>Ps(Ws?.connectedWalletInfo))}subscribeShouldUpdateToAddress(Ps){ChainController.subscribeChainProp("accountState",Hs=>Ps(Hs?.shouldUpdateToAddress))}subscribeCaipNetworkChange(Ps){ChainController.subscribeKey("activeCaipNetwork",Ps)}getState(){return PublicStateController.state}getRemoteFeatures(){return OptionsController.state.remoteFeatures}subscribeState(Ps){return PublicStateController.subscribe(Ps)}subscribeRemoteFeatures(Ps){return OptionsController.subscribeKey("remoteFeatures",Ps)}showErrorMessage(Ps){SnackController.showError(Ps)}showSuccessMessage(Ps){SnackController.showSuccess(Ps)}getEvent(){return{...EventsController.state}}subscribeEvents(Ps){return EventsController.subscribe(Ps)}replace(Ps){RouterController.replace(Ps)}redirect(Ps){RouterController.push(Ps)}popTransactionStack(Ps){RouterController.popTransactionStack(Ps)}isOpen(){return ModalController.state.open}isTransactionStackEmpty(){return RouterController.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(Ps){OptionsController.setFeatures(Ps)}updateRemoteFeatures(Ps){OptionsController.setRemoteFeatures(Ps)}updateOptions(Ps){const Ws={...OptionsController.state||{},...Ps};OptionsController.setOptions(Ws)}setConnectMethodsOrder(Ps){OptionsController.setConnectMethodsOrder(Ps)}setWalletFeaturesOrder(Ps){OptionsController.setWalletFeaturesOrder(Ps)}setCollapseWallets(Ps){OptionsController.setCollapseWallets(Ps)}setSocialsOrder(Ps){OptionsController.setSocialsOrder(Ps)}getConnectMethodsOrder(){return WalletUtil.getConnectOrderMethod(OptionsController.state.features,ConnectorController.getConnectors())}addNetwork(Ps,Hs){if(this.chainAdapters&&!this.chainAdapters[Ps])throw new Error(`Adapter for namespace ${Ps} doesn't exist`);const Ws=this.extendCaipNetwork(Hs,this.options);this.getCaipNetworks().find(Zs=>Zs.id===Ws.id)||ChainController.addNetwork(Ws)}removeNetwork(Ps,Hs){if(this.chainAdapters&&!this.chainAdapters[Ps])throw new Error(`Adapter for namespace ${Ps} doesn't exist`);this.getCaipNetworks().find(Zs=>Zs.id===Hs)&&ChainController.removeNetwork(Ps,Hs)}}let isInitialized=!1;class AppKit extends AppKitBaseClient{async onAuthProviderConnected(Ps){const Hs=HelpersUtil$1.userChainIdToChainNamespace(Ps?.chainId);if(Ps.message&&Ps.signature&&Ps.siwxMessage&&await SIWXUtil.addEmbeddedWalletSession({chainId:Ps.siwxMessage.chainId,accountAddress:Ps.address,notBefore:Ps.siwxMessage.notBefore,statement:Ps.siwxMessage.statement,resources:Ps.siwxMessage.resources,requestId:Ps.siwxMessage.requestId,issuedAt:Ps.siwxMessage.issuedAt,domain:Ps.siwxMessage.domain,uri:Ps.siwxMessage.uri,version:Ps.siwxMessage.version,nonce:Ps.siwxMessage.nonce},Ps.message,Ps.signature),!Hs)throw new Error("AppKit:onAuthProviderConnected - namespace is required");const Ws=Hs===ConstantsUtil$3.CHAIN.EVM?`eip155:${Ps.chainId}:${Ps.address}`:`${Ps.chainId}:${Ps.address}`,Zs=OptionsController.state.defaultAccountTypes[Hs],zs=getPreferredAccountType(Hs),Ys=Ps.preferredAccountType||zs||Zs;this.setCaipAddress(Ws,Hs);const{signature:Va,siwxMessage:Xs,message:Ma,...qs}=Ps,Js=ChainController.getAccountData(Hs);this.setUser({...Js?.user||{},...qs},Hs),this.setSmartAccountDeployed(!!Ps.smartAccountDeployed,Hs),this.setPreferredAccountType(Ys,Hs),await Promise.all([this.syncAuthConnectorTheme(this.authProvider),this.syncAccount({address:Ps.address,chainId:Ps.chainId,chainNamespace:Hs})]),this.setLoading(!1,Hs)}setupAuthConnectorListeners(Ps){Ps.onRpcRequest(Hs=>{W3mFrameHelpers.checkIfRequestExists(Hs)?W3mFrameHelpers.checkIfRequestIsSafe(Hs)||this.handleUnsafeRPCRequest():(this.open(),console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE,{method:Hs.method}),setTimeout(()=>{this.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE)},300),Ps.rejectRpcRequests())}),Ps.onRpcError(()=>{this.isOpen()&&(this.isTransactionStackEmpty()?this.close():this.popTransactionStack("error"))}),Ps.onRpcSuccess((Hs,Ws)=>{const Zs=W3mFrameHelpers.checkIfRequestIsSafe(Ws),zs=this.getAddress(),Ys=ChainController.state.activeCaipNetwork;Zs||(zs&&Ys?.id&&this.updateNativeBalance(zs,Ys.id,Ys.chainNamespace),this.isTransactionStackEmpty()?this.close():this.popTransactionStack("success"))}),Ps.onNotConnected(()=>{const Hs=ChainController.state.activeChain;if(!Hs)throw new Error("AppKit:onNotConnected - namespace is required");ConnectorController.getConnectorId(Hs)===ConstantsUtil$3.CONNECTOR_ID.AUTH&&(this.setCaipAddress(null,Hs),this.setLoading(!1,Hs))}),Ps.onConnect(this.onAuthProviderConnected.bind(this)),Ps.onSocialConnected(this.onAuthProviderConnected.bind(this)),Ps.onSetPreferredAccount(({address:Hs,type:Ws})=>{const Zs=ChainController.state.activeChain;if(!Zs)throw new Error("AppKit:onSetPreferredAccount - namespace is required");Hs&&this.setPreferredAccountType(Ws,Zs)})}async syncAuthConnectorTheme(Ps){if(!Ps)return;const Hs=ThemeController.getSnapshot();await Ps.syncTheme({themeMode:Hs.themeMode,themeVariables:Hs.themeVariables,w3mThemeVariables:getW3mThemeVariables(Hs.themeVariables,Hs.themeMode)})}async syncAuthConnector(Ps,Hs){const Ws=ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Hs),Zs=Hs===ChainController.state.activeChain;if(!Ws)return;this.setLoading(!0,Hs);const zs=Ps.getLoginEmailUsed();this.setLoading(zs,Hs),zs&&this.setStatus("connecting",Hs);const Ys=Ps.getEmail(),Va=Ps.getUsername(),Xs=ChainController.getAccountData(Hs)?.user||{};this.setUser({...Xs,username:Va,email:Ys},Hs),this.setupAuthConnectorListeners(Ps);const{isConnected:Ma}=await Ps.isConnected();if(Hs&&Ws&&Zs)if(Ma&&this.connectionControllerClient?.connectExternal){await Ps.init(),await this.syncAuthConnectorTheme(Ps),await this.connectionControllerClient?.connectExternal({id:ConstantsUtil$3.CONNECTOR_ID.AUTH,info:{name:ConstantsUtil$3.CONNECTOR_ID.AUTH},type:ConstantsUtil$1.CONNECTOR_TYPE_AUTH,provider:Ps,chainId:ChainController.getNetworkData(Hs)?.caipNetwork?.id,chain:Hs}),this.setStatus("connected",Hs);const qs=StorageUtil.getConnectedSocialProvider();qs?EventsController.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",address:this.getAddress(),properties:{provider:qs,reconnect:!0}}):EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:this.getAddress(),properties:{method:"email",name:this.universalProvider?.session?.peer?.metadata?.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:void 0}})}else ConnectorController.getConnectorId(Hs)===ConstantsUtil$3.CONNECTOR_ID.AUTH&&(this.setStatus("disconnected",Hs),StorageUtil.removeConnectedNamespace(Hs));this.setLoading(!1,Hs)}async checkExistingTelegramSocialConnection(Ps){try{if(!CoreHelperUtil.isTelegram())return;const Hs=StorageUtil.getTelegramSocialProvider();if(!Hs||!CoreHelperUtil.isClient())return;const Zs=new URL(window.location.href).searchParams.get("result_uri");if(!Zs)return;Hs&&ChainController.setAccountProp("socialProvider",Hs,Ps),await this.authProvider?.init();const zs=ConnectorController.getAuthConnector();Hs&&zs&&(this.setLoading(!0,Ps),await ConnectionController.connectExternal({id:zs.id,type:zs.type,socialUri:Zs},zs.chain),StorageUtil.setConnectedSocialProvider(Hs),StorageUtil.removeTelegramSocialProvider(),EventsController.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:Hs}}))}catch(Hs){this.setLoading(!1,Ps),console.error("checkExistingSTelegramocialConnection error",Hs)}try{const Hs=new URL(window.location.href);Hs.searchParams.delete("result_uri"),window.history.replaceState({},document.title,Hs.toString())}catch(Hs){console.error("tma social login failed",Hs)}}createAuthProvider(Ps){if(!ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Ps))return;const Ws=this.remoteFeatures?.email,Zs=Array.isArray(this.remoteFeatures?.socials)&&this.remoteFeatures.socials.length>0,zs=Ws||Zs,Va=HelpersUtil$1.getActiveNamespaceConnectedToAuth()||Ps;!this.authProvider&&this.options?.projectId&&zs&&(this.authProvider=W3mFrameProviderSingleton.getInstance({projectId:this.options.projectId,enableLogger:this.options.enableAuthLogger,chainId:this.getCaipNetwork(Va)?.caipNetworkId,abortController:ErrorUtil.EmbeddedWalletAbortController,onTimeout:Ma=>{Ma==="iframe_load_failed"?AlertController.open(ErrorUtil.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):Ma==="iframe_request_timeout"?AlertController.open(ErrorUtil.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):Ma==="unverified_domain"&&AlertController.open(ErrorUtil.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},getActiveCaipNetwork:Ma=>getActiveCaipNetwork(Ma),getCaipNetworks:Ma=>ChainController.getCaipNetworks(Ma)}),PublicStateController.subscribeOpen(Ma=>{!Ma&&this.isTransactionStackEmpty()&&this.authProvider?.rejectRpcRequests()}));const Xs=Ps===ChainController.state.activeChain&&OptionsController.state.enableReconnect;OptionsController.state.enableReconnect===!1?this.syncAuthConnectorTheme(this.authProvider):this.authProvider&&Xs&&(this.syncAuthConnector(this.authProvider,Ps),this.checkExistingTelegramSocialConnection(Ps))}createAuthProviderForAdapter(Ps){this.createAuthProvider(Ps),this.authProvider&&this.chainAdapters?.[Ps]?.setAuthProvider?.(this.authProvider)}initControllers(Ps){super.initControllers(Ps),this.options.excludeWalletIds&&ApiController.initializeExcludedWallets({ids:this.options.excludeWalletIds})}async switchCaipNetwork(Ps){if(!Ps)return;const Hs=ChainController.state.activeChain,Ws=Ps.chainNamespace,Zs=this.getAddressByChainNamespace(Ws);if(Ws===Hs&&ChainController.getAccountData(Ws)?.caipAddress)await this.getAdapter(Ws)?.switchNetwork({caipNetwork:Ps}),this.setCaipNetwork(Ps);else{const Va=ProviderController.getProviderId(Hs)===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,Xs=ProviderController.getProviderId(Ws),Ma=Xs===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,qs=ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Ws);if(!Ws)throw new Error("AppKit:switchCaipNetwork - networkNamespace is required");if((Va&&Xs===void 0||Ma)&&qs)try{ChainController.state.activeChain=Ps.chainNamespace,Zs?await this.getAdapter(Ws)?.switchNetwork({caipNetwork:Ps}):await this.connectionControllerClient?.connectExternal?.({id:ConstantsUtil$3.CONNECTOR_ID.AUTH,provider:this.authProvider,chain:Ws,chainId:Ps.id,type:ConstantsUtil$1.CONNECTOR_TYPE_AUTH,caipNetwork:Ps}),this.setCaipNetwork(Ps)}catch{await this.getAdapter(Ws)?.switchNetwork({caipNetwork:Ps})}else Xs===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT?(ChainController.state.noAdapters||await this.getAdapter(Ws)?.switchNetwork({caipNetwork:Ps}),this.setCaipNetwork(Ps),this.syncWalletConnectAccount()):(this.setCaipNetwork(Ps),Zs&&this.syncAccount({address:Zs,chainId:Ps.id,chainNamespace:Ws}))}}async initialize(Ps){await super.initialize(Ps),this.chainNamespaces?.forEach(Hs=>{this.createAuthProviderForAdapter(Hs)}),await this.injectModalUi(),PublicStateController.set({initialized:!0})}async syncIdentity({address:Ps,chainId:Hs,chainNamespace:Ws}){const Zs=`${Ws}:${Hs}`;if(this.caipNetworks?.find(Va=>Va.caipNetworkId===Zs)?.testnet){this.setProfileName(null,Ws),this.setProfileImage(null,Ws);return}const Ys=ConnectorController.getConnectorId(Ws)===ConstantsUtil$3.CONNECTOR_ID.AUTH;try{const{name:Va,avatar:Xs}=await this.fetchIdentity({address:Ps});!Va&&Ys?await this.syncReownName(Ps,Ws):(this.setProfileName(Va,Ws),this.setProfileImage(Xs,Ws))}catch{Hs!==1&&this.setProfileImage(null,Ws)}}syncConnectedWalletInfo(Ps){const Hs=ProviderController.getProviderId(Ps);if(Hs===ConstantsUtil$1.CONNECTOR_TYPE_AUTH){const Ws=this.authProvider;if(Ws){const Zs=StorageUtil.getConnectedSocialProvider()??"email",zs=Ws.getEmail()??Ws.getUsername();this.setConnectedWalletInfo({name:Hs,identifier:zs,social:Zs},Ps)}}else super.syncConnectedWalletInfo(Ps)}async injectModalUi(){if(CoreHelperUtil.isClient()&&!isInitialized)try{const Ps={...ConstantsUtil$2.DEFAULT_FEATURES,...this.options.features},Hs=this.remoteFeatures;if(await this.loadModalComponents(Ps,Hs),CoreHelperUtil.isClient()&&!document.querySelector("w3m-modal")){const Zs=document.createElement("w3m-modal");!OptionsController.state.disableAppend&&!OptionsController.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",Zs)}isInitialized=!0}catch(Ps){console.error("Error injecting modal UI:",Ps)}}async loadModalComponents(Ps,Hs){if(!CoreHelperUtil.isClient())return;const Ws=[];(Hs.email||Hs.socials&&Hs.socials.length>0)&&Ws.push(Promise.resolve().then(()=>embeddedWallet)),Hs.email&&Ws.push(Promise.resolve().then(()=>email)),Hs.socials&&Ws.push(Promise.resolve().then(()=>socials)),Hs.swaps&&Hs.swaps.length>0&&Ws.push(Promise.resolve().then(()=>swaps)),Ps.send&&Ws.push(Promise.resolve().then(()=>send)),Ps.receive&&Ws.push(Promise.resolve().then(()=>receive)),Hs.onramp&&Hs.onramp.length>0&&Ws.push(Promise.resolve().then(()=>onramp)),Hs.payWithExchange&&Ws.push(Promise.resolve().then(()=>payWithExchange)),Hs.activity&&Ws.push(Promise.resolve().then(()=>transactions)),(Ps.pay||Hs.payments)&&Ws.push(Promise.resolve().then(()=>index$2)),Hs.emailCapture&&Ws.push(Promise.resolve().then(()=>dataCapture)),await Promise.all([...Ws,Promise.resolve().then(()=>index$1),Promise.resolve().then(()=>w3mModal)])}}const PACKAGE_VERSION="1.8.9";function createAppKit(Fs){return new AppKit({...Fs,sdkVersion:CoreHelperUtil.generateSdkVersion(Fs.adapters??[],"html",PACKAGE_VERSION)})}var HederaChainId;(function(Fs){Fs.Mainnet="hedera:mainnet",Fs.Testnet="hedera:testnet",Fs.Previewnet="hedera:previewnet",Fs.Devnet="hedera:devnet"})(HederaChainId||(HederaChainId={}));var HederaSessionEvent;(function(Fs){Fs.AccountsChanged="accountsChanged",Fs.ChainChanged="chainChanged"})(HederaSessionEvent||(HederaSessionEvent={}));var HederaJsonRpcMethod;(function(Fs){Fs.GetNodeAddresses="hedera_getNodeAddresses",Fs.ExecuteTransaction="hedera_executeTransaction",Fs.SignMessage="hedera_signMessage",Fs.SignAndExecuteQuery="hedera_signAndExecuteQuery",Fs.SignAndExecuteTransaction="hedera_signAndExecuteTransaction",Fs.SignTransaction="hedera_signTransaction"})(HederaJsonRpcMethod||(HederaJsonRpcMethod={}));function transactionToBase64String(Fs){const Ps=Fs.toBytes();return Buffer$1.from(Ps).toString("base64")}function transactionToTransactionBody(Fs,Ps=null){return Fs._makeTransactionBody(Ps)}function transactionBodyToBase64String(Fs){return Uint8ArrayToBase64String(libExports.proto.TransactionBody.encode(Fs).finish())}function base64StringToSignatureMap(Fs){const Ps=Buffer$1.from(Fs,"base64");return libExports.proto.SignatureMap.decode(Ps)}function Uint8ArrayToBase64String(Fs){return Buffer$1.from(Fs).toString("base64")}function Uint8ArrayToString(Fs){return Buffer$1.from(Fs).toString("utf-8")}function base64StringToUint8Array(Fs){const Ps=Buffer$1.from(Fs,"base64");return new Uint8Array(Ps)}function queryToBase64String(Fs){const Ps=Fs.toBytes();return Buffer$1.from(Ps).toString("base64")}function prefixMessageToSign(Fs){return`Hedera Signed Message:
464
464
  `+Fs.length+Fs}function verifyMessageSignature(Fs,Ps,Hs){const Ws=base64StringToSignatureMap(Ps),Zs=Ws.sigPair[0].ed25519||Ws.sigPair[0].ECDSASecp256k1;if(!Zs)throw new Error("Signature not found in signature map");return Hs.verify(Buffer$1.from(prefixMessageToSign(Fs)),Zs)}const LEDGER_ID_MAPPINGS=[[r$y.MAINNET,295,"hedera:mainnet"],[r$y.TESTNET,296,"hedera:testnet"],[r$y.PREVIEWNET,297,"hedera:previewnet"],[r$y.LOCAL_NODE,298,"hedera:devnet"]],DEFAULT_LEDGER_ID=r$y.LOCAL_NODE,DEFAULT_CAIP=LEDGER_ID_MAPPINGS[3][2];function CAIPChainIdToLedgerId(Fs){for(let Ps=0;Ps<LEDGER_ID_MAPPINGS.length;Ps++){const[Hs,Ws,Zs]=LEDGER_ID_MAPPINGS[Ps];if(Fs===Zs)return Hs}return DEFAULT_LEDGER_ID}function ledgerIdToCAIPChainId(Fs){for(let Ps=0;Ps<LEDGER_ID_MAPPINGS.length;Ps++){const[Hs,Ws,Zs]=LEDGER_ID_MAPPINGS[Ps];if(Fs.toString()===Hs.toString())return Zs}return DEFAULT_CAIP}const networkNamespaces=(Fs,Ps,Hs)=>({hedera:{chains:[ledgerIdToCAIPChainId(Fs)],methods:Ps,events:Hs}}),accountAndLedgerFromSession=Fs=>{const Ps=Fs.namespaces.hedera;if(!Ps)throw new Error("No hedera namespace found");return Ps.accounts.map(Hs=>{const[Ws,Zs,zs]=Hs.split(":");return{network:CAIPChainIdToLedgerId(Ws+":"+Zs),account:y$f.fromString(zs)}})};var EVENTS;(function(Fs){Fs.extensionQuery="hedera-extension-query",Fs.extensionConnect="hedera-extension-connect-",Fs.extensionOpen="hedera-extension-open-",Fs.extensionResponse="hedera-extension-response",Fs.iframeQuery="hedera-iframe-query",Fs.iframeQueryResponse="hedera-iframe-response",Fs.iframeConnect="hedera-iframe-connect"})(EVENTS||(EVENTS={}));const findExtensions=Fs=>{typeof window>"u"||(window.addEventListener("message",Ps=>{var Hs,Ws;((Hs=Ps?.data)===null||Hs===void 0?void 0:Hs.type)==EVENTS.extensionResponse&&Ps.data.metadata&&Fs(Ps.data.metadata,!1),((Ws=Ps?.data)===null||Ws===void 0?void 0:Ws.type)==EVENTS.iframeQueryResponse&&Ps.data.metadata&&Fs(Ps.data.metadata,!0)}),setTimeout(()=>{extensionQuery()},200))},extensionQuery=()=>{window.postMessage({type:EVENTS.extensionQuery},"*"),window.parent&&window.parent.postMessage({type:EVENTS.iframeQuery},"*")},extensionConnect=(Fs,Ps,Hs)=>{if(Ps){window.parent.postMessage({type:EVENTS.iframeConnect,pairingString:Hs},"*");return}window.postMessage({type:EVENTS.extensionConnect+Fs,pairingString:Hs},"*")},extensionOpen=Fs=>{window.postMessage({type:EVENTS.extensionOpen+Fs},"*")};var l$g={exports:{}},h$c=typeof Reflect=="object"?Reflect:null,y$6=h$c&&typeof h$c.apply=="function"?h$c.apply:function(Fs,Ps,Hs){return Function.prototype.apply.call(Fs,Ps,Hs)},f$k;h$c&&typeof h$c.ownKeys=="function"?f$k=h$c.ownKeys:Object.getOwnPropertySymbols?f$k=function(Fs){return Object.getOwnPropertyNames(Fs).concat(Object.getOwnPropertySymbols(Fs))}:f$k=function(Fs){return Object.getOwnPropertyNames(Fs)};function K$1(Fs){console&&console.warn&&console.warn(Fs)}var w$d=Number.isNaN||function(Fs){return Fs!==Fs};function o$v(){o$v.init.call(this)}l$g.exports=o$v,l$g.exports.once=F$1,o$v.EventEmitter=o$v,o$v.prototype._events=void 0,o$v.prototype._eventsCount=0,o$v.prototype._maxListeners=void 0;var L$2=10;function g$h(Fs){if(typeof Fs!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof Fs)}Object.defineProperty(o$v,"defaultMaxListeners",{enumerable:!0,get:function(){return L$2},set:function(Fs){if(typeof Fs!="number"||Fs<0||w$d(Fs))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+Fs+".");L$2=Fs}}),o$v.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o$v.prototype.setMaxListeners=function(Fs){if(typeof Fs!="number"||Fs<0||w$d(Fs))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+Fs+".");return this._maxListeners=Fs,this};function S$4(Fs){return Fs._maxListeners===void 0?o$v.defaultMaxListeners:Fs._maxListeners}o$v.prototype.getMaxListeners=function(){return S$4(this)},o$v.prototype.emit=function(Fs){for(var Ps=[],Hs=1;Hs<arguments.length;Hs++)Ps.push(arguments[Hs]);var Ws=Fs==="error",Zs=this._events;if(Zs!==void 0)Ws=Ws&&Zs.error===void 0;else if(!Ws)return!1;if(Ws){var zs;if(Ps.length>0&&(zs=Ps[0]),zs instanceof Error)throw zs;var Ys=new Error("Unhandled error."+(zs?" ("+zs.message+")":""));throw Ys.context=zs,Ys}var Va=Zs[Fs];if(Va===void 0)return!1;if(typeof Va=="function")y$6(Va,this,Ps);else for(var Xs=Va.length,Ma=b$5(Va,Xs),Hs=0;Hs<Xs;++Hs)y$6(Ma[Hs],this,Ps);return!0};function _$2(Fs,Ps,Hs,Ws){var Zs,zs,Ys;if(g$h(Hs),zs=Fs._events,zs===void 0?(zs=Fs._events=Object.create(null),Fs._eventsCount=0):(zs.newListener!==void 0&&(Fs.emit("newListener",Ps,Hs.listener?Hs.listener:Hs),zs=Fs._events),Ys=zs[Ps]),Ys===void 0)Ys=zs[Ps]=Hs,++Fs._eventsCount;else if(typeof Ys=="function"?Ys=zs[Ps]=Ws?[Hs,Ys]:[Ys,Hs]:Ws?Ys.unshift(Hs):Ys.push(Hs),Zs=S$4(Fs),Zs>0&&Ys.length>Zs&&!Ys.warned){Ys.warned=!0;var Va=new Error("Possible EventEmitter memory leak detected. "+Ys.length+" "+String(Ps)+" listeners added. Use emitter.setMaxListeners() to increase limit");Va.name="MaxListenersExceededWarning",Va.emitter=Fs,Va.type=Ps,Va.count=Ys.length,K$1(Va)}return Fs}o$v.prototype.addListener=function(Fs,Ps){return _$2(this,Fs,Ps,!1)},o$v.prototype.on=o$v.prototype.addListener,o$v.prototype.prependListener=function(Fs,Ps){return _$2(this,Fs,Ps,!0)};function k$2(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function C$1(Fs,Ps,Hs){var Ws={fired:!1,wrapFn:void 0,target:Fs,type:Ps,listener:Hs},Zs=k$2.bind(Ws);return Zs.listener=Hs,Ws.wrapFn=Zs,Zs}o$v.prototype.once=function(Fs,Ps){return g$h(Ps),this.on(Fs,C$1(this,Fs,Ps)),this},o$v.prototype.prependOnceListener=function(Fs,Ps){return g$h(Ps),this.prependListener(Fs,C$1(this,Fs,Ps)),this},o$v.prototype.removeListener=function(Fs,Ps){var Hs,Ws,Zs,zs,Ys;if(g$h(Ps),Ws=this._events,Ws===void 0)return this;if(Hs=Ws[Fs],Hs===void 0)return this;if(Hs===Ps||Hs.listener===Ps)--this._eventsCount===0?this._events=Object.create(null):(delete Ws[Fs],Ws.removeListener&&this.emit("removeListener",Fs,Hs.listener||Ps));else if(typeof Hs!="function"){for(Zs=-1,zs=Hs.length-1;zs>=0;zs--)if(Hs[zs]===Ps||Hs[zs].listener===Ps){Ys=Hs[zs].listener,Zs=zs;break}if(Zs<0)return this;Zs===0?Hs.shift():W$1(Hs,Zs),Hs.length===1&&(Ws[Fs]=Hs[0]),Ws.removeListener!==void 0&&this.emit("removeListener",Fs,Ys||Ps)}return this},o$v.prototype.off=o$v.prototype.removeListener,o$v.prototype.removeAllListeners=function(Fs){var Ps,Hs,Ws;if(Hs=this._events,Hs===void 0)return this;if(Hs.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):Hs[Fs]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete Hs[Fs]),this;if(arguments.length===0){var Zs=Object.keys(Hs),zs;for(Ws=0;Ws<Zs.length;++Ws)zs=Zs[Ws],zs!=="removeListener"&&this.removeAllListeners(zs);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(Ps=Hs[Fs],typeof Ps=="function")this.removeListener(Fs,Ps);else if(Ps!==void 0)for(Ws=Ps.length-1;Ws>=0;Ws--)this.removeListener(Fs,Ps[Ws]);return this};function E$3(Fs,Ps,Hs){var Ws=Fs._events;if(Ws===void 0)return[];var Zs=Ws[Ps];return Zs===void 0?[]:typeof Zs=="function"?Hs?[Zs.listener||Zs]:[Zs]:Hs?D$2(Zs):b$5(Zs,Zs.length)}o$v.prototype.listeners=function(Fs){return E$3(this,Fs,!0)},o$v.prototype.rawListeners=function(Fs){return E$3(this,Fs,!1)},o$v.listenerCount=function(Fs,Ps){return typeof Fs.listenerCount=="function"?Fs.listenerCount(Ps):O$3.call(Fs,Ps)},o$v.prototype.listenerCount=O$3;function O$3(Fs){var Ps=this._events;if(Ps!==void 0){var Hs=Ps[Fs];if(typeof Hs=="function")return 1;if(Hs!==void 0)return Hs.length}return 0}o$v.prototype.eventNames=function(){return this._eventsCount>0?f$k(this._events):[]};function b$5(Fs,Ps){for(var Hs=new Array(Ps),Ws=0;Ws<Ps;++Ws)Hs[Ws]=Fs[Ws];return Hs}function W$1(Fs,Ps){for(;Ps+1<Fs.length;Ps++)Fs[Ps]=Fs[Ps+1];Fs.pop()}function D$2(Fs){for(var Ps=new Array(Fs.length),Hs=0;Hs<Ps.length;++Hs)Ps[Hs]=Fs[Hs].listener||Fs[Hs];return Ps}function F$1(Fs,Ps){return new Promise(function(Hs,Ws){function Zs(Ys){Fs.removeListener(Ps,zs),Ws(Ys)}function zs(){typeof Fs.removeListener=="function"&&Fs.removeListener("error",Zs),Hs([].slice.call(arguments))}x$2(Fs,Ps,zs,{once:!0}),Ps!=="error"&&z$2(Fs,Zs,{once:!0})})}function z$2(Fs,Ps,Hs){typeof Fs.on=="function"&&x$2(Fs,"error",Ps,Hs)}function x$2(Fs,Ps,Hs,Ws){if(typeof Fs.on=="function")Ws.once?Fs.once(Ps,Hs):Fs.on(Ps,Hs);else if(typeof Fs.addEventListener=="function")Fs.addEventListener(Ps,function Zs(zs){Ws.once&&Fs.removeEventListener(Ps,Zs),Hs(zs)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof Fs)}const t$I=Symbol(),s$m=Object.getPrototypeOf,c$j=new WeakMap,l$f=Fs=>Fs&&(c$j.has(Fs)?c$j.get(Fs):s$m(Fs)===Object.prototype||s$m(Fs)===Array.prototype),y$5=Fs=>l$f(Fs)&&Fs[t$I]||null,h$b=(Fs,Ps=!0)=>{c$j.set(Fs,Ps)},__vite_import_meta_env__$1={},isObject$1=Fs=>typeof Fs=="object"&&Fs!==null,proxyStateMap$1=new WeakMap,refSet$1=new WeakSet,buildProxyFunction=(Fs=Object.is,Ps=(Ma,qs)=>new Proxy(Ma,qs),Hs=Ma=>isObject$1(Ma)&&!refSet$1.has(Ma)&&(Array.isArray(Ma)||!(Symbol.iterator in Ma))&&!(Ma instanceof WeakMap)&&!(Ma instanceof WeakSet)&&!(Ma instanceof Error)&&!(Ma instanceof Number)&&!(Ma instanceof Date)&&!(Ma instanceof String)&&!(Ma instanceof RegExp)&&!(Ma instanceof ArrayBuffer),Ws=Ma=>{switch(Ma.status){case"fulfilled":return Ma.value;case"rejected":throw Ma.reason;default:throw Ma}},Zs=new WeakMap,zs=(Ma,qs,Js=Ws)=>{const Mc=Zs.get(Ma);if(Mc?.[0]===qs)return Mc[1];const ol=Array.isArray(Ma)?[]:Object.create(Object.getPrototypeOf(Ma));return h$b(ol,!0),Zs.set(Ma,[qs,ol]),Reflect.ownKeys(Ma).forEach(Vc=>{if(Object.getOwnPropertyDescriptor(ol,Vc))return;const Dc=Reflect.get(Ma,Vc),sl={value:Dc,enumerable:!0,configurable:!0};if(refSet$1.has(Dc))h$b(Dc,!1);else if(Dc instanceof Promise)delete sl.value,sl.get=()=>Js(Dc);else if(proxyStateMap$1.has(Dc)){const[ll,hl]=proxyStateMap$1.get(Dc);sl.value=zs(ll,hl(),Js)}Object.defineProperty(ol,Vc,sl)}),Object.preventExtensions(ol)},Ys=new WeakMap,Va=[1,1],Xs=Ma=>{if(!isObject$1(Ma))throw new Error("object required");const qs=Ys.get(Ma);if(qs)return qs;let Js=Va[0];const Mc=new Set,ol=(vl,Sl=++Va[0])=>{Js!==Sl&&(Js=Sl,Mc.forEach(fl=>fl(vl,Sl)))};let Vc=Va[1];const Dc=(vl=++Va[1])=>(Vc!==vl&&!Mc.size&&(Vc=vl,ll.forEach(([Sl])=>{const fl=Sl[1](vl);fl>Js&&(Js=fl)})),Js),sl=vl=>(Sl,fl)=>{const Hc=[...Sl];Hc[1]=[vl,...Hc[1]],ol(Hc,fl)},ll=new Map,hl=(vl,Sl)=>{if((__vite_import_meta_env__$1?"production":void 0)!=="production"&&ll.has(vl))throw new Error("prop listener already exists");if(Mc.size){const fl=Sl[3](sl(vl));ll.set(vl,[Sl,fl])}else ll.set(vl,[Sl])},pl=vl=>{var Sl;const fl=ll.get(vl);fl&&(ll.delete(vl),(Sl=fl[1])==null||Sl.call(fl))},gl=vl=>(Mc.add(vl),Mc.size===1&&ll.forEach(([fl,Hc],tl)=>{if((__vite_import_meta_env__$1?"production":void 0)!=="production"&&Hc)throw new Error("remove already exists");const nl=fl[3](sl(tl));ll.set(tl,[fl,nl])}),()=>{Mc.delete(vl),Mc.size===0&&ll.forEach(([fl,Hc],tl)=>{Hc&&(Hc(),ll.set(tl,[fl]))})}),yl=Array.isArray(Ma)?[]:Object.create(Object.getPrototypeOf(Ma)),Il=Ps(yl,{deleteProperty(vl,Sl){const fl=Reflect.get(vl,Sl);pl(Sl);const Hc=Reflect.deleteProperty(vl,Sl);return Hc&&ol(["delete",[Sl],fl]),Hc},set(vl,Sl,fl,Hc){const tl=Reflect.has(vl,Sl),nl=Reflect.get(vl,Sl,Hc);if(tl&&(Fs(nl,fl)||Ys.has(fl)&&Fs(nl,Ys.get(fl))))return!0;pl(Sl),isObject$1(fl)&&(fl=y$5(fl)||fl);let rl=fl;if(fl instanceof Promise)fl.then(il=>{fl.status="fulfilled",fl.value=il,ol(["resolve",[Sl],il])}).catch(il=>{fl.status="rejected",fl.reason=il,ol(["reject",[Sl],il])});else{!proxyStateMap$1.has(fl)&&Hs(fl)&&(rl=Xs(fl));const il=!refSet$1.has(rl)&&proxyStateMap$1.get(rl);il&&hl(Sl,il)}return Reflect.set(vl,Sl,rl,Hc),ol(["set",[Sl],fl,nl]),!0}});Ys.set(Ma,Il);const $l=[yl,Dc,zs,gl];return proxyStateMap$1.set(Il,$l),Reflect.ownKeys(Ma).forEach(vl=>{const Sl=Object.getOwnPropertyDescriptor(Ma,vl);"value"in Sl&&(Il[vl]=Ma[vl],delete Sl.value,delete Sl.writable),Object.defineProperty(yl,vl,Sl)}),Il})=>[Xs,proxyStateMap$1,refSet$1,Fs,Ps,Hs,Ws,Zs,zs,Ys,Va],[defaultProxyFunction]=buildProxyFunction();function proxy$1(Fs={}){return defaultProxyFunction(Fs)}function subscribe$1(Fs,Ps,Hs){const Ws=proxyStateMap$1.get(Fs);(__vite_import_meta_env__$1?"production":void 0)!=="production"&&!Ws&&console.warn("Please use proxy object");let Zs;const zs=[],Ys=Ws[3];let Va=!1;const Ma=Ys(qs=>{zs.push(qs),Zs||(Zs=Promise.resolve().then(()=>{Zs=void 0,Va&&Ps(zs.splice(0))}))});return Va=!0,()=>{Va=!1,Ma()}}function snapshot(Fs,Ps){const Hs=proxyStateMap$1.get(Fs);(__vite_import_meta_env__$1?"production":void 0)!=="production"&&!Hs&&console.warn("Please use proxy object");const[Ws,Zs,zs]=Hs;return zs(Ws,Zs(),Ps)}const state$7=proxy$1({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),RouterCtrl={state:state$7,subscribe(Fs){return subscribe$1(state$7,()=>Fs(state$7))},push(Fs,Ps){Fs!==state$7.view&&(state$7.view=Fs,Ps&&(state$7.data=Ps),state$7.history.push(Fs))},reset(Fs){state$7.view=Fs,state$7.history=[Fs]},replace(Fs){state$7.history.length>1&&(state$7.history[state$7.history.length-1]=Fs,state$7.view=Fs)},goBack(){if(state$7.history.length>1){state$7.history.pop();const[Fs]=state$7.history.slice(-1);state$7.view=Fs}},setData(Fs){state$7.data=Fs}},CoreUtil={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return CoreUtil.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const Fs=navigator.userAgent.toLowerCase();return CoreUtil.isMobile()&&(Fs.includes("iphone")||Fs.includes("ipad"))},isHttpUrl(Fs){return Fs.startsWith("http://")||Fs.startsWith("https://")},isArray(Fs){return Array.isArray(Fs)&&Fs.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(Fs,Ps,Hs){if(CoreUtil.isHttpUrl(Fs))return this.formatUniversalUrl(Fs,Ps,Hs);let Ws=Fs;Ws.includes("://")||(Ws=Fs.replaceAll("/","").replaceAll(":",""),Ws=`${Ws}://`),Ws.endsWith("/")||(Ws=`${Ws}/`),this.setWalletConnectDeepLink(Ws,Hs);const Zs=encodeURIComponent(Ps);return`${Ws}wc?uri=${Zs}`},formatUniversalUrl(Fs,Ps,Hs){if(!CoreUtil.isHttpUrl(Fs))return this.formatNativeUrl(Fs,Ps,Hs);let Ws=Fs;if(Ws.startsWith("https://t.me")){const zs=Buffer.from(Ps).toString("base64").replace(/[=]/g,"");Ws.endsWith("/")&&(Ws=Ws.slice(0,-1)),this.setWalletConnectDeepLink(Ws,Hs);const Ys=new URL(Ws);return Ys.searchParams.set("startapp",zs),Ys.toString()}Ws.endsWith("/")||(Ws=`${Ws}/`),this.setWalletConnectDeepLink(Ws,Hs);const Zs=encodeURIComponent(Ps);return`${Ws}wc?uri=${Zs}`},async wait(Fs){return new Promise(Ps=>{setTimeout(Ps,Fs)})},openHref(Fs,Ps){const Hs=this.isTelegram()?"_blank":Ps;window.open(Fs,Hs,"noreferrer noopener")},setWalletConnectDeepLink(Fs,Ps){try{localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:Fs,name:Ps}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(Fs){try{const[Ps]=Fs.split("?");localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:Ps,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(CoreUtil.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var Fs;const Ps=(Fs=RouterCtrl.state.data)==null?void 0:Fs.Wallet;if(!Ps)throw new Error('Missing "Wallet" view data');return Ps}},isEnabled=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),state$6=proxy$1({enabled:isEnabled,userSessionId:"",events:[],connectedWalletId:void 0}),EventsCtrl={state:state$6,subscribe(Fs){return subscribe$1(state$6.events,()=>Fs(snapshot(state$6.events[state$6.events.length-1])))},initialize(){state$6.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(state$6.userSessionId=crypto.randomUUID())},setConnectedWalletId(Fs){state$6.connectedWalletId=Fs},click(Fs){if(state$6.enabled){const Ps={type:"CLICK",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}},track(Fs){if(state$6.enabled){const Ps={type:"TRACK",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}},view(Fs){if(state$6.enabled){const Ps={type:"VIEW",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}}},state$5=proxy$1({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),OptionsCtrl={state:state$5,subscribe(Fs){return subscribe$1(state$5,()=>Fs(state$5))},setChains(Fs){state$5.chains=Fs},setWalletConnectUri(Fs){state$5.walletConnectUri=Fs},setIsCustomDesktop(Fs){state$5.isCustomDesktop=Fs},setIsCustomMobile(Fs){state$5.isCustomMobile=Fs},setIsDataLoaded(Fs){state$5.isDataLoaded=Fs},setIsUiLoaded(Fs){state$5.isUiLoaded=Fs},setIsAuth(Fs){state$5.isAuth=Fs}},state$4=proxy$1({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),ConfigCtrl={state:state$4,subscribe(Fs){return subscribe$1(state$4,()=>Fs(state$4))},setConfig(Fs){var Ps,Hs;EventsCtrl.initialize(),OptionsCtrl.setChains(Fs.chains),OptionsCtrl.setIsAuth(!!Fs.enableAuthMode),OptionsCtrl.setIsCustomMobile(!!((Ps=Fs.mobileWallets)!=null&&Ps.length)),OptionsCtrl.setIsCustomDesktop(!!((Hs=Fs.desktopWallets)!=null&&Hs.length)),CoreUtil.setModalVersionInStorage(),Object.assign(state$4,Fs)}};var __defProp$2=Object.defineProperty,__getOwnPropSymbols$2=Object.getOwnPropertySymbols,__hasOwnProp$2=Object.prototype.hasOwnProperty,__propIsEnum$2=Object.prototype.propertyIsEnumerable,__defNormalProp$2=(Fs,Ps,Hs)=>Ps in Fs?__defProp$2(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Hs}):Fs[Ps]=Hs,__spreadValues$2=(Fs,Ps)=>{for(var Hs in Ps||(Ps={}))__hasOwnProp$2.call(Ps,Hs)&&__defNormalProp$2(Fs,Hs,Ps[Hs]);if(__getOwnPropSymbols$2)for(var Hs of __getOwnPropSymbols$2(Ps))__propIsEnum$2.call(Ps,Hs)&&__defNormalProp$2(Fs,Hs,Ps[Hs]);return Fs};const W3M_API="https://explorer-api.walletconnect.com",SDK_TYPE="wcm",SDK_VERSION="js-2.7.0";async function fetchListings(Fs,Ps){const Hs=__spreadValues$2({sdkType:SDK_TYPE,sdkVersion:SDK_VERSION},Ps),Ws=new URL(Fs,W3M_API);return Ws.searchParams.append("projectId",ConfigCtrl.state.projectId),Object.entries(Hs).forEach(([zs,Ys])=>{Ys&&Ws.searchParams.append(zs,String(Ys))}),(await fetch(Ws)).json()}const ExplorerUtil={async getDesktopListings(Fs){return fetchListings("/w3m/v1/getDesktopListings",Fs)},async getMobileListings(Fs){return fetchListings("/w3m/v1/getMobileListings",Fs)},async getInjectedListings(Fs){return fetchListings("/w3m/v1/getInjectedListings",Fs)},async getAllListings(Fs){return fetchListings("/w3m/v1/getAllListings",Fs)},getWalletImageUrl(Fs){return`${W3M_API}/w3m/v1/getWalletImage/${Fs}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`},getAssetImageUrl(Fs){return`${W3M_API}/w3m/v1/getAssetImage/${Fs}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`}};var __defProp$1$1=Object.defineProperty,__getOwnPropSymbols$1=Object.getOwnPropertySymbols,__hasOwnProp$1=Object.prototype.hasOwnProperty,__propIsEnum$1=Object.prototype.propertyIsEnumerable,__defNormalProp$1=(Fs,Ps,Hs)=>Ps in Fs?__defProp$1$1(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Hs}):Fs[Ps]=Hs,__spreadValues$1=(Fs,Ps)=>{for(var Hs in Ps||(Ps={}))__hasOwnProp$1.call(Ps,Hs)&&__defNormalProp$1(Fs,Hs,Ps[Hs]);if(__getOwnPropSymbols$1)for(var Hs of __getOwnPropSymbols$1(Ps))__propIsEnum$1.call(Ps,Hs)&&__defNormalProp$1(Fs,Hs,Ps[Hs]);return Fs};const isMobile=CoreUtil.isMobile(),state$3=proxy$1({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),ExplorerCtrl={state:state$3,async getRecomendedWallets(){const{explorerRecommendedWalletIds:Fs,explorerExcludedWalletIds:Ps}=ConfigCtrl.state;if(Fs==="NONE"||Ps==="ALL"&&!Fs)return state$3.recomendedWallets;if(CoreUtil.isArray(Fs)){const Ws={recommendedIds:Fs.join(",")},{listings:Zs}=await ExplorerUtil.getAllListings(Ws),zs=Object.values(Zs);zs.sort((Ys,Va)=>{const Xs=Fs.indexOf(Ys.id),Ma=Fs.indexOf(Va.id);return Xs-Ma}),state$3.recomendedWallets=zs}else{const{chains:Hs,isAuth:Ws}=OptionsCtrl.state,Zs=Hs?.join(","),zs=CoreUtil.isArray(Ps),Ys={page:1,sdks:Ws?"auth_v1":void 0,entries:CoreUtil.RECOMMENDED_WALLET_AMOUNT,chains:Zs,version:2,excludedIds:zs?Ps.join(","):void 0},{listings:Va}=isMobile?await ExplorerUtil.getMobileListings(Ys):await ExplorerUtil.getDesktopListings(Ys);state$3.recomendedWallets=Object.values(Va)}return state$3.recomendedWallets},async getWallets(Fs){const Ps=__spreadValues$1({},Fs),{explorerRecommendedWalletIds:Hs,explorerExcludedWalletIds:Ws}=ConfigCtrl.state,{recomendedWallets:Zs}=state$3;if(Ws==="ALL")return state$3.wallets;Zs.length?Ps.excludedIds=Zs.map(Js=>Js.id).join(","):CoreUtil.isArray(Hs)&&(Ps.excludedIds=Hs.join(",")),CoreUtil.isArray(Ws)&&(Ps.excludedIds=[Ps.excludedIds,Ws].filter(Boolean).join(",")),OptionsCtrl.state.isAuth&&(Ps.sdks="auth_v1");const{page:zs,search:Ys}=Fs,{listings:Va,total:Xs}=isMobile?await ExplorerUtil.getMobileListings(Ps):await ExplorerUtil.getDesktopListings(Ps),Ma=Object.values(Va),qs=Ys?"search":"wallets";return state$3[qs]={listings:[...state$3[qs].listings,...Ma],total:Xs,page:zs??1},{listings:Ma,total:Xs}},getWalletImageUrl(Fs){return ExplorerUtil.getWalletImageUrl(Fs)},getAssetImageUrl(Fs){return ExplorerUtil.getAssetImageUrl(Fs)},resetSearch(){state$3.search={listings:[],total:0,page:1}}},state$2=proxy$1({open:!1}),ModalCtrl={state:state$2,subscribe(Fs){return subscribe$1(state$2,()=>Fs(state$2))},async open(Fs){return new Promise(Ps=>{const{isUiLoaded:Hs,isDataLoaded:Ws}=OptionsCtrl.state;if(CoreUtil.removeWalletConnectDeepLink(),OptionsCtrl.setWalletConnectUri(Fs?.uri),OptionsCtrl.setChains(Fs?.chains),RouterCtrl.reset("ConnectWallet"),Hs&&Ws)state$2.open=!0,Ps();else{const Zs=setInterval(()=>{const zs=OptionsCtrl.state;zs.isUiLoaded&&zs.isDataLoaded&&(clearInterval(Zs),state$2.open=!0,Ps())},200)}})},close(){state$2.open=!1}};var __defProp$3=Object.defineProperty,__getOwnPropSymbols$3=Object.getOwnPropertySymbols,__hasOwnProp$3=Object.prototype.hasOwnProperty,__propIsEnum$3=Object.prototype.propertyIsEnumerable,__defNormalProp$3=(Fs,Ps,Hs)=>Ps in Fs?__defProp$3(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Hs}):Fs[Ps]=Hs,__spreadValues$3=(Fs,Ps)=>{for(var Hs in Ps||(Ps={}))__hasOwnProp$3.call(Ps,Hs)&&__defNormalProp$3(Fs,Hs,Ps[Hs]);if(__getOwnPropSymbols$3)for(var Hs of __getOwnPropSymbols$3(Ps))__propIsEnum$3.call(Ps,Hs)&&__defNormalProp$3(Fs,Hs,Ps[Hs]);return Fs};function isDarkMode(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const state$1=proxy$1({themeMode:isDarkMode()?"dark":"light"}),ThemeCtrl={state:state$1,subscribe(Fs){return subscribe$1(state$1,()=>Fs(state$1))},setThemeConfig(Fs){const{themeMode:Ps,themeVariables:Hs}=Fs;Ps&&(state$1.themeMode=Ps),Hs&&(state$1.themeVariables=__spreadValues$3({},Hs))}},state$8=proxy$1({open:!1,message:"",variant:"success"}),ToastCtrl={state:state$8,subscribe(Fs){return subscribe$1(state$8,()=>Fs(state$8))},openToast(Fs,Ps){state$8.open=!0,state$8.message=Fs,state$8.variant=Ps},closeToast(){state$8.open=!1}};class WalletConnectModal{constructor(Ps){this.openModal=ModalCtrl.open,this.closeModal=ModalCtrl.close,this.subscribeModal=ModalCtrl.subscribe,this.setTheme=ThemeCtrl.setThemeConfig,ThemeCtrl.setThemeConfig(Ps),ConfigCtrl.setConfig(Ps),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(()=>index);const Ps=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",Ps),OptionsCtrl.setIsUiLoaded(!0)}}}var _a;class DefaultLogger{constructor(Ps="info",Hs){this.logLevel="info",this.logLevel=Ps,this.name=Hs||"Logger"}setLogLevel(Ps){this.logLevel=Ps}getLogLevel(){return this.logLevel}error(Ps,...Hs){["error","warn","info","debug"].includes(this.logLevel)&&console.error(`[ERROR - ${this.name}] ${Ps}`,...Hs)}warn(Ps,...Hs){["warn","info","debug"].includes(this.logLevel)&&console.warn(`[WARN - ${this.name}] ${Ps}`,...Hs)}info(Ps,...Hs){["info","debug"].includes(this.logLevel)&&console.info(`[INFO - ${this.name}] ${Ps}`,...Hs)}debug(Ps,...Hs){this.logLevel==="debug"&&console.debug(`[DEBUG - ${this.name}] ${Ps}`,...Hs)}}let globalLogLevel="info";if(typeof process$1<"u"&&(!((_a=process$1.env)===null||_a===void 0)&&_a.HWC_LOG_LEVEL)){const Fs=process$1.env.HWC_LOG_LEVEL.toLowerCase();["error","warn","info","debug","off"].includes(Fs)&&(globalLogLevel=Fs)}if(typeof localStorage<"u"){const Fs=localStorage.getItem("hwc_log_level");Fs&&["error","warn","info","debug","off"].includes(Fs)&&(globalLogLevel=Fs)}function createLogger(Fs,Ps){return new DefaultLogger(globalLogLevel,Fs)}class SessionNotFoundError extends Error{constructor(Ps){super(Ps),this.name="SessionNotFoundError"}}const clients={};class DAppSigner{constructor(Ps,Hs,Ws,Zs=r$y.MAINNET,zs,Ys="debug"){this.accountId=Ps,this.signClient=Hs,this.topic=Ws,this.ledgerId=Zs,this.extensionId=zs,this.logger=new DefaultLogger(Ys)}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}_getHederaClient(){const Ps=this.ledgerId.toString();return clients[Ps]||(clients[Ps]=a$u.forName(Ps)),clients[Ps]}get _signerAccountId(){return`${ledgerIdToCAIPChainId(this.ledgerId)}:${this.accountId.toString()}`}request(Ps){var Hs,Ws;if(!(!((Ws=(Hs=this===null||this===void 0?void 0:this.signClient)===null||Hs===void 0?void 0:Hs.session)===null||Ws===void 0)&&Ws.get(this.topic)))throw this.logger.error("Session no longer exists, signer will be removed. Please reconnect to the wallet."),this.signClient.emit({topic:this.topic,event:{name:"session_delete",data:{topic:this.topic}},chainId:ledgerIdToCAIPChainId(this.ledgerId)}),new SessionNotFoundError("Session no longer exists. Please reconnect to the wallet.");return this.extensionId&&extensionOpen(this.extensionId),this.signClient.request({topic:this.topic,request:Ps,chainId:ledgerIdToCAIPChainId(this.ledgerId)})}getAccountId(){return this.accountId}getAccountKey(){throw new Error("Method not implemented.")}getLedgerId(){return this.ledgerId}getNetwork(){return this._getHederaClient().network}getMirrorNetwork(){return this._getHederaClient().mirrorNetwork}getAccountBalance(){return this.call(new e$x().setAccountId(this.accountId))}getAccountInfo(){return this.call(new c$A().setAccountId(this.accountId))}getAccountRecords(){return this.call(new e$w().setAccountId(this.accountId))}getMetadata(){return this.signClient.metadata}async sign(Ps,Hs={encoding:"utf-8"}){try{const Ws=Hs.encoding==="base64"?Uint8ArrayToBase64String(Ps[0]):Uint8ArrayToString(Ps[0]),{signatureMap:Zs}=await this.request({method:HederaJsonRpcMethod.SignMessage,params:{signerAccountId:this._signerAccountId,message:Ws}}),zs=base64StringToSignatureMap(Zs),Ys=new t$M({accountId:this.getAccountId(),publicKey:i$v.fromBytes(zs.sigPair[0].pubKeyPrefix),signature:zs.sigPair[0].ed25519||zs.sigPair[0].ECDSASecp256k1});return this.logger.debug("Data signed successfully"),[Ys]}catch(Ws){throw this.logger.error("Error signing data:",Ws),Ws}}async checkTransaction(Ps){throw new Error("Method not implemented.")}async populateTransaction(Ps){return Ps.setTransactionId(i$s.generate(this.getAccountId()))}async signTransaction(Ps){var Hs,Ws;Ps.isFrozen()||Ps.freezeWith(this._getHederaClient());const Zs=(Ws=(Hs=Ps.nodeAccountIds)===null||Hs===void 0?void 0:Hs[0])!==null&&Ws!==void 0?Ws:null,zs=transactionToTransactionBody(Ps,Zs);if(!zs)throw new Error("Failed to serialize transaction body");const Ys=transactionBodyToBase64String(zs),{signatureMap:Va}=await this.request({method:HederaJsonRpcMethod.SignTransaction,params:{signerAccountId:this._signerAccountId,transactionBody:Ys}}),Xs=base64StringToSignatureMap(Va),Ma=Ps.toBytes(),Js=libExports.proto.TransactionList.decode(Ma).transactionList.map(ol=>{if(ol.signedTransactionBytes){const Vc=libExports.proto.SignedTransaction.decode(ol.signedTransactionBytes),sl=[...(Vc.sigMap||libExports.proto.SignatureMap.create({})).sigPair||[],...Xs.sigPair||[]];return{signedTransactionBytes:libExports.proto.SignedTransaction.encode({bodyBytes:Vc.bodyBytes,sigMap:libExports.proto.SignatureMap.create({sigPair:sl})}).finish()}}else{const Vc=ol.sigMap||libExports.proto.SignatureMap.create({}),Dc=[...Vc.sigPair||[],...Xs.sigPair||[]];return Object.assign(Object.assign({},ol),{sigMap:Object.assign(Object.assign({},Vc),{sigPair:Dc})})}}),Mc=libExports.proto.TransactionList.encode({transactionList:Js}).finish();return L$a.fromBytes(Mc)}async _tryExecuteTransactionRequest(Ps){try{const Hs=Ps.toBytes();this.logger.debug("Creating transaction from bytes",Hs,Ps);const Ws=L$a.fromBytes(Hs);this.logger.debug("Executing transaction request",Ws);const Zs=await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:{signerAccountId:this._signerAccountId,transactionList:transactionToBase64String(Ws)}});return this.logger.debug("Transaction request completed successfully"),{result:h$n.fromJSON(Zs)}}catch(Hs){return this.logger.error("Error executing transaction request:",Hs),{error:Hs}}}async _parseQueryResponse(Ps,Hs){if(Ps instanceof e$w)return Hs.split(",").map(Ys=>base64StringToUint8Array(Ys)).map(Ys=>b$f.fromBytes(Ys));const Ws=base64StringToUint8Array(Hs);if(Ps instanceof e$x)return a$D.fromBytes(Ws);if(Ps instanceof c$A)return d$p.fromBytes(Ws);if(Ps instanceof l$C)return d$r.fromBytes(Ws);if(Ps instanceof h$o)return b$f.fromBytes(Ws);throw new Error("Unsupported query type")}async executeReceiptQueryFromRequest(Ps){try{const Ws=this.ledgerId===r$y.MAINNET?a$u.forMainnet():a$u.forTestnet();return{result:await l$C.fromBytes(Ps.toBytes()).execute(Ws)}}catch(Hs){return{error:Hs}}}async _tryExecuteQueryRequest(Ps){try{const Hs=Ps instanceof l$C;if(Hs){this.logger.debug("Attempting to execute free receipt query",Ps);const zs=await this.executeReceiptQueryFromRequest(Ps);if(!zs?.error)return{result:zs.result};this.logger.error("Error executing free receipt query. Sending to wallet.",zs.error)}const Ws=Hs?l$C.fromBytes(Ps.toBytes()):h$p.fromBytes(Ps.toBytes());this.logger.debug("Executing query request",Ws,queryToBase64String(Ws),Hs);const Zs=await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:{signerAccountId:this._signerAccountId,query:queryToBase64String(Ws)}});return this.logger.debug("Query request completed successfully",Zs),{result:this._parseQueryResponse(Ws,Zs.response)}}catch(Hs){return this.logger.error("Error executing query request:",Hs),{error:Hs}}}async call(Ps){var Hs,Ws,Zs,zs,Ys,Va,Xs,Ma,qs;const Js=Ps instanceof l$C;let Mc;if(!Js&&(Mc=await this._tryExecuteTransactionRequest(Ps),Mc.result))return Mc.result;const ol=await this._tryExecuteQueryRequest(Ps);if(ol.result)return ol.result;throw Js?new Error(`Error executing receipt query:
465
465
  `+JSON.stringify({queryError:{name:(Hs=ol.error)===null||Hs===void 0?void 0:Hs.name,message:(Ws=ol.error)===null||Ws===void 0?void 0:Ws.message,stack:(Zs=ol.error)===null||Zs===void 0?void 0:Zs.stack}})):new Error(`Error executing transaction or query:
466
- `+JSON.stringify({txError:{name:(zs=Mc?.error)===null||zs===void 0?void 0:zs.name,message:(Ys=Mc?.error)===null||Ys===void 0?void 0:Ys.message,stack:(Va=Mc?.error)===null||Va===void 0?void 0:Va.stack},queryError:{name:(Xs=ol.error)===null||Xs===void 0?void 0:Xs.name,message:(Ma=ol.error)===null||Ma===void 0?void 0:Ma.message,stack:(qs=ol.error)===null||qs===void 0?void 0:qs.stack}},null,2))}}class DAppConnector{constructor(Ps,Hs,Ws,Zs,zs,Ys,Va="debug"){this.network=r$y.TESTNET,this.supportedMethods=[],this.supportedEvents=[],this.supportedChains=[],this.extensions=[],this.onSessionIframeCreated=null,this.signers=[],this.isInitializing=!1,this.abortableConnect=async Xs=>new Promise(async(Ma,qs)=>{const Mc=setTimeout(()=>{this.walletConnectModal.closeModal(),qs(new Error("Connect timed out after 480000(ms)"))},48e4);try{return Ma(await Xs())}catch(ol){qs(ol)}finally{clearTimeout(Mc)}}),this.logger=new DefaultLogger(Va),this.dAppMetadata=Ps,this.network=Hs,this.projectId=Ws,this.supportedMethods=Zs??Object.values(HederaJsonRpcMethod),this.supportedEvents=zs??[],this.supportedChains=Ys??[],this.extensions=[],this.walletConnectModal=new WalletConnectModal({projectId:Ws,chains:Ys}),findExtensions((Xs,Ma)=>{this.extensions.push(Object.assign(Object.assign({},Xs),{available:!0,availableInIframe:Ma}))})}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}async init({logger:Ps}={}){try{if(this.isInitializing=!0,!this.projectId)throw new Error("Project ID is not defined");this.walletConnectClient=await fe$1.init({logger:Ps,relayUrl:"wss://relay.walletconnect.com",projectId:this.projectId,metadata:this.dAppMetadata});const Hs=this.walletConnectClient.session.getAll();Hs.length>0?this.signers=Hs.flatMap(Ws=>this.createSigners(Ws)):this.checkIframeConnect(),this.walletConnectClient.on("session_event",this.handleSessionEvent.bind(this)),this.walletConnectClient.on("session_update",this.handleSessionUpdate.bind(this)),this.walletConnectClient.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.events.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.pairing.events.on("pairing_delete",this.handlePairingDelete.bind(this))}catch(Hs){this.logger.error("Error initializing DAppConnector:",Hs)}finally{this.isInitializing=!1}}getSigner(Ps){if(this.isInitializing)throw new Error("DAppConnector is not initialized yet. Try again later.");const Hs=this.signers.find(Ws=>Ws.getAccountId().equals(Ps));if(!Hs)throw new Error("Signer is not found for this accountId");return Hs}async openModal(Ps,Hs=!1){try{const{uri:Ws,approval:Zs}=await this.connectURI(Ps);return this.walletConnectModal.openModal({uri:Ws}),await new Promise(async(Ys,Va)=>{Hs&&this.walletConnectModal.subscribeModal(Xs=>{Xs.open||Va(new Error("User rejected pairing"))});try{const Xs=await Zs();await this.onSessionConnected(Xs),Ys(Xs)}catch(Xs){Va(Xs)}})}finally{this.walletConnectModal.closeModal()}}async connect(Ps,Hs,Ws){return this.abortableConnect(async()=>{var Zs;const{uri:zs,approval:Ys}=await this.connectURI(Hs);if(!zs)throw new Error("URI is not defined");Ps(zs);const Va=await Ys();if(Ws){const Xs=Object.assign(Object.assign({},Va.sessionProperties),{extensionId:Ws});Va.sessionProperties=Xs,await((Zs=this.walletConnectClient)===null||Zs===void 0?void 0:Zs.session.update(Va.topic,{sessionProperties:Xs}))}return await this.onSessionConnected(Va),Va})}async connectExtension(Ps,Hs){const Ws=this.extensions.find(Zs=>Zs.id===Ps);if(!Ws||!Ws.available)throw new Error("Extension is not available");return this.connect(Zs=>{extensionConnect(Ws.id,Ws.availableInIframe,Zs)},Hs,Ws.availableInIframe?void 0:Ps)}validateSession(Ps){try{if(!this.walletConnectClient)return!1;const Hs=this.walletConnectClient.session.get(Ps),Ws=this.signers.some(Zs=>Zs.topic===Ps);return Hs?Ws?!0:(this.logger.warn(`Session exists but no signer found for topic: ${Ps}`),!1):(Ws&&(this.logger.warn(`Signer exists but no session found for topic: ${Ps}`),this.handleSessionDelete({topic:Ps})),!1)}catch(Hs){return this.logger.error("Error validating session:",Hs),!1}}validateAndRefreshSigners(){this.signers=this.signers.filter(Ps=>this.validateSession(Ps.topic))}async checkIframeConnect(){const Ps=this.extensions.find(Hs=>Hs.availableInIframe);if(Ps){const Hs=await this.connectExtension(Ps.id);this.onSessionIframeCreated&&this.onSessionIframeCreated(Hs)}}async disconnect(Ps){try{if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");return await this.walletConnectClient.disconnect({topic:Ps,reason:zt$2("USER_DISCONNECTED")}),!0}catch(Hs){return this.logger.error("Either the session was already disconnected or the topic is invalid",Hs),!1}}async disconnectAll(){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ps=this.walletConnectClient.session.getAll(),Hs=this.walletConnectClient.core.pairing.getPairings();if(!Ps?.length&&!Hs?.length)throw new Error("There is no active session/pairing. Connect to the wallet at first.");const Ws=[];for(const Zs of this.walletConnectClient.session.getAll()){this.logger.info(`Disconnecting from session: ${Zs}`);const zs=this.disconnect(Zs.topic);Ws.push(zs)}for(const Zs of Hs){const zs=this.disconnect(Zs.topic);Ws.push(zs)}await Promise.all(Ws),this.signers=[]}createSigners(Ps){return accountAndLedgerFromSession(Ps).map(({account:Ws,network:Zs})=>{var zs;return new DAppSigner(Ws,this.walletConnectClient,Ps.topic,Zs,(zs=Ps.sessionProperties)===null||zs===void 0?void 0:zs.extensionId,this.logger instanceof DefaultLogger?this.logger.getLogLevel():"debug")})}async onSessionConnected(Ps){const Hs=this.createSigners(Ps);for(const Ws of Hs){const Zs=this.signers.filter(zs=>{var Ys,Va;const Xs=((Ys=zs?.getAccountId())===null||Ys===void 0?void 0:Ys.toString())===((Va=Ws?.getAccountId())===null||Va===void 0?void 0:Va.toString()),Ma=Ws.extensionId===zs.extensionId,qs=Ws.getMetadata(),Js=zs.getMetadata(),Mc=qs?.name===Js?.name;return zs.topic===Ws.topic&&this.logger.error("The topic was already connected. This is a weird error. Please report it.",Ws.getAccountId().toString()),Xs&&Ma&&Mc});for(const zs of Zs)this.logger.debug(`Disconnecting duplicate signer for account ${zs.getAccountId().toString()}`),await this.disconnect(zs.topic),this.signers=this.signers.filter(Ys=>Ys.topic!==zs.topic)}this.signers.push(...Hs),this.logger.debug(`Current signers after connection: ${this.signers.map(Ws=>`${Ws.getAccountId().toString()}:${Ws.topic}`).join(", ")}`)}async connectURI(Ps){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Hs=networkNamespaces(this.network,this.supportedMethods,this.supportedEvents);return this.logger.debug("V1 DAppConnector: Connecting with params:",{network:this.network.toString(),pairingTopic:Ps,requiredNamespaces:Hs,supportedMethods:this.supportedMethods,supportedEvents:this.supportedEvents}),this.walletConnectClient.connect({pairingTopic:Ps,requiredNamespaces:Hs})}async request({method:Ps,params:Hs}){var Ws,Zs,zs;let Ys;if(this.logger.debug(`Requesting method: ${Ps} with params: ${JSON.stringify(Hs)}`),Hs?.signerAccountId){const Va=(Zs=(Ws=Hs?.signerAccountId)===null||Ws===void 0?void 0:Ws.split(":"))===null||Zs===void 0?void 0:Zs.pop();if(Ys=this.signers.find(Xs=>{var Ma;return((Ma=Xs?.getAccountId())===null||Ma===void 0?void 0:Ma.toString())===Va}),this.logger.debug(`Found signer: ${(zs=Ys?.getAccountId())===null||zs===void 0?void 0:zs.toString()}`),!Ys)throw new Error(`Signer not found for account ID: ${Hs?.signerAccountId}. Did you use the correct format? e.g hedera:<network>:<address> `)}else Ys=this.signers[this.signers.length-1];if(!Ys)throw new Error("There is no active session. Connect to the wallet at first.");return this.logger.debug(`Using signer: ${Ys.getAccountId().toString()}: ${Ys.topic} - about to request.`),await Ys.request({method:Ps,params:Hs})}async getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async signTransaction(Ps){var Hs,Ws;if(typeof Ps?.transactionBody=="string")return this.logger.warn("Transaction body is a string. This is not recommended, please migrate to passing a transaction object directly."),await this.request({method:HederaJsonRpcMethod.SignTransaction,params:Ps});if(Ps?.transactionBody instanceof L$a){const Zs=(Ws=(Hs=Ps?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Ws===void 0?void 0:Ws.pop(),zs=this.signers.find(Ys=>{var Va;return((Va=Ys?.getAccountId())===null||Va===void 0?void 0:Va.toString())===Zs});if(!zs)throw new Error(`No signer found for account ${Zs}`);if(!Ps?.transactionBody)throw new Error("No transaction provided");return await zs.signTransaction(Ps.transactionBody)}throw new Error("Transaction sent in incorrect format. Ensure transaction body is either a base64 transaction body or Transaction object.")}handleSessionEvent(Ps){this.logger.debug("Session event received:",Ps),this.validateAndRefreshSigners()}handleSessionUpdate({topic:Ps,params:Hs}){const{namespaces:Ws}=Hs,Zs=this.walletConnectClient.session.get(Ps),zs=Object.assign(Object.assign({},Zs),{namespaces:Ws});this.logger.info("Session updated:",zs),this.signers=this.signers.filter(Ys=>Ys.topic!==Ps),this.signers.push(...this.createSigners(zs))}handleSessionDelete(Ps){this.logger.info("Session deleted:",Ps);let Hs=!1;if(this.signers=this.signers.filter(Ws=>Ws.topic!==Ps.topic?!0:(Hs=!0,!1)),Hs){try{this.disconnect(Ps.topic)}catch(Ws){this.logger.error("Error disconnecting session:",Ws)}this.logger.info("Session deleted and signer removed")}}handlePairingDelete(Ps){this.logger.info("Pairing deleted:",Ps),this.signers=this.signers.filter(Hs=>Hs.topic!==Ps.topic);try{this.disconnect(Ps.topic)}catch(Hs){this.logger.error("Error disconnecting pairing:",Hs)}this.logger.info("Pairing deleted by wallet")}}const version$1="6.15.0";function checkType(Fs,Ps,Hs){const Ws=Ps.split("|").map(zs=>zs.trim());for(let zs=0;zs<Ws.length;zs++)switch(Ps){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof Fs===Ps)return}const Zs=new Error(`invalid value for type ${Ps}`);throw Zs.code="INVALID_ARGUMENT",Zs.argument=`value.${Hs}`,Zs.value=Fs,Zs}async function resolveProperties(Fs){const Ps=Object.keys(Fs);return(await Promise.all(Ps.map(Ws=>Promise.resolve(Fs[Ws])))).reduce((Ws,Zs,zs)=>(Ws[Ps[zs]]=Zs,Ws),{})}function defineProperties(Fs,Ps,Hs){for(let Ws in Ps){let Zs=Ps[Ws];const zs=Hs?Hs[Ws]:null;zs&&checkType(Zs,zs,Ws),Object.defineProperty(Fs,Ws,{enumerable:!0,value:Zs,writable:!1})}}function stringify(Fs,Ps){if(Fs==null)return"null";if(Ps==null&&(Ps=new Set),typeof Fs=="object"){if(Ps.has(Fs))return"[Circular]";Ps.add(Fs)}if(Array.isArray(Fs))return"[ "+Fs.map(Hs=>stringify(Hs,Ps)).join(", ")+" ]";if(Fs instanceof Uint8Array){const Hs="0123456789abcdef";let Ws="0x";for(let Zs=0;Zs<Fs.length;Zs++)Ws+=Hs[Fs[Zs]>>4],Ws+=Hs[Fs[Zs]&15];return Ws}if(typeof Fs=="object"&&typeof Fs.toJSON=="function")return stringify(Fs.toJSON(),Ps);switch(typeof Fs){case"boolean":case"number":case"symbol":return Fs.toString();case"bigint":return BigInt(Fs).toString();case"string":return JSON.stringify(Fs);case"object":{const Hs=Object.keys(Fs);return Hs.sort(),"{ "+Hs.map(Ws=>`${stringify(Ws,Ps)}: ${stringify(Fs[Ws],Ps)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function isError(Fs,Ps){return Fs&&Fs.code===Ps}function isCallException(Fs){return isError(Fs,"CALL_EXCEPTION")}function makeError(Fs,Ps,Hs){let Ws=Fs;{const zs=[];if(Hs){if("message"in Hs||"code"in Hs||"name"in Hs)throw new Error(`value will overwrite populated values: ${stringify(Hs)}`);for(const Ys in Hs){if(Ys==="shortMessage")continue;const Va=Hs[Ys];zs.push(Ys+"="+stringify(Va))}}zs.push(`code=${Ps}`),zs.push(`version=${version$1}`),zs.length&&(Fs+=" ("+zs.join(", ")+")")}let Zs;switch(Ps){case"INVALID_ARGUMENT":Zs=new TypeError(Fs);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":Zs=new RangeError(Fs);break;default:Zs=new Error(Fs)}return defineProperties(Zs,{code:Ps}),Hs&&Object.assign(Zs,Hs),Zs.shortMessage==null&&defineProperties(Zs,{shortMessage:Ws}),Zs}function assert(Fs,Ps,Hs,Ws){if(!Fs)throw makeError(Ps,Hs,Ws)}function assertArgument(Fs,Ps,Hs,Ws){assert(Fs,Ps,"INVALID_ARGUMENT",{argument:Hs,value:Ws})}function assertArgumentCount(Fs,Ps,Hs){Hs==null&&(Hs=""),Hs&&(Hs=": "+Hs),assert(Fs>=Ps,"missing argument"+Hs,"MISSING_ARGUMENT",{count:Fs,expectedCount:Ps}),assert(Fs<=Ps,"too many arguments"+Hs,"UNEXPECTED_ARGUMENT",{count:Fs,expectedCount:Ps})}["NFD","NFC","NFKD","NFKC"].reduce((Fs,Ps)=>{try{if("test".normalize(Ps)!=="test")throw new Error("bad");if(Ps==="NFD"&&"é".normalize("NFD")!=="é")throw new Error("broken");Fs.push(Ps)}catch{}return Fs},[]);function assertPrivate(Fs,Ps,Hs){if(Hs==null&&(Hs=""),Fs!==Ps){let Ws=Hs,Zs="new";Hs&&(Ws+=".",Zs+=" "+Hs),assert(!1,`private constructor; use ${Ws}from* methods`,"UNSUPPORTED_OPERATION",{operation:Zs})}}function _getBytes(Fs,Ps,Hs){if(Fs instanceof Uint8Array)return Hs?new Uint8Array(Fs):Fs;if(typeof Fs=="string"&&Fs.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)){const Ws=new Uint8Array((Fs.length-2)/2);let Zs=2;for(let zs=0;zs<Ws.length;zs++)Ws[zs]=parseInt(Fs.substring(Zs,Zs+2),16),Zs+=2;return Ws}assertArgument(!1,"invalid BytesLike value",Ps||"value",Fs)}function getBytes(Fs,Ps){return _getBytes(Fs,Ps,!1)}function getBytesCopy(Fs,Ps){return _getBytes(Fs,Ps,!0)}function isHexString(Fs,Ps){return!(typeof Fs!="string"||!Fs.match(/^0x[0-9A-Fa-f]*$/)||typeof Ps=="number"&&Fs.length!==2+2*Ps||Ps===!0&&Fs.length%2!==0)}function isBytesLike(Fs){return isHexString(Fs,!0)||Fs instanceof Uint8Array}const HexCharacters="0123456789abcdef";function hexlify(Fs){const Ps=getBytes(Fs);let Hs="0x";for(let Ws=0;Ws<Ps.length;Ws++){const Zs=Ps[Ws];Hs+=HexCharacters[(Zs&240)>>4]+HexCharacters[Zs&15]}return Hs}function concat(Fs){return"0x"+Fs.map(Ps=>hexlify(Ps).substring(2)).join("")}function dataLength(Fs){return isHexString(Fs,!0)?(Fs.length-2)/2:getBytes(Fs).length}function dataSlice(Fs,Ps,Hs){const Ws=getBytes(Fs);return Hs!=null&&Hs>Ws.length&&assert(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:Ws,length:Ws.length,offset:Hs}),hexlify(Ws.slice(Ps??0,Hs??Ws.length))}function zeroPad(Fs,Ps,Hs){const Ws=getBytes(Fs);assert(Ps>=Ws.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(Ws),length:Ps,offset:Ps+1});const Zs=new Uint8Array(Ps);return Zs.fill(0),Hs?Zs.set(Ws,Ps-Ws.length):Zs.set(Ws,0),hexlify(Zs)}function zeroPadValue(Fs,Ps){return zeroPad(Fs,Ps,!0)}function zeroPadBytes(Fs,Ps){return zeroPad(Fs,Ps,!1)}const BN_0$9=BigInt(0),BN_1$4=BigInt(1),maxValue=9007199254740991;function fromTwos(Fs,Ps){const Hs=getUint(Fs,"value"),Ws=BigInt(getNumber(Ps,"width"));if(assert(Hs>>Ws===BN_0$9,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:Fs}),Hs>>Ws-BN_1$4){const Zs=(BN_1$4<<Ws)-BN_1$4;return-((~Hs&Zs)+BN_1$4)}return Hs}function toTwos(Fs,Ps){let Hs=getBigInt(Fs,"value");const Ws=BigInt(getNumber(Ps,"width")),Zs=BN_1$4<<Ws-BN_1$4;if(Hs<BN_0$9){Hs=-Hs,assert(Hs<=Zs,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:Fs});const zs=(BN_1$4<<Ws)-BN_1$4;return(~Hs&zs)+BN_1$4}else assert(Hs<Zs,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:Fs});return Hs}function mask(Fs,Ps){const Hs=getUint(Fs,"value"),Ws=BigInt(getNumber(Ps,"bits"));return Hs&(BN_1$4<<Ws)-BN_1$4}function getBigInt(Fs,Ps){switch(typeof Fs){case"bigint":return Fs;case"number":return assertArgument(Number.isInteger(Fs),"underflow",Ps||"value",Fs),assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),BigInt(Fs);case"string":try{if(Fs==="")throw new Error("empty string");return Fs[0]==="-"&&Fs[1]!=="-"?-BigInt(Fs.substring(1)):BigInt(Fs)}catch(Hs){assertArgument(!1,`invalid BigNumberish string: ${Hs.message}`,Ps||"value",Fs)}}assertArgument(!1,"invalid BigNumberish value",Ps||"value",Fs)}function getUint(Fs,Ps){const Hs=getBigInt(Fs,Ps);return assert(Hs>=BN_0$9,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:Fs}),Hs}const Nibbles="0123456789abcdef";function toBigInt(Fs){if(Fs instanceof Uint8Array){let Ps="0x0";for(const Hs of Fs)Ps+=Nibbles[Hs>>4],Ps+=Nibbles[Hs&15];return BigInt(Ps)}return getBigInt(Fs)}function getNumber(Fs,Ps){switch(typeof Fs){case"bigint":return assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),Number(Fs);case"number":return assertArgument(Number.isInteger(Fs),"underflow",Ps||"value",Fs),assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),Fs;case"string":try{if(Fs==="")throw new Error("empty string");return getNumber(BigInt(Fs),Ps)}catch(Hs){assertArgument(!1,`invalid numeric string: ${Hs.message}`,Ps||"value",Fs)}}assertArgument(!1,"invalid numeric value",Ps||"value",Fs)}function toNumber(Fs){return getNumber(toBigInt(Fs))}function toBeHex(Fs,Ps){let Ws=getUint(Fs,"value").toString(16);if(Ps==null)Ws.length%2&&(Ws="0"+Ws);else{const Zs=getNumber(Ps,"width");for(assert(Zs*2>=Ws.length,`value exceeds width (${Zs} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:Fs});Ws.length<Zs*2;)Ws="0"+Ws}return"0x"+Ws}function toBeArray(Fs){const Ps=getUint(Fs,"value");if(Ps===BN_0$9)return new Uint8Array([]);let Hs=Ps.toString(16);Hs.length%2&&(Hs="0"+Hs);const Ws=new Uint8Array(Hs.length/2);for(let Zs=0;Zs<Ws.length;Zs++){const zs=Zs*2;Ws[Zs]=parseInt(Hs.substring(zs,zs+2),16)}return Ws}function toQuantity(Fs){let Ps=hexlify(isBytesLike(Fs)?Fs:toBeArray(Fs)).substring(2);for(;Ps.startsWith("0");)Ps=Ps.substring(1);return Ps===""&&(Ps="0"),"0x"+Ps}const Alphabet="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";BigInt(0);const BN_58=BigInt(58);function encodeBase58(Fs){const Ps=getBytes(Fs);let Hs=toBigInt(Ps),Ws="";for(;Hs;)Ws=Alphabet[Number(Hs%BN_58)]+Ws,Hs/=BN_58;for(let Zs=0;Zs<Ps.length&&!Ps[Zs];Zs++)Ws=Alphabet[0]+Ws;return Ws}function decodeBase64(Fs){Fs=atob(Fs);const Ps=new Uint8Array(Fs.length);for(let Hs=0;Hs<Fs.length;Hs++)Ps[Hs]=Fs.charCodeAt(Hs);return getBytes(Ps)}function encodeBase64(Fs){const Ps=getBytes(Fs);let Hs="";for(let Ws=0;Ws<Ps.length;Ws++)Hs+=String.fromCharCode(Ps[Ws]);return btoa(Hs)}class EventPayload{filter;emitter;#e;constructor(Ps,Hs,Ws){this.#e=Hs,defineProperties(this,{emitter:Ps,filter:Ws})}async removeListener(){this.#e!=null&&await this.emitter.off(this.filter,this.#e)}}function errorFunc(Fs,Ps,Hs,Ws,Zs){assertArgument(!1,`invalid codepoint at offset ${Ps}; ${Fs}`,"bytes",Hs)}function ignoreFunc(Fs,Ps,Hs,Ws,Zs){if(Fs==="BAD_PREFIX"||Fs==="UNEXPECTED_CONTINUE"){let zs=0;for(let Ys=Ps+1;Ys<Hs.length&&Hs[Ys]>>6===2;Ys++)zs++;return zs}return Fs==="OVERRUN"?Hs.length-Ps-1:0}function replaceFunc(Fs,Ps,Hs,Ws,Zs){return Fs==="OVERLONG"?(assertArgument(typeof Zs=="number","invalid bad code point for replacement","badCodepoint",Zs),Ws.push(Zs),0):(Ws.push(65533),ignoreFunc(Fs,Ps,Hs))}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(Fs,Ps){Ps==null&&(Ps=Utf8ErrorFuncs.error);const Hs=getBytes(Fs,"bytes"),Ws=[];let Zs=0;for(;Zs<Hs.length;){const zs=Hs[Zs++];if(zs>>7===0){Ws.push(zs);continue}let Ys=null,Va=null;if((zs&224)===192)Ys=1,Va=127;else if((zs&240)===224)Ys=2,Va=2047;else if((zs&248)===240)Ys=3,Va=65535;else{(zs&192)===128?Zs+=Ps("UNEXPECTED_CONTINUE",Zs-1,Hs,Ws):Zs+=Ps("BAD_PREFIX",Zs-1,Hs,Ws);continue}if(Zs-1+Ys>=Hs.length){Zs+=Ps("OVERRUN",Zs-1,Hs,Ws);continue}let Xs=zs&(1<<8-Ys-1)-1;for(let Ma=0;Ma<Ys;Ma++){let qs=Hs[Zs];if((qs&192)!=128){Zs+=Ps("MISSING_CONTINUE",Zs,Hs,Ws),Xs=null;break}Xs=Xs<<6|qs&63,Zs++}if(Xs!==null){if(Xs>1114111){Zs+=Ps("OUT_OF_RANGE",Zs-1-Ys,Hs,Ws,Xs);continue}if(Xs>=55296&&Xs<=57343){Zs+=Ps("UTF16_SURROGATE",Zs-1-Ys,Hs,Ws,Xs);continue}if(Xs<=Va){Zs+=Ps("OVERLONG",Zs-1-Ys,Hs,Ws,Xs);continue}Ws.push(Xs)}}return Ws}function toUtf8Bytes(Fs,Ps){assertArgument(typeof Fs=="string","invalid string value","str",Fs);let Hs=[];for(let Ws=0;Ws<Fs.length;Ws++){const Zs=Fs.charCodeAt(Ws);if(Zs<128)Hs.push(Zs);else if(Zs<2048)Hs.push(Zs>>6|192),Hs.push(Zs&63|128);else if((Zs&64512)==55296){Ws++;const zs=Fs.charCodeAt(Ws);assertArgument(Ws<Fs.length&&(zs&64512)===56320,"invalid surrogate pair","str",Fs);const Ys=65536+((Zs&1023)<<10)+(zs&1023);Hs.push(Ys>>18|240),Hs.push(Ys>>12&63|128),Hs.push(Ys>>6&63|128),Hs.push(Ys&63|128)}else Hs.push(Zs>>12|224),Hs.push(Zs>>6&63|128),Hs.push(Zs&63|128)}return new Uint8Array(Hs)}function _toUtf8String(Fs){return Fs.map(Ps=>Ps<=65535?String.fromCharCode(Ps):(Ps-=65536,String.fromCharCode((Ps>>10&1023)+55296,(Ps&1023)+56320))).join("")}function toUtf8String(Fs,Ps){return _toUtf8String(getUtf8CodePoints(Fs,Ps))}function createGetUrl(Fs){async function Ps(Hs,Ws){assert(Ws==null||!Ws.cancelled,"request cancelled before sending","CANCELLED");const Zs=Hs.url.split(":")[0].toLowerCase();assert(Zs==="http"||Zs==="https",`unsupported protocol ${Zs}`,"UNSUPPORTED_OPERATION",{info:{protocol:Zs},operation:"request"}),assert(Zs==="https"||!Hs.credentials||Hs.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let zs=null;const Ys=new AbortController,Va=setTimeout(()=>{zs=makeError("request timeout","TIMEOUT"),Ys.abort()},Hs.timeout);Ws&&Ws.addListener(()=>{zs=makeError("request cancelled","CANCELLED"),Ys.abort()});const Xs=Object.assign({},Fs,{method:Hs.method,headers:new Headers(Array.from(Hs)),body:Hs.body||void 0,signal:Ys.signal});let Ma;try{Ma=await fetch(Hs.url,Xs)}catch(ol){throw clearTimeout(Va),zs||ol}clearTimeout(Va);const qs={};Ma.headers.forEach((ol,Vc)=>{qs[Vc.toLowerCase()]=ol});const Js=await Ma.arrayBuffer(),Mc=Js==null?null:new Uint8Array(Js);return{statusCode:Ma.status,statusMessage:Ma.statusText,headers:qs,body:Mc}}return Ps}const MAX_ATTEMPTS=12,SLOT_INTERVAL=250;let defaultGetUrlFunc=createGetUrl();const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$1=!1;async function dataGatewayFunc(Fs,Ps){try{const Hs=Fs.match(reData);if(!Hs)throw new Error("invalid data");return new FetchResponse(200,"OK",{"content-type":Hs[1]||"text/plain"},Hs[2]?decodeBase64(Hs[3]):unpercent(Hs[3]))}catch{return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(Fs))}}function getIpfsGatewayFunc(Fs){async function Ps(Hs,Ws){try{const Zs=Hs.match(reIpfs);if(!Zs)throw new Error("invalid link");return new FetchRequest(`${Fs}${Zs[2]}`)}catch{return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(Hs))}}return Ps}const Gateways={data:dataGatewayFunc,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")},fetchSignals=new WeakMap;class FetchCancelSignal{#e;#t;constructor(Ps){this.#e=[],this.#t=!1,fetchSignals.set(Ps,()=>{if(!this.#t){this.#t=!0;for(const Hs of this.#e)setTimeout(()=>{Hs()},0);this.#e=[]}})}addListener(Ps){assert(!this.#t,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),this.#e.push(Ps)}get cancelled(){return this.#t}checkSignal(){assert(!this.cancelled,"cancelled","CANCELLED",{})}}function checkSignal(Fs){if(Fs==null)throw new Error("missing signal; should not happen");return Fs.checkSignal(),Fs}class FetchRequest{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;#c;#u;#f;get url(){return this.#s}set url(Ps){this.#s=String(Ps)}get body(){return this.#i==null?null:new Uint8Array(this.#i)}set body(Ps){if(Ps==null)this.#i=void 0,this.#a=void 0;else if(typeof Ps=="string")this.#i=toUtf8Bytes(Ps),this.#a="text/plain";else if(Ps instanceof Uint8Array)this.#i=Ps,this.#a="application/octet-stream";else if(typeof Ps=="object")this.#i=toUtf8Bytes(JSON.stringify(Ps)),this.#a="application/json";else throw new Error("invalid body")}hasBody(){return this.#i!=null}get method(){return this.#n?this.#n:this.hasBody()?"POST":"GET"}set method(Ps){Ps==null&&(Ps=""),this.#n=String(Ps).toUpperCase()}get headers(){const Ps=Object.assign({},this.#r);return this.#d&&(Ps.authorization=`Basic ${encodeBase64(toUtf8Bytes(this.#d))}`),this.allowGzip&&(Ps["accept-encoding"]="gzip"),Ps["content-type"]==null&&this.#a&&(Ps["content-type"]=this.#a),this.body&&(Ps["content-length"]=String(this.body.length)),Ps}getHeader(Ps){return this.headers[Ps.toLowerCase()]}setHeader(Ps,Hs){this.#r[String(Ps).toLowerCase()]=String(Hs)}clearHeaders(){this.#r={}}[Symbol.iterator](){const Ps=this.headers,Hs=Object.keys(Ps);let Ws=0;return{next:()=>{if(Ws<Hs.length){const Zs=Hs[Ws++];return{value:[Zs,Ps[Zs]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#d||null}setCredentials(Ps,Hs){assertArgument(!Ps.match(/:/),"invalid basic authentication username","username","[REDACTED]"),this.#d=`${Ps}:${Hs}`}get allowGzip(){return this.#t}set allowGzip(Ps){this.#t=!!Ps}get allowInsecureAuthentication(){return!!this.#e}set allowInsecureAuthentication(Ps){this.#e=!!Ps}get timeout(){return this.#o}set timeout(Ps){assertArgument(Ps>=0,"timeout must be non-zero","timeout",Ps),this.#o=Ps}get preflightFunc(){return this.#l||null}set preflightFunc(Ps){this.#l=Ps}get processFunc(){return this.#p||null}set processFunc(Ps){this.#p=Ps}get retryFunc(){return this.#g||null}set retryFunc(Ps){this.#g=Ps}get getUrlFunc(){return this.#f||defaultGetUrlFunc}set getUrlFunc(Ps){this.#f=Ps}constructor(Ps){this.#s=String(Ps),this.#e=!1,this.#t=!0,this.#r={},this.#n="",this.#o=3e5,this.#u={slotInterval:SLOT_INTERVAL,maxAttempts:MAX_ATTEMPTS},this.#f=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#i?hexlify(this.#i):"null"}>`}setThrottleParams(Ps){Ps.slotInterval!=null&&(this.#u.slotInterval=Ps.slotInterval),Ps.maxAttempts!=null&&(this.#u.maxAttempts=Ps.maxAttempts)}async#h(Ps,Hs,Ws,Zs,zs){if(Ps>=this.#u.maxAttempts)return zs.makeServerError("exceeded maximum retry limit");assert(getTime$1()<=Hs,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:Zs}),Ws>0&&await wait(Ws);let Ys=this.clone();const Va=(Ys.url.split(":")[0]||"").toLowerCase();if(Va in Gateways){const qs=await Gateways[Va](Ys.url,checkSignal(Zs.#c));if(qs instanceof FetchResponse){let Js=qs;if(this.processFunc){checkSignal(Zs.#c);try{Js=await this.processFunc(Ys,Js)}catch(Mc){(Mc.throttle==null||typeof Mc.stall!="number")&&Js.makeServerError("error in post-processing function",Mc).assertOk()}}return Js}Ys=qs}this.preflightFunc&&(Ys=await this.preflightFunc(Ys));const Xs=await this.getUrlFunc(Ys,checkSignal(Zs.#c));let Ma=new FetchResponse(Xs.statusCode,Xs.statusMessage,Xs.headers,Xs.body,Zs);if(Ma.statusCode===301||Ma.statusCode===302){try{const qs=Ma.headers.location||"";return Ys.redirect(qs).#h(Ps+1,Hs,0,Zs,Ma)}catch{}return Ma}else if(Ma.statusCode===429&&(this.retryFunc==null||await this.retryFunc(Ys,Ma,Ps))){const qs=Ma.headers["retry-after"];let Js=this.#u.slotInterval*Math.trunc(Math.random()*Math.pow(2,Ps));return typeof qs=="string"&&qs.match(/^[1-9][0-9]*$/)&&(Js=parseInt(qs)),Ys.clone().#h(Ps+1,Hs,Js,Zs,Ma)}if(this.processFunc){checkSignal(Zs.#c);try{Ma=await this.processFunc(Ys,Ma)}catch(qs){(qs.throttle==null||typeof qs.stall!="number")&&Ma.makeServerError("error in post-processing function",qs).assertOk();let Js=this.#u.slotInterval*Math.trunc(Math.random()*Math.pow(2,Ps));return qs.stall>=0&&(Js=qs.stall),Ys.clone().#h(Ps+1,Hs,Js,Zs,Ma)}}return Ma}send(){return assert(this.#c==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),this.#c=new FetchCancelSignal(this),this.#h(0,getTime$1()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){assert(this.#c!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const Ps=fetchSignals.get(this);if(!Ps)throw new Error("missing signal; should not happen");Ps()}redirect(Ps){const Hs=this.url.split(":")[0].toLowerCase(),Ws=Ps.split(":")[0].toLowerCase();assert(this.method==="GET"&&(Hs!=="https"||Ws!=="http")&&Ps.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(Ps)})`});const Zs=new FetchRequest(Ps);return Zs.method="GET",Zs.allowGzip=this.allowGzip,Zs.timeout=this.timeout,Zs.#r=Object.assign({},this.#r),this.#i&&(Zs.#i=new Uint8Array(this.#i)),Zs.#a=this.#a,Zs}clone(){const Ps=new FetchRequest(this.url);return Ps.#n=this.#n,this.#i&&(Ps.#i=this.#i),Ps.#a=this.#a,Ps.#r=Object.assign({},this.#r),Ps.#d=this.#d,this.allowGzip&&(Ps.allowGzip=!0),Ps.timeout=this.timeout,this.allowInsecureAuthentication&&(Ps.allowInsecureAuthentication=!0),Ps.#l=this.#l,Ps.#p=this.#p,Ps.#g=this.#g,Ps.#u=Object.assign({},this.#u),Ps.#f=this.#f,Ps}static lockConfig(){locked$1=!0}static getGateway(Ps){return Gateways[Ps.toLowerCase()]||null}static registerGateway(Ps,Hs){if(Ps=Ps.toLowerCase(),Ps==="http"||Ps==="https")throw new Error(`cannot intercept ${Ps}; use registerGetUrl`);if(locked$1)throw new Error("gateways locked");Gateways[Ps]=Hs}static registerGetUrl(Ps){if(locked$1)throw new Error("gateways locked");defaultGetUrlFunc=Ps}static createGetUrlFunc(Ps){return createGetUrl(Ps)}static createDataGateway(){return dataGatewayFunc}static createIpfsGatewayFunc(Ps){return getIpfsGatewayFunc(Ps)}}class FetchResponse{#e;#t;#r;#n;#o;#s;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#n?hexlify(this.#n):"null"}>`}get statusCode(){return this.#e}get statusMessage(){return this.#t}get headers(){return Object.assign({},this.#r)}get body(){return this.#n==null?null:new Uint8Array(this.#n)}get bodyText(){try{return this.#n==null?"":toUtf8String(this.#n)}catch{assert(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch{assert(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const Ps=this.headers,Hs=Object.keys(Ps);let Ws=0;return{next:()=>{if(Ws<Hs.length){const Zs=Hs[Ws++];return{value:[Zs,Ps[Zs]],done:!1}}return{value:void 0,done:!0}}}}constructor(Ps,Hs,Ws,Zs,zs){this.#e=Ps,this.#t=Hs,this.#r=Object.keys(Ws).reduce((Ys,Va)=>(Ys[Va.toLowerCase()]=String(Ws[Va]),Ys),{}),this.#n=Zs==null?null:new Uint8Array(Zs),this.#o=zs||null,this.#s={message:""}}makeServerError(Ps,Hs){let Ws;Ps?Ws=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${Ps})`:(Ps=`${this.statusCode} ${this.statusMessage}`,Ws=`CLIENT ESCALATED SERVER ERROR (${Ps})`);const Zs=new FetchResponse(599,Ws,this.headers,this.body,this.#o||void 0);return Zs.#s={message:Ps,error:Hs},Zs}throwThrottleError(Ps,Hs){Hs==null?Hs=-1:assertArgument(Number.isInteger(Hs)&&Hs>=0,"invalid stall timeout","stall",Hs);const Ws=new Error(Ps||"throttling requests");throw defineProperties(Ws,{stall:Hs,throttle:!0}),Ws}getHeader(Ps){return this.headers[Ps.toLowerCase()]}hasBody(){return this.#n!=null}get request(){return this.#o}ok(){return this.#s.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:Ps,error:Hs}=this.#s;Ps===""&&(Ps=`server response ${this.statusCode} ${this.statusMessage}`);let Ws=null;this.request&&(Ws=this.request.url);let Zs=null;try{this.#n&&(Zs=toUtf8String(this.#n))}catch{}assert(!1,Ps,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:Hs,info:{requestUrl:Ws,responseBody:Zs,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}function getTime$1(){return new Date().getTime()}function unpercent(Fs){return toUtf8Bytes(Fs.replace(/%([0-9a-f][0-9a-f])/gi,(Ps,Hs)=>String.fromCharCode(parseInt(Hs,16))))}function wait(Fs){return new Promise(Ps=>setTimeout(Ps,Fs))}const BN_N1=BigInt(-1),BN_0$8=BigInt(0),BN_1$3=BigInt(1),BN_5=BigInt(5),_guard$3={};let Zeros$1="0000";for(;Zeros$1.length<80;)Zeros$1+=Zeros$1;function getTens(Fs){let Ps=Zeros$1;for(;Ps.length<Fs;)Ps+=Ps;return BigInt("1"+Ps.substring(0,Fs))}function checkValue(Fs,Ps,Hs){const Ws=BigInt(Ps.width);if(Ps.signed){const Zs=BN_1$3<<Ws-BN_1$3;assert(Hs==null||Fs>=-Zs&&Fs<Zs,"overflow","NUMERIC_FAULT",{operation:Hs,fault:"overflow",value:Fs}),Fs>BN_0$8?Fs=fromTwos(mask(Fs,Ws),Ws):Fs=-fromTwos(mask(-Fs,Ws),Ws)}else{const Zs=BN_1$3<<Ws;assert(Hs==null||Fs>=0&&Fs<Zs,"overflow","NUMERIC_FAULT",{operation:Hs,fault:"overflow",value:Fs}),Fs=(Fs%Zs+Zs)%Zs&Zs-BN_1$3}return Fs}function getFormat(Fs){typeof Fs=="number"&&(Fs=`fixed128x${Fs}`);let Ps=!0,Hs=128,Ws=18;if(typeof Fs=="string"){if(Fs!=="fixed")if(Fs==="ufixed")Ps=!1;else{const zs=Fs.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);assertArgument(zs,"invalid fixed format","format",Fs),Ps=zs[1]!=="u",Hs=parseInt(zs[2]),Ws=parseInt(zs[3])}}else if(Fs){const zs=Fs,Ys=(Va,Xs,Ma)=>zs[Va]==null?Ma:(assertArgument(typeof zs[Va]===Xs,"invalid fixed format ("+Va+" not "+Xs+")","format."+Va,zs[Va]),zs[Va]);Ps=Ys("signed","boolean",Ps),Hs=Ys("width","number",Hs),Ws=Ys("decimals","number",Ws)}assertArgument(Hs%8===0,"invalid FixedNumber width (not byte aligned)","format.width",Hs),assertArgument(Ws<=80,"invalid FixedNumber decimals (too large)","format.decimals",Ws);const Zs=(Ps?"":"u")+"fixed"+String(Hs)+"x"+String(Ws);return{signed:Ps,width:Hs,decimals:Ws,name:Zs}}function toString(Fs,Ps){let Hs="";Fs<BN_0$8&&(Hs="-",Fs*=BN_N1);let Ws=Fs.toString();if(Ps===0)return Hs+Ws;for(;Ws.length<=Ps;)Ws=Zeros$1+Ws;const Zs=Ws.length-Ps;for(Ws=Ws.substring(0,Zs)+"."+Ws.substring(Zs);Ws[0]==="0"&&Ws[1]!==".";)Ws=Ws.substring(1);for(;Ws[Ws.length-1]==="0"&&Ws[Ws.length-2]!==".";)Ws=Ws.substring(0,Ws.length-1);return Hs+Ws}class FixedNumber{format;#e;#t;#r;_value;constructor(Ps,Hs,Ws){assertPrivate(Ps,_guard$3,"FixedNumber"),this.#t=Hs,this.#e=Ws;const Zs=toString(Hs,Ws.decimals);defineProperties(this,{format:Ws.name,_value:Zs}),this.#r=getTens(Ws.decimals)}get signed(){return this.#e.signed}get width(){return this.#e.width}get decimals(){return this.#e.decimals}get value(){return this.#t}#n(Ps){assertArgument(this.format===Ps.format,"incompatible format; use fixedNumber.toFormat","other",Ps)}#o(Ps,Hs){return Ps=checkValue(Ps,this.#e,Hs),new FixedNumber(_guard$3,Ps,this.#e)}#s(Ps,Hs){return this.#n(Ps),this.#o(this.#t+Ps.#t,Hs)}addUnsafe(Ps){return this.#s(Ps)}add(Ps){return this.#s(Ps,"add")}#i(Ps,Hs){return this.#n(Ps),this.#o(this.#t-Ps.#t,Hs)}subUnsafe(Ps){return this.#i(Ps)}sub(Ps){return this.#i(Ps,"sub")}#a(Ps,Hs){return this.#n(Ps),this.#o(this.#t*Ps.#t/this.#r,Hs)}mulUnsafe(Ps){return this.#a(Ps)}mul(Ps){return this.#a(Ps,"mul")}mulSignal(Ps){this.#n(Ps);const Hs=this.#t*Ps.#t;return assert(Hs%this.#r===BN_0$8,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this}),this.#o(Hs/this.#r,"mulSignal")}#d(Ps,Hs){return assert(Ps.#t!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#n(Ps),this.#o(this.#t*this.#r/Ps.#t,Hs)}divUnsafe(Ps){return this.#d(Ps)}div(Ps){return this.#d(Ps,"div")}divSignal(Ps){assert(Ps.#t!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#n(Ps);const Hs=this.#t*this.#r;return assert(Hs%Ps.#t===BN_0$8,"precision lost during signalling div","NUMERIC_FAULT",{operation:"divSignal",fault:"underflow",value:this}),this.#o(Hs/Ps.#t,"divSignal")}cmp(Ps){let Hs=this.value,Ws=Ps.value;const Zs=this.decimals-Ps.decimals;return Zs>0?Ws*=getTens(Zs):Zs<0&&(Hs*=getTens(-Zs)),Hs<Ws?-1:Hs>Ws?1:0}eq(Ps){return this.cmp(Ps)===0}lt(Ps){return this.cmp(Ps)<0}lte(Ps){return this.cmp(Ps)<=0}gt(Ps){return this.cmp(Ps)>0}gte(Ps){return this.cmp(Ps)>=0}floor(){let Ps=this.#t;return this.#t<BN_0$8&&(Ps-=this.#r-BN_1$3),Ps=this.#t/this.#r*this.#r,this.#o(Ps,"floor")}ceiling(){let Ps=this.#t;return this.#t>BN_0$8&&(Ps+=this.#r-BN_1$3),Ps=this.#t/this.#r*this.#r,this.#o(Ps,"ceiling")}round(Ps){if(Ps==null&&(Ps=0),Ps>=this.decimals)return this;const Hs=this.decimals-Ps,Ws=BN_5*getTens(Hs-1);let Zs=this.value+Ws;const zs=getTens(Hs);return Zs=Zs/zs*zs,checkValue(Zs,this.#e,"round"),new FixedNumber(_guard$3,Zs,this.#e)}isZero(){return this.#t===BN_0$8}isNegative(){return this.#t<BN_0$8}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(Ps){return FixedNumber.fromString(this.toString(),Ps)}static fromValue(Ps,Hs,Ws){const Zs=Hs==null?0:getNumber(Hs),zs=getFormat(Ws);let Ys=getBigInt(Ps,"value");const Va=Zs-zs.decimals;if(Va>0){const Xs=getTens(Va);assert(Ys%Xs===BN_0$8,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:Ps}),Ys/=Xs}else Va<0&&(Ys*=getTens(-Va));return checkValue(Ys,zs,"fromValue"),new FixedNumber(_guard$3,Ys,zs)}static fromString(Ps,Hs){const Ws=Ps.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(Ws&&Ws[2].length+Ws[3].length>0,"invalid FixedNumber string value","value",Ps);const Zs=getFormat(Hs);let zs=Ws[2]||"0",Ys=Ws[3]||"";for(;Ys.length<Zs.decimals;)Ys+=Zeros$1;assert(Ys.substring(Zs.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:Ps}),Ys=Ys.substring(0,Zs.decimals);const Va=BigInt(Ws[1]+zs+Ys);return checkValue(Va,Zs,"fromString"),new FixedNumber(_guard$3,Va,Zs)}static fromBytes(Ps,Hs){let Ws=toBigInt(getBytes(Ps,"value"));const Zs=getFormat(Hs);return Zs.signed&&(Ws=fromTwos(Ws,Zs.width)),checkValue(Ws,Zs,"fromBytes"),new FixedNumber(_guard$3,Ws,Zs)}}function hexlifyByte(Fs){let Ps=Fs.toString(16);for(;Ps.length<2;)Ps="0"+Ps;return"0x"+Ps}function unarrayifyInteger(Fs,Ps,Hs){let Ws=0;for(let Zs=0;Zs<Hs;Zs++)Ws=Ws*256+Fs[Ps+Zs];return Ws}function _decodeChildren(Fs,Ps,Hs,Ws){const Zs=[];for(;Hs<Ps+1+Ws;){const zs=_decode(Fs,Hs);Zs.push(zs.result),Hs+=zs.consumed,assert(Hs<=Ps+1+Ws,"child data too short","BUFFER_OVERRUN",{buffer:Fs,length:Ws,offset:Ps})}return{consumed:1+Ws,result:Zs}}function _decode(Fs,Ps){assert(Fs.length!==0,"data too short","BUFFER_OVERRUN",{buffer:Fs,length:0,offset:1});const Hs=Ws=>{assert(Ws<=Fs.length,"data short segment too short","BUFFER_OVERRUN",{buffer:Fs,length:Fs.length,offset:Ws})};if(Fs[Ps]>=248){const Ws=Fs[Ps]-247;Hs(Ps+1+Ws);const Zs=unarrayifyInteger(Fs,Ps+1,Ws);return Hs(Ps+1+Ws+Zs),_decodeChildren(Fs,Ps,Ps+1+Ws,Ws+Zs)}else if(Fs[Ps]>=192){const Ws=Fs[Ps]-192;return Hs(Ps+1+Ws),_decodeChildren(Fs,Ps,Ps+1,Ws)}else if(Fs[Ps]>=184){const Ws=Fs[Ps]-183;Hs(Ps+1+Ws);const Zs=unarrayifyInteger(Fs,Ps+1,Ws);Hs(Ps+1+Ws+Zs);const zs=hexlify(Fs.slice(Ps+1+Ws,Ps+1+Ws+Zs));return{consumed:1+Ws+Zs,result:zs}}else if(Fs[Ps]>=128){const Ws=Fs[Ps]-128;Hs(Ps+1+Ws);const Zs=hexlify(Fs.slice(Ps+1,Ps+1+Ws));return{consumed:1+Ws,result:Zs}}return{consumed:1,result:hexlifyByte(Fs[Ps])}}function decodeRlp(Fs){const Ps=getBytes(Fs,"data"),Hs=_decode(Ps,0);return assertArgument(Hs.consumed===Ps.length,"unexpected junk after rlp payload","data",Fs),Hs.result}function arrayifyInteger(Fs){const Ps=[];for(;Fs;)Ps.unshift(Fs&255),Fs>>=8;return Ps}function _encode(Fs){if(Array.isArray(Fs)){let Ws=[];if(Fs.forEach(function(zs){Ws=Ws.concat(_encode(zs))}),Ws.length<=55)return Ws.unshift(192+Ws.length),Ws;const Zs=arrayifyInteger(Ws.length);return Zs.unshift(247+Zs.length),Zs.concat(Ws)}const Ps=Array.prototype.slice.call(getBytes(Fs,"object"));if(Ps.length===1&&Ps[0]<=127)return Ps;if(Ps.length<=55)return Ps.unshift(128+Ps.length),Ps;const Hs=arrayifyInteger(Ps.length);return Hs.unshift(183+Hs.length),Hs.concat(Ps)}const nibbles="0123456789abcdef";function encodeRlp(Fs){let Ps="0x";for(const Hs of _encode(Fs))Ps+=nibbles[Hs>>4],Ps+=nibbles[Hs&15];return Ps}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(Fs,Ps){let Hs=18;if(typeof Ps=="string"){const Ws=names.indexOf(Ps);assertArgument(Ws>=0,"invalid unit","unit",Ps),Hs=3*Ws}else Ps!=null&&(Hs=getNumber(Ps,"unit"));return FixedNumber.fromValue(Fs,Hs,{decimals:Hs,width:512}).toString()}function parseUnits$1(Fs,Ps){assertArgument(typeof Fs=="string","value must be a string","value",Fs);let Hs=18;if(typeof Ps=="string"){const Ws=names.indexOf(Ps);assertArgument(Ws>=0,"invalid unit","unit",Ps),Hs=3*Ws}else Ps!=null&&(Hs=getNumber(Ps,"unit"));return FixedNumber.fromString(Fs,{decimals:Hs,width:512}).value}const WordSize=32,Padding=new Uint8Array(WordSize),passProperties$1=["then"],_guard$2={},resultNames=new WeakMap;function getNames(Fs){return resultNames.get(Fs)}function setNames(Fs,Ps){resultNames.set(Fs,Ps)}function throwError(Fs,Ps){const Hs=new Error(`deferred error during ABI decoding triggered accessing ${Fs}`);throw Hs.error=Ps,Hs}function toObject(Fs,Ps,Hs){return Fs.indexOf(null)>=0?Ps.map((Ws,Zs)=>Ws instanceof Result$1?toObject(getNames(Ws),Ws,Hs):Ws):Fs.reduce((Ws,Zs,zs)=>{let Ys=Ps.getValue(Zs);return Zs in Ws||(Hs&&Ys instanceof Result$1&&(Ys=toObject(getNames(Ys),Ys,Hs)),Ws[Zs]=Ys),Ws},{})}let Result$1=class mh extends Array{#e;constructor(...Ps){const Hs=Ps[0];let Ws=Ps[1],Zs=(Ps[2]||[]).slice(),zs=!0;Hs!==_guard$2&&(Ws=Ps,Zs=[],zs=!1),super(Ws.length),Ws.forEach((Xs,Ma)=>{this[Ma]=Xs});const Ys=Zs.reduce((Xs,Ma)=>(typeof Ma=="string"&&Xs.set(Ma,(Xs.get(Ma)||0)+1),Xs),new Map);if(setNames(this,Object.freeze(Ws.map((Xs,Ma)=>{const qs=Zs[Ma];return qs!=null&&Ys.get(qs)===1?qs:null}))),this.#e=[],this.#e==null&&this.#e,!zs)return;Object.freeze(this);const Va=new Proxy(this,{get:(Xs,Ma,qs)=>{if(typeof Ma=="string"){if(Ma.match(/^[0-9]+$/)){const Mc=getNumber(Ma,"%index");if(Mc<0||Mc>=this.length)throw new RangeError("out of result range");const ol=Xs[Mc];return ol instanceof Error&&throwError(`index ${Mc}`,ol),ol}if(passProperties$1.indexOf(Ma)>=0)return Reflect.get(Xs,Ma,qs);const Js=Xs[Ma];if(Js instanceof Function)return function(...Mc){return Js.apply(this===qs?Xs:this,Mc)};if(!(Ma in Xs))return Xs.getValue.apply(this===qs?Xs:this,[Ma])}return Reflect.get(Xs,Ma,qs)}});return setNames(Va,getNames(this)),Va}toArray(Ps){const Hs=[];return this.forEach((Ws,Zs)=>{Ws instanceof Error&&throwError(`index ${Zs}`,Ws),Ps&&Ws instanceof mh&&(Ws=Ws.toArray(Ps)),Hs.push(Ws)}),Hs}toObject(Ps){const Hs=getNames(this);return Hs.reduce((Ws,Zs,zs)=>(assert(Zs!=null,`value at index ${zs} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),toObject(Hs,this,Ps)),{})}slice(Ps,Hs){Ps==null&&(Ps=0),Ps<0&&(Ps+=this.length,Ps<0&&(Ps=0)),Hs==null&&(Hs=this.length),Hs<0&&(Hs+=this.length,Hs<0&&(Hs=0)),Hs>this.length&&(Hs=this.length);const Ws=getNames(this),Zs=[],zs=[];for(let Ys=Ps;Ys<Hs;Ys++)Zs.push(this[Ys]),zs.push(Ws[Ys]);return new mh(_guard$2,Zs,zs)}filter(Ps,Hs){const Ws=getNames(this),Zs=[],zs=[];for(let Ys=0;Ys<this.length;Ys++){const Va=this[Ys];Va instanceof Error&&throwError(`index ${Ys}`,Va),Ps.call(Hs,Va,Ys,this)&&(Zs.push(Va),zs.push(Ws[Ys]))}return new mh(_guard$2,Zs,zs)}map(Ps,Hs){const Ws=[];for(let Zs=0;Zs<this.length;Zs++){const zs=this[Zs];zs instanceof Error&&throwError(`index ${Zs}`,zs),Ws.push(Ps.call(Hs,zs,Zs,this))}return Ws}getValue(Ps){const Hs=getNames(this).indexOf(Ps);if(Hs===-1)return;const Ws=this[Hs];return Ws instanceof Error&&throwError(`property ${JSON.stringify(Ps)}`,Ws.error),Ws}static fromItems(Ps,Hs){return new mh(_guard$2,Ps,Hs)}};function getValue$1(Fs){let Ps=toBeArray(Fs);return assert(Ps.length<=WordSize,"value out-of-bounds","BUFFER_OVERRUN",{buffer:Ps,length:WordSize,offset:Ps.length}),Ps.length!==WordSize&&(Ps=getBytesCopy(concat([Padding.slice(Ps.length%WordSize),Ps]))),Ps}class Coder{name;type;localName;dynamic;constructor(Ps,Hs,Ws,Zs){defineProperties(this,{name:Ps,type:Hs,localName:Ws,dynamic:Zs},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(Ps,Hs){assertArgument(!1,Ps,this.localName,Hs)}}class Writer{#e;#t;constructor(){this.#e=[],this.#t=0}get data(){return concat(this.#e)}get length(){return this.#t}#r(Ps){return this.#e.push(Ps),this.#t+=Ps.length,Ps.length}appendWriter(Ps){return this.#r(getBytesCopy(Ps.data))}writeBytes(Ps){let Hs=getBytesCopy(Ps);const Ws=Hs.length%WordSize;return Ws&&(Hs=getBytesCopy(concat([Hs,Padding.slice(Ws)]))),this.#r(Hs)}writeValue(Ps){return this.#r(getValue$1(Ps))}writeUpdatableValue(){const Ps=this.#e.length;return this.#e.push(Padding),this.#t+=WordSize,Hs=>{this.#e[Ps]=getValue$1(Hs)}}}class Reader{allowLoose;#e;#t;#r;#n;#o;constructor(Ps,Hs,Ws){defineProperties(this,{allowLoose:!!Hs}),this.#e=getBytesCopy(Ps),this.#r=0,this.#n=null,this.#o=Ws??1024,this.#t=0}get data(){return hexlify(this.#e)}get dataLength(){return this.#e.length}get consumed(){return this.#t}get bytes(){return new Uint8Array(this.#e)}#s(Ps){if(this.#n)return this.#n.#s(Ps);this.#r+=Ps,assert(this.#o<1||this.#r<=this.#o*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#o} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:getBytesCopy(this.#e),offset:this.#t,length:Ps,info:{bytesRead:this.#r,dataLength:this.dataLength}})}#i(Ps,Hs,Ws){let Zs=Math.ceil(Hs/WordSize)*WordSize;return this.#t+Zs>this.#e.length&&(this.allowLoose&&Ws&&this.#t+Hs<=this.#e.length?Zs=Hs:assert(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#e),length:this.#e.length,offset:this.#t+Zs})),this.#e.slice(this.#t,this.#t+Zs)}subReader(Ps){const Hs=new Reader(this.#e.slice(this.#t+Ps),this.allowLoose,this.#o);return Hs.#n=this,Hs}readBytes(Ps,Hs){let Ws=this.#i(0,Ps,!!Hs);return this.#s(Ps),this.#t+=Ws.length,Ws.slice(0,Ps)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function number(Fs){if(!Number.isSafeInteger(Fs)||Fs<0)throw new Error(`Wrong positive integer: ${Fs}`)}function bytes(Fs,...Ps){if(!(Fs instanceof Uint8Array))throw new Error("Expected Uint8Array");if(Ps.length>0&&!Ps.includes(Fs.length))throw new Error(`Expected Uint8Array of length ${Ps}, not of length=${Fs.length}`)}function hash(Fs){if(typeof Fs!="function"||typeof Fs.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(Fs.outputLen),number(Fs.blockLen)}function exists(Fs,Ps=!0){if(Fs.destroyed)throw new Error("Hash instance has been destroyed");if(Ps&&Fs.finished)throw new Error("Hash#digest() has already been called")}function output(Fs,Ps){bytes(Fs);const Hs=Ps.outputLen;if(Fs.length<Hs)throw new Error(`digestInto() expects output buffer of length at least ${Hs}`)}const crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$1=Fs=>Fs instanceof Uint8Array,u32=Fs=>new Uint32Array(Fs.buffer,Fs.byteOffset,Math.floor(Fs.byteLength/4)),createView=Fs=>new DataView(Fs.buffer,Fs.byteOffset,Fs.byteLength),rotr=(Fs,Ps)=>Fs<<32-Ps|Fs>>>Ps,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$1(Fs){if(typeof Fs!="string")throw new Error(`utf8ToBytes expected string, got ${typeof Fs}`);return new Uint8Array(new TextEncoder().encode(Fs))}function toBytes(Fs){if(typeof Fs=="string"&&(Fs=utf8ToBytes$1(Fs)),!u8a$1(Fs))throw new Error(`expected Uint8Array, got ${typeof Fs}`);return Fs}function concatBytes$1(...Fs){const Ps=new Uint8Array(Fs.reduce((Ws,Zs)=>Ws+Zs.length,0));let Hs=0;return Fs.forEach(Ws=>{if(!u8a$1(Ws))throw new Error("Uint8Array expected");Ps.set(Ws,Hs),Hs+=Ws.length}),Ps}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(Fs){const Ps=Ws=>Fs().update(toBytes(Ws)).digest(),Hs=Fs();return Ps.outputLen=Hs.outputLen,Ps.blockLen=Hs.blockLen,Ps.create=()=>Fs(),Ps}function randomBytes(Fs=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(Fs));throw new Error("crypto.getRandomValues must be defined")}class HMAC extends Hash{constructor(Ps,Hs){super(),this.finished=!1,this.destroyed=!1,hash(Ps);const Ws=toBytes(Hs);if(this.iHash=Ps.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const Zs=this.blockLen,zs=new Uint8Array(Zs);zs.set(Ws.length>Zs?Ps.create().update(Ws).digest():Ws);for(let Ys=0;Ys<zs.length;Ys++)zs[Ys]^=54;this.iHash.update(zs),this.oHash=Ps.create();for(let Ys=0;Ys<zs.length;Ys++)zs[Ys]^=106;this.oHash.update(zs),zs.fill(0)}update(Ps){return exists(this),this.iHash.update(Ps),this}digestInto(Ps){exists(this),bytes(Ps,this.outputLen),this.finished=!0,this.iHash.digestInto(Ps),this.oHash.update(Ps),this.oHash.digestInto(Ps),this.destroy()}digest(){const Ps=new Uint8Array(this.oHash.outputLen);return this.digestInto(Ps),Ps}_cloneInto(Ps){Ps||(Ps=Object.create(Object.getPrototypeOf(this),{}));const{oHash:Hs,iHash:Ws,finished:Zs,destroyed:zs,blockLen:Ys,outputLen:Va}=this;return Ps=Ps,Ps.finished=Zs,Ps.destroyed=zs,Ps.blockLen=Ys,Ps.outputLen=Va,Ps.oHash=Hs._cloneInto(Ps.oHash),Ps.iHash=Ws._cloneInto(Ps.iHash),Ps}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(Fs,Ps,Hs)=>new HMAC(Fs,Ps).update(Hs).digest();hmac.create=(Fs,Ps)=>new HMAC(Fs,Ps);function setBigUint64(Fs,Ps,Hs,Ws){if(typeof Fs.setBigUint64=="function")return Fs.setBigUint64(Ps,Hs,Ws);const Zs=BigInt(32),zs=BigInt(4294967295),Ys=Number(Hs>>Zs&zs),Va=Number(Hs&zs),Xs=Ws?4:0,Ma=Ws?0:4;Fs.setUint32(Ps+Xs,Ys,Ws),Fs.setUint32(Ps+Ma,Va,Ws)}class SHA2 extends Hash{constructor(Ps,Hs,Ws,Zs){super(),this.blockLen=Ps,this.outputLen=Hs,this.padOffset=Ws,this.isLE=Zs,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(Ps),this.view=createView(this.buffer)}update(Ps){exists(this);const{view:Hs,buffer:Ws,blockLen:Zs}=this;Ps=toBytes(Ps);const zs=Ps.length;for(let Ys=0;Ys<zs;){const Va=Math.min(Zs-this.pos,zs-Ys);if(Va===Zs){const Xs=createView(Ps);for(;Zs<=zs-Ys;Ys+=Zs)this.process(Xs,Ys);continue}Ws.set(Ps.subarray(Ys,Ys+Va),this.pos),this.pos+=Va,Ys+=Va,this.pos===Zs&&(this.process(Hs,0),this.pos=0)}return this.length+=Ps.length,this.roundClean(),this}digestInto(Ps){exists(this),output(Ps,this),this.finished=!0;const{buffer:Hs,view:Ws,blockLen:Zs,isLE:zs}=this;let{pos:Ys}=this;Hs[Ys++]=128,this.buffer.subarray(Ys).fill(0),this.padOffset>Zs-Ys&&(this.process(Ws,0),Ys=0);for(let Js=Ys;Js<Zs;Js++)Hs[Js]=0;setBigUint64(Ws,Zs-8,BigInt(this.length*8),zs),this.process(Ws,0);const Va=createView(Ps),Xs=this.outputLen;if(Xs%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const Ma=Xs/4,qs=this.get();if(Ma>qs.length)throw new Error("_sha2: outputLen bigger than state");for(let Js=0;Js<Ma;Js++)Va.setUint32(4*Js,qs[Js],zs)}digest(){const{buffer:Ps,outputLen:Hs}=this;this.digestInto(Ps);const Ws=Ps.slice(0,Hs);return this.destroy(),Ws}_cloneInto(Ps){Ps||(Ps=new this.constructor),Ps.set(...this.get());const{blockLen:Hs,buffer:Ws,length:Zs,finished:zs,destroyed:Ys,pos:Va}=this;return Ps.length=Zs,Ps.pos=Va,Ps.finished=zs,Ps.destroyed=Ys,Zs%Hs&&Ps.buffer.set(Ws),Ps}}const Chi=(Fs,Ps,Hs)=>Fs&Ps^~Fs&Hs,Maj=(Fs,Ps,Hs)=>Fs&Ps^Fs&Hs^Ps&Hs,SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:Ps,B:Hs,C:Ws,D:Zs,E:zs,F:Ys,G:Va,H:Xs}=this;return[Ps,Hs,Ws,Zs,zs,Ys,Va,Xs]}set(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs){this.A=Ps|0,this.B=Hs|0,this.C=Ws|0,this.D=Zs|0,this.E=zs|0,this.F=Ys|0,this.G=Va|0,this.H=Xs|0}process(Ps,Hs){for(let Js=0;Js<16;Js++,Hs+=4)SHA256_W[Js]=Ps.getUint32(Hs,!1);for(let Js=16;Js<64;Js++){const Mc=SHA256_W[Js-15],ol=SHA256_W[Js-2],Vc=rotr(Mc,7)^rotr(Mc,18)^Mc>>>3,Dc=rotr(ol,17)^rotr(ol,19)^ol>>>10;SHA256_W[Js]=Dc+SHA256_W[Js-7]+Vc+SHA256_W[Js-16]|0}let{A:Ws,B:Zs,C:zs,D:Ys,E:Va,F:Xs,G:Ma,H:qs}=this;for(let Js=0;Js<64;Js++){const Mc=rotr(Va,6)^rotr(Va,11)^rotr(Va,25),ol=qs+Mc+Chi(Va,Xs,Ma)+SHA256_K[Js]+SHA256_W[Js]|0,Dc=(rotr(Ws,2)^rotr(Ws,13)^rotr(Ws,22))+Maj(Ws,Zs,zs)|0;qs=Ma,Ma=Xs,Xs=Va,Va=Ys+ol|0,Ys=zs,zs=Zs,Zs=Ws,Ws=ol+Dc|0}Ws=Ws+this.A|0,Zs=Zs+this.B|0,zs=zs+this.C|0,Ys=Ys+this.D|0,Va=Va+this.E|0,Xs=Xs+this.F|0,Ma=Ma+this.G|0,qs=qs+this.H|0,this.set(Ws,Zs,zs,Ys,Va,Xs,Ma,qs)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256),U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(Fs,Ps=!1){return Ps?{h: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2**32|0)|0,add5L=(Fs,Ps,Hs,Ws,Zs)=>(Fs>>>0)+(Ps>>>0)+(Hs>>>0)+(Ws>>>0)+(Zs>>>0),add5H=(Fs,Ps,Hs,Ws,Zs,zs)=>Ps+Hs+Ws+Zs+zs+(Fs/2**32|0)|0,u64={fromBig,split:split$1,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L},[SHA512_Kh,SHA512_Kl]=u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(Fs=>BigInt(Fs))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:Ps,Al:Hs,Bh:Ws,Bl:Zs,Ch:zs,Cl:Ys,Dh:Va,Dl:Xs,Eh:Ma,El:qs,Fh:Js,Fl:Mc,Gh:ol,Gl:Vc,Hh:Dc,Hl:sl}=this;return[Ps,Hs,Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl]}set(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl){this.Ah=Ps|0,this.Al=Hs|0,this.Bh=Ws|0,this.Bl=Zs|0,this.Ch=zs|0,this.Cl=Ys|0,this.Dh=Va|0,this.Dl=Xs|0,this.Eh=Ma|0,this.El=qs|0,this.Fh=Js|0,this.Fl=Mc|0,this.Gh=ol|0,this.Gl=Vc|0,this.Hh=Dc|0,this.Hl=sl|0}process(Ps,Hs){for(let pl=0;pl<16;pl++,Hs+=4)SHA512_W_H[pl]=Ps.getUint32(Hs),SHA512_W_L[pl]=Ps.getUint32(Hs+=4);for(let pl=16;pl<80;pl++){const gl=SHA512_W_H[pl-15]|0,yl=SHA512_W_L[pl-15]|0,bl=u64.rotrSH(gl,yl,1)^u64.rotrSH(gl,yl,8)^u64.shrSH(gl,yl,7),Il=u64.rotrSL(gl,yl,1)^u64.rotrSL(gl,yl,8)^u64.shrSL(gl,yl,7),$l=SHA512_W_H[pl-2]|0,vl=SHA512_W_L[pl-2]|0,Sl=u64.rotrSH($l,vl,19)^u64.rotrBH($l,vl,61)^u64.shrSH($l,vl,6),fl=u64.rotrSL($l,vl,19)^u64.rotrBL($l,vl,61)^u64.shrSL($l,vl,6),Hc=u64.add4L(Il,fl,SHA512_W_L[pl-7],SHA512_W_L[pl-16]),tl=u64.add4H(Hc,bl,Sl,SHA512_W_H[pl-7],SHA512_W_H[pl-16]);SHA512_W_H[pl]=tl|0,SHA512_W_L[pl]=Hc|0}let{Ah:Ws,Al:Zs,Bh:zs,Bl:Ys,Ch:Va,Cl:Xs,Dh:Ma,Dl:qs,Eh:Js,El:Mc,Fh:ol,Fl:Vc,Gh:Dc,Gl:sl,Hh:ll,Hl:hl}=this;for(let pl=0;pl<80;pl++){const gl=u64.rotrSH(Js,Mc,14)^u64.rotrSH(Js,Mc,18)^u64.rotrBH(Js,Mc,41),yl=u64.rotrSL(Js,Mc,14)^u64.rotrSL(Js,Mc,18)^u64.rotrBL(Js,Mc,41),bl=Js&ol^~Js&Dc,Il=Mc&Vc^~Mc&sl,$l=u64.add5L(hl,yl,Il,SHA512_Kl[pl],SHA512_W_L[pl]),vl=u64.add5H($l,ll,gl,bl,SHA512_Kh[pl],SHA512_W_H[pl]),Sl=$l|0,fl=u64.rotrSH(Ws,Zs,28)^u64.rotrBH(Ws,Zs,34)^u64.rotrBH(Ws,Zs,39),Hc=u64.rotrSL(Ws,Zs,28)^u64.rotrBL(Ws,Zs,34)^u64.rotrBL(Ws,Zs,39),tl=Ws&zs^Ws&Va^zs&Va,nl=Zs&Ys^Zs&Xs^Ys&Xs;ll=Dc|0,hl=sl|0,Dc=ol|0,sl=Vc|0,ol=Js|0,Vc=Mc|0,{h:Js,l:Mc}=u64.add(Ma|0,qs|0,vl|0,Sl|0),Ma=Va|0,qs=Xs|0,Va=zs|0,Xs=Ys|0,zs=Ws|0,Ys=Zs|0;const rl=u64.add3L(Sl,Hc,nl);Ws=u64.add3H(rl,vl,fl,tl),Zs=rl|0}({h:Ws,l:Zs}=u64.add(this.Ah|0,this.Al|0,Ws|0,Zs|0)),{h:zs,l:Ys}=u64.add(this.Bh|0,this.Bl|0,zs|0,Ys|0),{h:Va,l:Xs}=u64.add(this.Ch|0,this.Cl|0,Va|0,Xs|0),{h:Ma,l:qs}=u64.add(this.Dh|0,this.Dl|0,Ma|0,qs|0),{h:Js,l:Mc}=u64.add(this.Eh|0,this.El|0,Js|0,Mc|0),{h:ol,l:Vc}=u64.add(this.Fh|0,this.Fl|0,ol|0,Vc|0),{h:Dc,l:sl}=u64.add(this.Gh|0,this.Gl|0,Dc|0,sl|0),{h:ll,l:hl}=u64.add(this.Hh|0,this.Hl|0,ll|0,hl|0),this.set(Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl,ll,hl)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512=wrapConstructor(()=>new SHA512);function getGlobal(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global$1<"u")return global$1;throw new Error("unable to locate global object")}const anyGlobal=getGlobal();anyGlobal.crypto||anyGlobal.msCrypto;function createHash(Fs){switch(Fs){case"sha256":return sha256$1.create();case"sha512":return sha512.create()}assertArgument(!1,"invalid hashing algorithm name","algorithm",Fs)}const[SHA3_PI,SHA3_RO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){for(let Va=0;Va<10;Va++)Hs[Va]=Fs[Ys+Va];for(let Va=0;Va<10;Va++)Fs[Ys+Va]^=~Hs[(Va+2)%10]&Hs[(Va+4)%10]}Fs[0]^=SHA3_IOTA_H[Ws],Fs[1]^=SHA3_IOTA_L[Ws]}Hs.fill(0)}class Keccak extends Hash{constructor(Ps,Hs,Ws,Zs=!1,zs=24){if(super(),this.blockLen=Ps,this.suffix=Hs,this.outputLen=Ws,this.enableXOF=Zs,this.rounds=zs,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,number(Ws),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds),this.posOut=0,this.pos=0}update(Ps){exists(this);const{blockLen:Hs,state:Ws}=this;Ps=toBytes(Ps);const Zs=Ps.length;for(let zs=0;zs<Zs;){const Ys=Math.min(Hs-this.pos,Zs-zs);for(let Va=0;Va<Ys;Va++)Ws[this.pos++]^=Ps[zs++];this.pos===Hs&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:Ps,suffix:Hs,pos:Ws,blockLen:Zs}=this;Ps[Ws]^=Hs,(Hs&128)!==0&&Ws===Zs-1&&this.keccak(),Ps[Zs-1]^=128,this.keccak()}writeInto(Ps){exists(this,!1),bytes(Ps),this.finish();const Hs=this.state,{blockLen:Ws}=this;for(let Zs=0,zs=Ps.length;Zs<zs;){this.posOut>=Ws&&this.keccak();const Ys=Math.min(Ws-this.posOut,zs-Zs);Ps.set(Hs.subarray(this.posOut,this.posOut+Ys),Zs),this.posOut+=Ys,Zs+=Ys}return Ps}xofInto(Ps){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(Ps)}xof(Ps){return number(Ps),this.xofInto(new Uint8Array(Ps))}digestInto(Ps){if(output(Ps,this),this.finished)throw new Error("digest() was already called");return this.writeInto(Ps),this.destroy(),Ps}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(Ps){const{blockLen:Hs,suffix:Ws,outputLen:Zs,rounds:zs,enableXOF:Ys}=this;return Ps||(Ps=new Keccak(Hs,Ws,Zs,Ys,zs)),Ps.state32.set(this.state32),Ps.pos=this.pos,Ps.posOut=this.posOut,Ps.finished=this.finished,Ps.rounds=zs,Ps.suffix=Ws,Ps.outputLen=Zs,Ps.enableXOF=Ys,Ps.destroyed=this.destroyed,Ps}}const gen=(Fs,Ps,Hs)=>wrapConstructor(()=>new Keccak(Ps,Fs,Hs)),keccak_256=gen(1,136,256/8);let locked=!1;const _keccak256=function(Fs){return keccak_256(Fs)};let __keccak256=_keccak256;function keccak256(Fs){const Ps=getBytes(Fs,"data");return hexlify(__keccak256(Ps))}keccak256._=_keccak256,keccak256.lock=function(){locked=!0},keccak256.register=function(Fs){if(locked)throw new TypeError("keccak256 is locked");__keccak256=Fs},Object.freeze(keccak256);const _sha256=function(Fs){return createHash("sha256").update(Fs).digest()};let __sha256=_sha256,locked256=!1;function sha256(Fs){const Ps=getBytes(Fs,"data");return hexlify(__sha256(Ps))}sha256._=_sha256,sha256.lock=function(){locked256=!0},sha256.register=function(Fs){if(locked256)throw new Error("sha256 is locked");__sha256=Fs},Object.freeze(sha256),Object.freeze(sha256);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),u8a=Fs=>Fs instanceof Uint8Array,hexes=Array.from({length:256},(Fs,Ps)=>Ps.toString(16).padStart(2,"0"));function bytesToHex(Fs){if(!u8a(Fs))throw new Error("Uint8Array expected");let Ps="";for(let Hs=0;Hs<Fs.length;Hs++)Ps+=hexes[Fs[Hs]];return Ps}function numberToHexUnpadded(Fs){const Ps=Fs.toString(16);return Ps.length&1?`0${Ps}`:Ps}function hexToNumber(Fs){if(typeof Fs!="string")throw new Error("hex string expected, got "+typeof Fs);return BigInt(Fs===""?"0":`0x${Fs}`)}function hexToBytes(Fs){if(typeof Fs!="string")throw new Error("hex string expected, got "+typeof Fs);const Ps=Fs.length;if(Ps%2)throw new Error("padded hex string expected, got unpadded hex of length "+Ps);const Hs=new Uint8Array(Ps/2);for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Ws*2,zs=Fs.slice(Zs,Zs+2),Ys=Number.parseInt(zs,16);if(Number.isNaN(Ys)||Ys<0)throw new Error("Invalid byte sequence");Hs[Ws]=Ys}return Hs}function bytesToNumberBE(Fs){return hexToNumber(bytesToHex(Fs))}function bytesToNumberLE(Fs){if(!u8a(Fs))throw new Error("Uint8Array expected");return hexToNumber(bytesToHex(Uint8Array.from(Fs).reverse()))}function numberToBytesBE(Fs,Ps){return hexToBytes(Fs.toString(16).padStart(Ps*2,"0"))}function numberToBytesLE(Fs,Ps){return numberToBytesBE(Fs,Ps).reverse()}function numberToVarBytesBE(Fs){return hexToBytes(numberToHexUnpadded(Fs))}function ensureBytes(Fs,Ps,Hs){let Ws;if(typeof Ps=="string")try{Ws=hexToBytes(Ps)}catch(zs){throw new Error(`${Fs} must be valid hex string, got "${Ps}". Cause: ${zs}`)}else if(u8a(Ps))Ws=Uint8Array.from(Ps);else throw new Error(`${Fs} must be hex string or Uint8Array`);const Zs=Ws.length;if(typeof Hs=="number"&&Zs!==Hs)throw new Error(`${Fs} expected ${Hs} bytes, got ${Zs}`);return Ws}function concatBytes(...Fs){const Ps=new Uint8Array(Fs.reduce((Ws,Zs)=>Ws+Zs.length,0));let Hs=0;return Fs.forEach(Ws=>{if(!u8a(Ws))throw new Error("Uint8Array expected");Ps.set(Ws,Hs),Hs+=Ws.length}),Ps}function equalBytes(Fs,Ps){if(Fs.length!==Ps.length)return!1;for(let Hs=0;Hs<Fs.length;Hs++)if(Fs[Hs]!==Ps[Hs])return!1;return!0}function utf8ToBytes(Fs){if(typeof Fs!="string")throw new Error(`utf8ToBytes expected string, got ${typeof Fs}`);return new Uint8Array(new TextEncoder().encode(Fs))}function bitLen(Fs){let Ps;for(Ps=0;Fs>_0n$3;Fs>>=_1n$4,Ps+=1);return Ps}function bitGet(Fs,Ps){return Fs>>BigInt(Ps)&_1n$4}const bitSet=(Fs,Ps,Hs)=>Fs|(Hs?_1n$4:_0n$3)<<BigInt(Ps),bitMask=Fs=>(_2n$2<<BigInt(Fs-1))-_1n$4,u8n=Fs=>new Uint8Array(Fs),u8fr=Fs=>Uint8Array.from(Fs);function createHmacDrbg(Fs,Ps,Hs){if(typeof Fs!="number"||Fs<2)throw new Error("hashLen must be a number");if(typeof Ps!="number"||Ps<2)throw new Error("qByteLen must be a number");if(typeof Hs!="function")throw new Error("hmacFn must be a function");let Ws=u8n(Fs),Zs=u8n(Fs),zs=0;const Ys=()=>{Ws.fill(1),Zs.fill(0),zs=0},Va=(...Js)=>Hs(Zs,Ws,...Js),Xs=(Js=u8n())=>{Zs=Va(u8fr([0]),Js),Ws=Va(),Js.length!==0&&(Zs=Va(u8fr([1]),Js),Ws=Va())},Ma=()=>{if(zs++>=1e3)throw new Error("drbg: tried 1000 values");let Js=0;const Mc=[];for(;Js<Ps;){Ws=Va();const ol=Ws.slice();Mc.push(ol),Js+=Ws.length}return concatBytes(...Mc)};return(Js,Mc)=>{Ys(),Xs(Js);let ol;for(;!(ol=Mc(Ma()));)Xs();return Ys(),ol}}const validatorFns={bigint:Fs=>typeof Fs=="bigint",function:Fs=>typeof Fs=="function",boolean:Fs=>typeof Fs=="boolean",string:Fs=>typeof Fs=="string",stringOrUint8Array:Fs=>typeof Fs=="string"||Fs instanceof Uint8Array,isSafeInteger:Fs=>Number.isSafeInteger(Fs),array:Fs=>Array.isArray(Fs),field:(Fs,Ps)=>Ps.Fp.isValid(Fs),hash:Fs=>typeof Fs=="function"&&Number.isSafeInteger(Fs.outputLen)};function validateObject(Fs,Ps,Hs={}){const Ws=(Zs,zs,Ys)=>{const Va=validatorFns[zs];if(typeof Va!="function")throw new Error(`Invalid validator "${zs}", expected function`);const Xs=Fs[Zs];if(!(Ys&&Xs===void 0)&&!Va(Xs,Fs))throw new Error(`Invalid param ${String(Zs)}=${Xs} (${typeof Xs}), expected ${zs}`)};for(const[Zs,zs]of Object.entries(Ps))Ws(Zs,zs,!1);for(const[Zs,zs]of Object.entries(Hs))Ws(Zs,zs,!0);return Fs}const ut=Object.freeze(Object.defineProperty({__proto__:null,bitGet,bitLen,bitMask,bitSet,bytesToHex,bytesToNumberBE,bytesToNumberLE,concatBytes,createHmacDrbg,ensureBytes,equalBytes,hexToBytes,hexToNumber,numberToBytesBE,numberToBytesLE,numberToHexUnpadded,numberToVarBytesBE,utf8ToBytes,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$3=BigInt(1),_2n$1=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);BigInt(9),BigInt(16);function mod(Fs,Ps){const Hs=Fs%Ps;return Hs>=_0n$2?Hs:Ps+Hs}function pow(Fs,Ps,Hs){if(Hs<=_0n$2||Ps<_0n$2)throw new Error("Expected power/modulo > 0");if(Hs===_1n$3)return _0n$2;let Ws=_1n$3;for(;Ps>_0n$2;)Ps&_1n$3&&(Ws=Ws*Fs%Hs),Fs=Fs*Fs%Hs,Ps>>=_1n$3;return Ws}function pow2(Fs,Ps,Hs){let Ws=Fs;for(;Ps-- >_0n$2;)Ws*=Ws,Ws%=Hs;return Ws}function invert(Fs,Ps){if(Fs===_0n$2||Ps<=_0n$2)throw new Error(`invert: expected positive integers, got n=${Fs} mod=${Ps}`);let Hs=mod(Fs,Ps),Ws=Ps,Zs=_0n$2,zs=_1n$3;for(;Hs!==_0n$2;){const Va=Ws/Hs,Xs=Ws%Hs,Ma=Zs-zs*Va;Ws=Hs,Hs=Xs,Zs=zs,zs=Ma}if(Ws!==_1n$3)throw new Error("invert: does not exist");return mod(Zs,Ps)}function tonelliShanks(Fs){const Ps=(Fs-_1n$3)/_2n$1;let Hs,Ws,Zs;for(Hs=Fs-_1n$3,Ws=0;Hs%_2n$1===_0n$2;Hs/=_2n$1,Ws++);for(Zs=_2n$1;Zs<Fs&&pow(Zs,Ps,Fs)!==Fs-_1n$3;Zs++);if(Ws===1){const Ys=(Fs+_1n$3)/_4n;return function(Xs,Ma){const qs=Xs.pow(Ma,Ys);if(!Xs.eql(Xs.sqr(qs),Ma))throw new Error("Cannot find square root");return qs}}const zs=(Hs+_1n$3)/_2n$1;return function(Va,Xs){if(Va.pow(Xs,Ps)===Va.neg(Va.ONE))throw new Error("Cannot find square root");let Ma=Ws,qs=Va.pow(Va.mul(Va.ONE,Zs),Hs),Js=Va.pow(Xs,zs),Mc=Va.pow(Xs,Hs);for(;!Va.eql(Mc,Va.ONE);){if(Va.eql(Mc,Va.ZERO))return Va.ZERO;let ol=1;for(let Dc=Va.sqr(Mc);ol<Ma&&!Va.eql(Dc,Va.ONE);ol++)Dc=Va.sqr(Dc);const Vc=Va.pow(qs,_1n$3<<BigInt(Ma-ol-1));qs=Va.sqr(Vc),Js=Va.mul(Js,Vc),Mc=Va.mul(Mc,qs),Ma=ol}return Js}}function FpSqrt(Fs){if(Fs%_4n===_3n$1){const Ps=(Fs+_1n$3)/_4n;return function(Ws,Zs){const zs=Ws.pow(Zs,Ps);if(!Ws.eql(Ws.sqr(zs),Zs))throw new Error("Cannot find square root");return zs}}if(Fs%_8n===_5n){const Ps=(Fs-_5n)/_8n;return function(Ws,Zs){const zs=Ws.mul(Zs,_2n$1),Ys=Ws.pow(zs,Ps),Va=Ws.mul(Zs,Ys),Xs=Ws.mul(Ws.mul(Va,_2n$1),Ys),Ma=Ws.mul(Va,Ws.sub(Xs,Ws.ONE));if(!Ws.eql(Ws.sqr(Ma),Zs))throw new Error("Cannot find square root");return Ma}}return tonelliShanks(Fs)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(Fs){const Ps={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Hs=FIELD_FIELDS.reduce((Ws,Zs)=>(Ws[Zs]="function",Ws),Ps);return validateObject(Fs,Hs)}function FpPow(Fs,Ps,Hs){if(Hs<_0n$2)throw new Error("Expected power > 0");if(Hs===_0n$2)return Fs.ONE;if(Hs===_1n$3)return Ps;let Ws=Fs.ONE,Zs=Ps;for(;Hs>_0n$2;)Hs&_1n$3&&(Ws=Fs.mul(Ws,Zs)),Zs=Fs.sqr(Zs),Hs>>=_1n$3;return Ws}function FpInvertBatch(Fs,Ps){const Hs=new Array(Ps.length),Ws=Ps.reduce((zs,Ys,Va)=>Fs.is0(Ys)?zs:(Hs[Va]=zs,Fs.mul(zs,Ys)),Fs.ONE),Zs=Fs.inv(Ws);return Ps.reduceRight((zs,Ys,Va)=>Fs.is0(Ys)?zs:(Hs[Va]=Fs.mul(zs,Hs[Va]),Fs.mul(zs,Ys)),Zs),Hs}function nLength(Fs,Ps){const Hs=Ps!==void 0?Ps:Fs.toString(2).length,Ws=Math.ceil(Hs/8);return{nBitLength:Hs,nByteLength:Ws}}function Field(Fs,Ps,Hs=!1,Ws={}){if(Fs<=_0n$2)throw new Error(`Expected Field ORDER > 0, got ${Fs}`);const{nBitLength:Zs,nByteLength:zs}=nLength(Fs,Ps);if(zs>2048)throw new Error("Field lengths over 2048 bytes are not supported");const Ys=FpSqrt(Fs),Va=Object.freeze({ORDER:Fs,BITS:Zs,BYTES:zs,MASK:bitMask(Zs),ZERO:_0n$2,ONE:_1n$3,create:Xs=>mod(Xs,Fs),isValid:Xs=>{if(typeof Xs!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof Xs}`);return _0n$2<=Xs&&Xs<Fs},is0:Xs=>Xs===_0n$2,isOdd:Xs=>(Xs&_1n$3)===_1n$3,neg:Xs=>mod(-Xs,Fs),eql:(Xs,Ma)=>Xs===Ma,sqr:Xs=>mod(Xs*Xs,Fs),add:(Xs,Ma)=>mod(Xs+Ma,Fs),sub:(Xs,Ma)=>mod(Xs-Ma,Fs),mul:(Xs,Ma)=>mod(Xs*Ma,Fs),pow:(Xs,Ma)=>FpPow(Va,Xs,Ma),div:(Xs,Ma)=>mod(Xs*invert(Ma,Fs),Fs),sqrN:Xs=>Xs*Xs,addN:(Xs,Ma)=>Xs+Ma,subN:(Xs,Ma)=>Xs-Ma,mulN:(Xs,Ma)=>Xs*Ma,inv:Xs=>invert(Xs,Fs),sqrt:Ws.sqrt||(Xs=>Ys(Va,Xs)),invertBatch:Xs=>FpInvertBatch(Va,Xs),cmov:(Xs,Ma,qs)=>qs?Ma:Xs,toBytes:Xs=>Hs?numberToBytesLE(Xs,zs):numberToBytesBE(Xs,zs),fromBytes:Xs=>{if(Xs.length!==zs)throw new Error(`Fp.fromBytes: expected ${zs}, got ${Xs.length}`);return Hs?bytesToNumberLE(Xs):bytesToNumberBE(Xs)}});return Object.freeze(Va)}function getFieldBytesLength(Fs){if(typeof Fs!="bigint")throw new Error("field order must be bigint");const Ps=Fs.toString(2).length;return Math.ceil(Ps/8)}function getMinHashLength(Fs){const Ps=getFieldBytesLength(Fs);return Ps+Math.ceil(Ps/2)}function mapHashToField(Fs,Ps,Hs=!1){const Ws=Fs.length,Zs=getFieldBytesLength(Ps),zs=getMinHashLength(Ps);if(Ws<16||Ws<zs||Ws>1024)throw new Error(`expected ${zs}-1024 bytes of input, got ${Ws}`);const Ys=Hs?bytesToNumberBE(Fs):bytesToNumberLE(Fs),Va=mod(Ys,Ps-_1n$3)+_1n$3;return Hs?numberToBytesLE(Va,Zs):numberToBytesBE(Va,Zs)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$2=BigInt(1);function wNAF(Fs,Ps){const Hs=(Zs,zs)=>{const Ys=zs.negate();return Zs?Ys:zs},Ws=Zs=>{const zs=Math.ceil(Ps/Zs)+1,Ys=2**(Zs-1);return{windows:zs,windowSize:Ys}};return{constTimeNegate:Hs,unsafeLadder(Zs,zs){let Ys=Fs.ZERO,Va=Zs;for(;zs>_0n$1;)zs&_1n$2&&(Ys=Ys.add(Va)),Va=Va.double(),zs>>=_1n$2;return Ys},precomputeWindow(Zs,zs){const{windows:Ys,windowSize:Va}=Ws(zs),Xs=[];let Ma=Zs,qs=Ma;for(let Js=0;Js<Ys;Js++){qs=Ma,Xs.push(qs);for(let Mc=1;Mc<Va;Mc++)qs=qs.add(Ma),Xs.push(qs);Ma=qs.double()}return Xs},wNAF(Zs,zs,Ys){const{windows:Va,windowSize:Xs}=Ws(Zs);let Ma=Fs.ZERO,qs=Fs.BASE;const Js=BigInt(2**Zs-1),Mc=2**Zs,ol=BigInt(Zs);for(let Vc=0;Vc<Va;Vc++){const Dc=Vc*Xs;let sl=Number(Ys&Js);Ys>>=ol,sl>Xs&&(sl-=Mc,Ys+=_1n$2);const ll=Dc,hl=Dc+Math.abs(sl)-1,pl=Vc%2!==0,gl=sl<0;sl===0?qs=qs.add(Hs(pl,zs[ll])):Ma=Ma.add(Hs(gl,zs[hl]))}return{p:Ma,f:qs}},wNAFCached(Zs,zs,Ys,Va){const Xs=Zs._WINDOW_SIZE||1;let Ma=zs.get(Zs);return Ma||(Ma=this.precomputeWindow(Zs,Xs),Xs!==1&&zs.set(Zs,Va(Ma))),this.wNAF(Xs,Ma,Ys)}}}function validateBasic(Fs){return validateField(Fs.Fp),validateObject(Fs,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(Fs.n,Fs.nBitLength),...Fs,p:Fs.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(Fs){const Ps=validateBasic(Fs);validateObject(Ps,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:Hs,Fp:Ws,a:Zs}=Ps;if(Hs){if(!Ws.eql(Zs,Ws.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof Hs!="object"||typeof Hs.beta!="bigint"||typeof Hs.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...Ps})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER={Err:class extends Error{constructor(Ps=""){super(Ps)}},_parseInt(Fs){const{Err:Ps}=DER;if(Fs.length<2||Fs[0]!==2)throw new Ps("Invalid signature integer tag");const Hs=Fs[1],Ws=Fs.subarray(2,Hs+2);if(!Hs||Ws.length!==Hs)throw new Ps("Invalid signature integer: wrong length");if(Ws[0]&128)throw new Ps("Invalid signature integer: negative");if(Ws[0]===0&&!(Ws[1]&128))throw new Ps("Invalid signature integer: unnecessary leading zero");return{d:b2n(Ws),l:Fs.subarray(Hs+2)}},toSig(Fs){const{Err:Ps}=DER,Hs=typeof Fs=="string"?h2b(Fs):Fs;if(!(Hs instanceof Uint8Array))throw new Error("ui8a expected");let Ws=Hs.length;if(Ws<2||Hs[0]!=48)throw new Ps("Invalid signature tag");if(Hs[1]!==Ws-2)throw new Ps("Invalid signature: incorrect length");const{d:Zs,l:zs}=DER._parseInt(Hs.subarray(2)),{d:Ys,l:Va}=DER._parseInt(zs);if(Va.length)throw new Ps("Invalid signature: left bytes after parsing");return{r:Zs,s:Ys}},hexFromSig(Fs){const Ps=Ma=>Number.parseInt(Ma[0],16)&8?"00"+Ma:Ma,Hs=Ma=>{const qs=Ma.toString(16);return qs.length&1?`0${qs}`:qs},Ws=Ps(Hs(Fs.s)),Zs=Ps(Hs(Fs.r)),zs=Ws.length/2,Ys=Zs.length/2,Va=Hs(zs),Xs=Hs(Ys);return`30${Hs(Ys+zs+4)}02${Xs}${Zs}02${Va}${Ws}`}},_0n=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(Fs){const Ps=validatePointOpts(Fs),{Fp:Hs}=Ps,Ws=Ps.toBytes||((Vc,Dc,sl)=>{const ll=Dc.toAffine();return concatBytes(Uint8Array.from([4]),Hs.toBytes(ll.x),Hs.toBytes(ll.y))}),Zs=Ps.fromBytes||(Vc=>{const Dc=Vc.subarray(1),sl=Hs.fromBytes(Dc.subarray(0,Hs.BYTES)),ll=Hs.fromBytes(Dc.subarray(Hs.BYTES,2*Hs.BYTES));return{x:sl,y:ll}});function zs(Vc){const{a:Dc,b:sl}=Ps,ll=Hs.sqr(Vc),hl=Hs.mul(ll,Vc);return Hs.add(Hs.add(hl,Hs.mul(Vc,Dc)),sl)}if(!Hs.eql(Hs.sqr(Ps.Gy),zs(Ps.Gx)))throw new Error("bad generator point: equation left != right");function Ys(Vc){return typeof Vc=="bigint"&&_0n<Vc&&Vc<Ps.n}function Va(Vc){if(!Ys(Vc))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function Xs(Vc){const{allowedPrivateKeyLengths:Dc,nByteLength:sl,wrapPrivateKey:ll,n:hl}=Ps;if(Dc&&typeof Vc!="bigint"){if(Vc instanceof Uint8Array&&(Vc=bytesToHex(Vc)),typeof Vc!="string"||!Dc.includes(Vc.length))throw new Error("Invalid key");Vc=Vc.padStart(sl*2,"0")}let pl;try{pl=typeof Vc=="bigint"?Vc:bytesToNumberBE(ensureBytes("private key",Vc,sl))}catch{throw new Error(`private key must be ${sl} bytes, hex or bigint, not ${typeof Vc}`)}return ll&&(pl=mod(pl,hl)),Va(pl),pl}const Ma=new Map;function qs(Vc){if(!(Vc instanceof Js))throw new Error("ProjectivePoint expected")}class Js{constructor(Dc,sl,ll){if(this.px=Dc,this.py=sl,this.pz=ll,Dc==null||!Hs.isValid(Dc))throw new Error("x required");if(sl==null||!Hs.isValid(sl))throw new Error("y required");if(ll==null||!Hs.isValid(ll))throw new Error("z required")}static fromAffine(Dc){const{x:sl,y:ll}=Dc||{};if(!Dc||!Hs.isValid(sl)||!Hs.isValid(ll))throw new Error("invalid affine point");if(Dc instanceof Js)throw new Error("projective point not allowed");const hl=pl=>Hs.eql(pl,Hs.ZERO);return hl(sl)&&hl(ll)?Js.ZERO:new Js(sl,ll,Hs.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(Dc){const sl=Hs.invertBatch(Dc.map(ll=>ll.pz));return Dc.map((ll,hl)=>ll.toAffine(sl[hl])).map(Js.fromAffine)}static fromHex(Dc){const sl=Js.fromAffine(Zs(ensureBytes("pointHex",Dc)));return sl.assertValidity(),sl}static fromPrivateKey(Dc){return Js.BASE.multiply(Xs(Dc))}_setWindowSize(Dc){this._WINDOW_SIZE=Dc,Ma.delete(this)}assertValidity(){if(this.is0()){if(Ps.allowInfinityPoint&&!Hs.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:Dc,y:sl}=this.toAffine();if(!Hs.isValid(Dc)||!Hs.isValid(sl))throw new Error("bad point: x or y not FE");const ll=Hs.sqr(sl),hl=zs(Dc);if(!Hs.eql(ll,hl))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:Dc}=this.toAffine();if(Hs.isOdd)return!Hs.isOdd(Dc);throw new Error("Field doesn't support isOdd")}equals(Dc){qs(Dc);const{px:sl,py:ll,pz:hl}=this,{px:pl,py:gl,pz:yl}=Dc,bl=Hs.eql(Hs.mul(sl,yl),Hs.mul(pl,hl)),Il=Hs.eql(Hs.mul(ll,yl),Hs.mul(gl,hl));return bl&&Il}negate(){return new Js(this.px,Hs.neg(this.py),this.pz)}double(){const{a:Dc,b:sl}=Ps,ll=Hs.mul(sl,_3n),{px:hl,py:pl,pz:gl}=this;let yl=Hs.ZERO,bl=Hs.ZERO,Il=Hs.ZERO,$l=Hs.mul(hl,hl),vl=Hs.mul(pl,pl),Sl=Hs.mul(gl,gl),fl=Hs.mul(hl,pl);return fl=Hs.add(fl,fl),Il=Hs.mul(hl,gl),Il=Hs.add(Il,Il),yl=Hs.mul(Dc,Il),bl=Hs.mul(ll,Sl),bl=Hs.add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(il,rl),bl=Hs.mul(nl,bl),bl=Hs.sub(bl,fl),fl=Hs.mul(nl,Hc),$l=Hs.mul(il,$l),$l=Hs.add($l,fl),new Js(bl,Il,$l)}subtract(Dc){return this.add(Dc.negate())}is0(){return this.equals(Js.ZERO)}wNAF(Dc){return ol.wNAFCached(this,Ma,Dc,sl=>{const ll=Hs.invertBatch(sl.map(hl=>hl.pz));return sl.map((hl,pl)=>hl.toAffine(ll[pl])).map(Js.fromAffine)})}multiplyUnsafe(Dc){const sl=Js.ZERO;if(Dc===_0n)return sl;if(Va(Dc),Dc===_1n$1)return this;const{endo:ll}=Ps;if(!ll)return ol.unsafeLadder(this,Dc);let{k1neg:hl,k1:pl,k2neg:gl,k2:yl}=ll.splitScalar(Dc),bl=sl,Il=sl,$l=this;for(;pl>_0n||yl>_0n;)pl&_1n$1&&(bl=bl.add($l)),yl&_1n$1&&(Il=Il.add($l)),$l=$l.double(),pl>>=_1n$1,yl>>=_1n$1;return hl&&(bl=bl.negate()),gl&&(Il=Il.negate()),Il=new Js(Hs.mul(Il.px,ll.beta),Il.py,Il.pz),bl.add(Il)}multiply(Dc){Va(Dc);let sl=Dc,ll,hl;const{endo:pl}=Ps;if(pl){const{k1neg:gl,k1:yl,k2neg:bl,k2:Il}=pl.splitScalar(sl);let{p:$l,f:vl}=this.wNAF(yl),{p:Sl,f:fl}=this.wNAF(Il);$l=ol.constTimeNegate(gl,$l),Sl=ol.constTimeNegate(bl,Sl),Sl=new Js(Hs.mul(Sl.px,pl.beta),Sl.py,Sl.pz),ll=$l.add(Sl),hl=vl.add(fl)}else{const{p:gl,f:yl}=this.wNAF(sl);ll=gl,hl=yl}return Js.normalizeZ([ll,hl])[0]}multiplyAndAddUnsafe(Dc,sl,ll){const hl=Js.BASE,pl=(yl,bl)=>bl===_0n||bl===_1n$1||!yl.equals(hl)?yl.multiplyUnsafe(bl):yl.multiply(bl),gl=pl(this,sl).add(pl(Dc,ll));return gl.is0()?void 0:gl}toAffine(Dc){const{px:sl,py:ll,pz:hl}=this,pl=this.is0();Dc==null&&(Dc=pl?Hs.ONE:Hs.inv(hl));const gl=Hs.mul(sl,Dc),yl=Hs.mul(ll,Dc),bl=Hs.mul(hl,Dc);if(pl)return{x:Hs.ZERO,y:Hs.ZERO};if(!Hs.eql(bl,Hs.ONE))throw new Error("invZ was invalid");return{x:gl,y:yl}}isTorsionFree(){const{h:Dc,isTorsionFree:sl}=Ps;if(Dc===_1n$1)return!0;if(sl)return sl(Js,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:Dc,clearCofactor:sl}=Ps;return Dc===_1n$1?this:sl?sl(Js,this):this.multiplyUnsafe(Ps.h)}toRawBytes(Dc=!0){return this.assertValidity(),Ws(Js,this,Dc)}toHex(Dc=!0){return bytesToHex(this.toRawBytes(Dc))}}Js.BASE=new Js(Ps.Gx,Ps.Gy,Hs.ONE),Js.ZERO=new Js(Hs.ZERO,Hs.ONE,Hs.ZERO);const Mc=Ps.nBitLength,ol=wNAF(Js,Ps.endo?Math.ceil(Mc/2):Mc);return{CURVE:Ps,ProjectivePoint:Js,normPrivateKeyToScalar:Xs,weierstrassEquation:zs,isWithinCurveOrder:Ys}}function validateOpts(Fs){const Ps=validateBasic(Fs);return validateObject(Ps,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...Ps})}function weierstrass(Fs){const Ps=validateOpts(Fs),{Fp:Hs,n:Ws}=Ps,Zs=Hs.BYTES+1,zs=2*Hs.BYTES+1;function Ys(rl){return _0n<rl&&rl<Hs.ORDER}function Va(rl){return mod(rl,Ws)}function Xs(rl){return invert(rl,Ws)}const{ProjectivePoint:Ma,normPrivateKeyToScalar:qs,weierstrassEquation:Js,isWithinCurveOrder:Mc}=weierstrassPoints({...Ps,toBytes(rl,il,cl){const ul=il.toAffine(),al=Hs.toBytes(ul.x),el=concatBytes;return cl?el(Uint8Array.from([il.hasEvenY()?2:3]),al):el(Uint8Array.from([4]),al,Hs.toBytes(ul.y))},fromBytes(rl){const il=rl.length,cl=rl[0],ul=rl.subarray(1);if(il===Zs&&(cl===2||cl===3)){const al=bytesToNumberBE(ul);if(!Ys(al))throw new Error("Point is not on curve");const el=Js(al);let dl=Hs.sqrt(el);const ml=(dl&_1n$1)===_1n$1;return(cl&1)===1!==ml&&(dl=Hs.neg(dl)),{x:al,y:dl}}else if(il===zs&&cl===4){const al=Hs.fromBytes(ul.subarray(0,Hs.BYTES)),el=Hs.fromBytes(ul.subarray(Hs.BYTES,2*Hs.BYTES));return{x:al,y:el}}else throw new Error(`Point of length ${il} was invalid. Expected ${Zs} compressed bytes or ${zs} uncompressed bytes`)}}),ol=rl=>bytesToHex(numberToBytesBE(rl,Ps.nByteLength));function Vc(rl){const il=Ws>>_1n$1;return rl>il}function Dc(rl){return Vc(rl)?Va(-rl):rl}const sl=(rl,il,cl)=>bytesToNumberBE(rl.slice(il,cl));class ll{constructor(il,cl,ul){this.r=il,this.s=cl,this.recovery=ul,this.assertValidity()}static fromCompact(il){const cl=Ps.nByteLength;return il=ensureBytes("compactSignature",il,cl*2),new ll(sl(il,0,cl),sl(il,cl,2*cl))}static fromDER(il){const{r:cl,s:ul}=DER.toSig(ensureBytes("DER",il));return new ll(cl,ul)}assertValidity(){if(!Mc(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!Mc(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(il){return new ll(this.r,this.s,il)}recoverPublicKey(il){const{r:cl,s:ul,recovery:al}=this,el=Il(ensureBytes("msgHash",il));if(al==null||![0,1,2,3].includes(al))throw new Error("recovery id invalid");const dl=al===2||al===3?cl+Ps.n:cl;if(dl>=Hs.ORDER)throw new Error("recovery id 2 or 3 invalid");const ml=(al&1)===0?"02":"03",El=Ma.fromHex(ml+ol(dl)),Al=Xs(dl),_l=Va(-el*Al),Pl=Va(ul*Al),wl=Ma.BASE.multiplyAndAddUnsafe(El,_l,Pl);if(!wl)throw new Error("point at infinify");return wl.assertValidity(),wl}hasHighS(){return Vc(this.s)}normalizeS(){return this.hasHighS()?new ll(this.r,Va(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return ol(this.r)+ol(this.s)}}const hl={isValidPrivateKey(rl){try{return qs(rl),!0}catch{return!1}},normPrivateKeyToScalar:qs,randomPrivateKey:()=>{const rl=getMinHashLength(Ps.n);return mapHashToField(Ps.randomBytes(rl),Ps.n)},precompute(rl=8,il=Ma.BASE){return il._setWindowSize(rl),il.multiply(BigInt(3)),il}};function pl(rl,il=!0){return Ma.fromPrivateKey(rl).toRawBytes(il)}function gl(rl){const il=rl instanceof Uint8Array,cl=typeof rl=="string",ul=(il||cl)&&rl.length;return il?ul===Zs||ul===zs:cl?ul===2*Zs||ul===2*zs:rl instanceof Ma}function yl(rl,il,cl=!0){if(gl(rl))throw new Error("first arg must be private key");if(!gl(il))throw new Error("second arg must be public key");return Ma.fromHex(il).multiply(qs(rl)).toRawBytes(cl)}const bl=Ps.bits2int||function(rl){const il=bytesToNumberBE(rl),cl=rl.length*8-Ps.nBitLength;return cl>0?il>>BigInt(cl):il},Il=Ps.bits2int_modN||function(rl){return Va(bl(rl))},$l=bitMask(Ps.nBitLength);function vl(rl){if(typeof rl!="bigint")throw new Error("bigint expected");if(!(_0n<=rl&&rl<$l))throw new Error(`bigint expected < 2^${Ps.nBitLength}`);return numberToBytesBE(rl,Ps.nByteLength)}function Sl(rl,il,cl=fl){if(["recovered","canonical"].some(Nl=>Nl in cl))throw new Error("sign() legacy options not supported");const{hash:ul,randomBytes:al}=Ps;let{lowS:el,prehash:dl,extraEntropy:ml}=cl;el==null&&(el=!0),rl=ensureBytes("msgHash",rl),dl&&(rl=ensureBytes("prehashed msgHash",ul(rl)));const El=Il(rl),Al=qs(il),_l=[vl(Al),vl(El)];if(ml!=null){const Nl=ml===!0?al(Hs.BYTES):ml;_l.push(ensureBytes("extraEntropy",Nl))}const Pl=concatBytes(..._l),wl=El;function Cl(Nl){const Ml=bl(Nl);if(!Mc(Ml))return;const Fl=Xs(Ml),Ol=Ma.BASE.multiply(Ml).toAffine(),Vl=Va(Ol.x);if(Vl===_0n)return;const $u=Va(Fl*Va(wl+Vl*Al));if($u===_0n)return;let Ql=(Ol.x===Vl?0:2)|Number(Ol.y&_1n$1),_u=$u;return el&&Vc($u)&&(_u=Dc($u),Ql^=1),new ll(Vl,_u,Ql)}return{seed:Pl,k2sig:Cl}}const fl={lowS:Ps.lowS,prehash:!1},Hc={lowS:Ps.lowS,prehash:!1};function tl(rl,il,cl=fl){const{seed:ul,k2sig:al}=Sl(rl,il,cl),el=Ps;return createHmacDrbg(el.hash.outputLen,el.nByteLength,el.hmac)(ul,al)}Ma.BASE._setWindowSize(8);function nl(rl,il,cl,ul=Hc){const al=rl;if(il=ensureBytes("msgHash",il),cl=ensureBytes("publicKey",cl),"strict"in ul)throw new Error("options.strict was renamed to lowS");const{lowS:el,prehash:dl}=ul;let ml,El;try{if(typeof al=="string"||al instanceof Uint8Array)try{ml=ll.fromDER(al)}catch(Ol){if(!(Ol instanceof DER.Err))throw Ol;ml=ll.fromCompact(al)}else if(typeof al=="object"&&typeof al.r=="bigint"&&typeof al.s=="bigint"){const{r:Ol,s:Vl}=al;ml=new ll(Ol,Vl)}else throw new Error("PARSE");El=Ma.fromHex(cl)}catch(Ol){if(Ol.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(el&&ml.hasHighS())return!1;dl&&(il=Ps.hash(il));const{r:Al,s:_l}=ml,Pl=Il(il),wl=Xs(_l),Cl=Va(Pl*wl),Nl=Va(Al*wl),Ml=Ma.BASE.multiplyAndAddUnsafe(El,Cl,Nl)?.toAffine();return Ml?Va(Ml.x)===Al:!1}return{CURVE:Ps,getPublicKey:pl,getSharedSecret:yl,sign:tl,verify:nl,ProjectivePoint:Ma,Signature:ll,utils:hl}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(Fs){return{hash:Fs,hmac:(Ps,...Hs)=>hmac(Fs,Ps,concatBytes$1(...Hs)),randomBytes}}function createCurve(Fs,Ps){const Hs=Ws=>weierstrass({...Fs,...getHash(Ws)});return Object.freeze({...Hs(Ps),create:Hs})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(Fs,Ps)=>(Fs+Ps/_2n)/Ps;function sqrtMod(Fs){const Ps=secp256k1P,Hs=BigInt(3),Ws=BigInt(6),Zs=BigInt(11),zs=BigInt(22),Ys=BigInt(23),Va=BigInt(44),Xs=BigInt(88),Ma=Fs*Fs*Fs%Ps,qs=Ma*Ma*Fs%Ps,Js=pow2(qs,Hs,Ps)*qs%Ps,Mc=pow2(Js,Hs,Ps)*qs%Ps,ol=pow2(Mc,_2n,Ps)*Ma%Ps,Vc=pow2(ol,Zs,Ps)*ol%Ps,Dc=pow2(Vc,zs,Ps)*Vc%Ps,sl=pow2(Dc,Va,Ps)*Dc%Ps,ll=pow2(sl,Xs,Ps)*sl%Ps,hl=pow2(ll,Va,Ps)*Dc%Ps,pl=pow2(hl,Hs,Ps)*qs%Ps,gl=pow2(pl,Ys,Ps)*Vc%Ps,yl=pow2(gl,Ws,Ps)*Ma%Ps,bl=pow2(yl,_2n,Ps);if(!Fp.eql(Fp.sqr(bl),Fs))throw new Error("Cannot find square root");return bl}const Fp=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:Fs=>{const Ps=secp256k1N,Hs=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Ws=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),Zs=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),zs=Hs,Ys=BigInt("0x100000000000000000000000000000000"),Va=divNearest(zs*Fs,Ps),Xs=divNearest(-Ws*Fs,Ps);let Ma=mod(Fs-Va*Hs-Xs*Zs,Ps),qs=mod(-Va*Ws-Xs*zs,Ps);const Js=Ma>Ys,Mc=qs>Ys;if(Js&&(Ma=Ps-Ma),Mc&&(qs=Ps-qs),Ma>Ys||qs>Ys)throw new Error("splitScalar: Endomorphism failed, k="+Fs);return{k1neg:Js,k1:Ma,k2neg:Mc,k2:qs}}}},sha256$1);BigInt(0),secp256k1.ProjectivePoint;const ZeroAddress="0x0000000000000000000000000000000000000000",ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000",BN_0$7=BigInt(0),BN_1$2=BigInt(1),BN_2$2=BigInt(2),BN_27$1=BigInt(27),BN_28$1=BigInt(28),BN_35$1=BigInt(35),_guard$1={};function toUint256(Fs){return zeroPadValue(toBeArray(Fs),32)}class Signature{#e;#t;#r;#n;get r(){return this.#e}set r(Ps){assertArgument(dataLength(Ps)===32,"invalid r","value",Ps),this.#e=hexlify(Ps)}get s(){return assertArgument(parseInt(this.#t.substring(0,3))<8,"non-canonical s; use ._s","s",this.#t),this.#t}set s(Ps){assertArgument(dataLength(Ps)===32,"invalid s","value",Ps),this.#t=hexlify(Ps)}get _s(){return this.#t}isValid(){return parseInt(this.#t.substring(0,3))<8}get v(){return this.#r}set v(Ps){const Hs=getNumber(Ps,"value");assertArgument(Hs===27||Hs===28,"invalid v","v",Ps),this.#r=Hs}get networkV(){return this.#n}get legacyChainId(){const Ps=this.networkV;return Ps==null?null:Signature.getChainId(Ps)}get yParity(){return this.v===27?0:1}get yParityAndS(){const Ps=getBytes(this.s);return this.yParity&&(Ps[0]|=128),hexlify(Ps)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(Ps,Hs,Ws,Zs){assertPrivate(Ps,_guard$1,"Signature"),this.#e=Hs,this.#t=Ws,this.#r=Zs,this.#n=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this._s}"${this.isValid()?"":', valid: "false"'}, yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const Ps=new Signature(_guard$1,this.r,this._s,this.v);return this.networkV&&(Ps.#n=this.networkV),Ps}toJSON(){const Ps=this.networkV;return{_type:"signature",networkV:Ps!=null?Ps.toString():null,r:this.r,s:this._s,v:this.v}}static getChainId(Ps){const Hs=getBigInt(Ps,"v");return Hs==BN_27$1||Hs==BN_28$1?BN_0$7:(assertArgument(Hs>=BN_35$1,"invalid EIP-155 v","v",Ps),(Hs-BN_35$1)/BN_2$2)}static getChainIdV(Ps,Hs){return getBigInt(Ps)*BN_2$2+BigInt(35+Hs-27)}static getNormalizedV(Ps){const Hs=getBigInt(Ps);return Hs===BN_0$7||Hs===BN_27$1?27:Hs===BN_1$2||Hs===BN_28$1?28:(assertArgument(Hs>=BN_35$1,"invalid v","v",Ps),Hs&BN_1$2?27:28)}static from(Ps){function Hs(Ma,qs){assertArgument(Ma,qs,"signature",Ps)}if(Ps==null)return new Signature(_guard$1,ZeroHash,ZeroHash,27);if(typeof Ps=="string"){const Ma=getBytes(Ps,"signature");if(Ma.length===64){const qs=hexlify(Ma.slice(0,32)),Js=Ma.slice(32,64),Mc=Js[0]&128?28:27;return Js[0]&=127,new Signature(_guard$1,qs,hexlify(Js),Mc)}if(Ma.length===65){const qs=hexlify(Ma.slice(0,32)),Js=hexlify(Ma.slice(32,64)),Mc=Signature.getNormalizedV(Ma[64]);return new Signature(_guard$1,qs,Js,Mc)}Hs(!1,"invalid raw signature length")}if(Ps instanceof Signature)return Ps.clone();const Ws=Ps.r;Hs(Ws!=null,"missing r");const Zs=toUint256(Ws),zs=(function(Ma,qs){if(Ma!=null)return toUint256(Ma);if(qs!=null){Hs(isHexString(qs,32),"invalid yParityAndS");const Js=getBytes(qs);return Js[0]&=127,hexlify(Js)}Hs(!1,"missing s")})(Ps.s,Ps.yParityAndS),{networkV:Ys,v:Va}=(function(Ma,qs,Js){if(Ma!=null){const Mc=getBigInt(Ma);return{networkV:Mc>=BN_35$1?Mc:void 0,v:Signature.getNormalizedV(Mc)}}if(qs!=null)return Hs(isHexString(qs,32),"invalid yParityAndS"),{v:getBytes(qs)[0]&128?28:27};if(Js!=null){switch(getNumber(Js,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}Hs(!1,"invalid yParity")}Hs(!1,"missing v")})(Ps.v,Ps.yParityAndS,Ps.yParity),Xs=new Signature(_guard$1,Zs,zs,Va);return Ys&&(Xs.#n=Ys),Hs(Ps.yParity==null||getNumber(Ps.yParity,"sig.yParity")===Xs.yParity,"yParity mismatch"),Hs(Ps.yParityAndS==null||Ps.yParityAndS===Xs.yParityAndS,"yParityAndS mismatch"),Xs}}class SigningKey{#e;constructor(Ps){assertArgument(dataLength(Ps)===32,"invalid private key","privateKey","[REDACTED]"),this.#e=hexlify(Ps)}get privateKey(){return this.#e}get publicKey(){return SigningKey.computePublicKey(this.#e)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#e,!0)}sign(Ps){assertArgument(dataLength(Ps)===32,"invalid digest length","digest",Ps);const Hs=secp256k1.sign(getBytesCopy(Ps),getBytesCopy(this.#e),{lowS:!0});return Signature.from({r:toBeHex(Hs.r,32),s:toBeHex(Hs.s,32),v:Hs.recovery?28:27})}computeSharedSecret(Ps){const Hs=SigningKey.computePublicKey(Ps);return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#e),getBytes(Hs),!1))}static computePublicKey(Ps,Hs){let Ws=getBytes(Ps,"key");if(Ws.length===32){const zs=secp256k1.getPublicKey(Ws,!!Hs);return hexlify(zs)}if(Ws.length===64){const zs=new Uint8Array(65);zs[0]=4,zs.set(Ws,1),Ws=zs}const Zs=secp256k1.ProjectivePoint.fromHex(Ws);return hexlify(Zs.toRawBytes(Hs))}static recoverPublicKey(Ps,Hs){assertArgument(dataLength(Ps)===32,"invalid digest length","digest",Ps);const Ws=Signature.from(Hs);let Zs=secp256k1.Signature.fromCompact(getBytesCopy(concat([Ws.r,Ws.s])));Zs=Zs.addRecoveryBit(Ws.yParity);const zs=Zs.recoverPublicKey(getBytesCopy(Ps));return assertArgument(zs!=null,"invalid signature for digest","signature",Hs),"0x"+zs.toHex(!1)}static addPoints(Ps,Hs,Ws){const Zs=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(Ps).substring(2)),zs=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(Hs).substring(2));return"0x"+Zs.add(zs).toHex(!!Ws)}}const BN_0$6=BigInt(0),BN_36=BigInt(36);function getChecksumAddress(Fs){Fs=Fs.toLowerCase();const Ps=Fs.substring(2).split(""),Hs=new Uint8Array(40);for(let Zs=0;Zs<40;Zs++)Hs[Zs]=Ps[Zs].charCodeAt(0);const Ws=getBytes(keccak256(Hs));for(let Zs=0;Zs<40;Zs+=2)Ws[Zs>>1]>>4>=8&&(Ps[Zs]=Ps[Zs].toUpperCase()),(Ws[Zs>>1]&15)>=8&&(Ps[Zs+1]=Ps[Zs+1].toUpperCase());return"0x"+Ps.join("")}const ibanLookup={};for(let Fs=0;Fs<10;Fs++)ibanLookup[String(Fs)]=String(Fs);for(let Fs=0;Fs<26;Fs++)ibanLookup[String.fromCharCode(65+Fs)]=String(10+Fs);const safeDigits=15;function ibanChecksum(Fs){Fs=Fs.toUpperCase(),Fs=Fs.substring(4)+Fs.substring(0,2)+"00";let Ps=Fs.split("").map(Ws=>ibanLookup[Ws]).join("");for(;Ps.length>=safeDigits;){let Ws=Ps.substring(0,safeDigits);Ps=parseInt(Ws,10)%97+Ps.substring(Ws.length)}let Hs=String(98-parseInt(Ps,10)%97);for(;Hs.length<2;)Hs="0"+Hs;return Hs}const Base36=(function(){const Fs={};for(let Ps=0;Ps<36;Ps++){const Hs="0123456789abcdefghijklmnopqrstuvwxyz"[Ps];Fs[Hs]=BigInt(Ps)}return Fs})();function fromBase36(Fs){Fs=Fs.toLowerCase();let Ps=BN_0$6;for(let Hs=0;Hs<Fs.length;Hs++)Ps=Ps*BN_36+Base36[Fs[Hs]];return Ps}function getAddress(Fs){if(assertArgument(typeof Fs=="string","invalid address","address",Fs),Fs.match(/^(0x)?[0-9a-fA-F]{40}$/)){Fs.startsWith("0x")||(Fs="0x"+Fs);const Ps=getChecksumAddress(Fs);return assertArgument(!Fs.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||Ps===Fs,"bad address checksum","address",Fs),Ps}if(Fs.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){assertArgument(Fs.substring(2,4)===ibanChecksum(Fs),"bad icap checksum","address",Fs);let Ps=fromBase36(Fs.substring(4)).toString(16);for(;Ps.length<40;)Ps="0"+Ps;return getChecksumAddress("0x"+Ps)}assertArgument(!1,"invalid address","address",Fs)}function getCreateAddress(Fs){const Ps=getAddress(Fs.from);let Ws=getBigInt(Fs.nonce,"tx.nonce").toString(16);return Ws==="0"?Ws="0x":Ws.length%2?Ws="0x0"+Ws:Ws="0x"+Ws,getAddress(dataSlice(keccak256(encodeRlp([Ps,Ws])),12))}function isAddressable(Fs){return Fs&&typeof Fs.getAddress=="function"}async function checkAddress(Fs,Ps){const Hs=await Ps;return(Hs==null||Hs==="0x0000000000000000000000000000000000000000")&&(assert(typeof Fs!="string","unconfigured name","UNCONFIGURED_NAME",{value:Fs}),assertArgument(!1,"invalid AddressLike value; did not resolve to a value address","target",Fs)),getAddress(Hs)}function resolveAddress(Fs,Ps){if(typeof Fs=="string")return Fs.match(/^0x[0-9a-f]{40}$/i)?getAddress(Fs):(assert(Ps!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),checkAddress(Fs,Ps.resolveName(Fs)));if(isAddressable(Fs))return checkAddress(Fs,Fs.getAddress());if(Fs&&typeof Fs.then=="function")return checkAddress(Fs,Fs);assertArgument(!1,"unsupported addressable value","target",Fs)}const _gaurd={};function n$j(Fs,Ps){let Hs=!1;return Ps<0&&(Hs=!0,Ps*=-1),new Typed(_gaurd,`${Hs?"":"u"}int${Ps}`,Fs,{signed:Hs,width:Ps})}function b$4(Fs,Ps){return new Typed(_gaurd,`bytes${Ps||""}`,Fs,{size:Ps})}const _typedSymbol=Symbol.for("_ethers_typed");class Typed{type;value;#e;_typedSymbol;constructor(Ps,Hs,Ws,Zs){Zs==null&&(Zs=null),assertPrivate(_gaurd,Ps,"Typed"),defineProperties(this,{_typedSymbol,type:Hs,value:Ws}),this.#e=Zs,this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(Ps=>Ps.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return this.#e}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return this.#e===!0?-1:this.#e===!1?this.value.length:null}static from(Ps,Hs){return new Typed(_gaurd,Ps,Hs)}static uint8(Ps){return n$j(Ps,8)}static uint16(Ps){return n$j(Ps,16)}static uint24(Ps){return n$j(Ps,24)}static uint32(Ps){return n$j(Ps,32)}static uint40(Ps){return n$j(Ps,40)}static uint48(Ps){return n$j(Ps,48)}static uint56(Ps){return n$j(Ps,56)}static uint64(Ps){return n$j(Ps,64)}static uint72(Ps){return n$j(Ps,72)}static uint80(Ps){return n$j(Ps,80)}static uint88(Ps){return n$j(Ps,88)}static uint96(Ps){return n$j(Ps,96)}static uint104(Ps){return n$j(Ps,104)}static uint112(Ps){return n$j(Ps,112)}static uint120(Ps){return n$j(Ps,120)}static uint128(Ps){return n$j(Ps,128)}static uint136(Ps){return n$j(Ps,136)}static uint144(Ps){return n$j(Ps,144)}static uint152(Ps){return n$j(Ps,152)}static uint160(Ps){return n$j(Ps,160)}static uint168(Ps){return n$j(Ps,168)}static uint176(Ps){return n$j(Ps,176)}static uint184(Ps){return n$j(Ps,184)}static uint192(Ps){return n$j(Ps,192)}static uint200(Ps){return n$j(Ps,200)}static uint208(Ps){return n$j(Ps,208)}static uint216(Ps){return n$j(Ps,216)}static uint224(Ps){return n$j(Ps,224)}static uint232(Ps){return n$j(Ps,232)}static uint240(Ps){return n$j(Ps,240)}static uint248(Ps){return n$j(Ps,248)}static uint256(Ps){return n$j(Ps,256)}static uint(Ps){return n$j(Ps,256)}static int8(Ps){return n$j(Ps,-8)}static int16(Ps){return n$j(Ps,-16)}static int24(Ps){return n$j(Ps,-24)}static int32(Ps){return n$j(Ps,-32)}static int40(Ps){return n$j(Ps,-40)}static int48(Ps){return n$j(Ps,-48)}static int56(Ps){return n$j(Ps,-56)}static int64(Ps){return n$j(Ps,-64)}static int72(Ps){return n$j(Ps,-72)}static int80(Ps){return n$j(Ps,-80)}static int88(Ps){return n$j(Ps,-88)}static int96(Ps){return n$j(Ps,-96)}static int104(Ps){return n$j(Ps,-104)}static int112(Ps){return n$j(Ps,-112)}static int120(Ps){return n$j(Ps,-120)}static int128(Ps){return n$j(Ps,-128)}static int136(Ps){return n$j(Ps,-136)}static int144(Ps){return n$j(Ps,-144)}static int152(Ps){return n$j(Ps,-152)}static int160(Ps){return n$j(Ps,-160)}static int168(Ps){return n$j(Ps,-168)}static int176(Ps){return n$j(Ps,-176)}static int184(Ps){return n$j(Ps,-184)}static int192(Ps){return n$j(Ps,-192)}static int200(Ps){return n$j(Ps,-200)}static int208(Ps){return n$j(Ps,-208)}static int216(Ps){return n$j(Ps,-216)}static int224(Ps){return n$j(Ps,-224)}static int232(Ps){return n$j(Ps,-232)}static int240(Ps){return n$j(Ps,-240)}static int248(Ps){return n$j(Ps,-248)}static int256(Ps){return n$j(Ps,-256)}static int(Ps){return n$j(Ps,-256)}static bytes1(Ps){return b$4(Ps,1)}static bytes2(Ps){return b$4(Ps,2)}static bytes3(Ps){return b$4(Ps,3)}static bytes4(Ps){return b$4(Ps,4)}static bytes5(Ps){return b$4(Ps,5)}static bytes6(Ps){return b$4(Ps,6)}static bytes7(Ps){return b$4(Ps,7)}static bytes8(Ps){return b$4(Ps,8)}static bytes9(Ps){return b$4(Ps,9)}static bytes10(Ps){return b$4(Ps,10)}static bytes11(Ps){return b$4(Ps,11)}static bytes12(Ps){return b$4(Ps,12)}static bytes13(Ps){return b$4(Ps,13)}static bytes14(Ps){return b$4(Ps,14)}static bytes15(Ps){return b$4(Ps,15)}static bytes16(Ps){return b$4(Ps,16)}static bytes17(Ps){return b$4(Ps,17)}static bytes18(Ps){return b$4(Ps,18)}static bytes19(Ps){return b$4(Ps,19)}static bytes20(Ps){return b$4(Ps,20)}static bytes21(Ps){return b$4(Ps,21)}static bytes22(Ps){return b$4(Ps,22)}static bytes23(Ps){return b$4(Ps,23)}static bytes24(Ps){return b$4(Ps,24)}static bytes25(Ps){return b$4(Ps,25)}static bytes26(Ps){return b$4(Ps,26)}static bytes27(Ps){return b$4(Ps,27)}static bytes28(Ps){return b$4(Ps,28)}static bytes29(Ps){return b$4(Ps,29)}static bytes30(Ps){return b$4(Ps,30)}static bytes31(Ps){return b$4(Ps,31)}static bytes32(Ps){return b$4(Ps,32)}static address(Ps){return new Typed(_gaurd,"address",Ps)}static bool(Ps){return new Typed(_gaurd,"bool",!!Ps)}static bytes(Ps){return new Typed(_gaurd,"bytes",Ps)}static string(Ps){return new Typed(_gaurd,"string",Ps)}static array(Ps,Hs){throw new Error("not implemented yet")}static tuple(Ps,Hs){throw new Error("not implemented yet")}static overrides(Ps){return new Typed(_gaurd,"overrides",Object.assign({},Ps))}static isTyped(Ps){return Ps&&typeof Ps=="object"&&"_typedSymbol"in Ps&&Ps._typedSymbol===_typedSymbol}static dereference(Ps,Hs){if(Typed.isTyped(Ps)){if(Ps.type!==Hs)throw new Error(`invalid type: expecetd ${Hs}, got ${Ps.type}`);return Ps.value}return Ps}}class AddressCoder extends Coder{constructor(Ps){super("address","address",Ps,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(Ps,Hs){let Ws=Typed.dereference(Hs,"string");try{Ws=getAddress(Ws)}catch(Zs){return this._throwError(Zs.message,Hs)}return Ps.writeValue(Ws)}decode(Ps){return getAddress(toBeHex(Ps.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(Ps){super(Ps.name,Ps.type,"_",Ps.dynamic),this.coder=Ps}defaultValue(){return this.coder.defaultValue()}encode(Ps,Hs){return this.coder.encode(Ps,Hs)}decode(Ps){return this.coder.decode(Ps)}}function pack(Fs,Ps,Hs){let Ws=[];if(Array.isArray(Hs))Ws=Hs;else if(Hs&&typeof Hs=="object"){let Xs={};Ws=Ps.map(Ma=>{const qs=Ma.localName;return assert(qs,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:Ma},value:Hs}),assert(!Xs[qs],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:Ma},value:Hs}),Xs[qs]=!0,Hs[qs]})}else assertArgument(!1,"invalid tuple value","tuple",Hs);assertArgument(Ps.length===Ws.length,"types/value length mismatch","tuple",Hs);let Zs=new Writer,zs=new Writer,Ys=[];Ps.forEach((Xs,Ma)=>{let qs=Ws[Ma];if(Xs.dynamic){let Js=zs.length;Xs.encode(zs,qs);let Mc=Zs.writeUpdatableValue();Ys.push(ol=>{Mc(ol+Js)})}else Xs.encode(Zs,qs)}),Ys.forEach(Xs=>{Xs(Zs.length)});let Va=Fs.appendWriter(Zs);return Va+=Fs.appendWriter(zs),Va}function unpack(Fs,Ps){let Hs=[],Ws=[],Zs=Fs.subReader(0);return Ps.forEach(zs=>{let Ys=null;if(zs.dynamic){let Va=Fs.readIndex(),Xs=Zs.subReader(Va);try{Ys=zs.decode(Xs)}catch(Ma){if(isError(Ma,"BUFFER_OVERRUN"))throw Ma;Ys=Ma,Ys.baseType=zs.name,Ys.name=zs.localName,Ys.type=zs.type}}else try{Ys=zs.decode(Fs)}catch(Va){if(isError(Va,"BUFFER_OVERRUN"))throw Va;Ys=Va,Ys.baseType=zs.name,Ys.name=zs.localName,Ys.type=zs.type}if(Ys==null)throw new Error("investigate");Hs.push(Ys),Ws.push(zs.localName||null)}),Result$1.fromItems(Hs,Ws)}class ArrayCoder extends Coder{coder;length;constructor(Ps,Hs,Ws){const Zs=Ps.type+"["+(Hs>=0?Hs:"")+"]",zs=Hs===-1||Ps.dynamic;super("array",Zs,Ws,zs),defineProperties(this,{coder:Ps,length:Hs})}defaultValue(){const Ps=this.coder.defaultValue(),Hs=[];for(let Ws=0;Ws<this.length;Ws++)Hs.push(Ps);return Hs}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"array");Array.isArray(Ws)||this._throwError("expected array value",Ws);let Zs=this.length;Zs===-1&&(Zs=Ws.length,Ps.writeValue(Ws.length)),assertArgumentCount(Ws.length,Zs,"coder array"+(this.localName?" "+this.localName:""));let zs=[];for(let Ys=0;Ys<Ws.length;Ys++)zs.push(this.coder);return pack(Ps,zs,Ws)}decode(Ps){let Hs=this.length;Hs===-1&&(Hs=Ps.readIndex(),assert(Hs*WordSize<=Ps.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:Ps.bytes,offset:Hs*WordSize,length:Ps.dataLength}));let Ws=[];for(let Zs=0;Zs<Hs;Zs++)Ws.push(new AnonymousCoder(this.coder));return unpack(Ps,Ws)}}class BooleanCoder extends Coder{constructor(Ps){super("bool","bool",Ps,!1)}defaultValue(){return!1}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"bool");return Ps.writeValue(Ws?1:0)}decode(Ps){return!!Ps.readValue()}}class DynamicBytesCoder extends Coder{constructor(Ps,Hs){super(Ps,Ps,Hs,!0)}defaultValue(){return"0x"}encode(Ps,Hs){Hs=getBytesCopy(Hs);let Ws=Ps.writeValue(Hs.length);return Ws+=Ps.writeBytes(Hs),Ws}decode(Ps){return Ps.readBytes(Ps.readIndex(),!0)}}class BytesCoder extends DynamicBytesCoder{constructor(Ps){super("bytes",Ps)}decode(Ps){return hexlify(super.decode(Ps))}}class FixedBytesCoder extends Coder{size;constructor(Ps,Hs){let Ws="bytes"+String(Ps);super(Ws,Ws,Hs,!1),defineProperties(this,{size:Ps},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(Ps,Hs){let Ws=getBytesCopy(Typed.dereference(Hs,this.type));return Ws.length!==this.size&&this._throwError("incorrect data length",Hs),Ps.writeBytes(Ws)}decode(Ps){return hexlify(Ps.readBytes(this.size))}}const Empty=new Uint8Array([]);class NullCoder extends Coder{constructor(Ps){super("null","",Ps,!1)}defaultValue(){return null}encode(Ps,Hs){return Hs!=null&&this._throwError("not null",Hs),Ps.writeBytes(Empty)}decode(Ps){return Ps.readBytes(0),null}}const BN_0$5=BigInt(0),BN_1$1=BigInt(1),BN_MAX_UINT256$1=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class NumberCoder extends Coder{size;signed;constructor(Ps,Hs,Ws){const Zs=(Hs?"int":"uint")+Ps*8;super(Zs,Zs,Ws,!1),defineProperties(this,{size:Ps,signed:Hs},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(Ps,Hs){let Ws=getBigInt(Typed.dereference(Hs,this.type)),Zs=mask(BN_MAX_UINT256$1,WordSize*8);if(this.signed){let zs=mask(Zs,this.size*8-1);(Ws>zs||Ws<-(zs+BN_1$1))&&this._throwError("value out-of-bounds",Hs),Ws=toTwos(Ws,8*WordSize)}else(Ws<BN_0$5||Ws>mask(Zs,this.size*8))&&this._throwError("value out-of-bounds",Hs);return Ps.writeValue(Ws)}decode(Ps){let Hs=mask(Ps.readValue(),this.size*8);return this.signed&&(Hs=fromTwos(Hs,this.size*8)),Hs}}class StringCoder extends DynamicBytesCoder{constructor(Ps){super("string",Ps)}defaultValue(){return""}encode(Ps,Hs){return super.encode(Ps,toUtf8Bytes(Typed.dereference(Hs,"string")))}decode(Ps){return toUtf8String(super.decode(Ps))}}class TupleCoder extends Coder{coders;constructor(Ps,Hs){let Ws=!1;const Zs=[];Ps.forEach(Ys=>{Ys.dynamic&&(Ws=!0),Zs.push(Ys.type)});const zs="tuple("+Zs.join(",")+")";super("tuple",zs,Hs,Ws),defineProperties(this,{coders:Object.freeze(Ps.slice())})}defaultValue(){const Ps=[];this.coders.forEach(Ws=>{Ps.push(Ws.defaultValue())});const Hs=this.coders.reduce((Ws,Zs)=>{const zs=Zs.localName;return zs&&(Ws[zs]||(Ws[zs]=0),Ws[zs]++),Ws},{});return this.coders.forEach((Ws,Zs)=>{let zs=Ws.localName;!zs||Hs[zs]!==1||(zs==="length"&&(zs="_length"),Ps[zs]==null&&(Ps[zs]=Ps[Zs]))}),Object.freeze(Ps)}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"tuple");return pack(Ps,this.coders,Ws)}decode(Ps){return unpack(Ps,this.coders)}}function accessSetify(Fs,Ps){return{address:getAddress(Fs),storageKeys:Ps.map((Hs,Ws)=>(assertArgument(isHexString(Hs,32),"invalid slot",`storageKeys[${Ws}]`,Hs),Hs.toLowerCase()))}}function accessListify(Fs){if(Array.isArray(Fs))return Fs.map((Hs,Ws)=>Array.isArray(Hs)?(assertArgument(Hs.length===2,"invalid slot set",`value[${Ws}]`,Hs),accessSetify(Hs[0],Hs[1])):(assertArgument(Hs!=null&&typeof Hs=="object","invalid address-slot set","value",Fs),accessSetify(Hs.address,Hs.storageKeys)));assertArgument(Fs!=null&&typeof Fs=="object","invalid access list","value",Fs);const Ps=Object.keys(Fs).map(Hs=>{const Ws=Fs[Hs].reduce((Zs,zs)=>(Zs[zs]=!0,Zs),{});return accessSetify(Hs,Object.keys(Ws).sort())});return Ps.sort((Hs,Ws)=>Hs.address.localeCompare(Ws.address)),Ps}function authorizationify(Fs){return{address:getAddress(Fs.address),nonce:getBigInt(Fs.nonce!=null?Fs.nonce:0),chainId:getBigInt(Fs.chainId!=null?Fs.chainId:0),signature:Signature.from(Fs.signature)}}function computeAddress(Fs){let Ps;return typeof Fs=="string"?Ps=SigningKey.computePublicKey(Fs,!1):Ps=Fs.publicKey,getAddress(keccak256("0x"+Ps.substring(4)).substring(26))}function recoverAddress(Fs,Ps){return computeAddress(SigningKey.recoverPublicKey(Fs,Ps))}const BN_0$4=BigInt(0),BN_2$1=BigInt(2),BN_27=BigInt(27),BN_28=BigInt(28),BN_35=BigInt(35),BN_MAX_UINT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),BLOB_SIZE=4096*32;function getKzgLibrary(Fs){return{blobToKzgCommitment:Ws=>{if("computeBlobProof"in Fs){if("blobToKzgCommitment"in Fs&&typeof Fs.blobToKzgCommitment=="function")return getBytes(Fs.blobToKzgCommitment(hexlify(Ws)))}else if("blobToKzgCommitment"in Fs&&typeof Fs.blobToKzgCommitment=="function")return getBytes(Fs.blobToKzgCommitment(Ws));if("blobToKZGCommitment"in Fs&&typeof Fs.blobToKZGCommitment=="function")return getBytes(Fs.blobToKZGCommitment(hexlify(Ws)));assertArgument(!1,"unsupported KZG library","kzg",Fs)},computeBlobKzgProof:(Ws,Zs)=>{if("computeBlobProof"in Fs&&typeof Fs.computeBlobProof=="function")return getBytes(Fs.computeBlobProof(hexlify(Ws),hexlify(Zs)));if("computeBlobKzgProof"in Fs&&typeof Fs.computeBlobKzgProof=="function")return Fs.computeBlobKzgProof(Ws,Zs);if("computeBlobKZGProof"in Fs&&typeof Fs.computeBlobKZGProof=="function")return getBytes(Fs.computeBlobKZGProof(hexlify(Ws),hexlify(Zs)));assertArgument(!1,"unsupported KZG library","kzg",Fs)}}}function getVersionedHash(Fs,Ps){let Hs=Fs.toString(16);for(;Hs.length<2;)Hs="0"+Hs;return Hs+=sha256(Ps).substring(4),"0x"+Hs}function handleAddress(Fs){return Fs==="0x"?null:getAddress(Fs)}function handleAccessList(Fs,Ps){try{return accessListify(Fs)}catch(Hs){assertArgument(!1,Hs.message,Ps,Fs)}}function handleAuthorizationList(Fs,Ps){try{if(!Array.isArray(Fs))throw new Error("authorizationList: invalid array");const Hs=[];for(let Ws=0;Ws<Fs.length;Ws++){const Zs=Fs[Ws];if(!Array.isArray(Zs))throw new Error(`authorization[${Ws}]: invalid array`);if(Zs.length!==6)throw new Error(`authorization[${Ws}]: wrong length`);if(!Zs[1])throw new Error(`authorization[${Ws}]: null address`);Hs.push({address:handleAddress(Zs[1]),nonce:handleUint(Zs[2],"nonce"),chainId:handleUint(Zs[0],"chainId"),signature:Signature.from({yParity:handleNumber(Zs[3],"yParity"),r:zeroPadValue(Zs[4],32),s:zeroPadValue(Zs[5],32)})})}return Hs}catch(Hs){assertArgument(!1,Hs.message,Ps,Fs)}}function handleNumber(Fs,Ps){return Fs==="0x"?0:getNumber(Fs,Ps)}function handleUint(Fs,Ps){if(Fs==="0x")return BN_0$4;const Hs=getBigInt(Fs,Ps);return assertArgument(Hs<=BN_MAX_UINT,"value exceeds uint size",Ps,Hs),Hs}function formatNumber(Fs,Ps){const Hs=getBigInt(Fs,"value"),Ws=toBeArray(Hs);return assertArgument(Ws.length<=32,"value too large",`tx.${Ps}`,Hs),Ws}function formatAccessList(Fs){return accessListify(Fs).map(Ps=>[Ps.address,Ps.storageKeys])}function formatAuthorizationList(Fs){return Fs.map(Ps=>[formatNumber(Ps.chainId,"chainId"),Ps.address,formatNumber(Ps.nonce,"nonce"),formatNumber(Ps.signature.yParity,"yParity"),toBeArray(Ps.signature.r),toBeArray(Ps.signature.s)])}function formatHashes(Fs,Ps){assertArgument(Array.isArray(Fs),`invalid ${Ps}`,"value",Fs);for(let Hs=0;Hs<Fs.length;Hs++)assertArgument(isHexString(Fs[Hs],32),"invalid ${ param } hash",`value[${Hs}]`,Fs[Hs]);return Fs}function _parseLegacy(Fs){const Ps=decodeRlp(Fs);assertArgument(Array.isArray(Ps)&&(Ps.length===9||Ps.length===6),"invalid field count for legacy transaction","data",Fs);const Hs={type:0,nonce:handleNumber(Ps[0],"nonce"),gasPrice:handleUint(Ps[1],"gasPrice"),gasLimit:handleUint(Ps[2],"gasLimit"),to:handleAddress(Ps[3]),value:handleUint(Ps[4],"value"),data:hexlify(Ps[5]),chainId:BN_0$4};if(Ps.length===6)return Hs;const Ws=handleUint(Ps[6],"v"),Zs=handleUint(Ps[7],"r"),zs=handleUint(Ps[8],"s");if(Zs===BN_0$4&&zs===BN_0$4)Hs.chainId=Ws;else{let Ys=(Ws-BN_35)/BN_2$1;Ys<BN_0$4&&(Ys=BN_0$4),Hs.chainId=Ys,assertArgument(Ys!==BN_0$4||Ws===BN_27||Ws===BN_28,"non-canonical legacy v","v",Ps[6]),Hs.signature=Signature.from({r:zeroPadValue(Ps[7],32),s:zeroPadValue(Ps[8],32),v:Ws})}return Hs}function _serializeLegacy(Fs,Ps){const Hs=[formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.gasPrice||0,"gasPrice"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data];let Ws=BN_0$4;if(Fs.chainId!=BN_0$4)Ws=getBigInt(Fs.chainId,"tx.chainId"),assertArgument(!Ps||Ps.networkV==null||Ps.legacyChainId===Ws,"tx.chainId/sig.v mismatch","sig",Ps);else if(Fs.signature){const zs=Fs.signature.legacyChainId;zs!=null&&(Ws=zs)}if(!Ps)return Ws!==BN_0$4&&(Hs.push(toBeArray(Ws)),Hs.push("0x"),Hs.push("0x")),encodeRlp(Hs);let Zs=BigInt(27+Ps.yParity);return Ws!==BN_0$4?Zs=Signature.getChainIdV(Ws,Ps.v):BigInt(Ps.v)!==Zs&&assertArgument(!1,"tx.chainId/sig.v mismatch","sig",Ps),Hs.push(toBeArray(Zs)),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s)),encodeRlp(Hs)}function _parseEipSignature(Fs,Ps){let Hs;try{if(Hs=handleNumber(Ps[0],"yParity"),Hs!==0&&Hs!==1)throw new Error("bad yParity")}catch{assertArgument(!1,"invalid yParity","yParity",Ps[0])}const Ws=zeroPadValue(Ps[1],32),Zs=zeroPadValue(Ps[2],32),zs=Signature.from({r:Ws,s:Zs,yParity:Hs});Fs.signature=zs}function _parseEip1559(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===9||Ps.length===12),"invalid field count for transaction type: 2","data",hexlify(Fs));const Hs={type:2,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList")};return Ps.length===9||_parseEipSignature(Hs,Ps.slice(9)),Hs}function _serializeEip1559(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"yParity")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x02",encodeRlp(Hs)])}function _parseEip2930(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===8||Ps.length===11),"invalid field count for transaction type: 1","data",hexlify(Fs));const Hs={type:1,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),gasPrice:handleUint(Ps[2],"gasPrice"),gasLimit:handleUint(Ps[3],"gasLimit"),to:handleAddress(Ps[4]),value:handleUint(Ps[5],"value"),data:hexlify(Ps[6]),accessList:handleAccessList(Ps[7],"accessList")};return Ps.length===8||_parseEipSignature(Hs,Ps.slice(8)),Hs}function _serializeEip2930(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.gasPrice||0,"gasPrice"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"recoveryParam")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x01",encodeRlp(Hs)])}function _parseEip4844(Fs){let Ps=decodeRlp(getBytes(Fs).slice(1)),Hs="3",Ws=null;if(Ps.length===4&&Array.isArray(Ps[0])){Hs="3 (network format)";const zs=Ps[1],Ys=Ps[2],Va=Ps[3];assertArgument(Array.isArray(zs),"invalid network format: blobs not an array","fields[1]",zs),assertArgument(Array.isArray(Ys),"invalid network format: commitments not an array","fields[2]",Ys),assertArgument(Array.isArray(Va),"invalid network format: proofs not an array","fields[3]",Va),assertArgument(zs.length===Ys.length,"invalid network format: blobs/commitments length mismatch","fields",Ps),assertArgument(zs.length===Va.length,"invalid network format: blobs/proofs length mismatch","fields",Ps),Ws=[];for(let Xs=0;Xs<Ps[1].length;Xs++)Ws.push({data:zs[Xs],commitment:Ys[Xs],proof:Va[Xs]});Ps=Ps[0]}assertArgument(Array.isArray(Ps)&&(Ps.length===11||Ps.length===14),`invalid field count for transaction type: ${Hs}`,"data",hexlify(Fs));const Zs={type:3,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList"),maxFeePerBlobGas:handleUint(Ps[9],"maxFeePerBlobGas"),blobVersionedHashes:Ps[10]};Ws&&(Zs.blobs=Ws),assertArgument(Zs.to!=null,`invalid address for transaction type: ${Hs}`,"data",Fs),assertArgument(Array.isArray(Zs.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",Fs);for(let zs=0;zs<Zs.blobVersionedHashes.length;zs++)assertArgument(isHexString(Zs.blobVersionedHashes[zs],32),`invalid blobVersionedHash at index ${zs}: must be length 32`,"data",Fs);return Ps.length===11||_parseEipSignature(Zs,Ps.slice(11)),Zs}function _serializeEip4844(Fs,Ps,Hs){const Ws=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||ZeroAddress,formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[]),formatNumber(Fs.maxFeePerBlobGas||0,"maxFeePerBlobGas"),formatHashes(Fs.blobVersionedHashes||[],"blobVersionedHashes")];return Ps&&(Ws.push(formatNumber(Ps.yParity,"yParity")),Ws.push(toBeArray(Ps.r)),Ws.push(toBeArray(Ps.s)),Hs)?concat(["0x03",encodeRlp([Ws,Hs.map(Zs=>Zs.data),Hs.map(Zs=>Zs.commitment),Hs.map(Zs=>Zs.proof)])]):concat(["0x03",encodeRlp(Ws)])}function _parseEip7702(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===10||Ps.length===13),"invalid field count for transaction type: 4","data",hexlify(Fs));const Hs={type:4,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList"),authorizationList:handleAuthorizationList(Ps[9],"authorizationList")};return Ps.length===10||_parseEipSignature(Hs,Ps.slice(10)),Hs}function _serializeEip7702(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[]),formatAuthorizationList(Fs.authorizationList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"yParity")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x04",encodeRlp(Hs)])}class Transaction{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;#c;#u;#f;#h;#y;get type(){return this.#e}set type(Ps){switch(Ps){case null:this.#e=null;break;case 0:case"legacy":this.#e=0;break;case 1:case"berlin":case"eip-2930":this.#e=1;break;case 2:case"london":case"eip-1559":this.#e=2;break;case 3:case"cancun":case"eip-4844":this.#e=3;break;case 4:case"pectra":case"eip-7702":this.#e=4;break;default:assertArgument(!1,"unsupported transaction type","type",Ps)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const Ps=this.#t;return Ps==null&&this.type===3?ZeroAddress:Ps}set to(Ps){this.#t=Ps==null?null:getAddress(Ps)}get nonce(){return this.#n}set nonce(Ps){this.#n=getNumber(Ps,"value")}get gasLimit(){return this.#o}set gasLimit(Ps){this.#o=getBigInt(Ps)}get gasPrice(){const Ps=this.#s;return Ps==null&&(this.type===0||this.type===1)?BN_0$4:Ps}set gasPrice(Ps){this.#s=Ps==null?null:getBigInt(Ps,"gasPrice")}get maxPriorityFeePerGas(){const Ps=this.#i;return Ps??(this.type===2||this.type===3?BN_0$4:null)}set maxPriorityFeePerGas(Ps){this.#i=Ps==null?null:getBigInt(Ps,"maxPriorityFeePerGas")}get maxFeePerGas(){const Ps=this.#a;return Ps??(this.type===2||this.type===3?BN_0$4:null)}set maxFeePerGas(Ps){this.#a=Ps==null?null:getBigInt(Ps,"maxFeePerGas")}get data(){return this.#r}set data(Ps){this.#r=hexlify(Ps)}get value(){return this.#d}set value(Ps){this.#d=getBigInt(Ps,"value")}get chainId(){return this.#l}set chainId(Ps){this.#l=getBigInt(Ps)}get signature(){return this.#p||null}set signature(Ps){this.#p=Ps==null?null:Signature.from(Ps)}get accessList(){const Ps=this.#g||null;return Ps??(this.type===1||this.type===2||this.type===3?[]:null)}set accessList(Ps){this.#g=Ps==null?null:accessListify(Ps)}get authorizationList(){const Ps=this.#y||null;return Ps==null&&this.type===4?[]:Ps}set authorizationList(Ps){this.#y=Ps==null?null:Ps.map(Hs=>authorizationify(Hs))}get maxFeePerBlobGas(){const Ps=this.#c;return Ps==null&&this.type===3?BN_0$4:Ps}set maxFeePerBlobGas(Ps){this.#c=Ps==null?null:getBigInt(Ps,"maxFeePerBlobGas")}get blobVersionedHashes(){let Ps=this.#u;return Ps==null&&this.type===3?[]:Ps}set blobVersionedHashes(Ps){if(Ps!=null){assertArgument(Array.isArray(Ps),"blobVersionedHashes must be an Array","value",Ps),Ps=Ps.slice();for(let Hs=0;Hs<Ps.length;Hs++)assertArgument(isHexString(Ps[Hs],32),"invalid blobVersionedHash",`value[${Hs}]`,Ps[Hs])}this.#u=Ps}get blobs(){return this.#h==null?null:this.#h.map(Ps=>Object.assign({},Ps))}set blobs(Ps){if(Ps==null){this.#h=null;return}const Hs=[],Ws=[];for(let Zs=0;Zs<Ps.length;Zs++){const zs=Ps[Zs];if(isBytesLike(zs)){assert(this.#f,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let Ys=getBytes(zs);if(assertArgument(Ys.length<=BLOB_SIZE,"blob is too large",`blobs[${Zs}]`,zs),Ys.length!==BLOB_SIZE){const Ma=new Uint8Array(BLOB_SIZE);Ma.set(Ys),Ys=Ma}const Va=this.#f.blobToKzgCommitment(Ys),Xs=hexlify(this.#f.computeBlobKzgProof(Ys,Va));Hs.push({data:hexlify(Ys),commitment:hexlify(Va),proof:Xs}),Ws.push(getVersionedHash(1,Va))}else{const Ys=hexlify(zs.commitment);Hs.push({data:hexlify(zs.data),commitment:Ys,proof:hexlify(zs.proof)}),Ws.push(getVersionedHash(1,Ys))}}this.#h=Hs,this.#u=Ws}get kzg(){return this.#f}set kzg(Ps){Ps==null?this.#f=null:this.#f=getKzgLibrary(Ps)}constructor(){this.#e=null,this.#t=null,this.#n=0,this.#o=BN_0$4,this.#s=null,this.#i=null,this.#a=null,this.#r="0x",this.#d=BN_0$4,this.#l=BN_0$4,this.#p=null,this.#g=null,this.#c=null,this.#u=null,this.#f=null,this.#h=null,this.#y=null}get hash(){return this.signature==null?null:keccak256(this.#m(!0,!1))}get unsignedHash(){return keccak256(this.unsignedSerialized)}get from(){return this.signature==null?null:recoverAddress(this.unsignedHash,this.signature)}get fromPublicKey(){return this.signature==null?null:SigningKey.recoverPublicKey(this.unsignedHash,this.signature)}isSigned(){return this.signature!=null}#m(Ps,Hs){assert(!Ps||this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const Ws=Ps?this.signature:null;switch(this.inferType()){case 0:return _serializeLegacy(this,Ws);case 1:return _serializeEip2930(this,Ws);case 2:return _serializeEip1559(this,Ws);case 3:return _serializeEip4844(this,Ws,Hs?this.blobs:null);case 4:return _serializeEip7702(this,Ws)}assert(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#m(!0,!0)}get unsignedSerialized(){return this.#m(!1,!1)}inferType(){const Ps=this.inferTypes();return Ps.indexOf(2)>=0?2:Ps.pop()}inferTypes(){const Ps=this.gasPrice!=null,Hs=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null,Ws=this.accessList!=null,Zs=this.#c!=null||this.#u;this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null&&assert(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),assert(!Hs||this.type!==0&&this.type!==1,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),assert(this.type!==0||!Ws,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const zs=[];return this.type!=null?zs.push(this.type):this.authorizationList&&this.authorizationList.length?zs.push(4):Hs?zs.push(2):Ps?(zs.push(1),Ws||zs.push(0)):Ws?(zs.push(1),zs.push(2)):(Zs&&this.to||(zs.push(0),zs.push(1),zs.push(2)),zs.push(3)),zs.sort(),zs}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}clone(){return Transaction.from(this)}toJSON(){const Ps=Hs=>Hs==null?null:Hs.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:Ps(this.gasLimit),gasPrice:Ps(this.gasPrice),maxPriorityFeePerGas:Ps(this.maxPriorityFeePerGas),maxFeePerGas:Ps(this.maxFeePerGas),value:Ps(this.value),chainId:Ps(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}static from(Ps){if(Ps==null)return new Transaction;if(typeof Ps=="string"){const Ws=getBytes(Ps);if(Ws[0]>=127)return Transaction.from(_parseLegacy(Ws));switch(Ws[0]){case 1:return Transaction.from(_parseEip2930(Ws));case 2:return Transaction.from(_parseEip1559(Ws));case 3:return Transaction.from(_parseEip4844(Ws));case 4:return Transaction.from(_parseEip7702(Ws))}assert(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const Hs=new Transaction;return Ps.type!=null&&(Hs.type=Ps.type),Ps.to!=null&&(Hs.to=Ps.to),Ps.nonce!=null&&(Hs.nonce=Ps.nonce),Ps.gasLimit!=null&&(Hs.gasLimit=Ps.gasLimit),Ps.gasPrice!=null&&(Hs.gasPrice=Ps.gasPrice),Ps.maxPriorityFeePerGas!=null&&(Hs.maxPriorityFeePerGas=Ps.maxPriorityFeePerGas),Ps.maxFeePerGas!=null&&(Hs.maxFeePerGas=Ps.maxFeePerGas),Ps.maxFeePerBlobGas!=null&&(Hs.maxFeePerBlobGas=Ps.maxFeePerBlobGas),Ps.data!=null&&(Hs.data=Ps.data),Ps.value!=null&&(Hs.value=Ps.value),Ps.chainId!=null&&(Hs.chainId=Ps.chainId),Ps.signature!=null&&(Hs.signature=Signature.from(Ps.signature)),Ps.accessList!=null&&(Hs.accessList=Ps.accessList),Ps.authorizationList!=null&&(Hs.authorizationList=Ps.authorizationList),Ps.blobVersionedHashes!=null&&(Hs.blobVersionedHashes=Ps.blobVersionedHashes),Ps.kzg!=null&&(Hs.kzg=Ps.kzg),Ps.blobs!=null&&(Hs.blobs=Ps.blobs),Ps.hash!=null&&(assertArgument(Hs.isSigned(),"unsigned transaction cannot define '.hash'","tx",Ps),assertArgument(Hs.hash===Ps.hash,"hash mismatch","tx",Ps)),Ps.from!=null&&(assertArgument(Hs.isSigned(),"unsigned transaction cannot define '.from'","tx",Ps),assertArgument(Hs.from.toLowerCase()===(Ps.from||"").toLowerCase(),"from mismatch","tx",Ps)),Hs}}function id(Fs){return keccak256(toUtf8Bytes(Fs))}var COMPRESSED$1="AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQC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LKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI";const FENCED=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]),NSM_MAX=4;function decode_arithmetic(Fs){let Ps=0;function Hs(){return Fs[Ps++]<<8|Fs[Ps++]}let Ws=Hs(),Zs=1,zs=[0,1];for(let yl=1;yl<Ws;yl++)zs.push(Zs+=Hs());let Ys=Hs(),Va=Ps;Ps+=Ys;let Xs=0,Ma=0;function qs(){return Xs==0&&(Ma=Ma<<8|Fs[Ps++],Xs=8),Ma>>--Xs&1}const Js=31,Mc=2**Js,ol=Mc>>>1,Vc=ol>>1,Dc=Mc-1;let sl=0;for(let yl=0;yl<Js;yl++)sl=sl<<1|qs();let ll=[],hl=0,pl=Mc;for(;;){let yl=Math.floor(((sl-hl+1)*Zs-1)/pl),bl=0,Il=Ws;for(;Il-bl>1;){let Sl=bl+Il>>>1;yl<zs[Sl]?Il=Sl:bl=Sl}if(bl==0)break;ll.push(bl);let $l=hl+Math.floor(pl*zs[bl]/Zs),vl=hl+Math.floor(pl*zs[bl+1]/Zs)-1;for(;(($l^vl)&ol)==0;)sl=sl<<1&Dc|qs(),$l=$l<<1&Dc,vl=vl<<1&Dc|1;for(;$l&~vl&Vc;)sl=sl&ol|sl<<1&Dc>>>1|qs(),$l=$l<<1^ol,vl=(vl^ol)<<1|ol|1;hl=$l,pl=1+vl-$l}let gl=Ws-4;return ll.map(yl=>{switch(yl-gl){case 3:return gl+65792+(Fs[Va++]<<16|Fs[Va++]<<8|Fs[Va++]);case 2:return gl+256+(Fs[Va++]<<8|Fs[Va++]);case 1:return gl+Fs[Va++];default:return yl-1}})}function read_payload(Fs){let Ps=0;return()=>Fs[Ps++]}function read_compressed_payload(Fs){return read_payload(decode_arithmetic(unsafe_atob(Fs)))}function unsafe_atob(Fs){let Ps=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((Zs,zs)=>Ps[Zs.charCodeAt(0)]=zs);let Hs=Fs.length,Ws=new Uint8Array(6*Hs>>3);for(let Zs=0,zs=0,Ys=0,Va=0;Zs<Hs;Zs++)Va=Va<<6|Ps[Fs.charCodeAt(Zs)],Ys+=6,Ys>=8&&(Ws[zs++]=Va>>(Ys-=8));return Ws}function signed(Fs){return Fs&1?~Fs>>1:Fs>>1}function read_deltas(Fs,Ps){let Hs=Array(Fs);for(let Ws=0,Zs=0;Ws<Fs;Ws++)Hs[Ws]=Zs+=signed(Ps());return Hs}function read_sorted(Fs,Ps=0){let Hs=[];for(;;){let Ws=Fs(),Zs=Fs();if(!Zs)break;Ps+=Ws;for(let zs=0;zs<Zs;zs++)Hs.push(Ps+zs);Ps+=Zs+1}return Hs}function read_sorted_arrays(Fs){return read_array_while(()=>{let Ps=read_sorted(Fs);if(Ps.length)return Ps})}function read_mapped(Fs){let Ps=[];for(;;){let Hs=Fs();if(Hs==0)break;Ps.push(read_linear_table(Hs,Fs))}for(;;){let Hs=Fs()-1;if(Hs<0)break;Ps.push(read_replacement_table(Hs,Fs))}return Ps.flat()}function read_array_while(Fs){let Ps=[];for(;;){let Hs=Fs(Ps.length);if(!Hs)break;Ps.push(Hs)}return Ps}function read_transposed(Fs,Ps,Hs){let Ws=Array(Fs).fill().map(()=>[]);for(let Zs=0;Zs<Ps;Zs++)read_deltas(Fs,Hs).forEach((zs,Ys)=>Ws[Ys].push(zs));return Ws}function read_linear_table(Fs,Ps){let Hs=1+Ps(),Ws=Ps(),Zs=read_array_while(Ps);return read_transposed(Zs.length,1+Fs,Ps).flatMap((Ys,Va)=>{let[Xs,...Ma]=Ys;return Array(Zs[Va]).fill().map((qs,Js)=>{let Mc=Js*Ws;return[Xs+Js*Hs,Ma.map(ol=>ol+Mc)]})})}function read_replacement_table(Fs,Ps){let Hs=1+Ps();return read_transposed(Hs,1+Fs,Ps).map(Zs=>[Zs[0],Zs.slice(1)])}function read_trie(Fs){let Ps=[],Hs=read_sorted(Fs);return Zs(Ws([]),[]),Ps;function Ws(zs){let Ys=Fs(),Va=read_array_while(()=>{let Xs=read_sorted(Fs).map(Ma=>Hs[Ma]);if(Xs.length)return Ws(Xs)});return{S:Ys,B:Va,Q:zs}}function Zs({S:zs,B:Ys},Va,Xs){if(!(zs&4&&Xs===Va[Va.length-1])){zs&2&&(Xs=Va[Va.length-1]),zs&1&&Ps.push(Va);for(let Ma of Ys)for(let qs of Ma.Q)Zs(Ma,[...Va,qs],Xs)}}}function hex_cp(Fs){return Fs.toString(16).toUpperCase().padStart(2,"0")}function quote_cp(Fs){return`{${hex_cp(Fs)}}`}function explode_cp(Fs){let Ps=[];for(let Hs=0,Ws=Fs.length;Hs<Ws;){let Zs=Fs.codePointAt(Hs);Hs+=Zs<65536?1:2,Ps.push(Zs)}return Ps}function str_from_cps(Fs){let Hs=Fs.length;if(Hs<4096)return String.fromCodePoint(...Fs);let Ws=[];for(let Zs=0;Zs<Hs;)Ws.push(String.fromCodePoint(...Fs.slice(Zs,Zs+=4096)));return Ws.join("")}function compare_arrays(Fs,Ps){let Hs=Fs.length,Ws=Hs-Ps.length;for(let Zs=0;Ws==0&&Zs<Hs;Zs++)Ws=Fs[Zs]-Ps[Zs];return Ws}var COMPRESSED="AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQ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cF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";const S0=44032,L0=4352,V0=4449,T0=4519,L_COUNT=19,V_COUNT=21,T_COUNT=28,N_COUNT=V_COUNT*T_COUNT,S_COUNT=L_COUNT*N_COUNT,S1=S0+S_COUNT,L1=L0+L_COUNT,V1=V0+V_COUNT,T1=T0+T_COUNT;function unpack_cc(Fs){return Fs>>24&255}function unpack_cp(Fs){return Fs&16777215}let SHIFTED_RANK,EXCLUSIONS,DECOMP,RECOMP;function init$1(){let Fs=read_compressed_payload(COMPRESSED);SHIFTED_RANK=new Map(read_sorted_arrays(Fs).flatMap((Ps,Hs)=>Ps.map(Ws=>[Ws,Hs+1<<24]))),EXCLUSIONS=new Set(read_sorted(Fs)),DECOMP=new Map,RECOMP=new Map;for(let[Ps,Hs]of read_mapped(Fs)){if(!EXCLUSIONS.has(Ps)&&Hs.length==2){let[Ws,Zs]=Hs,zs=RECOMP.get(Ws);zs||(zs=new Map,RECOMP.set(Ws,zs)),zs.set(Zs,Ps)}DECOMP.set(Ps,Hs.reverse())}}function is_hangul(Fs){return Fs>=S0&&Fs<S1}function compose_pair(Fs,Ps){if(Fs>=L0&&Fs<L1&&Ps>=V0&&Ps<V1)return S0+(Fs-L0)*N_COUNT+(Ps-V0)*T_COUNT;if(is_hangul(Fs)&&Ps>T0&&Ps<T1&&(Fs-S0)%T_COUNT==0)return Fs+(Ps-T0);{let Hs=RECOMP.get(Fs);return Hs&&(Hs=Hs.get(Ps),Hs)?Hs:-1}}function decomposed(Fs){SHIFTED_RANK||init$1();let Ps=[],Hs=[],Ws=!1;function Zs(zs){let Ys=SHIFTED_RANK.get(zs);Ys&&(Ws=!0,zs|=Ys),Ps.push(zs)}for(let zs of Fs)for(;;){if(zs<128)Ps.push(zs);else if(is_hangul(zs)){let Ys=zs-S0,Va=Ys/N_COUNT|0,Xs=Ys%N_COUNT/T_COUNT|0,Ma=Ys%T_COUNT;Zs(L0+Va),Zs(V0+Xs),Ma>0&&Zs(T0+Ma)}else{let Ys=DECOMP.get(zs);Ys?Hs.push(...Ys):Zs(zs)}if(!Hs.length)break;zs=Hs.pop()}if(Ws&&Ps.length>1){let zs=unpack_cc(Ps[0]);for(let Ys=1;Ys<Ps.length;Ys++){let Va=unpack_cc(Ps[Ys]);if(Va==0||zs<=Va){zs=Va;continue}let Xs=Ys-1;for(;;){let Ma=Ps[Xs+1];if(Ps[Xs+1]=Ps[Xs],Ps[Xs]=Ma,!Xs||(zs=unpack_cc(Ps[--Xs]),zs<=Va))break}zs=unpack_cc(Ps[Ys])}}return Ps}function composed_from_decomposed(Fs){let Ps=[],Hs=[],Ws=-1,Zs=0;for(let zs of Fs){let Ys=unpack_cc(zs),Va=unpack_cp(zs);if(Ws==-1)Ys==0?Ws=Va:Ps.push(Va);else if(Zs>0&&Zs>=Ys)Ys==0?(Ps.push(Ws,...Hs),Hs.length=0,Ws=Va):Hs.push(Va),Zs=Ys;else{let Xs=compose_pair(Ws,Va);Xs>=0?Ws=Xs:Zs==0&&Ys==0?(Ps.push(Ws),Ws=Va):(Hs.push(Va),Zs=Ys)}}return Ws>=0&&Ps.push(Ws,...Hs),Ps}function nfd(Fs){return decomposed(Fs).map(unpack_cp)}function nfc(Fs){return composed_from_decomposed(decomposed(Fs))}const HYPHEN=45,STOP_CH=".",FE0F=65039,UNIQUE_PH=1,Array_from=Fs=>Array.from(Fs);function group_has_cp(Fs,Ps){return Fs.P.has(Ps)||Fs.Q.has(Ps)}class Emoji extends Array{get is_emoji(){return!0}}let MAPPED,IGNORED,CM,NSM,ESCAPE,GROUPS,WHOLE_VALID,WHOLE_MAP,VALID,EMOJI_LIST,EMOJI_ROOT;function init(){if(MAPPED)return;let Fs=read_compressed_payload(COMPRESSED$1);const Ps=()=>read_sorted(Fs),Hs=()=>new Set(Ps()),Ws=(qs,Js)=>Js.forEach(Mc=>qs.add(Mc));MAPPED=new Map(read_mapped(Fs)),IGNORED=Hs(),CM=Ps(),NSM=new Set(Ps().map(qs=>CM[qs])),CM=new Set(CM),ESCAPE=Hs(),Hs();let Zs=read_sorted_arrays(Fs),zs=Fs();const Ys=()=>{let qs=new Set;return Ps().forEach(Js=>Ws(qs,Zs[Js])),Ws(qs,Ps()),qs};GROUPS=read_array_while(qs=>{let Js=read_array_while(Fs).map(Mc=>Mc+96);if(Js.length){let Mc=qs>=zs;Js[0]-=32,Js=str_from_cps(Js),Mc&&(Js=`Restricted[${Js}]`);let ol=Ys(),Vc=Ys(),Dc=!Fs();return{N:Js,P:ol,Q:Vc,M:Dc,R:Mc}}}),WHOLE_VALID=Hs(),WHOLE_MAP=new Map;let Va=Ps().concat(Array_from(WHOLE_VALID)).sort((qs,Js)=>qs-Js);Va.forEach((qs,Js)=>{let Mc=Fs(),ol=Va[Js]=Mc?Va[Js-Mc]:{V:[],M:new Map};ol.V.push(qs),WHOLE_VALID.has(qs)||WHOLE_MAP.set(qs,ol)});for(let{V:qs,M:Js}of new Set(WHOLE_MAP.values())){let Mc=[];for(let Vc of qs){let Dc=GROUPS.filter(ll=>group_has_cp(ll,Vc)),sl=Mc.find(({G:ll})=>Dc.some(hl=>ll.has(hl)));sl||(sl={G:new Set,V:[]},Mc.push(sl)),sl.V.push(Vc),Ws(sl.G,Dc)}let ol=Mc.flatMap(Vc=>Array_from(Vc.G));for(let{G:Vc,V:Dc}of Mc){let sl=new Set(ol.filter(ll=>!Vc.has(ll)));for(let ll of Dc)Js.set(ll,sl)}}VALID=new Set;let Xs=new Set;const Ma=qs=>VALID.has(qs)?Xs.add(qs):VALID.add(qs);for(let qs of GROUPS){for(let Js of qs.P)Ma(Js);for(let Js of qs.Q)Ma(Js)}for(let qs of VALID)!WHOLE_MAP.has(qs)&&!Xs.has(qs)&&WHOLE_MAP.set(qs,UNIQUE_PH);Ws(VALID,nfd(VALID)),EMOJI_LIST=read_trie(Fs).map(qs=>Emoji.from(qs)).sort(compare_arrays),EMOJI_ROOT=new Map;for(let qs of EMOJI_LIST){let Js=[EMOJI_ROOT];for(let Mc of qs){let ol=Js.map(Vc=>{let Dc=Vc.get(Mc);return Dc||(Dc=new Map,Vc.set(Mc,Dc)),Dc});Mc===FE0F?Js.push(...ol):Js=ol}for(let Mc of Js)Mc.V=qs}}function quoted_cp(Fs){return(should_escape(Fs)?"":`${bidi_qq(safe_str_from_cps([Fs]))} `)+quote_cp(Fs)}function bidi_qq(Fs){return`"${Fs}"‎`}function check_label_extension(Fs){if(Fs.length>=4&&Fs[2]==HYPHEN&&Fs[3]==HYPHEN)throw new Error(`invalid label extension: "${str_from_cps(Fs.slice(0,4))}"`)}function check_leading_underscore(Fs){for(let Hs=Fs.lastIndexOf(95);Hs>0;)if(Fs[--Hs]!==95)throw new Error("underscore allowed only at start")}function check_fenced(Fs){let Ps=Fs[0],Hs=FENCED.get(Ps);if(Hs)throw error_placement(`leading ${Hs}`);let Ws=Fs.length,Zs=-1;for(let zs=1;zs<Ws;zs++){Ps=Fs[zs];let Ys=FENCED.get(Ps);if(Ys){if(Zs==zs)throw error_placement(`${Hs} + ${Ys}`);Zs=zs+1,Hs=Ys}}if(Zs==Ws)throw error_placement(`trailing ${Hs}`)}function safe_str_from_cps(Fs,Ps=1/0,Hs=quote_cp){let Ws=[];is_combining_mark(Fs[0])&&Ws.push("◌"),Fs.length>Ps&&(Ps>>=1,Fs=[...Fs.slice(0,Ps),8230,...Fs.slice(-Ps)]);let Zs=0,zs=Fs.length;for(let Ys=0;Ys<zs;Ys++){let Va=Fs[Ys];should_escape(Va)&&(Ws.push(str_from_cps(Fs.slice(Zs,Ys))),Ws.push(Hs(Va)),Zs=Ys+1)}return Ws.push(str_from_cps(Fs.slice(Zs,zs))),Ws.join("")}function is_combining_mark(Fs){return init(),CM.has(Fs)}function should_escape(Fs){return init(),ESCAPE.has(Fs)}function ens_normalize(Fs){return flatten(split(Fs,nfc,filter_fe0f))}function split(Fs,Ps,Hs){if(!Fs)return[];init();let Ws=0;return Fs.split(STOP_CH).map(Zs=>{let zs=explode_cp(Zs),Ys={input:zs,offset:Ws};Ws+=zs.length+1;try{let Va=Ys.tokens=tokens_from_str(zs,Ps,Hs),Xs=Va.length,Ma;if(!Xs)throw new Error("empty label");let qs=Ys.output=Va.flat();if(check_leading_underscore(qs),!(Ys.emoji=Xs>1||Va[0].is_emoji)&&qs.every(Mc=>Mc<128))check_label_extension(qs),Ma="ASCII";else{let Mc=Va.flatMap(ol=>ol.is_emoji?[]:ol);if(!Mc.length)Ma="Emoji";else{if(CM.has(qs[0]))throw error_placement("leading combining mark");for(let Dc=1;Dc<Xs;Dc++){let sl=Va[Dc];if(!sl.is_emoji&&CM.has(sl[0]))throw error_placement(`emoji + combining mark: "${str_from_cps(Va[Dc-1])} + ${safe_str_from_cps([sl[0]])}"`)}check_fenced(qs);let ol=Array_from(new Set(Mc)),[Vc]=determine_group(ol);check_group(Vc,Mc),check_whole(Vc,ol),Ma=Vc.N}}Ys.type=Ma}catch(Va){Ys.error=Va}return Ys})}function check_whole(Fs,Ps){let Hs,Ws=[];for(let Zs of Ps){let zs=WHOLE_MAP.get(Zs);if(zs===UNIQUE_PH)return;if(zs){let Ys=zs.M.get(Zs);if(Hs=Hs?Hs.filter(Va=>Ys.has(Va)):Array_from(Ys),!Hs.length)return}else Ws.push(Zs)}if(Hs){for(let Zs of Hs)if(Ws.every(zs=>group_has_cp(Zs,zs)))throw new Error(`whole-script confusable: ${Fs.N}/${Zs.N}`)}}function determine_group(Fs){let Ps=GROUPS;for(let Hs of Fs){let Ws=Ps.filter(Zs=>group_has_cp(Zs,Hs));if(!Ws.length)throw GROUPS.some(Zs=>group_has_cp(Zs,Hs))?error_group_member(Ps[0],Hs):error_disallowed(Hs);if(Ps=Ws,Ws.length==1)break}return Ps}function flatten(Fs){return Fs.map(({input:Ps,error:Hs,output:Ws})=>{if(Hs){let Zs=Hs.message;throw new Error(Fs.length==1?Zs:`Invalid label ${bidi_qq(safe_str_from_cps(Ps,63))}: ${Zs}`)}return str_from_cps(Ws)}).join(STOP_CH)}function error_disallowed(Fs){return new Error(`disallowed character: ${quoted_cp(Fs)}`)}function error_group_member(Fs,Ps){let Hs=quoted_cp(Ps),Ws=GROUPS.find(Zs=>Zs.P.has(Ps));return Ws&&(Hs=`${Ws.N} ${Hs}`),new Error(`illegal mixture: ${Fs.N} + ${Hs}`)}function error_placement(Fs){return new Error(`illegal placement: ${Fs}`)}function check_group(Fs,Ps){for(let Hs of Ps)if(!group_has_cp(Fs,Hs))throw error_group_member(Fs,Hs);if(Fs.M){let Hs=nfd(Ps);for(let Ws=1,Zs=Hs.length;Ws<Zs;Ws++)if(NSM.has(Hs[Ws])){let zs=Ws+1;for(let Ys;zs<Zs&&NSM.has(Ys=Hs[zs]);zs++)for(let Va=Ws;Va<zs;Va++)if(Hs[Va]==Ys)throw new Error(`duplicate non-spacing marks: ${quoted_cp(Ys)}`);if(zs-Ws>NSM_MAX)throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(Hs.slice(Ws-1,zs)))} (${zs-Ws}/${NSM_MAX})`);Ws=zs}}}function tokens_from_str(Fs,Ps,Hs){let Ws=[],Zs=[];for(Fs=Fs.slice().reverse();Fs.length;){let zs=consume_emoji_reversed(Fs);if(zs)Zs.length&&(Ws.push(Ps(Zs)),Zs=[]),Ws.push(Hs(zs));else{let Ys=Fs.pop();if(VALID.has(Ys))Zs.push(Ys);else{let Va=MAPPED.get(Ys);if(Va)Zs.push(...Va);else if(!IGNORED.has(Ys))throw error_disallowed(Ys)}}}return Zs.length&&Ws.push(Ps(Zs)),Ws}function filter_fe0f(Fs){return Fs.filter(Ps=>Ps!=FE0F)}function consume_emoji_reversed(Fs,Ps){let Hs=EMOJI_ROOT,Ws,Zs=Fs.length;for(;Zs&&(Hs=Hs.get(Fs[--Zs]),!!Hs);){let{V:zs}=Hs;zs&&(Ws=zs,Fs.length=Zs)}return Ws}const Zeros=new Uint8Array(32);Zeros.fill(0);function checkComponent(Fs){return assertArgument(Fs.length!==0,"invalid ENS name; empty component","comp",Fs),Fs}function ensNameSplit(Fs){const Ps=toUtf8Bytes(ensNormalize(Fs)),Hs=[];if(Fs.length===0)return Hs;let Ws=0;for(let Zs=0;Zs<Ps.length;Zs++)Ps[Zs]===46&&(Hs.push(checkComponent(Ps.slice(Ws,Zs))),Ws=Zs+1);return assertArgument(Ws<Ps.length,"invalid ENS name; empty component","name",Fs),Hs.push(checkComponent(Ps.slice(Ws))),Hs}function ensNormalize(Fs){try{if(Fs.length===0)throw new Error("empty label");return ens_normalize(Fs)}catch(Ps){assertArgument(!1,`invalid ENS name (${Ps.message})`,"name",Fs)}}function namehash(Fs){assertArgument(typeof Fs=="string","invalid ENS name; not a string","name",Fs),assertArgument(Fs.length,"invalid ENS name (empty label)","name",Fs);let Ps=Zeros;const Hs=ensNameSplit(Fs);for(;Hs.length;)Ps=keccak256(concat([Ps,keccak256(Hs.pop())]));return hexlify(Ps)}function dnsEncode(Fs,Ps){const Hs=Ps;return assertArgument(Hs<=255,"DNS encoded label cannot exceed 255","length",Hs),hexlify(concat(ensNameSplit(Fs).map(Ws=>{assertArgument(Ws.length<=Hs,`label ${JSON.stringify(Fs)} exceeds ${Hs} bytes`,"name",Fs);const Zs=new Uint8Array(Ws.length+1);return Zs.set(Ws,1),Zs[0]=Zs.length-1,Zs})))+"00"}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1),BN_0$3=BigInt(0),BN_1=BigInt(1),BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(Fs){const Ps=getBytes(Fs),Hs=Ps.length%32;return Hs?concat([Ps,padding.slice(Hs)]):hexlify(Ps)}const hexTrue=toBeHex(BN_1,32),hexFalse=toBeHex(BN_0$3,32),domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(Fs){return function(Ps){return assertArgument(typeof Ps=="string",`invalid domain value for ${JSON.stringify(Fs)}`,`domain.${Fs}`,Ps),Ps}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(Fs){const Ps=getBigInt(Fs,"domain.chainId");return assertArgument(Ps>=0,"invalid chain ID","domain.chainId",Fs),Number.isSafeInteger(Ps)?Number(Ps):toQuantity(Ps)},verifyingContract:function(Fs){try{return getAddress(Fs).toLowerCase()}catch{}assertArgument(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",Fs)},salt:function(Fs){const Ps=getBytes(Fs,"domain.salt");return assertArgument(Ps.length===32,'invalid domain value "salt"',"domain.salt",Fs),hexlify(Ps)}};function getBaseEncoder(Fs){{const Ps=Fs.match(/^(u?)int(\d+)$/);if(Ps){const Hs=Ps[1]==="",Ws=parseInt(Ps[2]);assertArgument(Ws%8===0&&Ws!==0&&Ws<=256&&Ps[2]===String(Ws),"invalid numeric width","type",Fs);const Zs=mask(BN_MAX_UINT256,Hs?Ws-1:Ws),zs=Hs?(Zs+BN_1)*BN__1:BN_0$3;return function(Ys){const Va=getBigInt(Ys,"value");return assertArgument(Va>=zs&&Va<=Zs,`value out-of-bounds for ${Fs}`,"value",Va),toBeHex(Hs?toTwos(Va,256):Va,32)}}}{const Ps=Fs.match(/^bytes(\d+)$/);if(Ps){const Hs=parseInt(Ps[1]);return assertArgument(Hs!==0&&Hs<=32&&Ps[1]===String(Hs),"invalid bytes width","type",Fs),function(Ws){const Zs=getBytes(Ws);return assertArgument(Zs.length===Hs,`invalid length for ${Fs}`,"value",Ws),hexPadRight(Ws)}}}switch(Fs){case"address":return function(Ps){return zeroPadValue(getAddress(Ps),32)};case"bool":return function(Ps){return Ps?hexTrue:hexFalse};case"bytes":return function(Ps){return keccak256(Ps)};case"string":return function(Ps){return id(Ps)}}return null}function encodeType(Fs,Ps){return`${Fs}(${Ps.map(({name:Hs,type:Ws})=>Ws+" "+Hs).join(",")})`}function splitArray(Fs){const Ps=Fs.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return Ps?{base:Ps[1],index:Ps[2]+Ps[4],array:{base:Ps[1],prefix:Ps[1]+Ps[2],count:Ps[5]?parseInt(Ps[5]):-1}}:{base:Fs}}class TypedDataEncoder{primaryType;#e;get types(){return JSON.parse(this.#e)}#t;#r;constructor(Ps){this.#t=new Map,this.#r=new Map;const Hs=new Map,Ws=new Map,Zs=new Map,zs={};Object.keys(Ps).forEach(Xs=>{zs[Xs]=Ps[Xs].map(({name:Ma,type:qs})=>{let{base:Js,index:Mc}=splitArray(qs);return Js==="int"&&!Ps.int&&(Js="int256"),Js==="uint"&&!Ps.uint&&(Js="uint256"),{name:Ma,type:Js+(Mc||"")}}),Hs.set(Xs,new Set),Ws.set(Xs,[]),Zs.set(Xs,new Set)}),this.#e=JSON.stringify(zs);for(const Xs in zs){const Ma=new Set;for(const qs of zs[Xs]){assertArgument(!Ma.has(qs.name),`duplicate variable name ${JSON.stringify(qs.name)} in ${JSON.stringify(Xs)}`,"types",Ps),Ma.add(qs.name);const Js=splitArray(qs.type).base;assertArgument(Js!==Xs,`circular type reference to ${JSON.stringify(Js)}`,"types",Ps),!getBaseEncoder(Js)&&(assertArgument(Ws.has(Js),`unknown type ${JSON.stringify(Js)}`,"types",Ps),Ws.get(Js).push(Xs),Hs.get(Xs).add(Js))}}const Ys=Array.from(Ws.keys()).filter(Xs=>Ws.get(Xs).length===0);assertArgument(Ys.length!==0,"missing primary type","types",Ps),assertArgument(Ys.length===1,`ambiguous primary types or unused types: ${Ys.map(Xs=>JSON.stringify(Xs)).join(", ")}`,"types",Ps),defineProperties(this,{primaryType:Ys[0]});function Va(Xs,Ma){assertArgument(!Ma.has(Xs),`circular type reference to ${JSON.stringify(Xs)}`,"types",Ps),Ma.add(Xs);for(const qs of Hs.get(Xs))if(Ws.has(qs)){Va(qs,Ma);for(const Js of Ma)Zs.get(Js).add(qs)}Ma.delete(Xs)}Va(this.primaryType,new Set);for(const[Xs,Ma]of Zs){const qs=Array.from(Ma);qs.sort(),this.#t.set(Xs,encodeType(Xs,zs[Xs])+qs.map(Js=>encodeType(Js,zs[Js])).join(""))}}getEncoder(Ps){let Hs=this.#r.get(Ps);return Hs||(Hs=this.#n(Ps),this.#r.set(Ps,Hs)),Hs}#n(Ps){{const Zs=getBaseEncoder(Ps);if(Zs)return Zs}const Hs=splitArray(Ps).array;if(Hs){const Zs=Hs.prefix,zs=this.getEncoder(Zs);return Ys=>{assertArgument(Hs.count===-1||Hs.count===Ys.length,`array length mismatch; expected length ${Hs.count}`,"value",Ys);let Va=Ys.map(zs);return this.#t.has(Zs)&&(Va=Va.map(keccak256)),keccak256(concat(Va))}}const Ws=this.types[Ps];if(Ws){const Zs=id(this.#t.get(Ps));return zs=>{const Ys=Ws.map(({name:Va,type:Xs})=>{const Ma=this.getEncoder(Xs)(zs[Va]);return this.#t.has(Xs)?keccak256(Ma):Ma});return Ys.unshift(Zs),concat(Ys)}}assertArgument(!1,`unknown type: ${Ps}`,"type",Ps)}encodeType(Ps){const Hs=this.#t.get(Ps);return assertArgument(Hs,`unknown type: ${JSON.stringify(Ps)}`,"name",Ps),Hs}encodeData(Ps,Hs){return this.getEncoder(Ps)(Hs)}hashStruct(Ps,Hs){return keccak256(this.encodeData(Ps,Hs))}encode(Ps){return this.encodeData(this.primaryType,Ps)}hash(Ps){return this.hashStruct(this.primaryType,Ps)}_visit(Ps,Hs,Ws){if(getBaseEncoder(Ps))return Ws(Ps,Hs);const Zs=splitArray(Ps).array;if(Zs)return assertArgument(Zs.count===-1||Zs.count===Hs.length,`array length mismatch; expected length ${Zs.count}`,"value",Hs),Hs.map(Ys=>this._visit(Zs.prefix,Ys,Ws));const zs=this.types[Ps];if(zs)return zs.reduce((Ys,{name:Va,type:Xs})=>(Ys[Va]=this._visit(Xs,Hs[Va],Ws),Ys),{});assertArgument(!1,`unknown type: ${Ps}`,"type",Ps)}visit(Ps,Hs){return this._visit(this.primaryType,Ps,Hs)}static from(Ps){return new TypedDataEncoder(Ps)}static getPrimaryType(Ps){return TypedDataEncoder.from(Ps).primaryType}static hashStruct(Ps,Hs,Ws){return TypedDataEncoder.from(Hs).hashStruct(Ps,Ws)}static hashDomain(Ps){const Hs=[];for(const Ws in Ps){if(Ps[Ws]==null)continue;const Zs=domainFieldTypes[Ws];assertArgument(Zs,`invalid typed-data domain key: ${JSON.stringify(Ws)}`,"domain",Ps),Hs.push({name:Ws,type:Zs})}return Hs.sort((Ws,Zs)=>domainFieldNames.indexOf(Ws.name)-domainFieldNames.indexOf(Zs.name)),TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:Hs},Ps)}static encode(Ps,Hs,Ws){return concat(["0x1901",TypedDataEncoder.hashDomain(Ps),TypedDataEncoder.from(Hs).hash(Ws)])}static hash(Ps,Hs,Ws){return keccak256(TypedDataEncoder.encode(Ps,Hs,Ws))}static async resolveNames(Ps,Hs,Ws,Zs){Ps=Object.assign({},Ps);for(const Va in Ps)Ps[Va]==null&&delete Ps[Va];const zs={};Ps.verifyingContract&&!isHexString(Ps.verifyingContract,20)&&(zs[Ps.verifyingContract]="0x");const Ys=TypedDataEncoder.from(Hs);Ys.visit(Ws,(Va,Xs)=>(Va==="address"&&!isHexString(Xs,20)&&(zs[Xs]="0x"),Xs));for(const Va in zs)zs[Va]=await Zs(Va);return Ps.verifyingContract&&zs[Ps.verifyingContract]&&(Ps.verifyingContract=zs[Ps.verifyingContract]),Ws=Ys.visit(Ws,(Va,Xs)=>Va==="address"&&zs[Xs]?zs[Xs]:Xs),{domain:Ps,value:Ws}}static getPayload(Ps,Hs,Ws){TypedDataEncoder.hashDomain(Ps);const Zs={},zs=[];domainFieldNames.forEach(Xs=>{const Ma=Ps[Xs];Ma!=null&&(Zs[Xs]=domainChecks[Xs](Ma),zs.push({name:Xs,type:domainFieldTypes[Xs]}))});const Ys=TypedDataEncoder.from(Hs);Hs=Ys.types;const Va=Object.assign({},Hs);return assertArgument(Va.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",Hs),Va.EIP712Domain=zs,Ys.encode(Ws),{types:Va,domain:Zs,primaryType:Ys.primaryType,message:Ys.visit(Ws,(Xs,Ma)=>{if(Xs.match(/^bytes(\d*)/))return hexlify(getBytes(Ma));if(Xs.match(/^u?int/))return getBigInt(Ma).toString();switch(Xs){case"address":return Ma.toLowerCase();case"bool":return!!Ma;case"string":return assertArgument(typeof Ma=="string","invalid string","value",Ma),Ma}assertArgument(!1,"unsupported type","type",Xs)})}}}function setify(Fs){const Ps=new Set;return Fs.forEach(Hs=>Ps.add(Hs)),Object.freeze(Ps)}const _kwVisibDeploy="external public payable override",KwVisibDeploy=setify(_kwVisibDeploy.split(" ")),_kwVisib="constant external internal payable private public pure view override",KwVisib=setify(_kwVisib.split(" ")),_kwTypes="constructor error event fallback function receive struct",KwTypes=setify(_kwTypes.split(" ")),_kwModifiers="calldata memory storage payable indexed",KwModifiers=setify(_kwModifiers.split(" ")),_kwOther="tuple returns",_keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" "),Keywords=setify(_keywords.split(" ")),SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},regexWhitespacePrefix=new RegExp("^(\\s*)"),regexNumberPrefix=new RegExp("^([0-9]+)"),regexIdPrefix=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),regexId=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class TokenString{#e;#t;get offset(){return this.#e}get length(){return this.#t.length-this.#e}constructor(Ps){this.#e=0,this.#t=Ps.slice()}clone(){return new TokenString(this.#t)}reset(){this.#e=0}#r(Ps=0,Hs=0){return new TokenString(this.#t.slice(Ps,Hs).map(Ws=>Object.freeze(Object.assign({},Ws,{match:Ws.match-Ps,linkBack:Ws.linkBack-Ps,linkNext:Ws.linkNext-Ps}))))}popKeyword(Ps){const Hs=this.peek();if(Hs.type!=="KEYWORD"||!Ps.has(Hs.text))throw new Error(`expected keyword ${Hs.text}`);return this.pop().text}popType(Ps){if(this.peek().type!==Ps){const Hs=this.peek();throw new Error(`expected ${Ps}; got ${Hs.type} ${JSON.stringify(Hs.text)}`)}return this.pop().text}popParen(){const Ps=this.peek();if(Ps.type!=="OPEN_PAREN")throw new Error("bad start");const Hs=this.#r(this.#e+1,Ps.match+1);return this.#e=Ps.match+1,Hs}popParams(){const Ps=this.peek();if(Ps.type!=="OPEN_PAREN")throw new Error("bad start");const Hs=[];for(;this.#e<Ps.match-1;){const Ws=this.peek().linkNext;Hs.push(this.#r(this.#e+1,Ws)),this.#e=Ws}return this.#e=Ps.match+1,Hs}peek(){if(this.#e>=this.#t.length)throw new Error("out-of-bounds");return this.#t[this.#e]}peekKeyword(Ps){const Hs=this.peekType("KEYWORD");return Hs!=null&&Ps.has(Hs)?Hs:null}peekType(Ps){if(this.length===0)return null;const Hs=this.peek();return Hs.type===Ps?Hs.text:null}pop(){const Ps=this.peek();return this.#e++,Ps}toString(){const Ps=[];for(let Hs=this.#e;Hs<this.#t.length;Hs++){const Ws=this.#t[Hs];Ps.push(`${Ws.type}:${Ws.text}`)}return`<TokenString ${Ps.join(" ")}>`}}function lex(Fs){const Ps=[],Hs=Ys=>{const Va=zs<Fs.length?JSON.stringify(Fs[zs]):"$EOI";throw new Error(`invalid token ${Va} at ${zs}: ${Ys}`)};let Ws=[],Zs=[],zs=0;for(;zs<Fs.length;){let Ys=Fs.substring(zs),Va=Ys.match(regexWhitespacePrefix);Va&&(zs+=Va[1].length,Ys=Fs.substring(zs));const Xs={depth:Ws.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:zs,value:-1};Ps.push(Xs);let Ma=SimpleTokens[Ys[0]]||"";if(Ma){if(Xs.type=Ma,Xs.text=Ys[0],zs++,Ma==="OPEN_PAREN")Ws.push(Ps.length-1),Zs.push(Ps.length-1);else if(Ma=="CLOSE_PAREN")Ws.length===0&&Hs("no matching open bracket"),Xs.match=Ws.pop(),Ps[Xs.match].match=Ps.length-1,Xs.depth--,Xs.linkBack=Zs.pop(),Ps[Xs.linkBack].linkNext=Ps.length-1;else if(Ma==="COMMA")Xs.linkBack=Zs.pop(),Ps[Xs.linkBack].linkNext=Ps.length-1,Zs.push(Ps.length-1);else if(Ma==="OPEN_BRACKET")Xs.type="BRACKET";else if(Ma==="CLOSE_BRACKET"){let qs=Ps.pop().text;if(Ps.length>0&&Ps[Ps.length-1].type==="NUMBER"){const Js=Ps.pop().text;qs=Js+qs,Ps[Ps.length-1].value=getNumber(Js)}if(Ps.length===0||Ps[Ps.length-1].type!=="BRACKET")throw new Error("missing opening bracket");Ps[Ps.length-1].text+=qs}continue}if(Va=Ys.match(regexIdPrefix),Va){if(Xs.text=Va[1],zs+=Xs.text.length,Keywords.has(Xs.text)){Xs.type="KEYWORD";continue}if(Xs.text.match(regexType)){Xs.type="TYPE";continue}Xs.type="ID";continue}if(Va=Ys.match(regexNumberPrefix),Va){Xs.text=Va[1],Xs.type="NUMBER",zs+=Xs.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(Ys[0])} at position ${zs}`)}return new TokenString(Ps.map(Ys=>Object.freeze(Ys)))}function allowSingle(Fs,Ps){let Hs=[];for(const Ws in Ps.keys())Fs.has(Ws)&&Hs.push(Ws);if(Hs.length>1)throw new Error(`conflicting types: ${Hs.join(", ")}`)}function consumeName(Fs,Ps){if(Ps.peekKeyword(KwTypes)){const Hs=Ps.pop().text;if(Hs!==Fs)throw new Error(`expected ${Fs}, got ${Hs}`)}return Ps.popType("ID")}function consumeKeywords(Fs,Ps){const Hs=new Set;for(;;){const Ws=Fs.peekType("KEYWORD");if(Ws==null||Ps&&!Ps.has(Ws))break;if(Fs.pop(),Hs.has(Ws))throw new Error(`duplicate keywords: ${JSON.stringify(Ws)}`);Hs.add(Ws)}return Object.freeze(Hs)}function consumeMutability(Fs){let Ps=consumeKeywords(Fs,KwVisib);return allowSingle(Ps,setify("constant payable nonpayable".split(" "))),allowSingle(Ps,setify("pure view payable nonpayable".split(" "))),Ps.has("view")?"view":Ps.has("pure")?"pure":Ps.has("payable")?"payable":Ps.has("nonpayable")?"nonpayable":Ps.has("constant")?"view":"nonpayable"}function consumeParams(Fs,Ps){return Fs.popParams().map(Hs=>ParamType.from(Hs,Ps))}function consumeGas(Fs){if(Fs.peekType("AT")){if(Fs.pop(),Fs.peekType("NUMBER"))return getBigInt(Fs.pop().text);throw new Error("invalid gas")}return null}function consumeEoi(Fs){if(Fs.length)throw new Error(`unexpected tokens at offset ${Fs.offset}: ${Fs.toString()}`)}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(Fs){const Ps=Fs.match(regexType);if(assertArgument(Ps,"invalid type","type",Fs),Fs==="uint")return"uint256";if(Fs==="int")return"int256";if(Ps[2]){const Hs=parseInt(Ps[2]);assertArgument(Hs!==0&&Hs<=32,"invalid bytes length","type",Fs)}else if(Ps[3]){const Hs=parseInt(Ps[3]);assertArgument(Hs!==0&&Hs<=256&&Hs%8===0,"invalid numeric width","type",Fs)}return Fs}const _guard={},internal$1=Symbol.for("_ethers_internal"),ParamTypeInternal="_ParamTypeInternal",ErrorFragmentInternal="_ErrorInternal",EventFragmentInternal="_EventInternal",ConstructorFragmentInternal="_ConstructorInternal",FallbackFragmentInternal="_FallbackInternal",FunctionFragmentInternal="_FunctionInternal",StructFragmentInternal="_StructInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs){if(assertPrivate(Ps,_guard,"ParamType"),Object.defineProperty(this,internal$1,{value:ParamTypeInternal}),Ys&&(Ys=Object.freeze(Ys.slice())),Zs==="array"){if(Va==null||Xs==null)throw new Error("")}else if(Va!=null||Xs!=null)throw new Error("");if(Zs==="tuple"){if(Ys==null)throw new Error("")}else if(Ys!=null)throw new Error("");defineProperties(this,{name:Hs,type:Ws,baseType:Zs,indexed:zs,components:Ys,arrayLength:Va,arrayChildren:Xs})}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json"){const Ws=this.name||"";if(this.isArray()){const zs=JSON.parse(this.arrayChildren.format("json"));return zs.name=Ws,zs.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(zs)}const Zs={type:this.baseType==="tuple"?"tuple":this.type,name:Ws};return typeof this.indexed=="boolean"&&(Zs.indexed=this.indexed),this.isTuple()&&(Zs.components=this.components.map(zs=>JSON.parse(zs.format(Ps)))),JSON.stringify(Zs)}let Hs="";return this.isArray()?(Hs+=this.arrayChildren.format(Ps),Hs+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?Hs+="("+this.components.map(Ws=>Ws.format(Ps)).join(Ps==="full"?", ":",")+")":Hs+=this.type,Ps!=="sighash"&&(this.indexed===!0&&(Hs+=" indexed"),Ps==="full"&&this.name&&(Hs+=" "+this.name)),Hs}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(Ps,Hs){if(this.isArray()){if(!Array.isArray(Ps))throw new Error("invalid array value");if(this.arrayLength!==-1&&Ps.length!==this.arrayLength)throw new Error("array is wrong length");const Ws=this;return Ps.map(Zs=>Ws.arrayChildren.walk(Zs,Hs))}if(this.isTuple()){if(!Array.isArray(Ps))throw new Error("invalid tuple value");if(Ps.length!==this.components.length)throw new Error("array is wrong length");const Ws=this;return Ps.map((Zs,zs)=>Ws.components[zs].walk(Zs,Hs))}return Hs(this.type,Ps)}#e(Ps,Hs,Ws,Zs){if(this.isArray()){if(!Array.isArray(Hs))throw new Error("invalid array value");if(this.arrayLength!==-1&&Hs.length!==this.arrayLength)throw new Error("array is wrong length");const Ys=this.arrayChildren,Va=Hs.slice();Va.forEach((Xs,Ma)=>{Ys.#e(Ps,Xs,Ws,qs=>{Va[Ma]=qs})}),Zs(Va);return}if(this.isTuple()){const Ys=this.components;let Va;if(Array.isArray(Hs))Va=Hs.slice();else{if(Hs==null||typeof Hs!="object")throw new Error("invalid tuple value");Va=Ys.map(Xs=>{if(!Xs.name)throw new Error("cannot use object value with unnamed components");if(!(Xs.name in Hs))throw new Error(`missing value for component ${Xs.name}`);return Hs[Xs.name]})}if(Va.length!==this.components.length)throw new Error("array is wrong length");Va.forEach((Xs,Ma)=>{Ys[Ma].#e(Ps,Xs,Ws,qs=>{Va[Ma]=qs})}),Zs(Va);return}const zs=Ws(this.type,Hs);zs.then?Ps.push((async function(){Zs(await zs)})()):Zs(zs)}async walkAsync(Ps,Hs){const Ws=[],Zs=[Ps];return this.#e(Ws,Ps,Hs,zs=>{Zs[0]=zs}),Ws.length&&await Promise.all(Ws),Zs[0]}static from(Ps,Hs){if(ParamType.isParamType(Ps))return Ps;if(typeof Ps=="string")try{return ParamType.from(lex(Ps),Hs)}catch{assertArgument(!1,"invalid param type","obj",Ps)}else if(Ps instanceof TokenString){let Va="",Xs="",Ma=null;consumeKeywords(Ps,setify(["tuple"])).has("tuple")||Ps.peekType("OPEN_PAREN")?(Xs="tuple",Ma=Ps.popParams().map(Dc=>ParamType.from(Dc)),Va=`tuple(${Ma.map(Dc=>Dc.format()).join(",")})`):(Va=verifyBasicType(Ps.popType("TYPE")),Xs=Va);let qs=null,Js=null;for(;Ps.length&&Ps.peekType("BRACKET");){const Dc=Ps.pop();qs=new ParamType(_guard,"",Va,Xs,null,Ma,Js,qs),Js=Dc.value,Va+=Dc.text,Xs="array",Ma=null}let Mc=null;if(consumeKeywords(Ps,KwModifiers).has("indexed")){if(!Hs)throw new Error("");Mc=!0}const Vc=Ps.peekType("ID")?Ps.pop().text:"";if(Ps.length)throw new Error("leftover tokens");return new ParamType(_guard,Vc,Va,Xs,Mc,Ma,Js,qs)}const Ws=Ps.name;assertArgument(!Ws||typeof Ws=="string"&&Ws.match(regexId),"invalid name","obj.name",Ws);let Zs=Ps.indexed;Zs!=null&&(assertArgument(Hs,"parameter cannot be indexed","obj.indexed",Ps.indexed),Zs=!!Zs);let zs=Ps.type,Ys=zs.match(regexArrayType);if(Ys){const Va=parseInt(Ys[2]||"-1"),Xs=ParamType.from({type:Ys[1],components:Ps.components});return new ParamType(_guard,Ws||"",zs,"array",Zs,null,Va,Xs)}if(zs==="tuple"||zs.startsWith("tuple(")||zs.startsWith("(")){const Va=Ps.components!=null?Ps.components.map(Ma=>ParamType.from(Ma)):null;return new ParamType(_guard,Ws||"",zs,"tuple",Zs,Va,null,null)}return zs=verifyBasicType(Ps.type),new ParamType(_guard,Ws||"",zs,zs,Zs,null,null,null)}static isParamType(Ps){return Ps&&Ps[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(Ps,Hs,Ws){assertPrivate(Ps,_guard,"Fragment"),Ws=Object.freeze(Ws.slice()),defineProperties(this,{type:Hs,inputs:Ws})}static from(Ps){if(typeof Ps=="string"){try{Fragment.from(JSON.parse(Ps))}catch{}return Fragment.from(lex(Ps))}if(Ps instanceof TokenString)switch(Ps.peekKeyword(KwTypes)){case"constructor":return ConstructorFragment.from(Ps);case"error":return ErrorFragment.from(Ps);case"event":return EventFragment.from(Ps);case"fallback":case"receive":return FallbackFragment.from(Ps);case"function":return FunctionFragment.from(Ps);case"struct":return StructFragment.from(Ps)}else if(typeof Ps=="object"){switch(Ps.type){case"constructor":return ConstructorFragment.from(Ps);case"error":return ErrorFragment.from(Ps);case"event":return EventFragment.from(Ps);case"fallback":case"receive":return FallbackFragment.from(Ps);case"function":return FunctionFragment.from(Ps);case"struct":return StructFragment.from(Ps)}assert(!1,`unsupported type: ${Ps.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}assertArgument(!1,"unsupported frgament object","obj",Ps)}static isConstructor(Ps){return ConstructorFragment.isFragment(Ps)}static isError(Ps){return ErrorFragment.isFragment(Ps)}static isEvent(Ps){return EventFragment.isFragment(Ps)}static isFunction(Ps){return FunctionFragment.isFragment(Ps)}static isStruct(Ps){return StructFragment.isFragment(Ps)}}class NamedFragment extends Fragment{name;constructor(Ps,Hs,Ws,Zs){super(Ps,Hs,Zs),assertArgument(typeof Ws=="string"&&Ws.match(regexId),"invalid identifier","name",Ws),Zs=Object.freeze(Zs.slice()),defineProperties(this,{name:Ws})}}function joinParams(Fs,Ps){return"("+Ps.map(Hs=>Hs.format(Fs)).join(Fs==="full"?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(Ps,Hs,Ws){super(Ps,"error",Hs,Ws),Object.defineProperty(this,internal$1,{value:ErrorFragmentInternal})}get selector(){return id(this.format("sighash")).substring(0,10)}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("error"),Hs.push(this.name+joinParams(Ps,this.inputs)),Hs.join(" ")}static from(Ps){if(ErrorFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")return ErrorFragment.from(lex(Ps));if(Ps instanceof TokenString){const Hs=consumeName("error",Ps),Ws=consumeParams(Ps);return consumeEoi(Ps),new ErrorFragment(_guard,Hs,Ws)}return new ErrorFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(ParamType.from):[])}static isFragment(Ps){return Ps&&Ps[internal$1]===ErrorFragmentInternal}}class EventFragment extends NamedFragment{anonymous;constructor(Ps,Hs,Ws,Zs){super(Ps,"event",Hs,Ws),Object.defineProperty(this,internal$1,{value:EventFragmentInternal}),defineProperties(this,{anonymous:Zs})}get topicHash(){return id(this.format("sighash"))}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("event"),Hs.push(this.name+joinParams(Ps,this.inputs)),Ps!=="sighash"&&this.anonymous&&Hs.push("anonymous"),Hs.join(" ")}static getTopicHash(Ps,Hs){return Hs=(Hs||[]).map(Zs=>ParamType.from(Zs)),new EventFragment(_guard,Ps,Hs,!1).topicHash}static from(Ps){if(EventFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return EventFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid event fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=consumeName("event",Ps),Ws=consumeParams(Ps,!0),Zs=!!consumeKeywords(Ps,setify(["anonymous"])).has("anonymous");return consumeEoi(Ps),new EventFragment(_guard,Hs,Ws,Zs)}return new EventFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(Hs=>ParamType.from(Hs,!0)):[],!!Ps.anonymous)}static isFragment(Ps){return Ps&&Ps[internal$1]===EventFragmentInternal}}class ConstructorFragment extends Fragment{payable;gas;constructor(Ps,Hs,Ws,Zs,zs){super(Ps,Hs,Ws),Object.defineProperty(this,internal$1,{value:ConstructorFragmentInternal}),defineProperties(this,{payable:Zs,gas:zs})}format(Ps){if(assert(Ps!=null&&Ps!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),Ps==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[`constructor${joinParams(Ps,this.inputs)}`];return this.payable&&Hs.push("payable"),this.gas!=null&&Hs.push(`@${this.gas.toString()}`),Hs.join(" ")}static from(Ps){if(ConstructorFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return ConstructorFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid constuctor fragment","obj",Ps)}else if(Ps instanceof TokenString){consumeKeywords(Ps,setify(["constructor"]));const Hs=consumeParams(Ps),Ws=!!consumeKeywords(Ps,KwVisibDeploy).has("payable"),Zs=consumeGas(Ps);return consumeEoi(Ps),new ConstructorFragment(_guard,"constructor",Hs,Ws,Zs)}return new ConstructorFragment(_guard,"constructor",Ps.inputs?Ps.inputs.map(ParamType.from):[],!!Ps.payable,Ps.gas!=null?Ps.gas:null)}static isFragment(Ps){return Ps&&Ps[internal$1]===ConstructorFragmentInternal}}class FallbackFragment extends Fragment{payable;constructor(Ps,Hs,Ws){super(Ps,"fallback",Hs),Object.defineProperty(this,internal$1,{value:FallbackFragmentInternal}),defineProperties(this,{payable:Ws})}format(Ps){const Hs=this.inputs.length===0?"receive":"fallback";if(Ps==="json"){const Ws=this.payable?"payable":"nonpayable";return JSON.stringify({type:Hs,stateMutability:Ws})}return`${Hs}()${this.payable?" payable":""}`}static from(Ps){if(FallbackFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return FallbackFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid fallback fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=Ps.toString(),Ws=Ps.peekKeyword(setify(["fallback","receive"]));if(assertArgument(Ws,"type must be fallback or receive","obj",Hs),Ps.popKeyword(setify(["fallback","receive"]))==="receive"){const Va=consumeParams(Ps);return assertArgument(Va.length===0,"receive cannot have arguments","obj.inputs",Va),consumeKeywords(Ps,setify(["payable"])),consumeEoi(Ps),new FallbackFragment(_guard,[],!0)}let zs=consumeParams(Ps);zs.length?assertArgument(zs.length===1&&zs[0].type==="bytes","invalid fallback inputs","obj.inputs",zs.map(Va=>Va.format("minimal")).join(", ")):zs=[ParamType.from("bytes")];const Ys=consumeMutability(Ps);if(assertArgument(Ys==="nonpayable"||Ys==="payable","fallback cannot be constants","obj.stateMutability",Ys),consumeKeywords(Ps,setify(["returns"])).has("returns")){const Va=consumeParams(Ps);assertArgument(Va.length===1&&Va[0].type==="bytes","invalid fallback outputs","obj.outputs",Va.map(Xs=>Xs.format("minimal")).join(", "))}return consumeEoi(Ps),new FallbackFragment(_guard,zs,Ys==="payable")}if(Ps.type==="receive")return new FallbackFragment(_guard,[],!0);if(Ps.type==="fallback"){const Hs=[ParamType.from("bytes")],Ws=Ps.stateMutability==="payable";return new FallbackFragment(_guard,Hs,Ws)}assertArgument(!1,"invalid fallback description","obj",Ps)}static isFragment(Ps){return Ps&&Ps[internal$1]===FallbackFragmentInternal}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(Ps,Hs,Ws,Zs,zs,Ys){super(Ps,"function",Hs,Zs),Object.defineProperty(this,internal$1,{value:FunctionFragmentInternal}),zs=Object.freeze(zs.slice()),defineProperties(this,{constant:Ws==="view"||Ws==="pure",gas:Ys,outputs:zs,payable:Ws==="payable",stateMutability:Ws})}get selector(){return id(this.format("sighash")).substring(0,10)}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps))),outputs:this.outputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("function"),Hs.push(this.name+joinParams(Ps,this.inputs)),Ps!=="sighash"&&(this.stateMutability!=="nonpayable"&&Hs.push(this.stateMutability),this.outputs&&this.outputs.length&&(Hs.push("returns"),Hs.push(joinParams(Ps,this.outputs))),this.gas!=null&&Hs.push(`@${this.gas.toString()}`)),Hs.join(" ")}static getSelector(Ps,Hs){return Hs=(Hs||[]).map(Zs=>ParamType.from(Zs)),new FunctionFragment(_guard,Ps,"view",Hs,[],null).selector}static from(Ps){if(FunctionFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return FunctionFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid function fragment","obj",Ps)}else if(Ps instanceof TokenString){const Ws=consumeName("function",Ps),Zs=consumeParams(Ps),zs=consumeMutability(Ps);let Ys=[];consumeKeywords(Ps,setify(["returns"])).has("returns")&&(Ys=consumeParams(Ps));const Va=consumeGas(Ps);return consumeEoi(Ps),new FunctionFragment(_guard,Ws,zs,Zs,Ys,Va)}let Hs=Ps.stateMutability;return Hs==null&&(Hs="payable",typeof Ps.constant=="boolean"?(Hs="view",Ps.constant||(Hs="payable",typeof Ps.payable=="boolean"&&!Ps.payable&&(Hs="nonpayable"))):typeof Ps.payable=="boolean"&&!Ps.payable&&(Hs="nonpayable")),new FunctionFragment(_guard,Ps.name,Hs,Ps.inputs?Ps.inputs.map(ParamType.from):[],Ps.outputs?Ps.outputs.map(ParamType.from):[],Ps.gas!=null?Ps.gas:null)}static isFragment(Ps){return Ps&&Ps[internal$1]===FunctionFragmentInternal}}class StructFragment extends NamedFragment{constructor(Ps,Hs,Ws){super(Ps,"struct",Hs,Ws),Object.defineProperty(this,internal$1,{value:StructFragmentInternal})}format(){throw new Error("@TODO")}static from(Ps){if(typeof Ps=="string")try{return StructFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid struct fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=consumeName("struct",Ps),Ws=consumeParams(Ps);return consumeEoi(Ps),new StructFragment(_guard,Hs,Ws)}return new StructFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(ParamType.from):[])}static isFragment(Ps){return Ps&&Ps[internal$1]===StructFragmentInternal}}const PanicReasons$1=new Map;PanicReasons$1.set(0,"GENERIC_PANIC"),PanicReasons$1.set(1,"ASSERT_FALSE"),PanicReasons$1.set(17,"OVERFLOW"),PanicReasons$1.set(18,"DIVIDE_BY_ZERO"),PanicReasons$1.set(33,"ENUM_RANGE_ERROR"),PanicReasons$1.set(34,"BAD_STORAGE_DATA"),PanicReasons$1.set(49,"STACK_UNDERFLOW"),PanicReasons$1.set(50,"ARRAY_RANGE_ERROR"),PanicReasons$1.set(65,"OUT_OF_MEMORY"),PanicReasons$1.set(81,"UNINITIALIZED_FUNCTION_CALL");const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/),paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);let defaultCoder=null,defaultMaxInflation=1024;function getBuiltinCallException(Fs,Ps,Hs,Ws){let Zs="missing revert data",zs=null;const Ys=null;let Va=null;if(Hs){Zs="execution reverted";const Ma=getBytes(Hs);if(Hs=hexlify(Hs),Ma.length===0)Zs+=" (no data present; likely require(false) occurred",zs="require(false)";else if(Ma.length%32!==4)Zs+=" (could not decode reason; invalid data length)";else if(hexlify(Ma.slice(0,4))==="0x08c379a0")try{zs=Ws.decode(["string"],Ma.slice(4))[0],Va={signature:"Error(string)",name:"Error",args:[zs]},Zs+=`: ${JSON.stringify(zs)}`}catch{Zs+=" (could not decode reason; invalid string data)"}else if(hexlify(Ma.slice(0,4))==="0x4e487b71")try{const qs=Number(Ws.decode(["uint256"],Ma.slice(4))[0]);Va={signature:"Panic(uint256)",name:"Panic",args:[qs]},zs=`Panic due to ${PanicReasons$1.get(qs)||"UNKNOWN"}(${qs})`,Zs+=`: ${zs}`}catch{Zs+=" (could not decode panic code)"}else Zs+=" (unknown custom error)"}const Xs={to:Ps.to?getAddress(Ps.to):null,data:Ps.data||"0x"};return Ps.from&&(Xs.from=getAddress(Ps.from)),makeError(Zs,"CALL_EXCEPTION",{action:Fs,data:Hs,reason:zs,transaction:Xs,invocation:Ys,revert:Va})}class AbiCoder{#e(Ps){if(Ps.isArray())return new ArrayCoder(this.#e(Ps.arrayChildren),Ps.arrayLength,Ps.name);if(Ps.isTuple())return new TupleCoder(Ps.components.map(Ws=>this.#e(Ws)),Ps.name);switch(Ps.baseType){case"address":return new AddressCoder(Ps.name);case"bool":return new BooleanCoder(Ps.name);case"string":return new StringCoder(Ps.name);case"bytes":return new BytesCoder(Ps.name);case"":return new NullCoder(Ps.name)}let Hs=Ps.type.match(paramTypeNumber);if(Hs){let Ws=parseInt(Hs[2]||"256");return assertArgument(Ws!==0&&Ws<=256&&Ws%8===0,"invalid "+Hs[1]+" bit length","param",Ps),new NumberCoder(Ws/8,Hs[1]==="int",Ps.name)}if(Hs=Ps.type.match(paramTypeBytes),Hs){let Ws=parseInt(Hs[1]);return assertArgument(Ws!==0&&Ws<=32,"invalid bytes length","param",Ps),new FixedBytesCoder(Ws,Ps.name)}assertArgument(!1,"invalid type","type",Ps.type)}getDefaultValue(Ps){const Hs=Ps.map(Zs=>this.#e(ParamType.from(Zs)));return new TupleCoder(Hs,"_").defaultValue()}encode(Ps,Hs){assertArgumentCount(Hs.length,Ps.length,"types/values length mismatch");const Ws=Ps.map(Ys=>this.#e(ParamType.from(Ys))),Zs=new TupleCoder(Ws,"_"),zs=new Writer;return Zs.encode(zs,Hs),zs.data}decode(Ps,Hs,Ws){const Zs=Ps.map(Ys=>this.#e(ParamType.from(Ys)));return new TupleCoder(Zs,"_").decode(new Reader(Hs,Ws,defaultMaxInflation))}static _setDefaultMaxInflation(Ps){assertArgument(typeof Ps=="number"&&Number.isInteger(Ps),"invalid defaultMaxInflation factor","value",Ps),defaultMaxInflation=Ps}static defaultAbiCoder(){return defaultCoder==null&&(defaultCoder=new AbiCoder),defaultCoder}static getBuiltinCallException(Ps,Hs,Ws){return getBuiltinCallException(Ps,Hs,Ws,AbiCoder.defaultAbiCoder())}}class LogDescription{fragment;name;signature;topic;args;constructor(Ps,Hs,Ws){const Zs=Ps.name,zs=Ps.format();defineProperties(this,{fragment:Ps,name:Zs,signature:zs,topic:Hs,args:Ws})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(Ps,Hs,Ws,Zs){const zs=Ps.name,Ys=Ps.format();defineProperties(this,{fragment:Ps,name:zs,args:Ws,signature:Ys,selector:Hs,value:Zs})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(Ps,Hs,Ws){const Zs=Ps.name,zs=Ps.format();defineProperties(this,{fragment:Ps,name:Zs,args:Ws,signature:zs,selector:Hs})}}class Indexed{hash;_isIndexed;static isIndexed(Ps){return!!(Ps&&Ps._isIndexed)}constructor(Ps){defineProperties(this,{hash:Ps,_isIndexed:!0})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:Fs=>`reverted with reason string ${JSON.stringify(Fs)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:Fs=>{let Ps="unknown panic code";return Fs>=0&&Fs<=255&&PanicReasons[Fs.toString()]&&(Ps=PanicReasons[Fs.toString()]),`reverted with panic code 0x${Fs.toString(16)} (${Ps})`}}};class Interface{fragments;deploy;fallback;receive;#e;#t;#r;#n;constructor(Ps){let Hs=[];typeof Ps=="string"?Hs=JSON.parse(Ps):Hs=Ps,this.#r=new Map,this.#e=new Map,this.#t=new Map;const Ws=[];for(const Ys of Hs)try{Ws.push(Fragment.from(Ys))}catch(Va){console.log(`[Warning] Invalid Fragment ${JSON.stringify(Ys)}:`,Va.message)}defineProperties(this,{fragments:Object.freeze(Ws)});let Zs=null,zs=!1;this.#n=this.getAbiCoder(),this.fragments.forEach((Ys,Va)=>{let Xs;switch(Ys.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}defineProperties(this,{deploy:Ys});return;case"fallback":Ys.inputs.length===0?zs=!0:(assertArgument(!Zs||Ys.payable!==Zs.payable,"conflicting fallback fragments",`fragments[${Va}]`,Ys),Zs=Ys,zs=Zs.payable);return;case"function":Xs=this.#r;break;case"event":Xs=this.#t;break;case"error":Xs=this.#e;break;default:return}const Ma=Ys.format();Xs.has(Ma)||Xs.set(Ma,Ys)}),this.deploy||defineProperties(this,{deploy:ConstructorFragment.from("constructor()")}),defineProperties(this,{fallback:Zs,receive:zs})}format(Ps){const Hs=Ps?"minimal":"full";return this.fragments.map(Zs=>Zs.format(Hs))}formatJson(){const Ps=this.fragments.map(Hs=>Hs.format("json"));return JSON.stringify(Ps.map(Hs=>JSON.parse(Hs)))}getAbiCoder(){return AbiCoder.defaultAbiCoder()}#o(Ps,Hs,Ws){if(isHexString(Ps)){const zs=Ps.toLowerCase();for(const Ys of this.#r.values())if(zs===Ys.selector)return Ys;return null}if(Ps.indexOf("(")===-1){const zs=[];for(const[Ys,Va]of this.#r)Ys.split("(")[0]===Ps&&zs.push(Va);if(Hs){const Ys=Hs.length>0?Hs[Hs.length-1]:null;let Va=Hs.length,Xs=!0;Typed.isTyped(Ys)&&Ys.type==="overrides"&&(Xs=!1,Va--);for(let Ma=zs.length-1;Ma>=0;Ma--){const qs=zs[Ma].inputs.length;qs!==Va&&(!Xs||qs!==Va-1)&&zs.splice(Ma,1)}for(let Ma=zs.length-1;Ma>=0;Ma--){const qs=zs[Ma].inputs;for(let Js=0;Js<Hs.length;Js++)if(Typed.isTyped(Hs[Js])){if(Js>=qs.length){if(Hs[Js].type==="overrides")continue;zs.splice(Ma,1);break}if(Hs[Js].type!==qs[Js].baseType){zs.splice(Ma,1);break}}}}if(zs.length===1&&Hs&&Hs.length!==zs[0].inputs.length){const Ys=Hs[Hs.length-1];(Ys==null||Array.isArray(Ys)||typeof Ys!="object")&&zs.splice(0,1)}if(zs.length===0)return null;if(zs.length>1&&Ws){const Ys=zs.map(Va=>JSON.stringify(Va.format())).join(", ");assertArgument(!1,`ambiguous function description (i.e. matches ${Ys})`,"key",Ps)}return zs[0]}const Zs=this.#r.get(FunctionFragment.from(Ps).format());return Zs||null}getFunctionName(Ps){const Hs=this.#o(Ps,null,!1);return assertArgument(Hs,"no matching function","key",Ps),Hs.name}hasFunction(Ps){return!!this.#o(Ps,null,!1)}getFunction(Ps,Hs){return this.#o(Ps,Hs||null,!0)}forEachFunction(Ps){const Hs=Array.from(this.#r.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#r.get(Zs),Ws)}}#s(Ps,Hs,Ws){if(isHexString(Ps)){const zs=Ps.toLowerCase();for(const Ys of this.#t.values())if(zs===Ys.topicHash)return Ys;return null}if(Ps.indexOf("(")===-1){const zs=[];for(const[Ys,Va]of this.#t)Ys.split("(")[0]===Ps&&zs.push(Va);if(Hs){for(let Ys=zs.length-1;Ys>=0;Ys--)zs[Ys].inputs.length<Hs.length&&zs.splice(Ys,1);for(let Ys=zs.length-1;Ys>=0;Ys--){const Va=zs[Ys].inputs;for(let Xs=0;Xs<Hs.length;Xs++)if(Typed.isTyped(Hs[Xs])&&Hs[Xs].type!==Va[Xs].baseType){zs.splice(Ys,1);break}}}if(zs.length===0)return null;if(zs.length>1&&Ws){const Ys=zs.map(Va=>JSON.stringify(Va.format())).join(", ");assertArgument(!1,`ambiguous event description (i.e. matches ${Ys})`,"key",Ps)}return zs[0]}const Zs=this.#t.get(EventFragment.from(Ps).format());return Zs||null}getEventName(Ps){const Hs=this.#s(Ps,null,!1);return assertArgument(Hs,"no matching event","key",Ps),Hs.name}hasEvent(Ps){return!!this.#s(Ps,null,!1)}getEvent(Ps,Hs){return this.#s(Ps,Hs||null,!0)}forEachEvent(Ps){const Hs=Array.from(this.#t.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#t.get(Zs),Ws)}}getError(Ps,Hs){if(isHexString(Ps)){const Zs=Ps.toLowerCase();if(BuiltinErrors[Zs])return ErrorFragment.from(BuiltinErrors[Zs].signature);for(const zs of this.#e.values())if(Zs===zs.selector)return zs;return null}if(Ps.indexOf("(")===-1){const Zs=[];for(const[zs,Ys]of this.#e)zs.split("(")[0]===Ps&&Zs.push(Ys);if(Zs.length===0)return Ps==="Error"?ErrorFragment.from("error Error(string)"):Ps==="Panic"?ErrorFragment.from("error Panic(uint256)"):null;if(Zs.length>1){const zs=Zs.map(Ys=>JSON.stringify(Ys.format())).join(", ");assertArgument(!1,`ambiguous error description (i.e. ${zs})`,"name",Ps)}return Zs[0]}if(Ps=ErrorFragment.from(Ps).format(),Ps==="Error(string)")return ErrorFragment.from("error Error(string)");if(Ps==="Panic(uint256)")return ErrorFragment.from("error Panic(uint256)");const Ws=this.#e.get(Ps);return Ws||null}forEachError(Ps){const Hs=Array.from(this.#e.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#e.get(Zs),Ws)}}_decodeParams(Ps,Hs){return this.#n.decode(Ps,Hs)}_encodeParams(Ps,Hs){return this.#n.encode(Ps,Hs)}encodeDeploy(Ps){return this._encodeParams(this.deploy.inputs,Ps||[])}decodeErrorResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getError(Ps);assertArgument(Ws,"unknown error","fragment",Ps),Ps=Ws}return assertArgument(dataSlice(Hs,0,4)===Ps.selector,`data signature does not match error ${Ps.name}.`,"data",Hs),this._decodeParams(Ps.inputs,dataSlice(Hs,4))}encodeErrorResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getError(Ps);assertArgument(Ws,"unknown error","fragment",Ps),Ps=Ws}return concat([Ps.selector,this._encodeParams(Ps.inputs,Hs||[])])}decodeFunctionData(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return assertArgument(dataSlice(Hs,0,4)===Ps.selector,`data signature does not match function ${Ps.name}.`,"data",Hs),this._decodeParams(Ps.inputs,dataSlice(Hs,4))}encodeFunctionData(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return concat([Ps.selector,this._encodeParams(Ps.inputs,Hs||[])])}decodeFunctionResult(Ps,Hs){if(typeof Ps=="string"){const zs=this.getFunction(Ps);assertArgument(zs,"unknown function","fragment",Ps),Ps=zs}let Ws="invalid length for result data";const Zs=getBytesCopy(Hs);if(Zs.length%32===0)try{return this.#n.decode(Ps.outputs,Zs)}catch{Ws="could not decode result data"}assert(!1,Ws,"BAD_DATA",{value:hexlify(Zs),info:{method:Ps.name,signature:Ps.format()}})}makeError(Ps,Hs){const Ws=getBytes(Ps,"data"),Zs=AbiCoder.getBuiltinCallException("call",Hs,Ws);if(Zs.message.startsWith("execution reverted (unknown custom error)")){const Va=hexlify(Ws.slice(0,4)),Xs=this.getError(Va);if(Xs)try{const Ma=this.#n.decode(Xs.inputs,Ws.slice(4));Zs.revert={name:Xs.name,signature:Xs.format(),args:Ma},Zs.reason=Zs.revert.signature,Zs.message=`execution reverted: ${Zs.reason}`}catch{Zs.message="execution reverted (coult not decode custom error)"}}const Ys=this.parseTransaction(Hs);return Ys&&(Zs.invocation={method:Ys.name,signature:Ys.signature,args:Ys.args}),Zs}encodeFunctionResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return hexlify(this.#n.encode(Ps.outputs,Hs||[]))}encodeFilterTopics(Ps,Hs){if(typeof Ps=="string"){const zs=this.getEvent(Ps);assertArgument(zs,"unknown event","eventFragment",Ps),Ps=zs}assert(Hs.length<=Ps.inputs.length,`too many arguments for ${Ps.format()}`,"UNEXPECTED_ARGUMENT",{count:Hs.length,expectedCount:Ps.inputs.length});const Ws=[];Ps.anonymous||Ws.push(Ps.topicHash);const Zs=(zs,Ys)=>zs.type==="string"?id(Ys):zs.type==="bytes"?keccak256(hexlify(Ys)):(zs.type==="bool"&&typeof Ys=="boolean"?Ys=Ys?"0x01":"0x00":zs.type.match(/^u?int/)?Ys=toBeHex(Ys):zs.type.match(/^bytes/)?Ys=zeroPadBytes(Ys,32):zs.type==="address"&&this.#n.encode(["address"],[Ys]),zeroPadValue(hexlify(Ys),32));for(Hs.forEach((zs,Ys)=>{const Va=Ps.inputs[Ys];if(!Va.indexed){assertArgument(zs==null,"cannot filter non-indexed parameters; must be null","contract."+Va.name,zs);return}zs==null?Ws.push(null):Va.baseType==="array"||Va.baseType==="tuple"?assertArgument(!1,"filtering with tuples or arrays not supported","contract."+Va.name,zs):Array.isArray(zs)?Ws.push(zs.map(Xs=>Zs(Va,Xs))):Ws.push(Zs(Va,zs))});Ws.length&&Ws[Ws.length-1]===null;)Ws.pop();return Ws}encodeEventLog(Ps,Hs){if(typeof Ps=="string"){const Ys=this.getEvent(Ps);assertArgument(Ys,"unknown event","eventFragment",Ps),Ps=Ys}const Ws=[],Zs=[],zs=[];return Ps.anonymous||Ws.push(Ps.topicHash),assertArgument(Hs.length===Ps.inputs.length,"event arguments/values mismatch","values",Hs),Ps.inputs.forEach((Ys,Va)=>{const Xs=Hs[Va];if(Ys.indexed)if(Ys.type==="string")Ws.push(id(Xs));else if(Ys.type==="bytes")Ws.push(keccak256(Xs));else{if(Ys.baseType==="tuple"||Ys.baseType==="array")throw new Error("not implemented");Ws.push(this.#n.encode([Ys.type],[Xs]))}else Zs.push(Ys),zs.push(Xs)}),{data:this.#n.encode(Zs,zs),topics:Ws}}decodeEventLog(Ps,Hs,Ws){if(typeof Ps=="string"){const ol=this.getEvent(Ps);assertArgument(ol,"unknown event","eventFragment",Ps),Ps=ol}if(Ws!=null&&!Ps.anonymous){const ol=Ps.topicHash;assertArgument(isHexString(Ws[0],32)&&Ws[0].toLowerCase()===ol,"fragment/topic mismatch","topics[0]",Ws[0]),Ws=Ws.slice(1)}const Zs=[],zs=[],Ys=[];Ps.inputs.forEach((ol,Vc)=>{ol.indexed?ol.type==="string"||ol.type==="bytes"||ol.baseType==="tuple"||ol.baseType==="array"?(Zs.push(ParamType.from({type:"bytes32",name:ol.name})),Ys.push(!0)):(Zs.push(ol),Ys.push(!1)):(zs.push(ol),Ys.push(!1))});const Va=Ws!=null?this.#n.decode(Zs,concat(Ws)):null,Xs=this.#n.decode(zs,Hs,!0),Ma=[],qs=[];let Js=0,Mc=0;return Ps.inputs.forEach((ol,Vc)=>{let Dc=null;if(ol.indexed)if(Va==null)Dc=new Indexed(null);else if(Ys[Vc])Dc=new Indexed(Va[Mc++]);else try{Dc=Va[Mc++]}catch(sl){Dc=sl}else try{Dc=Xs[Js++]}catch(sl){Dc=sl}Ma.push(Dc),qs.push(ol.name||null)}),Result$1.fromItems(Ma,qs)}parseTransaction(Ps){const Hs=getBytes(Ps.data,"tx.data"),Ws=getBigInt(Ps.value!=null?Ps.value:0,"tx.value"),Zs=this.getFunction(hexlify(Hs.slice(0,4)));if(!Zs)return null;const zs=this.#n.decode(Zs.inputs,Hs.slice(4));return new TransactionDescription(Zs,Zs.selector,zs,Ws)}parseCallResult(Ps){throw new Error("@TODO")}parseLog(Ps){const Hs=this.getEvent(Ps.topics[0]);return!Hs||Hs.anonymous?null:new LogDescription(Hs,Hs.topicHash,this.decodeEventLog(Hs,Ps.data,Ps.topics))}parseError(Ps){const Hs=hexlify(Ps),Ws=this.getError(dataSlice(Hs,0,4));if(!Ws)return null;const Zs=this.#n.decode(Ws.inputs,dataSlice(Hs,4));return new ErrorDescription(Ws,Ws.selector,Zs)}static from(Ps){return Ps instanceof Interface?Ps:typeof Ps=="string"?new Interface(JSON.parse(Ps)):typeof Ps.formatJson=="function"?new Interface(Ps.formatJson()):typeof Ps.format=="function"?new Interface(Ps.format("json")):new Interface(Ps)}}const BN_0$2=BigInt(0);function getValue(Fs){return Fs??null}function toJson(Fs){return Fs==null?null:Fs.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(Ps,Hs,Ws){defineProperties(this,{gasPrice:getValue(Ps),maxFeePerGas:getValue(Hs),maxPriorityFeePerGas:getValue(Ws)})}toJSON(){const{gasPrice:Ps,maxFeePerGas:Hs,maxPriorityFeePerGas:Ws}=this;return{_type:"FeeData",gasPrice:toJson(Ps),maxFeePerGas:toJson(Hs),maxPriorityFeePerGas:toJson(Ws)}}}function copyRequest(Fs){const Ps={};Fs.to&&(Ps.to=Fs.to),Fs.from&&(Ps.from=Fs.from),Fs.data&&(Ps.data=hexlify(Fs.data));const Hs="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const Zs of Hs)!(Zs in Fs)||Fs[Zs]==null||(Ps[Zs]=getBigInt(Fs[Zs],`request.${Zs}`));const Ws="type,nonce".split(/,/);for(const Zs of Ws)!(Zs in Fs)||Fs[Zs]==null||(Ps[Zs]=getNumber(Fs[Zs],`request.${Zs}`));return Fs.accessList&&(Ps.accessList=accessListify(Fs.accessList)),Fs.authorizationList&&(Ps.authorizationList=Fs.authorizationList.slice()),"blockTag"in Fs&&(Ps.blockTag=Fs.blockTag),"enableCcipRead"in Fs&&(Ps.enableCcipRead=!!Fs.enableCcipRead),"customData"in Fs&&(Ps.customData=Fs.customData),"blobVersionedHashes"in Fs&&Fs.blobVersionedHashes&&(Ps.blobVersionedHashes=Fs.blobVersionedHashes.slice()),"kzg"in Fs&&(Ps.kzg=Fs.kzg),"blobs"in Fs&&Fs.blobs&&(Ps.blobs=Fs.blobs.map(Zs=>isBytesLike(Zs)?hexlify(Zs):Object.assign({},Zs))),Ps}class Block{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#e;constructor(Ps,Hs){this.#e=Ps.transactions.map(Ws=>typeof Ws!="string"?new TransactionResponse(Ws,Hs):Ws),defineProperties(this,{provider:Hs,hash:getValue(Ps.hash),number:Ps.number,timestamp:Ps.timestamp,parentHash:Ps.parentHash,parentBeaconBlockRoot:Ps.parentBeaconBlockRoot,nonce:Ps.nonce,difficulty:Ps.difficulty,gasLimit:Ps.gasLimit,gasUsed:Ps.gasUsed,blobGasUsed:Ps.blobGasUsed,excessBlobGas:Ps.excessBlobGas,miner:Ps.miner,prevRandao:getValue(Ps.prevRandao),extraData:Ps.extraData,baseFeePerGas:getValue(Ps.baseFeePerGas),stateRoot:Ps.stateRoot,receiptsRoot:Ps.receiptsRoot})}get transactions(){return this.#e.map(Ps=>typeof Ps=="string"?Ps:Ps.hash)}get prefetchedTransactions(){const Ps=this.#e.slice();return Ps.length===0?[]:(assert(typeof Ps[0]=="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),Ps)}toJSON(){const{baseFeePerGas:Ps,difficulty:Hs,extraData:Ws,gasLimit:Zs,gasUsed:zs,hash:Ys,miner:Va,prevRandao:Xs,nonce:Ma,number:qs,parentHash:Js,parentBeaconBlockRoot:Mc,stateRoot:ol,receiptsRoot:Vc,timestamp:Dc,transactions:sl}=this;return{_type:"Block",baseFeePerGas:toJson(Ps),difficulty:toJson(Hs),extraData:Ws,gasLimit:toJson(Zs),gasUsed:toJson(zs),blobGasUsed:toJson(this.blobGasUsed),excessBlobGas:toJson(this.excessBlobGas),hash:Ys,miner:Va,prevRandao:Xs,nonce:Ma,number:qs,parentHash:Js,timestamp:Dc,parentBeaconBlockRoot:Mc,stateRoot:ol,receiptsRoot:Vc,transactions:sl}}[Symbol.iterator](){let Ps=0;const Hs=this.transactions;return{next:()=>Ps<this.length?{value:Hs[Ps++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#e.length}get date(){return this.timestamp==null?null:new Date(this.timestamp*1e3)}async getTransaction(Ps){let Hs;if(typeof Ps=="number")Hs=this.#e[Ps];else{const Ws=Ps.toLowerCase();for(const Zs of this.#e)if(typeof Zs=="string"){if(Zs!==Ws)continue;Hs=Zs;break}else{if(Zs.hash!==Ws)continue;Hs=Zs;break}}if(Hs==null)throw new Error("no such tx");return typeof Hs=="string"?await this.provider.getTransaction(Hs):Hs}getPrefetchedTransaction(Ps){const Hs=this.prefetchedTransactions;if(typeof Ps=="number")return Hs[Ps];Ps=Ps.toLowerCase();for(const Ws of Hs)if(Ws.hash===Ps)return Ws;assertArgument(!1,"no matching transaction","indexOrHash",Ps)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return createOrphanedBlockFilter(this)}}class Log{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(Ps,Hs){this.provider=Hs;const Ws=Object.freeze(Ps.topics.slice());defineProperties(this,{transactionHash:Ps.transactionHash,blockHash:Ps.blockHash,blockNumber:Ps.blockNumber,removed:Ps.removed,address:Ps.address,data:Ps.data,topics:Ws,index:Ps.index,transactionIndex:Ps.transactionIndex})}toJSON(){const{address:Ps,blockHash:Hs,blockNumber:Ws,data:Zs,index:zs,removed:Ys,topics:Va,transactionHash:Xs,transactionIndex:Ma}=this;return{_type:"log",address:Ps,blockHash:Hs,blockNumber:Ws,data:Zs,index:zs,removed:Ys,topics:Va,transactionHash:Xs,transactionIndex:Ma}}async getBlock(){const Ps=await this.provider.getBlock(this.blockHash);return assert(!!Ps,"failed to find transaction","UNKNOWN_ERROR",{}),Ps}async getTransaction(){const Ps=await this.provider.getTransaction(this.transactionHash);return assert(!!Ps,"failed to find transaction","UNKNOWN_ERROR",{}),Ps}async getTransactionReceipt(){const Ps=await this.provider.getTransactionReceipt(this.transactionHash);return assert(!!Ps,"failed to find transaction receipt","UNKNOWN_ERROR",{}),Ps}removedEvent(){return createRemovedLogFilter(this)}}class TransactionReceipt{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#e;constructor(Ps,Hs){this.#e=Object.freeze(Ps.logs.map(Zs=>new Log(Zs,Hs)));let Ws=BN_0$2;Ps.effectiveGasPrice!=null?Ws=Ps.effectiveGasPrice:Ps.gasPrice!=null&&(Ws=Ps.gasPrice),defineProperties(this,{provider:Hs,to:Ps.to,from:Ps.from,contractAddress:Ps.contractAddress,hash:Ps.hash,index:Ps.index,blockHash:Ps.blockHash,blockNumber:Ps.blockNumber,logsBloom:Ps.logsBloom,gasUsed:Ps.gasUsed,cumulativeGasUsed:Ps.cumulativeGasUsed,blobGasUsed:Ps.blobGasUsed,gasPrice:Ws,blobGasPrice:Ps.blobGasPrice,type:Ps.type,status:Ps.status,root:Ps.root})}get logs(){return this.#e}toJSON(){const{to:Ps,from:Hs,contractAddress:Ws,hash:Zs,index:zs,blockHash:Ys,blockNumber:Va,logsBloom:Xs,logs:Ma,status:qs,root:Js}=this;return{_type:"TransactionReceipt",blockHash:Ys,blockNumber:Va,contractAddress:Ws,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:Hs,gasPrice:toJson(this.gasPrice),blobGasUsed:toJson(this.blobGasUsed),blobGasPrice:toJson(this.blobGasPrice),gasUsed:toJson(this.gasUsed),hash:Zs,index:zs,logs:Ma,logsBloom:Xs,root:Js,status:qs,to:Ps}}get length(){return this.logs.length}[Symbol.iterator](){let Ps=0;return{next:()=>Ps<this.length?{value:this.logs[Ps++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const Ps=await this.provider.getBlock(this.blockHash);if(Ps==null)throw new Error("TODO");return Ps}async getTransaction(){const Ps=await this.provider.getTransaction(this.hash);if(Ps==null)throw new Error("TODO");return Ps}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return createRemovedTransactionFilter(this)}reorderedEvent(Ps){return assert(!Ps||Ps.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),createReorderedTransactionFilter(this,Ps)}}class TransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#e;constructor(Ps,Hs){this.provider=Hs,this.blockNumber=Ps.blockNumber!=null?Ps.blockNumber:null,this.blockHash=Ps.blockHash!=null?Ps.blockHash:null,this.hash=Ps.hash,this.index=Ps.index,this.type=Ps.type,this.from=Ps.from,this.to=Ps.to||null,this.gasLimit=Ps.gasLimit,this.nonce=Ps.nonce,this.data=Ps.data,this.value=Ps.value,this.gasPrice=Ps.gasPrice,this.maxPriorityFeePerGas=Ps.maxPriorityFeePerGas!=null?Ps.maxPriorityFeePerGas:null,this.maxFeePerGas=Ps.maxFeePerGas!=null?Ps.maxFeePerGas:null,this.maxFeePerBlobGas=Ps.maxFeePerBlobGas!=null?Ps.maxFeePerBlobGas:null,this.chainId=Ps.chainId,this.signature=Ps.signature,this.accessList=Ps.accessList!=null?Ps.accessList:null,this.blobVersionedHashes=Ps.blobVersionedHashes!=null?Ps.blobVersionedHashes:null,this.authorizationList=Ps.authorizationList!=null?Ps.authorizationList:null,this.#e=-1}toJSON(){const{blockNumber:Ps,blockHash:Hs,index:Ws,hash:Zs,type:zs,to:Ys,from:Va,nonce:Xs,data:Ma,signature:qs,accessList:Js,blobVersionedHashes:Mc}=this;return{_type:"TransactionResponse",accessList:Js,blockNumber:Ps,blockHash:Hs,blobVersionedHashes:Mc,chainId:toJson(this.chainId),data:Ma,from:Va,gasLimit:toJson(this.gasLimit),gasPrice:toJson(this.gasPrice),hash:Zs,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),maxFeePerBlobGas:toJson(this.maxFeePerBlobGas),nonce:Xs,signature:qs,to:Ys,index:Ws,type:zs,value:toJson(this.value)}}async getBlock(){let Ps=this.blockNumber;if(Ps==null){const Ws=await this.getTransaction();Ws&&(Ps=Ws.blockNumber)}if(Ps==null)return null;const Hs=this.provider.getBlock(Ps);if(Hs==null)throw new Error("TODO");return Hs}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(this.blockNumber==null){const{tx:Hs,blockNumber:Ws}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return Hs==null||Hs.blockNumber==null?0:Ws-Hs.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(Ps,Hs){const Ws=Ps??1,Zs=Hs??0;let zs=this.#e,Ys=-1,Va=zs===-1;const Xs=async()=>{if(Va)return null;const{blockNumber:Mc,nonce:ol}=await resolveProperties({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(ol<this.nonce){zs=Mc;return}if(Va)return null;const Vc=await this.getTransaction();if(!(Vc&&Vc.blockNumber!=null))for(Ys===-1&&(Ys=zs-3,Ys<this.#e&&(Ys=this.#e));Ys<=Mc;){if(Va)return null;const Dc=await this.provider.getBlock(Ys,!0);if(Dc==null)return;for(const sl of Dc)if(sl===this.hash)return;for(let sl=0;sl<Dc.length;sl++){const ll=await Dc.getTransaction(sl);if(ll.from===this.from&&ll.nonce===this.nonce){if(Va)return null;const hl=await this.provider.getTransactionReceipt(ll.hash);if(hl==null||Mc-hl.blockNumber+1<Ws)return;let pl="replaced";ll.data===this.data&&ll.to===this.to&&ll.value===this.value?pl="repriced":ll.data==="0x"&&ll.from===ll.to&&ll.value===BN_0$2&&(pl="cancelled"),assert(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:pl==="replaced"||pl==="cancelled",reason:pl,replacement:ll.replaceableTransaction(zs),hash:ll.hash,receipt:hl})}}Ys++}},Ma=Mc=>{if(Mc==null||Mc.status!==0)return Mc;assert(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:Mc.to,from:Mc.from,data:""},receipt:Mc})},qs=await this.provider.getTransactionReceipt(this.hash);if(Ws===0)return Ma(qs);if(qs){if(Ws===1||await qs.confirmations()>=Ws)return Ma(qs)}else if(await Xs(),Ws===0)return null;return await new Promise((Mc,ol)=>{const Vc=[],Dc=()=>{Vc.forEach(ll=>ll())};if(Vc.push(()=>{Va=!0}),Zs>0){const ll=setTimeout(()=>{Dc(),ol(makeError("wait for transaction timeout","TIMEOUT"))},Zs);Vc.push(()=>{clearTimeout(ll)})}const sl=async ll=>{if(await ll.confirmations()>=Ws){Dc();try{Mc(Ma(ll))}catch(hl){ol(hl)}}};if(Vc.push(()=>{this.provider.off(this.hash,sl)}),this.provider.on(this.hash,sl),zs>=0){const ll=async()=>{try{await Xs()}catch(hl){if(isError(hl,"TRANSACTION_REPLACED")){Dc(),ol(hl);return}}Va||this.provider.once("block",ll)};Vc.push(()=>{this.provider.off("block",ll)}),this.provider.once("block",ll)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}removedEvent(){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createRemovedTransactionFilter(this)}reorderedEvent(Ps){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),assert(!Ps||Ps.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createReorderedTransactionFilter(this,Ps)}replaceableTransaction(Ps){assertArgument(Number.isInteger(Ps)&&Ps>=0,"invalid startBlock","startBlock",Ps);const Hs=new TransactionResponse(this,this.provider);return Hs.#e=Ps,Hs}}function createOrphanedBlockFilter(Fs){return{orphan:"drop-block",hash:Fs.hash,number:Fs.number}}function createReorderedTransactionFilter(Fs,Ps){return{orphan:"reorder-transaction",tx:Fs,other:Ps}}function createRemovedTransactionFilter(Fs){return{orphan:"drop-transaction",tx:Fs}}function createRemovedLogFilter(Fs){return{orphan:"drop-log",log:{transactionHash:Fs.transactionHash,blockHash:Fs.blockHash,blockNumber:Fs.blockNumber,address:Fs.address,data:Fs.data,topics:Object.freeze(Fs.topics.slice()),index:Fs.index}}}class EventLog extends Log{interface;fragment;args;constructor(Ps,Hs,Ws){super(Ps,Ps.provider);const Zs=Hs.decodeEventLog(Ws,Ps.data,Ps.topics);defineProperties(this,{args:Zs,fragment:Ws,interface:Hs})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class UndecodedEventLog extends Log{error;constructor(Ps,Hs){super(Ps,Ps.provider),defineProperties(this,{error:Hs})}}class ContractTransactionReceipt extends TransactionReceipt{#e;constructor(Ps,Hs,Ws){super(Ws,Hs),this.#e=Ps}get logs(){return super.logs.map(Ps=>{const Hs=Ps.topics.length?this.#e.getEvent(Ps.topics[0]):null;if(Hs)try{return new EventLog(Ps,this.#e,Hs)}catch(Ws){return new UndecodedEventLog(Ps,Ws)}return Ps})}}class ContractTransactionResponse extends TransactionResponse{#e;constructor(Ps,Hs,Ws){super(Ws,Hs),this.#e=Ps}async wait(Ps,Hs){const Ws=await super.wait(Ps,Hs);return Ws==null?null:new ContractTransactionReceipt(this.#e,this.provider,Ws)}}class ContractUnknownEventPayload extends EventPayload{log;constructor(Ps,Hs,Ws,Zs){super(Ps,Hs,Ws),defineProperties(this,{log:Zs})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ContractEventPayload extends ContractUnknownEventPayload{constructor(Ps,Hs,Ws,Zs,zs){super(Ps,Hs,Ws,new EventLog(zs,Ps.interface,Zs));const Ys=Ps.interface.decodeEventLog(Zs,this.log.data,this.log.topics);defineProperties(this,{args:Ys,fragment:Zs})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const BN_0$1=BigInt(0);function canCall(Fs){return Fs&&typeof Fs.call=="function"}function canEstimate(Fs){return Fs&&typeof Fs.estimateGas=="function"}function canResolve(Fs){return Fs&&typeof Fs.resolveName=="function"}function canSend(Fs){return Fs&&typeof Fs.sendTransaction=="function"}function getResolver(Fs){if(Fs!=null){if(canResolve(Fs))return Fs;if(Fs.provider)return Fs.provider}}class PreparedTopicFilter{#e;fragment;constructor(Ps,Hs,Ws){if(defineProperties(this,{fragment:Hs}),Hs.inputs.length<Ws.length)throw new Error("too many arguments");const Zs=getRunner(Ps.runner,"resolveName"),zs=canResolve(Zs)?Zs:null;this.#e=(async function(){const Ys=await Promise.all(Hs.inputs.map((Va,Xs)=>Ws[Xs]==null?null:Va.walkAsync(Ws[Xs],(qs,Js)=>qs==="address"?Array.isArray(Js)?Promise.all(Js.map(Mc=>resolveAddress(Mc,zs))):resolveAddress(Js,zs):Js)));return Ps.interface.encodeFilterTopics(Hs,Ys)})()}getTopicFilter(){return this.#e}}function getRunner(Fs,Ps){return Fs==null?null:typeof Fs[Ps]=="function"?Fs:Fs.provider&&typeof Fs.provider[Ps]=="function"?Fs.provider:null}function getProvider(Fs){return Fs==null?null:Fs.provider||null}async function copyOverrides(Fs,Ps){const Hs=Typed.dereference(Fs,"overrides");assertArgument(typeof Hs=="object","invalid overrides parameter","overrides",Fs);const Ws=copyRequest(Hs);return assertArgument(Ws.to==null||(Ps||[]).indexOf("to")>=0,"cannot override to","overrides.to",Ws.to),assertArgument(Ws.data==null||(Ps||[]).indexOf("data")>=0,"cannot override data","overrides.data",Ws.data),Ws.from&&(Ws.from=Ws.from),Ws}async function resolveArgs(Fs,Ps,Hs){const Ws=getRunner(Fs,"resolveName"),Zs=canResolve(Ws)?Ws:null;return await Promise.all(Ps.map((zs,Ys)=>zs.walkAsync(Hs[Ys],(Va,Xs)=>(Xs=Typed.dereference(Xs,Va),Va==="address"?resolveAddress(Xs,Zs):Xs))))}function buildWrappedFallback(Fs){const Ps=async function(Ys){const Va=await copyOverrides(Ys,["data"]);Va.to=await Fs.getAddress(),Va.from&&(Va.from=await resolveAddress(Va.from,getResolver(Fs.runner)));const Xs=Fs.interface,Ma=getBigInt(Va.value||BN_0$1,"overrides.value")===BN_0$1,qs=(Va.data||"0x")==="0x";Xs.fallback&&!Xs.fallback.payable&&Xs.receive&&!qs&&!Ma&&assertArgument(!1,"cannot send data to receive or send value to non-payable fallback","overrides",Ys),assertArgument(Xs.fallback||qs,"cannot send data to receive-only contract","overrides.data",Va.data);const Js=Xs.receive||Xs.fallback&&Xs.fallback.payable;return assertArgument(Js||Ma,"cannot send value to non-payable fallback","overrides.value",Va.value),assertArgument(Xs.fallback||qs,"cannot send data to receive-only contract","overrides.data",Va.data),Va},Hs=async function(Ys){const Va=getRunner(Fs.runner,"call");assert(canCall(Va),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const Xs=await Ps(Ys);try{return await Va.call(Xs)}catch(Ma){throw isCallException(Ma)&&Ma.data?Fs.interface.makeError(Ma.data,Xs):Ma}},Ws=async function(Ys){const Va=Fs.runner;assert(canSend(Va),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const Xs=await Va.sendTransaction(await Ps(Ys)),Ma=getProvider(Fs.runner);return new ContractTransactionResponse(Fs.interface,Ma,Xs)},Zs=async function(Ys){const Va=getRunner(Fs.runner,"estimateGas");return assert(canEstimate(Va),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await Va.estimateGas(await Ps(Ys))},zs=async Ys=>await Ws(Ys);return defineProperties(zs,{_contract:Fs,estimateGas:Zs,populateTransaction:Ps,send:Ws,staticCall:Hs}),zs}function buildWrappedMethod(Fs,Ps){const Hs=function(...Ma){const qs=Fs.interface.getFunction(Ps,Ma);return assert(qs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps,args:Ma}}),qs},Ws=async function(...Ma){const qs=Hs(...Ma);let Js={};if(qs.inputs.length+1===Ma.length&&(Js=await copyOverrides(Ma.pop()),Js.from&&(Js.from=await resolveAddress(Js.from,getResolver(Fs.runner)))),qs.inputs.length!==Ma.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const Mc=await resolveArgs(Fs.runner,qs.inputs,Ma);return Object.assign({},Js,await resolveProperties({to:Fs.getAddress(),data:Fs.interface.encodeFunctionData(qs,Mc)}))},Zs=async function(...Ma){const qs=await Va(...Ma);return qs.length===1?qs[0]:qs},zs=async function(...Ma){const qs=Fs.runner;assert(canSend(qs),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const Js=await qs.sendTransaction(await Ws(...Ma)),Mc=getProvider(Fs.runner);return new ContractTransactionResponse(Fs.interface,Mc,Js)},Ys=async function(...Ma){const qs=getRunner(Fs.runner,"estimateGas");return assert(canEstimate(qs),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await qs.estimateGas(await Ws(...Ma))},Va=async function(...Ma){const qs=getRunner(Fs.runner,"call");assert(canCall(qs),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const Js=await Ws(...Ma);let Mc="0x";try{Mc=await qs.call(Js)}catch(Vc){throw isCallException(Vc)&&Vc.data?Fs.interface.makeError(Vc.data,Js):Vc}const ol=Hs(...Ma);return Fs.interface.decodeFunctionResult(ol,Mc)},Xs=async(...Ma)=>Hs(...Ma).constant?await Zs(...Ma):await zs(...Ma);return defineProperties(Xs,{name:Fs.interface.getFunctionName(Ps),_contract:Fs,_key:Ps,getFragment:Hs,estimateGas:Ys,populateTransaction:Ws,send:zs,staticCall:Zs,staticCallResult:Va}),Object.defineProperty(Xs,"fragment",{configurable:!1,enumerable:!0,get:()=>{const Ma=Fs.interface.getFunction(Ps);return assert(Ma,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps}}),Ma}}),Xs}function buildWrappedEvent(Fs,Ps){const Hs=function(...Zs){const zs=Fs.interface.getEvent(Ps,Zs);return assert(zs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps,args:Zs}}),zs},Ws=function(...Zs){return new PreparedTopicFilter(Fs,Hs(...Zs),Zs)};return defineProperties(Ws,{name:Fs.interface.getEventName(Ps),_contract:Fs,_key:Ps,getFragment:Hs}),Object.defineProperty(Ws,"fragment",{configurable:!1,enumerable:!0,get:()=>{const Zs=Fs.interface.getEvent(Ps);return assert(Zs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps}}),Zs}}),Ws}const internal=Symbol.for("_ethersInternal_contract"),internalValues=new WeakMap;function setInternal(Fs,Ps){internalValues.set(Fs[internal],Ps)}function getInternal(Fs){return internalValues.get(Fs[internal])}function isDeferred(Fs){return Fs&&typeof Fs=="object"&&"getTopicFilter"in Fs&&typeof Fs.getTopicFilter=="function"&&Fs.fragment}async function getSubInfo(Fs,Ps){let Hs,Ws=null;if(Array.isArray(Ps)){const zs=function(Ys){if(isHexString(Ys,32))return Ys;const Va=Fs.interface.getEvent(Ys);return assertArgument(Va,"unknown fragment","name",Ys),Va.topicHash};Hs=Ps.map(Ys=>Ys==null?null:Array.isArray(Ys)?Ys.map(zs):zs(Ys))}else Ps==="*"?Hs=[null]:typeof Ps=="string"?isHexString(Ps,32)?Hs=[Ps]:(Ws=Fs.interface.getEvent(Ps),assertArgument(Ws,"unknown fragment","event",Ps),Hs=[Ws.topicHash]):isDeferred(Ps)?Hs=await Ps.getTopicFilter():"fragment"in Ps?(Ws=Ps.fragment,Hs=[Ws.topicHash]):assertArgument(!1,"unknown event name","event",Ps);Hs=Hs.map(zs=>{if(zs==null)return null;if(Array.isArray(zs)){const Ys=Array.from(new Set(zs.map(Va=>Va.toLowerCase())).values());return Ys.length===1?Ys[0]:(Ys.sort(),Ys)}return zs.toLowerCase()});const Zs=Hs.map(zs=>zs==null?"null":Array.isArray(zs)?zs.join("|"):zs).join("&");return{fragment:Ws,tag:Zs,topics:Hs}}async function hasSub(Fs,Ps){const{subs:Hs}=getInternal(Fs);return Hs.get((await getSubInfo(Fs,Ps)).tag)||null}async function getSub(Fs,Ps,Hs){const Ws=getProvider(Fs.runner);assert(Ws,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:Ps});const{fragment:Zs,tag:zs,topics:Ys}=await getSubInfo(Fs,Hs),{addr:Va,subs:Xs}=getInternal(Fs);let Ma=Xs.get(zs);if(!Ma){const Js={address:Va||Fs,topics:Ys},Mc=sl=>{let ll=Zs;if(ll==null)try{ll=Fs.interface.getEvent(sl.topics[0])}catch{}if(ll){const hl=ll,pl=Zs?Fs.interface.decodeEventLog(Zs,sl.data,sl.topics):[];emit(Fs,Hs,pl,gl=>new ContractEventPayload(Fs,gl,Hs,hl,sl))}else emit(Fs,Hs,[],hl=>new ContractUnknownEventPayload(Fs,hl,Hs,sl))};let ol=[];Ma={tag:zs,listeners:[],start:()=>{ol.length||ol.push(Ws.on(Js,Mc))},stop:async()=>{if(ol.length==0)return;let sl=ol;ol=[],await Promise.all(sl),Ws.off(Js,Mc)}},Xs.set(zs,Ma)}return Ma}let lastEmit=Promise.resolve();async function _emit(Fs,Ps,Hs,Ws){await lastEmit;const Zs=await hasSub(Fs,Ps);if(!Zs)return!1;const zs=Zs.listeners.length;return Zs.listeners=Zs.listeners.filter(({listener:Ys,once:Va})=>{const Xs=Array.from(Hs);Ws&&Xs.push(Ws(Va?null:Ys));try{Ys.call(Fs,...Xs)}catch{}return!Va}),Zs.listeners.length===0&&(Zs.stop(),getInternal(Fs).subs.delete(Zs.tag)),zs>0}async function emit(Fs,Ps,Hs,Ws){try{await lastEmit}catch{}const Zs=_emit(Fs,Ps,Hs,Ws);return lastEmit=Zs,await Zs}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];fallback;constructor(Ps,Hs,Ws,Zs){assertArgument(typeof Ps=="string"||isAddressable(Ps),"invalid value for Contract target","target",Ps),Ws==null&&(Ws=null);const zs=Interface.from(Hs);defineProperties(this,{target:Ps,runner:Ws,interface:zs}),Object.defineProperty(this,internal,{value:{}});let Ys,Va=null,Xs=null;if(Zs){const Js=getProvider(Ws);Xs=new ContractTransactionResponse(this.interface,Js,Zs)}let Ma=new Map;if(typeof Ps=="string")if(isHexString(Ps))Va=Ps,Ys=Promise.resolve(Ps);else{const Js=getRunner(Ws,"resolveName");if(!canResolve(Js))throw makeError("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});Ys=Js.resolveName(Ps).then(Mc=>{if(Mc==null)throw makeError("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:Ps});return getInternal(this).addr=Mc,Mc})}else Ys=Ps.getAddress().then(Js=>{if(Js==null)throw new Error("TODO");return getInternal(this).addr=Js,Js});setInternal(this,{addrPromise:Ys,addr:Va,deployTx:Xs,subs:Ma});const qs=new Proxy({},{get:(Js,Mc,ol)=>{if(typeof Mc=="symbol"||passProperties.indexOf(Mc)>=0)return Reflect.get(Js,Mc,ol);try{return this.getEvent(Mc)}catch(Vc){if(!isError(Vc,"INVALID_ARGUMENT")||Vc.argument!=="key")throw Vc}},has:(Js,Mc)=>passProperties.indexOf(Mc)>=0?Reflect.has(Js,Mc):Reflect.has(Js,Mc)||this.interface.hasEvent(String(Mc))});return defineProperties(this,{filters:qs}),defineProperties(this,{fallback:zs.receive||zs.fallback?buildWrappedFallback(this):null}),new Proxy(this,{get:(Js,Mc,ol)=>{if(typeof Mc=="symbol"||Mc in Js||passProperties.indexOf(Mc)>=0)return Reflect.get(Js,Mc,ol);try{return Js.getFunction(Mc)}catch(Vc){if(!isError(Vc,"INVALID_ARGUMENT")||Vc.argument!=="key")throw Vc}},has:(Js,Mc)=>typeof Mc=="symbol"||Mc in Js||passProperties.indexOf(Mc)>=0?Reflect.has(Js,Mc):Js.interface.hasFunction(Mc)})}connect(Ps){return new BaseContract(this.target,this.interface,Ps)}attach(Ps){return new BaseContract(Ps,this.interface,this.runner)}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const Ps=getProvider(this.runner);assert(Ps,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const Hs=await Ps.getCode(await this.getAddress());return Hs==="0x"?null:Hs}async waitForDeployment(){const Ps=this.deploymentTransaction();if(Ps)return await Ps.wait(),this;if(await this.getDeployedCode()!=null)return this;const Ws=getProvider(this.runner);return assert(Ws!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((Zs,zs)=>{const Ys=async()=>{try{if(await this.getDeployedCode()!=null)return Zs(this);Ws.once("block",Ys)}catch(Va){zs(Va)}};Ys()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(Ps){return typeof Ps!="string"&&(Ps=Ps.format()),buildWrappedMethod(this,Ps)}getEvent(Ps){return typeof Ps!="string"&&(Ps=Ps.format()),buildWrappedEvent(this,Ps)}async queryTransaction(Ps){throw new Error("@TODO")}async queryFilter(Ps,Hs,Ws){Hs==null&&(Hs=0),Ws==null&&(Ws="latest");const{addr:Zs,addrPromise:zs}=getInternal(this),Ys=Zs||await zs,{fragment:Va,topics:Xs}=await getSubInfo(this,Ps),Ma={address:Ys,topics:Xs,fromBlock:Hs,toBlock:Ws},qs=getProvider(this.runner);return assert(qs,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await qs.getLogs(Ma)).map(Js=>{let Mc=Va;if(Mc==null)try{Mc=this.interface.getEvent(Js.topics[0])}catch{}if(Mc)try{return new EventLog(Js,this.interface,Mc)}catch(ol){return new UndecodedEventLog(Js,ol)}return new Log(Js,qs)})}async on(Ps,Hs){const Ws=await getSub(this,"on",Ps);return Ws.listeners.push({listener:Hs,once:!1}),Ws.start(),this}async once(Ps,Hs){const Ws=await getSub(this,"once",Ps);return Ws.listeners.push({listener:Hs,once:!0}),Ws.start(),this}async emit(Ps,...Hs){return await emit(this,Ps,Hs,null)}async listenerCount(Ps){if(Ps){const Zs=await hasSub(this,Ps);return Zs?Zs.listeners.length:0}const{subs:Hs}=getInternal(this);let Ws=0;for(const{listeners:Zs}of Hs.values())Ws+=Zs.length;return Ws}async listeners(Ps){if(Ps){const Zs=await hasSub(this,Ps);return Zs?Zs.listeners.map(({listener:zs})=>zs):[]}const{subs:Hs}=getInternal(this);let Ws=[];for(const{listeners:Zs}of Hs.values())Ws=Ws.concat(Zs.map(({listener:zs})=>zs));return Ws}async off(Ps,Hs){const Ws=await hasSub(this,Ps);if(!Ws)return this;if(Hs){const Zs=Ws.listeners.map(({listener:zs})=>zs).indexOf(Hs);Zs>=0&&Ws.listeners.splice(Zs,1)}return(Hs==null||Ws.listeners.length===0)&&(Ws.stop(),getInternal(this).subs.delete(Ws.tag)),this}async removeAllListeners(Ps){if(Ps){const Hs=await hasSub(this,Ps);if(!Hs)return this;Hs.stop(),getInternal(this).subs.delete(Hs.tag)}else{const{subs:Hs}=getInternal(this);for(const{tag:Ws,stop:Zs}of Hs.values())Zs(),Hs.delete(Ws)}return this}async addListener(Ps,Hs){return await this.on(Ps,Hs)}async removeListener(Ps,Hs){return await this.off(Ps,Hs)}static buildClass(Ps){class Hs extends BaseContract{constructor(Zs,zs=null){super(Zs,Ps,zs)}}return Hs}static from(Ps,Hs,Ws){return Ws==null&&(Ws=null),new this(Ps,Hs,Ws)}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}function getIpfsLink(Fs){return Fs.match(/^ipfs:\/\/ipfs\//i)?Fs=Fs.substring(12):Fs.match(/^ipfs:\/\//i)?Fs=Fs.substring(7):assertArgument(!1,"unsupported IPFS format","link",Fs),`https://gateway.ipfs.io/ipfs/${Fs}`}class MulticoinProviderPlugin{name;constructor(Ps){defineProperties(this,{name:Ps})}connect(Ps){return this}supportsCoinType(Ps){return!1}async encodeAddress(Ps,Hs){throw new Error("unsupported coin")}async decodeAddress(Ps,Hs){throw new Error("unsupported coin")}}const matcherIpfs=new RegExp("^(ipfs)://(.*)$","i"),matchers=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),matcherIpfs,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class EnsResolver{provider;address;name;#e;#t;constructor(Ps,Hs,Ws){defineProperties(this,{provider:Ps,address:Hs,name:Ws}),this.#e=null,this.#t=new Contract(Hs,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],Ps)}async supportsWildcard(){return this.#e==null&&(this.#e=(async()=>{try{return await this.#t.supportsInterface("0x9061b923")}catch(Ps){if(isError(Ps,"CALL_EXCEPTION"))return!1;throw this.#e=null,Ps}})()),await this.#e}async#r(Ps,Hs){Hs=(Hs||[]).slice();const Ws=this.#t.interface;Hs.unshift(namehash(this.name));let Zs=null;await this.supportsWildcard()&&(Zs=Ws.getFunction(Ps),assert(Zs,"missing fragment","UNKNOWN_ERROR",{info:{funcName:Ps}}),Hs=[dnsEncode(this.name,255),Ws.encodeFunctionData(Zs,Hs)],Ps="resolve(bytes,bytes)"),Hs.push({enableCcipRead:!0});try{const zs=await this.#t[Ps](...Hs);return Zs?Ws.decodeFunctionResult(Zs,zs)[0]:zs}catch(zs){if(!isError(zs,"CALL_EXCEPTION"))throw zs}return null}async getAddress(Ps){if(Ps==null&&(Ps=60),Ps===60)try{const zs=await this.#r("addr(bytes32)");return zs==null||zs===ZeroAddress?null:zs}catch(zs){if(isError(zs,"CALL_EXCEPTION"))return null;throw zs}if(Ps>=0&&Ps<2147483648){let zs=Ps+2147483648;const Ys=await this.#r("addr(bytes32,uint)",[zs]);if(isHexString(Ys,20))return getAddress(Ys)}let Hs=null;for(const zs of this.provider.plugins)if(zs instanceof MulticoinProviderPlugin&&zs.supportsCoinType(Ps)){Hs=zs;break}if(Hs==null)return null;const Ws=await this.#r("addr(bytes32,uint)",[Ps]);if(Ws==null||Ws==="0x")return null;const Zs=await Hs.decodeAddress(Ps,Ws);if(Zs!=null)return Zs;assert(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${Ps})`,info:{coinType:Ps,data:Ws}})}async getText(Ps){const Hs=await this.#r("text(bytes32,string)",[Ps]);return Hs==null||Hs==="0x"?null:Hs}async getContentHash(){const Ps=await this.#r("contenthash(bytes32)");if(Ps==null||Ps==="0x")return null;const Hs=Ps.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(Hs){const Zs=Hs[1]==="e3010170"?"ipfs":"ipns",zs=parseInt(Hs[4],16);if(Hs[5].length===zs*2)return`${Zs}://${encodeBase58("0x"+Hs[2])}`}const Ws=Ps.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(Ws&&Ws[1].length===64)return`bzz://${Ws[1]}`;assert(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:Ps}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const Ps=[{type:"name",value:this.name}];try{const Hs=await this.getText("avatar");if(Hs==null)return Ps.push({type:"!avatar",value:""}),{url:null,linkage:Ps};Ps.push({type:"avatar",value:Hs});for(let Ws=0;Ws<matchers.length;Ws++){const Zs=Hs.match(matchers[Ws]);if(Zs==null)continue;const zs=Zs[1].toLowerCase();switch(zs){case"https":case"data":return Ps.push({type:"url",value:Hs}),{linkage:Ps,url:Hs};case"ipfs":{const Ys=getIpfsLink(Hs);return Ps.push({type:"ipfs",value:Hs}),Ps.push({type:"url",value:Ys}),{linkage:Ps,url:Ys}}case"erc721":case"erc1155":{const Ys=zs==="erc721"?"tokenURI(uint256)":"uri(uint256)";Ps.push({type:zs,value:Hs});const Va=await this.getAddress();if(Va==null)return Ps.push({type:"!owner",value:""}),{url:null,linkage:Ps};const Xs=(Zs[2]||"").split("/");if(Xs.length!==2)return Ps.push({type:`!${zs}caip`,value:Zs[2]||""}),{url:null,linkage:Ps};const Ma=Xs[1],qs=new Contract(Xs[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if(zs==="erc721"){const Dc=await qs.ownerOf(Ma);if(Va!==Dc)return Ps.push({type:"!owner",value:Dc}),{url:null,linkage:Ps};Ps.push({type:"owner",value:Dc})}else if(zs==="erc1155"){const Dc=await qs.balanceOf(Va,Ma);if(!Dc)return Ps.push({type:"!balance",value:"0"}),{url:null,linkage:Ps};Ps.push({type:"balance",value:Dc.toString()})}let Js=await qs[Ys](Ma);if(Js==null||Js==="0x")return Ps.push({type:"!metadata-url",value:""}),{url:null,linkage:Ps};Ps.push({type:"metadata-url-base",value:Js}),zs==="erc1155"&&(Js=Js.replace("{id}",toBeHex(Ma,32).substring(2)),Ps.push({type:"metadata-url-expanded",value:Js})),Js.match(/^ipfs:/i)&&(Js=getIpfsLink(Js)),Ps.push({type:"metadata-url",value:Js});let Mc={};const ol=await new FetchRequest(Js).send();ol.assertOk();try{Mc=ol.bodyJson}catch{try{Ps.push({type:"!metadata",value:ol.bodyText})}catch{const ll=ol.body;return ll&&Ps.push({type:"!metadata",value:hexlify(ll)}),{url:null,linkage:Ps}}return{url:null,linkage:Ps}}if(!Mc)return Ps.push({type:"!metadata",value:""}),{url:null,linkage:Ps};Ps.push({type:"metadata",value:JSON.stringify(Mc)});let Vc=Mc.image;if(typeof Vc!="string")return Ps.push({type:"!imageUrl",value:""}),{url:null,linkage:Ps};if(!Vc.match(/^(https:\/\/|data:)/i)){if(Vc.match(matcherIpfs)==null)return Ps.push({type:"!imageUrl-ipfs",value:Vc}),{url:null,linkage:Ps};Ps.push({type:"imageUrl-ipfs",value:Vc}),Vc=getIpfsLink(Vc)}return Ps.push({type:"url",value:Vc}),{linkage:Ps,url:Vc}}}}}catch{}return{linkage:Ps,url:null}}static async getEnsAddress(Ps){const Hs=await Ps.getNetwork(),Ws=Hs.getPlugin("org.ethers.plugins.network.Ens");return assert(Ws,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:Hs}}),Ws.address}static async#n(Ps,Hs){const Ws=await EnsResolver.getEnsAddress(Ps);try{const zs=await new Contract(Ws,["function resolver(bytes32) view returns (address)"],Ps).resolver(namehash(Hs),{enableCcipRead:!0});return zs===ZeroAddress?null:zs}catch(Zs){throw Zs}return null}static async fromName(Ps,Hs){let Ws=Hs;for(;;){if(Ws===""||Ws==="."||Hs!=="eth"&&Ws==="eth")return null;const Zs=await EnsResolver.#n(Ps,Ws);if(Zs!=null){const zs=new EnsResolver(Ps,Zs,Hs);return Ws!==Hs&&!await zs.supportsWildcard()?null:zs}Ws=Ws.split(".").slice(1).join(".")}}}const BN_0=BigInt(0);function allowNull(Fs,Ps){return(function(Hs){return Hs==null?Ps:Fs(Hs)})}function arrayOf(Fs,Ps){return(Hs=>{if(Ps&&Hs==null)return null;if(!Array.isArray(Hs))throw new Error("not an array");return Hs.map(Ws=>Fs(Ws))})}function object(Fs,Ps){return(Hs=>{const Ws={};for(const Zs in Fs){let zs=Zs;if(Ps&&Zs in Ps&&!(zs in Hs)){for(const Ys of Ps[Zs])if(Ys in Hs){zs=Ys;break}}try{const Ys=Fs[Zs](Hs[zs]);Ys!==void 0&&(Ws[Zs]=Ys)}catch(Ys){const Va=Ys instanceof Error?Ys.message:"not-an-error";assert(!1,`invalid value for value.${Zs} (${Va})`,"BAD_DATA",{value:Hs})}}return Ws})}function formatBoolean(Fs){switch(Fs){case!0:case"true":return!0;case!1:case"false":return!1}assertArgument(!1,`invalid boolean; ${JSON.stringify(Fs)}`,"value",Fs)}function formatData(Fs){return assertArgument(isHexString(Fs,!0),"invalid data","value",Fs),Fs}function formatHash(Fs){return assertArgument(isHexString(Fs,32),"invalid hash","value",Fs),Fs}const _formatLog=object({address:getAddress,blockHash:formatHash,blockNumber:getNumber,data:formatData,index:getNumber,removed:allowNull(formatBoolean,!1),topics:arrayOf(formatHash),transactionHash:formatHash,transactionIndex:getNumber},{index:["logIndex"]});function formatLog(Fs){return _formatLog(Fs)}const _formatBlock=object({hash:allowNull(formatHash),parentHash:formatHash,parentBeaconBlockRoot:allowNull(formatHash,null),number:getNumber,timestamp:getNumber,nonce:allowNull(formatData),difficulty:getBigInt,gasLimit:getBigInt,gasUsed:getBigInt,stateRoot:allowNull(formatHash,null),receiptsRoot:allowNull(formatHash,null),blobGasUsed:allowNull(getBigInt,null),excessBlobGas:allowNull(getBigInt,null),miner:allowNull(getAddress),prevRandao:allowNull(formatHash,null),extraData:formatData,baseFeePerGas:allowNull(getBigInt)},{prevRandao:["mixHash"]});function formatBlock(Fs){const Ps=_formatBlock(Fs);return Ps.transactions=Fs.transactions.map(Hs=>typeof Hs=="string"?Hs:formatTransactionResponse(Hs)),Ps}const _formatReceiptLog=object({transactionIndex:getNumber,blockNumber:getNumber,transactionHash:formatHash,address:getAddress,topics:arrayOf(formatHash),data:formatData,index:getNumber,blockHash:formatHash},{index:["logIndex"]});function formatReceiptLog(Fs){return _formatReceiptLog(Fs)}const _formatTransactionReceipt=object({to:allowNull(getAddress,null),from:allowNull(getAddress,null),contractAddress:allowNull(getAddress,null),index:getNumber,root:allowNull(hexlify),gasUsed:getBigInt,blobGasUsed:allowNull(getBigInt,null),logsBloom:allowNull(formatData),blockHash:formatHash,hash:formatHash,logs:arrayOf(formatReceiptLog),blockNumber:getNumber,cumulativeGasUsed:getBigInt,effectiveGasPrice:allowNull(getBigInt),blobGasPrice:allowNull(getBigInt,null),status:allowNull(getNumber),type:allowNull(getNumber,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function formatTransactionReceipt(Fs){return _formatTransactionReceipt(Fs)}function formatTransactionResponse(Fs){Fs.to&&getBigInt(Fs.to)===BN_0&&(Fs.to="0x0000000000000000000000000000000000000000");const Ps=object({hash:formatHash,index:allowNull(getNumber,void 0),type:Hs=>Hs==="0x"||Hs==null?0:getNumber(Hs),accessList:allowNull(accessListify,null),blobVersionedHashes:allowNull(arrayOf(formatHash,!0),null),authorizationList:allowNull(arrayOf(Hs=>{let Ws;if(Hs.signature)Ws=Hs.signature;else{let Zs=Hs.yParity;Zs==="0x1b"?Zs=0:Zs==="0x1c"&&(Zs=1),Ws=Object.assign({},Hs,{yParity:Zs})}return{address:getAddress(Hs.address),chainId:getBigInt(Hs.chainId),nonce:getBigInt(Hs.nonce),signature:Signature.from(Ws)}},!1),null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(getNumber,null),transactionIndex:allowNull(getNumber,null),from:getAddress,gasPrice:allowNull(getBigInt),maxPriorityFeePerGas:allowNull(getBigInt),maxFeePerGas:allowNull(getBigInt),maxFeePerBlobGas:allowNull(getBigInt,null),gasLimit:getBigInt,to:allowNull(getAddress,null),value:getBigInt,nonce:getNumber,data:formatData,creates:allowNull(getAddress,null),chainId:allowNull(getBigInt,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(Fs);if(Ps.to==null&&Ps.creates==null&&(Ps.creates=getCreateAddress(Ps)),(Fs.type===1||Fs.type===2)&&Fs.accessList==null&&(Ps.accessList=[]),Fs.signature?Ps.signature=Signature.from(Fs.signature):Ps.signature=Signature.from(Fs),Ps.chainId==null){const Hs=Ps.signature.legacyChainId;Hs!=null&&(Ps.chainId=Hs)}return Ps.blockHash&&getBigInt(Ps.blockHash)===BN_0&&(Ps.blockHash=null),Ps}const EnsAddress="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class NetworkPlugin{name;constructor(Ps){defineProperties(this,{name:Ps})}clone(){return new NetworkPlugin(this.name)}}class GasCostPlugin extends NetworkPlugin{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(Ps,Hs){Ps==null&&(Ps=0),super(`org.ethers.network.plugins.GasCost#${Ps||0}`);const Ws={effectiveBlock:Ps};function Zs(zs,Ys){let Va=(Hs||{})[zs];Va==null&&(Va=Ys),assertArgument(typeof Va=="number",`invalud value for ${zs}`,"costs",Hs),Ws[zs]=Va}Zs("txBase",21e3),Zs("txCreate",32e3),Zs("txDataZero",4),Zs("txDataNonzero",16),Zs("txAccessListStorageKey",1900),Zs("txAccessListAddress",2400),defineProperties(this,Ws)}clone(){return new GasCostPlugin(this.effectiveBlock,this)}}class EnsPlugin extends NetworkPlugin{address;targetNetwork;constructor(Ps,Hs){super("org.ethers.plugins.network.Ens"),defineProperties(this,{address:Ps||EnsAddress,targetNetwork:Hs??1})}clone(){return new EnsPlugin(this.address,this.targetNetwork)}}class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin{#e;#t;get url(){return this.#e}get processFunc(){return this.#t}constructor(Ps,Hs){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#e=Ps,this.#t=Hs}clone(){return this}}const Networks=new Map;class Network{#e;#t;#r;constructor(Ps,Hs){this.#e=Ps,this.#t=getBigInt(Hs),this.#r=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#e}set name(Ps){this.#e=Ps}get chainId(){return this.#t}set chainId(Ps){this.#t=getBigInt(Ps,"chainId")}matches(Ps){if(Ps==null)return!1;if(typeof Ps=="string"){try{return this.chainId===getBigInt(Ps)}catch{}return this.name===Ps}if(typeof Ps=="number"||typeof Ps=="bigint"){try{return this.chainId===getBigInt(Ps)}catch{}return!1}if(typeof Ps=="object"){if(Ps.chainId!=null){try{return this.chainId===getBigInt(Ps.chainId)}catch{}return!1}return Ps.name!=null?this.name===Ps.name:!1}return!1}get plugins(){return Array.from(this.#r.values())}attachPlugin(Ps){if(this.#r.get(Ps.name))throw new Error(`cannot replace existing plugin: ${Ps.name} `);return this.#r.set(Ps.name,Ps.clone()),this}getPlugin(Ps){return this.#r.get(Ps)||null}getPlugins(Ps){return this.plugins.filter(Hs=>Hs.name.split("#")[0]===Ps)}clone(){const Ps=new Network(this.name,this.chainId);return this.plugins.forEach(Hs=>{Ps.attachPlugin(Hs.clone())}),Ps}computeIntrinsicGas(Ps){const Hs=this.getPlugin("org.ethers.plugins.network.GasCost")||new GasCostPlugin;let Ws=Hs.txBase;if(Ps.to==null&&(Ws+=Hs.txCreate),Ps.data)for(let Zs=2;Zs<Ps.data.length;Zs+=2)Ps.data.substring(Zs,Zs+2)==="00"?Ws+=Hs.txDataZero:Ws+=Hs.txDataNonzero;if(Ps.accessList){const Zs=accessListify(Ps.accessList);for(const zs in Zs)Ws+=Hs.txAccessListAddress+Hs.txAccessListStorageKey*Zs[zs].storageKeys.length}return Ws}static from(Ps){if(injectCommonNetworks(),Ps==null)return Network.from("mainnet");if(typeof Ps=="number"&&(Ps=BigInt(Ps)),typeof Ps=="string"||typeof Ps=="bigint"){const Hs=Networks.get(Ps);if(Hs)return Hs();if(typeof Ps=="bigint")return new Network("unknown",Ps);assertArgument(!1,"unknown network","network",Ps)}if(typeof Ps.clone=="function")return Ps.clone();if(typeof Ps=="object"){assertArgument(typeof Ps.name=="string"&&typeof Ps.chainId=="number","invalid network object name or chainId","network",Ps);const Hs=new Network(Ps.name,Ps.chainId);return(Ps.ensAddress||Ps.ensNetwork!=null)&&Hs.attachPlugin(new EnsPlugin(Ps.ensAddress,Ps.ensNetwork)),Hs}assertArgument(!1,"invalid network","network",Ps)}static register(Ps,Hs){typeof Ps=="number"&&(Ps=BigInt(Ps));const Ws=Networks.get(Ps);Ws&&assertArgument(!1,`conflicting network for ${JSON.stringify(Ws.name)}`,"nameOrChainId",Ps),Networks.set(Ps,Hs)}}function parseUnits(Fs,Ps){const Hs=String(Fs);if(!Hs.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${Fs}`);const Ws=Hs.split(".");if(Ws.length===1&&Ws.push(""),Ws.length!==2)throw new Error(`invalid gwei value: ${Fs}`);for(;Ws[1].length<Ps;)Ws[1]+="0";if(Ws[1].length>9){let Zs=BigInt(Ws[1].substring(0,9));Ws[1].substring(9).match(/^0+$/)||Zs++,Ws[1]=Zs.toString()}return BigInt(Ws[0]+Ws[1])}function getGasStationPlugin(Fs){return new FetchUrlFeeDataNetworkPlugin(Fs,async(Ps,Hs,Ws)=>{Ws.setHeader("User-Agent","ethers");let Zs;try{const[zs,Ys]=await Promise.all([Ws.send(),Ps()]);Zs=zs;const Va=Zs.bodyJson.standard;return{gasPrice:Ys.gasPrice,maxFeePerGas:parseUnits(Va.maxFee,9),maxPriorityFeePerGas:parseUnits(Va.maxPriorityFee,9)}}catch(zs){assert(!1,`error encountered with polygon gas station (${JSON.stringify(Ws.url)})`,"SERVER_ERROR",{request:Ws,response:Zs,error:zs})}})}let injected=!1;function injectCommonNetworks(){if(injected)return;injected=!0;function Fs(Ps,Hs,Ws){const Zs=function(){const zs=new Network(Ps,Hs);return Ws.ensNetwork!=null&&zs.attachPlugin(new EnsPlugin(null,Ws.ensNetwork)),zs.attachPlugin(new GasCostPlugin),(Ws.plugins||[]).forEach(Ys=>{zs.attachPlugin(Ys)}),zs};Network.register(Ps,Zs),Network.register(Hs,Zs),Ws.altNames&&Ws.altNames.forEach(zs=>{Network.register(zs,Zs)})}Fs("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),Fs("ropsten",3,{ensNetwork:3}),Fs("rinkeby",4,{ensNetwork:4}),Fs("goerli",5,{ensNetwork:5}),Fs("kovan",42,{ensNetwork:42}),Fs("sepolia",11155111,{ensNetwork:11155111}),Fs("holesky",17e3,{ensNetwork:17e3}),Fs("classic",61,{}),Fs("classicKotti",6,{}),Fs("arbitrum",42161,{ensNetwork:1}),Fs("arbitrum-goerli",421613,{}),Fs("arbitrum-sepolia",421614,{}),Fs("base",8453,{ensNetwork:1}),Fs("base-goerli",84531,{}),Fs("base-sepolia",84532,{}),Fs("bnb",56,{ensNetwork:1}),Fs("bnbt",97,{}),Fs("linea",59144,{ensNetwork:1}),Fs("linea-goerli",59140,{}),Fs("linea-sepolia",59141,{}),Fs("matic",137,{ensNetwork:1,plugins:[getGasStationPlugin("https://gasstation.polygon.technology/v2")]}),Fs("matic-amoy",80002,{}),Fs("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[getGasStationPlugin("https://gasstation-testnet.polygon.technology/v2")]}),Fs("optimism",10,{ensNetwork:1,plugins:[]}),Fs("optimism-goerli",420,{}),Fs("optimism-sepolia",11155420,{}),Fs("xdai",100,{ensNetwork:1})}function copy$2(Fs){return JSON.parse(JSON.stringify(Fs))}class PollingBlockSubscriber{#e;#t;#r;#n;constructor(Ps){this.#e=Ps,this.#t=null,this.#r=4e3,this.#n=-2}get pollingInterval(){return this.#r}set pollingInterval(Ps){this.#r=Ps}async#o(){try{const Ps=await this.#e.getBlockNumber();if(this.#n===-2){this.#n=Ps;return}if(Ps!==this.#n){for(let Hs=this.#n+1;Hs<=Ps;Hs++){if(this.#t==null)return;await this.#e.emit("block",Hs)}this.#n=Ps}}catch{}this.#t!=null&&(this.#t=this.#e._setTimeout(this.#o.bind(this),this.#r))}start(){this.#t||(this.#t=this.#e._setTimeout(this.#o.bind(this),this.#r),this.#o())}stop(){this.#t&&(this.#e._clearTimeout(this.#t),this.#t=null)}pause(Ps){this.stop(),Ps&&(this.#n=-2)}resume(){this.start()}}class OnBlockSubscriber{#e;#t;#r;constructor(Ps){this.#e=Ps,this.#r=!1,this.#t=Hs=>{this._poll(Hs,this.#e)}}async _poll(Ps,Hs){throw new Error("sub-classes must override this")}start(){this.#r||(this.#r=!0,this.#t(-2),this.#e.on("block",this.#t))}stop(){this.#r&&(this.#r=!1,this.#e.off("block",this.#t))}pause(Ps){this.stop()}resume(){this.start()}}class PollingBlockTagSubscriber extends OnBlockSubscriber{#e;#t;constructor(Ps,Hs){super(Ps),this.#e=Hs,this.#t=-2}pause(Ps){Ps&&(this.#t=-2),super.pause(Ps)}async _poll(Ps,Hs){const Ws=await Hs.getBlock(this.#e);Ws!=null&&(this.#t===-2?this.#t=Ws.number:Ws.number>this.#t&&(Hs.emit(this.#e,Ws.number),this.#t=Ws.number))}}class PollingOrphanSubscriber extends OnBlockSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=copy$2(Hs)}async _poll(Ps,Hs){throw new Error("@TODO")}}class PollingTransactionSubscriber extends OnBlockSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=Hs}async _poll(Ps,Hs){const Ws=await Hs.getTransactionReceipt(this.#e);Ws&&Hs.emit(this.#e,Ws)}}class PollingEventSubscriber{#e;#t;#r;#n;#o;constructor(Ps,Hs){this.#e=Ps,this.#t=copy$2(Hs),this.#r=this.#s.bind(this),this.#n=!1,this.#o=-2}async#s(Ps){if(this.#o===-2)return;const Hs=copy$2(this.#t);Hs.fromBlock=this.#o+1,Hs.toBlock=Ps;const Ws=await this.#e.getLogs(Hs);if(Ws.length===0){this.#o<Ps-60&&(this.#o=Ps-60);return}for(const Zs of Ws)this.#e.emit(this.#t,Zs),this.#o=Zs.blockNumber}start(){this.#n||(this.#n=!0,this.#o===-2&&this.#e.getBlockNumber().then(Ps=>{this.#o=Ps}),this.#e.on("block",this.#r))}stop(){this.#n&&(this.#n=!1,this.#e.off("block",this.#r))}pause(Ps){this.stop(),Ps&&(this.#o=-2)}resume(){this.start()}}const BN_2=BigInt(2),MAX_CCIP_REDIRECTS=10;function isPromise(Fs){return Fs&&typeof Fs.then=="function"}function getTag(Fs,Ps){return Fs+":"+JSON.stringify(Ps,(Hs,Ws)=>{if(Ws==null)return"null";if(typeof Ws=="bigint")return`bigint:${Ws.toString()}`;if(typeof Ws=="string")return Ws.toLowerCase();if(typeof Ws=="object"&&!Array.isArray(Ws)){const Zs=Object.keys(Ws);return Zs.sort(),Zs.reduce((zs,Ys)=>(zs[Ys]=Ws[Ys],zs),{})}return Ws})}class UnmanagedSubscriber{name;constructor(Ps){defineProperties(this,{name:Ps})}start(){}stop(){}pause(Ps){}resume(){}}function copy$1(Fs){return JSON.parse(JSON.stringify(Fs))}function concisify(Fs){return Fs=Array.from(new Set(Fs).values()),Fs.sort(),Fs}async function getSubscription(Fs,Ps){if(Fs==null)throw new Error("invalid event");if(Array.isArray(Fs)&&(Fs={topics:Fs}),typeof Fs=="string")switch(Fs){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:Fs,tag:Fs}}if(isHexString(Fs,32)){const Hs=Fs.toLowerCase();return{type:"transaction",tag:getTag("tx",{hash:Hs}),hash:Hs}}if(Fs.orphan){const Hs=Fs;return{type:"orphan",tag:getTag("orphan",Hs),filter:copy$1(Hs)}}if(Fs.address||Fs.topics){const Hs=Fs,Ws={topics:(Hs.topics||[]).map(Zs=>Zs==null?null:Array.isArray(Zs)?concisify(Zs.map(zs=>zs.toLowerCase())):Zs.toLowerCase())};if(Hs.address){const Zs=[],zs=[],Ys=Va=>{isHexString(Va)?Zs.push(Va):zs.push((async()=>{Zs.push(await resolveAddress(Va,Ps))})())};Array.isArray(Hs.address)?Hs.address.forEach(Ys):Ys(Hs.address),zs.length&&await Promise.all(zs),Ws.address=concisify(Zs.map(Va=>Va.toLowerCase()))}return{filter:Ws,tag:getTag("event",Ws),type:"event"}}assertArgument(!1,"unknown ProviderEvent","event",Fs)}function getTime(){return new Date().getTime()}const defaultOptions$1={cacheTimeout:250,pollingInterval:4e3};class AbstractProvider{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;constructor(Ps,Hs){if(this.#g=Object.assign({},defaultOptions$1,Hs||{}),Ps==="any")this.#s=!0,this.#o=null;else if(Ps){const Ws=Network.from(Ps);this.#s=!1,this.#o=Promise.resolve(Ws),setTimeout(()=>{this.emit("network",Ws,null)},0)}else this.#s=!1,this.#o=null;this.#a=-1,this.#i=new Map,this.#e=new Map,this.#t=new Map,this.#r=null,this.#n=!1,this.#d=1,this.#l=new Map,this.#p=!1}get pollingInterval(){return this.#g.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#t.values())}attachPlugin(Ps){if(this.#t.get(Ps.name))throw new Error(`cannot replace existing plugin: ${Ps.name} `);return this.#t.set(Ps.name,Ps.connect(this)),this}getPlugin(Ps){return this.#t.get(Ps)||null}get disableCcipRead(){return this.#p}set disableCcipRead(Ps){this.#p=!!Ps}async#c(Ps){const Hs=this.#g.cacheTimeout;if(Hs<0)return await this._perform(Ps);const Ws=getTag(Ps.method,Ps);let Zs=this.#i.get(Ws);return Zs||(Zs=this._perform(Ps),this.#i.set(Ws,Zs),setTimeout(()=>{this.#i.get(Ws)===Zs&&this.#i.delete(Ws)},Hs)),await Zs}async ccipReadFetch(Ps,Hs,Ws){if(this.disableCcipRead||Ws.length===0||Ps.to==null)return null;const Zs=Ps.to.toLowerCase(),zs=Hs.toLowerCase(),Ys=[];for(let Va=0;Va<Ws.length;Va++){const Xs=Ws[Va],Ma=Xs.replace("{sender}",Zs).replace("{data}",zs),qs=new FetchRequest(Ma);Xs.indexOf("{data}")===-1&&(qs.body={data:zs,sender:Zs}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:qs,index:Va,urls:Ws});let Js="unknown error",Mc;try{Mc=await qs.send()}catch(ol){Ys.push(ol.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:qs,result:{error:ol}});continue}try{const ol=Mc.bodyJson;if(ol.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:qs,result:ol}),ol.data;ol.message&&(Js=ol.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:qs,result:ol})}catch{}assert(Mc.statusCode<400||Mc.statusCode>=500,`response not found during CCIP fetch: ${Js}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:Ps,info:{url:Xs,errorMessage:Js}}),Ys.push(Js)}assert(!1,`error encountered during CCIP fetch: ${Ys.map(Va=>JSON.stringify(Va)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:Ps,info:{urls:Ws,errorMessages:Ys}})}_wrapBlock(Ps,Hs){return new Block(formatBlock(Ps),this)}_wrapLog(Ps,Hs){return new Log(formatLog(Ps),this)}_wrapTransactionReceipt(Ps,Hs){return new TransactionReceipt(formatTransactionReceipt(Ps),this)}_wrapTransactionResponse(Ps,Hs){return new TransactionResponse(formatTransactionResponse(Ps),this)}_detectNetwork(){assert(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(Ps){assert(!1,`unsupported method: ${Ps.method}`,"UNSUPPORTED_OPERATION",{operation:Ps.method,info:Ps})}async getBlockNumber(){const Ps=getNumber(await this.#c({method:"getBlockNumber"}),"%response");return this.#a>=0&&(this.#a=Ps),Ps}_getAddress(Ps){return resolveAddress(Ps,this)}_getBlockTag(Ps){if(Ps==null)return"latest";switch(Ps){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return Ps}if(isHexString(Ps))return isHexString(Ps,32)?Ps:toQuantity(Ps);if(typeof Ps=="bigint"&&(Ps=getNumber(Ps,"blockTag")),typeof Ps=="number")return Ps>=0?toQuantity(Ps):this.#a>=0?toQuantity(this.#a+Ps):this.getBlockNumber().then(Hs=>toQuantity(Hs+Ps));assertArgument(!1,"invalid blockTag","blockTag",Ps)}_getFilter(Ps){const Hs=(Ps.topics||[]).map(Xs=>Xs==null?null:Array.isArray(Xs)?concisify(Xs.map(Ma=>Ma.toLowerCase())):Xs.toLowerCase()),Ws="blockHash"in Ps?Ps.blockHash:void 0,Zs=(Xs,Ma,qs)=>{let Js;switch(Xs.length){case 0:break;case 1:Js=Xs[0];break;default:Xs.sort(),Js=Xs}if(Ws&&(Ma!=null||qs!=null))throw new Error("invalid filter");const Mc={};return Js&&(Mc.address=Js),Hs.length&&(Mc.topics=Hs),Ma&&(Mc.fromBlock=Ma),qs&&(Mc.toBlock=qs),Ws&&(Mc.blockHash=Ws),Mc};let zs=[];if(Ps.address)if(Array.isArray(Ps.address))for(const Xs of Ps.address)zs.push(this._getAddress(Xs));else zs.push(this._getAddress(Ps.address));let Ys;"fromBlock"in Ps&&(Ys=this._getBlockTag(Ps.fromBlock));let Va;return"toBlock"in Ps&&(Va=this._getBlockTag(Ps.toBlock)),zs.filter(Xs=>typeof Xs!="string").length||Ys!=null&&typeof Ys!="string"||Va!=null&&typeof Va!="string"?Promise.all([Promise.all(zs),Ys,Va]).then(Xs=>Zs(Xs[0],Xs[1],Xs[2])):Zs(zs,Ys,Va)}_getTransactionRequest(Ps){const Hs=copyRequest(Ps),Ws=[];if(["to","from"].forEach(Zs=>{if(Hs[Zs]==null)return;const zs=resolveAddress(Hs[Zs],this);isPromise(zs)?Ws.push((async function(){Hs[Zs]=await zs})()):Hs[Zs]=zs}),Hs.blockTag!=null){const Zs=this._getBlockTag(Hs.blockTag);isPromise(Zs)?Ws.push((async function(){Hs.blockTag=await Zs})()):Hs.blockTag=Zs}return Ws.length?(async function(){return await Promise.all(Ws),Hs})():Hs}async getNetwork(){if(this.#o==null){const Zs=(async()=>{try{const zs=await this._detectNetwork();return this.emit("network",zs,null),zs}catch(zs){throw this.#o===Zs&&(this.#o=null),zs}})();return this.#o=Zs,(await Zs).clone()}const Ps=this.#o,[Hs,Ws]=await Promise.all([Ps,this._detectNetwork()]);return Hs.chainId!==Ws.chainId&&(this.#s?(this.emit("network",Ws,Hs),this.#o===Ps&&(this.#o=Promise.resolve(Ws))):assert(!1,`network changed: ${Hs.chainId} => ${Ws.chainId} `,"NETWORK_ERROR",{event:"changed"})),Hs.clone()}async getFeeData(){const Ps=await this.getNetwork(),Hs=async()=>{const{_block:Zs,gasPrice:zs,priorityFee:Ys}=await resolveProperties({_block:this.#y("latest",!1),gasPrice:(async()=>{try{const qs=await this.#c({method:"getGasPrice"});return getBigInt(qs,"%response")}catch{}return null})(),priorityFee:(async()=>{try{const qs=await this.#c({method:"getPriorityFee"});return getBigInt(qs,"%response")}catch{}return null})()});let Va=null,Xs=null;const Ma=this._wrapBlock(Zs,Ps);return Ma&&Ma.baseFeePerGas&&(Xs=Ys??BigInt("1000000000"),Va=Ma.baseFeePerGas*BN_2+Xs),new FeeData(zs,Va,Xs)},Ws=Ps.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(Ws){const Zs=new FetchRequest(Ws.url),zs=await Ws.processFunc(Hs,this,Zs);return new FeeData(zs.gasPrice,zs.maxFeePerGas,zs.maxPriorityFeePerGas)}return await Hs()}async estimateGas(Ps){let Hs=this._getTransactionRequest(Ps);return isPromise(Hs)&&(Hs=await Hs),getBigInt(await this.#c({method:"estimateGas",transaction:Hs}),"%response")}async#u(Ps,Hs,Ws){assert(Ws<MAX_CCIP_REDIRECTS,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},Ps,{blockTag:Hs,enableCcipRead:!0})});const Zs=copyRequest(Ps);try{return hexlify(await this._perform({method:"call",transaction:Zs,blockTag:Hs}))}catch(zs){if(!this.disableCcipRead&&isCallException(zs)&&zs.data&&Ws>=0&&Hs==="latest"&&Zs.to!=null&&dataSlice(zs.data,0,4)==="0x556f1830"){const Ys=zs.data,Va=await resolveAddress(Zs.to,this);let Xs;try{Xs=parseOffchainLookup(dataSlice(zs.data,4))}catch(Js){assert(!1,Js.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:Zs,info:{data:Ys}})}assert(Xs.sender.toLowerCase()===Va.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:Ys,reason:"OffchainLookup",transaction:Zs,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:Xs.errorArgs}});const Ma=await this.ccipReadFetch(Zs,Xs.calldata,Xs.urls);assert(Ma!=null,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:Zs,info:{data:zs.data,errorArgs:Xs.errorArgs}});const qs={to:Va,data:concat([Xs.selector,encodeBytes([Ma,Xs.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:qs});try{const Js=await this.#u(qs,Hs,Ws+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},qs),result:Js}),Js}catch(Js){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},qs),error:Js}),Js}}throw zs}}async#f(Ps){const{value:Hs}=await resolveProperties({network:this.getNetwork(),value:Ps});return Hs}async call(Ps){const{tx:Hs,blockTag:Ws}=await resolveProperties({tx:this._getTransactionRequest(Ps),blockTag:this._getBlockTag(Ps.blockTag)});return await this.#f(this.#u(Hs,Ws,Ps.enableCcipRead?0:-1))}async#h(Ps,Hs,Ws){let Zs=this._getAddress(Hs),zs=this._getBlockTag(Ws);return(typeof Zs!="string"||typeof zs!="string")&&([Zs,zs]=await Promise.all([Zs,zs])),await this.#f(this.#c(Object.assign(Ps,{address:Zs,blockTag:zs})))}async getBalance(Ps,Hs){return getBigInt(await this.#h({method:"getBalance"},Ps,Hs),"%response")}async getTransactionCount(Ps,Hs){return getNumber(await this.#h({method:"getTransactionCount"},Ps,Hs),"%response")}async getCode(Ps,Hs){return hexlify(await this.#h({method:"getCode"},Ps,Hs))}async getStorage(Ps,Hs,Ws){const Zs=getBigInt(Hs,"position");return hexlify(await this.#h({method:"getStorage",position:Zs},Ps,Ws))}async broadcastTransaction(Ps){const{blockNumber:Hs,hash:Ws,network:Zs}=await resolveProperties({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:Ps}),network:this.getNetwork()}),zs=Transaction.from(Ps);if(zs.hash!==Ws)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(zs,Zs).replaceableTransaction(Hs)}async#y(Ps,Hs){if(isHexString(Ps,32))return await this.#c({method:"getBlock",blockHash:Ps,includeTransactions:Hs});let Ws=this._getBlockTag(Ps);return typeof Ws!="string"&&(Ws=await Ws),await this.#c({method:"getBlock",blockTag:Ws,includeTransactions:Hs})}async getBlock(Ps,Hs){const{network:Ws,params:Zs}=await resolveProperties({network:this.getNetwork(),params:this.#y(Ps,!!Hs)});return Zs==null?null:this._wrapBlock(Zs,Ws)}async getTransaction(Ps){const{network:Hs,params:Ws}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getTransaction",hash:Ps})});return Ws==null?null:this._wrapTransactionResponse(Ws,Hs)}async getTransactionReceipt(Ps){const{network:Hs,params:Ws}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getTransactionReceipt",hash:Ps})});if(Ws==null)return null;if(Ws.gasPrice==null&&Ws.effectiveGasPrice==null){const Zs=await this.#c({method:"getTransaction",hash:Ps});if(Zs==null)throw new Error("report this; could not find tx or effectiveGasPrice");Ws.effectiveGasPrice=Zs.gasPrice}return this._wrapTransactionReceipt(Ws,Hs)}async getTransactionResult(Ps){const{result:Hs}=await resolveProperties({network:this.getNetwork(),result:this.#c({method:"getTransactionResult",hash:Ps})});return Hs==null?null:hexlify(Hs)}async getLogs(Ps){let Hs=this._getFilter(Ps);isPromise(Hs)&&(Hs=await Hs);const{network:Ws,params:Zs}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getLogs",filter:Hs})});return Zs.map(zs=>this._wrapLog(zs,Ws))}_getProvider(Ps){assert(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(Ps){return await EnsResolver.fromName(this,Ps)}async getAvatar(Ps){const Hs=await this.getResolver(Ps);return Hs?await Hs.getAvatar():null}async resolveName(Ps){const Hs=await this.getResolver(Ps);return Hs?await Hs.getAddress():null}async lookupAddress(Ps){Ps=getAddress(Ps);const Hs=namehash(Ps.substring(2).toLowerCase()+".addr.reverse");try{const Ws=await EnsResolver.getEnsAddress(this),zs=await new Contract(Ws,["function resolver(bytes32) view returns (address)"],this).resolver(Hs);if(zs==null||zs===ZeroAddress)return null;const Va=await new Contract(zs,["function name(bytes32) view returns (string)"],this).name(Hs);return await this.resolveName(Va)!==Ps?null:Va}catch(Ws){if(isError(Ws,"BAD_DATA")&&Ws.value==="0x"||isError(Ws,"CALL_EXCEPTION"))return null;throw Ws}return null}async waitForTransaction(Ps,Hs,Ws){const Zs=Hs??1;return Zs===0?this.getTransactionReceipt(Ps):new Promise(async(zs,Ys)=>{let Va=null;const Xs=(async Ma=>{try{const qs=await this.getTransactionReceipt(Ps);if(qs!=null&&Ma-qs.blockNumber+1>=Zs){zs(qs),Va&&(clearTimeout(Va),Va=null);return}}catch(qs){console.log("EEE",qs)}this.once("block",Xs)});Ws!=null&&(Va=setTimeout(()=>{Va!=null&&(Va=null,this.off("block",Xs),Ys(makeError("timeout","TIMEOUT",{reason:"timeout"})))},Ws)),Xs(await this.getBlockNumber())})}async waitForBlock(Ps){assert(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(Ps){const Hs=this.#l.get(Ps);Hs&&(Hs.timer&&clearTimeout(Hs.timer),this.#l.delete(Ps))}_setTimeout(Ps,Hs){Hs==null&&(Hs=0);const Ws=this.#d++,Zs=()=>{this.#l.delete(Ws),Ps()};if(this.paused)this.#l.set(Ws,{timer:null,func:Zs,time:Hs});else{const zs=setTimeout(Zs,Hs);this.#l.set(Ws,{timer:zs,func:Zs,time:getTime()})}return Ws}_forEachSubscriber(Ps){for(const Hs of this.#e.values())Ps(Hs.subscriber)}_getSubscriber(Ps){switch(Ps.type){case"debug":case"error":case"network":return new UnmanagedSubscriber(Ps.type);case"block":{const Hs=new PollingBlockSubscriber(this);return Hs.pollingInterval=this.pollingInterval,Hs}case"safe":case"finalized":return new PollingBlockTagSubscriber(this,Ps.type);case"event":return new PollingEventSubscriber(this,Ps.filter);case"transaction":return new PollingTransactionSubscriber(this,Ps.hash);case"orphan":return new PollingOrphanSubscriber(this,Ps.filter)}throw new Error(`unsupported event: ${Ps.type}`)}_recoverSubscriber(Ps,Hs){for(const Ws of this.#e.values())if(Ws.subscriber===Ps){Ws.started&&Ws.subscriber.stop(),Ws.subscriber=Hs,Ws.started&&Hs.start(),this.#r!=null&&Hs.pause(this.#r);break}}async#m(Ps,Hs){let Ws=await getSubscription(Ps,this);return Ws.type==="event"&&Hs&&Hs.length>0&&Hs[0].removed===!0&&(Ws=await getSubscription({orphan:"drop-log",log:Hs[0]},this)),this.#e.get(Ws.tag)||null}async#b(Ps){const Hs=await getSubscription(Ps,this),Ws=Hs.tag;let Zs=this.#e.get(Ws);return Zs||(Zs={subscriber:this._getSubscriber(Hs),tag:Ws,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#e.set(Ws,Zs)),Zs}async on(Ps,Hs){const Ws=await this.#b(Ps);return Ws.listeners.push({listener:Hs,once:!1}),Ws.started||(Ws.subscriber.start(),Ws.started=!0,this.#r!=null&&Ws.subscriber.pause(this.#r)),this}async once(Ps,Hs){const Ws=await this.#b(Ps);return Ws.listeners.push({listener:Hs,once:!0}),Ws.started||(Ws.subscriber.start(),Ws.started=!0,this.#r!=null&&Ws.subscriber.pause(this.#r)),this}async emit(Ps,...Hs){const Ws=await this.#m(Ps,Hs);if(!Ws||Ws.listeners.length===0)return!1;const Zs=Ws.listeners.length;return Ws.listeners=Ws.listeners.filter(({listener:zs,once:Ys})=>{const Va=new EventPayload(this,Ys?null:zs,Ps);try{zs.call(this,...Hs,Va)}catch{}return!Ys}),Ws.listeners.length===0&&(Ws.started&&Ws.subscriber.stop(),this.#e.delete(Ws.tag)),Zs>0}async listenerCount(Ps){if(Ps){const Ws=await this.#m(Ps);return Ws?Ws.listeners.length:0}let Hs=0;for(const{listeners:Ws}of this.#e.values())Hs+=Ws.length;return Hs}async listeners(Ps){if(Ps){const Ws=await this.#m(Ps);return Ws?Ws.listeners.map(({listener:Zs})=>Zs):[]}let Hs=[];for(const{listeners:Ws}of this.#e.values())Hs=Hs.concat(Ws.map(({listener:Zs})=>Zs));return Hs}async off(Ps,Hs){const Ws=await this.#m(Ps);if(!Ws)return this;if(Hs){const Zs=Ws.listeners.map(({listener:zs})=>zs).indexOf(Hs);Zs>=0&&Ws.listeners.splice(Zs,1)}return(!Hs||Ws.listeners.length===0)&&(Ws.started&&Ws.subscriber.stop(),this.#e.delete(Ws.tag)),this}async removeAllListeners(Ps){if(Ps){const{tag:Hs,started:Ws,subscriber:Zs}=await this.#b(Ps);Ws&&Zs.stop(),this.#e.delete(Hs)}else for(const[Hs,{started:Ws,subscriber:Zs}]of this.#e)Ws&&Zs.stop(),this.#e.delete(Hs);return this}async addListener(Ps,Hs){return await this.on(Ps,Hs)}async removeListener(Ps,Hs){return this.off(Ps,Hs)}get destroyed(){return this.#n}destroy(){this.removeAllListeners();for(const Ps of this.#l.keys())this._clearTimeout(Ps);this.#n=!0}get paused(){return this.#r!=null}set paused(Ps){!!Ps!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(Ps){if(this.#a=-1,this.#r!=null){if(this.#r==!!Ps)return;assert(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(Hs=>Hs.pause(Ps)),this.#r=!!Ps;for(const Hs of this.#l.values())Hs.timer&&clearTimeout(Hs.timer),Hs.time=getTime()-Hs.time}resume(){if(this.#r!=null){this._forEachSubscriber(Ps=>Ps.resume()),this.#r=null;for(const Ps of this.#l.values()){let Hs=Ps.time;Hs<0&&(Hs=0),Ps.time=getTime(),setTimeout(Ps.func,Hs)}}}}function _parseString(Fs,Ps){try{const Hs=_parseBytes(Fs,Ps);if(Hs)return toUtf8String(Hs)}catch{}return null}function _parseBytes(Fs,Ps){if(Fs==="0x")return null;try{const Hs=getNumber(dataSlice(Fs,Ps,Ps+32)),Ws=getNumber(dataSlice(Fs,Hs,Hs+32));return dataSlice(Fs,Hs+32,Hs+32+Ws)}catch{}return null}function numPad(Fs){const Ps=toBeArray(Fs);if(Ps.length>32)throw new Error("internal; should not happen");const Hs=new Uint8Array(32);return Hs.set(Ps,32-Ps.length),Hs}function bytesPad(Fs){if(Fs.length%32===0)return Fs;const Ps=new Uint8Array(Math.ceil(Fs.length/32)*32);return Ps.set(Fs),Ps}const empty=new Uint8Array([]);function encodeBytes(Fs){const Ps=[];let Hs=0;for(let Ws=0;Ws<Fs.length;Ws++)Ps.push(empty),Hs+=32;for(let Ws=0;Ws<Fs.length;Ws++){const Zs=getBytes(Fs[Ws]);Ps[Ws]=numPad(Hs),Ps.push(numPad(Zs.length)),Ps.push(bytesPad(Zs)),Hs+=32+Math.ceil(Zs.length/32)*32}return concat(Ps)}const zeros="0x0000000000000000000000000000000000000000000000000000000000000000";function parseOffchainLookup(Fs){const Ps={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};assert(dataLength(Fs)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const Hs=dataSlice(Fs,0,32);assert(dataSlice(Hs,0,12)===dataSlice(zeros,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),Ps.sender=dataSlice(Hs,12);try{const Ws=[],Zs=getNumber(dataSlice(Fs,32,64)),zs=getNumber(dataSlice(Fs,Zs,Zs+32)),Ys=dataSlice(Fs,Zs+32);for(let Va=0;Va<zs;Va++){const Xs=_parseString(Ys,Va*32);if(Xs==null)throw new Error("abort");Ws.push(Xs)}Ps.urls=Ws}catch{assert(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const Ws=_parseBytes(Fs,64);if(Ws==null)throw new Error("abort");Ps.calldata=Ws}catch{assert(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}assert(dataSlice(Fs,100,128)===dataSlice(zeros,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),Ps.selector=dataSlice(Fs,96,100);try{const Ws=_parseBytes(Fs,128);if(Ws==null)throw new Error("abort");Ps.extraData=Ws}catch{assert(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return Ps.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map(Ws=>Ps[Ws]),Ps}function checkProvider(Fs,Ps){if(Fs.provider)return Fs.provider;assert(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:Ps})}async function populate(Fs,Ps){let Hs=copyRequest(Ps);if(Hs.to!=null&&(Hs.to=resolveAddress(Hs.to,Fs)),Hs.from!=null){const Ws=Hs.from;Hs.from=Promise.all([Fs.getAddress(),resolveAddress(Ws,Fs)]).then(([Zs,zs])=>(assertArgument(Zs.toLowerCase()===zs.toLowerCase(),"transaction from mismatch","tx.from",zs),Zs))}else Hs.from=Fs.getAddress();return await resolveProperties(Hs)}class AbstractSigner{provider;constructor(Ps){defineProperties(this,{provider:Ps||null})}async getNonce(Ps){return checkProvider(this,"getTransactionCount").getTransactionCount(await this.getAddress(),Ps)}async populateCall(Ps){return await populate(this,Ps)}async populateTransaction(Ps){const Hs=checkProvider(this,"populateTransaction"),Ws=await populate(this,Ps);Ws.nonce==null&&(Ws.nonce=await this.getNonce("pending")),Ws.gasLimit==null&&(Ws.gasLimit=await this.estimateGas(Ws));const Zs=await this.provider.getNetwork();if(Ws.chainId!=null){const Ys=getBigInt(Ws.chainId);assertArgument(Ys===Zs.chainId,"transaction chainId mismatch","tx.chainId",Ps.chainId)}else Ws.chainId=Zs.chainId;const zs=Ws.maxFeePerGas!=null||Ws.maxPriorityFeePerGas!=null;if(Ws.gasPrice!=null&&(Ws.type===2||zs)?assertArgument(!1,"eip-1559 transaction do not support gasPrice","tx",Ps):(Ws.type===0||Ws.type===1)&&zs&&assertArgument(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",Ps),(Ws.type===2||Ws.type==null)&&Ws.maxFeePerGas!=null&&Ws.maxPriorityFeePerGas!=null)Ws.type=2;else if(Ws.type===0||Ws.type===1){const Ys=await Hs.getFeeData();assert(Ys.gasPrice!=null,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),Ws.gasPrice==null&&(Ws.gasPrice=Ys.gasPrice)}else{const Ys=await Hs.getFeeData();if(Ws.type==null)if(Ys.maxFeePerGas!=null&&Ys.maxPriorityFeePerGas!=null)if(Ws.authorizationList&&Ws.authorizationList.length?Ws.type=4:Ws.type=2,Ws.gasPrice!=null){const Va=Ws.gasPrice;delete Ws.gasPrice,Ws.maxFeePerGas=Va,Ws.maxPriorityFeePerGas=Va}else Ws.maxFeePerGas==null&&(Ws.maxFeePerGas=Ys.maxFeePerGas),Ws.maxPriorityFeePerGas==null&&(Ws.maxPriorityFeePerGas=Ys.maxPriorityFeePerGas);else Ys.gasPrice!=null?(assert(!zs,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),Ws.gasPrice==null&&(Ws.gasPrice=Ys.gasPrice),Ws.type=0):assert(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else(Ws.type===2||Ws.type===3||Ws.type===4)&&(Ws.maxFeePerGas==null&&(Ws.maxFeePerGas=Ys.maxFeePerGas),Ws.maxPriorityFeePerGas==null&&(Ws.maxPriorityFeePerGas=Ys.maxPriorityFeePerGas))}return await resolveProperties(Ws)}async populateAuthorization(Ps){const Hs=Object.assign({},Ps);return Hs.chainId==null&&(Hs.chainId=(await checkProvider(this,"getNetwork").getNetwork()).chainId),Hs.nonce==null&&(Hs.nonce=await this.getNonce()),Hs}async estimateGas(Ps){return checkProvider(this,"estimateGas").estimateGas(await this.populateCall(Ps))}async call(Ps){return checkProvider(this,"call").call(await this.populateCall(Ps))}async resolveName(Ps){return await checkProvider(this,"resolveName").resolveName(Ps)}async sendTransaction(Ps){const Hs=checkProvider(this,"sendTransaction"),Ws=await this.populateTransaction(Ps);delete Ws.from;const Zs=Transaction.from(Ws);return await Hs.broadcastTransaction(await this.signTransaction(Zs))}authorize(Ps){assert(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}function copy(Fs){return JSON.parse(JSON.stringify(Fs))}class FilterIdSubscriber{#e;#t;#r;#n;#o;#s;constructor(Ps){this.#e=Ps,this.#t=null,this.#r=this.#i.bind(this),this.#n=!1,this.#o=null,this.#s=!1}_subscribe(Ps){throw new Error("subclasses must override this")}_emitResults(Ps,Hs){throw new Error("subclasses must override this")}_recover(Ps){throw new Error("subclasses must override this")}async#i(Ps){try{this.#t==null&&(this.#t=this._subscribe(this.#e));let Hs=null;try{Hs=await this.#t}catch(zs){if(!isError(zs,"UNSUPPORTED_OPERATION")||zs.operation!=="eth_newFilter")throw zs}if(Hs==null){this.#t=null,this.#e._recoverSubscriber(this,this._recover(this.#e));return}const Ws=await this.#e.getNetwork();if(this.#o||(this.#o=Ws),this.#o.chainId!==Ws.chainId)throw new Error("chaid changed");if(this.#s)return;const Zs=await this.#e.send("eth_getFilterChanges",[Hs]);await this._emitResults(this.#e,Zs)}catch(Hs){console.log("@TODO",Hs)}this.#e.once("block",this.#r)}#a(){const Ps=this.#t;Ps&&(this.#t=null,Ps.then(Hs=>{this.#e.destroyed||this.#e.send("eth_uninstallFilter",[Hs])}))}start(){this.#n||(this.#n=!0,this.#i(-2))}stop(){this.#n&&(this.#n=!1,this.#s=!0,this.#a(),this.#e.off("block",this.#r))}pause(Ps){Ps&&this.#a(),this.#e.off("block",this.#r)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=copy(Hs)}_recover(Ps){return new PollingEventSubscriber(Ps,this.#e)}async _subscribe(Ps){return await Ps.send("eth_newFilter",[this.#e])}async _emitResults(Ps,Hs){for(const Ws of Hs)Ps.emit(this.#e,Ps._wrapLog(Ws,Ps._network))}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(Ps){return await Ps.send("eth_newPendingTransactionFilter",[])}async _emitResults(Ps,Hs){for(const Ws of Hs)Ps.emit("pending",Ws)}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(Fs){if(Fs==null||Primitive.indexOf(typeof Fs)>=0||typeof Fs.getAddress=="function")return Fs;if(Array.isArray(Fs))return Fs.map(deepCopy);if(typeof Fs=="object")return Object.keys(Fs).reduce((Ps,Hs)=>(Ps[Hs]=Fs[Hs],Ps),{});throw new Error(`should not happen: ${Fs} (${typeof Fs})`)}function stall(Fs){return new Promise(Ps=>{setTimeout(Ps,Fs)})}function getLowerCase(Fs){return Fs&&Fs.toLowerCase()}function isPollable(Fs){return Fs&&typeof Fs.pollingInterval=="number"}const defaultOptions={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class JsonRpcSigner extends AbstractSigner{address;constructor(Ps,Hs){super(Ps),Hs=getAddress(Hs),defineProperties(this,{address:Hs})}connect(Ps){assert(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(Ps){return await this.populateCall(Ps)}async sendUncheckedTransaction(Ps){const Hs=deepCopy(Ps),Ws=[];if(Hs.from){const zs=Hs.from;Ws.push((async()=>{const Ys=await resolveAddress(zs,this.provider);assertArgument(Ys!=null&&Ys.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",Ps),Hs.from=Ys})())}else Hs.from=this.address;if(Hs.gasLimit==null&&Ws.push((async()=>{Hs.gasLimit=await this.provider.estimateGas({...Hs,from:this.address})})()),Hs.to!=null){const zs=Hs.to;Ws.push((async()=>{Hs.to=await resolveAddress(zs,this.provider)})())}Ws.length&&await Promise.all(Ws);const Zs=this.provider.getRpcTransaction(Hs);return this.provider.send("eth_sendTransaction",[Zs])}async sendTransaction(Ps){const Hs=await this.provider.getBlockNumber(),Ws=await this.sendUncheckedTransaction(Ps);return await new Promise((Zs,zs)=>{const Ys=[1e3,100];let Va=0;const Xs=async()=>{try{const Ma=await this.provider.getTransaction(Ws);if(Ma!=null){Zs(Ma.replaceableTransaction(Hs));return}}catch(Ma){if(isError(Ma,"CANCELLED")||isError(Ma,"BAD_DATA")||isError(Ma,"NETWORK_ERROR")||isError(Ma,"UNSUPPORTED_OPERATION")){Ma.info==null&&(Ma.info={}),Ma.info.sendTransactionHash=Ws,zs(Ma);return}if(isError(Ma,"INVALID_ARGUMENT")&&(Va++,Ma.info==null&&(Ma.info={}),Ma.info.sendTransactionHash=Ws,Va>10)){zs(Ma);return}this.provider.emit("error",makeError("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:Ma}))}this.provider._setTimeout(()=>{Xs()},Ys.pop()||4e3)};Xs()})}async signTransaction(Ps){const Hs=deepCopy(Ps);if(Hs.from){const Zs=await resolveAddress(Hs.from,this.provider);assertArgument(Zs!=null&&Zs.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",Ps),Hs.from=Zs}else Hs.from=this.address;const Ws=this.provider.getRpcTransaction(Hs);return await this.provider.send("eth_signTransaction",[Ws])}async signMessage(Ps){const Hs=typeof Ps=="string"?toUtf8Bytes(Ps):Ps;return await this.provider.send("personal_sign",[hexlify(Hs),this.address.toLowerCase()])}async signTypedData(Ps,Hs,Ws){const Zs=deepCopy(Ws),zs=await TypedDataEncoder.resolveNames(Ps,Hs,Zs,async Ys=>{const Va=await resolveAddress(Ys);return assertArgument(Va!=null,"TypedData does not support null address","value",Ys),Va});return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(zs.domain,Hs,zs.value))])}async unlock(Ps){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),Ps,null])}async _legacySignMessage(Ps){const Hs=typeof Ps=="string"?toUtf8Bytes(Ps):Ps;return await this.provider.send("eth_sign",[this.address.toLowerCase(),hexlify(Hs)])}}class JsonRpcApiProvider extends AbstractProvider{#e;#t;#r;#n;#o;#s;#i;#a(){if(this.#n)return;const Ps=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#n=setTimeout(()=>{this.#n=null;const Hs=this.#r;for(this.#r=[];Hs.length;){const Ws=[Hs.shift()];for(;Hs.length&&Ws.length!==this.#e.batchMaxCount;)if(Ws.push(Hs.shift()),JSON.stringify(Ws.map(zs=>zs.payload)).length>this.#e.batchMaxSize){Hs.unshift(Ws.pop());break}(async()=>{const Zs=Ws.length===1?Ws[0].payload:Ws.map(zs=>zs.payload);this.emit("debug",{action:"sendRpcPayload",payload:Zs});try{const zs=await this._send(Zs);this.emit("debug",{action:"receiveRpcResult",result:zs});for(const{resolve:Ys,reject:Va,payload:Xs}of Ws){if(this.destroyed){Va(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Xs.method}));continue}const Ma=zs.filter(qs=>qs.id===Xs.id)[0];if(Ma==null){const qs=makeError("missing response for request","BAD_DATA",{value:zs,info:{payload:Xs}});this.emit("error",qs),Va(qs);continue}if("error"in Ma){Va(this.getRpcError(Xs,Ma));continue}Ys(Ma.result)}}catch(zs){this.emit("debug",{action:"receiveRpcError",error:zs});for(const{reject:Ys}of Ws)Ys(zs)}})()}},Ps)}constructor(Ps,Hs){super(Ps,Hs),this.#t=1,this.#e=Object.assign({},defaultOptions,Hs||{}),this.#r=[],this.#n=null,this.#s=null,this.#i=null;{let Zs=null;const zs=new Promise(Ys=>{Zs=Ys});this.#o={promise:zs,resolve:Zs}}const Ws=this._getOption("staticNetwork");typeof Ws=="boolean"?(assertArgument(!Ws||Ps!=="any","staticNetwork cannot be used on special network 'any'","options",Hs),Ws&&Ps!=null&&(this.#s=Network.from(Ps))):Ws&&(assertArgument(Ps==null||Ws.matches(Ps),"staticNetwork MUST match network object","options",Hs),this.#s=Ws)}_getOption(Ps){return this.#e[Ps]}get _network(){return assert(this.#s,"network is not available yet","NETWORK_ERROR"),this.#s}async _perform(Ps){if(Ps.method==="call"||Ps.method==="estimateGas"){let Ws=Ps.transaction;if(Ws&&Ws.type!=null&&getBigInt(Ws.type)&&Ws.maxFeePerGas==null&&Ws.maxPriorityFeePerGas==null){const Zs=await this.getFeeData();Zs.maxFeePerGas==null&&Zs.maxPriorityFeePerGas==null&&(Ps=Object.assign({},Ps,{transaction:Object.assign({},Ws,{type:void 0})}))}}const Hs=this.getRpcRequest(Ps);return Hs!=null?await this.send(Hs.method,Hs.args):super._perform(Ps)}async _detectNetwork(){const Ps=this._getOption("staticNetwork");if(Ps)if(Ps===!0){if(this.#s)return this.#s}else return Ps;return this.#i?await this.#i:this.ready?(this.#i=(async()=>{try{const Hs=Network.from(getBigInt(await this.send("eth_chainId",[])));return this.#i=null,Hs}catch(Hs){throw this.#i=null,Hs}})(),await this.#i):(this.#i=(async()=>{const Hs={id:this.#t++,method:"eth_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",{action:"sendRpcPayload",payload:Hs});let Ws;try{Ws=(await this._send(Hs))[0],this.#i=null}catch(Zs){throw this.#i=null,this.emit("debug",{action:"receiveRpcError",error:Zs}),Zs}if(this.emit("debug",{action:"receiveRpcResult",result:Ws}),"result"in Ws)return Network.from(getBigInt(Ws.result));throw this.getRpcError(Hs,Ws)})(),await this.#i)}_start(){this.#o==null||this.#o.resolve==null||(this.#o.resolve(),this.#o=null,(async()=>{for(;this.#s==null&&!this.destroyed;)try{this.#s=await this._detectNetwork()}catch(Ps){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",makeError("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:Ps}})),await stall(1e3)}this.#a()})())}async _waitUntilReady(){if(this.#o!=null)return await this.#o.promise}_getSubscriber(Ps){return Ps.type==="pending"?new FilterIdPendingSubscriber(this):Ps.type==="event"?this._getOption("polling")?new PollingEventSubscriber(this,Ps.filter):new FilterIdEventSubscriber(this,Ps.filter):Ps.type==="orphan"&&Ps.filter.orphan==="drop-log"?new UnmanagedSubscriber("orphan"):super._getSubscriber(Ps)}get ready(){return this.#o==null}getRpcTransaction(Ps){const Hs={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(Ws=>{if(Ps[Ws]==null)return;let Zs=Ws;Ws==="gasLimit"&&(Zs="gas"),Hs[Zs]=toQuantity(getBigInt(Ps[Ws],`tx.${Ws}`))}),["from","to","data"].forEach(Ws=>{Ps[Ws]!=null&&(Hs[Ws]=hexlify(Ps[Ws]))}),Ps.accessList&&(Hs.accessList=accessListify(Ps.accessList)),Ps.blobVersionedHashes&&(Hs.blobVersionedHashes=Ps.blobVersionedHashes.map(Ws=>Ws.toLowerCase())),Ps.authorizationList&&(Hs.authorizationList=Ps.authorizationList.map(Ws=>{const Zs=authorizationify(Ws);return{address:Zs.address,nonce:toQuantity(Zs.nonce),chainId:toQuantity(Zs.chainId),yParity:toQuantity(Zs.signature.yParity),r:toQuantity(Zs.signature.r),s:toQuantity(Zs.signature.s)}})),Hs}getRpcRequest(Ps){switch(Ps.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getCode":return{method:"eth_getCode",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[getLowerCase(Ps.address),"0x"+Ps.position.toString(16),Ps.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[Ps.signedTransaction]};case"getBlock":if("blockTag"in Ps)return{method:"eth_getBlockByNumber",args:[Ps.blockTag,!!Ps.includeTransactions]};if("blockHash"in Ps)return{method:"eth_getBlockByHash",args:[Ps.blockHash,!!Ps.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[Ps.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[Ps.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(Ps.transaction),Ps.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(Ps.transaction)]};case"getLogs":return Ps.filter&&Ps.filter.address!=null&&(Array.isArray(Ps.filter.address)?Ps.filter.address=Ps.filter.address.map(getLowerCase):Ps.filter.address=getLowerCase(Ps.filter.address)),{method:"eth_getLogs",args:[Ps.filter]}}return null}getRpcError(Ps,Hs){const{method:Ws}=Ps,{error:Zs}=Hs;if(Ws==="eth_estimateGas"&&Zs.message){const Va=Zs.message;if(!Va.match(/revert/i)&&Va.match(/insufficient funds/i))return makeError("insufficient funds","INSUFFICIENT_FUNDS",{transaction:Ps.params[0],info:{payload:Ps,error:Zs}});if(Va.match(/nonce/i)&&Va.match(/too low/i))return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:Ps.params[0],info:{payload:Ps,error:Zs}})}if(Ws==="eth_call"||Ws==="eth_estimateGas"){const Va=spelunkData(Zs),Xs=AbiCoder.getBuiltinCallException(Ws==="eth_call"?"call":"estimateGas",Ps.params[0],Va?Va.data:null);return Xs.info={error:Zs,payload:Ps},Xs}const zs=JSON.stringify(spelunkMessage(Zs));if(typeof Zs.message=="string"&&Zs.message.match(/user denied|ethers-user-denied/i))return makeError("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[Ws]||"unknown",reason:"rejected",info:{payload:Ps,error:Zs}});if(Ws==="eth_sendRawTransaction"||Ws==="eth_sendTransaction"){const Va=Ps.params[0];if(zs.match(/insufficient funds|base fee exceeds gas limit/i))return makeError("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:Va,info:{error:Zs}});if(zs.match(/nonce/i)&&zs.match(/too low/i))return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:Va,info:{error:Zs}});if(zs.match(/replacement transaction/i)&&zs.match(/underpriced/i))return makeError("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:Va,info:{error:Zs}});if(zs.match(/only replay-protected/i))return makeError("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:Ws,info:{transaction:Va,info:{error:Zs}}})}let Ys=!!zs.match(/the method .* does not exist/i);return Ys||Zs&&Zs.details&&Zs.details.startsWith("Unauthorized method:")&&(Ys=!0),Ys?makeError("unsupported operation","UNSUPPORTED_OPERATION",{operation:Ps.method,info:{error:Zs,payload:Ps}}):makeError("could not coalesce error","UNKNOWN_ERROR",{error:Zs,payload:Ps})}send(Ps,Hs){if(this.destroyed)return Promise.reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Ps}));const Ws=this.#t++,Zs=new Promise((zs,Ys)=>{this.#r.push({resolve:zs,reject:Ys,payload:{method:Ps,params:Hs,id:Ws,jsonrpc:"2.0"}})});return this.#a(),Zs}async getSigner(Ps){Ps==null&&(Ps=0);const Hs=this.send("eth_accounts",[]);if(typeof Ps=="number"){const Zs=await Hs;if(Ps>=Zs.length)throw new Error("no such account");return new JsonRpcSigner(this,Zs[Ps])}const{accounts:Ws}=await resolveProperties({network:this.getNetwork(),accounts:Hs});Ps=getAddress(Ps);for(const Zs of Ws)if(getAddress(Zs)===Ps)return new JsonRpcSigner(this,Ps);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map(Hs=>new JsonRpcSigner(this,Hs))}destroy(){this.#n&&(clearTimeout(this.#n),this.#n=null);for(const{payload:Ps,reject:Hs}of this.#r)Hs(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Ps.method}));this.#r=[],super.destroy()}}class JsonRpcApiPollingProvider extends JsonRpcApiProvider{#e;constructor(Ps,Hs){super(Ps,Hs);let Ws=this._getOption("pollingInterval");Ws==null&&(Ws=defaultOptions.pollingInterval),this.#e=Ws}_getSubscriber(Ps){const Hs=super._getSubscriber(Ps);return isPollable(Hs)&&(Hs.pollingInterval=this.#e),Hs}get pollingInterval(){return this.#e}set pollingInterval(Ps){if(!Number.isInteger(Ps)||Ps<0)throw new Error("invalid interval");this.#e=Ps,this._forEachSubscriber(Hs=>{isPollable(Hs)&&(Hs.pollingInterval=this.#e)})}}function spelunkData(Fs){if(Fs==null)return null;if(typeof Fs.message=="string"&&Fs.message.match(/revert/i)&&isHexString(Fs.data))return{message:Fs.message,data:Fs.data};if(typeof Fs=="object"){for(const Ps in Fs){const Hs=spelunkData(Fs[Ps]);if(Hs)return Hs}return null}if(typeof Fs=="string")try{return spelunkData(JSON.parse(Fs))}catch{}return null}function _spelunkMessage(Fs,Ps){if(Fs!=null){if(typeof Fs.message=="string"&&Ps.push(Fs.message),typeof Fs=="object")for(const Hs in Fs)_spelunkMessage(Fs[Hs],Ps);if(typeof Fs=="string")try{return _spelunkMessage(JSON.parse(Fs),Ps)}catch{}}}function spelunkMessage(Fs){const Ps=[];return _spelunkMessage(Fs,Ps),Ps}class BrowserProvider extends JsonRpcApiPollingProvider{#e;#t;constructor(Ps,Hs,Ws){const Zs=Object.assign({},Ws??{},{batchMaxCount:1});assertArgument(Ps&&Ps.request,"invalid EIP-1193 provider","ethereum",Ps),super(Hs,Zs),this.#t=null,Ws&&Ws.providerInfo&&(this.#t=Ws.providerInfo),this.#e=async(zs,Ys)=>{const Va={method:zs,params:Ys};this.emit("debug",{action:"sendEip1193Request",payload:Va});try{const Xs=await Ps.request(Va);return this.emit("debug",{action:"receiveEip1193Result",result:Xs}),Xs}catch(Xs){const Ma=new Error(Xs.message);throw Ma.code=Xs.code,Ma.data=Xs.data,Ma.payload=Va,this.emit("debug",{action:"receiveEip1193Error",error:Ma}),Ma}}}get providerInfo(){return this.#t}async send(Ps,Hs){return await this._start(),await super.send(Ps,Hs)}async _send(Ps){assertArgument(!Array.isArray(Ps),"EIP-1193 does not support batch request","payload",Ps);try{const Hs=await this.#e(Ps.method,Ps.params||[]);return[{id:Ps.id,result:Hs}]}catch(Hs){return[{id:Ps.id,error:{code:Hs.code,data:Hs.data,message:Hs.message}}]}}getRpcError(Ps,Hs){switch(Hs=JSON.parse(JSON.stringify(Hs)),Hs.error.code||-1){case 4001:Hs.error.message=`ethers-user-denied: ${Hs.error.message}`;break;case 4200:Hs.error.message=`ethers-unsupported: ${Hs.error.message}`;break}return super.getRpcError(Ps,Hs)}async hasSigner(Ps){Ps==null&&(Ps=0);const Hs=await this.send("eth_accounts",[]);return typeof Ps=="number"?Hs.length>Ps:(Ps=Ps.toLowerCase(),Hs.filter(Ws=>Ws.toLowerCase()===Ps).length!==0)}async getSigner(Ps){if(Ps==null&&(Ps=0),!await this.hasSigner(Ps))try{await this.#e("eth_requestAccounts",[])}catch(Hs){const Ws=Hs.payload;throw this.getRpcError(Ws,{id:Ws.id,error:Hs})}return await super.getSigner(Ps)}static async discover(Ps){if(Ps==null&&(Ps={}),Ps.provider)return new BrowserProvider(Ps.provider);const Hs=Ps.window?Ps.window:typeof window<"u"?window:null;if(Hs==null)return null;const Ws=Ps.anyProvider;if(Ws&&Hs.ethereum)return new BrowserProvider(Hs.ethereum);if(!("addEventListener"in Hs&&"dispatchEvent"in Hs&&"removeEventListener"in Hs))return null;const Zs=Ps.timeout?Ps.timeout:300;return Zs===0?null:await new Promise((zs,Ys)=>{let Va=[];const Xs=Js=>{Va.push(Js.detail),Ws&&Ma()},Ma=()=>{if(clearTimeout(qs),Va.length)if(Ps&&Ps.filter){const Js=Ps.filter(Va.map(Mc=>Object.assign({},Mc.info)));if(Js==null)zs(null);else if(Js instanceof BrowserProvider)zs(Js);else{let Mc=null;if(Js.uuid&&(Mc=Va.filter(Vc=>Js.uuid===Vc.info.uuid)[0]),Mc){const{provider:ol,info:Vc}=Mc;zs(new BrowserProvider(ol,void 0,{providerInfo:Vc}))}else Ys(makeError("filter returned unknown info","UNSUPPORTED_OPERATION",{value:Js}))}}else{const{provider:Js,info:Mc}=Va[0];zs(new BrowserProvider(Js,void 0,{providerInfo:Mc}))}else zs(null);Hs.removeEventListener("eip6963:announceProvider",Xs)},qs=setTimeout(()=>{Ma()},Zs);Hs.addEventListener("eip6963:announceProvider",Xs),Hs.dispatchEvent(new Event("eip6963:requestProvider"))})}}function defineChain(Fs){return{formatters:void 0,fees:void 0,serializers:void 0,...Fs}}defineChain({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),defineChain({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"}),defineChain({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"}),defineChain({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),defineChain({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0}),defineChain({id:"00000008819873e925422c1ff0f99f7c",caipNetworkId:"bip122:00000008819873e925422c1ff0f99f7c",chainNamespace:"bip122",name:"Bitcoin Signet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const hederaNamespace="hedera",HederaChainDefinition={Native:{Mainnet:defineChain({id:"mainnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:mainnet",name:"Hedera Mainnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/mainnet"}},testnet:!1}),Testnet:defineChain({id:"testnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:testnet",name:"Hedera Testnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})},EVM:{Mainnet:defineChain({id:295,name:"Hedera Mainnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:295",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!1}),Testnet:defineChain({id:296,name:"Hedera Testnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:296",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})}};function createNamespaces(Fs){return Fs.reduce((Ps,Hs)=>{const{id:Ws,chainNamespace:Zs,rpcUrls:zs}=Hs,Ys=zs.default.http[0],Va=Zs=="hedera"?Object.values(HederaJsonRpcMethod):WcHelpersUtil.getMethodsByChainNamespace(Zs);Ps[Zs]||(Ps[Zs]={methods:Va,events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}});const Xs=`${Zs}:${Ws}`,Ma=Ps[Zs];return Ma.chains.push(Xs),Ma?.rpcMap&&Ys&&(Ma.rpcMap[Ws]=Ys),Ps},{})}function getChainsFromApprovedSession(Fs){return Fs.map(Ps=>`${Ps.split(":")[0]}:${Ps.split(":")[1]}`)}function getChainId(Fs){return Fs.includes(":")?Fs.split(":")[1]:Fs}function mergeRequiredOptionalNamespaces(Fs={},Ps={}){const Hs=xe(Fs),Ws=xe(Ps);return merge(Hs,Ws)}function merge(Fs,Ps){var Hs,Ws,Zs;const zs=Object.assign({},Fs);for(const[Ys,Va]of Object.entries(Ps))zs[Ys]?zs[Ys]=Object.assign(Object.assign(Object.assign({},zs[Ys]),Va),{chains:ut$3(Va.chains,(Hs=zs[Ys])===null||Hs===void 0?void 0:Hs.chains),methods:ut$3(Va.methods||[],((Ws=zs[Ys])===null||Ws===void 0?void 0:Ws.methods)||[]),events:ut$3(Va.events||[],((Zs=zs[Ys])===null||Zs===void 0?void 0:Zs.events)||[])}):zs[Ys]=Va;return zs}const RPC_URL="https://rpc.walletconnect.org/v1/",BUNDLER_URL=`${RPC_URL}bundler`;var Eip155JsonRpcMethod;(function(Fs){Fs.PersonalSign="personal_sign",Fs.Sign="eth_sign",Fs.SignTransaction="eth_signTransaction",Fs.SignTypedData="eth_signTypedData",Fs.SignTypedDataV3="eth_signTypedData_v3",Fs.SignTypedDataV4="eth_signTypedData_v4",Fs.SendRawTransaction="eth_sendRawTransaction",Fs.SendTransaction="eth_sendTransaction"})(Eip155JsonRpcMethod||(Eip155JsonRpcMethod={}));const logger=createLogger("AccountUtils");async function getAccountBalance(Fs,Ps){const Hs=Fs===r$y.TESTNET?a$u.forTestnet():a$u.forMainnet();let Ws;try{Ws=y$f.fromString(Ps)}catch{if(Ps.startsWith("0x"))try{Ws=y$f.fromEvmAddress(0,0,Ps),Ws.num.isZero()&&Ws.evmAddress!=null&&await Ws.populateAccountNum(Hs)}catch{return logger.debug("No Hedera account found for EVM address:",Ps),null}else return logger.debug("Invalid address format:",Ps),null}try{return await new e$x().setAccountId(Ws).execute(Hs)}catch(Zs){return logger.debug("Failed to get account balance:",Zs),null}}class HederaConnector{constructor({provider:Ps,caipNetworks:Hs,namespace:Ws}){this.id=ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT,this.name=PresetsUtil.ConnectorNamesMap[ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=PresetsUtil.ConnectorImageIds[ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=Hs,this.provider=Ps,this.chain=Ws}get chains(){return this.caipNetworks}async connectWalletConnect(){const Hs={optionalNamespaces:createNamespaces(this.caipNetworks)};return await this.provider.connect(Hs),{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){return!1}}class HederaAdapter extends AdapterBlueprint{constructor(Ps){var Hs,Ws;if(Ps.namespace!==hederaNamespace&&Ps.namespace!=="eip155")throw new Error('Namespace must be "hedera" or "eip155"');if(Ps.namespace=="eip155"){if(!((Hs=Ps.networks)===null||Hs===void 0)&&Hs.some(Zs=>Zs.chainNamespace!="eip155"))throw new Error("Invalid networks for eip155 namespace")}else if(!((Ws=Ps.networks)===null||Ws===void 0)&&Ws.some(Zs=>Zs.chainNamespace!=hederaNamespace))throw new Error("Invalid networks for hedera namespace");super(Object.assign({},Ps)),this.logger=createLogger("HederaAdapter"),this.getCaipNetworks=Zs=>{const zs=Zs||this.namespace;return zs==="eip155"?[HederaChainDefinition.EVM.Mainnet,HederaChainDefinition.EVM.Testnet]:zs===hederaNamespace?[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet]:[HederaChainDefinition.EVM.Mainnet,HederaChainDefinition.EVM.Testnet,HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet]}}async setUniversalProvider(Ps){this.addConnector(new HederaConnector({provider:Ps,caipNetworks:this.getCaipNetworks()||[],namespace:this.namespace}))}async connect(Ps){this.logger.debug("connect called with params:",Ps);const Hs=this.getWalletConnectConnector();return Hs&&"connectWalletConnect"in Hs?(this.logger.debug("Calling HederaConnector.connectWalletConnect"),await Hs.connectWalletConnect()):this.logger.warn("HederaConnector not found or connectWalletConnect method missing"),Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(Ps.chainId),provider:this.provider,address:""})}async disconnect(Ps){try{await this.getWalletConnectConnector().disconnect()}catch(Hs){this.logger.warn("disconnect - error",Hs)}return{connections:[]}}async getAccounts({namespace:Ps}){var Hs,Ws,Zs,zs;const Ys=this.provider,Va=((zs=(Zs=(Ws=(Hs=Ys?.session)===null||Hs===void 0?void 0:Hs.namespaces)===null||Ws===void 0?void 0:Ws[Ps])===null||Zs===void 0?void 0:Zs.accounts)===null||zs===void 0?void 0:zs.map(Xs=>{const[,,Ma]=Xs.split(":");return Ma}).filter((Xs,Ma,qs)=>qs.indexOf(Xs)===Ma))||[];return Promise.resolve({accounts:Va.map(Xs=>CoreHelperUtil.createAccount(Ps,Xs,"eoa"))})}async syncConnectors(){return Promise.resolve()}async syncConnections(Ps){return Promise.resolve()}async getBalance(Ps){const{address:Hs,caipNetwork:Ws}=Ps;if(!Ws)return Promise.resolve({balance:"0",decimals:0,symbol:""});const Zs=await getAccountBalance(Ws.testnet?r$y.TESTNET:r$y.MAINNET,Hs);return Promise.resolve({balance:Zs?formatUnits(Zs.hbars.toTinybars().toString(),8).toString():"0",decimals:Ws.nativeCurrency.decimals,symbol:Ws.nativeCurrency.symbol})}async signMessage(Ps){const{provider:Hs,message:Ws,address:Zs}=Ps;if(!Hs)throw new Error("Provider is undefined");const zs=Hs;let Ys="";return this.namespace===hederaNamespace?Ys=(await zs.hedera_signMessage({signerAccountId:Zs,message:Ws})).signatureMap:Ys=await zs.eth_signMessage(Ws,Zs),{signature:Ys}}async estimateGas(Ps){const{provider:Hs,caipNetwork:Ws,address:Zs}=Ps;if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");if(!Hs)throw new Error("Provider is undefined");return{gas:await Hs.eth_estimateGas({data:Ps.data,to:Ps.to,address:Zs},Zs,Number(Ws?.id))}}async sendTransaction(Ps){var Hs;if(!Ps.provider)throw new Error("Provider is undefined");const Ws=Ps.provider;if(this.namespace=="eip155")return{hash:await Ws.eth_sendTransaction({value:Ps.value,to:Ps.to,data:Ps.data,gas:Ps.gas,gasPrice:Ps.gasPrice,address:Ps.address},Ps.address,Number((Hs=Ps.caipNetwork)===null||Hs===void 0?void 0:Hs.id))};throw new Error("Namespace is not eip155")}async writeContract(Ps){if(!Ps.provider)throw new Error("Provider is undefined");if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const{provider:Hs,caipNetwork:Ws,caipAddress:Zs,abi:zs,tokenAddress:Ys,method:Va,args:Xs}=Ps,Ma=new BrowserProvider(Hs,Number(Ws?.id)),qs=new JsonRpcSigner(Ma,Zs),Js=new Contract(Ys,zs,qs);if(!Js||!Va)throw new Error("Contract method is undefined");const Mc=Js[Va];if(Mc)return{hash:await Mc(...Xs)};throw new Error("Contract method is undefined")}async getEnsAddress(Ps){if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const{name:Hs,caipNetwork:Ws}=Ps;return Ws&&isReownName(Hs)?{address:await WcHelpersUtil.resolveReownName(Hs)||!1}:{address:!1}}parseUnits(Ps){return parseUnits$1(Ps.value,Ps.decimals)}formatUnits(Ps){return formatUnits(Ps.value,Ps.decimals)}async getCapabilities(Ps){var Hs,Ws;if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const Zs=this.provider;if(!Zs)throw new Error("Provider is undefined");const zs=(Ws=(Hs=Zs.session)===null||Hs===void 0?void 0:Hs.sessionProperties)===null||Ws===void 0?void 0:Ws.capabilities;if(zs)try{const Va=JSON.parse(zs)[Ps];if(Va)return Va}catch{throw new Error("Error parsing wallet capabilities")}return await Zs.request({method:"wallet_getCapabilities",params:[Ps]})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(Ps){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Ps.chainId,provider:this.provider,address:""})}async switchNetwork(Ps){const{caipNetwork:Hs}=Ps;this.getWalletConnectConnector().provider.setDefaultChain(Hs.caipNetworkId)}getWalletConnectConnector(){const Ps=this.connectors.find(Hs=>Hs.type=="WALLET_CONNECT");if(!Ps)throw new Error("WalletConnectConnector not found");return Ps}getWalletConnectProvider(){const Ps=this.connectors.find(Ws=>Ws.type==="WALLET_CONNECT");return Ps?.provider}async walletGetAssets(Ps){return Promise.resolve({})}}class HIP820Provider{constructor(Ps){this.namespace=Ps.namespace,this.chainId=this.getDefaultChain(),this.events=Ps.events,this.client=Ps.client}get httpProviders(){return{}}updateNamespace(Ps){this.namespace=Object.assign(this.namespace,Ps)}request(Ps){return this.getSigner(Ps.topic).request({method:Ps.request.method,params:Ps.request.params})}async signTransaction(Ps,Hs){return this.getSigner(Hs).signTransaction(Ps)}requestAccounts(){const Ps=this.namespace.accounts;return Ps?Array.from(new Set(Ps.filter(Hs=>Hs.split(":")[1]===this.chainId.toString()).map(Hs=>Hs.split(":")[2]))):[]}setDefaultChain(Ps){this.chainId=Ps,this.namespace.defaultChain=Ps}getDefaultChain(){return this.chainId?this.chainId:this.namespace.defaultChain?this.namespace.defaultChain:(this.namespace.chains[0]||"hedera:mainnet").split(":")[1]}getSigner(Ps){return this.getSigners(Ps)[0]}getSigners(Ps){var Hs;const Ws=(Hs=this.namespace.accounts)===null||Hs===void 0?void 0:Hs.map(Zs=>{const[zs,Ys,Va]=Zs.split(":");return{ledgerId:CAIPChainIdToLedgerId(`${zs}:${Ys}`),accountId:y$f.fromString(Va)}});if(!Ws)throw new Error("Accounts not found");return Ws.map(({accountId:Zs,ledgerId:zs})=>new DAppSigner(Zs,this.client,Ps,zs))}}class EIP155Provider{constructor({client:Ps,events:Hs,namespace:Ws}){this.name="eip155",this.logger=createLogger("EIP155Provider"),this.namespace=Ws,this.events=Hs,this.client=Ps,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(Ps){switch(Ps.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.switchChain(Ps);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCallsStatus":return await this.getCallStatus(Ps)}return this.namespace.methods.includes(Ps.request.method)?await this.client.request(Ps):this.getHttpProvider().request(Ps.request)}updateNamespace(Ps){this.namespace=Object.assign(this.namespace,Ps)}setDefaultChain(Ps,Hs){this.httpProviders[Ps]||this.setHttpProvider(parseInt(Ps),Hs),this.chainId=parseInt(Ps),this.events.emit("default_chain_changed",`${this.name}:${Ps}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){return this.chainId?this.chainId.toString():this.namespace.defaultChain?this.namespace.defaultChain:(this.namespace.chains[0]||"eip155:295").split(":")[1]}createHttpProvider(Ps,Hs){if(!Ps)return;const{Testnet:Ws,Mainnet:Zs}=HederaChainDefinition.EVM,zs=[Zs,Ws].find(Xs=>Xs.id==Ps),Ys=zs?.rpcUrls.default.http[0]||Hs;if(!Ys)throw new Error(`No RPC url provided for chainId: ${Ps}`);return new o$B(new f$o(Ys,!1))}setHttpProvider(Ps,Hs){const Ws=this.createHttpProvider(Ps,Hs);Ws&&(this.httpProviders[Ps]=Ws)}createHttpProviders(){const Ps={};return this.namespace.chains.forEach(Hs=>{var Ws;const Zs=parseInt(getChainId(Hs));Ps[Zs]=this.createHttpProvider(Zs,(Ws=this.namespace.rpcMap)===null||Ws===void 0?void 0:Ws[Hs])}),Ps}getAccounts(){const Ps=this.namespace.accounts;return Ps?Array.from(new Set(Ps.filter(Hs=>Hs.split(":")[1]===this.chainId.toString()).map(Hs=>Hs.split(":")[2]))):[]}getHttpProvider(){const Ps=this.chainId,Hs=this.httpProviders[Ps];if(typeof Hs>"u")throw new Error(`JSON-RPC provider for ${Ps} not found`);return Hs}async switchChain(Ps){var Hs,Ws;let Zs=Ps.request.params?(Hs=Ps.request.params[0])===null||Hs===void 0?void 0:Hs.chainId:"0x0";Zs=Zs.startsWith("0x")?Zs:`0x${Zs}`;const zs=parseInt(Zs,16);if(this.isChainApproved(zs))this.setDefaultChain(`${zs}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:Ps.topic,request:{method:Ps.request.method,params:[{chainId:Zs}]},chainId:(Ws=this.namespace.chains)===null||Ws===void 0?void 0:Ws[0]}),this.setDefaultChain(`${zs}`);else throw new Error(`Failed to switch to chain 'eip155:${zs}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(Ps){return this.namespace.chains.includes(`${this.name}:${Ps}`)}async getCallStatus(Ps){var Hs,Ws;const Zs=this.client.session.get(Ps.topic),zs=(Hs=Zs.sessionProperties)===null||Hs===void 0?void 0:Hs.bundler_name;if(zs){const Va=this.getBundlerUrl(Ps.chainId,zs);try{return await this.getUserOperationReceipt(Va,Ps)}catch(Xs){this.logger.warn("Failed to fetch call status from bundler",Xs,Va)}}const Ys=(Ws=Zs.sessionProperties)===null||Ws===void 0?void 0:Ws.bundler_url;if(Ys)try{return await this.getUserOperationReceipt(Ys,Ps)}catch(Va){this.logger.warn("Failed to fetch call status from custom bundler",Va,Ys)}if(this.namespace.methods.includes(Ps.request.method))return await this.client.request(Ps);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(Ps,Hs){var Ws,Zs;const zs=new URL(Ps),Ys=await fetch(zs,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formatJsonRpcRequest("eth_getUserOperationReceipt",[(Zs=(Ws=Hs.request)===null||Ws===void 0?void 0:Ws.params)===null||Zs===void 0?void 0:Zs[0]]))});if(!Ys.ok)throw new Error(`Failed to fetch user operation receipt - ${Ys.status}`);return await Ys.json()}getBundlerUrl(Ps,Hs){return`${BUNDLER_URL}?projectId=${this.client.core.projectId}&chainId=${Ps}&bundler=${Hs}`}}class HederaProvider extends N$4{constructor(Ps){super(Ps),this.hederaLogger=createLogger("HederaProvider")}static async init(Ps){var Hs,Ws;const Zs=new HederaProvider(Ps);return await Zs.initialize(),Zs.namespaces=Object.assign(Object.assign({},((Hs=Zs.providerOpts)===null||Hs===void 0?void 0:Hs.optionalNamespaces)||{}),((Ws=Zs.providerOpts)===null||Ws===void 0?void 0:Ws.requiredNamespaces)||{}),Zs.session&&Zs.initProviders(),Zs}emit(Ps,Hs){this.events.emit(Ps,Hs)}getAccountAddresses(){if(!this.session)throw new Error("Not initialized. Please call connect()");return Object.values(this.session.namespaces).flatMap(Ps=>{var Hs;return(Hs=Ps.accounts.map(Ws=>Ws.split(":")[2]))!==null&&Hs!==void 0?Hs:[]})}async request(Ps,Hs,Ws){var Zs,zs,Ys,Va,Xs;if(!this.session||!this.namespaces)throw new Error("Please call connect() before request()");let Ma=Hs;if(Object.values(HederaJsonRpcMethod).includes(Ps.method)){if(!this.nativeProvider)throw new Error("nativeProvider not initialized. Please call connect()");return Ma=Ma??((Zs=this.namespaces.hedera)===null||Zs===void 0?void 0:Zs.chains[0]),(zs=this.nativeProvider)===null||zs===void 0?void 0:zs.request({request:Object.assign({},Ps),chainId:Ma,topic:this.session.topic,expiry:Ws})}else{if(!this.eip155Provider)throw new Error("eip155Provider not initialized");return Ma=Ma??((Va=(Ys=this.namespaces)===null||Ys===void 0?void 0:Ys.eip155)===null||Va===void 0?void 0:Va.chains[0]),(Xs=this.eip155Provider)===null||Xs===void 0?void 0:Xs.request({request:Object.assign({},Ps),chainId:Ma,topic:this.session.topic,expiry:Ws})}}async hedera_getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async hedera_executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async hedera_signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async hedera_signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async hedera_signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async hedera_signTransaction(Ps){var Hs,Ws,Zs;if(!this.session)throw new Error("Session not initialized. Please call connect()");if(!this.nativeProvider)throw new Error("nativeProvider not initialized. Please call connect()");if(!(Ps?.transactionBody instanceof L$a))throw new Error("Transaction sent in incorrect format. Ensure transaction body is a Transaction object.");const zs=(Ws=(Hs=Ps?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Ws===void 0?void 0:Ws.pop();if(!((Zs=this.nativeProvider)===null||Zs===void 0?void 0:Zs.requestAccounts().includes(zs??"")))throw new Error(`Signer not found for account ${zs}`);return await this.nativeProvider.signTransaction(Ps.transactionBody,this.session.topic)}async eth_signMessage(Ps,Hs){const Ws=isHexString(Ps)?Ps:hexlify(toUtf8Bytes(Ps));return await this.request({method:"personal_sign",params:[Ws,Hs]})}async eth_estimateGas(Ps,Hs,Ws){if(!Hs)throw new Error("estimateGas - address is undefined");if(Ps.chainNamespace!=="eip155")throw new Error("estimateGas - chainNamespace is not eip155");const Zs={from:Ps.address,to:Ps.to,data:Ps.data,type:0},zs=new BrowserProvider(this,Ws);return await new JsonRpcSigner(zs,Hs).estimateGas(Zs)}async eth_sendTransaction(Ps,Hs,Ws){if(!Hs)throw new Error("sendTransaction - address is undefined");if(Ps.chainNamespace!=="eip155")throw new Error("sendTransaction - chainNamespace is not eip155");const Zs={to:Ps.to,value:Ps.value,gasLimit:Ps.gas,gasPrice:Ps.gasPrice,data:Ps.data,type:0},zs=new BrowserProvider(this,Ws),Xs=await(await new JsonRpcSigner(zs,Hs).sendTransaction(Zs)).wait();return Xs?.hash||null}async eth_writeContract(Ps,Hs,Ws){if(!Hs)throw new Error("writeContract - address is undefined");const Zs=new BrowserProvider(this,Ws),zs=new JsonRpcSigner(Zs,Hs),Ys=new Contract(Ps.tokenAddress,Ps.abi,zs);if(!Ys||!Ps.method)throw new Error("Contract method is undefined");const Va=Ys[Ps.method];if(Va)return await Va(...Ps.args);throw new Error("Contract method is undefined")}async eth_blockNumber(){return this.request({method:"eth_blockNumber",params:[]})}async eth_call(Ps,Hs="latest"){return this.request({method:"eth_call",params:[Ps,Hs]})}async eth_feeHistory(Ps,Hs,Ws){return this.request({method:"eth_feeHistory",params:[toQuantity(Ps),Hs,Ws]})}async eth_gasPrice(){return this.request({method:"eth_gasPrice",params:[]})}async eth_getBlockByHash(Ps,Hs=!1){return this.request({method:"eth_getBlockByHash",params:[Ps,Hs]})}async eth_getBlockByNumber(Ps,Hs=!1){return this.request({method:"eth_getBlockByNumber",params:[Ps,Hs]})}async eth_getBlockTransactionCountByHash(Ps){return this.request({method:"eth_getBlockTransactionCountByHash",params:[Ps]})}async eth_getBlockTransactionCountByNumber(Ps){return this.request({method:"eth_getBlockTransactionCountByNumber",params:[Ps]})}async eth_getCode(Ps,Hs="latest"){return this.request({method:"eth_getCode",params:[Ps,Hs]})}async eth_getFilterLogs(Ps){return this.request({method:"eth_getFilterLogs",params:[Ps]})}async eth_getFilterChanges(Ps){return this.request({method:"eth_getFilterChanges",params:[Ps]})}async eth_getLogs(Ps){return this.request({method:"eth_getLogs",params:[Ps]})}async eth_getStorageAt(Ps,Hs,Ws="latest"){return this.request({method:"eth_getStorageAt",params:[Ps,Hs,Ws]})}async eth_getTransactionByBlockHashAndIndex(Ps,Hs){return await this.request({method:"eth_getTransactionByBlockHashAndIndex",params:[Ps,Hs]})}async eth_getTransactionByBlockNumberAndIndex(Ps,Hs){return this.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[Ps,Hs]})}async eth_getTransactionByHash(Ps){return this.request({method:"eth_getTransactionByHash",params:[Ps]})}async eth_getTransactionCount(Ps,Hs="latest"){return this.request({method:"eth_getTransactionCount",params:[Ps,Hs]})}async eth_getTransactionReceipt(Ps){return this.request({method:"eth_getTransactionReceipt",params:[Ps]})}async eth_hashrate(){return this.request({method:"eth_hashrate",params:[]})}async eth_maxPriorityFeePerGas(){return this.request({method:"eth_maxPriorityFeePerGas",params:[]})}async eth_mining(){return this.request({method:"eth_mining",params:[]})}async eth_newBlockFilter(){return this.request({method:"eth_newBlockFilter",params:[]})}async eth_newFilter(Ps){return this.request({method:"eth_newFilter",params:[Ps]})}async eth_submitWork(Ps){return this.request({method:"eth_submitWork",params:Ps})}async eth_syncing(){return this.request({method:"eth_syncing",params:[]})}async eth_uninstallFilter(Ps){return this.request({method:"eth_uninstallFilter",params:[Ps]})}async net_listening(){return this.request({method:"net_listening",params:[]})}async net_version(){return this.request({method:"net_version",params:[]})}async web3_clientVersion(){return this.request({method:"web3_clientVersion",params:[]})}async eth_chainId(){return this.request({method:"eth_chainId",params:[]})}async connect(Ps){this.hederaLogger.debug("connect called with params:",Ps),Ps&&(Ps.requiredNamespaces&&(this.hederaLogger.debug("Setting requiredNamespaces:",Ps.requiredNamespaces),this.requiredNamespaces=Ps.requiredNamespaces),Ps.optionalNamespaces&&(this.hederaLogger.debug("Setting optionalNamespaces:",Ps.requiredNamespaces),this.optionalNamespaces=Ps.optionalNamespaces),Ps.namespaces&&(this.hederaLogger.debug("Setting namespaces:",Ps.namespaces),this.namespaces=Ps.namespaces)),this.hederaLogger.debug("Calling super.connect with params");let Hs;try{Hs=await super.connect(Ps)}catch(Ws){throw this.hederaLogger.error("Error in super.connect:",Ws),Ws}return this.hederaLogger.info("super.connect completed successfully"),this.hederaLogger.debug("Result from super.connect:",Hs),this.initProviders(),Hs}async pair(Ps){console.log(Ps),console.log(this.requiredNamespaces);const Hs=await super.pair(Ps);return this.initProviders(),Hs}initProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session||!this.namespaces)return{};const Ps=Object.keys(this.namespaces),Hs={};return Ps.forEach(Ws=>{var Zs,zs,Ys,Va;const Xs=((zs=(Zs=this.session)===null||Zs===void 0?void 0:Zs.namespaces[Ws])===null||zs===void 0?void 0:zs.accounts)||[],Ma=getChainsFromApprovedSession(Xs),qs=mergeRequiredOptionalNamespaces(this.namespaces,this.optionalNamespaces),Js=Object.assign(Object.assign(Object.assign({},qs[Ws]),{accounts:Xs,chains:Ma}),((Va=(Ys=this.optionalNamespaces)===null||Ys===void 0?void 0:Ys[Ws])===null||Va===void 0?void 0:Va.rpcMap)&&{rpcMap:this.optionalNamespaces[Ws].rpcMap});switch(Ws){case"hedera":{const Mc=new HIP820Provider({namespace:Js,events:this.events,client:this.client});this.nativeProvider=Mc,Hs[Ws]=Mc;break}case"eip155":{const Mc=new EIP155Provider({namespace:Js,events:this.events,client:this.client});this.eip155Provider=Mc,Hs[Ws]=Mc;break}default:throw new Error(`Unsupported namespace: ${Ws}`)}}),Hs}get rpcProviders(){return!this.nativeProvider&&!this.eip155Provider?this.initProviders():{hedera:this.nativeProvider,eip155:this.eip155Provider}}set rpcProviders(Ps){}}const LEVEL_ORDER={error:0,warn:1,info:2,debug:3};class Logger{constructor(){this.level="info"}setLogLevel(Ps){this.level=Ps}error(Ps,...Hs){this.shouldLog("error")&&console.error(Ps,...Hs)}warn(Ps,...Hs){this.shouldLog("warn")&&console.warn(Ps,...Hs)}info(Ps,...Hs){this.shouldLog("info")&&console.info(Ps,...Hs)}debug(Ps,...Hs){this.shouldLog("debug")&&console.debug(Ps,...Hs)}shouldLog(Ps){return LEVEL_ORDER[Ps]<=LEVEL_ORDER[this.level]}}var fetchRetry_umd$1={exports:{}},fetchRetry_umd=fetchRetry_umd$1.exports,hasRequiredFetchRetry_umd;function requireFetchRetry_umd(){return hasRequiredFetchRetry_umd||(hasRequiredFetchRetry_umd=1,(function(Fs,Ps){(function(Hs,Ws){Fs.exports=Ws()})(fetchRetry_umd,(function(){var Hs=function(zs,Ys){if(Ys=Ys||{},typeof zs!="function")throw new Zs("fetch must be a function");if(typeof Ys!="object")throw new Zs("defaults must be an object");if(Ys.retries!==void 0&&!Ws(Ys.retries))throw new Zs("retries must be a positive integer");if(Ys.retryDelay!==void 0&&!Ws(Ys.retryDelay)&&typeof Ys.retryDelay!="function")throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(Ys.retryOn!==void 0&&!Array.isArray(Ys.retryOn)&&typeof Ys.retryOn!="function")throw new Zs("retryOn property expects an array or function");var Va={retries:3,retryDelay:1e3,retryOn:[]};return Ys=Object.assign(Va,Ys),function(Ma,qs){var Js=Ys.retries,Mc=Ys.retryDelay,ol=Ys.retryOn;if(qs&&qs.retries!==void 0)if(Ws(qs.retries))Js=qs.retries;else throw new Zs("retries must be a positive integer");if(qs&&qs.retryDelay!==void 0)if(Ws(qs.retryDelay)||typeof qs.retryDelay=="function")Mc=qs.retryDelay;else throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(qs&&qs.retryOn)if(Array.isArray(qs.retryOn)||typeof qs.retryOn=="function")ol=qs.retryOn;else throw new Zs("retryOn property expects an array or function");return new Promise(function(Vc,Dc){var sl=function(hl){var pl=typeof Request<"u"&&Ma instanceof Request?Ma.clone():Ma;zs(pl,qs).then(function(gl){if(Array.isArray(ol)&&ol.indexOf(gl.status)===-1)Vc(gl);else if(typeof ol=="function")try{return Promise.resolve(ol(hl,null,gl)).then(function(yl){yl?ll(hl,null,gl):Vc(gl)}).catch(Dc)}catch(yl){Dc(yl)}else hl<Js?ll(hl,null,gl):Vc(gl)}).catch(function(gl){if(typeof ol=="function")try{Promise.resolve(ol(hl,gl,null)).then(function(yl){yl?ll(hl,gl,null):Dc(gl)}).catch(function(yl){Dc(yl)})}catch(yl){Dc(yl)}else hl<Js?ll(hl,gl,null):Dc(gl)})};function ll(hl,pl,gl){var yl=typeof Mc=="function"?Mc(hl,pl,gl):Mc;setTimeout(function(){sl(++hl)},yl)}sl(0)})}};function Ws(zs){return Number.isInteger(zs)&&zs>=0}function Zs(zs){this.name="ArgumentError",this.message=zs}return Hs}))})(fetchRetry_umd$1)),fetchRetry_umd$1.exports}var fetchRetry_umdExports=requireFetchRetry_umd();const retryFetch=getDefaultExportFromCjs$1(fetchRetry_umdExports),fetchWithRetry=()=>retryFetch(fetch,{retries:3});var Name=(Fs=>(Fs.Contractcall="CONTRACTCALL",Fs.Cryptotransfer="CRYPTOTRANSFER",Fs))(Name||{}),Result=(Fs=>(Fs.Success="SUCCESS",Fs))(Result||{});function ensureGlobalHTMLElement(){typeof globalThis>"u"||typeof globalThis.HTMLElement>"u"&&(globalThis.HTMLElement=class{})}ensureGlobalHTMLElement();const HASH_PACK_WALLET_ID="a29498d225fa4b13468ff4d6cf4ae0ea4adcbd95f07ce8a843a1dee10b632f3f",Nd=class Nd{constructor(Ps,Hs){this.reownAppKit=null,this.reownAppKitKey=null,this.extensionCheckInterval=null,this.hasCalledExtensionCallback=!1,this.logger=Ps||new Logger,this.network=Hs||r$y.MAINNET}get dAppConnector(){return Nd.dAppConnectorInstance}static getInstance(Ps,Hs){let Ws=Nd?.instance;return Ws||(Nd.instance=new Nd(Ps,Hs),Ws=Nd.instance,Nd.proxyInstance=null),Hs&&Ws.setNetwork(Hs),Nd.proxyInstance||(Nd.proxyInstance=new Proxy(Ws,{get(Zs,zs,Ys){const Va=Reflect.get(Zs,zs,Ys);return typeof Va=="function"?Va.bind(Zs):Va}})),Nd.proxyInstance}setLogger(Ps){this.logger=Ps}setNetwork(Ps){this.network=Ps}getNetwork(){return this.network}setReownAppKit(Ps){this.reownAppKit=Ps}async ensureReownAppKit(Ps,Hs,Ws){if(typeof window>"u")return;const Zs=`${Ps}:${Ws.toString()}`;if(!(this.reownAppKit&&this.reownAppKitKey===Zs))try{let zs=HederaChainDefinition.Native.Mainnet;Ws.toString()==="testnet"&&(zs=HederaChainDefinition.Native.Testnet);const Ys=new HederaAdapter({projectId:Ps,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],namespace:hederaNamespace}),Va=await HederaProvider.init({projectId:Ps,metadata:Hs});this.reownAppKit=createAppKit({adapters:[Ys],universalProvider:Va,projectId:Ps,metadata:Hs,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],defaultNetwork:zs,enableWalletGuide:!1,enableWallets:!0,featuredWalletIds:[HASH_PACK_WALLET_ID]}),this.reownAppKitKey=Zs}catch(zs){this.logger.warn("Failed to initialize Reown AppKit",zs),this.reownAppKit=null,this.reownAppKitKey=null}}setLogLevel(Ps){this.logger instanceof Logger&&this.logger.setLogLevel(Ps)}async init(Ps,Hs,Ws,Zs){const zs=Ws||this.network,Ys=zs.toString()==="mainnet";return Nd.dAppConnectorInstance||(Nd.dAppConnectorInstance=new DAppConnector(Hs,zs,Ps,Object.values(HederaJsonRpcMethod),[HederaSessionEvent.ChainChanged,HederaSessionEvent.AccountsChanged],[Ys?HederaChainId.Mainnet:HederaChainId.Testnet],"debug"),await Nd.dAppConnectorInstance.init({logger:"error"}),await this.ensureReownAppKit(Ps,Hs,zs),Nd.dAppConnectorInstance.onSessionIframeCreated=Va=>{this.logger.info("new session from from iframe",Va),this.handleNewSession(Va),Zs&&Zs(Va)},this.logger.info(`Hedera Wallet Connect SDK initialized on ${zs}`)),Nd.dAppConnectorInstance}async connect(Ps){this.ensureInitialized();const Hs=Ps?.pairingTopic,Ws=this.reownAppKit;if(Ws){const zs=await this.connectUsingReownAppKit(Ws,Hs);return this.handleNewSession(zs),zs}const Zs=await this.dAppConnector.openModal(Hs);return this.handleNewSession(Zs),Zs}async connectUsingReownAppKit(Ps,Hs){if(this.ensureInitialized(),!Ps)throw new Error("AppKit instance is required.");try{return await this.dAppConnector.connect(Ws=>{Ps.open({view:"ConnectingWalletConnectBasic",uri:Ws}).catch(Zs=>{this.logger.error("Failed to open Reown AppKit modal",Zs)})},Hs)}finally{try{await Ps.close()}catch(Ws){this.logger.warn("Failed to close Reown AppKit modal",Ws)}}}async disconnect(){try{this.ensureInitialized();const Ps=this.getAccountInfo(),Hs=Ps?.accountId,Ws=Ps?.network,Zs=this?.dAppConnector?.signers.find(zs=>zs.getAccountId().toString()===Hs);return await this.dAppConnector?.disconnect(Zs?.topic),this.logger.info(`Disconnected from ${Hs} on ${Ws}`),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async disconnectAll(){try{return this.ensureInitialized(),await this.dAppConnector?.disconnectAll(),this.logger.info("Disconnected from all wallets"),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async executeTransaction(Ps,Hs=!1){this.ensureInitialized();const Zs=this.getAccountInfo()?.accountId,zs=this.dAppConnector.signers.find(Ys=>Ys.getAccountId().toString()===Zs);if(!zs)throw new Error("No signer available. Please ensure wallet is connected.");try{return Hs?await(await Ps.executeWithSigner(zs)).getReceiptWithSigner(zs):await(await(await Ps.freezeWithSigner(zs)).executeWithSigner(zs)).getReceiptWithSigner(zs)}catch(Ys){throw(Ys.message??"").toLowerCase().includes("nodeaccountid")?new Error("Transaction execution failed because nodeAccountId is not set. Set node account IDs on the transaction before calling executeTransaction."):Ys}}async executeTransactionWithErrorHandling(Ps,Hs){try{return{result:await this.executeTransaction(Ps,Hs),error:void 0}}catch(Ws){const zs=Ws.message?.toLowerCase();if(this.logger.error("Failed to execute transaction",Ws),this.logger.error("Failure reason for transaction is",zs),zs.includes("insufficient payer balance"))return{result:void 0,error:"Insufficient balance to complete the transaction."};if(zs.includes("reject"))return{result:void 0,error:"You rejected the transaction"};if(zs.includes("invalid signature"))return{result:void 0,error:"Invalid signature. Please check your account and try again."};if(zs.includes("transaction expired"))return{result:void 0,error:"Transaction expired. Please try again."};if(zs.includes("account not found"))return{result:void 0,error:"Account not found. Please check the account ID and try again."};if(zs.includes("unauthorized"))return{result:void 0,error:"Unauthorized. You may not have the necessary permissions for this action."};if(zs.includes("busy"))return{result:void 0,error:"The network is busy. Please try again later."};if(zs.includes("invalid transaction"))return{result:void 0,error:"Invalid transaction. Please check your inputs and try again."}}}async submitMessageToTopic(Ps,Hs,Ws){this.ensureInitialized();let Zs=new u$u().setTopicId(d$s.fromString(Ps)).setMessage(Hs);return Ws&&(Zs=await Zs.sign(Ws)),this.executeTransaction(Zs)}async transferHbar(Ps,Hs,Ws){this.ensureInitialized();const Zs=new T$a().setTransactionId(i$s.generate(Ps)).addHbarTransfer(y$f.fromString(Ps),new e$F(-Ws)).addHbarTransfer(y$f.fromString(Hs),new e$F(Ws));return this.executeTransaction(Zs)}async executeSmartContract(Ps,Hs,Ws,Zs=1e5){this.ensureInitialized();const zs=new i$o().setContractId(g$p.fromString(Ps)).setGas(Zs).setFunction(Hs,Ws);return this.executeTransaction(zs)}handleNewSession(Ps){const Ws=Ps.namespaces?.hedera?.accounts?.[0]?.split(":"),Zs=Ws.pop(),zs=Ws.pop();if(this.logger.info("sessionAccount is",Zs,zs),Zs)this.saveConnectionInfo(Zs,zs);else{this.logger.error("No account id found in the session");return}}getNetworkPrefix(){const Hs=this.getAccountInfo()?.network;if(!Hs){this.logger.warn("Network is not set on SDK, defaulting.");const Ws=localStorage.getItem("connectedNetwork");return Ws||"mainnet-public"}return Hs!==this.network&&(this.logger.warn("Detected network mismatch, reverting to signer network",Hs),this.network=Hs),Hs.isMainnet()?"mainnet-public":"testnet"}async requestAccount(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/accounts/${Ps}`,Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to make request to mirror node for account: ${Zs.status}`);return await Zs.json()}catch(Hs){throw this.logger.error("Failed to fetch account",Hs),Hs}}async getAccountBalance(){this.ensureInitialized();const Hs=this.getAccountInfo()?.accountId;if(!Hs)return null;const Ws=await this.requestAccount(Hs);if(!Ws)throw new Error("Failed to fetch account. Try again or check if the Account ID is valid.");const Zs=Ws.balance.balance/10**8;return Number(Zs).toLocaleString("en-US")}getAccountInfo(){const{accountId:Ps}=this.loadConnectionInfo();if(!Ps||!this?.dAppConnector?.signers?.length)return null;const Ws=this.dAppConnector.signers.find(Ys=>Ys.getAccountId().toString()===Ps);if(!Ws)return null;const Zs=Ws?.getAccountId()?.toString();if(!Zs)return null;const zs=Ws.getLedgerId();return{accountId:Zs,network:zs}}async createTopic(Ps,Hs,Ws){this.ensureInitialized();let Zs=new c$w().setTopicMemo(Ps||"");if(Hs){const Ys=g$q.fromString(Hs);Zs.setAdminKey(Ys.publicKey),Zs=await Zs.sign(Ys)}return Ws&&Zs.setSubmitKey(g$q.fromString(Ws).publicKey),(await this.executeTransaction(Zs)).topicId.toString()}async createToken(Ps,Hs,Ws,Zs,zs,Ys,Va){this.ensureInitialized();let Xs=new c$x().setTokenName(Ps).setTokenSymbol(Hs).setDecimals(Zs).setInitialSupply(Ws).setTreasuryAccountId(y$f.fromString(zs)).setTokenType(e$l.NonFungibleUnique).setSupplyType(e$k.Finite);return Va&&(Xs=Xs.setSupplyKey(g$q.fromString(Va))),Ys&&(Xs=Xs.setAdminKey(g$q.fromString(Ys)),Xs=await Xs.sign(g$q.fromString(Ys))),(await this.executeTransaction(Xs)).tokenId.toString()}async mintNFT(Ps,Hs,Ws){this.ensureInitialized();let Zs=await new r$n().setTokenId(Ps).setMetadata([Buffer$1.from(Hs,"utf-8")]).sign(Ws);return this.executeTransaction(Zs)}async getMessages(Ps,Hs,Ws=!1,Zs){const Ys=`https://${Zs||this.getNetworkPrefix()}.mirrornode.hedera.com`,Va=Number(Hs)>0&&!Ws?`&timestamp=gt:${Hs}`:"",Xs=`${Ys}/api/v1/topics/${Ps}/messages?limit=200${Va}`;try{const Ma=await fetchWithRetry()(Xs);if(!Ma.ok)throw new Error(`Failed to make request to mirror node: ${Ma.status}`);const qs=await Ma.json(),Js=qs?.messages||[],Mc=qs?.links?.next,ol=Js.map(Vc=>({...JSON.parse(atob(Vc.message)),payer:Vc.payer_account_id,created:new Date(Number(Vc.consensus_timestamp)*1e3),consensus_timestamp:Vc.consensus_timestamp,sequence_number:Vc.sequence_number}));if(Mc){const Vc=await this.getMessages(Ps,Number(ol[ol.length-1]?.consensus_timestamp),Ws);ol.push(...Vc.messages)}return{messages:ol.sort((Vc,Dc)=>Vc.sequence_number-Dc.sequence_number),error:""}}catch(Ma){return this.logger.error("Error fetching topic data:",Ma),{messages:[],error:Ma.toString()}}}async signMessage(Ps){const Hs=this.dAppConnector;if(!Hs)throw new Error("No active connection or signer");const Zs=this.getAccountInfo()?.accountId,zs={signerAccountId:`hedera:${this.network}:${Zs}`,message:Ps};return{userSignature:(await Hs.signMessage(zs)).signatureMap}}saveConnectionInfo(Ps,Hs){if(!Ps)localStorage.removeItem("connectedAccountId"),localStorage.removeItem("connectedNetwork");else{const Ws=Hs?.replace(/['"]+/g,"");localStorage.setItem("connectedNetwork",Ws),localStorage.setItem("connectedAccountId",Ps)}}loadConnectionInfo(){return{accountId:localStorage.getItem("connectedAccountId"),network:localStorage.getItem("connectedNetwork")}}async connectWallet(Ps,Hs,Ws){try{await this.init(Ps,Hs,Ws);const Zs=await this.connect(),Ys=this.getAccountInfo()?.accountId,Va=await this.getAccountBalance(),Xs=this.getNetworkPrefix();return this.saveConnectionInfo(Ys,Xs),{accountId:Ys,balance:Va,session:Zs}}catch(Zs){throw this.logger.error("Failed to connect wallet:",Zs),Zs}}async disconnectWallet(Ps=!0){try{const Hs=await this.disconnect();return Hs&&Ps&&localStorage.clear(),this.saveConnectionInfo(void 0),Hs}catch(Hs){return this.logger.error("Failed to disconnect wallet:",Hs),!1}}async initAccount(Ps,Hs,Ws,Zs=()=>{}){const{accountId:zs,network:Ys}=this.loadConnectionInfo();if(zs&&Ys)try{const Va=Ys==="mainnet"?r$y.MAINNET:r$y.TESTNET,Xs=Ws||Va;await this.init(Ps,Hs,Xs,Zs);const Ma=await this.getAccountBalance();return{accountId:zs,balance:Ma}}catch(Va){return this.logger.error("Failed to reconnect:",Va),this.saveConnectionInfo(void 0,void 0),null}else if(Ws)try{this.logger.info("initializing normally through override.",Ws),await this.init(Ps,Hs,Ws,Zs),this.logger.info("initialized",Ws),await this.connectViaDappBrowser(),this.logger.info("connected via dapp browser")}catch(Va){return this.logger.error("Failed to fallback connect:",Va),this.saveConnectionInfo(void 0,void 0),null}return null}subscribeToExtensions(Ps){return this.extensionCheckInterval&&clearInterval(this.extensionCheckInterval),this.hasCalledExtensionCallback=!1,this.extensionCheckInterval=setInterval(()=>{const Ws=(this.dAppConnector?.extensions||[]).find(Zs=>Zs.availableInIframe);Ws&&!this.hasCalledExtensionCallback&&(this.hasCalledExtensionCallback=!0,Ps(Ws),this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null))},1e3),()=>{this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null),this.hasCalledExtensionCallback=!1}}async connectViaDappBrowser(){const Ps=this.dAppConnector.extensions||[],Hs=Ps.find(Ws=>(this.logger.info("Checking extension",Ws),Ws.availableInIframe));this.logger.info("extensions are",Ps,Hs),Hs?await this.connectToExtension(Hs):this.subscribeToExtensions(async Ws=>{await this.connectToExtension(Ws)})}async connectToExtension(Ps){this.logger.info("found extension, connecting to iframe.",Ps);const Hs=await this.dAppConnector.connectExtension(Ps.id),Ws=this.dAppConnector.onSessionIframeCreated;Ws&&Ws(Hs)}ensureInitialized(){if(!this.dAppConnector)throw new Error("SDK not initialized. Call init() first.")}static run(){try{typeof window<"u"&&(window.HashinalsWalletConnectSDK=Nd.getInstance(),window.HashgraphSDK=HashgraphSDK)}catch{console.error("[ERROR]: failed setting sdk on window")}}async transferToken(Ps,Hs,Ws,Zs){this.ensureInitialized();const zs=new T$a().setTransactionId(i$s.generate(Hs)).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Hs),-Zs).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Ws),Zs);return this.executeTransaction(zs)}async createAccount(Ps){this.ensureInitialized();const Hs=new h$m().setInitialBalance(new e$F(Ps));return this.executeTransaction(Hs)}async associateTokenToAccount(Ps,Hs){this.ensureInitialized();const Ws=new r$t().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Hs)]);return this.executeTransaction(Ws)}async dissociateTokenFromAccount(Ps,Hs){this.ensureInitialized();const Ws=new r$s().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Hs)]);return this.executeTransaction(Ws)}async updateAccount(Ps,Hs){this.ensureInitialized();const Ws=new s$G().setAccountId(y$f.fromString(Ps)).setMaxAutomaticTokenAssociations(Hs);return this.executeTransaction(Ws)}async approveAllowance(Ps,Hs,Ws,Zs){this.ensureInitialized();const zs=new A$c().approveTokenAllowance(c$E.fromString(Hs),y$f.fromString(Zs),y$f.fromString(Ps),Ws);return this.executeTransaction(zs)}async getAccountTokens(Ps){this.ensureInitialized();const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com`,Zs=`${Ws}/api/v1/accounts/${Ps}/tokens?limit=200`;try{const zs=await fetchWithRetry()(Zs);if(!zs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${zs.status}`);const Ys=await zs.json(),Va=[];for(const Ma of Ys.tokens)Ma.token_id&&Va.push({tokenId:Ma.token_id,balance:Ma.balance,decimals:Ma.decimals,formatted_balance:(Ma.balance/10**Ma.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Ma.created_timestamp)*1e3)});let Xs=Ys.links?.next;for(;Xs;){const Ma=`${Ws}${Xs}`,qs=await fetchWithRetry()(Ma);if(!qs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${qs.status}, page: ${Ma}`);const Js=await qs.json();for(const Mc of Js.tokens)Mc.token_id&&Va.push({tokenId:Mc.token_id,balance:Mc.balance,decimals:Mc.decimals,formatted_balance:(Mc.balance/10**Mc.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Mc.created_timestamp)*1e3)});Xs=Js.links?.next}return{tokens:Va}}catch(zs){throw this.logger.error("Error fetching account tokens:",zs),zs}}async getTransaction(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions/${Ps}`;this.logger.debug("Fetching transaction",Ws);const Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to fetch transaction: ${Zs.status}`);return await Zs.json()}catch(Hs){return this.logger.error("Failed to get transaction",Hs),null}}async getTransactionByTimestamp(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions?timestamp=${Ps}`;this.logger.debug("Fetching transaction by timestamp",Ws);const Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to fetch transaction by timestamp: ${Zs.status}`);const Ys=(await Zs.json())?.transactions?.[0];return Ys?await this.getTransaction(Ys.transaction_id):null}catch(Hs){return this.logger.error("Failed to get transaction by timestamp",Hs),null}}async getAccountNFTs(Ps,Hs){try{const Ws=this.getNetworkPrefix(),Zs=Hs?`&token.id=${Hs}`:"",zs=`https://${Ws}.mirrornode.hedera.com/api/v1/accounts/${Ps}/nfts?limit=200${Zs}`,Ys=await fetchWithRetry()(zs);if(!Ys.ok)throw new Error(`Failed to fetch NFTs for account: ${Ys.status}`);const Va=await Ys.json();let Xs=Va?.links?.next||null,Ma=Va.nfts||[];for(;Xs;)try{const qs=await fetchWithRetry()(`https://${Ws}.mirrornode.hedera.com${Xs}`);if(!qs.ok)throw new Error(`Failed to fetch next page of NFTs: ${qs.status}`);const Js=await qs.json(),Mc=Js?.nfts||[];Ma=[...Ma,...Mc],Xs=Js?.links?.next&&Xs!==Js?.links?.next?Js.links.next:null}catch(qs){this.logger.error("Failed to fetch next page of NFTs",qs);break}return Ma.map(qs=>{try{qs.token_uri=Buffer$1.from(qs.metadata,"base64").toString("ascii")}catch(Js){this.logger.error("Failed to decode NFT metadata",Js)}return qs})}catch(Ws){return this.logger.error("Failed to get account NFTs",Ws),[]}}async validateNFTOwnership(Ps,Hs,Ws){return(await this.getAccountNFTs(Hs,Ws)).find(zs=>zs.token_id===Ws&&zs.serial_number.toString()===Ps)||null}async readSmartContract(Ps,Hs,Ws,Zs=!0,zs=0){try{const Ys=this.getNetworkPrefix(),Va={block:"latest",data:Ps,estimate:Zs,from:Hs.toSolidityAddress(),to:Ws.toSolidityAddress(),value:zs};Zs||(Va.gas=3e5,Va.gasPrice=1e8);const Xs=`https://${Ys}.mirrornode.hedera.com/api/v1/contracts/call`,Ma=await fetchWithRetry()(Xs,{method:"POST",body:JSON.stringify(Va),headers:{"Content-Type":"application/json"}});if(!Ma.ok)throw new Error(`Failed to make contract call: ${Ma.status}`);return await Ma.json()}catch(Ys){return this.logger.error("Failed to make contract call",Ys),null}}};Nd.proxyInstance=null;let HashinalsWalletConnectSDK=Nd;HashinalsWalletConnectSDK.run();class ReownAuthenticationMessenger{constructor(Ps){this.getNonce=Ps.getNonce}async createMessage(Ps){const Hs={accountAddress:Ps.accountAddress,chainId:Ps.chainId,version:"1",domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,resources:this.resources,nonce:await this.getNonce(Ps),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(Hs,{toString:()=>this.stringify(Hs)})}stringify(Ps){const Hs=this.getNetworkName(Ps.chainId);return[`${Ps.domain} wants you to sign in with your ${Hs} account:`,Ps.accountAddress,Ps.statement?`
466
+ `+JSON.stringify({txError:{name:(zs=Mc?.error)===null||zs===void 0?void 0:zs.name,message:(Ys=Mc?.error)===null||Ys===void 0?void 0:Ys.message,stack:(Va=Mc?.error)===null||Va===void 0?void 0:Va.stack},queryError:{name:(Xs=ol.error)===null||Xs===void 0?void 0:Xs.name,message:(Ma=ol.error)===null||Ma===void 0?void 0:Ma.message,stack:(qs=ol.error)===null||qs===void 0?void 0:qs.stack}},null,2))}}class DAppConnector{constructor(Ps,Hs,Ws,Zs,zs,Ys,Va="debug"){this.network=r$y.TESTNET,this.supportedMethods=[],this.supportedEvents=[],this.supportedChains=[],this.extensions=[],this.onSessionIframeCreated=null,this.signers=[],this.isInitializing=!1,this.abortableConnect=async Xs=>new Promise(async(Ma,qs)=>{const Mc=setTimeout(()=>{this.walletConnectModal.closeModal(),qs(new Error("Connect timed out after 480000(ms)"))},48e4);try{return Ma(await Xs())}catch(ol){qs(ol)}finally{clearTimeout(Mc)}}),this.logger=new DefaultLogger(Va),this.dAppMetadata=Ps,this.network=Hs,this.projectId=Ws,this.supportedMethods=Zs??Object.values(HederaJsonRpcMethod),this.supportedEvents=zs??[],this.supportedChains=Ys??[],this.extensions=[],this.walletConnectModal=new WalletConnectModal({projectId:Ws,chains:Ys}),findExtensions((Xs,Ma)=>{this.extensions.push(Object.assign(Object.assign({},Xs),{available:!0,availableInIframe:Ma}))})}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}async init({logger:Ps}={}){try{if(this.isInitializing=!0,!this.projectId)throw new Error("Project ID is not defined");this.walletConnectClient=await fe$1.init({logger:Ps,relayUrl:"wss://relay.walletconnect.com",projectId:this.projectId,metadata:this.dAppMetadata});const Hs=this.walletConnectClient.session.getAll();Hs.length>0?this.signers=Hs.flatMap(Ws=>this.createSigners(Ws)):this.checkIframeConnect(),this.walletConnectClient.on("session_event",this.handleSessionEvent.bind(this)),this.walletConnectClient.on("session_update",this.handleSessionUpdate.bind(this)),this.walletConnectClient.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.events.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.pairing.events.on("pairing_delete",this.handlePairingDelete.bind(this))}catch(Hs){this.logger.error("Error initializing DAppConnector:",Hs)}finally{this.isInitializing=!1}}getSigner(Ps){if(this.isInitializing)throw new Error("DAppConnector is not initialized yet. Try again later.");const Hs=this.signers.find(Ws=>Ws.getAccountId().equals(Ps));if(!Hs)throw new Error("Signer is not found for this accountId");return Hs}async openModal(Ps,Hs=!1){try{const{uri:Ws,approval:Zs}=await this.connectURI(Ps);return this.walletConnectModal.openModal({uri:Ws}),await new Promise(async(Ys,Va)=>{Hs&&this.walletConnectModal.subscribeModal(Xs=>{Xs.open||Va(new Error("User rejected pairing"))});try{const Xs=await Zs();await this.onSessionConnected(Xs),Ys(Xs)}catch(Xs){Va(Xs)}})}finally{this.walletConnectModal.closeModal()}}async connect(Ps,Hs,Ws){return this.abortableConnect(async()=>{var Zs;const{uri:zs,approval:Ys}=await this.connectURI(Hs);if(!zs)throw new Error("URI is not defined");Ps(zs);const Va=await Ys();if(Ws){const Xs=Object.assign(Object.assign({},Va.sessionProperties),{extensionId:Ws});Va.sessionProperties=Xs,await((Zs=this.walletConnectClient)===null||Zs===void 0?void 0:Zs.session.update(Va.topic,{sessionProperties:Xs}))}return await this.onSessionConnected(Va),Va})}async connectExtension(Ps,Hs){const Ws=this.extensions.find(Zs=>Zs.id===Ps);if(!Ws||!Ws.available)throw new Error("Extension is not available");return this.connect(Zs=>{extensionConnect(Ws.id,Ws.availableInIframe,Zs)},Hs,Ws.availableInIframe?void 0:Ps)}validateSession(Ps){try{if(!this.walletConnectClient)return!1;const Hs=this.walletConnectClient.session.get(Ps),Ws=this.signers.some(Zs=>Zs.topic===Ps);return Hs?Ws?!0:(this.logger.warn(`Session exists but no signer found for topic: ${Ps}`),!1):(Ws&&(this.logger.warn(`Signer exists but no session found for topic: ${Ps}`),this.handleSessionDelete({topic:Ps})),!1)}catch(Hs){return this.logger.error("Error validating session:",Hs),!1}}validateAndRefreshSigners(){this.signers=this.signers.filter(Ps=>this.validateSession(Ps.topic))}async checkIframeConnect(){const Ps=this.extensions.find(Hs=>Hs.availableInIframe);if(Ps){const Hs=await this.connectExtension(Ps.id);this.onSessionIframeCreated&&this.onSessionIframeCreated(Hs)}}async disconnect(Ps){try{if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");return await this.walletConnectClient.disconnect({topic:Ps,reason:zt$2("USER_DISCONNECTED")}),!0}catch(Hs){return this.logger.error("Either the session was already disconnected or the topic is invalid",Hs),!1}}async disconnectAll(){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ps=this.walletConnectClient.session.getAll(),Hs=this.walletConnectClient.core.pairing.getPairings();if(!Ps?.length&&!Hs?.length)throw new Error("There is no active session/pairing. Connect to the wallet at first.");const Ws=[];for(const Zs of this.walletConnectClient.session.getAll()){this.logger.info(`Disconnecting from session: ${Zs}`);const zs=this.disconnect(Zs.topic);Ws.push(zs)}for(const Zs of Hs){const zs=this.disconnect(Zs.topic);Ws.push(zs)}await Promise.all(Ws),this.signers=[]}createSigners(Ps){return accountAndLedgerFromSession(Ps).map(({account:Ws,network:Zs})=>{var zs;return new DAppSigner(Ws,this.walletConnectClient,Ps.topic,Zs,(zs=Ps.sessionProperties)===null||zs===void 0?void 0:zs.extensionId,this.logger instanceof DefaultLogger?this.logger.getLogLevel():"debug")})}async onSessionConnected(Ps){const Hs=this.createSigners(Ps);for(const Ws of Hs){const Zs=this.signers.filter(zs=>{var Ys,Va;const Xs=((Ys=zs?.getAccountId())===null||Ys===void 0?void 0:Ys.toString())===((Va=Ws?.getAccountId())===null||Va===void 0?void 0:Va.toString()),Ma=Ws.extensionId===zs.extensionId,qs=Ws.getMetadata(),Js=zs.getMetadata(),Mc=qs?.name===Js?.name;return zs.topic===Ws.topic&&this.logger.error("The topic was already connected. This is a weird error. Please report it.",Ws.getAccountId().toString()),Xs&&Ma&&Mc});for(const zs of Zs)this.logger.debug(`Disconnecting duplicate signer for account ${zs.getAccountId().toString()}`),await this.disconnect(zs.topic),this.signers=this.signers.filter(Ys=>Ys.topic!==zs.topic)}this.signers.push(...Hs),this.logger.debug(`Current signers after connection: ${this.signers.map(Ws=>`${Ws.getAccountId().toString()}:${Ws.topic}`).join(", ")}`)}async connectURI(Ps){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Hs=networkNamespaces(this.network,this.supportedMethods,this.supportedEvents);return this.logger.debug("V1 DAppConnector: Connecting with params:",{network:this.network.toString(),pairingTopic:Ps,requiredNamespaces:Hs,supportedMethods:this.supportedMethods,supportedEvents:this.supportedEvents}),this.walletConnectClient.connect({pairingTopic:Ps,requiredNamespaces:Hs})}async request({method:Ps,params:Hs}){var Ws,Zs,zs;let Ys;if(this.logger.debug(`Requesting method: ${Ps} with params: ${JSON.stringify(Hs)}`),Hs?.signerAccountId){const Va=(Zs=(Ws=Hs?.signerAccountId)===null||Ws===void 0?void 0:Ws.split(":"))===null||Zs===void 0?void 0:Zs.pop();if(Ys=this.signers.find(Xs=>{var Ma;return((Ma=Xs?.getAccountId())===null||Ma===void 0?void 0:Ma.toString())===Va}),this.logger.debug(`Found signer: ${(zs=Ys?.getAccountId())===null||zs===void 0?void 0:zs.toString()}`),!Ys)throw new Error(`Signer not found for account ID: ${Hs?.signerAccountId}. Did you use the correct format? e.g hedera:<network>:<address> `)}else Ys=this.signers[this.signers.length-1];if(!Ys)throw new Error("There is no active session. Connect to the wallet at first.");return this.logger.debug(`Using signer: ${Ys.getAccountId().toString()}: ${Ys.topic} - about to request.`),await Ys.request({method:Ps,params:Hs})}async getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async signTransaction(Ps){var Hs,Ws;if(typeof Ps?.transactionBody=="string")return this.logger.warn("Transaction body is a string. This is not recommended, please migrate to passing a transaction object directly."),await this.request({method:HederaJsonRpcMethod.SignTransaction,params:Ps});if(Ps?.transactionBody instanceof L$a){const Zs=(Ws=(Hs=Ps?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Ws===void 0?void 0:Ws.pop(),zs=this.signers.find(Ys=>{var Va;return((Va=Ys?.getAccountId())===null||Va===void 0?void 0:Va.toString())===Zs});if(!zs)throw new Error(`No signer found for account ${Zs}`);if(!Ps?.transactionBody)throw new Error("No transaction provided");return await zs.signTransaction(Ps.transactionBody)}throw new Error("Transaction sent in incorrect format. Ensure transaction body is either a base64 transaction body or Transaction object.")}handleSessionEvent(Ps){this.logger.debug("Session event received:",Ps),this.validateAndRefreshSigners()}handleSessionUpdate({topic:Ps,params:Hs}){const{namespaces:Ws}=Hs,Zs=this.walletConnectClient.session.get(Ps),zs=Object.assign(Object.assign({},Zs),{namespaces:Ws});this.logger.info("Session updated:",zs),this.signers=this.signers.filter(Ys=>Ys.topic!==Ps),this.signers.push(...this.createSigners(zs))}handleSessionDelete(Ps){this.logger.info("Session deleted:",Ps);let Hs=!1;if(this.signers=this.signers.filter(Ws=>Ws.topic!==Ps.topic?!0:(Hs=!0,!1)),Hs){try{this.disconnect(Ps.topic)}catch(Ws){this.logger.error("Error disconnecting session:",Ws)}this.logger.info("Session deleted and signer removed")}}handlePairingDelete(Ps){this.logger.info("Pairing deleted:",Ps),this.signers=this.signers.filter(Hs=>Hs.topic!==Ps.topic);try{this.disconnect(Ps.topic)}catch(Hs){this.logger.error("Error disconnecting pairing:",Hs)}this.logger.info("Pairing deleted by wallet")}}const version$1="6.15.0";function checkType(Fs,Ps,Hs){const Ws=Ps.split("|").map(zs=>zs.trim());for(let zs=0;zs<Ws.length;zs++)switch(Ps){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof Fs===Ps)return}const Zs=new Error(`invalid value for type ${Ps}`);throw Zs.code="INVALID_ARGUMENT",Zs.argument=`value.${Hs}`,Zs.value=Fs,Zs}async function resolveProperties(Fs){const Ps=Object.keys(Fs);return(await Promise.all(Ps.map(Ws=>Promise.resolve(Fs[Ws])))).reduce((Ws,Zs,zs)=>(Ws[Ps[zs]]=Zs,Ws),{})}function defineProperties(Fs,Ps,Hs){for(let Ws in Ps){let Zs=Ps[Ws];const zs=Hs?Hs[Ws]:null;zs&&checkType(Zs,zs,Ws),Object.defineProperty(Fs,Ws,{enumerable:!0,value:Zs,writable:!1})}}function stringify(Fs,Ps){if(Fs==null)return"null";if(Ps==null&&(Ps=new Set),typeof Fs=="object"){if(Ps.has(Fs))return"[Circular]";Ps.add(Fs)}if(Array.isArray(Fs))return"[ "+Fs.map(Hs=>stringify(Hs,Ps)).join(", ")+" ]";if(Fs instanceof Uint8Array){const Hs="0123456789abcdef";let Ws="0x";for(let Zs=0;Zs<Fs.length;Zs++)Ws+=Hs[Fs[Zs]>>4],Ws+=Hs[Fs[Zs]&15];return Ws}if(typeof Fs=="object"&&typeof Fs.toJSON=="function")return stringify(Fs.toJSON(),Ps);switch(typeof Fs){case"boolean":case"number":case"symbol":return Fs.toString();case"bigint":return BigInt(Fs).toString();case"string":return JSON.stringify(Fs);case"object":{const Hs=Object.keys(Fs);return Hs.sort(),"{ "+Hs.map(Ws=>`${stringify(Ws,Ps)}: ${stringify(Fs[Ws],Ps)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function isError(Fs,Ps){return Fs&&Fs.code===Ps}function isCallException(Fs){return isError(Fs,"CALL_EXCEPTION")}function makeError(Fs,Ps,Hs){let Ws=Fs;{const zs=[];if(Hs){if("message"in Hs||"code"in Hs||"name"in Hs)throw new Error(`value will overwrite populated values: ${stringify(Hs)}`);for(const Ys in Hs){if(Ys==="shortMessage")continue;const Va=Hs[Ys];zs.push(Ys+"="+stringify(Va))}}zs.push(`code=${Ps}`),zs.push(`version=${version$1}`),zs.length&&(Fs+=" ("+zs.join(", ")+")")}let Zs;switch(Ps){case"INVALID_ARGUMENT":Zs=new TypeError(Fs);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":Zs=new RangeError(Fs);break;default:Zs=new Error(Fs)}return defineProperties(Zs,{code:Ps}),Hs&&Object.assign(Zs,Hs),Zs.shortMessage==null&&defineProperties(Zs,{shortMessage:Ws}),Zs}function assert(Fs,Ps,Hs,Ws){if(!Fs)throw makeError(Ps,Hs,Ws)}function assertArgument(Fs,Ps,Hs,Ws){assert(Fs,Ps,"INVALID_ARGUMENT",{argument:Hs,value:Ws})}function assertArgumentCount(Fs,Ps,Hs){Hs==null&&(Hs=""),Hs&&(Hs=": "+Hs),assert(Fs>=Ps,"missing argument"+Hs,"MISSING_ARGUMENT",{count:Fs,expectedCount:Ps}),assert(Fs<=Ps,"too many arguments"+Hs,"UNEXPECTED_ARGUMENT",{count:Fs,expectedCount:Ps})}["NFD","NFC","NFKD","NFKC"].reduce((Fs,Ps)=>{try{if("test".normalize(Ps)!=="test")throw new Error("bad");if(Ps==="NFD"&&"é".normalize("NFD")!=="é")throw new Error("broken");Fs.push(Ps)}catch{}return Fs},[]);function assertPrivate(Fs,Ps,Hs){if(Hs==null&&(Hs=""),Fs!==Ps){let Ws=Hs,Zs="new";Hs&&(Ws+=".",Zs+=" "+Hs),assert(!1,`private constructor; use ${Ws}from* methods`,"UNSUPPORTED_OPERATION",{operation:Zs})}}function _getBytes(Fs,Ps,Hs){if(Fs instanceof Uint8Array)return Hs?new Uint8Array(Fs):Fs;if(typeof Fs=="string"&&Fs.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)){const Ws=new Uint8Array((Fs.length-2)/2);let Zs=2;for(let zs=0;zs<Ws.length;zs++)Ws[zs]=parseInt(Fs.substring(Zs,Zs+2),16),Zs+=2;return Ws}assertArgument(!1,"invalid BytesLike value",Ps||"value",Fs)}function getBytes(Fs,Ps){return _getBytes(Fs,Ps,!1)}function getBytesCopy(Fs,Ps){return _getBytes(Fs,Ps,!0)}function isHexString(Fs,Ps){return!(typeof Fs!="string"||!Fs.match(/^0x[0-9A-Fa-f]*$/)||typeof Ps=="number"&&Fs.length!==2+2*Ps||Ps===!0&&Fs.length%2!==0)}function isBytesLike(Fs){return isHexString(Fs,!0)||Fs instanceof Uint8Array}const HexCharacters="0123456789abcdef";function hexlify(Fs){const Ps=getBytes(Fs);let Hs="0x";for(let Ws=0;Ws<Ps.length;Ws++){const Zs=Ps[Ws];Hs+=HexCharacters[(Zs&240)>>4]+HexCharacters[Zs&15]}return Hs}function concat(Fs){return"0x"+Fs.map(Ps=>hexlify(Ps).substring(2)).join("")}function dataLength(Fs){return isHexString(Fs,!0)?(Fs.length-2)/2:getBytes(Fs).length}function dataSlice(Fs,Ps,Hs){const Ws=getBytes(Fs);return Hs!=null&&Hs>Ws.length&&assert(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:Ws,length:Ws.length,offset:Hs}),hexlify(Ws.slice(Ps??0,Hs??Ws.length))}function zeroPad(Fs,Ps,Hs){const Ws=getBytes(Fs);assert(Ps>=Ws.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(Ws),length:Ps,offset:Ps+1});const Zs=new Uint8Array(Ps);return Zs.fill(0),Hs?Zs.set(Ws,Ps-Ws.length):Zs.set(Ws,0),hexlify(Zs)}function zeroPadValue(Fs,Ps){return zeroPad(Fs,Ps,!0)}function zeroPadBytes(Fs,Ps){return zeroPad(Fs,Ps,!1)}const BN_0$9=BigInt(0),BN_1$4=BigInt(1),maxValue=9007199254740991;function fromTwos(Fs,Ps){const Hs=getUint(Fs,"value"),Ws=BigInt(getNumber(Ps,"width"));if(assert(Hs>>Ws===BN_0$9,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:Fs}),Hs>>Ws-BN_1$4){const Zs=(BN_1$4<<Ws)-BN_1$4;return-((~Hs&Zs)+BN_1$4)}return Hs}function toTwos(Fs,Ps){let Hs=getBigInt(Fs,"value");const Ws=BigInt(getNumber(Ps,"width")),Zs=BN_1$4<<Ws-BN_1$4;if(Hs<BN_0$9){Hs=-Hs,assert(Hs<=Zs,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:Fs});const zs=(BN_1$4<<Ws)-BN_1$4;return(~Hs&zs)+BN_1$4}else assert(Hs<Zs,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:Fs});return Hs}function mask(Fs,Ps){const Hs=getUint(Fs,"value"),Ws=BigInt(getNumber(Ps,"bits"));return Hs&(BN_1$4<<Ws)-BN_1$4}function getBigInt(Fs,Ps){switch(typeof Fs){case"bigint":return Fs;case"number":return assertArgument(Number.isInteger(Fs),"underflow",Ps||"value",Fs),assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),BigInt(Fs);case"string":try{if(Fs==="")throw new Error("empty string");return Fs[0]==="-"&&Fs[1]!=="-"?-BigInt(Fs.substring(1)):BigInt(Fs)}catch(Hs){assertArgument(!1,`invalid BigNumberish string: ${Hs.message}`,Ps||"value",Fs)}}assertArgument(!1,"invalid BigNumberish value",Ps||"value",Fs)}function getUint(Fs,Ps){const Hs=getBigInt(Fs,Ps);return assert(Hs>=BN_0$9,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:Fs}),Hs}const Nibbles="0123456789abcdef";function toBigInt(Fs){if(Fs instanceof Uint8Array){let Ps="0x0";for(const Hs of Fs)Ps+=Nibbles[Hs>>4],Ps+=Nibbles[Hs&15];return BigInt(Ps)}return getBigInt(Fs)}function getNumber(Fs,Ps){switch(typeof Fs){case"bigint":return assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),Number(Fs);case"number":return assertArgument(Number.isInteger(Fs),"underflow",Ps||"value",Fs),assertArgument(Fs>=-maxValue&&Fs<=maxValue,"overflow",Ps||"value",Fs),Fs;case"string":try{if(Fs==="")throw new Error("empty string");return getNumber(BigInt(Fs),Ps)}catch(Hs){assertArgument(!1,`invalid numeric string: ${Hs.message}`,Ps||"value",Fs)}}assertArgument(!1,"invalid numeric value",Ps||"value",Fs)}function toNumber(Fs){return getNumber(toBigInt(Fs))}function toBeHex(Fs,Ps){let Ws=getUint(Fs,"value").toString(16);if(Ps==null)Ws.length%2&&(Ws="0"+Ws);else{const Zs=getNumber(Ps,"width");for(assert(Zs*2>=Ws.length,`value exceeds width (${Zs} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:Fs});Ws.length<Zs*2;)Ws="0"+Ws}return"0x"+Ws}function toBeArray(Fs){const Ps=getUint(Fs,"value");if(Ps===BN_0$9)return new Uint8Array([]);let Hs=Ps.toString(16);Hs.length%2&&(Hs="0"+Hs);const Ws=new Uint8Array(Hs.length/2);for(let Zs=0;Zs<Ws.length;Zs++){const zs=Zs*2;Ws[Zs]=parseInt(Hs.substring(zs,zs+2),16)}return Ws}function toQuantity(Fs){let Ps=hexlify(isBytesLike(Fs)?Fs:toBeArray(Fs)).substring(2);for(;Ps.startsWith("0");)Ps=Ps.substring(1);return Ps===""&&(Ps="0"),"0x"+Ps}const Alphabet="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";BigInt(0);const BN_58=BigInt(58);function encodeBase58(Fs){const Ps=getBytes(Fs);let Hs=toBigInt(Ps),Ws="";for(;Hs;)Ws=Alphabet[Number(Hs%BN_58)]+Ws,Hs/=BN_58;for(let Zs=0;Zs<Ps.length&&!Ps[Zs];Zs++)Ws=Alphabet[0]+Ws;return Ws}function decodeBase64(Fs){Fs=atob(Fs);const Ps=new Uint8Array(Fs.length);for(let Hs=0;Hs<Fs.length;Hs++)Ps[Hs]=Fs.charCodeAt(Hs);return getBytes(Ps)}function encodeBase64(Fs){const Ps=getBytes(Fs);let Hs="";for(let Ws=0;Ws<Ps.length;Ws++)Hs+=String.fromCharCode(Ps[Ws]);return btoa(Hs)}class EventPayload{filter;emitter;#e;constructor(Ps,Hs,Ws){this.#e=Hs,defineProperties(this,{emitter:Ps,filter:Ws})}async removeListener(){this.#e!=null&&await this.emitter.off(this.filter,this.#e)}}function errorFunc(Fs,Ps,Hs,Ws,Zs){assertArgument(!1,`invalid codepoint at offset ${Ps}; ${Fs}`,"bytes",Hs)}function ignoreFunc(Fs,Ps,Hs,Ws,Zs){if(Fs==="BAD_PREFIX"||Fs==="UNEXPECTED_CONTINUE"){let zs=0;for(let Ys=Ps+1;Ys<Hs.length&&Hs[Ys]>>6===2;Ys++)zs++;return zs}return Fs==="OVERRUN"?Hs.length-Ps-1:0}function replaceFunc(Fs,Ps,Hs,Ws,Zs){return Fs==="OVERLONG"?(assertArgument(typeof Zs=="number","invalid bad code point for replacement","badCodepoint",Zs),Ws.push(Zs),0):(Ws.push(65533),ignoreFunc(Fs,Ps,Hs))}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(Fs,Ps){Ps==null&&(Ps=Utf8ErrorFuncs.error);const Hs=getBytes(Fs,"bytes"),Ws=[];let Zs=0;for(;Zs<Hs.length;){const zs=Hs[Zs++];if(zs>>7===0){Ws.push(zs);continue}let Ys=null,Va=null;if((zs&224)===192)Ys=1,Va=127;else if((zs&240)===224)Ys=2,Va=2047;else if((zs&248)===240)Ys=3,Va=65535;else{(zs&192)===128?Zs+=Ps("UNEXPECTED_CONTINUE",Zs-1,Hs,Ws):Zs+=Ps("BAD_PREFIX",Zs-1,Hs,Ws);continue}if(Zs-1+Ys>=Hs.length){Zs+=Ps("OVERRUN",Zs-1,Hs,Ws);continue}let Xs=zs&(1<<8-Ys-1)-1;for(let Ma=0;Ma<Ys;Ma++){let qs=Hs[Zs];if((qs&192)!=128){Zs+=Ps("MISSING_CONTINUE",Zs,Hs,Ws),Xs=null;break}Xs=Xs<<6|qs&63,Zs++}if(Xs!==null){if(Xs>1114111){Zs+=Ps("OUT_OF_RANGE",Zs-1-Ys,Hs,Ws,Xs);continue}if(Xs>=55296&&Xs<=57343){Zs+=Ps("UTF16_SURROGATE",Zs-1-Ys,Hs,Ws,Xs);continue}if(Xs<=Va){Zs+=Ps("OVERLONG",Zs-1-Ys,Hs,Ws,Xs);continue}Ws.push(Xs)}}return Ws}function toUtf8Bytes(Fs,Ps){assertArgument(typeof Fs=="string","invalid string value","str",Fs);let Hs=[];for(let Ws=0;Ws<Fs.length;Ws++){const Zs=Fs.charCodeAt(Ws);if(Zs<128)Hs.push(Zs);else if(Zs<2048)Hs.push(Zs>>6|192),Hs.push(Zs&63|128);else if((Zs&64512)==55296){Ws++;const zs=Fs.charCodeAt(Ws);assertArgument(Ws<Fs.length&&(zs&64512)===56320,"invalid surrogate pair","str",Fs);const Ys=65536+((Zs&1023)<<10)+(zs&1023);Hs.push(Ys>>18|240),Hs.push(Ys>>12&63|128),Hs.push(Ys>>6&63|128),Hs.push(Ys&63|128)}else Hs.push(Zs>>12|224),Hs.push(Zs>>6&63|128),Hs.push(Zs&63|128)}return new Uint8Array(Hs)}function _toUtf8String(Fs){return Fs.map(Ps=>Ps<=65535?String.fromCharCode(Ps):(Ps-=65536,String.fromCharCode((Ps>>10&1023)+55296,(Ps&1023)+56320))).join("")}function toUtf8String(Fs,Ps){return _toUtf8String(getUtf8CodePoints(Fs,Ps))}function createGetUrl(Fs){async function Ps(Hs,Ws){assert(Ws==null||!Ws.cancelled,"request cancelled before sending","CANCELLED");const Zs=Hs.url.split(":")[0].toLowerCase();assert(Zs==="http"||Zs==="https",`unsupported protocol ${Zs}`,"UNSUPPORTED_OPERATION",{info:{protocol:Zs},operation:"request"}),assert(Zs==="https"||!Hs.credentials||Hs.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let zs=null;const Ys=new AbortController,Va=setTimeout(()=>{zs=makeError("request timeout","TIMEOUT"),Ys.abort()},Hs.timeout);Ws&&Ws.addListener(()=>{zs=makeError("request cancelled","CANCELLED"),Ys.abort()});const Xs=Object.assign({},Fs,{method:Hs.method,headers:new Headers(Array.from(Hs)),body:Hs.body||void 0,signal:Ys.signal});let Ma;try{Ma=await fetch(Hs.url,Xs)}catch(ol){throw clearTimeout(Va),zs||ol}clearTimeout(Va);const qs={};Ma.headers.forEach((ol,Vc)=>{qs[Vc.toLowerCase()]=ol});const Js=await Ma.arrayBuffer(),Mc=Js==null?null:new Uint8Array(Js);return{statusCode:Ma.status,statusMessage:Ma.statusText,headers:qs,body:Mc}}return Ps}const MAX_ATTEMPTS=12,SLOT_INTERVAL=250;let defaultGetUrlFunc=createGetUrl();const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$1=!1;async function dataGatewayFunc(Fs,Ps){try{const Hs=Fs.match(reData);if(!Hs)throw new Error("invalid data");return new FetchResponse(200,"OK",{"content-type":Hs[1]||"text/plain"},Hs[2]?decodeBase64(Hs[3]):unpercent(Hs[3]))}catch{return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(Fs))}}function getIpfsGatewayFunc(Fs){async function Ps(Hs,Ws){try{const Zs=Hs.match(reIpfs);if(!Zs)throw new Error("invalid link");return new FetchRequest(`${Fs}${Zs[2]}`)}catch{return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(Hs))}}return Ps}const Gateways={data:dataGatewayFunc,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")},fetchSignals=new WeakMap;class FetchCancelSignal{#e;#t;constructor(Ps){this.#e=[],this.#t=!1,fetchSignals.set(Ps,()=>{if(!this.#t){this.#t=!0;for(const Hs of this.#e)setTimeout(()=>{Hs()},0);this.#e=[]}})}addListener(Ps){assert(!this.#t,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),this.#e.push(Ps)}get cancelled(){return this.#t}checkSignal(){assert(!this.cancelled,"cancelled","CANCELLED",{})}}function checkSignal(Fs){if(Fs==null)throw new Error("missing signal; should not happen");return Fs.checkSignal(),Fs}class FetchRequest{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;#c;#u;#f;get url(){return this.#s}set url(Ps){this.#s=String(Ps)}get body(){return this.#i==null?null:new Uint8Array(this.#i)}set body(Ps){if(Ps==null)this.#i=void 0,this.#a=void 0;else if(typeof Ps=="string")this.#i=toUtf8Bytes(Ps),this.#a="text/plain";else if(Ps instanceof Uint8Array)this.#i=Ps,this.#a="application/octet-stream";else if(typeof Ps=="object")this.#i=toUtf8Bytes(JSON.stringify(Ps)),this.#a="application/json";else throw new Error("invalid body")}hasBody(){return this.#i!=null}get method(){return this.#n?this.#n:this.hasBody()?"POST":"GET"}set method(Ps){Ps==null&&(Ps=""),this.#n=String(Ps).toUpperCase()}get headers(){const Ps=Object.assign({},this.#r);return this.#d&&(Ps.authorization=`Basic ${encodeBase64(toUtf8Bytes(this.#d))}`),this.allowGzip&&(Ps["accept-encoding"]="gzip"),Ps["content-type"]==null&&this.#a&&(Ps["content-type"]=this.#a),this.body&&(Ps["content-length"]=String(this.body.length)),Ps}getHeader(Ps){return this.headers[Ps.toLowerCase()]}setHeader(Ps,Hs){this.#r[String(Ps).toLowerCase()]=String(Hs)}clearHeaders(){this.#r={}}[Symbol.iterator](){const Ps=this.headers,Hs=Object.keys(Ps);let Ws=0;return{next:()=>{if(Ws<Hs.length){const Zs=Hs[Ws++];return{value:[Zs,Ps[Zs]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#d||null}setCredentials(Ps,Hs){assertArgument(!Ps.match(/:/),"invalid basic authentication username","username","[REDACTED]"),this.#d=`${Ps}:${Hs}`}get allowGzip(){return this.#t}set allowGzip(Ps){this.#t=!!Ps}get allowInsecureAuthentication(){return!!this.#e}set allowInsecureAuthentication(Ps){this.#e=!!Ps}get timeout(){return this.#o}set timeout(Ps){assertArgument(Ps>=0,"timeout must be non-zero","timeout",Ps),this.#o=Ps}get preflightFunc(){return this.#l||null}set preflightFunc(Ps){this.#l=Ps}get processFunc(){return this.#p||null}set processFunc(Ps){this.#p=Ps}get retryFunc(){return this.#g||null}set retryFunc(Ps){this.#g=Ps}get getUrlFunc(){return this.#f||defaultGetUrlFunc}set getUrlFunc(Ps){this.#f=Ps}constructor(Ps){this.#s=String(Ps),this.#e=!1,this.#t=!0,this.#r={},this.#n="",this.#o=3e5,this.#u={slotInterval:SLOT_INTERVAL,maxAttempts:MAX_ATTEMPTS},this.#f=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#i?hexlify(this.#i):"null"}>`}setThrottleParams(Ps){Ps.slotInterval!=null&&(this.#u.slotInterval=Ps.slotInterval),Ps.maxAttempts!=null&&(this.#u.maxAttempts=Ps.maxAttempts)}async#h(Ps,Hs,Ws,Zs,zs){if(Ps>=this.#u.maxAttempts)return zs.makeServerError("exceeded maximum retry limit");assert(getTime$1()<=Hs,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:Zs}),Ws>0&&await wait(Ws);let Ys=this.clone();const Va=(Ys.url.split(":")[0]||"").toLowerCase();if(Va in Gateways){const qs=await Gateways[Va](Ys.url,checkSignal(Zs.#c));if(qs instanceof FetchResponse){let Js=qs;if(this.processFunc){checkSignal(Zs.#c);try{Js=await this.processFunc(Ys,Js)}catch(Mc){(Mc.throttle==null||typeof Mc.stall!="number")&&Js.makeServerError("error in post-processing function",Mc).assertOk()}}return Js}Ys=qs}this.preflightFunc&&(Ys=await this.preflightFunc(Ys));const Xs=await this.getUrlFunc(Ys,checkSignal(Zs.#c));let Ma=new FetchResponse(Xs.statusCode,Xs.statusMessage,Xs.headers,Xs.body,Zs);if(Ma.statusCode===301||Ma.statusCode===302){try{const qs=Ma.headers.location||"";return Ys.redirect(qs).#h(Ps+1,Hs,0,Zs,Ma)}catch{}return Ma}else if(Ma.statusCode===429&&(this.retryFunc==null||await this.retryFunc(Ys,Ma,Ps))){const qs=Ma.headers["retry-after"];let Js=this.#u.slotInterval*Math.trunc(Math.random()*Math.pow(2,Ps));return typeof qs=="string"&&qs.match(/^[1-9][0-9]*$/)&&(Js=parseInt(qs)),Ys.clone().#h(Ps+1,Hs,Js,Zs,Ma)}if(this.processFunc){checkSignal(Zs.#c);try{Ma=await this.processFunc(Ys,Ma)}catch(qs){(qs.throttle==null||typeof qs.stall!="number")&&Ma.makeServerError("error in post-processing function",qs).assertOk();let Js=this.#u.slotInterval*Math.trunc(Math.random()*Math.pow(2,Ps));return qs.stall>=0&&(Js=qs.stall),Ys.clone().#h(Ps+1,Hs,Js,Zs,Ma)}}return Ma}send(){return assert(this.#c==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),this.#c=new FetchCancelSignal(this),this.#h(0,getTime$1()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){assert(this.#c!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const Ps=fetchSignals.get(this);if(!Ps)throw new Error("missing signal; should not happen");Ps()}redirect(Ps){const Hs=this.url.split(":")[0].toLowerCase(),Ws=Ps.split(":")[0].toLowerCase();assert(this.method==="GET"&&(Hs!=="https"||Ws!=="http")&&Ps.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(Ps)})`});const Zs=new FetchRequest(Ps);return Zs.method="GET",Zs.allowGzip=this.allowGzip,Zs.timeout=this.timeout,Zs.#r=Object.assign({},this.#r),this.#i&&(Zs.#i=new Uint8Array(this.#i)),Zs.#a=this.#a,Zs}clone(){const Ps=new FetchRequest(this.url);return Ps.#n=this.#n,this.#i&&(Ps.#i=this.#i),Ps.#a=this.#a,Ps.#r=Object.assign({},this.#r),Ps.#d=this.#d,this.allowGzip&&(Ps.allowGzip=!0),Ps.timeout=this.timeout,this.allowInsecureAuthentication&&(Ps.allowInsecureAuthentication=!0),Ps.#l=this.#l,Ps.#p=this.#p,Ps.#g=this.#g,Ps.#u=Object.assign({},this.#u),Ps.#f=this.#f,Ps}static lockConfig(){locked$1=!0}static getGateway(Ps){return Gateways[Ps.toLowerCase()]||null}static registerGateway(Ps,Hs){if(Ps=Ps.toLowerCase(),Ps==="http"||Ps==="https")throw new Error(`cannot intercept ${Ps}; use registerGetUrl`);if(locked$1)throw new Error("gateways locked");Gateways[Ps]=Hs}static registerGetUrl(Ps){if(locked$1)throw new Error("gateways locked");defaultGetUrlFunc=Ps}static createGetUrlFunc(Ps){return createGetUrl(Ps)}static createDataGateway(){return dataGatewayFunc}static createIpfsGatewayFunc(Ps){return getIpfsGatewayFunc(Ps)}}class FetchResponse{#e;#t;#r;#n;#o;#s;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#n?hexlify(this.#n):"null"}>`}get statusCode(){return this.#e}get statusMessage(){return this.#t}get headers(){return Object.assign({},this.#r)}get body(){return this.#n==null?null:new Uint8Array(this.#n)}get bodyText(){try{return this.#n==null?"":toUtf8String(this.#n)}catch{assert(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch{assert(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const Ps=this.headers,Hs=Object.keys(Ps);let Ws=0;return{next:()=>{if(Ws<Hs.length){const Zs=Hs[Ws++];return{value:[Zs,Ps[Zs]],done:!1}}return{value:void 0,done:!0}}}}constructor(Ps,Hs,Ws,Zs,zs){this.#e=Ps,this.#t=Hs,this.#r=Object.keys(Ws).reduce((Ys,Va)=>(Ys[Va.toLowerCase()]=String(Ws[Va]),Ys),{}),this.#n=Zs==null?null:new Uint8Array(Zs),this.#o=zs||null,this.#s={message:""}}makeServerError(Ps,Hs){let Ws;Ps?Ws=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${Ps})`:(Ps=`${this.statusCode} ${this.statusMessage}`,Ws=`CLIENT ESCALATED SERVER ERROR (${Ps})`);const Zs=new FetchResponse(599,Ws,this.headers,this.body,this.#o||void 0);return Zs.#s={message:Ps,error:Hs},Zs}throwThrottleError(Ps,Hs){Hs==null?Hs=-1:assertArgument(Number.isInteger(Hs)&&Hs>=0,"invalid stall timeout","stall",Hs);const Ws=new Error(Ps||"throttling requests");throw defineProperties(Ws,{stall:Hs,throttle:!0}),Ws}getHeader(Ps){return this.headers[Ps.toLowerCase()]}hasBody(){return this.#n!=null}get request(){return this.#o}ok(){return this.#s.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:Ps,error:Hs}=this.#s;Ps===""&&(Ps=`server response ${this.statusCode} ${this.statusMessage}`);let Ws=null;this.request&&(Ws=this.request.url);let Zs=null;try{this.#n&&(Zs=toUtf8String(this.#n))}catch{}assert(!1,Ps,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:Hs,info:{requestUrl:Ws,responseBody:Zs,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}function getTime$1(){return new Date().getTime()}function unpercent(Fs){return toUtf8Bytes(Fs.replace(/%([0-9a-f][0-9a-f])/gi,(Ps,Hs)=>String.fromCharCode(parseInt(Hs,16))))}function wait(Fs){return new Promise(Ps=>setTimeout(Ps,Fs))}const BN_N1=BigInt(-1),BN_0$8=BigInt(0),BN_1$3=BigInt(1),BN_5=BigInt(5),_guard$3={};let Zeros$1="0000";for(;Zeros$1.length<80;)Zeros$1+=Zeros$1;function getTens(Fs){let Ps=Zeros$1;for(;Ps.length<Fs;)Ps+=Ps;return BigInt("1"+Ps.substring(0,Fs))}function checkValue(Fs,Ps,Hs){const Ws=BigInt(Ps.width);if(Ps.signed){const Zs=BN_1$3<<Ws-BN_1$3;assert(Hs==null||Fs>=-Zs&&Fs<Zs,"overflow","NUMERIC_FAULT",{operation:Hs,fault:"overflow",value:Fs}),Fs>BN_0$8?Fs=fromTwos(mask(Fs,Ws),Ws):Fs=-fromTwos(mask(-Fs,Ws),Ws)}else{const Zs=BN_1$3<<Ws;assert(Hs==null||Fs>=0&&Fs<Zs,"overflow","NUMERIC_FAULT",{operation:Hs,fault:"overflow",value:Fs}),Fs=(Fs%Zs+Zs)%Zs&Zs-BN_1$3}return Fs}function getFormat(Fs){typeof Fs=="number"&&(Fs=`fixed128x${Fs}`);let Ps=!0,Hs=128,Ws=18;if(typeof Fs=="string"){if(Fs!=="fixed")if(Fs==="ufixed")Ps=!1;else{const zs=Fs.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);assertArgument(zs,"invalid fixed format","format",Fs),Ps=zs[1]!=="u",Hs=parseInt(zs[2]),Ws=parseInt(zs[3])}}else if(Fs){const zs=Fs,Ys=(Va,Xs,Ma)=>zs[Va]==null?Ma:(assertArgument(typeof zs[Va]===Xs,"invalid fixed format ("+Va+" not "+Xs+")","format."+Va,zs[Va]),zs[Va]);Ps=Ys("signed","boolean",Ps),Hs=Ys("width","number",Hs),Ws=Ys("decimals","number",Ws)}assertArgument(Hs%8===0,"invalid FixedNumber width (not byte aligned)","format.width",Hs),assertArgument(Ws<=80,"invalid FixedNumber decimals (too large)","format.decimals",Ws);const Zs=(Ps?"":"u")+"fixed"+String(Hs)+"x"+String(Ws);return{signed:Ps,width:Hs,decimals:Ws,name:Zs}}function toString(Fs,Ps){let Hs="";Fs<BN_0$8&&(Hs="-",Fs*=BN_N1);let Ws=Fs.toString();if(Ps===0)return Hs+Ws;for(;Ws.length<=Ps;)Ws=Zeros$1+Ws;const Zs=Ws.length-Ps;for(Ws=Ws.substring(0,Zs)+"."+Ws.substring(Zs);Ws[0]==="0"&&Ws[1]!==".";)Ws=Ws.substring(1);for(;Ws[Ws.length-1]==="0"&&Ws[Ws.length-2]!==".";)Ws=Ws.substring(0,Ws.length-1);return Hs+Ws}class FixedNumber{format;#e;#t;#r;_value;constructor(Ps,Hs,Ws){assertPrivate(Ps,_guard$3,"FixedNumber"),this.#t=Hs,this.#e=Ws;const Zs=toString(Hs,Ws.decimals);defineProperties(this,{format:Ws.name,_value:Zs}),this.#r=getTens(Ws.decimals)}get signed(){return this.#e.signed}get width(){return this.#e.width}get decimals(){return this.#e.decimals}get value(){return this.#t}#n(Ps){assertArgument(this.format===Ps.format,"incompatible format; use fixedNumber.toFormat","other",Ps)}#o(Ps,Hs){return Ps=checkValue(Ps,this.#e,Hs),new FixedNumber(_guard$3,Ps,this.#e)}#s(Ps,Hs){return this.#n(Ps),this.#o(this.#t+Ps.#t,Hs)}addUnsafe(Ps){return this.#s(Ps)}add(Ps){return this.#s(Ps,"add")}#i(Ps,Hs){return this.#n(Ps),this.#o(this.#t-Ps.#t,Hs)}subUnsafe(Ps){return this.#i(Ps)}sub(Ps){return this.#i(Ps,"sub")}#a(Ps,Hs){return this.#n(Ps),this.#o(this.#t*Ps.#t/this.#r,Hs)}mulUnsafe(Ps){return this.#a(Ps)}mul(Ps){return this.#a(Ps,"mul")}mulSignal(Ps){this.#n(Ps);const Hs=this.#t*Ps.#t;return assert(Hs%this.#r===BN_0$8,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this}),this.#o(Hs/this.#r,"mulSignal")}#d(Ps,Hs){return assert(Ps.#t!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#n(Ps),this.#o(this.#t*this.#r/Ps.#t,Hs)}divUnsafe(Ps){return this.#d(Ps)}div(Ps){return this.#d(Ps,"div")}divSignal(Ps){assert(Ps.#t!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#n(Ps);const Hs=this.#t*this.#r;return assert(Hs%Ps.#t===BN_0$8,"precision lost during signalling div","NUMERIC_FAULT",{operation:"divSignal",fault:"underflow",value:this}),this.#o(Hs/Ps.#t,"divSignal")}cmp(Ps){let Hs=this.value,Ws=Ps.value;const Zs=this.decimals-Ps.decimals;return Zs>0?Ws*=getTens(Zs):Zs<0&&(Hs*=getTens(-Zs)),Hs<Ws?-1:Hs>Ws?1:0}eq(Ps){return this.cmp(Ps)===0}lt(Ps){return this.cmp(Ps)<0}lte(Ps){return this.cmp(Ps)<=0}gt(Ps){return this.cmp(Ps)>0}gte(Ps){return this.cmp(Ps)>=0}floor(){let Ps=this.#t;return this.#t<BN_0$8&&(Ps-=this.#r-BN_1$3),Ps=this.#t/this.#r*this.#r,this.#o(Ps,"floor")}ceiling(){let Ps=this.#t;return this.#t>BN_0$8&&(Ps+=this.#r-BN_1$3),Ps=this.#t/this.#r*this.#r,this.#o(Ps,"ceiling")}round(Ps){if(Ps==null&&(Ps=0),Ps>=this.decimals)return this;const Hs=this.decimals-Ps,Ws=BN_5*getTens(Hs-1);let Zs=this.value+Ws;const zs=getTens(Hs);return Zs=Zs/zs*zs,checkValue(Zs,this.#e,"round"),new FixedNumber(_guard$3,Zs,this.#e)}isZero(){return this.#t===BN_0$8}isNegative(){return this.#t<BN_0$8}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(Ps){return FixedNumber.fromString(this.toString(),Ps)}static fromValue(Ps,Hs,Ws){const Zs=Hs==null?0:getNumber(Hs),zs=getFormat(Ws);let Ys=getBigInt(Ps,"value");const Va=Zs-zs.decimals;if(Va>0){const Xs=getTens(Va);assert(Ys%Xs===BN_0$8,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:Ps}),Ys/=Xs}else Va<0&&(Ys*=getTens(-Va));return checkValue(Ys,zs,"fromValue"),new FixedNumber(_guard$3,Ys,zs)}static fromString(Ps,Hs){const Ws=Ps.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(Ws&&Ws[2].length+Ws[3].length>0,"invalid FixedNumber string value","value",Ps);const Zs=getFormat(Hs);let zs=Ws[2]||"0",Ys=Ws[3]||"";for(;Ys.length<Zs.decimals;)Ys+=Zeros$1;assert(Ys.substring(Zs.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:Ps}),Ys=Ys.substring(0,Zs.decimals);const Va=BigInt(Ws[1]+zs+Ys);return checkValue(Va,Zs,"fromString"),new FixedNumber(_guard$3,Va,Zs)}static fromBytes(Ps,Hs){let Ws=toBigInt(getBytes(Ps,"value"));const Zs=getFormat(Hs);return Zs.signed&&(Ws=fromTwos(Ws,Zs.width)),checkValue(Ws,Zs,"fromBytes"),new FixedNumber(_guard$3,Ws,Zs)}}function hexlifyByte(Fs){let Ps=Fs.toString(16);for(;Ps.length<2;)Ps="0"+Ps;return"0x"+Ps}function unarrayifyInteger(Fs,Ps,Hs){let Ws=0;for(let Zs=0;Zs<Hs;Zs++)Ws=Ws*256+Fs[Ps+Zs];return Ws}function _decodeChildren(Fs,Ps,Hs,Ws){const Zs=[];for(;Hs<Ps+1+Ws;){const zs=_decode(Fs,Hs);Zs.push(zs.result),Hs+=zs.consumed,assert(Hs<=Ps+1+Ws,"child data too short","BUFFER_OVERRUN",{buffer:Fs,length:Ws,offset:Ps})}return{consumed:1+Ws,result:Zs}}function _decode(Fs,Ps){assert(Fs.length!==0,"data too short","BUFFER_OVERRUN",{buffer:Fs,length:0,offset:1});const Hs=Ws=>{assert(Ws<=Fs.length,"data short segment too short","BUFFER_OVERRUN",{buffer:Fs,length:Fs.length,offset:Ws})};if(Fs[Ps]>=248){const Ws=Fs[Ps]-247;Hs(Ps+1+Ws);const Zs=unarrayifyInteger(Fs,Ps+1,Ws);return Hs(Ps+1+Ws+Zs),_decodeChildren(Fs,Ps,Ps+1+Ws,Ws+Zs)}else if(Fs[Ps]>=192){const Ws=Fs[Ps]-192;return Hs(Ps+1+Ws),_decodeChildren(Fs,Ps,Ps+1,Ws)}else if(Fs[Ps]>=184){const Ws=Fs[Ps]-183;Hs(Ps+1+Ws);const Zs=unarrayifyInteger(Fs,Ps+1,Ws);Hs(Ps+1+Ws+Zs);const zs=hexlify(Fs.slice(Ps+1+Ws,Ps+1+Ws+Zs));return{consumed:1+Ws+Zs,result:zs}}else if(Fs[Ps]>=128){const Ws=Fs[Ps]-128;Hs(Ps+1+Ws);const Zs=hexlify(Fs.slice(Ps+1,Ps+1+Ws));return{consumed:1+Ws,result:Zs}}return{consumed:1,result:hexlifyByte(Fs[Ps])}}function decodeRlp(Fs){const Ps=getBytes(Fs,"data"),Hs=_decode(Ps,0);return assertArgument(Hs.consumed===Ps.length,"unexpected junk after rlp payload","data",Fs),Hs.result}function arrayifyInteger(Fs){const Ps=[];for(;Fs;)Ps.unshift(Fs&255),Fs>>=8;return Ps}function _encode(Fs){if(Array.isArray(Fs)){let Ws=[];if(Fs.forEach(function(zs){Ws=Ws.concat(_encode(zs))}),Ws.length<=55)return Ws.unshift(192+Ws.length),Ws;const Zs=arrayifyInteger(Ws.length);return Zs.unshift(247+Zs.length),Zs.concat(Ws)}const Ps=Array.prototype.slice.call(getBytes(Fs,"object"));if(Ps.length===1&&Ps[0]<=127)return Ps;if(Ps.length<=55)return Ps.unshift(128+Ps.length),Ps;const Hs=arrayifyInteger(Ps.length);return Hs.unshift(183+Hs.length),Hs.concat(Ps)}const nibbles="0123456789abcdef";function encodeRlp(Fs){let Ps="0x";for(const Hs of _encode(Fs))Ps+=nibbles[Hs>>4],Ps+=nibbles[Hs&15];return Ps}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(Fs,Ps){let Hs=18;if(typeof Ps=="string"){const Ws=names.indexOf(Ps);assertArgument(Ws>=0,"invalid unit","unit",Ps),Hs=3*Ws}else Ps!=null&&(Hs=getNumber(Ps,"unit"));return FixedNumber.fromValue(Fs,Hs,{decimals:Hs,width:512}).toString()}function parseUnits$1(Fs,Ps){assertArgument(typeof Fs=="string","value must be a string","value",Fs);let Hs=18;if(typeof Ps=="string"){const Ws=names.indexOf(Ps);assertArgument(Ws>=0,"invalid unit","unit",Ps),Hs=3*Ws}else Ps!=null&&(Hs=getNumber(Ps,"unit"));return FixedNumber.fromString(Fs,{decimals:Hs,width:512}).value}const WordSize=32,Padding=new Uint8Array(WordSize),passProperties$1=["then"],_guard$2={},resultNames=new WeakMap;function getNames(Fs){return resultNames.get(Fs)}function setNames(Fs,Ps){resultNames.set(Fs,Ps)}function throwError(Fs,Ps){const Hs=new Error(`deferred error during ABI decoding triggered accessing ${Fs}`);throw Hs.error=Ps,Hs}function toObject(Fs,Ps,Hs){return Fs.indexOf(null)>=0?Ps.map((Ws,Zs)=>Ws instanceof Result$1?toObject(getNames(Ws),Ws,Hs):Ws):Fs.reduce((Ws,Zs,zs)=>{let Ys=Ps.getValue(Zs);return Zs in Ws||(Hs&&Ys instanceof Result$1&&(Ys=toObject(getNames(Ys),Ys,Hs)),Ws[Zs]=Ys),Ws},{})}let Result$1=class mh extends Array{#e;constructor(...Ps){const Hs=Ps[0];let Ws=Ps[1],Zs=(Ps[2]||[]).slice(),zs=!0;Hs!==_guard$2&&(Ws=Ps,Zs=[],zs=!1),super(Ws.length),Ws.forEach((Xs,Ma)=>{this[Ma]=Xs});const Ys=Zs.reduce((Xs,Ma)=>(typeof Ma=="string"&&Xs.set(Ma,(Xs.get(Ma)||0)+1),Xs),new Map);if(setNames(this,Object.freeze(Ws.map((Xs,Ma)=>{const qs=Zs[Ma];return qs!=null&&Ys.get(qs)===1?qs:null}))),this.#e=[],this.#e==null&&this.#e,!zs)return;Object.freeze(this);const Va=new Proxy(this,{get:(Xs,Ma,qs)=>{if(typeof Ma=="string"){if(Ma.match(/^[0-9]+$/)){const Mc=getNumber(Ma,"%index");if(Mc<0||Mc>=this.length)throw new RangeError("out of result range");const ol=Xs[Mc];return ol instanceof Error&&throwError(`index ${Mc}`,ol),ol}if(passProperties$1.indexOf(Ma)>=0)return Reflect.get(Xs,Ma,qs);const Js=Xs[Ma];if(Js instanceof Function)return function(...Mc){return Js.apply(this===qs?Xs:this,Mc)};if(!(Ma in Xs))return Xs.getValue.apply(this===qs?Xs:this,[Ma])}return Reflect.get(Xs,Ma,qs)}});return setNames(Va,getNames(this)),Va}toArray(Ps){const Hs=[];return this.forEach((Ws,Zs)=>{Ws instanceof Error&&throwError(`index ${Zs}`,Ws),Ps&&Ws instanceof mh&&(Ws=Ws.toArray(Ps)),Hs.push(Ws)}),Hs}toObject(Ps){const Hs=getNames(this);return Hs.reduce((Ws,Zs,zs)=>(assert(Zs!=null,`value at index ${zs} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),toObject(Hs,this,Ps)),{})}slice(Ps,Hs){Ps==null&&(Ps=0),Ps<0&&(Ps+=this.length,Ps<0&&(Ps=0)),Hs==null&&(Hs=this.length),Hs<0&&(Hs+=this.length,Hs<0&&(Hs=0)),Hs>this.length&&(Hs=this.length);const Ws=getNames(this),Zs=[],zs=[];for(let Ys=Ps;Ys<Hs;Ys++)Zs.push(this[Ys]),zs.push(Ws[Ys]);return new mh(_guard$2,Zs,zs)}filter(Ps,Hs){const Ws=getNames(this),Zs=[],zs=[];for(let Ys=0;Ys<this.length;Ys++){const Va=this[Ys];Va instanceof Error&&throwError(`index ${Ys}`,Va),Ps.call(Hs,Va,Ys,this)&&(Zs.push(Va),zs.push(Ws[Ys]))}return new mh(_guard$2,Zs,zs)}map(Ps,Hs){const Ws=[];for(let Zs=0;Zs<this.length;Zs++){const zs=this[Zs];zs instanceof Error&&throwError(`index ${Zs}`,zs),Ws.push(Ps.call(Hs,zs,Zs,this))}return Ws}getValue(Ps){const Hs=getNames(this).indexOf(Ps);if(Hs===-1)return;const Ws=this[Hs];return Ws instanceof Error&&throwError(`property ${JSON.stringify(Ps)}`,Ws.error),Ws}static fromItems(Ps,Hs){return new mh(_guard$2,Ps,Hs)}};function getValue$1(Fs){let Ps=toBeArray(Fs);return assert(Ps.length<=WordSize,"value out-of-bounds","BUFFER_OVERRUN",{buffer:Ps,length:WordSize,offset:Ps.length}),Ps.length!==WordSize&&(Ps=getBytesCopy(concat([Padding.slice(Ps.length%WordSize),Ps]))),Ps}class Coder{name;type;localName;dynamic;constructor(Ps,Hs,Ws,Zs){defineProperties(this,{name:Ps,type:Hs,localName:Ws,dynamic:Zs},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(Ps,Hs){assertArgument(!1,Ps,this.localName,Hs)}}class Writer{#e;#t;constructor(){this.#e=[],this.#t=0}get data(){return concat(this.#e)}get length(){return this.#t}#r(Ps){return this.#e.push(Ps),this.#t+=Ps.length,Ps.length}appendWriter(Ps){return this.#r(getBytesCopy(Ps.data))}writeBytes(Ps){let Hs=getBytesCopy(Ps);const Ws=Hs.length%WordSize;return Ws&&(Hs=getBytesCopy(concat([Hs,Padding.slice(Ws)]))),this.#r(Hs)}writeValue(Ps){return this.#r(getValue$1(Ps))}writeUpdatableValue(){const Ps=this.#e.length;return this.#e.push(Padding),this.#t+=WordSize,Hs=>{this.#e[Ps]=getValue$1(Hs)}}}class Reader{allowLoose;#e;#t;#r;#n;#o;constructor(Ps,Hs,Ws){defineProperties(this,{allowLoose:!!Hs}),this.#e=getBytesCopy(Ps),this.#r=0,this.#n=null,this.#o=Ws??1024,this.#t=0}get data(){return hexlify(this.#e)}get dataLength(){return this.#e.length}get consumed(){return this.#t}get bytes(){return new Uint8Array(this.#e)}#s(Ps){if(this.#n)return this.#n.#s(Ps);this.#r+=Ps,assert(this.#o<1||this.#r<=this.#o*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#o} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:getBytesCopy(this.#e),offset:this.#t,length:Ps,info:{bytesRead:this.#r,dataLength:this.dataLength}})}#i(Ps,Hs,Ws){let Zs=Math.ceil(Hs/WordSize)*WordSize;return this.#t+Zs>this.#e.length&&(this.allowLoose&&Ws&&this.#t+Hs<=this.#e.length?Zs=Hs:assert(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#e),length:this.#e.length,offset:this.#t+Zs})),this.#e.slice(this.#t,this.#t+Zs)}subReader(Ps){const Hs=new Reader(this.#e.slice(this.#t+Ps),this.allowLoose,this.#o);return Hs.#n=this,Hs}readBytes(Ps,Hs){let Ws=this.#i(0,Ps,!!Hs);return this.#s(Ps),this.#t+=Ws.length,Ws.slice(0,Ps)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function number(Fs){if(!Number.isSafeInteger(Fs)||Fs<0)throw new Error(`Wrong positive integer: ${Fs}`)}function bytes(Fs,...Ps){if(!(Fs instanceof Uint8Array))throw new Error("Expected Uint8Array");if(Ps.length>0&&!Ps.includes(Fs.length))throw new Error(`Expected Uint8Array of length ${Ps}, not of length=${Fs.length}`)}function hash(Fs){if(typeof Fs!="function"||typeof Fs.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(Fs.outputLen),number(Fs.blockLen)}function exists(Fs,Ps=!0){if(Fs.destroyed)throw new Error("Hash instance has been destroyed");if(Ps&&Fs.finished)throw new Error("Hash#digest() has already been called")}function output(Fs,Ps){bytes(Fs);const Hs=Ps.outputLen;if(Fs.length<Hs)throw new Error(`digestInto() expects output buffer of length at least ${Hs}`)}const crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$1=Fs=>Fs instanceof Uint8Array,u32=Fs=>new Uint32Array(Fs.buffer,Fs.byteOffset,Math.floor(Fs.byteLength/4)),createView=Fs=>new DataView(Fs.buffer,Fs.byteOffset,Fs.byteLength),rotr=(Fs,Ps)=>Fs<<32-Ps|Fs>>>Ps,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$1(Fs){if(typeof Fs!="string")throw new Error(`utf8ToBytes expected string, got ${typeof Fs}`);return new Uint8Array(new TextEncoder().encode(Fs))}function toBytes(Fs){if(typeof Fs=="string"&&(Fs=utf8ToBytes$1(Fs)),!u8a$1(Fs))throw new Error(`expected Uint8Array, got ${typeof Fs}`);return Fs}function concatBytes$1(...Fs){const Ps=new Uint8Array(Fs.reduce((Ws,Zs)=>Ws+Zs.length,0));let Hs=0;return Fs.forEach(Ws=>{if(!u8a$1(Ws))throw new Error("Uint8Array expected");Ps.set(Ws,Hs),Hs+=Ws.length}),Ps}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(Fs){const Ps=Ws=>Fs().update(toBytes(Ws)).digest(),Hs=Fs();return Ps.outputLen=Hs.outputLen,Ps.blockLen=Hs.blockLen,Ps.create=()=>Fs(),Ps}function randomBytes(Fs=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(Fs));throw new Error("crypto.getRandomValues must be defined")}class HMAC extends Hash{constructor(Ps,Hs){super(),this.finished=!1,this.destroyed=!1,hash(Ps);const Ws=toBytes(Hs);if(this.iHash=Ps.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const Zs=this.blockLen,zs=new Uint8Array(Zs);zs.set(Ws.length>Zs?Ps.create().update(Ws).digest():Ws);for(let Ys=0;Ys<zs.length;Ys++)zs[Ys]^=54;this.iHash.update(zs),this.oHash=Ps.create();for(let Ys=0;Ys<zs.length;Ys++)zs[Ys]^=106;this.oHash.update(zs),zs.fill(0)}update(Ps){return exists(this),this.iHash.update(Ps),this}digestInto(Ps){exists(this),bytes(Ps,this.outputLen),this.finished=!0,this.iHash.digestInto(Ps),this.oHash.update(Ps),this.oHash.digestInto(Ps),this.destroy()}digest(){const Ps=new Uint8Array(this.oHash.outputLen);return this.digestInto(Ps),Ps}_cloneInto(Ps){Ps||(Ps=Object.create(Object.getPrototypeOf(this),{}));const{oHash:Hs,iHash:Ws,finished:Zs,destroyed:zs,blockLen:Ys,outputLen:Va}=this;return Ps=Ps,Ps.finished=Zs,Ps.destroyed=zs,Ps.blockLen=Ys,Ps.outputLen=Va,Ps.oHash=Hs._cloneInto(Ps.oHash),Ps.iHash=Ws._cloneInto(Ps.iHash),Ps}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(Fs,Ps,Hs)=>new HMAC(Fs,Ps).update(Hs).digest();hmac.create=(Fs,Ps)=>new HMAC(Fs,Ps);function setBigUint64(Fs,Ps,Hs,Ws){if(typeof Fs.setBigUint64=="function")return Fs.setBigUint64(Ps,Hs,Ws);const Zs=BigInt(32),zs=BigInt(4294967295),Ys=Number(Hs>>Zs&zs),Va=Number(Hs&zs),Xs=Ws?4:0,Ma=Ws?0:4;Fs.setUint32(Ps+Xs,Ys,Ws),Fs.setUint32(Ps+Ma,Va,Ws)}class SHA2 extends Hash{constructor(Ps,Hs,Ws,Zs){super(),this.blockLen=Ps,this.outputLen=Hs,this.padOffset=Ws,this.isLE=Zs,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(Ps),this.view=createView(this.buffer)}update(Ps){exists(this);const{view:Hs,buffer:Ws,blockLen:Zs}=this;Ps=toBytes(Ps);const zs=Ps.length;for(let Ys=0;Ys<zs;){const Va=Math.min(Zs-this.pos,zs-Ys);if(Va===Zs){const Xs=createView(Ps);for(;Zs<=zs-Ys;Ys+=Zs)this.process(Xs,Ys);continue}Ws.set(Ps.subarray(Ys,Ys+Va),this.pos),this.pos+=Va,Ys+=Va,this.pos===Zs&&(this.process(Hs,0),this.pos=0)}return this.length+=Ps.length,this.roundClean(),this}digestInto(Ps){exists(this),output(Ps,this),this.finished=!0;const{buffer:Hs,view:Ws,blockLen:Zs,isLE:zs}=this;let{pos:Ys}=this;Hs[Ys++]=128,this.buffer.subarray(Ys).fill(0),this.padOffset>Zs-Ys&&(this.process(Ws,0),Ys=0);for(let Js=Ys;Js<Zs;Js++)Hs[Js]=0;setBigUint64(Ws,Zs-8,BigInt(this.length*8),zs),this.process(Ws,0);const Va=createView(Ps),Xs=this.outputLen;if(Xs%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const Ma=Xs/4,qs=this.get();if(Ma>qs.length)throw new Error("_sha2: outputLen bigger than state");for(let Js=0;Js<Ma;Js++)Va.setUint32(4*Js,qs[Js],zs)}digest(){const{buffer:Ps,outputLen:Hs}=this;this.digestInto(Ps);const Ws=Ps.slice(0,Hs);return this.destroy(),Ws}_cloneInto(Ps){Ps||(Ps=new this.constructor),Ps.set(...this.get());const{blockLen:Hs,buffer:Ws,length:Zs,finished:zs,destroyed:Ys,pos:Va}=this;return Ps.length=Zs,Ps.pos=Va,Ps.finished=zs,Ps.destroyed=Ys,Zs%Hs&&Ps.buffer.set(Ws),Ps}}const Chi=(Fs,Ps,Hs)=>Fs&Ps^~Fs&Hs,Maj=(Fs,Ps,Hs)=>Fs&Ps^Fs&Hs^Ps&Hs,SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:Ps,B:Hs,C:Ws,D:Zs,E:zs,F:Ys,G:Va,H:Xs}=this;return[Ps,Hs,Ws,Zs,zs,Ys,Va,Xs]}set(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs){this.A=Ps|0,this.B=Hs|0,this.C=Ws|0,this.D=Zs|0,this.E=zs|0,this.F=Ys|0,this.G=Va|0,this.H=Xs|0}process(Ps,Hs){for(let Js=0;Js<16;Js++,Hs+=4)SHA256_W[Js]=Ps.getUint32(Hs,!1);for(let Js=16;Js<64;Js++){const Mc=SHA256_W[Js-15],ol=SHA256_W[Js-2],Vc=rotr(Mc,7)^rotr(Mc,18)^Mc>>>3,Dc=rotr(ol,17)^rotr(ol,19)^ol>>>10;SHA256_W[Js]=Dc+SHA256_W[Js-7]+Vc+SHA256_W[Js-16]|0}let{A:Ws,B:Zs,C:zs,D:Ys,E:Va,F:Xs,G:Ma,H:qs}=this;for(let Js=0;Js<64;Js++){const Mc=rotr(Va,6)^rotr(Va,11)^rotr(Va,25),ol=qs+Mc+Chi(Va,Xs,Ma)+SHA256_K[Js]+SHA256_W[Js]|0,Dc=(rotr(Ws,2)^rotr(Ws,13)^rotr(Ws,22))+Maj(Ws,Zs,zs)|0;qs=Ma,Ma=Xs,Xs=Va,Va=Ys+ol|0,Ys=zs,zs=Zs,Zs=Ws,Ws=ol+Dc|0}Ws=Ws+this.A|0,Zs=Zs+this.B|0,zs=zs+this.C|0,Ys=Ys+this.D|0,Va=Va+this.E|0,Xs=Xs+this.F|0,Ma=Ma+this.G|0,qs=qs+this.H|0,this.set(Ws,Zs,zs,Ys,Va,Xs,Ma,qs)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256),U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(Fs,Ps=!1){return Ps?{h:Number(Fs&U32_MASK64),l:Number(Fs>>_32n&U32_MASK64)}:{h:Number(Fs>>_32n&U32_MASK64)|0,l:Number(Fs&U32_MASK64)|0}}function split$1(Fs,Ps=!1){let Hs=new Uint32Array(Fs.length),Ws=new Uint32Array(Fs.length);for(let Zs=0;Zs<Fs.length;Zs++){const{h:zs,l:Ys}=fromBig(Fs[Zs],Ps);[Hs[Zs],Ws[Zs]]=[zs,Ys]}return[Hs,Ws]}const toBig=(Fs,Ps)=>BigInt(Fs>>>0)<<_32n|BigInt(Ps>>>0),shrSH=(Fs,Ps,Hs)=>Fs>>>Hs,shrSL=(Fs,Ps,Hs)=>Fs<<32-Hs|Ps>>>Hs,rotrSH=(Fs,Ps,Hs)=>Fs>>>Hs|Ps<<32-Hs,rotrSL=(Fs,Ps,Hs)=>Fs<<32-Hs|Ps>>>Hs,rotrBH=(Fs,Ps,Hs)=>Fs<<64-Hs|Ps>>>Hs-32,rotrBL=(Fs,Ps,Hs)=>Fs>>>Hs-32|Ps<<64-Hs,rotr32H=(Fs,Ps)=>Ps,rotr32L=(Fs,Ps)=>Fs,rotlSH=(Fs,Ps,Hs)=>Fs<<Hs|Ps>>>32-Hs,rotlSL=(Fs,Ps,Hs)=>Ps<<Hs|Fs>>>32-Hs,rotlBH=(Fs,Ps,Hs)=>Ps<<Hs-32|Fs>>>64-Hs,rotlBL=(Fs,Ps,Hs)=>Fs<<Hs-32|Ps>>>64-Hs;function add(Fs,Ps,Hs,Ws){const Zs=(Ps>>>0)+(Ws>>>0);return{h:Fs+Hs+(Zs/2**32|0)|0,l:Zs|0}}const add3L=(Fs,Ps,Hs)=>(Fs>>>0)+(Ps>>>0)+(Hs>>>0),add3H=(Fs,Ps,Hs,Ws)=>Ps+Hs+Ws+(Fs/2**32|0)|0,add4L=(Fs,Ps,Hs,Ws)=>(Fs>>>0)+(Ps>>>0)+(Hs>>>0)+(Ws>>>0),add4H=(Fs,Ps,Hs,Ws,Zs)=>Ps+Hs+Ws+Zs+(Fs/2**32|0)|0,add5L=(Fs,Ps,Hs,Ws,Zs)=>(Fs>>>0)+(Ps>>>0)+(Hs>>>0)+(Ws>>>0)+(Zs>>>0),add5H=(Fs,Ps,Hs,Ws,Zs,zs)=>Ps+Hs+Ws+Zs+zs+(Fs/2**32|0)|0,u64={fromBig,split:split$1,toBig,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,rotr32H,rotr32L,rotlSH,rotlSL,rotlBH,rotlBL,add,add3L,add3H,add4L,add4H,add5H,add5L},[SHA512_Kh,SHA512_Kl]=u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(Fs=>BigInt(Fs))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:Ps,Al:Hs,Bh:Ws,Bl:Zs,Ch:zs,Cl:Ys,Dh:Va,Dl:Xs,Eh:Ma,El:qs,Fh:Js,Fl:Mc,Gh:ol,Gl:Vc,Hh:Dc,Hl:sl}=this;return[Ps,Hs,Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl]}set(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl){this.Ah=Ps|0,this.Al=Hs|0,this.Bh=Ws|0,this.Bl=Zs|0,this.Ch=zs|0,this.Cl=Ys|0,this.Dh=Va|0,this.Dl=Xs|0,this.Eh=Ma|0,this.El=qs|0,this.Fh=Js|0,this.Fl=Mc|0,this.Gh=ol|0,this.Gl=Vc|0,this.Hh=Dc|0,this.Hl=sl|0}process(Ps,Hs){for(let pl=0;pl<16;pl++,Hs+=4)SHA512_W_H[pl]=Ps.getUint32(Hs),SHA512_W_L[pl]=Ps.getUint32(Hs+=4);for(let pl=16;pl<80;pl++){const gl=SHA512_W_H[pl-15]|0,yl=SHA512_W_L[pl-15]|0,bl=u64.rotrSH(gl,yl,1)^u64.rotrSH(gl,yl,8)^u64.shrSH(gl,yl,7),Il=u64.rotrSL(gl,yl,1)^u64.rotrSL(gl,yl,8)^u64.shrSL(gl,yl,7),$l=SHA512_W_H[pl-2]|0,vl=SHA512_W_L[pl-2]|0,Sl=u64.rotrSH($l,vl,19)^u64.rotrBH($l,vl,61)^u64.shrSH($l,vl,6),fl=u64.rotrSL($l,vl,19)^u64.rotrBL($l,vl,61)^u64.shrSL($l,vl,6),Hc=u64.add4L(Il,fl,SHA512_W_L[pl-7],SHA512_W_L[pl-16]),tl=u64.add4H(Hc,bl,Sl,SHA512_W_H[pl-7],SHA512_W_H[pl-16]);SHA512_W_H[pl]=tl|0,SHA512_W_L[pl]=Hc|0}let{Ah:Ws,Al:Zs,Bh:zs,Bl:Ys,Ch:Va,Cl:Xs,Dh:Ma,Dl:qs,Eh:Js,El:Mc,Fh:ol,Fl:Vc,Gh:Dc,Gl:sl,Hh:ll,Hl:hl}=this;for(let pl=0;pl<80;pl++){const gl=u64.rotrSH(Js,Mc,14)^u64.rotrSH(Js,Mc,18)^u64.rotrBH(Js,Mc,41),yl=u64.rotrSL(Js,Mc,14)^u64.rotrSL(Js,Mc,18)^u64.rotrBL(Js,Mc,41),bl=Js&ol^~Js&Dc,Il=Mc&Vc^~Mc&sl,$l=u64.add5L(hl,yl,Il,SHA512_Kl[pl],SHA512_W_L[pl]),vl=u64.add5H($l,ll,gl,bl,SHA512_Kh[pl],SHA512_W_H[pl]),Sl=$l|0,fl=u64.rotrSH(Ws,Zs,28)^u64.rotrBH(Ws,Zs,34)^u64.rotrBH(Ws,Zs,39),Hc=u64.rotrSL(Ws,Zs,28)^u64.rotrBL(Ws,Zs,34)^u64.rotrBL(Ws,Zs,39),tl=Ws&zs^Ws&Va^zs&Va,nl=Zs&Ys^Zs&Xs^Ys&Xs;ll=Dc|0,hl=sl|0,Dc=ol|0,sl=Vc|0,ol=Js|0,Vc=Mc|0,{h:Js,l:Mc}=u64.add(Ma|0,qs|0,vl|0,Sl|0),Ma=Va|0,qs=Xs|0,Va=zs|0,Xs=Ys|0,zs=Ws|0,Ys=Zs|0;const rl=u64.add3L(Sl,Hc,nl);Ws=u64.add3H(rl,vl,fl,tl),Zs=rl|0}({h:Ws,l:Zs}=u64.add(this.Ah|0,this.Al|0,Ws|0,Zs|0)),{h:zs,l:Ys}=u64.add(this.Bh|0,this.Bl|0,zs|0,Ys|0),{h:Va,l:Xs}=u64.add(this.Ch|0,this.Cl|0,Va|0,Xs|0),{h:Ma,l:qs}=u64.add(this.Dh|0,this.Dl|0,Ma|0,qs|0),{h:Js,l:Mc}=u64.add(this.Eh|0,this.El|0,Js|0,Mc|0),{h:ol,l:Vc}=u64.add(this.Fh|0,this.Fl|0,ol|0,Vc|0),{h:Dc,l:sl}=u64.add(this.Gh|0,this.Gl|0,Dc|0,sl|0),{h:ll,l:hl}=u64.add(this.Hh|0,this.Hl|0,ll|0,hl|0),this.set(Ws,Zs,zs,Ys,Va,Xs,Ma,qs,Js,Mc,ol,Vc,Dc,sl,ll,hl)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512=wrapConstructor(()=>new SHA512);function getGlobal(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global$1<"u")return global$1;throw new Error("unable to locate global object")}const anyGlobal=getGlobal();anyGlobal.crypto||anyGlobal.msCrypto;function createHash(Fs){switch(Fs){case"sha256":return sha256$1.create();case"sha512":return sha512.create()}assertArgument(!1,"invalid hashing algorithm name","algorithm",Fs)}const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]],_0n$4=BigInt(0),_1n$5=BigInt(1),_2n$3=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113);for(let Fs=0,Ps=_1n$5,Hs=1,Ws=0;Fs<24;Fs++){[Hs,Ws]=[Ws,(2*Hs+3*Ws)%5],SHA3_PI.push(2*(5*Ws+Hs)),SHA3_ROTL.push((Fs+1)*(Fs+2)/2%64);let Zs=_0n$4;for(let zs=0;zs<7;zs++)Ps=(Ps<<_1n$5^(Ps>>_7n)*_0x71n)%_256n,Ps&_2n$3&&(Zs^=_1n$5<<(_1n$5<<BigInt(zs))-_1n$5);_SHA3_IOTA.push(Zs)}const[SHA3_IOTA_H,SHA3_IOTA_L]=split$1(_SHA3_IOTA,!0),rotlH=(Fs,Ps,Hs)=>Hs>32?rotlBH(Fs,Ps,Hs):rotlSH(Fs,Ps,Hs),rotlL=(Fs,Ps,Hs)=>Hs>32?rotlBL(Fs,Ps,Hs):rotlSL(Fs,Ps,Hs);function keccakP(Fs,Ps=24){const Hs=new Uint32Array(10);for(let Ws=24-Ps;Ws<24;Ws++){for(let Ys=0;Ys<10;Ys++)Hs[Ys]=Fs[Ys]^Fs[Ys+10]^Fs[Ys+20]^Fs[Ys+30]^Fs[Ys+40];for(let Ys=0;Ys<10;Ys+=2){const Va=(Ys+8)%10,Xs=(Ys+2)%10,Ma=Hs[Xs],qs=Hs[Xs+1],Js=rotlH(Ma,qs,1)^Hs[Va],Mc=rotlL(Ma,qs,1)^Hs[Va+1];for(let ol=0;ol<50;ol+=10)Fs[Ys+ol]^=Js,Fs[Ys+ol+1]^=Mc}let Zs=Fs[2],zs=Fs[3];for(let Ys=0;Ys<24;Ys++){const Va=SHA3_ROTL[Ys],Xs=rotlH(Zs,zs,Va),Ma=rotlL(Zs,zs,Va),qs=SHA3_PI[Ys];Zs=Fs[qs],zs=Fs[qs+1],Fs[qs]=Xs,Fs[qs+1]=Ma}for(let Ys=0;Ys<50;Ys+=10){for(let Va=0;Va<10;Va++)Hs[Va]=Fs[Ys+Va];for(let Va=0;Va<10;Va++)Fs[Ys+Va]^=~Hs[(Va+2)%10]&Hs[(Va+4)%10]}Fs[0]^=SHA3_IOTA_H[Ws],Fs[1]^=SHA3_IOTA_L[Ws]}Hs.fill(0)}class Keccak extends Hash{constructor(Ps,Hs,Ws,Zs=!1,zs=24){if(super(),this.blockLen=Ps,this.suffix=Hs,this.outputLen=Ws,this.enableXOF=Zs,this.rounds=zs,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,number(Ws),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds),this.posOut=0,this.pos=0}update(Ps){exists(this);const{blockLen:Hs,state:Ws}=this;Ps=toBytes(Ps);const Zs=Ps.length;for(let zs=0;zs<Zs;){const Ys=Math.min(Hs-this.pos,Zs-zs);for(let Va=0;Va<Ys;Va++)Ws[this.pos++]^=Ps[zs++];this.pos===Hs&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:Ps,suffix:Hs,pos:Ws,blockLen:Zs}=this;Ps[Ws]^=Hs,(Hs&128)!==0&&Ws===Zs-1&&this.keccak(),Ps[Zs-1]^=128,this.keccak()}writeInto(Ps){exists(this,!1),bytes(Ps),this.finish();const Hs=this.state,{blockLen:Ws}=this;for(let Zs=0,zs=Ps.length;Zs<zs;){this.posOut>=Ws&&this.keccak();const Ys=Math.min(Ws-this.posOut,zs-Zs);Ps.set(Hs.subarray(this.posOut,this.posOut+Ys),Zs),this.posOut+=Ys,Zs+=Ys}return Ps}xofInto(Ps){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(Ps)}xof(Ps){return number(Ps),this.xofInto(new Uint8Array(Ps))}digestInto(Ps){if(output(Ps,this),this.finished)throw new Error("digest() was already called");return this.writeInto(Ps),this.destroy(),Ps}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(Ps){const{blockLen:Hs,suffix:Ws,outputLen:Zs,rounds:zs,enableXOF:Ys}=this;return Ps||(Ps=new Keccak(Hs,Ws,Zs,Ys,zs)),Ps.state32.set(this.state32),Ps.pos=this.pos,Ps.posOut=this.posOut,Ps.finished=this.finished,Ps.rounds=zs,Ps.suffix=Ws,Ps.outputLen=Zs,Ps.enableXOF=Ys,Ps.destroyed=this.destroyed,Ps}}const gen=(Fs,Ps,Hs)=>wrapConstructor(()=>new Keccak(Ps,Fs,Hs)),keccak_256=gen(1,136,256/8);let locked=!1;const _keccak256=function(Fs){return keccak_256(Fs)};let __keccak256=_keccak256;function keccak256(Fs){const Ps=getBytes(Fs,"data");return hexlify(__keccak256(Ps))}keccak256._=_keccak256,keccak256.lock=function(){locked=!0},keccak256.register=function(Fs){if(locked)throw new TypeError("keccak256 is locked");__keccak256=Fs},Object.freeze(keccak256);const _sha256=function(Fs){return createHash("sha256").update(Fs).digest()};let __sha256=_sha256,locked256=!1;function sha256(Fs){const Ps=getBytes(Fs,"data");return hexlify(__sha256(Ps))}sha256._=_sha256,sha256.lock=function(){locked256=!0},sha256.register=function(Fs){if(locked256)throw new Error("sha256 is locked");__sha256=Fs},Object.freeze(sha256),Object.freeze(sha256);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),u8a=Fs=>Fs instanceof Uint8Array,hexes=Array.from({length:256},(Fs,Ps)=>Ps.toString(16).padStart(2,"0"));function bytesToHex(Fs){if(!u8a(Fs))throw new Error("Uint8Array expected");let Ps="";for(let Hs=0;Hs<Fs.length;Hs++)Ps+=hexes[Fs[Hs]];return Ps}function numberToHexUnpadded(Fs){const Ps=Fs.toString(16);return Ps.length&1?`0${Ps}`:Ps}function hexToNumber(Fs){if(typeof Fs!="string")throw new Error("hex string expected, got "+typeof Fs);return BigInt(Fs===""?"0":`0x${Fs}`)}function hexToBytes(Fs){if(typeof Fs!="string")throw new Error("hex string expected, got "+typeof Fs);const Ps=Fs.length;if(Ps%2)throw new Error("padded hex string expected, got unpadded hex of length "+Ps);const Hs=new Uint8Array(Ps/2);for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Ws*2,zs=Fs.slice(Zs,Zs+2),Ys=Number.parseInt(zs,16);if(Number.isNaN(Ys)||Ys<0)throw new Error("Invalid byte sequence");Hs[Ws]=Ys}return Hs}function bytesToNumberBE(Fs){return hexToNumber(bytesToHex(Fs))}function bytesToNumberLE(Fs){if(!u8a(Fs))throw new Error("Uint8Array expected");return hexToNumber(bytesToHex(Uint8Array.from(Fs).reverse()))}function numberToBytesBE(Fs,Ps){return hexToBytes(Fs.toString(16).padStart(Ps*2,"0"))}function numberToBytesLE(Fs,Ps){return numberToBytesBE(Fs,Ps).reverse()}function numberToVarBytesBE(Fs){return hexToBytes(numberToHexUnpadded(Fs))}function ensureBytes(Fs,Ps,Hs){let Ws;if(typeof Ps=="string")try{Ws=hexToBytes(Ps)}catch(zs){throw new Error(`${Fs} must be valid hex string, got "${Ps}". Cause: ${zs}`)}else if(u8a(Ps))Ws=Uint8Array.from(Ps);else throw new Error(`${Fs} must be hex string or Uint8Array`);const Zs=Ws.length;if(typeof Hs=="number"&&Zs!==Hs)throw new Error(`${Fs} expected ${Hs} bytes, got ${Zs}`);return Ws}function concatBytes(...Fs){const Ps=new Uint8Array(Fs.reduce((Ws,Zs)=>Ws+Zs.length,0));let Hs=0;return Fs.forEach(Ws=>{if(!u8a(Ws))throw new Error("Uint8Array expected");Ps.set(Ws,Hs),Hs+=Ws.length}),Ps}function equalBytes(Fs,Ps){if(Fs.length!==Ps.length)return!1;for(let Hs=0;Hs<Fs.length;Hs++)if(Fs[Hs]!==Ps[Hs])return!1;return!0}function utf8ToBytes(Fs){if(typeof Fs!="string")throw new Error(`utf8ToBytes expected string, got ${typeof Fs}`);return new Uint8Array(new TextEncoder().encode(Fs))}function bitLen(Fs){let Ps;for(Ps=0;Fs>_0n$3;Fs>>=_1n$4,Ps+=1);return Ps}function bitGet(Fs,Ps){return Fs>>BigInt(Ps)&_1n$4}const bitSet=(Fs,Ps,Hs)=>Fs|(Hs?_1n$4:_0n$3)<<BigInt(Ps),bitMask=Fs=>(_2n$2<<BigInt(Fs-1))-_1n$4,u8n=Fs=>new Uint8Array(Fs),u8fr=Fs=>Uint8Array.from(Fs);function createHmacDrbg(Fs,Ps,Hs){if(typeof Fs!="number"||Fs<2)throw new Error("hashLen must be a number");if(typeof Ps!="number"||Ps<2)throw new Error("qByteLen must be a number");if(typeof Hs!="function")throw new Error("hmacFn must be a function");let Ws=u8n(Fs),Zs=u8n(Fs),zs=0;const Ys=()=>{Ws.fill(1),Zs.fill(0),zs=0},Va=(...Js)=>Hs(Zs,Ws,...Js),Xs=(Js=u8n())=>{Zs=Va(u8fr([0]),Js),Ws=Va(),Js.length!==0&&(Zs=Va(u8fr([1]),Js),Ws=Va())},Ma=()=>{if(zs++>=1e3)throw new Error("drbg: tried 1000 values");let Js=0;const Mc=[];for(;Js<Ps;){Ws=Va();const ol=Ws.slice();Mc.push(ol),Js+=Ws.length}return concatBytes(...Mc)};return(Js,Mc)=>{Ys(),Xs(Js);let ol;for(;!(ol=Mc(Ma()));)Xs();return Ys(),ol}}const validatorFns={bigint:Fs=>typeof Fs=="bigint",function:Fs=>typeof Fs=="function",boolean:Fs=>typeof Fs=="boolean",string:Fs=>typeof Fs=="string",stringOrUint8Array:Fs=>typeof Fs=="string"||Fs instanceof Uint8Array,isSafeInteger:Fs=>Number.isSafeInteger(Fs),array:Fs=>Array.isArray(Fs),field:(Fs,Ps)=>Ps.Fp.isValid(Fs),hash:Fs=>typeof Fs=="function"&&Number.isSafeInteger(Fs.outputLen)};function validateObject(Fs,Ps,Hs={}){const Ws=(Zs,zs,Ys)=>{const Va=validatorFns[zs];if(typeof Va!="function")throw new Error(`Invalid validator "${zs}", expected function`);const Xs=Fs[Zs];if(!(Ys&&Xs===void 0)&&!Va(Xs,Fs))throw new Error(`Invalid param ${String(Zs)}=${Xs} (${typeof Xs}), expected ${zs}`)};for(const[Zs,zs]of Object.entries(Ps))Ws(Zs,zs,!1);for(const[Zs,zs]of Object.entries(Hs))Ws(Zs,zs,!0);return Fs}const ut=Object.freeze(Object.defineProperty({__proto__:null,bitGet,bitLen,bitMask,bitSet,bytesToHex,bytesToNumberBE,bytesToNumberLE,concatBytes,createHmacDrbg,ensureBytes,equalBytes,hexToBytes,hexToNumber,numberToBytesBE,numberToBytesLE,numberToHexUnpadded,numberToVarBytesBE,utf8ToBytes,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$3=BigInt(1),_2n$1=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);BigInt(9),BigInt(16);function mod(Fs,Ps){const Hs=Fs%Ps;return Hs>=_0n$2?Hs:Ps+Hs}function pow(Fs,Ps,Hs){if(Hs<=_0n$2||Ps<_0n$2)throw new Error("Expected power/modulo > 0");if(Hs===_1n$3)return _0n$2;let Ws=_1n$3;for(;Ps>_0n$2;)Ps&_1n$3&&(Ws=Ws*Fs%Hs),Fs=Fs*Fs%Hs,Ps>>=_1n$3;return Ws}function pow2(Fs,Ps,Hs){let Ws=Fs;for(;Ps-- >_0n$2;)Ws*=Ws,Ws%=Hs;return Ws}function invert(Fs,Ps){if(Fs===_0n$2||Ps<=_0n$2)throw new Error(`invert: expected positive integers, got n=${Fs} mod=${Ps}`);let Hs=mod(Fs,Ps),Ws=Ps,Zs=_0n$2,zs=_1n$3;for(;Hs!==_0n$2;){const Va=Ws/Hs,Xs=Ws%Hs,Ma=Zs-zs*Va;Ws=Hs,Hs=Xs,Zs=zs,zs=Ma}if(Ws!==_1n$3)throw new Error("invert: does not exist");return mod(Zs,Ps)}function tonelliShanks(Fs){const Ps=(Fs-_1n$3)/_2n$1;let Hs,Ws,Zs;for(Hs=Fs-_1n$3,Ws=0;Hs%_2n$1===_0n$2;Hs/=_2n$1,Ws++);for(Zs=_2n$1;Zs<Fs&&pow(Zs,Ps,Fs)!==Fs-_1n$3;Zs++);if(Ws===1){const Ys=(Fs+_1n$3)/_4n;return function(Xs,Ma){const qs=Xs.pow(Ma,Ys);if(!Xs.eql(Xs.sqr(qs),Ma))throw new Error("Cannot find square root");return qs}}const zs=(Hs+_1n$3)/_2n$1;return function(Va,Xs){if(Va.pow(Xs,Ps)===Va.neg(Va.ONE))throw new Error("Cannot find square root");let Ma=Ws,qs=Va.pow(Va.mul(Va.ONE,Zs),Hs),Js=Va.pow(Xs,zs),Mc=Va.pow(Xs,Hs);for(;!Va.eql(Mc,Va.ONE);){if(Va.eql(Mc,Va.ZERO))return Va.ZERO;let ol=1;for(let Dc=Va.sqr(Mc);ol<Ma&&!Va.eql(Dc,Va.ONE);ol++)Dc=Va.sqr(Dc);const Vc=Va.pow(qs,_1n$3<<BigInt(Ma-ol-1));qs=Va.sqr(Vc),Js=Va.mul(Js,Vc),Mc=Va.mul(Mc,qs),Ma=ol}return Js}}function FpSqrt(Fs){if(Fs%_4n===_3n$1){const Ps=(Fs+_1n$3)/_4n;return function(Ws,Zs){const zs=Ws.pow(Zs,Ps);if(!Ws.eql(Ws.sqr(zs),Zs))throw new Error("Cannot find square root");return zs}}if(Fs%_8n===_5n){const Ps=(Fs-_5n)/_8n;return function(Ws,Zs){const zs=Ws.mul(Zs,_2n$1),Ys=Ws.pow(zs,Ps),Va=Ws.mul(Zs,Ys),Xs=Ws.mul(Ws.mul(Va,_2n$1),Ys),Ma=Ws.mul(Va,Ws.sub(Xs,Ws.ONE));if(!Ws.eql(Ws.sqr(Ma),Zs))throw new Error("Cannot find square root");return Ma}}return tonelliShanks(Fs)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(Fs){const Ps={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Hs=FIELD_FIELDS.reduce((Ws,Zs)=>(Ws[Zs]="function",Ws),Ps);return validateObject(Fs,Hs)}function FpPow(Fs,Ps,Hs){if(Hs<_0n$2)throw new Error("Expected power > 0");if(Hs===_0n$2)return Fs.ONE;if(Hs===_1n$3)return Ps;let Ws=Fs.ONE,Zs=Ps;for(;Hs>_0n$2;)Hs&_1n$3&&(Ws=Fs.mul(Ws,Zs)),Zs=Fs.sqr(Zs),Hs>>=_1n$3;return Ws}function FpInvertBatch(Fs,Ps){const Hs=new Array(Ps.length),Ws=Ps.reduce((zs,Ys,Va)=>Fs.is0(Ys)?zs:(Hs[Va]=zs,Fs.mul(zs,Ys)),Fs.ONE),Zs=Fs.inv(Ws);return Ps.reduceRight((zs,Ys,Va)=>Fs.is0(Ys)?zs:(Hs[Va]=Fs.mul(zs,Hs[Va]),Fs.mul(zs,Ys)),Zs),Hs}function nLength(Fs,Ps){const Hs=Ps!==void 0?Ps:Fs.toString(2).length,Ws=Math.ceil(Hs/8);return{nBitLength:Hs,nByteLength:Ws}}function Field(Fs,Ps,Hs=!1,Ws={}){if(Fs<=_0n$2)throw new Error(`Expected Field ORDER > 0, got ${Fs}`);const{nBitLength:Zs,nByteLength:zs}=nLength(Fs,Ps);if(zs>2048)throw new Error("Field lengths over 2048 bytes are not supported");const Ys=FpSqrt(Fs),Va=Object.freeze({ORDER:Fs,BITS:Zs,BYTES:zs,MASK:bitMask(Zs),ZERO:_0n$2,ONE:_1n$3,create:Xs=>mod(Xs,Fs),isValid:Xs=>{if(typeof Xs!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof Xs}`);return _0n$2<=Xs&&Xs<Fs},is0:Xs=>Xs===_0n$2,isOdd:Xs=>(Xs&_1n$3)===_1n$3,neg:Xs=>mod(-Xs,Fs),eql:(Xs,Ma)=>Xs===Ma,sqr:Xs=>mod(Xs*Xs,Fs),add:(Xs,Ma)=>mod(Xs+Ma,Fs),sub:(Xs,Ma)=>mod(Xs-Ma,Fs),mul:(Xs,Ma)=>mod(Xs*Ma,Fs),pow:(Xs,Ma)=>FpPow(Va,Xs,Ma),div:(Xs,Ma)=>mod(Xs*invert(Ma,Fs),Fs),sqrN:Xs=>Xs*Xs,addN:(Xs,Ma)=>Xs+Ma,subN:(Xs,Ma)=>Xs-Ma,mulN:(Xs,Ma)=>Xs*Ma,inv:Xs=>invert(Xs,Fs),sqrt:Ws.sqrt||(Xs=>Ys(Va,Xs)),invertBatch:Xs=>FpInvertBatch(Va,Xs),cmov:(Xs,Ma,qs)=>qs?Ma:Xs,toBytes:Xs=>Hs?numberToBytesLE(Xs,zs):numberToBytesBE(Xs,zs),fromBytes:Xs=>{if(Xs.length!==zs)throw new Error(`Fp.fromBytes: expected ${zs}, got ${Xs.length}`);return Hs?bytesToNumberLE(Xs):bytesToNumberBE(Xs)}});return Object.freeze(Va)}function getFieldBytesLength(Fs){if(typeof Fs!="bigint")throw new Error("field order must be bigint");const Ps=Fs.toString(2).length;return Math.ceil(Ps/8)}function getMinHashLength(Fs){const Ps=getFieldBytesLength(Fs);return Ps+Math.ceil(Ps/2)}function mapHashToField(Fs,Ps,Hs=!1){const Ws=Fs.length,Zs=getFieldBytesLength(Ps),zs=getMinHashLength(Ps);if(Ws<16||Ws<zs||Ws>1024)throw new Error(`expected ${zs}-1024 bytes of input, got ${Ws}`);const Ys=Hs?bytesToNumberBE(Fs):bytesToNumberLE(Fs),Va=mod(Ys,Ps-_1n$3)+_1n$3;return Hs?numberToBytesLE(Va,Zs):numberToBytesBE(Va,Zs)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$2=BigInt(1);function wNAF(Fs,Ps){const Hs=(Zs,zs)=>{const Ys=zs.negate();return Zs?Ys:zs},Ws=Zs=>{const zs=Math.ceil(Ps/Zs)+1,Ys=2**(Zs-1);return{windows:zs,windowSize:Ys}};return{constTimeNegate:Hs,unsafeLadder(Zs,zs){let Ys=Fs.ZERO,Va=Zs;for(;zs>_0n$1;)zs&_1n$2&&(Ys=Ys.add(Va)),Va=Va.double(),zs>>=_1n$2;return Ys},precomputeWindow(Zs,zs){const{windows:Ys,windowSize:Va}=Ws(zs),Xs=[];let Ma=Zs,qs=Ma;for(let Js=0;Js<Ys;Js++){qs=Ma,Xs.push(qs);for(let Mc=1;Mc<Va;Mc++)qs=qs.add(Ma),Xs.push(qs);Ma=qs.double()}return Xs},wNAF(Zs,zs,Ys){const{windows:Va,windowSize:Xs}=Ws(Zs);let Ma=Fs.ZERO,qs=Fs.BASE;const Js=BigInt(2**Zs-1),Mc=2**Zs,ol=BigInt(Zs);for(let Vc=0;Vc<Va;Vc++){const Dc=Vc*Xs;let sl=Number(Ys&Js);Ys>>=ol,sl>Xs&&(sl-=Mc,Ys+=_1n$2);const ll=Dc,hl=Dc+Math.abs(sl)-1,pl=Vc%2!==0,gl=sl<0;sl===0?qs=qs.add(Hs(pl,zs[ll])):Ma=Ma.add(Hs(gl,zs[hl]))}return{p:Ma,f:qs}},wNAFCached(Zs,zs,Ys,Va){const Xs=Zs._WINDOW_SIZE||1;let Ma=zs.get(Zs);return Ma||(Ma=this.precomputeWindow(Zs,Xs),Xs!==1&&zs.set(Zs,Va(Ma))),this.wNAF(Xs,Ma,Ys)}}}function validateBasic(Fs){return validateField(Fs.Fp),validateObject(Fs,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(Fs.n,Fs.nBitLength),...Fs,p:Fs.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(Fs){const Ps=validateBasic(Fs);validateObject(Ps,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:Hs,Fp:Ws,a:Zs}=Ps;if(Hs){if(!Ws.eql(Zs,Ws.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof Hs!="object"||typeof Hs.beta!="bigint"||typeof Hs.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...Ps})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER={Err:class extends Error{constructor(Ps=""){super(Ps)}},_parseInt(Fs){const{Err:Ps}=DER;if(Fs.length<2||Fs[0]!==2)throw new Ps("Invalid signature integer tag");const Hs=Fs[1],Ws=Fs.subarray(2,Hs+2);if(!Hs||Ws.length!==Hs)throw new Ps("Invalid signature integer: wrong length");if(Ws[0]&128)throw new Ps("Invalid signature integer: negative");if(Ws[0]===0&&!(Ws[1]&128))throw new Ps("Invalid signature integer: unnecessary leading zero");return{d:b2n(Ws),l:Fs.subarray(Hs+2)}},toSig(Fs){const{Err:Ps}=DER,Hs=typeof Fs=="string"?h2b(Fs):Fs;if(!(Hs instanceof Uint8Array))throw new Error("ui8a expected");let Ws=Hs.length;if(Ws<2||Hs[0]!=48)throw new Ps("Invalid signature tag");if(Hs[1]!==Ws-2)throw new Ps("Invalid signature: incorrect length");const{d:Zs,l:zs}=DER._parseInt(Hs.subarray(2)),{d:Ys,l:Va}=DER._parseInt(zs);if(Va.length)throw new Ps("Invalid signature: left bytes after parsing");return{r:Zs,s:Ys}},hexFromSig(Fs){const Ps=Ma=>Number.parseInt(Ma[0],16)&8?"00"+Ma:Ma,Hs=Ma=>{const qs=Ma.toString(16);return qs.length&1?`0${qs}`:qs},Ws=Ps(Hs(Fs.s)),Zs=Ps(Hs(Fs.r)),zs=Ws.length/2,Ys=Zs.length/2,Va=Hs(zs),Xs=Hs(Ys);return`30${Hs(Ys+zs+4)}02${Xs}${Zs}02${Va}${Ws}`}},_0n=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(Fs){const Ps=validatePointOpts(Fs),{Fp:Hs}=Ps,Ws=Ps.toBytes||((Vc,Dc,sl)=>{const ll=Dc.toAffine();return concatBytes(Uint8Array.from([4]),Hs.toBytes(ll.x),Hs.toBytes(ll.y))}),Zs=Ps.fromBytes||(Vc=>{const Dc=Vc.subarray(1),sl=Hs.fromBytes(Dc.subarray(0,Hs.BYTES)),ll=Hs.fromBytes(Dc.subarray(Hs.BYTES,2*Hs.BYTES));return{x:sl,y:ll}});function zs(Vc){const{a:Dc,b:sl}=Ps,ll=Hs.sqr(Vc),hl=Hs.mul(ll,Vc);return Hs.add(Hs.add(hl,Hs.mul(Vc,Dc)),sl)}if(!Hs.eql(Hs.sqr(Ps.Gy),zs(Ps.Gx)))throw new Error("bad generator point: equation left != right");function Ys(Vc){return typeof Vc=="bigint"&&_0n<Vc&&Vc<Ps.n}function Va(Vc){if(!Ys(Vc))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function Xs(Vc){const{allowedPrivateKeyLengths:Dc,nByteLength:sl,wrapPrivateKey:ll,n:hl}=Ps;if(Dc&&typeof Vc!="bigint"){if(Vc instanceof Uint8Array&&(Vc=bytesToHex(Vc)),typeof Vc!="string"||!Dc.includes(Vc.length))throw new Error("Invalid key");Vc=Vc.padStart(sl*2,"0")}let pl;try{pl=typeof Vc=="bigint"?Vc:bytesToNumberBE(ensureBytes("private key",Vc,sl))}catch{throw new Error(`private key must be ${sl} bytes, hex or bigint, not ${typeof Vc}`)}return ll&&(pl=mod(pl,hl)),Va(pl),pl}const Ma=new Map;function qs(Vc){if(!(Vc instanceof Js))throw new Error("ProjectivePoint expected")}class Js{constructor(Dc,sl,ll){if(this.px=Dc,this.py=sl,this.pz=ll,Dc==null||!Hs.isValid(Dc))throw new Error("x required");if(sl==null||!Hs.isValid(sl))throw new Error("y required");if(ll==null||!Hs.isValid(ll))throw new Error("z required")}static fromAffine(Dc){const{x:sl,y:ll}=Dc||{};if(!Dc||!Hs.isValid(sl)||!Hs.isValid(ll))throw new Error("invalid affine point");if(Dc instanceof Js)throw new Error("projective point not allowed");const hl=pl=>Hs.eql(pl,Hs.ZERO);return hl(sl)&&hl(ll)?Js.ZERO:new Js(sl,ll,Hs.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(Dc){const sl=Hs.invertBatch(Dc.map(ll=>ll.pz));return Dc.map((ll,hl)=>ll.toAffine(sl[hl])).map(Js.fromAffine)}static fromHex(Dc){const sl=Js.fromAffine(Zs(ensureBytes("pointHex",Dc)));return sl.assertValidity(),sl}static fromPrivateKey(Dc){return Js.BASE.multiply(Xs(Dc))}_setWindowSize(Dc){this._WINDOW_SIZE=Dc,Ma.delete(this)}assertValidity(){if(this.is0()){if(Ps.allowInfinityPoint&&!Hs.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:Dc,y:sl}=this.toAffine();if(!Hs.isValid(Dc)||!Hs.isValid(sl))throw new Error("bad point: x or y not FE");const ll=Hs.sqr(sl),hl=zs(Dc);if(!Hs.eql(ll,hl))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:Dc}=this.toAffine();if(Hs.isOdd)return!Hs.isOdd(Dc);throw new Error("Field doesn't support isOdd")}equals(Dc){qs(Dc);const{px:sl,py:ll,pz:hl}=this,{px:pl,py:gl,pz:yl}=Dc,bl=Hs.eql(Hs.mul(sl,yl),Hs.mul(pl,hl)),Il=Hs.eql(Hs.mul(ll,yl),Hs.mul(gl,hl));return bl&&Il}negate(){return new Js(this.px,Hs.neg(this.py),this.pz)}double(){const{a:Dc,b:sl}=Ps,ll=Hs.mul(sl,_3n),{px:hl,py:pl,pz:gl}=this;let yl=Hs.ZERO,bl=Hs.ZERO,Il=Hs.ZERO,$l=Hs.mul(hl,hl),vl=Hs.mul(pl,pl),Sl=Hs.mul(gl,gl),fl=Hs.mul(hl,pl);return fl=Hs.add(fl,fl),Il=Hs.mul(hl,gl),Il=Hs.add(Il,Il),yl=Hs.mul(Dc,Il),bl=Hs.mul(ll,Sl),bl=Hs.add(yl,bl),yl=Hs.sub(vl,bl),bl=Hs.add(vl,bl),bl=Hs.mul(yl,bl),yl=Hs.mul(fl,yl),Il=Hs.mul(ll,Il),Sl=Hs.mul(Dc,Sl),fl=Hs.sub($l,Sl),fl=Hs.mul(Dc,fl),fl=Hs.add(fl,Il),Il=Hs.add($l,$l),$l=Hs.add(Il,$l),$l=Hs.add($l,Sl),$l=Hs.mul($l,fl),bl=Hs.add(bl,$l),Sl=Hs.mul(pl,gl),Sl=Hs.add(Sl,Sl),$l=Hs.mul(Sl,fl),yl=Hs.sub(yl,$l),Il=Hs.mul(Sl,vl),Il=Hs.add(Il,Il),Il=Hs.add(Il,Il),new Js(yl,bl,Il)}add(Dc){qs(Dc);const{px:sl,py:ll,pz:hl}=this,{px:pl,py:gl,pz:yl}=Dc;let bl=Hs.ZERO,Il=Hs.ZERO,$l=Hs.ZERO;const vl=Ps.a,Sl=Hs.mul(Ps.b,_3n);let fl=Hs.mul(sl,pl),Hc=Hs.mul(ll,gl),tl=Hs.mul(hl,yl),nl=Hs.add(sl,ll),rl=Hs.add(pl,gl);nl=Hs.mul(nl,rl),rl=Hs.add(fl,Hc),nl=Hs.sub(nl,rl),rl=Hs.add(sl,hl);let il=Hs.add(pl,yl);return rl=Hs.mul(rl,il),il=Hs.add(fl,tl),rl=Hs.sub(rl,il),il=Hs.add(ll,hl),bl=Hs.add(gl,yl),il=Hs.mul(il,bl),bl=Hs.add(Hc,tl),il=Hs.sub(il,bl),$l=Hs.mul(vl,rl),bl=Hs.mul(Sl,tl),$l=Hs.add(bl,$l),bl=Hs.sub(Hc,$l),$l=Hs.add(Hc,$l),Il=Hs.mul(bl,$l),Hc=Hs.add(fl,fl),Hc=Hs.add(Hc,fl),tl=Hs.mul(vl,tl),rl=Hs.mul(Sl,rl),Hc=Hs.add(Hc,tl),tl=Hs.sub(fl,tl),tl=Hs.mul(vl,tl),rl=Hs.add(rl,tl),fl=Hs.mul(Hc,rl),Il=Hs.add(Il,fl),fl=Hs.mul(il,rl),bl=Hs.mul(nl,bl),bl=Hs.sub(bl,fl),fl=Hs.mul(nl,Hc),$l=Hs.mul(il,$l),$l=Hs.add($l,fl),new Js(bl,Il,$l)}subtract(Dc){return this.add(Dc.negate())}is0(){return this.equals(Js.ZERO)}wNAF(Dc){return ol.wNAFCached(this,Ma,Dc,sl=>{const ll=Hs.invertBatch(sl.map(hl=>hl.pz));return sl.map((hl,pl)=>hl.toAffine(ll[pl])).map(Js.fromAffine)})}multiplyUnsafe(Dc){const sl=Js.ZERO;if(Dc===_0n)return sl;if(Va(Dc),Dc===_1n$1)return this;const{endo:ll}=Ps;if(!ll)return ol.unsafeLadder(this,Dc);let{k1neg:hl,k1:pl,k2neg:gl,k2:yl}=ll.splitScalar(Dc),bl=sl,Il=sl,$l=this;for(;pl>_0n||yl>_0n;)pl&_1n$1&&(bl=bl.add($l)),yl&_1n$1&&(Il=Il.add($l)),$l=$l.double(),pl>>=_1n$1,yl>>=_1n$1;return hl&&(bl=bl.negate()),gl&&(Il=Il.negate()),Il=new Js(Hs.mul(Il.px,ll.beta),Il.py,Il.pz),bl.add(Il)}multiply(Dc){Va(Dc);let sl=Dc,ll,hl;const{endo:pl}=Ps;if(pl){const{k1neg:gl,k1:yl,k2neg:bl,k2:Il}=pl.splitScalar(sl);let{p:$l,f:vl}=this.wNAF(yl),{p:Sl,f:fl}=this.wNAF(Il);$l=ol.constTimeNegate(gl,$l),Sl=ol.constTimeNegate(bl,Sl),Sl=new Js(Hs.mul(Sl.px,pl.beta),Sl.py,Sl.pz),ll=$l.add(Sl),hl=vl.add(fl)}else{const{p:gl,f:yl}=this.wNAF(sl);ll=gl,hl=yl}return Js.normalizeZ([ll,hl])[0]}multiplyAndAddUnsafe(Dc,sl,ll){const hl=Js.BASE,pl=(yl,bl)=>bl===_0n||bl===_1n$1||!yl.equals(hl)?yl.multiplyUnsafe(bl):yl.multiply(bl),gl=pl(this,sl).add(pl(Dc,ll));return gl.is0()?void 0:gl}toAffine(Dc){const{px:sl,py:ll,pz:hl}=this,pl=this.is0();Dc==null&&(Dc=pl?Hs.ONE:Hs.inv(hl));const gl=Hs.mul(sl,Dc),yl=Hs.mul(ll,Dc),bl=Hs.mul(hl,Dc);if(pl)return{x:Hs.ZERO,y:Hs.ZERO};if(!Hs.eql(bl,Hs.ONE))throw new Error("invZ was invalid");return{x:gl,y:yl}}isTorsionFree(){const{h:Dc,isTorsionFree:sl}=Ps;if(Dc===_1n$1)return!0;if(sl)return sl(Js,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:Dc,clearCofactor:sl}=Ps;return Dc===_1n$1?this:sl?sl(Js,this):this.multiplyUnsafe(Ps.h)}toRawBytes(Dc=!0){return this.assertValidity(),Ws(Js,this,Dc)}toHex(Dc=!0){return bytesToHex(this.toRawBytes(Dc))}}Js.BASE=new Js(Ps.Gx,Ps.Gy,Hs.ONE),Js.ZERO=new Js(Hs.ZERO,Hs.ONE,Hs.ZERO);const Mc=Ps.nBitLength,ol=wNAF(Js,Ps.endo?Math.ceil(Mc/2):Mc);return{CURVE:Ps,ProjectivePoint:Js,normPrivateKeyToScalar:Xs,weierstrassEquation:zs,isWithinCurveOrder:Ys}}function validateOpts(Fs){const Ps=validateBasic(Fs);return validateObject(Ps,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...Ps})}function weierstrass(Fs){const Ps=validateOpts(Fs),{Fp:Hs,n:Ws}=Ps,Zs=Hs.BYTES+1,zs=2*Hs.BYTES+1;function Ys(rl){return _0n<rl&&rl<Hs.ORDER}function Va(rl){return mod(rl,Ws)}function Xs(rl){return invert(rl,Ws)}const{ProjectivePoint:Ma,normPrivateKeyToScalar:qs,weierstrassEquation:Js,isWithinCurveOrder:Mc}=weierstrassPoints({...Ps,toBytes(rl,il,cl){const ul=il.toAffine(),al=Hs.toBytes(ul.x),el=concatBytes;return cl?el(Uint8Array.from([il.hasEvenY()?2:3]),al):el(Uint8Array.from([4]),al,Hs.toBytes(ul.y))},fromBytes(rl){const il=rl.length,cl=rl[0],ul=rl.subarray(1);if(il===Zs&&(cl===2||cl===3)){const al=bytesToNumberBE(ul);if(!Ys(al))throw new Error("Point is not on curve");const el=Js(al);let dl=Hs.sqrt(el);const ml=(dl&_1n$1)===_1n$1;return(cl&1)===1!==ml&&(dl=Hs.neg(dl)),{x:al,y:dl}}else if(il===zs&&cl===4){const al=Hs.fromBytes(ul.subarray(0,Hs.BYTES)),el=Hs.fromBytes(ul.subarray(Hs.BYTES,2*Hs.BYTES));return{x:al,y:el}}else throw new Error(`Point of length ${il} was invalid. Expected ${Zs} compressed bytes or ${zs} uncompressed bytes`)}}),ol=rl=>bytesToHex(numberToBytesBE(rl,Ps.nByteLength));function Vc(rl){const il=Ws>>_1n$1;return rl>il}function Dc(rl){return Vc(rl)?Va(-rl):rl}const sl=(rl,il,cl)=>bytesToNumberBE(rl.slice(il,cl));class ll{constructor(il,cl,ul){this.r=il,this.s=cl,this.recovery=ul,this.assertValidity()}static fromCompact(il){const cl=Ps.nByteLength;return il=ensureBytes("compactSignature",il,cl*2),new ll(sl(il,0,cl),sl(il,cl,2*cl))}static fromDER(il){const{r:cl,s:ul}=DER.toSig(ensureBytes("DER",il));return new ll(cl,ul)}assertValidity(){if(!Mc(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!Mc(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(il){return new ll(this.r,this.s,il)}recoverPublicKey(il){const{r:cl,s:ul,recovery:al}=this,el=Il(ensureBytes("msgHash",il));if(al==null||![0,1,2,3].includes(al))throw new Error("recovery id invalid");const dl=al===2||al===3?cl+Ps.n:cl;if(dl>=Hs.ORDER)throw new Error("recovery id 2 or 3 invalid");const ml=(al&1)===0?"02":"03",El=Ma.fromHex(ml+ol(dl)),Al=Xs(dl),_l=Va(-el*Al),Pl=Va(ul*Al),wl=Ma.BASE.multiplyAndAddUnsafe(El,_l,Pl);if(!wl)throw new Error("point at infinify");return wl.assertValidity(),wl}hasHighS(){return Vc(this.s)}normalizeS(){return this.hasHighS()?new ll(this.r,Va(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return ol(this.r)+ol(this.s)}}const hl={isValidPrivateKey(rl){try{return qs(rl),!0}catch{return!1}},normPrivateKeyToScalar:qs,randomPrivateKey:()=>{const rl=getMinHashLength(Ps.n);return mapHashToField(Ps.randomBytes(rl),Ps.n)},precompute(rl=8,il=Ma.BASE){return il._setWindowSize(rl),il.multiply(BigInt(3)),il}};function pl(rl,il=!0){return Ma.fromPrivateKey(rl).toRawBytes(il)}function gl(rl){const il=rl instanceof Uint8Array,cl=typeof rl=="string",ul=(il||cl)&&rl.length;return il?ul===Zs||ul===zs:cl?ul===2*Zs||ul===2*zs:rl instanceof Ma}function yl(rl,il,cl=!0){if(gl(rl))throw new Error("first arg must be private key");if(!gl(il))throw new Error("second arg must be public key");return Ma.fromHex(il).multiply(qs(rl)).toRawBytes(cl)}const bl=Ps.bits2int||function(rl){const il=bytesToNumberBE(rl),cl=rl.length*8-Ps.nBitLength;return cl>0?il>>BigInt(cl):il},Il=Ps.bits2int_modN||function(rl){return Va(bl(rl))},$l=bitMask(Ps.nBitLength);function vl(rl){if(typeof rl!="bigint")throw new Error("bigint expected");if(!(_0n<=rl&&rl<$l))throw new Error(`bigint expected < 2^${Ps.nBitLength}`);return numberToBytesBE(rl,Ps.nByteLength)}function Sl(rl,il,cl=fl){if(["recovered","canonical"].some(Nl=>Nl in cl))throw new Error("sign() legacy options not supported");const{hash:ul,randomBytes:al}=Ps;let{lowS:el,prehash:dl,extraEntropy:ml}=cl;el==null&&(el=!0),rl=ensureBytes("msgHash",rl),dl&&(rl=ensureBytes("prehashed msgHash",ul(rl)));const El=Il(rl),Al=qs(il),_l=[vl(Al),vl(El)];if(ml!=null){const Nl=ml===!0?al(Hs.BYTES):ml;_l.push(ensureBytes("extraEntropy",Nl))}const Pl=concatBytes(..._l),wl=El;function Cl(Nl){const Ml=bl(Nl);if(!Mc(Ml))return;const Fl=Xs(Ml),Ol=Ma.BASE.multiply(Ml).toAffine(),Vl=Va(Ol.x);if(Vl===_0n)return;const $u=Va(Fl*Va(wl+Vl*Al));if($u===_0n)return;let Ql=(Ol.x===Vl?0:2)|Number(Ol.y&_1n$1),_u=$u;return el&&Vc($u)&&(_u=Dc($u),Ql^=1),new ll(Vl,_u,Ql)}return{seed:Pl,k2sig:Cl}}const fl={lowS:Ps.lowS,prehash:!1},Hc={lowS:Ps.lowS,prehash:!1};function tl(rl,il,cl=fl){const{seed:ul,k2sig:al}=Sl(rl,il,cl),el=Ps;return createHmacDrbg(el.hash.outputLen,el.nByteLength,el.hmac)(ul,al)}Ma.BASE._setWindowSize(8);function nl(rl,il,cl,ul=Hc){const al=rl;if(il=ensureBytes("msgHash",il),cl=ensureBytes("publicKey",cl),"strict"in ul)throw new Error("options.strict was renamed to lowS");const{lowS:el,prehash:dl}=ul;let ml,El;try{if(typeof al=="string"||al instanceof Uint8Array)try{ml=ll.fromDER(al)}catch(Ol){if(!(Ol instanceof DER.Err))throw Ol;ml=ll.fromCompact(al)}else if(typeof al=="object"&&typeof al.r=="bigint"&&typeof al.s=="bigint"){const{r:Ol,s:Vl}=al;ml=new ll(Ol,Vl)}else throw new Error("PARSE");El=Ma.fromHex(cl)}catch(Ol){if(Ol.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(el&&ml.hasHighS())return!1;dl&&(il=Ps.hash(il));const{r:Al,s:_l}=ml,Pl=Il(il),wl=Xs(_l),Cl=Va(Pl*wl),Nl=Va(Al*wl),Ml=Ma.BASE.multiplyAndAddUnsafe(El,Cl,Nl)?.toAffine();return Ml?Va(Ml.x)===Al:!1}return{CURVE:Ps,getPublicKey:pl,getSharedSecret:yl,sign:tl,verify:nl,ProjectivePoint:Ma,Signature:ll,utils:hl}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(Fs){return{hash:Fs,hmac:(Ps,...Hs)=>hmac(Fs,Ps,concatBytes$1(...Hs)),randomBytes}}function createCurve(Fs,Ps){const Hs=Ws=>weierstrass({...Fs,...getHash(Ws)});return Object.freeze({...Hs(Ps),create:Hs})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(Fs,Ps)=>(Fs+Ps/_2n)/Ps;function sqrtMod(Fs){const Ps=secp256k1P,Hs=BigInt(3),Ws=BigInt(6),Zs=BigInt(11),zs=BigInt(22),Ys=BigInt(23),Va=BigInt(44),Xs=BigInt(88),Ma=Fs*Fs*Fs%Ps,qs=Ma*Ma*Fs%Ps,Js=pow2(qs,Hs,Ps)*qs%Ps,Mc=pow2(Js,Hs,Ps)*qs%Ps,ol=pow2(Mc,_2n,Ps)*Ma%Ps,Vc=pow2(ol,Zs,Ps)*ol%Ps,Dc=pow2(Vc,zs,Ps)*Vc%Ps,sl=pow2(Dc,Va,Ps)*Dc%Ps,ll=pow2(sl,Xs,Ps)*sl%Ps,hl=pow2(ll,Va,Ps)*Dc%Ps,pl=pow2(hl,Hs,Ps)*qs%Ps,gl=pow2(pl,Ys,Ps)*Vc%Ps,yl=pow2(gl,Ws,Ps)*Ma%Ps,bl=pow2(yl,_2n,Ps);if(!Fp.eql(Fp.sqr(bl),Fs))throw new Error("Cannot find square root");return bl}const Fp=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:Fs=>{const Ps=secp256k1N,Hs=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Ws=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),Zs=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),zs=Hs,Ys=BigInt("0x100000000000000000000000000000000"),Va=divNearest(zs*Fs,Ps),Xs=divNearest(-Ws*Fs,Ps);let Ma=mod(Fs-Va*Hs-Xs*Zs,Ps),qs=mod(-Va*Ws-Xs*zs,Ps);const Js=Ma>Ys,Mc=qs>Ys;if(Js&&(Ma=Ps-Ma),Mc&&(qs=Ps-qs),Ma>Ys||qs>Ys)throw new Error("splitScalar: Endomorphism failed, k="+Fs);return{k1neg:Js,k1:Ma,k2neg:Mc,k2:qs}}}},sha256$1);BigInt(0),secp256k1.ProjectivePoint;const ZeroAddress="0x0000000000000000000000000000000000000000",ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000",BN_0$7=BigInt(0),BN_1$2=BigInt(1),BN_2$2=BigInt(2),BN_27$1=BigInt(27),BN_28$1=BigInt(28),BN_35$1=BigInt(35),_guard$1={};function toUint256(Fs){return zeroPadValue(toBeArray(Fs),32)}class Signature{#e;#t;#r;#n;get r(){return this.#e}set r(Ps){assertArgument(dataLength(Ps)===32,"invalid r","value",Ps),this.#e=hexlify(Ps)}get s(){return assertArgument(parseInt(this.#t.substring(0,3))<8,"non-canonical s; use ._s","s",this.#t),this.#t}set s(Ps){assertArgument(dataLength(Ps)===32,"invalid s","value",Ps),this.#t=hexlify(Ps)}get _s(){return this.#t}isValid(){return parseInt(this.#t.substring(0,3))<8}get v(){return this.#r}set v(Ps){const Hs=getNumber(Ps,"value");assertArgument(Hs===27||Hs===28,"invalid v","v",Ps),this.#r=Hs}get networkV(){return this.#n}get legacyChainId(){const Ps=this.networkV;return Ps==null?null:Signature.getChainId(Ps)}get yParity(){return this.v===27?0:1}get yParityAndS(){const Ps=getBytes(this.s);return this.yParity&&(Ps[0]|=128),hexlify(Ps)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(Ps,Hs,Ws,Zs){assertPrivate(Ps,_guard$1,"Signature"),this.#e=Hs,this.#t=Ws,this.#r=Zs,this.#n=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this._s}"${this.isValid()?"":', valid: "false"'}, yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const Ps=new Signature(_guard$1,this.r,this._s,this.v);return this.networkV&&(Ps.#n=this.networkV),Ps}toJSON(){const Ps=this.networkV;return{_type:"signature",networkV:Ps!=null?Ps.toString():null,r:this.r,s:this._s,v:this.v}}static getChainId(Ps){const Hs=getBigInt(Ps,"v");return Hs==BN_27$1||Hs==BN_28$1?BN_0$7:(assertArgument(Hs>=BN_35$1,"invalid EIP-155 v","v",Ps),(Hs-BN_35$1)/BN_2$2)}static getChainIdV(Ps,Hs){return getBigInt(Ps)*BN_2$2+BigInt(35+Hs-27)}static getNormalizedV(Ps){const Hs=getBigInt(Ps);return Hs===BN_0$7||Hs===BN_27$1?27:Hs===BN_1$2||Hs===BN_28$1?28:(assertArgument(Hs>=BN_35$1,"invalid v","v",Ps),Hs&BN_1$2?27:28)}static from(Ps){function Hs(Ma,qs){assertArgument(Ma,qs,"signature",Ps)}if(Ps==null)return new Signature(_guard$1,ZeroHash,ZeroHash,27);if(typeof Ps=="string"){const Ma=getBytes(Ps,"signature");if(Ma.length===64){const qs=hexlify(Ma.slice(0,32)),Js=Ma.slice(32,64),Mc=Js[0]&128?28:27;return Js[0]&=127,new Signature(_guard$1,qs,hexlify(Js),Mc)}if(Ma.length===65){const qs=hexlify(Ma.slice(0,32)),Js=hexlify(Ma.slice(32,64)),Mc=Signature.getNormalizedV(Ma[64]);return new Signature(_guard$1,qs,Js,Mc)}Hs(!1,"invalid raw signature length")}if(Ps instanceof Signature)return Ps.clone();const Ws=Ps.r;Hs(Ws!=null,"missing r");const Zs=toUint256(Ws),zs=(function(Ma,qs){if(Ma!=null)return toUint256(Ma);if(qs!=null){Hs(isHexString(qs,32),"invalid yParityAndS");const Js=getBytes(qs);return Js[0]&=127,hexlify(Js)}Hs(!1,"missing s")})(Ps.s,Ps.yParityAndS),{networkV:Ys,v:Va}=(function(Ma,qs,Js){if(Ma!=null){const Mc=getBigInt(Ma);return{networkV:Mc>=BN_35$1?Mc:void 0,v:Signature.getNormalizedV(Mc)}}if(qs!=null)return Hs(isHexString(qs,32),"invalid yParityAndS"),{v:getBytes(qs)[0]&128?28:27};if(Js!=null){switch(getNumber(Js,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}Hs(!1,"invalid yParity")}Hs(!1,"missing v")})(Ps.v,Ps.yParityAndS,Ps.yParity),Xs=new Signature(_guard$1,Zs,zs,Va);return Ys&&(Xs.#n=Ys),Hs(Ps.yParity==null||getNumber(Ps.yParity,"sig.yParity")===Xs.yParity,"yParity mismatch"),Hs(Ps.yParityAndS==null||Ps.yParityAndS===Xs.yParityAndS,"yParityAndS mismatch"),Xs}}class SigningKey{#e;constructor(Ps){assertArgument(dataLength(Ps)===32,"invalid private key","privateKey","[REDACTED]"),this.#e=hexlify(Ps)}get privateKey(){return this.#e}get publicKey(){return SigningKey.computePublicKey(this.#e)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#e,!0)}sign(Ps){assertArgument(dataLength(Ps)===32,"invalid digest length","digest",Ps);const Hs=secp256k1.sign(getBytesCopy(Ps),getBytesCopy(this.#e),{lowS:!0});return Signature.from({r:toBeHex(Hs.r,32),s:toBeHex(Hs.s,32),v:Hs.recovery?28:27})}computeSharedSecret(Ps){const Hs=SigningKey.computePublicKey(Ps);return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#e),getBytes(Hs),!1))}static computePublicKey(Ps,Hs){let Ws=getBytes(Ps,"key");if(Ws.length===32){const zs=secp256k1.getPublicKey(Ws,!!Hs);return hexlify(zs)}if(Ws.length===64){const zs=new Uint8Array(65);zs[0]=4,zs.set(Ws,1),Ws=zs}const Zs=secp256k1.ProjectivePoint.fromHex(Ws);return hexlify(Zs.toRawBytes(Hs))}static recoverPublicKey(Ps,Hs){assertArgument(dataLength(Ps)===32,"invalid digest length","digest",Ps);const Ws=Signature.from(Hs);let Zs=secp256k1.Signature.fromCompact(getBytesCopy(concat([Ws.r,Ws.s])));Zs=Zs.addRecoveryBit(Ws.yParity);const zs=Zs.recoverPublicKey(getBytesCopy(Ps));return assertArgument(zs!=null,"invalid signature for digest","signature",Hs),"0x"+zs.toHex(!1)}static addPoints(Ps,Hs,Ws){const Zs=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(Ps).substring(2)),zs=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(Hs).substring(2));return"0x"+Zs.add(zs).toHex(!!Ws)}}const BN_0$6=BigInt(0),BN_36=BigInt(36);function getChecksumAddress(Fs){Fs=Fs.toLowerCase();const Ps=Fs.substring(2).split(""),Hs=new Uint8Array(40);for(let Zs=0;Zs<40;Zs++)Hs[Zs]=Ps[Zs].charCodeAt(0);const Ws=getBytes(keccak256(Hs));for(let Zs=0;Zs<40;Zs+=2)Ws[Zs>>1]>>4>=8&&(Ps[Zs]=Ps[Zs].toUpperCase()),(Ws[Zs>>1]&15)>=8&&(Ps[Zs+1]=Ps[Zs+1].toUpperCase());return"0x"+Ps.join("")}const ibanLookup={};for(let Fs=0;Fs<10;Fs++)ibanLookup[String(Fs)]=String(Fs);for(let Fs=0;Fs<26;Fs++)ibanLookup[String.fromCharCode(65+Fs)]=String(10+Fs);const safeDigits=15;function ibanChecksum(Fs){Fs=Fs.toUpperCase(),Fs=Fs.substring(4)+Fs.substring(0,2)+"00";let Ps=Fs.split("").map(Ws=>ibanLookup[Ws]).join("");for(;Ps.length>=safeDigits;){let Ws=Ps.substring(0,safeDigits);Ps=parseInt(Ws,10)%97+Ps.substring(Ws.length)}let Hs=String(98-parseInt(Ps,10)%97);for(;Hs.length<2;)Hs="0"+Hs;return Hs}const Base36=(function(){const Fs={};for(let Ps=0;Ps<36;Ps++){const Hs="0123456789abcdefghijklmnopqrstuvwxyz"[Ps];Fs[Hs]=BigInt(Ps)}return Fs})();function fromBase36(Fs){Fs=Fs.toLowerCase();let Ps=BN_0$6;for(let Hs=0;Hs<Fs.length;Hs++)Ps=Ps*BN_36+Base36[Fs[Hs]];return Ps}function getAddress(Fs){if(assertArgument(typeof Fs=="string","invalid address","address",Fs),Fs.match(/^(0x)?[0-9a-fA-F]{40}$/)){Fs.startsWith("0x")||(Fs="0x"+Fs);const Ps=getChecksumAddress(Fs);return assertArgument(!Fs.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||Ps===Fs,"bad address checksum","address",Fs),Ps}if(Fs.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){assertArgument(Fs.substring(2,4)===ibanChecksum(Fs),"bad icap checksum","address",Fs);let Ps=fromBase36(Fs.substring(4)).toString(16);for(;Ps.length<40;)Ps="0"+Ps;return getChecksumAddress("0x"+Ps)}assertArgument(!1,"invalid address","address",Fs)}function getCreateAddress(Fs){const Ps=getAddress(Fs.from);let Ws=getBigInt(Fs.nonce,"tx.nonce").toString(16);return Ws==="0"?Ws="0x":Ws.length%2?Ws="0x0"+Ws:Ws="0x"+Ws,getAddress(dataSlice(keccak256(encodeRlp([Ps,Ws])),12))}function isAddressable(Fs){return Fs&&typeof Fs.getAddress=="function"}async function checkAddress(Fs,Ps){const Hs=await Ps;return(Hs==null||Hs==="0x0000000000000000000000000000000000000000")&&(assert(typeof Fs!="string","unconfigured name","UNCONFIGURED_NAME",{value:Fs}),assertArgument(!1,"invalid AddressLike value; did not resolve to a value address","target",Fs)),getAddress(Hs)}function resolveAddress(Fs,Ps){if(typeof Fs=="string")return Fs.match(/^0x[0-9a-f]{40}$/i)?getAddress(Fs):(assert(Ps!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),checkAddress(Fs,Ps.resolveName(Fs)));if(isAddressable(Fs))return checkAddress(Fs,Fs.getAddress());if(Fs&&typeof Fs.then=="function")return checkAddress(Fs,Fs);assertArgument(!1,"unsupported addressable value","target",Fs)}const _gaurd={};function n$j(Fs,Ps){let Hs=!1;return Ps<0&&(Hs=!0,Ps*=-1),new Typed(_gaurd,`${Hs?"":"u"}int${Ps}`,Fs,{signed:Hs,width:Ps})}function b$4(Fs,Ps){return new Typed(_gaurd,`bytes${Ps||""}`,Fs,{size:Ps})}const _typedSymbol=Symbol.for("_ethers_typed");class Typed{type;value;#e;_typedSymbol;constructor(Ps,Hs,Ws,Zs){Zs==null&&(Zs=null),assertPrivate(_gaurd,Ps,"Typed"),defineProperties(this,{_typedSymbol,type:Hs,value:Ws}),this.#e=Zs,this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(Ps=>Ps.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return this.#e}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return this.#e===!0?-1:this.#e===!1?this.value.length:null}static from(Ps,Hs){return new Typed(_gaurd,Ps,Hs)}static uint8(Ps){return n$j(Ps,8)}static uint16(Ps){return n$j(Ps,16)}static uint24(Ps){return n$j(Ps,24)}static uint32(Ps){return n$j(Ps,32)}static uint40(Ps){return n$j(Ps,40)}static uint48(Ps){return n$j(Ps,48)}static uint56(Ps){return n$j(Ps,56)}static uint64(Ps){return n$j(Ps,64)}static uint72(Ps){return n$j(Ps,72)}static uint80(Ps){return n$j(Ps,80)}static uint88(Ps){return n$j(Ps,88)}static uint96(Ps){return n$j(Ps,96)}static uint104(Ps){return n$j(Ps,104)}static uint112(Ps){return n$j(Ps,112)}static uint120(Ps){return n$j(Ps,120)}static uint128(Ps){return n$j(Ps,128)}static uint136(Ps){return n$j(Ps,136)}static uint144(Ps){return n$j(Ps,144)}static uint152(Ps){return n$j(Ps,152)}static uint160(Ps){return n$j(Ps,160)}static uint168(Ps){return n$j(Ps,168)}static uint176(Ps){return n$j(Ps,176)}static uint184(Ps){return n$j(Ps,184)}static uint192(Ps){return n$j(Ps,192)}static uint200(Ps){return n$j(Ps,200)}static uint208(Ps){return n$j(Ps,208)}static uint216(Ps){return n$j(Ps,216)}static uint224(Ps){return n$j(Ps,224)}static uint232(Ps){return n$j(Ps,232)}static uint240(Ps){return n$j(Ps,240)}static uint248(Ps){return n$j(Ps,248)}static uint256(Ps){return n$j(Ps,256)}static uint(Ps){return n$j(Ps,256)}static int8(Ps){return n$j(Ps,-8)}static int16(Ps){return n$j(Ps,-16)}static int24(Ps){return n$j(Ps,-24)}static int32(Ps){return n$j(Ps,-32)}static int40(Ps){return n$j(Ps,-40)}static int48(Ps){return n$j(Ps,-48)}static int56(Ps){return n$j(Ps,-56)}static int64(Ps){return n$j(Ps,-64)}static int72(Ps){return n$j(Ps,-72)}static int80(Ps){return n$j(Ps,-80)}static int88(Ps){return n$j(Ps,-88)}static int96(Ps){return n$j(Ps,-96)}static int104(Ps){return n$j(Ps,-104)}static int112(Ps){return n$j(Ps,-112)}static int120(Ps){return n$j(Ps,-120)}static int128(Ps){return n$j(Ps,-128)}static int136(Ps){return n$j(Ps,-136)}static int144(Ps){return n$j(Ps,-144)}static int152(Ps){return n$j(Ps,-152)}static int160(Ps){return n$j(Ps,-160)}static int168(Ps){return n$j(Ps,-168)}static int176(Ps){return n$j(Ps,-176)}static int184(Ps){return n$j(Ps,-184)}static int192(Ps){return n$j(Ps,-192)}static int200(Ps){return n$j(Ps,-200)}static int208(Ps){return n$j(Ps,-208)}static int216(Ps){return n$j(Ps,-216)}static int224(Ps){return n$j(Ps,-224)}static int232(Ps){return n$j(Ps,-232)}static int240(Ps){return n$j(Ps,-240)}static int248(Ps){return n$j(Ps,-248)}static int256(Ps){return n$j(Ps,-256)}static int(Ps){return n$j(Ps,-256)}static bytes1(Ps){return b$4(Ps,1)}static bytes2(Ps){return b$4(Ps,2)}static bytes3(Ps){return b$4(Ps,3)}static bytes4(Ps){return b$4(Ps,4)}static bytes5(Ps){return b$4(Ps,5)}static bytes6(Ps){return b$4(Ps,6)}static bytes7(Ps){return b$4(Ps,7)}static bytes8(Ps){return b$4(Ps,8)}static bytes9(Ps){return b$4(Ps,9)}static bytes10(Ps){return b$4(Ps,10)}static bytes11(Ps){return b$4(Ps,11)}static bytes12(Ps){return b$4(Ps,12)}static bytes13(Ps){return b$4(Ps,13)}static bytes14(Ps){return b$4(Ps,14)}static bytes15(Ps){return b$4(Ps,15)}static bytes16(Ps){return b$4(Ps,16)}static bytes17(Ps){return b$4(Ps,17)}static bytes18(Ps){return b$4(Ps,18)}static bytes19(Ps){return b$4(Ps,19)}static bytes20(Ps){return b$4(Ps,20)}static bytes21(Ps){return b$4(Ps,21)}static bytes22(Ps){return b$4(Ps,22)}static bytes23(Ps){return b$4(Ps,23)}static bytes24(Ps){return b$4(Ps,24)}static bytes25(Ps){return b$4(Ps,25)}static bytes26(Ps){return b$4(Ps,26)}static bytes27(Ps){return b$4(Ps,27)}static bytes28(Ps){return b$4(Ps,28)}static bytes29(Ps){return b$4(Ps,29)}static bytes30(Ps){return b$4(Ps,30)}static bytes31(Ps){return b$4(Ps,31)}static bytes32(Ps){return b$4(Ps,32)}static address(Ps){return new Typed(_gaurd,"address",Ps)}static bool(Ps){return new Typed(_gaurd,"bool",!!Ps)}static bytes(Ps){return new Typed(_gaurd,"bytes",Ps)}static string(Ps){return new Typed(_gaurd,"string",Ps)}static array(Ps,Hs){throw new Error("not implemented yet")}static tuple(Ps,Hs){throw new Error("not implemented yet")}static overrides(Ps){return new Typed(_gaurd,"overrides",Object.assign({},Ps))}static isTyped(Ps){return Ps&&typeof Ps=="object"&&"_typedSymbol"in Ps&&Ps._typedSymbol===_typedSymbol}static dereference(Ps,Hs){if(Typed.isTyped(Ps)){if(Ps.type!==Hs)throw new Error(`invalid type: expecetd ${Hs}, got ${Ps.type}`);return Ps.value}return Ps}}class AddressCoder extends Coder{constructor(Ps){super("address","address",Ps,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(Ps,Hs){let Ws=Typed.dereference(Hs,"string");try{Ws=getAddress(Ws)}catch(Zs){return this._throwError(Zs.message,Hs)}return Ps.writeValue(Ws)}decode(Ps){return getAddress(toBeHex(Ps.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(Ps){super(Ps.name,Ps.type,"_",Ps.dynamic),this.coder=Ps}defaultValue(){return this.coder.defaultValue()}encode(Ps,Hs){return this.coder.encode(Ps,Hs)}decode(Ps){return this.coder.decode(Ps)}}function pack(Fs,Ps,Hs){let Ws=[];if(Array.isArray(Hs))Ws=Hs;else if(Hs&&typeof Hs=="object"){let Xs={};Ws=Ps.map(Ma=>{const qs=Ma.localName;return assert(qs,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:Ma},value:Hs}),assert(!Xs[qs],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:Ma},value:Hs}),Xs[qs]=!0,Hs[qs]})}else assertArgument(!1,"invalid tuple value","tuple",Hs);assertArgument(Ps.length===Ws.length,"types/value length mismatch","tuple",Hs);let Zs=new Writer,zs=new Writer,Ys=[];Ps.forEach((Xs,Ma)=>{let qs=Ws[Ma];if(Xs.dynamic){let Js=zs.length;Xs.encode(zs,qs);let Mc=Zs.writeUpdatableValue();Ys.push(ol=>{Mc(ol+Js)})}else Xs.encode(Zs,qs)}),Ys.forEach(Xs=>{Xs(Zs.length)});let Va=Fs.appendWriter(Zs);return Va+=Fs.appendWriter(zs),Va}function unpack(Fs,Ps){let Hs=[],Ws=[],Zs=Fs.subReader(0);return Ps.forEach(zs=>{let Ys=null;if(zs.dynamic){let Va=Fs.readIndex(),Xs=Zs.subReader(Va);try{Ys=zs.decode(Xs)}catch(Ma){if(isError(Ma,"BUFFER_OVERRUN"))throw Ma;Ys=Ma,Ys.baseType=zs.name,Ys.name=zs.localName,Ys.type=zs.type}}else try{Ys=zs.decode(Fs)}catch(Va){if(isError(Va,"BUFFER_OVERRUN"))throw Va;Ys=Va,Ys.baseType=zs.name,Ys.name=zs.localName,Ys.type=zs.type}if(Ys==null)throw new Error("investigate");Hs.push(Ys),Ws.push(zs.localName||null)}),Result$1.fromItems(Hs,Ws)}class ArrayCoder extends Coder{coder;length;constructor(Ps,Hs,Ws){const Zs=Ps.type+"["+(Hs>=0?Hs:"")+"]",zs=Hs===-1||Ps.dynamic;super("array",Zs,Ws,zs),defineProperties(this,{coder:Ps,length:Hs})}defaultValue(){const Ps=this.coder.defaultValue(),Hs=[];for(let Ws=0;Ws<this.length;Ws++)Hs.push(Ps);return Hs}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"array");Array.isArray(Ws)||this._throwError("expected array value",Ws);let Zs=this.length;Zs===-1&&(Zs=Ws.length,Ps.writeValue(Ws.length)),assertArgumentCount(Ws.length,Zs,"coder array"+(this.localName?" "+this.localName:""));let zs=[];for(let Ys=0;Ys<Ws.length;Ys++)zs.push(this.coder);return pack(Ps,zs,Ws)}decode(Ps){let Hs=this.length;Hs===-1&&(Hs=Ps.readIndex(),assert(Hs*WordSize<=Ps.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:Ps.bytes,offset:Hs*WordSize,length:Ps.dataLength}));let Ws=[];for(let Zs=0;Zs<Hs;Zs++)Ws.push(new AnonymousCoder(this.coder));return unpack(Ps,Ws)}}class BooleanCoder extends Coder{constructor(Ps){super("bool","bool",Ps,!1)}defaultValue(){return!1}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"bool");return Ps.writeValue(Ws?1:0)}decode(Ps){return!!Ps.readValue()}}class DynamicBytesCoder extends Coder{constructor(Ps,Hs){super(Ps,Ps,Hs,!0)}defaultValue(){return"0x"}encode(Ps,Hs){Hs=getBytesCopy(Hs);let Ws=Ps.writeValue(Hs.length);return Ws+=Ps.writeBytes(Hs),Ws}decode(Ps){return Ps.readBytes(Ps.readIndex(),!0)}}class BytesCoder extends DynamicBytesCoder{constructor(Ps){super("bytes",Ps)}decode(Ps){return hexlify(super.decode(Ps))}}class FixedBytesCoder extends Coder{size;constructor(Ps,Hs){let Ws="bytes"+String(Ps);super(Ws,Ws,Hs,!1),defineProperties(this,{size:Ps},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(Ps,Hs){let Ws=getBytesCopy(Typed.dereference(Hs,this.type));return Ws.length!==this.size&&this._throwError("incorrect data length",Hs),Ps.writeBytes(Ws)}decode(Ps){return hexlify(Ps.readBytes(this.size))}}const Empty=new Uint8Array([]);class NullCoder extends Coder{constructor(Ps){super("null","",Ps,!1)}defaultValue(){return null}encode(Ps,Hs){return Hs!=null&&this._throwError("not null",Hs),Ps.writeBytes(Empty)}decode(Ps){return Ps.readBytes(0),null}}const BN_0$5=BigInt(0),BN_1$1=BigInt(1),BN_MAX_UINT256$1=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class NumberCoder extends Coder{size;signed;constructor(Ps,Hs,Ws){const Zs=(Hs?"int":"uint")+Ps*8;super(Zs,Zs,Ws,!1),defineProperties(this,{size:Ps,signed:Hs},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(Ps,Hs){let Ws=getBigInt(Typed.dereference(Hs,this.type)),Zs=mask(BN_MAX_UINT256$1,WordSize*8);if(this.signed){let zs=mask(Zs,this.size*8-1);(Ws>zs||Ws<-(zs+BN_1$1))&&this._throwError("value out-of-bounds",Hs),Ws=toTwos(Ws,8*WordSize)}else(Ws<BN_0$5||Ws>mask(Zs,this.size*8))&&this._throwError("value out-of-bounds",Hs);return Ps.writeValue(Ws)}decode(Ps){let Hs=mask(Ps.readValue(),this.size*8);return this.signed&&(Hs=fromTwos(Hs,this.size*8)),Hs}}class StringCoder extends DynamicBytesCoder{constructor(Ps){super("string",Ps)}defaultValue(){return""}encode(Ps,Hs){return super.encode(Ps,toUtf8Bytes(Typed.dereference(Hs,"string")))}decode(Ps){return toUtf8String(super.decode(Ps))}}class TupleCoder extends Coder{coders;constructor(Ps,Hs){let Ws=!1;const Zs=[];Ps.forEach(Ys=>{Ys.dynamic&&(Ws=!0),Zs.push(Ys.type)});const zs="tuple("+Zs.join(",")+")";super("tuple",zs,Hs,Ws),defineProperties(this,{coders:Object.freeze(Ps.slice())})}defaultValue(){const Ps=[];this.coders.forEach(Ws=>{Ps.push(Ws.defaultValue())});const Hs=this.coders.reduce((Ws,Zs)=>{const zs=Zs.localName;return zs&&(Ws[zs]||(Ws[zs]=0),Ws[zs]++),Ws},{});return this.coders.forEach((Ws,Zs)=>{let zs=Ws.localName;!zs||Hs[zs]!==1||(zs==="length"&&(zs="_length"),Ps[zs]==null&&(Ps[zs]=Ps[Zs]))}),Object.freeze(Ps)}encode(Ps,Hs){const Ws=Typed.dereference(Hs,"tuple");return pack(Ps,this.coders,Ws)}decode(Ps){return unpack(Ps,this.coders)}}function accessSetify(Fs,Ps){return{address:getAddress(Fs),storageKeys:Ps.map((Hs,Ws)=>(assertArgument(isHexString(Hs,32),"invalid slot",`storageKeys[${Ws}]`,Hs),Hs.toLowerCase()))}}function accessListify(Fs){if(Array.isArray(Fs))return Fs.map((Hs,Ws)=>Array.isArray(Hs)?(assertArgument(Hs.length===2,"invalid slot set",`value[${Ws}]`,Hs),accessSetify(Hs[0],Hs[1])):(assertArgument(Hs!=null&&typeof Hs=="object","invalid address-slot set","value",Fs),accessSetify(Hs.address,Hs.storageKeys)));assertArgument(Fs!=null&&typeof Fs=="object","invalid access list","value",Fs);const Ps=Object.keys(Fs).map(Hs=>{const Ws=Fs[Hs].reduce((Zs,zs)=>(Zs[zs]=!0,Zs),{});return accessSetify(Hs,Object.keys(Ws).sort())});return Ps.sort((Hs,Ws)=>Hs.address.localeCompare(Ws.address)),Ps}function authorizationify(Fs){return{address:getAddress(Fs.address),nonce:getBigInt(Fs.nonce!=null?Fs.nonce:0),chainId:getBigInt(Fs.chainId!=null?Fs.chainId:0),signature:Signature.from(Fs.signature)}}function computeAddress(Fs){let Ps;return typeof Fs=="string"?Ps=SigningKey.computePublicKey(Fs,!1):Ps=Fs.publicKey,getAddress(keccak256("0x"+Ps.substring(4)).substring(26))}function recoverAddress(Fs,Ps){return computeAddress(SigningKey.recoverPublicKey(Fs,Ps))}const BN_0$4=BigInt(0),BN_2$1=BigInt(2),BN_27=BigInt(27),BN_28=BigInt(28),BN_35=BigInt(35),BN_MAX_UINT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),BLOB_SIZE=4096*32;function getKzgLibrary(Fs){return{blobToKzgCommitment:Ws=>{if("computeBlobProof"in Fs){if("blobToKzgCommitment"in Fs&&typeof Fs.blobToKzgCommitment=="function")return getBytes(Fs.blobToKzgCommitment(hexlify(Ws)))}else if("blobToKzgCommitment"in Fs&&typeof Fs.blobToKzgCommitment=="function")return getBytes(Fs.blobToKzgCommitment(Ws));if("blobToKZGCommitment"in Fs&&typeof Fs.blobToKZGCommitment=="function")return getBytes(Fs.blobToKZGCommitment(hexlify(Ws)));assertArgument(!1,"unsupported KZG library","kzg",Fs)},computeBlobKzgProof:(Ws,Zs)=>{if("computeBlobProof"in Fs&&typeof Fs.computeBlobProof=="function")return getBytes(Fs.computeBlobProof(hexlify(Ws),hexlify(Zs)));if("computeBlobKzgProof"in Fs&&typeof Fs.computeBlobKzgProof=="function")return Fs.computeBlobKzgProof(Ws,Zs);if("computeBlobKZGProof"in Fs&&typeof Fs.computeBlobKZGProof=="function")return getBytes(Fs.computeBlobKZGProof(hexlify(Ws),hexlify(Zs)));assertArgument(!1,"unsupported KZG library","kzg",Fs)}}}function getVersionedHash(Fs,Ps){let Hs=Fs.toString(16);for(;Hs.length<2;)Hs="0"+Hs;return Hs+=sha256(Ps).substring(4),"0x"+Hs}function handleAddress(Fs){return Fs==="0x"?null:getAddress(Fs)}function handleAccessList(Fs,Ps){try{return accessListify(Fs)}catch(Hs){assertArgument(!1,Hs.message,Ps,Fs)}}function handleAuthorizationList(Fs,Ps){try{if(!Array.isArray(Fs))throw new Error("authorizationList: invalid array");const Hs=[];for(let Ws=0;Ws<Fs.length;Ws++){const Zs=Fs[Ws];if(!Array.isArray(Zs))throw new Error(`authorization[${Ws}]: invalid array`);if(Zs.length!==6)throw new Error(`authorization[${Ws}]: wrong length`);if(!Zs[1])throw new Error(`authorization[${Ws}]: null address`);Hs.push({address:handleAddress(Zs[1]),nonce:handleUint(Zs[2],"nonce"),chainId:handleUint(Zs[0],"chainId"),signature:Signature.from({yParity:handleNumber(Zs[3],"yParity"),r:zeroPadValue(Zs[4],32),s:zeroPadValue(Zs[5],32)})})}return Hs}catch(Hs){assertArgument(!1,Hs.message,Ps,Fs)}}function handleNumber(Fs,Ps){return Fs==="0x"?0:getNumber(Fs,Ps)}function handleUint(Fs,Ps){if(Fs==="0x")return BN_0$4;const Hs=getBigInt(Fs,Ps);return assertArgument(Hs<=BN_MAX_UINT,"value exceeds uint size",Ps,Hs),Hs}function formatNumber(Fs,Ps){const Hs=getBigInt(Fs,"value"),Ws=toBeArray(Hs);return assertArgument(Ws.length<=32,"value too large",`tx.${Ps}`,Hs),Ws}function formatAccessList(Fs){return accessListify(Fs).map(Ps=>[Ps.address,Ps.storageKeys])}function formatAuthorizationList(Fs){return Fs.map(Ps=>[formatNumber(Ps.chainId,"chainId"),Ps.address,formatNumber(Ps.nonce,"nonce"),formatNumber(Ps.signature.yParity,"yParity"),toBeArray(Ps.signature.r),toBeArray(Ps.signature.s)])}function formatHashes(Fs,Ps){assertArgument(Array.isArray(Fs),`invalid ${Ps}`,"value",Fs);for(let Hs=0;Hs<Fs.length;Hs++)assertArgument(isHexString(Fs[Hs],32),"invalid ${ param } hash",`value[${Hs}]`,Fs[Hs]);return Fs}function _parseLegacy(Fs){const Ps=decodeRlp(Fs);assertArgument(Array.isArray(Ps)&&(Ps.length===9||Ps.length===6),"invalid field count for legacy transaction","data",Fs);const Hs={type:0,nonce:handleNumber(Ps[0],"nonce"),gasPrice:handleUint(Ps[1],"gasPrice"),gasLimit:handleUint(Ps[2],"gasLimit"),to:handleAddress(Ps[3]),value:handleUint(Ps[4],"value"),data:hexlify(Ps[5]),chainId:BN_0$4};if(Ps.length===6)return Hs;const Ws=handleUint(Ps[6],"v"),Zs=handleUint(Ps[7],"r"),zs=handleUint(Ps[8],"s");if(Zs===BN_0$4&&zs===BN_0$4)Hs.chainId=Ws;else{let Ys=(Ws-BN_35)/BN_2$1;Ys<BN_0$4&&(Ys=BN_0$4),Hs.chainId=Ys,assertArgument(Ys!==BN_0$4||Ws===BN_27||Ws===BN_28,"non-canonical legacy v","v",Ps[6]),Hs.signature=Signature.from({r:zeroPadValue(Ps[7],32),s:zeroPadValue(Ps[8],32),v:Ws})}return Hs}function _serializeLegacy(Fs,Ps){const Hs=[formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.gasPrice||0,"gasPrice"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data];let Ws=BN_0$4;if(Fs.chainId!=BN_0$4)Ws=getBigInt(Fs.chainId,"tx.chainId"),assertArgument(!Ps||Ps.networkV==null||Ps.legacyChainId===Ws,"tx.chainId/sig.v mismatch","sig",Ps);else if(Fs.signature){const zs=Fs.signature.legacyChainId;zs!=null&&(Ws=zs)}if(!Ps)return Ws!==BN_0$4&&(Hs.push(toBeArray(Ws)),Hs.push("0x"),Hs.push("0x")),encodeRlp(Hs);let Zs=BigInt(27+Ps.yParity);return Ws!==BN_0$4?Zs=Signature.getChainIdV(Ws,Ps.v):BigInt(Ps.v)!==Zs&&assertArgument(!1,"tx.chainId/sig.v mismatch","sig",Ps),Hs.push(toBeArray(Zs)),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s)),encodeRlp(Hs)}function _parseEipSignature(Fs,Ps){let Hs;try{if(Hs=handleNumber(Ps[0],"yParity"),Hs!==0&&Hs!==1)throw new Error("bad yParity")}catch{assertArgument(!1,"invalid yParity","yParity",Ps[0])}const Ws=zeroPadValue(Ps[1],32),Zs=zeroPadValue(Ps[2],32),zs=Signature.from({r:Ws,s:Zs,yParity:Hs});Fs.signature=zs}function _parseEip1559(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===9||Ps.length===12),"invalid field count for transaction type: 2","data",hexlify(Fs));const Hs={type:2,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList")};return Ps.length===9||_parseEipSignature(Hs,Ps.slice(9)),Hs}function _serializeEip1559(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"yParity")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x02",encodeRlp(Hs)])}function _parseEip2930(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===8||Ps.length===11),"invalid field count for transaction type: 1","data",hexlify(Fs));const Hs={type:1,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),gasPrice:handleUint(Ps[2],"gasPrice"),gasLimit:handleUint(Ps[3],"gasLimit"),to:handleAddress(Ps[4]),value:handleUint(Ps[5],"value"),data:hexlify(Ps[6]),accessList:handleAccessList(Ps[7],"accessList")};return Ps.length===8||_parseEipSignature(Hs,Ps.slice(8)),Hs}function _serializeEip2930(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.gasPrice||0,"gasPrice"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"recoveryParam")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x01",encodeRlp(Hs)])}function _parseEip4844(Fs){let Ps=decodeRlp(getBytes(Fs).slice(1)),Hs="3",Ws=null;if(Ps.length===4&&Array.isArray(Ps[0])){Hs="3 (network format)";const zs=Ps[1],Ys=Ps[2],Va=Ps[3];assertArgument(Array.isArray(zs),"invalid network format: blobs not an array","fields[1]",zs),assertArgument(Array.isArray(Ys),"invalid network format: commitments not an array","fields[2]",Ys),assertArgument(Array.isArray(Va),"invalid network format: proofs not an array","fields[3]",Va),assertArgument(zs.length===Ys.length,"invalid network format: blobs/commitments length mismatch","fields",Ps),assertArgument(zs.length===Va.length,"invalid network format: blobs/proofs length mismatch","fields",Ps),Ws=[];for(let Xs=0;Xs<Ps[1].length;Xs++)Ws.push({data:zs[Xs],commitment:Ys[Xs],proof:Va[Xs]});Ps=Ps[0]}assertArgument(Array.isArray(Ps)&&(Ps.length===11||Ps.length===14),`invalid field count for transaction type: ${Hs}`,"data",hexlify(Fs));const Zs={type:3,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList"),maxFeePerBlobGas:handleUint(Ps[9],"maxFeePerBlobGas"),blobVersionedHashes:Ps[10]};Ws&&(Zs.blobs=Ws),assertArgument(Zs.to!=null,`invalid address for transaction type: ${Hs}`,"data",Fs),assertArgument(Array.isArray(Zs.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",Fs);for(let zs=0;zs<Zs.blobVersionedHashes.length;zs++)assertArgument(isHexString(Zs.blobVersionedHashes[zs],32),`invalid blobVersionedHash at index ${zs}: must be length 32`,"data",Fs);return Ps.length===11||_parseEipSignature(Zs,Ps.slice(11)),Zs}function _serializeEip4844(Fs,Ps,Hs){const Ws=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||ZeroAddress,formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[]),formatNumber(Fs.maxFeePerBlobGas||0,"maxFeePerBlobGas"),formatHashes(Fs.blobVersionedHashes||[],"blobVersionedHashes")];return Ps&&(Ws.push(formatNumber(Ps.yParity,"yParity")),Ws.push(toBeArray(Ps.r)),Ws.push(toBeArray(Ps.s)),Hs)?concat(["0x03",encodeRlp([Ws,Hs.map(Zs=>Zs.data),Hs.map(Zs=>Zs.commitment),Hs.map(Zs=>Zs.proof)])]):concat(["0x03",encodeRlp(Ws)])}function _parseEip7702(Fs){const Ps=decodeRlp(getBytes(Fs).slice(1));assertArgument(Array.isArray(Ps)&&(Ps.length===10||Ps.length===13),"invalid field count for transaction type: 4","data",hexlify(Fs));const Hs={type:4,chainId:handleUint(Ps[0],"chainId"),nonce:handleNumber(Ps[1],"nonce"),maxPriorityFeePerGas:handleUint(Ps[2],"maxPriorityFeePerGas"),maxFeePerGas:handleUint(Ps[3],"maxFeePerGas"),gasPrice:null,gasLimit:handleUint(Ps[4],"gasLimit"),to:handleAddress(Ps[5]),value:handleUint(Ps[6],"value"),data:hexlify(Ps[7]),accessList:handleAccessList(Ps[8],"accessList"),authorizationList:handleAuthorizationList(Ps[9],"authorizationList")};return Ps.length===10||_parseEipSignature(Hs,Ps.slice(10)),Hs}function _serializeEip7702(Fs,Ps){const Hs=[formatNumber(Fs.chainId,"chainId"),formatNumber(Fs.nonce,"nonce"),formatNumber(Fs.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(Fs.maxFeePerGas||0,"maxFeePerGas"),formatNumber(Fs.gasLimit,"gasLimit"),Fs.to||"0x",formatNumber(Fs.value,"value"),Fs.data,formatAccessList(Fs.accessList||[]),formatAuthorizationList(Fs.authorizationList||[])];return Ps&&(Hs.push(formatNumber(Ps.yParity,"yParity")),Hs.push(toBeArray(Ps.r)),Hs.push(toBeArray(Ps.s))),concat(["0x04",encodeRlp(Hs)])}class Transaction{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;#c;#u;#f;#h;#y;get type(){return this.#e}set type(Ps){switch(Ps){case null:this.#e=null;break;case 0:case"legacy":this.#e=0;break;case 1:case"berlin":case"eip-2930":this.#e=1;break;case 2:case"london":case"eip-1559":this.#e=2;break;case 3:case"cancun":case"eip-4844":this.#e=3;break;case 4:case"pectra":case"eip-7702":this.#e=4;break;default:assertArgument(!1,"unsupported transaction type","type",Ps)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const Ps=this.#t;return Ps==null&&this.type===3?ZeroAddress:Ps}set to(Ps){this.#t=Ps==null?null:getAddress(Ps)}get nonce(){return this.#n}set nonce(Ps){this.#n=getNumber(Ps,"value")}get gasLimit(){return this.#o}set gasLimit(Ps){this.#o=getBigInt(Ps)}get gasPrice(){const Ps=this.#s;return Ps==null&&(this.type===0||this.type===1)?BN_0$4:Ps}set gasPrice(Ps){this.#s=Ps==null?null:getBigInt(Ps,"gasPrice")}get maxPriorityFeePerGas(){const Ps=this.#i;return Ps??(this.type===2||this.type===3?BN_0$4:null)}set maxPriorityFeePerGas(Ps){this.#i=Ps==null?null:getBigInt(Ps,"maxPriorityFeePerGas")}get maxFeePerGas(){const Ps=this.#a;return Ps??(this.type===2||this.type===3?BN_0$4:null)}set maxFeePerGas(Ps){this.#a=Ps==null?null:getBigInt(Ps,"maxFeePerGas")}get data(){return this.#r}set data(Ps){this.#r=hexlify(Ps)}get value(){return this.#d}set value(Ps){this.#d=getBigInt(Ps,"value")}get chainId(){return this.#l}set chainId(Ps){this.#l=getBigInt(Ps)}get signature(){return this.#p||null}set signature(Ps){this.#p=Ps==null?null:Signature.from(Ps)}get accessList(){const Ps=this.#g||null;return Ps??(this.type===1||this.type===2||this.type===3?[]:null)}set accessList(Ps){this.#g=Ps==null?null:accessListify(Ps)}get authorizationList(){const Ps=this.#y||null;return Ps==null&&this.type===4?[]:Ps}set authorizationList(Ps){this.#y=Ps==null?null:Ps.map(Hs=>authorizationify(Hs))}get maxFeePerBlobGas(){const Ps=this.#c;return Ps==null&&this.type===3?BN_0$4:Ps}set maxFeePerBlobGas(Ps){this.#c=Ps==null?null:getBigInt(Ps,"maxFeePerBlobGas")}get blobVersionedHashes(){let Ps=this.#u;return Ps==null&&this.type===3?[]:Ps}set blobVersionedHashes(Ps){if(Ps!=null){assertArgument(Array.isArray(Ps),"blobVersionedHashes must be an Array","value",Ps),Ps=Ps.slice();for(let Hs=0;Hs<Ps.length;Hs++)assertArgument(isHexString(Ps[Hs],32),"invalid blobVersionedHash",`value[${Hs}]`,Ps[Hs])}this.#u=Ps}get blobs(){return this.#h==null?null:this.#h.map(Ps=>Object.assign({},Ps))}set blobs(Ps){if(Ps==null){this.#h=null;return}const Hs=[],Ws=[];for(let Zs=0;Zs<Ps.length;Zs++){const zs=Ps[Zs];if(isBytesLike(zs)){assert(this.#f,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let Ys=getBytes(zs);if(assertArgument(Ys.length<=BLOB_SIZE,"blob is too large",`blobs[${Zs}]`,zs),Ys.length!==BLOB_SIZE){const Ma=new Uint8Array(BLOB_SIZE);Ma.set(Ys),Ys=Ma}const Va=this.#f.blobToKzgCommitment(Ys),Xs=hexlify(this.#f.computeBlobKzgProof(Ys,Va));Hs.push({data:hexlify(Ys),commitment:hexlify(Va),proof:Xs}),Ws.push(getVersionedHash(1,Va))}else{const Ys=hexlify(zs.commitment);Hs.push({data:hexlify(zs.data),commitment:Ys,proof:hexlify(zs.proof)}),Ws.push(getVersionedHash(1,Ys))}}this.#h=Hs,this.#u=Ws}get kzg(){return this.#f}set kzg(Ps){Ps==null?this.#f=null:this.#f=getKzgLibrary(Ps)}constructor(){this.#e=null,this.#t=null,this.#n=0,this.#o=BN_0$4,this.#s=null,this.#i=null,this.#a=null,this.#r="0x",this.#d=BN_0$4,this.#l=BN_0$4,this.#p=null,this.#g=null,this.#c=null,this.#u=null,this.#f=null,this.#h=null,this.#y=null}get hash(){return this.signature==null?null:keccak256(this.#m(!0,!1))}get unsignedHash(){return keccak256(this.unsignedSerialized)}get from(){return this.signature==null?null:recoverAddress(this.unsignedHash,this.signature)}get fromPublicKey(){return this.signature==null?null:SigningKey.recoverPublicKey(this.unsignedHash,this.signature)}isSigned(){return this.signature!=null}#m(Ps,Hs){assert(!Ps||this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const Ws=Ps?this.signature:null;switch(this.inferType()){case 0:return _serializeLegacy(this,Ws);case 1:return _serializeEip2930(this,Ws);case 2:return _serializeEip1559(this,Ws);case 3:return _serializeEip4844(this,Ws,Hs?this.blobs:null);case 4:return _serializeEip7702(this,Ws)}assert(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#m(!0,!0)}get unsignedSerialized(){return this.#m(!1,!1)}inferType(){const Ps=this.inferTypes();return Ps.indexOf(2)>=0?2:Ps.pop()}inferTypes(){const Ps=this.gasPrice!=null,Hs=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null,Ws=this.accessList!=null,Zs=this.#c!=null||this.#u;this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null&&assert(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),assert(!Hs||this.type!==0&&this.type!==1,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),assert(this.type!==0||!Ws,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const zs=[];return this.type!=null?zs.push(this.type):this.authorizationList&&this.authorizationList.length?zs.push(4):Hs?zs.push(2):Ps?(zs.push(1),Ws||zs.push(0)):Ws?(zs.push(1),zs.push(2)):(Zs&&this.to||(zs.push(0),zs.push(1),zs.push(2)),zs.push(3)),zs.sort(),zs}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}clone(){return Transaction.from(this)}toJSON(){const Ps=Hs=>Hs==null?null:Hs.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:Ps(this.gasLimit),gasPrice:Ps(this.gasPrice),maxPriorityFeePerGas:Ps(this.maxPriorityFeePerGas),maxFeePerGas:Ps(this.maxFeePerGas),value:Ps(this.value),chainId:Ps(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}static from(Ps){if(Ps==null)return new Transaction;if(typeof Ps=="string"){const Ws=getBytes(Ps);if(Ws[0]>=127)return Transaction.from(_parseLegacy(Ws));switch(Ws[0]){case 1:return Transaction.from(_parseEip2930(Ws));case 2:return Transaction.from(_parseEip1559(Ws));case 3:return Transaction.from(_parseEip4844(Ws));case 4:return Transaction.from(_parseEip7702(Ws))}assert(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const Hs=new Transaction;return Ps.type!=null&&(Hs.type=Ps.type),Ps.to!=null&&(Hs.to=Ps.to),Ps.nonce!=null&&(Hs.nonce=Ps.nonce),Ps.gasLimit!=null&&(Hs.gasLimit=Ps.gasLimit),Ps.gasPrice!=null&&(Hs.gasPrice=Ps.gasPrice),Ps.maxPriorityFeePerGas!=null&&(Hs.maxPriorityFeePerGas=Ps.maxPriorityFeePerGas),Ps.maxFeePerGas!=null&&(Hs.maxFeePerGas=Ps.maxFeePerGas),Ps.maxFeePerBlobGas!=null&&(Hs.maxFeePerBlobGas=Ps.maxFeePerBlobGas),Ps.data!=null&&(Hs.data=Ps.data),Ps.value!=null&&(Hs.value=Ps.value),Ps.chainId!=null&&(Hs.chainId=Ps.chainId),Ps.signature!=null&&(Hs.signature=Signature.from(Ps.signature)),Ps.accessList!=null&&(Hs.accessList=Ps.accessList),Ps.authorizationList!=null&&(Hs.authorizationList=Ps.authorizationList),Ps.blobVersionedHashes!=null&&(Hs.blobVersionedHashes=Ps.blobVersionedHashes),Ps.kzg!=null&&(Hs.kzg=Ps.kzg),Ps.blobs!=null&&(Hs.blobs=Ps.blobs),Ps.hash!=null&&(assertArgument(Hs.isSigned(),"unsigned transaction cannot define '.hash'","tx",Ps),assertArgument(Hs.hash===Ps.hash,"hash mismatch","tx",Ps)),Ps.from!=null&&(assertArgument(Hs.isSigned(),"unsigned transaction cannot define '.from'","tx",Ps),assertArgument(Hs.from.toLowerCase()===(Ps.from||"").toLowerCase(),"from mismatch","tx",Ps)),Hs}}function id(Fs){return keccak256(toUtf8Bytes(Fs))}var COMPRESSED$1="AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAO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gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI";const FENCED=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]),NSM_MAX=4;function decode_arithmetic(Fs){let Ps=0;function Hs(){return Fs[Ps++]<<8|Fs[Ps++]}let Ws=Hs(),Zs=1,zs=[0,1];for(let yl=1;yl<Ws;yl++)zs.push(Zs+=Hs());let Ys=Hs(),Va=Ps;Ps+=Ys;let Xs=0,Ma=0;function qs(){return Xs==0&&(Ma=Ma<<8|Fs[Ps++],Xs=8),Ma>>--Xs&1}const Js=31,Mc=2**Js,ol=Mc>>>1,Vc=ol>>1,Dc=Mc-1;let sl=0;for(let yl=0;yl<Js;yl++)sl=sl<<1|qs();let ll=[],hl=0,pl=Mc;for(;;){let yl=Math.floor(((sl-hl+1)*Zs-1)/pl),bl=0,Il=Ws;for(;Il-bl>1;){let Sl=bl+Il>>>1;yl<zs[Sl]?Il=Sl:bl=Sl}if(bl==0)break;ll.push(bl);let $l=hl+Math.floor(pl*zs[bl]/Zs),vl=hl+Math.floor(pl*zs[bl+1]/Zs)-1;for(;(($l^vl)&ol)==0;)sl=sl<<1&Dc|qs(),$l=$l<<1&Dc,vl=vl<<1&Dc|1;for(;$l&~vl&Vc;)sl=sl&ol|sl<<1&Dc>>>1|qs(),$l=$l<<1^ol,vl=(vl^ol)<<1|ol|1;hl=$l,pl=1+vl-$l}let gl=Ws-4;return ll.map(yl=>{switch(yl-gl){case 3:return gl+65792+(Fs[Va++]<<16|Fs[Va++]<<8|Fs[Va++]);case 2:return gl+256+(Fs[Va++]<<8|Fs[Va++]);case 1:return gl+Fs[Va++];default:return yl-1}})}function read_payload(Fs){let Ps=0;return()=>Fs[Ps++]}function read_compressed_payload(Fs){return read_payload(decode_arithmetic(unsafe_atob(Fs)))}function unsafe_atob(Fs){let Ps=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((Zs,zs)=>Ps[Zs.charCodeAt(0)]=zs);let Hs=Fs.length,Ws=new Uint8Array(6*Hs>>3);for(let Zs=0,zs=0,Ys=0,Va=0;Zs<Hs;Zs++)Va=Va<<6|Ps[Fs.charCodeAt(Zs)],Ys+=6,Ys>=8&&(Ws[zs++]=Va>>(Ys-=8));return Ws}function signed(Fs){return Fs&1?~Fs>>1:Fs>>1}function read_deltas(Fs,Ps){let Hs=Array(Fs);for(let Ws=0,Zs=0;Ws<Fs;Ws++)Hs[Ws]=Zs+=signed(Ps());return Hs}function read_sorted(Fs,Ps=0){let Hs=[];for(;;){let Ws=Fs(),Zs=Fs();if(!Zs)break;Ps+=Ws;for(let zs=0;zs<Zs;zs++)Hs.push(Ps+zs);Ps+=Zs+1}return Hs}function read_sorted_arrays(Fs){return read_array_while(()=>{let Ps=read_sorted(Fs);if(Ps.length)return Ps})}function read_mapped(Fs){let Ps=[];for(;;){let Hs=Fs();if(Hs==0)break;Ps.push(read_linear_table(Hs,Fs))}for(;;){let Hs=Fs()-1;if(Hs<0)break;Ps.push(read_replacement_table(Hs,Fs))}return Ps.flat()}function read_array_while(Fs){let Ps=[];for(;;){let Hs=Fs(Ps.length);if(!Hs)break;Ps.push(Hs)}return Ps}function read_transposed(Fs,Ps,Hs){let Ws=Array(Fs).fill().map(()=>[]);for(let Zs=0;Zs<Ps;Zs++)read_deltas(Fs,Hs).forEach((zs,Ys)=>Ws[Ys].push(zs));return Ws}function read_linear_table(Fs,Ps){let Hs=1+Ps(),Ws=Ps(),Zs=read_array_while(Ps);return read_transposed(Zs.length,1+Fs,Ps).flatMap((Ys,Va)=>{let[Xs,...Ma]=Ys;return Array(Zs[Va]).fill().map((qs,Js)=>{let Mc=Js*Ws;return[Xs+Js*Hs,Ma.map(ol=>ol+Mc)]})})}function read_replacement_table(Fs,Ps){let Hs=1+Ps();return read_transposed(Hs,1+Fs,Ps).map(Zs=>[Zs[0],Zs.slice(1)])}function read_trie(Fs){let Ps=[],Hs=read_sorted(Fs);return Zs(Ws([]),[]),Ps;function Ws(zs){let Ys=Fs(),Va=read_array_while(()=>{let Xs=read_sorted(Fs).map(Ma=>Hs[Ma]);if(Xs.length)return Ws(Xs)});return{S:Ys,B:Va,Q:zs}}function Zs({S:zs,B:Ys},Va,Xs){if(!(zs&4&&Xs===Va[Va.length-1])){zs&2&&(Xs=Va[Va.length-1]),zs&1&&Ps.push(Va);for(let Ma of Ys)for(let qs of Ma.Q)Zs(Ma,[...Va,qs],Xs)}}}function hex_cp(Fs){return Fs.toString(16).toUpperCase().padStart(2,"0")}function quote_cp(Fs){return`{${hex_cp(Fs)}}`}function explode_cp(Fs){let Ps=[];for(let Hs=0,Ws=Fs.length;Hs<Ws;){let Zs=Fs.codePointAt(Hs);Hs+=Zs<65536?1:2,Ps.push(Zs)}return Ps}function str_from_cps(Fs){let Hs=Fs.length;if(Hs<4096)return String.fromCodePoint(...Fs);let Ws=[];for(let Zs=0;Zs<Hs;)Ws.push(String.fromCodePoint(...Fs.slice(Zs,Zs+=4096)));return Ws.join("")}function compare_arrays(Fs,Ps){let Hs=Fs.length,Ws=Hs-Ps.length;for(let Zs=0;Ws==0&&Zs<Hs;Zs++)Ws=Fs[Zs]-Ps[Zs];return Ws}var COMPRESSED="AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFL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ofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";const S0=44032,L0=4352,V0=4449,T0=4519,L_COUNT=19,V_COUNT=21,T_COUNT=28,N_COUNT=V_COUNT*T_COUNT,S_COUNT=L_COUNT*N_COUNT,S1=S0+S_COUNT,L1=L0+L_COUNT,V1=V0+V_COUNT,T1=T0+T_COUNT;function unpack_cc(Fs){return Fs>>24&255}function unpack_cp(Fs){return Fs&16777215}let SHIFTED_RANK,EXCLUSIONS,DECOMP,RECOMP;function init$1(){let Fs=read_compressed_payload(COMPRESSED);SHIFTED_RANK=new Map(read_sorted_arrays(Fs).flatMap((Ps,Hs)=>Ps.map(Ws=>[Ws,Hs+1<<24]))),EXCLUSIONS=new Set(read_sorted(Fs)),DECOMP=new Map,RECOMP=new Map;for(let[Ps,Hs]of read_mapped(Fs)){if(!EXCLUSIONS.has(Ps)&&Hs.length==2){let[Ws,Zs]=Hs,zs=RECOMP.get(Ws);zs||(zs=new Map,RECOMP.set(Ws,zs)),zs.set(Zs,Ps)}DECOMP.set(Ps,Hs.reverse())}}function is_hangul(Fs){return Fs>=S0&&Fs<S1}function compose_pair(Fs,Ps){if(Fs>=L0&&Fs<L1&&Ps>=V0&&Ps<V1)return S0+(Fs-L0)*N_COUNT+(Ps-V0)*T_COUNT;if(is_hangul(Fs)&&Ps>T0&&Ps<T1&&(Fs-S0)%T_COUNT==0)return Fs+(Ps-T0);{let Hs=RECOMP.get(Fs);return Hs&&(Hs=Hs.get(Ps),Hs)?Hs:-1}}function decomposed(Fs){SHIFTED_RANK||init$1();let Ps=[],Hs=[],Ws=!1;function Zs(zs){let Ys=SHIFTED_RANK.get(zs);Ys&&(Ws=!0,zs|=Ys),Ps.push(zs)}for(let zs of Fs)for(;;){if(zs<128)Ps.push(zs);else if(is_hangul(zs)){let Ys=zs-S0,Va=Ys/N_COUNT|0,Xs=Ys%N_COUNT/T_COUNT|0,Ma=Ys%T_COUNT;Zs(L0+Va),Zs(V0+Xs),Ma>0&&Zs(T0+Ma)}else{let Ys=DECOMP.get(zs);Ys?Hs.push(...Ys):Zs(zs)}if(!Hs.length)break;zs=Hs.pop()}if(Ws&&Ps.length>1){let zs=unpack_cc(Ps[0]);for(let Ys=1;Ys<Ps.length;Ys++){let Va=unpack_cc(Ps[Ys]);if(Va==0||zs<=Va){zs=Va;continue}let Xs=Ys-1;for(;;){let Ma=Ps[Xs+1];if(Ps[Xs+1]=Ps[Xs],Ps[Xs]=Ma,!Xs||(zs=unpack_cc(Ps[--Xs]),zs<=Va))break}zs=unpack_cc(Ps[Ys])}}return Ps}function composed_from_decomposed(Fs){let Ps=[],Hs=[],Ws=-1,Zs=0;for(let zs of Fs){let Ys=unpack_cc(zs),Va=unpack_cp(zs);if(Ws==-1)Ys==0?Ws=Va:Ps.push(Va);else if(Zs>0&&Zs>=Ys)Ys==0?(Ps.push(Ws,...Hs),Hs.length=0,Ws=Va):Hs.push(Va),Zs=Ys;else{let Xs=compose_pair(Ws,Va);Xs>=0?Ws=Xs:Zs==0&&Ys==0?(Ps.push(Ws),Ws=Va):(Hs.push(Va),Zs=Ys)}}return Ws>=0&&Ps.push(Ws,...Hs),Ps}function nfd(Fs){return decomposed(Fs).map(unpack_cp)}function nfc(Fs){return composed_from_decomposed(decomposed(Fs))}const HYPHEN=45,STOP_CH=".",FE0F=65039,UNIQUE_PH=1,Array_from=Fs=>Array.from(Fs);function group_has_cp(Fs,Ps){return Fs.P.has(Ps)||Fs.Q.has(Ps)}class Emoji extends Array{get is_emoji(){return!0}}let MAPPED,IGNORED,CM,NSM,ESCAPE,GROUPS,WHOLE_VALID,WHOLE_MAP,VALID,EMOJI_LIST,EMOJI_ROOT;function init(){if(MAPPED)return;let Fs=read_compressed_payload(COMPRESSED$1);const Ps=()=>read_sorted(Fs),Hs=()=>new Set(Ps()),Ws=(qs,Js)=>Js.forEach(Mc=>qs.add(Mc));MAPPED=new Map(read_mapped(Fs)),IGNORED=Hs(),CM=Ps(),NSM=new Set(Ps().map(qs=>CM[qs])),CM=new Set(CM),ESCAPE=Hs(),Hs();let Zs=read_sorted_arrays(Fs),zs=Fs();const Ys=()=>{let qs=new Set;return Ps().forEach(Js=>Ws(qs,Zs[Js])),Ws(qs,Ps()),qs};GROUPS=read_array_while(qs=>{let Js=read_array_while(Fs).map(Mc=>Mc+96);if(Js.length){let Mc=qs>=zs;Js[0]-=32,Js=str_from_cps(Js),Mc&&(Js=`Restricted[${Js}]`);let ol=Ys(),Vc=Ys(),Dc=!Fs();return{N:Js,P:ol,Q:Vc,M:Dc,R:Mc}}}),WHOLE_VALID=Hs(),WHOLE_MAP=new Map;let Va=Ps().concat(Array_from(WHOLE_VALID)).sort((qs,Js)=>qs-Js);Va.forEach((qs,Js)=>{let Mc=Fs(),ol=Va[Js]=Mc?Va[Js-Mc]:{V:[],M:new Map};ol.V.push(qs),WHOLE_VALID.has(qs)||WHOLE_MAP.set(qs,ol)});for(let{V:qs,M:Js}of new Set(WHOLE_MAP.values())){let Mc=[];for(let Vc of qs){let Dc=GROUPS.filter(ll=>group_has_cp(ll,Vc)),sl=Mc.find(({G:ll})=>Dc.some(hl=>ll.has(hl)));sl||(sl={G:new Set,V:[]},Mc.push(sl)),sl.V.push(Vc),Ws(sl.G,Dc)}let ol=Mc.flatMap(Vc=>Array_from(Vc.G));for(let{G:Vc,V:Dc}of Mc){let sl=new Set(ol.filter(ll=>!Vc.has(ll)));for(let ll of Dc)Js.set(ll,sl)}}VALID=new Set;let Xs=new Set;const Ma=qs=>VALID.has(qs)?Xs.add(qs):VALID.add(qs);for(let qs of GROUPS){for(let Js of qs.P)Ma(Js);for(let Js of qs.Q)Ma(Js)}for(let qs of VALID)!WHOLE_MAP.has(qs)&&!Xs.has(qs)&&WHOLE_MAP.set(qs,UNIQUE_PH);Ws(VALID,nfd(VALID)),EMOJI_LIST=read_trie(Fs).map(qs=>Emoji.from(qs)).sort(compare_arrays),EMOJI_ROOT=new Map;for(let qs of EMOJI_LIST){let Js=[EMOJI_ROOT];for(let Mc of qs){let ol=Js.map(Vc=>{let Dc=Vc.get(Mc);return Dc||(Dc=new Map,Vc.set(Mc,Dc)),Dc});Mc===FE0F?Js.push(...ol):Js=ol}for(let Mc of Js)Mc.V=qs}}function quoted_cp(Fs){return(should_escape(Fs)?"":`${bidi_qq(safe_str_from_cps([Fs]))} `)+quote_cp(Fs)}function bidi_qq(Fs){return`"${Fs}"‎`}function check_label_extension(Fs){if(Fs.length>=4&&Fs[2]==HYPHEN&&Fs[3]==HYPHEN)throw new Error(`invalid label extension: "${str_from_cps(Fs.slice(0,4))}"`)}function check_leading_underscore(Fs){for(let Hs=Fs.lastIndexOf(95);Hs>0;)if(Fs[--Hs]!==95)throw new Error("underscore allowed only at start")}function check_fenced(Fs){let Ps=Fs[0],Hs=FENCED.get(Ps);if(Hs)throw error_placement(`leading ${Hs}`);let Ws=Fs.length,Zs=-1;for(let zs=1;zs<Ws;zs++){Ps=Fs[zs];let Ys=FENCED.get(Ps);if(Ys){if(Zs==zs)throw error_placement(`${Hs} + ${Ys}`);Zs=zs+1,Hs=Ys}}if(Zs==Ws)throw error_placement(`trailing ${Hs}`)}function safe_str_from_cps(Fs,Ps=1/0,Hs=quote_cp){let Ws=[];is_combining_mark(Fs[0])&&Ws.push("◌"),Fs.length>Ps&&(Ps>>=1,Fs=[...Fs.slice(0,Ps),8230,...Fs.slice(-Ps)]);let Zs=0,zs=Fs.length;for(let Ys=0;Ys<zs;Ys++){let Va=Fs[Ys];should_escape(Va)&&(Ws.push(str_from_cps(Fs.slice(Zs,Ys))),Ws.push(Hs(Va)),Zs=Ys+1)}return Ws.push(str_from_cps(Fs.slice(Zs,zs))),Ws.join("")}function is_combining_mark(Fs){return init(),CM.has(Fs)}function should_escape(Fs){return init(),ESCAPE.has(Fs)}function ens_normalize(Fs){return flatten(split(Fs,nfc,filter_fe0f))}function split(Fs,Ps,Hs){if(!Fs)return[];init();let Ws=0;return Fs.split(STOP_CH).map(Zs=>{let zs=explode_cp(Zs),Ys={input:zs,offset:Ws};Ws+=zs.length+1;try{let Va=Ys.tokens=tokens_from_str(zs,Ps,Hs),Xs=Va.length,Ma;if(!Xs)throw new Error("empty label");let qs=Ys.output=Va.flat();if(check_leading_underscore(qs),!(Ys.emoji=Xs>1||Va[0].is_emoji)&&qs.every(Mc=>Mc<128))check_label_extension(qs),Ma="ASCII";else{let Mc=Va.flatMap(ol=>ol.is_emoji?[]:ol);if(!Mc.length)Ma="Emoji";else{if(CM.has(qs[0]))throw error_placement("leading combining mark");for(let Dc=1;Dc<Xs;Dc++){let sl=Va[Dc];if(!sl.is_emoji&&CM.has(sl[0]))throw error_placement(`emoji + combining mark: "${str_from_cps(Va[Dc-1])} + ${safe_str_from_cps([sl[0]])}"`)}check_fenced(qs);let ol=Array_from(new Set(Mc)),[Vc]=determine_group(ol);check_group(Vc,Mc),check_whole(Vc,ol),Ma=Vc.N}}Ys.type=Ma}catch(Va){Ys.error=Va}return Ys})}function check_whole(Fs,Ps){let Hs,Ws=[];for(let Zs of Ps){let zs=WHOLE_MAP.get(Zs);if(zs===UNIQUE_PH)return;if(zs){let Ys=zs.M.get(Zs);if(Hs=Hs?Hs.filter(Va=>Ys.has(Va)):Array_from(Ys),!Hs.length)return}else Ws.push(Zs)}if(Hs){for(let Zs of Hs)if(Ws.every(zs=>group_has_cp(Zs,zs)))throw new Error(`whole-script confusable: ${Fs.N}/${Zs.N}`)}}function determine_group(Fs){let Ps=GROUPS;for(let Hs of Fs){let Ws=Ps.filter(Zs=>group_has_cp(Zs,Hs));if(!Ws.length)throw GROUPS.some(Zs=>group_has_cp(Zs,Hs))?error_group_member(Ps[0],Hs):error_disallowed(Hs);if(Ps=Ws,Ws.length==1)break}return Ps}function flatten(Fs){return Fs.map(({input:Ps,error:Hs,output:Ws})=>{if(Hs){let Zs=Hs.message;throw new Error(Fs.length==1?Zs:`Invalid label ${bidi_qq(safe_str_from_cps(Ps,63))}: ${Zs}`)}return str_from_cps(Ws)}).join(STOP_CH)}function error_disallowed(Fs){return new Error(`disallowed character: ${quoted_cp(Fs)}`)}function error_group_member(Fs,Ps){let Hs=quoted_cp(Ps),Ws=GROUPS.find(Zs=>Zs.P.has(Ps));return Ws&&(Hs=`${Ws.N} ${Hs}`),new Error(`illegal mixture: ${Fs.N} + ${Hs}`)}function error_placement(Fs){return new Error(`illegal placement: ${Fs}`)}function check_group(Fs,Ps){for(let Hs of Ps)if(!group_has_cp(Fs,Hs))throw error_group_member(Fs,Hs);if(Fs.M){let Hs=nfd(Ps);for(let Ws=1,Zs=Hs.length;Ws<Zs;Ws++)if(NSM.has(Hs[Ws])){let zs=Ws+1;for(let Ys;zs<Zs&&NSM.has(Ys=Hs[zs]);zs++)for(let Va=Ws;Va<zs;Va++)if(Hs[Va]==Ys)throw new Error(`duplicate non-spacing marks: ${quoted_cp(Ys)}`);if(zs-Ws>NSM_MAX)throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(Hs.slice(Ws-1,zs)))} (${zs-Ws}/${NSM_MAX})`);Ws=zs}}}function tokens_from_str(Fs,Ps,Hs){let Ws=[],Zs=[];for(Fs=Fs.slice().reverse();Fs.length;){let zs=consume_emoji_reversed(Fs);if(zs)Zs.length&&(Ws.push(Ps(Zs)),Zs=[]),Ws.push(Hs(zs));else{let Ys=Fs.pop();if(VALID.has(Ys))Zs.push(Ys);else{let Va=MAPPED.get(Ys);if(Va)Zs.push(...Va);else if(!IGNORED.has(Ys))throw error_disallowed(Ys)}}}return Zs.length&&Ws.push(Ps(Zs)),Ws}function filter_fe0f(Fs){return Fs.filter(Ps=>Ps!=FE0F)}function consume_emoji_reversed(Fs,Ps){let Hs=EMOJI_ROOT,Ws,Zs=Fs.length;for(;Zs&&(Hs=Hs.get(Fs[--Zs]),!!Hs);){let{V:zs}=Hs;zs&&(Ws=zs,Fs.length=Zs)}return Ws}const Zeros=new Uint8Array(32);Zeros.fill(0);function checkComponent(Fs){return assertArgument(Fs.length!==0,"invalid ENS name; empty component","comp",Fs),Fs}function ensNameSplit(Fs){const Ps=toUtf8Bytes(ensNormalize(Fs)),Hs=[];if(Fs.length===0)return Hs;let Ws=0;for(let Zs=0;Zs<Ps.length;Zs++)Ps[Zs]===46&&(Hs.push(checkComponent(Ps.slice(Ws,Zs))),Ws=Zs+1);return assertArgument(Ws<Ps.length,"invalid ENS name; empty component","name",Fs),Hs.push(checkComponent(Ps.slice(Ws))),Hs}function ensNormalize(Fs){try{if(Fs.length===0)throw new Error("empty label");return ens_normalize(Fs)}catch(Ps){assertArgument(!1,`invalid ENS name (${Ps.message})`,"name",Fs)}}function namehash(Fs){assertArgument(typeof Fs=="string","invalid ENS name; not a string","name",Fs),assertArgument(Fs.length,"invalid ENS name (empty label)","name",Fs);let Ps=Zeros;const Hs=ensNameSplit(Fs);for(;Hs.length;)Ps=keccak256(concat([Ps,keccak256(Hs.pop())]));return hexlify(Ps)}function dnsEncode(Fs,Ps){const Hs=Ps;return assertArgument(Hs<=255,"DNS encoded label cannot exceed 255","length",Hs),hexlify(concat(ensNameSplit(Fs).map(Ws=>{assertArgument(Ws.length<=Hs,`label ${JSON.stringify(Fs)} exceeds ${Hs} bytes`,"name",Fs);const Zs=new Uint8Array(Ws.length+1);return Zs.set(Ws,1),Zs[0]=Zs.length-1,Zs})))+"00"}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1),BN_0$3=BigInt(0),BN_1=BigInt(1),BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(Fs){const Ps=getBytes(Fs),Hs=Ps.length%32;return Hs?concat([Ps,padding.slice(Hs)]):hexlify(Ps)}const hexTrue=toBeHex(BN_1,32),hexFalse=toBeHex(BN_0$3,32),domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(Fs){return function(Ps){return assertArgument(typeof Ps=="string",`invalid domain value for ${JSON.stringify(Fs)}`,`domain.${Fs}`,Ps),Ps}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(Fs){const Ps=getBigInt(Fs,"domain.chainId");return assertArgument(Ps>=0,"invalid chain ID","domain.chainId",Fs),Number.isSafeInteger(Ps)?Number(Ps):toQuantity(Ps)},verifyingContract:function(Fs){try{return getAddress(Fs).toLowerCase()}catch{}assertArgument(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",Fs)},salt:function(Fs){const Ps=getBytes(Fs,"domain.salt");return assertArgument(Ps.length===32,'invalid domain value "salt"',"domain.salt",Fs),hexlify(Ps)}};function getBaseEncoder(Fs){{const Ps=Fs.match(/^(u?)int(\d+)$/);if(Ps){const Hs=Ps[1]==="",Ws=parseInt(Ps[2]);assertArgument(Ws%8===0&&Ws!==0&&Ws<=256&&Ps[2]===String(Ws),"invalid numeric width","type",Fs);const Zs=mask(BN_MAX_UINT256,Hs?Ws-1:Ws),zs=Hs?(Zs+BN_1)*BN__1:BN_0$3;return function(Ys){const Va=getBigInt(Ys,"value");return assertArgument(Va>=zs&&Va<=Zs,`value out-of-bounds for ${Fs}`,"value",Va),toBeHex(Hs?toTwos(Va,256):Va,32)}}}{const Ps=Fs.match(/^bytes(\d+)$/);if(Ps){const Hs=parseInt(Ps[1]);return assertArgument(Hs!==0&&Hs<=32&&Ps[1]===String(Hs),"invalid bytes width","type",Fs),function(Ws){const Zs=getBytes(Ws);return assertArgument(Zs.length===Hs,`invalid length for ${Fs}`,"value",Ws),hexPadRight(Ws)}}}switch(Fs){case"address":return function(Ps){return zeroPadValue(getAddress(Ps),32)};case"bool":return function(Ps){return Ps?hexTrue:hexFalse};case"bytes":return function(Ps){return keccak256(Ps)};case"string":return function(Ps){return id(Ps)}}return null}function encodeType(Fs,Ps){return`${Fs}(${Ps.map(({name:Hs,type:Ws})=>Ws+" "+Hs).join(",")})`}function splitArray(Fs){const Ps=Fs.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return Ps?{base:Ps[1],index:Ps[2]+Ps[4],array:{base:Ps[1],prefix:Ps[1]+Ps[2],count:Ps[5]?parseInt(Ps[5]):-1}}:{base:Fs}}class TypedDataEncoder{primaryType;#e;get types(){return JSON.parse(this.#e)}#t;#r;constructor(Ps){this.#t=new Map,this.#r=new Map;const Hs=new Map,Ws=new Map,Zs=new Map,zs={};Object.keys(Ps).forEach(Xs=>{zs[Xs]=Ps[Xs].map(({name:Ma,type:qs})=>{let{base:Js,index:Mc}=splitArray(qs);return Js==="int"&&!Ps.int&&(Js="int256"),Js==="uint"&&!Ps.uint&&(Js="uint256"),{name:Ma,type:Js+(Mc||"")}}),Hs.set(Xs,new Set),Ws.set(Xs,[]),Zs.set(Xs,new Set)}),this.#e=JSON.stringify(zs);for(const Xs in zs){const Ma=new Set;for(const qs of zs[Xs]){assertArgument(!Ma.has(qs.name),`duplicate variable name ${JSON.stringify(qs.name)} in ${JSON.stringify(Xs)}`,"types",Ps),Ma.add(qs.name);const Js=splitArray(qs.type).base;assertArgument(Js!==Xs,`circular type reference to ${JSON.stringify(Js)}`,"types",Ps),!getBaseEncoder(Js)&&(assertArgument(Ws.has(Js),`unknown type ${JSON.stringify(Js)}`,"types",Ps),Ws.get(Js).push(Xs),Hs.get(Xs).add(Js))}}const Ys=Array.from(Ws.keys()).filter(Xs=>Ws.get(Xs).length===0);assertArgument(Ys.length!==0,"missing primary type","types",Ps),assertArgument(Ys.length===1,`ambiguous primary types or unused types: ${Ys.map(Xs=>JSON.stringify(Xs)).join(", ")}`,"types",Ps),defineProperties(this,{primaryType:Ys[0]});function Va(Xs,Ma){assertArgument(!Ma.has(Xs),`circular type reference to ${JSON.stringify(Xs)}`,"types",Ps),Ma.add(Xs);for(const qs of Hs.get(Xs))if(Ws.has(qs)){Va(qs,Ma);for(const Js of Ma)Zs.get(Js).add(qs)}Ma.delete(Xs)}Va(this.primaryType,new Set);for(const[Xs,Ma]of Zs){const qs=Array.from(Ma);qs.sort(),this.#t.set(Xs,encodeType(Xs,zs[Xs])+qs.map(Js=>encodeType(Js,zs[Js])).join(""))}}getEncoder(Ps){let Hs=this.#r.get(Ps);return Hs||(Hs=this.#n(Ps),this.#r.set(Ps,Hs)),Hs}#n(Ps){{const Zs=getBaseEncoder(Ps);if(Zs)return Zs}const Hs=splitArray(Ps).array;if(Hs){const Zs=Hs.prefix,zs=this.getEncoder(Zs);return Ys=>{assertArgument(Hs.count===-1||Hs.count===Ys.length,`array length mismatch; expected length ${Hs.count}`,"value",Ys);let Va=Ys.map(zs);return this.#t.has(Zs)&&(Va=Va.map(keccak256)),keccak256(concat(Va))}}const Ws=this.types[Ps];if(Ws){const Zs=id(this.#t.get(Ps));return zs=>{const Ys=Ws.map(({name:Va,type:Xs})=>{const Ma=this.getEncoder(Xs)(zs[Va]);return this.#t.has(Xs)?keccak256(Ma):Ma});return Ys.unshift(Zs),concat(Ys)}}assertArgument(!1,`unknown type: ${Ps}`,"type",Ps)}encodeType(Ps){const Hs=this.#t.get(Ps);return assertArgument(Hs,`unknown type: ${JSON.stringify(Ps)}`,"name",Ps),Hs}encodeData(Ps,Hs){return this.getEncoder(Ps)(Hs)}hashStruct(Ps,Hs){return keccak256(this.encodeData(Ps,Hs))}encode(Ps){return this.encodeData(this.primaryType,Ps)}hash(Ps){return this.hashStruct(this.primaryType,Ps)}_visit(Ps,Hs,Ws){if(getBaseEncoder(Ps))return Ws(Ps,Hs);const Zs=splitArray(Ps).array;if(Zs)return assertArgument(Zs.count===-1||Zs.count===Hs.length,`array length mismatch; expected length ${Zs.count}`,"value",Hs),Hs.map(Ys=>this._visit(Zs.prefix,Ys,Ws));const zs=this.types[Ps];if(zs)return zs.reduce((Ys,{name:Va,type:Xs})=>(Ys[Va]=this._visit(Xs,Hs[Va],Ws),Ys),{});assertArgument(!1,`unknown type: ${Ps}`,"type",Ps)}visit(Ps,Hs){return this._visit(this.primaryType,Ps,Hs)}static from(Ps){return new TypedDataEncoder(Ps)}static getPrimaryType(Ps){return TypedDataEncoder.from(Ps).primaryType}static hashStruct(Ps,Hs,Ws){return TypedDataEncoder.from(Hs).hashStruct(Ps,Ws)}static hashDomain(Ps){const Hs=[];for(const Ws in Ps){if(Ps[Ws]==null)continue;const Zs=domainFieldTypes[Ws];assertArgument(Zs,`invalid typed-data domain key: ${JSON.stringify(Ws)}`,"domain",Ps),Hs.push({name:Ws,type:Zs})}return Hs.sort((Ws,Zs)=>domainFieldNames.indexOf(Ws.name)-domainFieldNames.indexOf(Zs.name)),TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:Hs},Ps)}static encode(Ps,Hs,Ws){return concat(["0x1901",TypedDataEncoder.hashDomain(Ps),TypedDataEncoder.from(Hs).hash(Ws)])}static hash(Ps,Hs,Ws){return keccak256(TypedDataEncoder.encode(Ps,Hs,Ws))}static async resolveNames(Ps,Hs,Ws,Zs){Ps=Object.assign({},Ps);for(const Va in Ps)Ps[Va]==null&&delete Ps[Va];const zs={};Ps.verifyingContract&&!isHexString(Ps.verifyingContract,20)&&(zs[Ps.verifyingContract]="0x");const Ys=TypedDataEncoder.from(Hs);Ys.visit(Ws,(Va,Xs)=>(Va==="address"&&!isHexString(Xs,20)&&(zs[Xs]="0x"),Xs));for(const Va in zs)zs[Va]=await Zs(Va);return Ps.verifyingContract&&zs[Ps.verifyingContract]&&(Ps.verifyingContract=zs[Ps.verifyingContract]),Ws=Ys.visit(Ws,(Va,Xs)=>Va==="address"&&zs[Xs]?zs[Xs]:Xs),{domain:Ps,value:Ws}}static getPayload(Ps,Hs,Ws){TypedDataEncoder.hashDomain(Ps);const Zs={},zs=[];domainFieldNames.forEach(Xs=>{const Ma=Ps[Xs];Ma!=null&&(Zs[Xs]=domainChecks[Xs](Ma),zs.push({name:Xs,type:domainFieldTypes[Xs]}))});const Ys=TypedDataEncoder.from(Hs);Hs=Ys.types;const Va=Object.assign({},Hs);return assertArgument(Va.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",Hs),Va.EIP712Domain=zs,Ys.encode(Ws),{types:Va,domain:Zs,primaryType:Ys.primaryType,message:Ys.visit(Ws,(Xs,Ma)=>{if(Xs.match(/^bytes(\d*)/))return hexlify(getBytes(Ma));if(Xs.match(/^u?int/))return getBigInt(Ma).toString();switch(Xs){case"address":return Ma.toLowerCase();case"bool":return!!Ma;case"string":return assertArgument(typeof Ma=="string","invalid string","value",Ma),Ma}assertArgument(!1,"unsupported type","type",Xs)})}}}function setify(Fs){const Ps=new Set;return Fs.forEach(Hs=>Ps.add(Hs)),Object.freeze(Ps)}const _kwVisibDeploy="external public payable override",KwVisibDeploy=setify(_kwVisibDeploy.split(" ")),_kwVisib="constant external internal payable private public pure view override",KwVisib=setify(_kwVisib.split(" ")),_kwTypes="constructor error event fallback function receive struct",KwTypes=setify(_kwTypes.split(" ")),_kwModifiers="calldata memory storage payable indexed",KwModifiers=setify(_kwModifiers.split(" ")),_kwOther="tuple returns",_keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" "),Keywords=setify(_keywords.split(" ")),SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},regexWhitespacePrefix=new RegExp("^(\\s*)"),regexNumberPrefix=new RegExp("^([0-9]+)"),regexIdPrefix=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),regexId=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class TokenString{#e;#t;get offset(){return this.#e}get length(){return this.#t.length-this.#e}constructor(Ps){this.#e=0,this.#t=Ps.slice()}clone(){return new TokenString(this.#t)}reset(){this.#e=0}#r(Ps=0,Hs=0){return new TokenString(this.#t.slice(Ps,Hs).map(Ws=>Object.freeze(Object.assign({},Ws,{match:Ws.match-Ps,linkBack:Ws.linkBack-Ps,linkNext:Ws.linkNext-Ps}))))}popKeyword(Ps){const Hs=this.peek();if(Hs.type!=="KEYWORD"||!Ps.has(Hs.text))throw new Error(`expected keyword ${Hs.text}`);return this.pop().text}popType(Ps){if(this.peek().type!==Ps){const Hs=this.peek();throw new Error(`expected ${Ps}; got ${Hs.type} ${JSON.stringify(Hs.text)}`)}return this.pop().text}popParen(){const Ps=this.peek();if(Ps.type!=="OPEN_PAREN")throw new Error("bad start");const Hs=this.#r(this.#e+1,Ps.match+1);return this.#e=Ps.match+1,Hs}popParams(){const Ps=this.peek();if(Ps.type!=="OPEN_PAREN")throw new Error("bad start");const Hs=[];for(;this.#e<Ps.match-1;){const Ws=this.peek().linkNext;Hs.push(this.#r(this.#e+1,Ws)),this.#e=Ws}return this.#e=Ps.match+1,Hs}peek(){if(this.#e>=this.#t.length)throw new Error("out-of-bounds");return this.#t[this.#e]}peekKeyword(Ps){const Hs=this.peekType("KEYWORD");return Hs!=null&&Ps.has(Hs)?Hs:null}peekType(Ps){if(this.length===0)return null;const Hs=this.peek();return Hs.type===Ps?Hs.text:null}pop(){const Ps=this.peek();return this.#e++,Ps}toString(){const Ps=[];for(let Hs=this.#e;Hs<this.#t.length;Hs++){const Ws=this.#t[Hs];Ps.push(`${Ws.type}:${Ws.text}`)}return`<TokenString ${Ps.join(" ")}>`}}function lex(Fs){const Ps=[],Hs=Ys=>{const Va=zs<Fs.length?JSON.stringify(Fs[zs]):"$EOI";throw new Error(`invalid token ${Va} at ${zs}: ${Ys}`)};let Ws=[],Zs=[],zs=0;for(;zs<Fs.length;){let Ys=Fs.substring(zs),Va=Ys.match(regexWhitespacePrefix);Va&&(zs+=Va[1].length,Ys=Fs.substring(zs));const Xs={depth:Ws.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:zs,value:-1};Ps.push(Xs);let Ma=SimpleTokens[Ys[0]]||"";if(Ma){if(Xs.type=Ma,Xs.text=Ys[0],zs++,Ma==="OPEN_PAREN")Ws.push(Ps.length-1),Zs.push(Ps.length-1);else if(Ma=="CLOSE_PAREN")Ws.length===0&&Hs("no matching open bracket"),Xs.match=Ws.pop(),Ps[Xs.match].match=Ps.length-1,Xs.depth--,Xs.linkBack=Zs.pop(),Ps[Xs.linkBack].linkNext=Ps.length-1;else if(Ma==="COMMA")Xs.linkBack=Zs.pop(),Ps[Xs.linkBack].linkNext=Ps.length-1,Zs.push(Ps.length-1);else if(Ma==="OPEN_BRACKET")Xs.type="BRACKET";else if(Ma==="CLOSE_BRACKET"){let qs=Ps.pop().text;if(Ps.length>0&&Ps[Ps.length-1].type==="NUMBER"){const Js=Ps.pop().text;qs=Js+qs,Ps[Ps.length-1].value=getNumber(Js)}if(Ps.length===0||Ps[Ps.length-1].type!=="BRACKET")throw new Error("missing opening bracket");Ps[Ps.length-1].text+=qs}continue}if(Va=Ys.match(regexIdPrefix),Va){if(Xs.text=Va[1],zs+=Xs.text.length,Keywords.has(Xs.text)){Xs.type="KEYWORD";continue}if(Xs.text.match(regexType)){Xs.type="TYPE";continue}Xs.type="ID";continue}if(Va=Ys.match(regexNumberPrefix),Va){Xs.text=Va[1],Xs.type="NUMBER",zs+=Xs.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(Ys[0])} at position ${zs}`)}return new TokenString(Ps.map(Ys=>Object.freeze(Ys)))}function allowSingle(Fs,Ps){let Hs=[];for(const Ws in Ps.keys())Fs.has(Ws)&&Hs.push(Ws);if(Hs.length>1)throw new Error(`conflicting types: ${Hs.join(", ")}`)}function consumeName(Fs,Ps){if(Ps.peekKeyword(KwTypes)){const Hs=Ps.pop().text;if(Hs!==Fs)throw new Error(`expected ${Fs}, got ${Hs}`)}return Ps.popType("ID")}function consumeKeywords(Fs,Ps){const Hs=new Set;for(;;){const Ws=Fs.peekType("KEYWORD");if(Ws==null||Ps&&!Ps.has(Ws))break;if(Fs.pop(),Hs.has(Ws))throw new Error(`duplicate keywords: ${JSON.stringify(Ws)}`);Hs.add(Ws)}return Object.freeze(Hs)}function consumeMutability(Fs){let Ps=consumeKeywords(Fs,KwVisib);return allowSingle(Ps,setify("constant payable nonpayable".split(" "))),allowSingle(Ps,setify("pure view payable nonpayable".split(" "))),Ps.has("view")?"view":Ps.has("pure")?"pure":Ps.has("payable")?"payable":Ps.has("nonpayable")?"nonpayable":Ps.has("constant")?"view":"nonpayable"}function consumeParams(Fs,Ps){return Fs.popParams().map(Hs=>ParamType.from(Hs,Ps))}function consumeGas(Fs){if(Fs.peekType("AT")){if(Fs.pop(),Fs.peekType("NUMBER"))return getBigInt(Fs.pop().text);throw new Error("invalid gas")}return null}function consumeEoi(Fs){if(Fs.length)throw new Error(`unexpected tokens at offset ${Fs.offset}: ${Fs.toString()}`)}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(Fs){const Ps=Fs.match(regexType);if(assertArgument(Ps,"invalid type","type",Fs),Fs==="uint")return"uint256";if(Fs==="int")return"int256";if(Ps[2]){const Hs=parseInt(Ps[2]);assertArgument(Hs!==0&&Hs<=32,"invalid bytes length","type",Fs)}else if(Ps[3]){const Hs=parseInt(Ps[3]);assertArgument(Hs!==0&&Hs<=256&&Hs%8===0,"invalid numeric width","type",Fs)}return Fs}const _guard={},internal$1=Symbol.for("_ethers_internal"),ParamTypeInternal="_ParamTypeInternal",ErrorFragmentInternal="_ErrorInternal",EventFragmentInternal="_EventInternal",ConstructorFragmentInternal="_ConstructorInternal",FallbackFragmentInternal="_FallbackInternal",FunctionFragmentInternal="_FunctionInternal",StructFragmentInternal="_StructInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(Ps,Hs,Ws,Zs,zs,Ys,Va,Xs){if(assertPrivate(Ps,_guard,"ParamType"),Object.defineProperty(this,internal$1,{value:ParamTypeInternal}),Ys&&(Ys=Object.freeze(Ys.slice())),Zs==="array"){if(Va==null||Xs==null)throw new Error("")}else if(Va!=null||Xs!=null)throw new Error("");if(Zs==="tuple"){if(Ys==null)throw new Error("")}else if(Ys!=null)throw new Error("");defineProperties(this,{name:Hs,type:Ws,baseType:Zs,indexed:zs,components:Ys,arrayLength:Va,arrayChildren:Xs})}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json"){const Ws=this.name||"";if(this.isArray()){const zs=JSON.parse(this.arrayChildren.format("json"));return zs.name=Ws,zs.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(zs)}const Zs={type:this.baseType==="tuple"?"tuple":this.type,name:Ws};return typeof this.indexed=="boolean"&&(Zs.indexed=this.indexed),this.isTuple()&&(Zs.components=this.components.map(zs=>JSON.parse(zs.format(Ps)))),JSON.stringify(Zs)}let Hs="";return this.isArray()?(Hs+=this.arrayChildren.format(Ps),Hs+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?Hs+="("+this.components.map(Ws=>Ws.format(Ps)).join(Ps==="full"?", ":",")+")":Hs+=this.type,Ps!=="sighash"&&(this.indexed===!0&&(Hs+=" indexed"),Ps==="full"&&this.name&&(Hs+=" "+this.name)),Hs}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(Ps,Hs){if(this.isArray()){if(!Array.isArray(Ps))throw new Error("invalid array value");if(this.arrayLength!==-1&&Ps.length!==this.arrayLength)throw new Error("array is wrong length");const Ws=this;return Ps.map(Zs=>Ws.arrayChildren.walk(Zs,Hs))}if(this.isTuple()){if(!Array.isArray(Ps))throw new Error("invalid tuple value");if(Ps.length!==this.components.length)throw new Error("array is wrong length");const Ws=this;return Ps.map((Zs,zs)=>Ws.components[zs].walk(Zs,Hs))}return Hs(this.type,Ps)}#e(Ps,Hs,Ws,Zs){if(this.isArray()){if(!Array.isArray(Hs))throw new Error("invalid array value");if(this.arrayLength!==-1&&Hs.length!==this.arrayLength)throw new Error("array is wrong length");const Ys=this.arrayChildren,Va=Hs.slice();Va.forEach((Xs,Ma)=>{Ys.#e(Ps,Xs,Ws,qs=>{Va[Ma]=qs})}),Zs(Va);return}if(this.isTuple()){const Ys=this.components;let Va;if(Array.isArray(Hs))Va=Hs.slice();else{if(Hs==null||typeof Hs!="object")throw new Error("invalid tuple value");Va=Ys.map(Xs=>{if(!Xs.name)throw new Error("cannot use object value with unnamed components");if(!(Xs.name in Hs))throw new Error(`missing value for component ${Xs.name}`);return Hs[Xs.name]})}if(Va.length!==this.components.length)throw new Error("array is wrong length");Va.forEach((Xs,Ma)=>{Ys[Ma].#e(Ps,Xs,Ws,qs=>{Va[Ma]=qs})}),Zs(Va);return}const zs=Ws(this.type,Hs);zs.then?Ps.push((async function(){Zs(await zs)})()):Zs(zs)}async walkAsync(Ps,Hs){const Ws=[],Zs=[Ps];return this.#e(Ws,Ps,Hs,zs=>{Zs[0]=zs}),Ws.length&&await Promise.all(Ws),Zs[0]}static from(Ps,Hs){if(ParamType.isParamType(Ps))return Ps;if(typeof Ps=="string")try{return ParamType.from(lex(Ps),Hs)}catch{assertArgument(!1,"invalid param type","obj",Ps)}else if(Ps instanceof TokenString){let Va="",Xs="",Ma=null;consumeKeywords(Ps,setify(["tuple"])).has("tuple")||Ps.peekType("OPEN_PAREN")?(Xs="tuple",Ma=Ps.popParams().map(Dc=>ParamType.from(Dc)),Va=`tuple(${Ma.map(Dc=>Dc.format()).join(",")})`):(Va=verifyBasicType(Ps.popType("TYPE")),Xs=Va);let qs=null,Js=null;for(;Ps.length&&Ps.peekType("BRACKET");){const Dc=Ps.pop();qs=new ParamType(_guard,"",Va,Xs,null,Ma,Js,qs),Js=Dc.value,Va+=Dc.text,Xs="array",Ma=null}let Mc=null;if(consumeKeywords(Ps,KwModifiers).has("indexed")){if(!Hs)throw new Error("");Mc=!0}const Vc=Ps.peekType("ID")?Ps.pop().text:"";if(Ps.length)throw new Error("leftover tokens");return new ParamType(_guard,Vc,Va,Xs,Mc,Ma,Js,qs)}const Ws=Ps.name;assertArgument(!Ws||typeof Ws=="string"&&Ws.match(regexId),"invalid name","obj.name",Ws);let Zs=Ps.indexed;Zs!=null&&(assertArgument(Hs,"parameter cannot be indexed","obj.indexed",Ps.indexed),Zs=!!Zs);let zs=Ps.type,Ys=zs.match(regexArrayType);if(Ys){const Va=parseInt(Ys[2]||"-1"),Xs=ParamType.from({type:Ys[1],components:Ps.components});return new ParamType(_guard,Ws||"",zs,"array",Zs,null,Va,Xs)}if(zs==="tuple"||zs.startsWith("tuple(")||zs.startsWith("(")){const Va=Ps.components!=null?Ps.components.map(Ma=>ParamType.from(Ma)):null;return new ParamType(_guard,Ws||"",zs,"tuple",Zs,Va,null,null)}return zs=verifyBasicType(Ps.type),new ParamType(_guard,Ws||"",zs,zs,Zs,null,null,null)}static isParamType(Ps){return Ps&&Ps[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(Ps,Hs,Ws){assertPrivate(Ps,_guard,"Fragment"),Ws=Object.freeze(Ws.slice()),defineProperties(this,{type:Hs,inputs:Ws})}static from(Ps){if(typeof Ps=="string"){try{Fragment.from(JSON.parse(Ps))}catch{}return Fragment.from(lex(Ps))}if(Ps instanceof TokenString)switch(Ps.peekKeyword(KwTypes)){case"constructor":return ConstructorFragment.from(Ps);case"error":return ErrorFragment.from(Ps);case"event":return EventFragment.from(Ps);case"fallback":case"receive":return FallbackFragment.from(Ps);case"function":return FunctionFragment.from(Ps);case"struct":return StructFragment.from(Ps)}else if(typeof Ps=="object"){switch(Ps.type){case"constructor":return ConstructorFragment.from(Ps);case"error":return ErrorFragment.from(Ps);case"event":return EventFragment.from(Ps);case"fallback":case"receive":return FallbackFragment.from(Ps);case"function":return FunctionFragment.from(Ps);case"struct":return StructFragment.from(Ps)}assert(!1,`unsupported type: ${Ps.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}assertArgument(!1,"unsupported frgament object","obj",Ps)}static isConstructor(Ps){return ConstructorFragment.isFragment(Ps)}static isError(Ps){return ErrorFragment.isFragment(Ps)}static isEvent(Ps){return EventFragment.isFragment(Ps)}static isFunction(Ps){return FunctionFragment.isFragment(Ps)}static isStruct(Ps){return StructFragment.isFragment(Ps)}}class NamedFragment extends Fragment{name;constructor(Ps,Hs,Ws,Zs){super(Ps,Hs,Zs),assertArgument(typeof Ws=="string"&&Ws.match(regexId),"invalid identifier","name",Ws),Zs=Object.freeze(Zs.slice()),defineProperties(this,{name:Ws})}}function joinParams(Fs,Ps){return"("+Ps.map(Hs=>Hs.format(Fs)).join(Fs==="full"?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(Ps,Hs,Ws){super(Ps,"error",Hs,Ws),Object.defineProperty(this,internal$1,{value:ErrorFragmentInternal})}get selector(){return id(this.format("sighash")).substring(0,10)}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("error"),Hs.push(this.name+joinParams(Ps,this.inputs)),Hs.join(" ")}static from(Ps){if(ErrorFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")return ErrorFragment.from(lex(Ps));if(Ps instanceof TokenString){const Hs=consumeName("error",Ps),Ws=consumeParams(Ps);return consumeEoi(Ps),new ErrorFragment(_guard,Hs,Ws)}return new ErrorFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(ParamType.from):[])}static isFragment(Ps){return Ps&&Ps[internal$1]===ErrorFragmentInternal}}class EventFragment extends NamedFragment{anonymous;constructor(Ps,Hs,Ws,Zs){super(Ps,"event",Hs,Ws),Object.defineProperty(this,internal$1,{value:EventFragmentInternal}),defineProperties(this,{anonymous:Zs})}get topicHash(){return id(this.format("sighash"))}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("event"),Hs.push(this.name+joinParams(Ps,this.inputs)),Ps!=="sighash"&&this.anonymous&&Hs.push("anonymous"),Hs.join(" ")}static getTopicHash(Ps,Hs){return Hs=(Hs||[]).map(Zs=>ParamType.from(Zs)),new EventFragment(_guard,Ps,Hs,!1).topicHash}static from(Ps){if(EventFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return EventFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid event fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=consumeName("event",Ps),Ws=consumeParams(Ps,!0),Zs=!!consumeKeywords(Ps,setify(["anonymous"])).has("anonymous");return consumeEoi(Ps),new EventFragment(_guard,Hs,Ws,Zs)}return new EventFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(Hs=>ParamType.from(Hs,!0)):[],!!Ps.anonymous)}static isFragment(Ps){return Ps&&Ps[internal$1]===EventFragmentInternal}}class ConstructorFragment extends Fragment{payable;gas;constructor(Ps,Hs,Ws,Zs,zs){super(Ps,Hs,Ws),Object.defineProperty(this,internal$1,{value:ConstructorFragmentInternal}),defineProperties(this,{payable:Zs,gas:zs})}format(Ps){if(assert(Ps!=null&&Ps!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),Ps==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[`constructor${joinParams(Ps,this.inputs)}`];return this.payable&&Hs.push("payable"),this.gas!=null&&Hs.push(`@${this.gas.toString()}`),Hs.join(" ")}static from(Ps){if(ConstructorFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return ConstructorFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid constuctor fragment","obj",Ps)}else if(Ps instanceof TokenString){consumeKeywords(Ps,setify(["constructor"]));const Hs=consumeParams(Ps),Ws=!!consumeKeywords(Ps,KwVisibDeploy).has("payable"),Zs=consumeGas(Ps);return consumeEoi(Ps),new ConstructorFragment(_guard,"constructor",Hs,Ws,Zs)}return new ConstructorFragment(_guard,"constructor",Ps.inputs?Ps.inputs.map(ParamType.from):[],!!Ps.payable,Ps.gas!=null?Ps.gas:null)}static isFragment(Ps){return Ps&&Ps[internal$1]===ConstructorFragmentInternal}}class FallbackFragment extends Fragment{payable;constructor(Ps,Hs,Ws){super(Ps,"fallback",Hs),Object.defineProperty(this,internal$1,{value:FallbackFragmentInternal}),defineProperties(this,{payable:Ws})}format(Ps){const Hs=this.inputs.length===0?"receive":"fallback";if(Ps==="json"){const Ws=this.payable?"payable":"nonpayable";return JSON.stringify({type:Hs,stateMutability:Ws})}return`${Hs}()${this.payable?" payable":""}`}static from(Ps){if(FallbackFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return FallbackFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid fallback fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=Ps.toString(),Ws=Ps.peekKeyword(setify(["fallback","receive"]));if(assertArgument(Ws,"type must be fallback or receive","obj",Hs),Ps.popKeyword(setify(["fallback","receive"]))==="receive"){const Va=consumeParams(Ps);return assertArgument(Va.length===0,"receive cannot have arguments","obj.inputs",Va),consumeKeywords(Ps,setify(["payable"])),consumeEoi(Ps),new FallbackFragment(_guard,[],!0)}let zs=consumeParams(Ps);zs.length?assertArgument(zs.length===1&&zs[0].type==="bytes","invalid fallback inputs","obj.inputs",zs.map(Va=>Va.format("minimal")).join(", ")):zs=[ParamType.from("bytes")];const Ys=consumeMutability(Ps);if(assertArgument(Ys==="nonpayable"||Ys==="payable","fallback cannot be constants","obj.stateMutability",Ys),consumeKeywords(Ps,setify(["returns"])).has("returns")){const Va=consumeParams(Ps);assertArgument(Va.length===1&&Va[0].type==="bytes","invalid fallback outputs","obj.outputs",Va.map(Xs=>Xs.format("minimal")).join(", "))}return consumeEoi(Ps),new FallbackFragment(_guard,zs,Ys==="payable")}if(Ps.type==="receive")return new FallbackFragment(_guard,[],!0);if(Ps.type==="fallback"){const Hs=[ParamType.from("bytes")],Ws=Ps.stateMutability==="payable";return new FallbackFragment(_guard,Hs,Ws)}assertArgument(!1,"invalid fallback description","obj",Ps)}static isFragment(Ps){return Ps&&Ps[internal$1]===FallbackFragmentInternal}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(Ps,Hs,Ws,Zs,zs,Ys){super(Ps,"function",Hs,Zs),Object.defineProperty(this,internal$1,{value:FunctionFragmentInternal}),zs=Object.freeze(zs.slice()),defineProperties(this,{constant:Ws==="view"||Ws==="pure",gas:Ys,outputs:zs,payable:Ws==="payable",stateMutability:Ws})}get selector(){return id(this.format("sighash")).substring(0,10)}format(Ps){if(Ps==null&&(Ps="sighash"),Ps==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(Ws=>JSON.parse(Ws.format(Ps))),outputs:this.outputs.map(Ws=>JSON.parse(Ws.format(Ps)))});const Hs=[];return Ps!=="sighash"&&Hs.push("function"),Hs.push(this.name+joinParams(Ps,this.inputs)),Ps!=="sighash"&&(this.stateMutability!=="nonpayable"&&Hs.push(this.stateMutability),this.outputs&&this.outputs.length&&(Hs.push("returns"),Hs.push(joinParams(Ps,this.outputs))),this.gas!=null&&Hs.push(`@${this.gas.toString()}`)),Hs.join(" ")}static getSelector(Ps,Hs){return Hs=(Hs||[]).map(Zs=>ParamType.from(Zs)),new FunctionFragment(_guard,Ps,"view",Hs,[],null).selector}static from(Ps){if(FunctionFragment.isFragment(Ps))return Ps;if(typeof Ps=="string")try{return FunctionFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid function fragment","obj",Ps)}else if(Ps instanceof TokenString){const Ws=consumeName("function",Ps),Zs=consumeParams(Ps),zs=consumeMutability(Ps);let Ys=[];consumeKeywords(Ps,setify(["returns"])).has("returns")&&(Ys=consumeParams(Ps));const Va=consumeGas(Ps);return consumeEoi(Ps),new FunctionFragment(_guard,Ws,zs,Zs,Ys,Va)}let Hs=Ps.stateMutability;return Hs==null&&(Hs="payable",typeof Ps.constant=="boolean"?(Hs="view",Ps.constant||(Hs="payable",typeof Ps.payable=="boolean"&&!Ps.payable&&(Hs="nonpayable"))):typeof Ps.payable=="boolean"&&!Ps.payable&&(Hs="nonpayable")),new FunctionFragment(_guard,Ps.name,Hs,Ps.inputs?Ps.inputs.map(ParamType.from):[],Ps.outputs?Ps.outputs.map(ParamType.from):[],Ps.gas!=null?Ps.gas:null)}static isFragment(Ps){return Ps&&Ps[internal$1]===FunctionFragmentInternal}}class StructFragment extends NamedFragment{constructor(Ps,Hs,Ws){super(Ps,"struct",Hs,Ws),Object.defineProperty(this,internal$1,{value:StructFragmentInternal})}format(){throw new Error("@TODO")}static from(Ps){if(typeof Ps=="string")try{return StructFragment.from(lex(Ps))}catch{assertArgument(!1,"invalid struct fragment","obj",Ps)}else if(Ps instanceof TokenString){const Hs=consumeName("struct",Ps),Ws=consumeParams(Ps);return consumeEoi(Ps),new StructFragment(_guard,Hs,Ws)}return new StructFragment(_guard,Ps.name,Ps.inputs?Ps.inputs.map(ParamType.from):[])}static isFragment(Ps){return Ps&&Ps[internal$1]===StructFragmentInternal}}const PanicReasons$1=new Map;PanicReasons$1.set(0,"GENERIC_PANIC"),PanicReasons$1.set(1,"ASSERT_FALSE"),PanicReasons$1.set(17,"OVERFLOW"),PanicReasons$1.set(18,"DIVIDE_BY_ZERO"),PanicReasons$1.set(33,"ENUM_RANGE_ERROR"),PanicReasons$1.set(34,"BAD_STORAGE_DATA"),PanicReasons$1.set(49,"STACK_UNDERFLOW"),PanicReasons$1.set(50,"ARRAY_RANGE_ERROR"),PanicReasons$1.set(65,"OUT_OF_MEMORY"),PanicReasons$1.set(81,"UNINITIALIZED_FUNCTION_CALL");const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/),paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);let defaultCoder=null,defaultMaxInflation=1024;function getBuiltinCallException(Fs,Ps,Hs,Ws){let Zs="missing revert data",zs=null;const Ys=null;let Va=null;if(Hs){Zs="execution reverted";const Ma=getBytes(Hs);if(Hs=hexlify(Hs),Ma.length===0)Zs+=" (no data present; likely require(false) occurred",zs="require(false)";else if(Ma.length%32!==4)Zs+=" (could not decode reason; invalid data length)";else if(hexlify(Ma.slice(0,4))==="0x08c379a0")try{zs=Ws.decode(["string"],Ma.slice(4))[0],Va={signature:"Error(string)",name:"Error",args:[zs]},Zs+=`: ${JSON.stringify(zs)}`}catch{Zs+=" (could not decode reason; invalid string data)"}else if(hexlify(Ma.slice(0,4))==="0x4e487b71")try{const qs=Number(Ws.decode(["uint256"],Ma.slice(4))[0]);Va={signature:"Panic(uint256)",name:"Panic",args:[qs]},zs=`Panic due to ${PanicReasons$1.get(qs)||"UNKNOWN"}(${qs})`,Zs+=`: ${zs}`}catch{Zs+=" (could not decode panic code)"}else Zs+=" (unknown custom error)"}const Xs={to:Ps.to?getAddress(Ps.to):null,data:Ps.data||"0x"};return Ps.from&&(Xs.from=getAddress(Ps.from)),makeError(Zs,"CALL_EXCEPTION",{action:Fs,data:Hs,reason:zs,transaction:Xs,invocation:Ys,revert:Va})}class AbiCoder{#e(Ps){if(Ps.isArray())return new ArrayCoder(this.#e(Ps.arrayChildren),Ps.arrayLength,Ps.name);if(Ps.isTuple())return new TupleCoder(Ps.components.map(Ws=>this.#e(Ws)),Ps.name);switch(Ps.baseType){case"address":return new AddressCoder(Ps.name);case"bool":return new BooleanCoder(Ps.name);case"string":return new StringCoder(Ps.name);case"bytes":return new BytesCoder(Ps.name);case"":return new NullCoder(Ps.name)}let Hs=Ps.type.match(paramTypeNumber);if(Hs){let Ws=parseInt(Hs[2]||"256");return assertArgument(Ws!==0&&Ws<=256&&Ws%8===0,"invalid "+Hs[1]+" bit length","param",Ps),new NumberCoder(Ws/8,Hs[1]==="int",Ps.name)}if(Hs=Ps.type.match(paramTypeBytes),Hs){let Ws=parseInt(Hs[1]);return assertArgument(Ws!==0&&Ws<=32,"invalid bytes length","param",Ps),new FixedBytesCoder(Ws,Ps.name)}assertArgument(!1,"invalid type","type",Ps.type)}getDefaultValue(Ps){const Hs=Ps.map(Zs=>this.#e(ParamType.from(Zs)));return new TupleCoder(Hs,"_").defaultValue()}encode(Ps,Hs){assertArgumentCount(Hs.length,Ps.length,"types/values length mismatch");const Ws=Ps.map(Ys=>this.#e(ParamType.from(Ys))),Zs=new TupleCoder(Ws,"_"),zs=new Writer;return Zs.encode(zs,Hs),zs.data}decode(Ps,Hs,Ws){const Zs=Ps.map(Ys=>this.#e(ParamType.from(Ys)));return new TupleCoder(Zs,"_").decode(new Reader(Hs,Ws,defaultMaxInflation))}static _setDefaultMaxInflation(Ps){assertArgument(typeof Ps=="number"&&Number.isInteger(Ps),"invalid defaultMaxInflation factor","value",Ps),defaultMaxInflation=Ps}static defaultAbiCoder(){return defaultCoder==null&&(defaultCoder=new AbiCoder),defaultCoder}static getBuiltinCallException(Ps,Hs,Ws){return getBuiltinCallException(Ps,Hs,Ws,AbiCoder.defaultAbiCoder())}}class LogDescription{fragment;name;signature;topic;args;constructor(Ps,Hs,Ws){const Zs=Ps.name,zs=Ps.format();defineProperties(this,{fragment:Ps,name:Zs,signature:zs,topic:Hs,args:Ws})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(Ps,Hs,Ws,Zs){const zs=Ps.name,Ys=Ps.format();defineProperties(this,{fragment:Ps,name:zs,args:Ws,signature:Ys,selector:Hs,value:Zs})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(Ps,Hs,Ws){const Zs=Ps.name,zs=Ps.format();defineProperties(this,{fragment:Ps,name:Zs,args:Ws,signature:zs,selector:Hs})}}class Indexed{hash;_isIndexed;static isIndexed(Ps){return!!(Ps&&Ps._isIndexed)}constructor(Ps){defineProperties(this,{hash:Ps,_isIndexed:!0})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:Fs=>`reverted with reason string ${JSON.stringify(Fs)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:Fs=>{let Ps="unknown panic code";return Fs>=0&&Fs<=255&&PanicReasons[Fs.toString()]&&(Ps=PanicReasons[Fs.toString()]),`reverted with panic code 0x${Fs.toString(16)} (${Ps})`}}};class Interface{fragments;deploy;fallback;receive;#e;#t;#r;#n;constructor(Ps){let Hs=[];typeof Ps=="string"?Hs=JSON.parse(Ps):Hs=Ps,this.#r=new Map,this.#e=new Map,this.#t=new Map;const Ws=[];for(const Ys of Hs)try{Ws.push(Fragment.from(Ys))}catch(Va){console.log(`[Warning] Invalid Fragment ${JSON.stringify(Ys)}:`,Va.message)}defineProperties(this,{fragments:Object.freeze(Ws)});let Zs=null,zs=!1;this.#n=this.getAbiCoder(),this.fragments.forEach((Ys,Va)=>{let Xs;switch(Ys.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}defineProperties(this,{deploy:Ys});return;case"fallback":Ys.inputs.length===0?zs=!0:(assertArgument(!Zs||Ys.payable!==Zs.payable,"conflicting fallback fragments",`fragments[${Va}]`,Ys),Zs=Ys,zs=Zs.payable);return;case"function":Xs=this.#r;break;case"event":Xs=this.#t;break;case"error":Xs=this.#e;break;default:return}const Ma=Ys.format();Xs.has(Ma)||Xs.set(Ma,Ys)}),this.deploy||defineProperties(this,{deploy:ConstructorFragment.from("constructor()")}),defineProperties(this,{fallback:Zs,receive:zs})}format(Ps){const Hs=Ps?"minimal":"full";return this.fragments.map(Zs=>Zs.format(Hs))}formatJson(){const Ps=this.fragments.map(Hs=>Hs.format("json"));return JSON.stringify(Ps.map(Hs=>JSON.parse(Hs)))}getAbiCoder(){return AbiCoder.defaultAbiCoder()}#o(Ps,Hs,Ws){if(isHexString(Ps)){const zs=Ps.toLowerCase();for(const Ys of this.#r.values())if(zs===Ys.selector)return Ys;return null}if(Ps.indexOf("(")===-1){const zs=[];for(const[Ys,Va]of this.#r)Ys.split("(")[0]===Ps&&zs.push(Va);if(Hs){const Ys=Hs.length>0?Hs[Hs.length-1]:null;let Va=Hs.length,Xs=!0;Typed.isTyped(Ys)&&Ys.type==="overrides"&&(Xs=!1,Va--);for(let Ma=zs.length-1;Ma>=0;Ma--){const qs=zs[Ma].inputs.length;qs!==Va&&(!Xs||qs!==Va-1)&&zs.splice(Ma,1)}for(let Ma=zs.length-1;Ma>=0;Ma--){const qs=zs[Ma].inputs;for(let Js=0;Js<Hs.length;Js++)if(Typed.isTyped(Hs[Js])){if(Js>=qs.length){if(Hs[Js].type==="overrides")continue;zs.splice(Ma,1);break}if(Hs[Js].type!==qs[Js].baseType){zs.splice(Ma,1);break}}}}if(zs.length===1&&Hs&&Hs.length!==zs[0].inputs.length){const Ys=Hs[Hs.length-1];(Ys==null||Array.isArray(Ys)||typeof Ys!="object")&&zs.splice(0,1)}if(zs.length===0)return null;if(zs.length>1&&Ws){const Ys=zs.map(Va=>JSON.stringify(Va.format())).join(", ");assertArgument(!1,`ambiguous function description (i.e. matches ${Ys})`,"key",Ps)}return zs[0]}const Zs=this.#r.get(FunctionFragment.from(Ps).format());return Zs||null}getFunctionName(Ps){const Hs=this.#o(Ps,null,!1);return assertArgument(Hs,"no matching function","key",Ps),Hs.name}hasFunction(Ps){return!!this.#o(Ps,null,!1)}getFunction(Ps,Hs){return this.#o(Ps,Hs||null,!0)}forEachFunction(Ps){const Hs=Array.from(this.#r.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#r.get(Zs),Ws)}}#s(Ps,Hs,Ws){if(isHexString(Ps)){const zs=Ps.toLowerCase();for(const Ys of this.#t.values())if(zs===Ys.topicHash)return Ys;return null}if(Ps.indexOf("(")===-1){const zs=[];for(const[Ys,Va]of this.#t)Ys.split("(")[0]===Ps&&zs.push(Va);if(Hs){for(let Ys=zs.length-1;Ys>=0;Ys--)zs[Ys].inputs.length<Hs.length&&zs.splice(Ys,1);for(let Ys=zs.length-1;Ys>=0;Ys--){const Va=zs[Ys].inputs;for(let Xs=0;Xs<Hs.length;Xs++)if(Typed.isTyped(Hs[Xs])&&Hs[Xs].type!==Va[Xs].baseType){zs.splice(Ys,1);break}}}if(zs.length===0)return null;if(zs.length>1&&Ws){const Ys=zs.map(Va=>JSON.stringify(Va.format())).join(", ");assertArgument(!1,`ambiguous event description (i.e. matches ${Ys})`,"key",Ps)}return zs[0]}const Zs=this.#t.get(EventFragment.from(Ps).format());return Zs||null}getEventName(Ps){const Hs=this.#s(Ps,null,!1);return assertArgument(Hs,"no matching event","key",Ps),Hs.name}hasEvent(Ps){return!!this.#s(Ps,null,!1)}getEvent(Ps,Hs){return this.#s(Ps,Hs||null,!0)}forEachEvent(Ps){const Hs=Array.from(this.#t.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#t.get(Zs),Ws)}}getError(Ps,Hs){if(isHexString(Ps)){const Zs=Ps.toLowerCase();if(BuiltinErrors[Zs])return ErrorFragment.from(BuiltinErrors[Zs].signature);for(const zs of this.#e.values())if(Zs===zs.selector)return zs;return null}if(Ps.indexOf("(")===-1){const Zs=[];for(const[zs,Ys]of this.#e)zs.split("(")[0]===Ps&&Zs.push(Ys);if(Zs.length===0)return Ps==="Error"?ErrorFragment.from("error Error(string)"):Ps==="Panic"?ErrorFragment.from("error Panic(uint256)"):null;if(Zs.length>1){const zs=Zs.map(Ys=>JSON.stringify(Ys.format())).join(", ");assertArgument(!1,`ambiguous error description (i.e. ${zs})`,"name",Ps)}return Zs[0]}if(Ps=ErrorFragment.from(Ps).format(),Ps==="Error(string)")return ErrorFragment.from("error Error(string)");if(Ps==="Panic(uint256)")return ErrorFragment.from("error Panic(uint256)");const Ws=this.#e.get(Ps);return Ws||null}forEachError(Ps){const Hs=Array.from(this.#e.keys());Hs.sort((Ws,Zs)=>Ws.localeCompare(Zs));for(let Ws=0;Ws<Hs.length;Ws++){const Zs=Hs[Ws];Ps(this.#e.get(Zs),Ws)}}_decodeParams(Ps,Hs){return this.#n.decode(Ps,Hs)}_encodeParams(Ps,Hs){return this.#n.encode(Ps,Hs)}encodeDeploy(Ps){return this._encodeParams(this.deploy.inputs,Ps||[])}decodeErrorResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getError(Ps);assertArgument(Ws,"unknown error","fragment",Ps),Ps=Ws}return assertArgument(dataSlice(Hs,0,4)===Ps.selector,`data signature does not match error ${Ps.name}.`,"data",Hs),this._decodeParams(Ps.inputs,dataSlice(Hs,4))}encodeErrorResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getError(Ps);assertArgument(Ws,"unknown error","fragment",Ps),Ps=Ws}return concat([Ps.selector,this._encodeParams(Ps.inputs,Hs||[])])}decodeFunctionData(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return assertArgument(dataSlice(Hs,0,4)===Ps.selector,`data signature does not match function ${Ps.name}.`,"data",Hs),this._decodeParams(Ps.inputs,dataSlice(Hs,4))}encodeFunctionData(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return concat([Ps.selector,this._encodeParams(Ps.inputs,Hs||[])])}decodeFunctionResult(Ps,Hs){if(typeof Ps=="string"){const zs=this.getFunction(Ps);assertArgument(zs,"unknown function","fragment",Ps),Ps=zs}let Ws="invalid length for result data";const Zs=getBytesCopy(Hs);if(Zs.length%32===0)try{return this.#n.decode(Ps.outputs,Zs)}catch{Ws="could not decode result data"}assert(!1,Ws,"BAD_DATA",{value:hexlify(Zs),info:{method:Ps.name,signature:Ps.format()}})}makeError(Ps,Hs){const Ws=getBytes(Ps,"data"),Zs=AbiCoder.getBuiltinCallException("call",Hs,Ws);if(Zs.message.startsWith("execution reverted (unknown custom error)")){const Va=hexlify(Ws.slice(0,4)),Xs=this.getError(Va);if(Xs)try{const Ma=this.#n.decode(Xs.inputs,Ws.slice(4));Zs.revert={name:Xs.name,signature:Xs.format(),args:Ma},Zs.reason=Zs.revert.signature,Zs.message=`execution reverted: ${Zs.reason}`}catch{Zs.message="execution reverted (coult not decode custom error)"}}const Ys=this.parseTransaction(Hs);return Ys&&(Zs.invocation={method:Ys.name,signature:Ys.signature,args:Ys.args}),Zs}encodeFunctionResult(Ps,Hs){if(typeof Ps=="string"){const Ws=this.getFunction(Ps);assertArgument(Ws,"unknown function","fragment",Ps),Ps=Ws}return hexlify(this.#n.encode(Ps.outputs,Hs||[]))}encodeFilterTopics(Ps,Hs){if(typeof Ps=="string"){const zs=this.getEvent(Ps);assertArgument(zs,"unknown event","eventFragment",Ps),Ps=zs}assert(Hs.length<=Ps.inputs.length,`too many arguments for ${Ps.format()}`,"UNEXPECTED_ARGUMENT",{count:Hs.length,expectedCount:Ps.inputs.length});const Ws=[];Ps.anonymous||Ws.push(Ps.topicHash);const Zs=(zs,Ys)=>zs.type==="string"?id(Ys):zs.type==="bytes"?keccak256(hexlify(Ys)):(zs.type==="bool"&&typeof Ys=="boolean"?Ys=Ys?"0x01":"0x00":zs.type.match(/^u?int/)?Ys=toBeHex(Ys):zs.type.match(/^bytes/)?Ys=zeroPadBytes(Ys,32):zs.type==="address"&&this.#n.encode(["address"],[Ys]),zeroPadValue(hexlify(Ys),32));for(Hs.forEach((zs,Ys)=>{const Va=Ps.inputs[Ys];if(!Va.indexed){assertArgument(zs==null,"cannot filter non-indexed parameters; must be null","contract."+Va.name,zs);return}zs==null?Ws.push(null):Va.baseType==="array"||Va.baseType==="tuple"?assertArgument(!1,"filtering with tuples or arrays not supported","contract."+Va.name,zs):Array.isArray(zs)?Ws.push(zs.map(Xs=>Zs(Va,Xs))):Ws.push(Zs(Va,zs))});Ws.length&&Ws[Ws.length-1]===null;)Ws.pop();return Ws}encodeEventLog(Ps,Hs){if(typeof Ps=="string"){const Ys=this.getEvent(Ps);assertArgument(Ys,"unknown event","eventFragment",Ps),Ps=Ys}const Ws=[],Zs=[],zs=[];return Ps.anonymous||Ws.push(Ps.topicHash),assertArgument(Hs.length===Ps.inputs.length,"event arguments/values mismatch","values",Hs),Ps.inputs.forEach((Ys,Va)=>{const Xs=Hs[Va];if(Ys.indexed)if(Ys.type==="string")Ws.push(id(Xs));else if(Ys.type==="bytes")Ws.push(keccak256(Xs));else{if(Ys.baseType==="tuple"||Ys.baseType==="array")throw new Error("not implemented");Ws.push(this.#n.encode([Ys.type],[Xs]))}else Zs.push(Ys),zs.push(Xs)}),{data:this.#n.encode(Zs,zs),topics:Ws}}decodeEventLog(Ps,Hs,Ws){if(typeof Ps=="string"){const ol=this.getEvent(Ps);assertArgument(ol,"unknown event","eventFragment",Ps),Ps=ol}if(Ws!=null&&!Ps.anonymous){const ol=Ps.topicHash;assertArgument(isHexString(Ws[0],32)&&Ws[0].toLowerCase()===ol,"fragment/topic mismatch","topics[0]",Ws[0]),Ws=Ws.slice(1)}const Zs=[],zs=[],Ys=[];Ps.inputs.forEach((ol,Vc)=>{ol.indexed?ol.type==="string"||ol.type==="bytes"||ol.baseType==="tuple"||ol.baseType==="array"?(Zs.push(ParamType.from({type:"bytes32",name:ol.name})),Ys.push(!0)):(Zs.push(ol),Ys.push(!1)):(zs.push(ol),Ys.push(!1))});const Va=Ws!=null?this.#n.decode(Zs,concat(Ws)):null,Xs=this.#n.decode(zs,Hs,!0),Ma=[],qs=[];let Js=0,Mc=0;return Ps.inputs.forEach((ol,Vc)=>{let Dc=null;if(ol.indexed)if(Va==null)Dc=new Indexed(null);else if(Ys[Vc])Dc=new Indexed(Va[Mc++]);else try{Dc=Va[Mc++]}catch(sl){Dc=sl}else try{Dc=Xs[Js++]}catch(sl){Dc=sl}Ma.push(Dc),qs.push(ol.name||null)}),Result$1.fromItems(Ma,qs)}parseTransaction(Ps){const Hs=getBytes(Ps.data,"tx.data"),Ws=getBigInt(Ps.value!=null?Ps.value:0,"tx.value"),Zs=this.getFunction(hexlify(Hs.slice(0,4)));if(!Zs)return null;const zs=this.#n.decode(Zs.inputs,Hs.slice(4));return new TransactionDescription(Zs,Zs.selector,zs,Ws)}parseCallResult(Ps){throw new Error("@TODO")}parseLog(Ps){const Hs=this.getEvent(Ps.topics[0]);return!Hs||Hs.anonymous?null:new LogDescription(Hs,Hs.topicHash,this.decodeEventLog(Hs,Ps.data,Ps.topics))}parseError(Ps){const Hs=hexlify(Ps),Ws=this.getError(dataSlice(Hs,0,4));if(!Ws)return null;const Zs=this.#n.decode(Ws.inputs,dataSlice(Hs,4));return new ErrorDescription(Ws,Ws.selector,Zs)}static from(Ps){return Ps instanceof Interface?Ps:typeof Ps=="string"?new Interface(JSON.parse(Ps)):typeof Ps.formatJson=="function"?new Interface(Ps.formatJson()):typeof Ps.format=="function"?new Interface(Ps.format("json")):new Interface(Ps)}}const BN_0$2=BigInt(0);function getValue(Fs){return Fs??null}function toJson(Fs){return Fs==null?null:Fs.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(Ps,Hs,Ws){defineProperties(this,{gasPrice:getValue(Ps),maxFeePerGas:getValue(Hs),maxPriorityFeePerGas:getValue(Ws)})}toJSON(){const{gasPrice:Ps,maxFeePerGas:Hs,maxPriorityFeePerGas:Ws}=this;return{_type:"FeeData",gasPrice:toJson(Ps),maxFeePerGas:toJson(Hs),maxPriorityFeePerGas:toJson(Ws)}}}function copyRequest(Fs){const Ps={};Fs.to&&(Ps.to=Fs.to),Fs.from&&(Ps.from=Fs.from),Fs.data&&(Ps.data=hexlify(Fs.data));const Hs="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const Zs of Hs)!(Zs in Fs)||Fs[Zs]==null||(Ps[Zs]=getBigInt(Fs[Zs],`request.${Zs}`));const Ws="type,nonce".split(/,/);for(const Zs of Ws)!(Zs in Fs)||Fs[Zs]==null||(Ps[Zs]=getNumber(Fs[Zs],`request.${Zs}`));return Fs.accessList&&(Ps.accessList=accessListify(Fs.accessList)),Fs.authorizationList&&(Ps.authorizationList=Fs.authorizationList.slice()),"blockTag"in Fs&&(Ps.blockTag=Fs.blockTag),"enableCcipRead"in Fs&&(Ps.enableCcipRead=!!Fs.enableCcipRead),"customData"in Fs&&(Ps.customData=Fs.customData),"blobVersionedHashes"in Fs&&Fs.blobVersionedHashes&&(Ps.blobVersionedHashes=Fs.blobVersionedHashes.slice()),"kzg"in Fs&&(Ps.kzg=Fs.kzg),"blobs"in Fs&&Fs.blobs&&(Ps.blobs=Fs.blobs.map(Zs=>isBytesLike(Zs)?hexlify(Zs):Object.assign({},Zs))),Ps}class Block{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#e;constructor(Ps,Hs){this.#e=Ps.transactions.map(Ws=>typeof Ws!="string"?new TransactionResponse(Ws,Hs):Ws),defineProperties(this,{provider:Hs,hash:getValue(Ps.hash),number:Ps.number,timestamp:Ps.timestamp,parentHash:Ps.parentHash,parentBeaconBlockRoot:Ps.parentBeaconBlockRoot,nonce:Ps.nonce,difficulty:Ps.difficulty,gasLimit:Ps.gasLimit,gasUsed:Ps.gasUsed,blobGasUsed:Ps.blobGasUsed,excessBlobGas:Ps.excessBlobGas,miner:Ps.miner,prevRandao:getValue(Ps.prevRandao),extraData:Ps.extraData,baseFeePerGas:getValue(Ps.baseFeePerGas),stateRoot:Ps.stateRoot,receiptsRoot:Ps.receiptsRoot})}get transactions(){return this.#e.map(Ps=>typeof Ps=="string"?Ps:Ps.hash)}get prefetchedTransactions(){const Ps=this.#e.slice();return Ps.length===0?[]:(assert(typeof Ps[0]=="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),Ps)}toJSON(){const{baseFeePerGas:Ps,difficulty:Hs,extraData:Ws,gasLimit:Zs,gasUsed:zs,hash:Ys,miner:Va,prevRandao:Xs,nonce:Ma,number:qs,parentHash:Js,parentBeaconBlockRoot:Mc,stateRoot:ol,receiptsRoot:Vc,timestamp:Dc,transactions:sl}=this;return{_type:"Block",baseFeePerGas:toJson(Ps),difficulty:toJson(Hs),extraData:Ws,gasLimit:toJson(Zs),gasUsed:toJson(zs),blobGasUsed:toJson(this.blobGasUsed),excessBlobGas:toJson(this.excessBlobGas),hash:Ys,miner:Va,prevRandao:Xs,nonce:Ma,number:qs,parentHash:Js,timestamp:Dc,parentBeaconBlockRoot:Mc,stateRoot:ol,receiptsRoot:Vc,transactions:sl}}[Symbol.iterator](){let Ps=0;const Hs=this.transactions;return{next:()=>Ps<this.length?{value:Hs[Ps++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#e.length}get date(){return this.timestamp==null?null:new Date(this.timestamp*1e3)}async getTransaction(Ps){let Hs;if(typeof Ps=="number")Hs=this.#e[Ps];else{const Ws=Ps.toLowerCase();for(const Zs of this.#e)if(typeof Zs=="string"){if(Zs!==Ws)continue;Hs=Zs;break}else{if(Zs.hash!==Ws)continue;Hs=Zs;break}}if(Hs==null)throw new Error("no such tx");return typeof Hs=="string"?await this.provider.getTransaction(Hs):Hs}getPrefetchedTransaction(Ps){const Hs=this.prefetchedTransactions;if(typeof Ps=="number")return Hs[Ps];Ps=Ps.toLowerCase();for(const Ws of Hs)if(Ws.hash===Ps)return Ws;assertArgument(!1,"no matching transaction","indexOrHash",Ps)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return createOrphanedBlockFilter(this)}}class Log{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(Ps,Hs){this.provider=Hs;const Ws=Object.freeze(Ps.topics.slice());defineProperties(this,{transactionHash:Ps.transactionHash,blockHash:Ps.blockHash,blockNumber:Ps.blockNumber,removed:Ps.removed,address:Ps.address,data:Ps.data,topics:Ws,index:Ps.index,transactionIndex:Ps.transactionIndex})}toJSON(){const{address:Ps,blockHash:Hs,blockNumber:Ws,data:Zs,index:zs,removed:Ys,topics:Va,transactionHash:Xs,transactionIndex:Ma}=this;return{_type:"log",address:Ps,blockHash:Hs,blockNumber:Ws,data:Zs,index:zs,removed:Ys,topics:Va,transactionHash:Xs,transactionIndex:Ma}}async getBlock(){const Ps=await this.provider.getBlock(this.blockHash);return assert(!!Ps,"failed to find transaction","UNKNOWN_ERROR",{}),Ps}async getTransaction(){const Ps=await this.provider.getTransaction(this.transactionHash);return assert(!!Ps,"failed to find transaction","UNKNOWN_ERROR",{}),Ps}async getTransactionReceipt(){const Ps=await this.provider.getTransactionReceipt(this.transactionHash);return assert(!!Ps,"failed to find transaction receipt","UNKNOWN_ERROR",{}),Ps}removedEvent(){return createRemovedLogFilter(this)}}class TransactionReceipt{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#e;constructor(Ps,Hs){this.#e=Object.freeze(Ps.logs.map(Zs=>new Log(Zs,Hs)));let Ws=BN_0$2;Ps.effectiveGasPrice!=null?Ws=Ps.effectiveGasPrice:Ps.gasPrice!=null&&(Ws=Ps.gasPrice),defineProperties(this,{provider:Hs,to:Ps.to,from:Ps.from,contractAddress:Ps.contractAddress,hash:Ps.hash,index:Ps.index,blockHash:Ps.blockHash,blockNumber:Ps.blockNumber,logsBloom:Ps.logsBloom,gasUsed:Ps.gasUsed,cumulativeGasUsed:Ps.cumulativeGasUsed,blobGasUsed:Ps.blobGasUsed,gasPrice:Ws,blobGasPrice:Ps.blobGasPrice,type:Ps.type,status:Ps.status,root:Ps.root})}get logs(){return this.#e}toJSON(){const{to:Ps,from:Hs,contractAddress:Ws,hash:Zs,index:zs,blockHash:Ys,blockNumber:Va,logsBloom:Xs,logs:Ma,status:qs,root:Js}=this;return{_type:"TransactionReceipt",blockHash:Ys,blockNumber:Va,contractAddress:Ws,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:Hs,gasPrice:toJson(this.gasPrice),blobGasUsed:toJson(this.blobGasUsed),blobGasPrice:toJson(this.blobGasPrice),gasUsed:toJson(this.gasUsed),hash:Zs,index:zs,logs:Ma,logsBloom:Xs,root:Js,status:qs,to:Ps}}get length(){return this.logs.length}[Symbol.iterator](){let Ps=0;return{next:()=>Ps<this.length?{value:this.logs[Ps++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const Ps=await this.provider.getBlock(this.blockHash);if(Ps==null)throw new Error("TODO");return Ps}async getTransaction(){const Ps=await this.provider.getTransaction(this.hash);if(Ps==null)throw new Error("TODO");return Ps}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return createRemovedTransactionFilter(this)}reorderedEvent(Ps){return assert(!Ps||Ps.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),createReorderedTransactionFilter(this,Ps)}}class TransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#e;constructor(Ps,Hs){this.provider=Hs,this.blockNumber=Ps.blockNumber!=null?Ps.blockNumber:null,this.blockHash=Ps.blockHash!=null?Ps.blockHash:null,this.hash=Ps.hash,this.index=Ps.index,this.type=Ps.type,this.from=Ps.from,this.to=Ps.to||null,this.gasLimit=Ps.gasLimit,this.nonce=Ps.nonce,this.data=Ps.data,this.value=Ps.value,this.gasPrice=Ps.gasPrice,this.maxPriorityFeePerGas=Ps.maxPriorityFeePerGas!=null?Ps.maxPriorityFeePerGas:null,this.maxFeePerGas=Ps.maxFeePerGas!=null?Ps.maxFeePerGas:null,this.maxFeePerBlobGas=Ps.maxFeePerBlobGas!=null?Ps.maxFeePerBlobGas:null,this.chainId=Ps.chainId,this.signature=Ps.signature,this.accessList=Ps.accessList!=null?Ps.accessList:null,this.blobVersionedHashes=Ps.blobVersionedHashes!=null?Ps.blobVersionedHashes:null,this.authorizationList=Ps.authorizationList!=null?Ps.authorizationList:null,this.#e=-1}toJSON(){const{blockNumber:Ps,blockHash:Hs,index:Ws,hash:Zs,type:zs,to:Ys,from:Va,nonce:Xs,data:Ma,signature:qs,accessList:Js,blobVersionedHashes:Mc}=this;return{_type:"TransactionResponse",accessList:Js,blockNumber:Ps,blockHash:Hs,blobVersionedHashes:Mc,chainId:toJson(this.chainId),data:Ma,from:Va,gasLimit:toJson(this.gasLimit),gasPrice:toJson(this.gasPrice),hash:Zs,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),maxFeePerBlobGas:toJson(this.maxFeePerBlobGas),nonce:Xs,signature:qs,to:Ys,index:Ws,type:zs,value:toJson(this.value)}}async getBlock(){let Ps=this.blockNumber;if(Ps==null){const Ws=await this.getTransaction();Ws&&(Ps=Ws.blockNumber)}if(Ps==null)return null;const Hs=this.provider.getBlock(Ps);if(Hs==null)throw new Error("TODO");return Hs}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(this.blockNumber==null){const{tx:Hs,blockNumber:Ws}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return Hs==null||Hs.blockNumber==null?0:Ws-Hs.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(Ps,Hs){const Ws=Ps??1,Zs=Hs??0;let zs=this.#e,Ys=-1,Va=zs===-1;const Xs=async()=>{if(Va)return null;const{blockNumber:Mc,nonce:ol}=await resolveProperties({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(ol<this.nonce){zs=Mc;return}if(Va)return null;const Vc=await this.getTransaction();if(!(Vc&&Vc.blockNumber!=null))for(Ys===-1&&(Ys=zs-3,Ys<this.#e&&(Ys=this.#e));Ys<=Mc;){if(Va)return null;const Dc=await this.provider.getBlock(Ys,!0);if(Dc==null)return;for(const sl of Dc)if(sl===this.hash)return;for(let sl=0;sl<Dc.length;sl++){const ll=await Dc.getTransaction(sl);if(ll.from===this.from&&ll.nonce===this.nonce){if(Va)return null;const hl=await this.provider.getTransactionReceipt(ll.hash);if(hl==null||Mc-hl.blockNumber+1<Ws)return;let pl="replaced";ll.data===this.data&&ll.to===this.to&&ll.value===this.value?pl="repriced":ll.data==="0x"&&ll.from===ll.to&&ll.value===BN_0$2&&(pl="cancelled"),assert(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:pl==="replaced"||pl==="cancelled",reason:pl,replacement:ll.replaceableTransaction(zs),hash:ll.hash,receipt:hl})}}Ys++}},Ma=Mc=>{if(Mc==null||Mc.status!==0)return Mc;assert(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:Mc.to,from:Mc.from,data:""},receipt:Mc})},qs=await this.provider.getTransactionReceipt(this.hash);if(Ws===0)return Ma(qs);if(qs){if(Ws===1||await qs.confirmations()>=Ws)return Ma(qs)}else if(await Xs(),Ws===0)return null;return await new Promise((Mc,ol)=>{const Vc=[],Dc=()=>{Vc.forEach(ll=>ll())};if(Vc.push(()=>{Va=!0}),Zs>0){const ll=setTimeout(()=>{Dc(),ol(makeError("wait for transaction timeout","TIMEOUT"))},Zs);Vc.push(()=>{clearTimeout(ll)})}const sl=async ll=>{if(await ll.confirmations()>=Ws){Dc();try{Mc(Ma(ll))}catch(hl){ol(hl)}}};if(Vc.push(()=>{this.provider.off(this.hash,sl)}),this.provider.on(this.hash,sl),zs>=0){const ll=async()=>{try{await Xs()}catch(hl){if(isError(hl,"TRANSACTION_REPLACED")){Dc(),ol(hl);return}}Va||this.provider.once("block",ll)};Vc.push(()=>{this.provider.off("block",ll)}),this.provider.once("block",ll)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}removedEvent(){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createRemovedTransactionFilter(this)}reorderedEvent(Ps){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),assert(!Ps||Ps.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createReorderedTransactionFilter(this,Ps)}replaceableTransaction(Ps){assertArgument(Number.isInteger(Ps)&&Ps>=0,"invalid startBlock","startBlock",Ps);const Hs=new TransactionResponse(this,this.provider);return Hs.#e=Ps,Hs}}function createOrphanedBlockFilter(Fs){return{orphan:"drop-block",hash:Fs.hash,number:Fs.number}}function createReorderedTransactionFilter(Fs,Ps){return{orphan:"reorder-transaction",tx:Fs,other:Ps}}function createRemovedTransactionFilter(Fs){return{orphan:"drop-transaction",tx:Fs}}function createRemovedLogFilter(Fs){return{orphan:"drop-log",log:{transactionHash:Fs.transactionHash,blockHash:Fs.blockHash,blockNumber:Fs.blockNumber,address:Fs.address,data:Fs.data,topics:Object.freeze(Fs.topics.slice()),index:Fs.index}}}class EventLog extends Log{interface;fragment;args;constructor(Ps,Hs,Ws){super(Ps,Ps.provider);const Zs=Hs.decodeEventLog(Ws,Ps.data,Ps.topics);defineProperties(this,{args:Zs,fragment:Ws,interface:Hs})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class UndecodedEventLog extends Log{error;constructor(Ps,Hs){super(Ps,Ps.provider),defineProperties(this,{error:Hs})}}class ContractTransactionReceipt extends TransactionReceipt{#e;constructor(Ps,Hs,Ws){super(Ws,Hs),this.#e=Ps}get logs(){return super.logs.map(Ps=>{const Hs=Ps.topics.length?this.#e.getEvent(Ps.topics[0]):null;if(Hs)try{return new EventLog(Ps,this.#e,Hs)}catch(Ws){return new UndecodedEventLog(Ps,Ws)}return Ps})}}class ContractTransactionResponse extends TransactionResponse{#e;constructor(Ps,Hs,Ws){super(Ws,Hs),this.#e=Ps}async wait(Ps,Hs){const Ws=await super.wait(Ps,Hs);return Ws==null?null:new ContractTransactionReceipt(this.#e,this.provider,Ws)}}class ContractUnknownEventPayload extends EventPayload{log;constructor(Ps,Hs,Ws,Zs){super(Ps,Hs,Ws),defineProperties(this,{log:Zs})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ContractEventPayload extends ContractUnknownEventPayload{constructor(Ps,Hs,Ws,Zs,zs){super(Ps,Hs,Ws,new EventLog(zs,Ps.interface,Zs));const Ys=Ps.interface.decodeEventLog(Zs,this.log.data,this.log.topics);defineProperties(this,{args:Ys,fragment:Zs})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const BN_0$1=BigInt(0);function canCall(Fs){return Fs&&typeof Fs.call=="function"}function canEstimate(Fs){return Fs&&typeof Fs.estimateGas=="function"}function canResolve(Fs){return Fs&&typeof Fs.resolveName=="function"}function canSend(Fs){return Fs&&typeof Fs.sendTransaction=="function"}function getResolver(Fs){if(Fs!=null){if(canResolve(Fs))return Fs;if(Fs.provider)return Fs.provider}}class PreparedTopicFilter{#e;fragment;constructor(Ps,Hs,Ws){if(defineProperties(this,{fragment:Hs}),Hs.inputs.length<Ws.length)throw new Error("too many arguments");const Zs=getRunner(Ps.runner,"resolveName"),zs=canResolve(Zs)?Zs:null;this.#e=(async function(){const Ys=await Promise.all(Hs.inputs.map((Va,Xs)=>Ws[Xs]==null?null:Va.walkAsync(Ws[Xs],(qs,Js)=>qs==="address"?Array.isArray(Js)?Promise.all(Js.map(Mc=>resolveAddress(Mc,zs))):resolveAddress(Js,zs):Js)));return Ps.interface.encodeFilterTopics(Hs,Ys)})()}getTopicFilter(){return this.#e}}function getRunner(Fs,Ps){return Fs==null?null:typeof Fs[Ps]=="function"?Fs:Fs.provider&&typeof Fs.provider[Ps]=="function"?Fs.provider:null}function getProvider(Fs){return Fs==null?null:Fs.provider||null}async function copyOverrides(Fs,Ps){const Hs=Typed.dereference(Fs,"overrides");assertArgument(typeof Hs=="object","invalid overrides parameter","overrides",Fs);const Ws=copyRequest(Hs);return assertArgument(Ws.to==null||(Ps||[]).indexOf("to")>=0,"cannot override to","overrides.to",Ws.to),assertArgument(Ws.data==null||(Ps||[]).indexOf("data")>=0,"cannot override data","overrides.data",Ws.data),Ws.from&&(Ws.from=Ws.from),Ws}async function resolveArgs(Fs,Ps,Hs){const Ws=getRunner(Fs,"resolveName"),Zs=canResolve(Ws)?Ws:null;return await Promise.all(Ps.map((zs,Ys)=>zs.walkAsync(Hs[Ys],(Va,Xs)=>(Xs=Typed.dereference(Xs,Va),Va==="address"?resolveAddress(Xs,Zs):Xs))))}function buildWrappedFallback(Fs){const Ps=async function(Ys){const Va=await copyOverrides(Ys,["data"]);Va.to=await Fs.getAddress(),Va.from&&(Va.from=await resolveAddress(Va.from,getResolver(Fs.runner)));const Xs=Fs.interface,Ma=getBigInt(Va.value||BN_0$1,"overrides.value")===BN_0$1,qs=(Va.data||"0x")==="0x";Xs.fallback&&!Xs.fallback.payable&&Xs.receive&&!qs&&!Ma&&assertArgument(!1,"cannot send data to receive or send value to non-payable fallback","overrides",Ys),assertArgument(Xs.fallback||qs,"cannot send data to receive-only contract","overrides.data",Va.data);const Js=Xs.receive||Xs.fallback&&Xs.fallback.payable;return assertArgument(Js||Ma,"cannot send value to non-payable fallback","overrides.value",Va.value),assertArgument(Xs.fallback||qs,"cannot send data to receive-only contract","overrides.data",Va.data),Va},Hs=async function(Ys){const Va=getRunner(Fs.runner,"call");assert(canCall(Va),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const Xs=await Ps(Ys);try{return await Va.call(Xs)}catch(Ma){throw isCallException(Ma)&&Ma.data?Fs.interface.makeError(Ma.data,Xs):Ma}},Ws=async function(Ys){const Va=Fs.runner;assert(canSend(Va),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const Xs=await Va.sendTransaction(await Ps(Ys)),Ma=getProvider(Fs.runner);return new ContractTransactionResponse(Fs.interface,Ma,Xs)},Zs=async function(Ys){const Va=getRunner(Fs.runner,"estimateGas");return assert(canEstimate(Va),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await Va.estimateGas(await Ps(Ys))},zs=async Ys=>await Ws(Ys);return defineProperties(zs,{_contract:Fs,estimateGas:Zs,populateTransaction:Ps,send:Ws,staticCall:Hs}),zs}function buildWrappedMethod(Fs,Ps){const Hs=function(...Ma){const qs=Fs.interface.getFunction(Ps,Ma);return assert(qs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps,args:Ma}}),qs},Ws=async function(...Ma){const qs=Hs(...Ma);let Js={};if(qs.inputs.length+1===Ma.length&&(Js=await copyOverrides(Ma.pop()),Js.from&&(Js.from=await resolveAddress(Js.from,getResolver(Fs.runner)))),qs.inputs.length!==Ma.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const Mc=await resolveArgs(Fs.runner,qs.inputs,Ma);return Object.assign({},Js,await resolveProperties({to:Fs.getAddress(),data:Fs.interface.encodeFunctionData(qs,Mc)}))},Zs=async function(...Ma){const qs=await Va(...Ma);return qs.length===1?qs[0]:qs},zs=async function(...Ma){const qs=Fs.runner;assert(canSend(qs),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const Js=await qs.sendTransaction(await Ws(...Ma)),Mc=getProvider(Fs.runner);return new ContractTransactionResponse(Fs.interface,Mc,Js)},Ys=async function(...Ma){const qs=getRunner(Fs.runner,"estimateGas");return assert(canEstimate(qs),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await qs.estimateGas(await Ws(...Ma))},Va=async function(...Ma){const qs=getRunner(Fs.runner,"call");assert(canCall(qs),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const Js=await Ws(...Ma);let Mc="0x";try{Mc=await qs.call(Js)}catch(Vc){throw isCallException(Vc)&&Vc.data?Fs.interface.makeError(Vc.data,Js):Vc}const ol=Hs(...Ma);return Fs.interface.decodeFunctionResult(ol,Mc)},Xs=async(...Ma)=>Hs(...Ma).constant?await Zs(...Ma):await zs(...Ma);return defineProperties(Xs,{name:Fs.interface.getFunctionName(Ps),_contract:Fs,_key:Ps,getFragment:Hs,estimateGas:Ys,populateTransaction:Ws,send:zs,staticCall:Zs,staticCallResult:Va}),Object.defineProperty(Xs,"fragment",{configurable:!1,enumerable:!0,get:()=>{const Ma=Fs.interface.getFunction(Ps);return assert(Ma,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps}}),Ma}}),Xs}function buildWrappedEvent(Fs,Ps){const Hs=function(...Zs){const zs=Fs.interface.getEvent(Ps,Zs);return assert(zs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps,args:Zs}}),zs},Ws=function(...Zs){return new PreparedTopicFilter(Fs,Hs(...Zs),Zs)};return defineProperties(Ws,{name:Fs.interface.getEventName(Ps),_contract:Fs,_key:Ps,getFragment:Hs}),Object.defineProperty(Ws,"fragment",{configurable:!1,enumerable:!0,get:()=>{const Zs=Fs.interface.getEvent(Ps);return assert(Zs,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:Ps}}),Zs}}),Ws}const internal=Symbol.for("_ethersInternal_contract"),internalValues=new WeakMap;function setInternal(Fs,Ps){internalValues.set(Fs[internal],Ps)}function getInternal(Fs){return internalValues.get(Fs[internal])}function isDeferred(Fs){return Fs&&typeof Fs=="object"&&"getTopicFilter"in Fs&&typeof Fs.getTopicFilter=="function"&&Fs.fragment}async function getSubInfo(Fs,Ps){let Hs,Ws=null;if(Array.isArray(Ps)){const zs=function(Ys){if(isHexString(Ys,32))return Ys;const Va=Fs.interface.getEvent(Ys);return assertArgument(Va,"unknown fragment","name",Ys),Va.topicHash};Hs=Ps.map(Ys=>Ys==null?null:Array.isArray(Ys)?Ys.map(zs):zs(Ys))}else Ps==="*"?Hs=[null]:typeof Ps=="string"?isHexString(Ps,32)?Hs=[Ps]:(Ws=Fs.interface.getEvent(Ps),assertArgument(Ws,"unknown fragment","event",Ps),Hs=[Ws.topicHash]):isDeferred(Ps)?Hs=await Ps.getTopicFilter():"fragment"in Ps?(Ws=Ps.fragment,Hs=[Ws.topicHash]):assertArgument(!1,"unknown event name","event",Ps);Hs=Hs.map(zs=>{if(zs==null)return null;if(Array.isArray(zs)){const Ys=Array.from(new Set(zs.map(Va=>Va.toLowerCase())).values());return Ys.length===1?Ys[0]:(Ys.sort(),Ys)}return zs.toLowerCase()});const Zs=Hs.map(zs=>zs==null?"null":Array.isArray(zs)?zs.join("|"):zs).join("&");return{fragment:Ws,tag:Zs,topics:Hs}}async function hasSub(Fs,Ps){const{subs:Hs}=getInternal(Fs);return Hs.get((await getSubInfo(Fs,Ps)).tag)||null}async function getSub(Fs,Ps,Hs){const Ws=getProvider(Fs.runner);assert(Ws,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:Ps});const{fragment:Zs,tag:zs,topics:Ys}=await getSubInfo(Fs,Hs),{addr:Va,subs:Xs}=getInternal(Fs);let Ma=Xs.get(zs);if(!Ma){const Js={address:Va||Fs,topics:Ys},Mc=sl=>{let ll=Zs;if(ll==null)try{ll=Fs.interface.getEvent(sl.topics[0])}catch{}if(ll){const hl=ll,pl=Zs?Fs.interface.decodeEventLog(Zs,sl.data,sl.topics):[];emit(Fs,Hs,pl,gl=>new ContractEventPayload(Fs,gl,Hs,hl,sl))}else emit(Fs,Hs,[],hl=>new ContractUnknownEventPayload(Fs,hl,Hs,sl))};let ol=[];Ma={tag:zs,listeners:[],start:()=>{ol.length||ol.push(Ws.on(Js,Mc))},stop:async()=>{if(ol.length==0)return;let sl=ol;ol=[],await Promise.all(sl),Ws.off(Js,Mc)}},Xs.set(zs,Ma)}return Ma}let lastEmit=Promise.resolve();async function _emit(Fs,Ps,Hs,Ws){await lastEmit;const Zs=await hasSub(Fs,Ps);if(!Zs)return!1;const zs=Zs.listeners.length;return Zs.listeners=Zs.listeners.filter(({listener:Ys,once:Va})=>{const Xs=Array.from(Hs);Ws&&Xs.push(Ws(Va?null:Ys));try{Ys.call(Fs,...Xs)}catch{}return!Va}),Zs.listeners.length===0&&(Zs.stop(),getInternal(Fs).subs.delete(Zs.tag)),zs>0}async function emit(Fs,Ps,Hs,Ws){try{await lastEmit}catch{}const Zs=_emit(Fs,Ps,Hs,Ws);return lastEmit=Zs,await Zs}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];fallback;constructor(Ps,Hs,Ws,Zs){assertArgument(typeof Ps=="string"||isAddressable(Ps),"invalid value for Contract target","target",Ps),Ws==null&&(Ws=null);const zs=Interface.from(Hs);defineProperties(this,{target:Ps,runner:Ws,interface:zs}),Object.defineProperty(this,internal,{value:{}});let Ys,Va=null,Xs=null;if(Zs){const Js=getProvider(Ws);Xs=new ContractTransactionResponse(this.interface,Js,Zs)}let Ma=new Map;if(typeof Ps=="string")if(isHexString(Ps))Va=Ps,Ys=Promise.resolve(Ps);else{const Js=getRunner(Ws,"resolveName");if(!canResolve(Js))throw makeError("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});Ys=Js.resolveName(Ps).then(Mc=>{if(Mc==null)throw makeError("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:Ps});return getInternal(this).addr=Mc,Mc})}else Ys=Ps.getAddress().then(Js=>{if(Js==null)throw new Error("TODO");return getInternal(this).addr=Js,Js});setInternal(this,{addrPromise:Ys,addr:Va,deployTx:Xs,subs:Ma});const qs=new Proxy({},{get:(Js,Mc,ol)=>{if(typeof Mc=="symbol"||passProperties.indexOf(Mc)>=0)return Reflect.get(Js,Mc,ol);try{return this.getEvent(Mc)}catch(Vc){if(!isError(Vc,"INVALID_ARGUMENT")||Vc.argument!=="key")throw Vc}},has:(Js,Mc)=>passProperties.indexOf(Mc)>=0?Reflect.has(Js,Mc):Reflect.has(Js,Mc)||this.interface.hasEvent(String(Mc))});return defineProperties(this,{filters:qs}),defineProperties(this,{fallback:zs.receive||zs.fallback?buildWrappedFallback(this):null}),new Proxy(this,{get:(Js,Mc,ol)=>{if(typeof Mc=="symbol"||Mc in Js||passProperties.indexOf(Mc)>=0)return Reflect.get(Js,Mc,ol);try{return Js.getFunction(Mc)}catch(Vc){if(!isError(Vc,"INVALID_ARGUMENT")||Vc.argument!=="key")throw Vc}},has:(Js,Mc)=>typeof Mc=="symbol"||Mc in Js||passProperties.indexOf(Mc)>=0?Reflect.has(Js,Mc):Js.interface.hasFunction(Mc)})}connect(Ps){return new BaseContract(this.target,this.interface,Ps)}attach(Ps){return new BaseContract(Ps,this.interface,this.runner)}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const Ps=getProvider(this.runner);assert(Ps,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const Hs=await Ps.getCode(await this.getAddress());return Hs==="0x"?null:Hs}async waitForDeployment(){const Ps=this.deploymentTransaction();if(Ps)return await Ps.wait(),this;if(await this.getDeployedCode()!=null)return this;const Ws=getProvider(this.runner);return assert(Ws!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((Zs,zs)=>{const Ys=async()=>{try{if(await this.getDeployedCode()!=null)return Zs(this);Ws.once("block",Ys)}catch(Va){zs(Va)}};Ys()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(Ps){return typeof Ps!="string"&&(Ps=Ps.format()),buildWrappedMethod(this,Ps)}getEvent(Ps){return typeof Ps!="string"&&(Ps=Ps.format()),buildWrappedEvent(this,Ps)}async queryTransaction(Ps){throw new Error("@TODO")}async queryFilter(Ps,Hs,Ws){Hs==null&&(Hs=0),Ws==null&&(Ws="latest");const{addr:Zs,addrPromise:zs}=getInternal(this),Ys=Zs||await zs,{fragment:Va,topics:Xs}=await getSubInfo(this,Ps),Ma={address:Ys,topics:Xs,fromBlock:Hs,toBlock:Ws},qs=getProvider(this.runner);return assert(qs,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await qs.getLogs(Ma)).map(Js=>{let Mc=Va;if(Mc==null)try{Mc=this.interface.getEvent(Js.topics[0])}catch{}if(Mc)try{return new EventLog(Js,this.interface,Mc)}catch(ol){return new UndecodedEventLog(Js,ol)}return new Log(Js,qs)})}async on(Ps,Hs){const Ws=await getSub(this,"on",Ps);return Ws.listeners.push({listener:Hs,once:!1}),Ws.start(),this}async once(Ps,Hs){const Ws=await getSub(this,"once",Ps);return Ws.listeners.push({listener:Hs,once:!0}),Ws.start(),this}async emit(Ps,...Hs){return await emit(this,Ps,Hs,null)}async listenerCount(Ps){if(Ps){const Zs=await hasSub(this,Ps);return Zs?Zs.listeners.length:0}const{subs:Hs}=getInternal(this);let Ws=0;for(const{listeners:Zs}of Hs.values())Ws+=Zs.length;return Ws}async listeners(Ps){if(Ps){const Zs=await hasSub(this,Ps);return Zs?Zs.listeners.map(({listener:zs})=>zs):[]}const{subs:Hs}=getInternal(this);let Ws=[];for(const{listeners:Zs}of Hs.values())Ws=Ws.concat(Zs.map(({listener:zs})=>zs));return Ws}async off(Ps,Hs){const Ws=await hasSub(this,Ps);if(!Ws)return this;if(Hs){const Zs=Ws.listeners.map(({listener:zs})=>zs).indexOf(Hs);Zs>=0&&Ws.listeners.splice(Zs,1)}return(Hs==null||Ws.listeners.length===0)&&(Ws.stop(),getInternal(this).subs.delete(Ws.tag)),this}async removeAllListeners(Ps){if(Ps){const Hs=await hasSub(this,Ps);if(!Hs)return this;Hs.stop(),getInternal(this).subs.delete(Hs.tag)}else{const{subs:Hs}=getInternal(this);for(const{tag:Ws,stop:Zs}of Hs.values())Zs(),Hs.delete(Ws)}return this}async addListener(Ps,Hs){return await this.on(Ps,Hs)}async removeListener(Ps,Hs){return await this.off(Ps,Hs)}static buildClass(Ps){class Hs extends BaseContract{constructor(Zs,zs=null){super(Zs,Ps,zs)}}return Hs}static from(Ps,Hs,Ws){return Ws==null&&(Ws=null),new this(Ps,Hs,Ws)}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}function getIpfsLink(Fs){return Fs.match(/^ipfs:\/\/ipfs\//i)?Fs=Fs.substring(12):Fs.match(/^ipfs:\/\//i)?Fs=Fs.substring(7):assertArgument(!1,"unsupported IPFS format","link",Fs),`https://gateway.ipfs.io/ipfs/${Fs}`}class MulticoinProviderPlugin{name;constructor(Ps){defineProperties(this,{name:Ps})}connect(Ps){return this}supportsCoinType(Ps){return!1}async encodeAddress(Ps,Hs){throw new Error("unsupported coin")}async decodeAddress(Ps,Hs){throw new Error("unsupported coin")}}const matcherIpfs=new RegExp("^(ipfs)://(.*)$","i"),matchers=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),matcherIpfs,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class EnsResolver{provider;address;name;#e;#t;constructor(Ps,Hs,Ws){defineProperties(this,{provider:Ps,address:Hs,name:Ws}),this.#e=null,this.#t=new Contract(Hs,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],Ps)}async supportsWildcard(){return this.#e==null&&(this.#e=(async()=>{try{return await this.#t.supportsInterface("0x9061b923")}catch(Ps){if(isError(Ps,"CALL_EXCEPTION"))return!1;throw this.#e=null,Ps}})()),await this.#e}async#r(Ps,Hs){Hs=(Hs||[]).slice();const Ws=this.#t.interface;Hs.unshift(namehash(this.name));let Zs=null;await this.supportsWildcard()&&(Zs=Ws.getFunction(Ps),assert(Zs,"missing fragment","UNKNOWN_ERROR",{info:{funcName:Ps}}),Hs=[dnsEncode(this.name,255),Ws.encodeFunctionData(Zs,Hs)],Ps="resolve(bytes,bytes)"),Hs.push({enableCcipRead:!0});try{const zs=await this.#t[Ps](...Hs);return Zs?Ws.decodeFunctionResult(Zs,zs)[0]:zs}catch(zs){if(!isError(zs,"CALL_EXCEPTION"))throw zs}return null}async getAddress(Ps){if(Ps==null&&(Ps=60),Ps===60)try{const zs=await this.#r("addr(bytes32)");return zs==null||zs===ZeroAddress?null:zs}catch(zs){if(isError(zs,"CALL_EXCEPTION"))return null;throw zs}if(Ps>=0&&Ps<2147483648){let zs=Ps+2147483648;const Ys=await this.#r("addr(bytes32,uint)",[zs]);if(isHexString(Ys,20))return getAddress(Ys)}let Hs=null;for(const zs of this.provider.plugins)if(zs instanceof MulticoinProviderPlugin&&zs.supportsCoinType(Ps)){Hs=zs;break}if(Hs==null)return null;const Ws=await this.#r("addr(bytes32,uint)",[Ps]);if(Ws==null||Ws==="0x")return null;const Zs=await Hs.decodeAddress(Ps,Ws);if(Zs!=null)return Zs;assert(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${Ps})`,info:{coinType:Ps,data:Ws}})}async getText(Ps){const Hs=await this.#r("text(bytes32,string)",[Ps]);return Hs==null||Hs==="0x"?null:Hs}async getContentHash(){const Ps=await this.#r("contenthash(bytes32)");if(Ps==null||Ps==="0x")return null;const Hs=Ps.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(Hs){const Zs=Hs[1]==="e3010170"?"ipfs":"ipns",zs=parseInt(Hs[4],16);if(Hs[5].length===zs*2)return`${Zs}://${encodeBase58("0x"+Hs[2])}`}const Ws=Ps.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(Ws&&Ws[1].length===64)return`bzz://${Ws[1]}`;assert(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:Ps}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const Ps=[{type:"name",value:this.name}];try{const Hs=await this.getText("avatar");if(Hs==null)return Ps.push({type:"!avatar",value:""}),{url:null,linkage:Ps};Ps.push({type:"avatar",value:Hs});for(let Ws=0;Ws<matchers.length;Ws++){const Zs=Hs.match(matchers[Ws]);if(Zs==null)continue;const zs=Zs[1].toLowerCase();switch(zs){case"https":case"data":return Ps.push({type:"url",value:Hs}),{linkage:Ps,url:Hs};case"ipfs":{const Ys=getIpfsLink(Hs);return Ps.push({type:"ipfs",value:Hs}),Ps.push({type:"url",value:Ys}),{linkage:Ps,url:Ys}}case"erc721":case"erc1155":{const Ys=zs==="erc721"?"tokenURI(uint256)":"uri(uint256)";Ps.push({type:zs,value:Hs});const Va=await this.getAddress();if(Va==null)return Ps.push({type:"!owner",value:""}),{url:null,linkage:Ps};const Xs=(Zs[2]||"").split("/");if(Xs.length!==2)return Ps.push({type:`!${zs}caip`,value:Zs[2]||""}),{url:null,linkage:Ps};const Ma=Xs[1],qs=new Contract(Xs[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if(zs==="erc721"){const Dc=await qs.ownerOf(Ma);if(Va!==Dc)return Ps.push({type:"!owner",value:Dc}),{url:null,linkage:Ps};Ps.push({type:"owner",value:Dc})}else if(zs==="erc1155"){const Dc=await qs.balanceOf(Va,Ma);if(!Dc)return Ps.push({type:"!balance",value:"0"}),{url:null,linkage:Ps};Ps.push({type:"balance",value:Dc.toString()})}let Js=await qs[Ys](Ma);if(Js==null||Js==="0x")return Ps.push({type:"!metadata-url",value:""}),{url:null,linkage:Ps};Ps.push({type:"metadata-url-base",value:Js}),zs==="erc1155"&&(Js=Js.replace("{id}",toBeHex(Ma,32).substring(2)),Ps.push({type:"metadata-url-expanded",value:Js})),Js.match(/^ipfs:/i)&&(Js=getIpfsLink(Js)),Ps.push({type:"metadata-url",value:Js});let Mc={};const ol=await new FetchRequest(Js).send();ol.assertOk();try{Mc=ol.bodyJson}catch{try{Ps.push({type:"!metadata",value:ol.bodyText})}catch{const ll=ol.body;return ll&&Ps.push({type:"!metadata",value:hexlify(ll)}),{url:null,linkage:Ps}}return{url:null,linkage:Ps}}if(!Mc)return Ps.push({type:"!metadata",value:""}),{url:null,linkage:Ps};Ps.push({type:"metadata",value:JSON.stringify(Mc)});let Vc=Mc.image;if(typeof Vc!="string")return Ps.push({type:"!imageUrl",value:""}),{url:null,linkage:Ps};if(!Vc.match(/^(https:\/\/|data:)/i)){if(Vc.match(matcherIpfs)==null)return Ps.push({type:"!imageUrl-ipfs",value:Vc}),{url:null,linkage:Ps};Ps.push({type:"imageUrl-ipfs",value:Vc}),Vc=getIpfsLink(Vc)}return Ps.push({type:"url",value:Vc}),{linkage:Ps,url:Vc}}}}}catch{}return{linkage:Ps,url:null}}static async getEnsAddress(Ps){const Hs=await Ps.getNetwork(),Ws=Hs.getPlugin("org.ethers.plugins.network.Ens");return assert(Ws,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:Hs}}),Ws.address}static async#n(Ps,Hs){const Ws=await EnsResolver.getEnsAddress(Ps);try{const zs=await new Contract(Ws,["function resolver(bytes32) view returns (address)"],Ps).resolver(namehash(Hs),{enableCcipRead:!0});return zs===ZeroAddress?null:zs}catch(Zs){throw Zs}return null}static async fromName(Ps,Hs){let Ws=Hs;for(;;){if(Ws===""||Ws==="."||Hs!=="eth"&&Ws==="eth")return null;const Zs=await EnsResolver.#n(Ps,Ws);if(Zs!=null){const zs=new EnsResolver(Ps,Zs,Hs);return Ws!==Hs&&!await zs.supportsWildcard()?null:zs}Ws=Ws.split(".").slice(1).join(".")}}}const BN_0=BigInt(0);function allowNull(Fs,Ps){return(function(Hs){return Hs==null?Ps:Fs(Hs)})}function arrayOf(Fs,Ps){return(Hs=>{if(Ps&&Hs==null)return null;if(!Array.isArray(Hs))throw new Error("not an array");return Hs.map(Ws=>Fs(Ws))})}function object(Fs,Ps){return(Hs=>{const Ws={};for(const Zs in Fs){let zs=Zs;if(Ps&&Zs in Ps&&!(zs in Hs)){for(const Ys of Ps[Zs])if(Ys in Hs){zs=Ys;break}}try{const Ys=Fs[Zs](Hs[zs]);Ys!==void 0&&(Ws[Zs]=Ys)}catch(Ys){const Va=Ys instanceof Error?Ys.message:"not-an-error";assert(!1,`invalid value for value.${Zs} (${Va})`,"BAD_DATA",{value:Hs})}}return Ws})}function formatBoolean(Fs){switch(Fs){case!0:case"true":return!0;case!1:case"false":return!1}assertArgument(!1,`invalid boolean; ${JSON.stringify(Fs)}`,"value",Fs)}function formatData(Fs){return assertArgument(isHexString(Fs,!0),"invalid data","value",Fs),Fs}function formatHash(Fs){return assertArgument(isHexString(Fs,32),"invalid hash","value",Fs),Fs}const _formatLog=object({address:getAddress,blockHash:formatHash,blockNumber:getNumber,data:formatData,index:getNumber,removed:allowNull(formatBoolean,!1),topics:arrayOf(formatHash),transactionHash:formatHash,transactionIndex:getNumber},{index:["logIndex"]});function formatLog(Fs){return _formatLog(Fs)}const _formatBlock=object({hash:allowNull(formatHash),parentHash:formatHash,parentBeaconBlockRoot:allowNull(formatHash,null),number:getNumber,timestamp:getNumber,nonce:allowNull(formatData),difficulty:getBigInt,gasLimit:getBigInt,gasUsed:getBigInt,stateRoot:allowNull(formatHash,null),receiptsRoot:allowNull(formatHash,null),blobGasUsed:allowNull(getBigInt,null),excessBlobGas:allowNull(getBigInt,null),miner:allowNull(getAddress),prevRandao:allowNull(formatHash,null),extraData:formatData,baseFeePerGas:allowNull(getBigInt)},{prevRandao:["mixHash"]});function formatBlock(Fs){const Ps=_formatBlock(Fs);return Ps.transactions=Fs.transactions.map(Hs=>typeof Hs=="string"?Hs:formatTransactionResponse(Hs)),Ps}const _formatReceiptLog=object({transactionIndex:getNumber,blockNumber:getNumber,transactionHash:formatHash,address:getAddress,topics:arrayOf(formatHash),data:formatData,index:getNumber,blockHash:formatHash},{index:["logIndex"]});function formatReceiptLog(Fs){return _formatReceiptLog(Fs)}const _formatTransactionReceipt=object({to:allowNull(getAddress,null),from:allowNull(getAddress,null),contractAddress:allowNull(getAddress,null),index:getNumber,root:allowNull(hexlify),gasUsed:getBigInt,blobGasUsed:allowNull(getBigInt,null),logsBloom:allowNull(formatData),blockHash:formatHash,hash:formatHash,logs:arrayOf(formatReceiptLog),blockNumber:getNumber,cumulativeGasUsed:getBigInt,effectiveGasPrice:allowNull(getBigInt),blobGasPrice:allowNull(getBigInt,null),status:allowNull(getNumber),type:allowNull(getNumber,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function formatTransactionReceipt(Fs){return _formatTransactionReceipt(Fs)}function formatTransactionResponse(Fs){Fs.to&&getBigInt(Fs.to)===BN_0&&(Fs.to="0x0000000000000000000000000000000000000000");const Ps=object({hash:formatHash,index:allowNull(getNumber,void 0),type:Hs=>Hs==="0x"||Hs==null?0:getNumber(Hs),accessList:allowNull(accessListify,null),blobVersionedHashes:allowNull(arrayOf(formatHash,!0),null),authorizationList:allowNull(arrayOf(Hs=>{let Ws;if(Hs.signature)Ws=Hs.signature;else{let Zs=Hs.yParity;Zs==="0x1b"?Zs=0:Zs==="0x1c"&&(Zs=1),Ws=Object.assign({},Hs,{yParity:Zs})}return{address:getAddress(Hs.address),chainId:getBigInt(Hs.chainId),nonce:getBigInt(Hs.nonce),signature:Signature.from(Ws)}},!1),null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(getNumber,null),transactionIndex:allowNull(getNumber,null),from:getAddress,gasPrice:allowNull(getBigInt),maxPriorityFeePerGas:allowNull(getBigInt),maxFeePerGas:allowNull(getBigInt),maxFeePerBlobGas:allowNull(getBigInt,null),gasLimit:getBigInt,to:allowNull(getAddress,null),value:getBigInt,nonce:getNumber,data:formatData,creates:allowNull(getAddress,null),chainId:allowNull(getBigInt,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(Fs);if(Ps.to==null&&Ps.creates==null&&(Ps.creates=getCreateAddress(Ps)),(Fs.type===1||Fs.type===2)&&Fs.accessList==null&&(Ps.accessList=[]),Fs.signature?Ps.signature=Signature.from(Fs.signature):Ps.signature=Signature.from(Fs),Ps.chainId==null){const Hs=Ps.signature.legacyChainId;Hs!=null&&(Ps.chainId=Hs)}return Ps.blockHash&&getBigInt(Ps.blockHash)===BN_0&&(Ps.blockHash=null),Ps}const EnsAddress="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class NetworkPlugin{name;constructor(Ps){defineProperties(this,{name:Ps})}clone(){return new NetworkPlugin(this.name)}}class GasCostPlugin extends NetworkPlugin{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(Ps,Hs){Ps==null&&(Ps=0),super(`org.ethers.network.plugins.GasCost#${Ps||0}`);const Ws={effectiveBlock:Ps};function Zs(zs,Ys){let Va=(Hs||{})[zs];Va==null&&(Va=Ys),assertArgument(typeof Va=="number",`invalud value for ${zs}`,"costs",Hs),Ws[zs]=Va}Zs("txBase",21e3),Zs("txCreate",32e3),Zs("txDataZero",4),Zs("txDataNonzero",16),Zs("txAccessListStorageKey",1900),Zs("txAccessListAddress",2400),defineProperties(this,Ws)}clone(){return new GasCostPlugin(this.effectiveBlock,this)}}class EnsPlugin extends NetworkPlugin{address;targetNetwork;constructor(Ps,Hs){super("org.ethers.plugins.network.Ens"),defineProperties(this,{address:Ps||EnsAddress,targetNetwork:Hs??1})}clone(){return new EnsPlugin(this.address,this.targetNetwork)}}class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin{#e;#t;get url(){return this.#e}get processFunc(){return this.#t}constructor(Ps,Hs){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#e=Ps,this.#t=Hs}clone(){return this}}const Networks=new Map;class Network{#e;#t;#r;constructor(Ps,Hs){this.#e=Ps,this.#t=getBigInt(Hs),this.#r=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#e}set name(Ps){this.#e=Ps}get chainId(){return this.#t}set chainId(Ps){this.#t=getBigInt(Ps,"chainId")}matches(Ps){if(Ps==null)return!1;if(typeof Ps=="string"){try{return this.chainId===getBigInt(Ps)}catch{}return this.name===Ps}if(typeof Ps=="number"||typeof Ps=="bigint"){try{return this.chainId===getBigInt(Ps)}catch{}return!1}if(typeof Ps=="object"){if(Ps.chainId!=null){try{return this.chainId===getBigInt(Ps.chainId)}catch{}return!1}return Ps.name!=null?this.name===Ps.name:!1}return!1}get plugins(){return Array.from(this.#r.values())}attachPlugin(Ps){if(this.#r.get(Ps.name))throw new Error(`cannot replace existing plugin: ${Ps.name} `);return this.#r.set(Ps.name,Ps.clone()),this}getPlugin(Ps){return this.#r.get(Ps)||null}getPlugins(Ps){return this.plugins.filter(Hs=>Hs.name.split("#")[0]===Ps)}clone(){const Ps=new Network(this.name,this.chainId);return this.plugins.forEach(Hs=>{Ps.attachPlugin(Hs.clone())}),Ps}computeIntrinsicGas(Ps){const Hs=this.getPlugin("org.ethers.plugins.network.GasCost")||new GasCostPlugin;let Ws=Hs.txBase;if(Ps.to==null&&(Ws+=Hs.txCreate),Ps.data)for(let Zs=2;Zs<Ps.data.length;Zs+=2)Ps.data.substring(Zs,Zs+2)==="00"?Ws+=Hs.txDataZero:Ws+=Hs.txDataNonzero;if(Ps.accessList){const Zs=accessListify(Ps.accessList);for(const zs in Zs)Ws+=Hs.txAccessListAddress+Hs.txAccessListStorageKey*Zs[zs].storageKeys.length}return Ws}static from(Ps){if(injectCommonNetworks(),Ps==null)return Network.from("mainnet");if(typeof Ps=="number"&&(Ps=BigInt(Ps)),typeof Ps=="string"||typeof Ps=="bigint"){const Hs=Networks.get(Ps);if(Hs)return Hs();if(typeof Ps=="bigint")return new Network("unknown",Ps);assertArgument(!1,"unknown network","network",Ps)}if(typeof Ps.clone=="function")return Ps.clone();if(typeof Ps=="object"){assertArgument(typeof Ps.name=="string"&&typeof Ps.chainId=="number","invalid network object name or chainId","network",Ps);const Hs=new Network(Ps.name,Ps.chainId);return(Ps.ensAddress||Ps.ensNetwork!=null)&&Hs.attachPlugin(new EnsPlugin(Ps.ensAddress,Ps.ensNetwork)),Hs}assertArgument(!1,"invalid network","network",Ps)}static register(Ps,Hs){typeof Ps=="number"&&(Ps=BigInt(Ps));const Ws=Networks.get(Ps);Ws&&assertArgument(!1,`conflicting network for ${JSON.stringify(Ws.name)}`,"nameOrChainId",Ps),Networks.set(Ps,Hs)}}function parseUnits(Fs,Ps){const Hs=String(Fs);if(!Hs.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${Fs}`);const Ws=Hs.split(".");if(Ws.length===1&&Ws.push(""),Ws.length!==2)throw new Error(`invalid gwei value: ${Fs}`);for(;Ws[1].length<Ps;)Ws[1]+="0";if(Ws[1].length>9){let Zs=BigInt(Ws[1].substring(0,9));Ws[1].substring(9).match(/^0+$/)||Zs++,Ws[1]=Zs.toString()}return BigInt(Ws[0]+Ws[1])}function getGasStationPlugin(Fs){return new FetchUrlFeeDataNetworkPlugin(Fs,async(Ps,Hs,Ws)=>{Ws.setHeader("User-Agent","ethers");let Zs;try{const[zs,Ys]=await Promise.all([Ws.send(),Ps()]);Zs=zs;const Va=Zs.bodyJson.standard;return{gasPrice:Ys.gasPrice,maxFeePerGas:parseUnits(Va.maxFee,9),maxPriorityFeePerGas:parseUnits(Va.maxPriorityFee,9)}}catch(zs){assert(!1,`error encountered with polygon gas station (${JSON.stringify(Ws.url)})`,"SERVER_ERROR",{request:Ws,response:Zs,error:zs})}})}let injected=!1;function injectCommonNetworks(){if(injected)return;injected=!0;function Fs(Ps,Hs,Ws){const Zs=function(){const zs=new Network(Ps,Hs);return Ws.ensNetwork!=null&&zs.attachPlugin(new EnsPlugin(null,Ws.ensNetwork)),zs.attachPlugin(new GasCostPlugin),(Ws.plugins||[]).forEach(Ys=>{zs.attachPlugin(Ys)}),zs};Network.register(Ps,Zs),Network.register(Hs,Zs),Ws.altNames&&Ws.altNames.forEach(zs=>{Network.register(zs,Zs)})}Fs("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),Fs("ropsten",3,{ensNetwork:3}),Fs("rinkeby",4,{ensNetwork:4}),Fs("goerli",5,{ensNetwork:5}),Fs("kovan",42,{ensNetwork:42}),Fs("sepolia",11155111,{ensNetwork:11155111}),Fs("holesky",17e3,{ensNetwork:17e3}),Fs("classic",61,{}),Fs("classicKotti",6,{}),Fs("arbitrum",42161,{ensNetwork:1}),Fs("arbitrum-goerli",421613,{}),Fs("arbitrum-sepolia",421614,{}),Fs("base",8453,{ensNetwork:1}),Fs("base-goerli",84531,{}),Fs("base-sepolia",84532,{}),Fs("bnb",56,{ensNetwork:1}),Fs("bnbt",97,{}),Fs("linea",59144,{ensNetwork:1}),Fs("linea-goerli",59140,{}),Fs("linea-sepolia",59141,{}),Fs("matic",137,{ensNetwork:1,plugins:[getGasStationPlugin("https://gasstation.polygon.technology/v2")]}),Fs("matic-amoy",80002,{}),Fs("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[getGasStationPlugin("https://gasstation-testnet.polygon.technology/v2")]}),Fs("optimism",10,{ensNetwork:1,plugins:[]}),Fs("optimism-goerli",420,{}),Fs("optimism-sepolia",11155420,{}),Fs("xdai",100,{ensNetwork:1})}function copy$2(Fs){return JSON.parse(JSON.stringify(Fs))}class PollingBlockSubscriber{#e;#t;#r;#n;constructor(Ps){this.#e=Ps,this.#t=null,this.#r=4e3,this.#n=-2}get pollingInterval(){return this.#r}set pollingInterval(Ps){this.#r=Ps}async#o(){try{const Ps=await this.#e.getBlockNumber();if(this.#n===-2){this.#n=Ps;return}if(Ps!==this.#n){for(let Hs=this.#n+1;Hs<=Ps;Hs++){if(this.#t==null)return;await this.#e.emit("block",Hs)}this.#n=Ps}}catch{}this.#t!=null&&(this.#t=this.#e._setTimeout(this.#o.bind(this),this.#r))}start(){this.#t||(this.#t=this.#e._setTimeout(this.#o.bind(this),this.#r),this.#o())}stop(){this.#t&&(this.#e._clearTimeout(this.#t),this.#t=null)}pause(Ps){this.stop(),Ps&&(this.#n=-2)}resume(){this.start()}}class OnBlockSubscriber{#e;#t;#r;constructor(Ps){this.#e=Ps,this.#r=!1,this.#t=Hs=>{this._poll(Hs,this.#e)}}async _poll(Ps,Hs){throw new Error("sub-classes must override this")}start(){this.#r||(this.#r=!0,this.#t(-2),this.#e.on("block",this.#t))}stop(){this.#r&&(this.#r=!1,this.#e.off("block",this.#t))}pause(Ps){this.stop()}resume(){this.start()}}class PollingBlockTagSubscriber extends OnBlockSubscriber{#e;#t;constructor(Ps,Hs){super(Ps),this.#e=Hs,this.#t=-2}pause(Ps){Ps&&(this.#t=-2),super.pause(Ps)}async _poll(Ps,Hs){const Ws=await Hs.getBlock(this.#e);Ws!=null&&(this.#t===-2?this.#t=Ws.number:Ws.number>this.#t&&(Hs.emit(this.#e,Ws.number),this.#t=Ws.number))}}class PollingOrphanSubscriber extends OnBlockSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=copy$2(Hs)}async _poll(Ps,Hs){throw new Error("@TODO")}}class PollingTransactionSubscriber extends OnBlockSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=Hs}async _poll(Ps,Hs){const Ws=await Hs.getTransactionReceipt(this.#e);Ws&&Hs.emit(this.#e,Ws)}}class PollingEventSubscriber{#e;#t;#r;#n;#o;constructor(Ps,Hs){this.#e=Ps,this.#t=copy$2(Hs),this.#r=this.#s.bind(this),this.#n=!1,this.#o=-2}async#s(Ps){if(this.#o===-2)return;const Hs=copy$2(this.#t);Hs.fromBlock=this.#o+1,Hs.toBlock=Ps;const Ws=await this.#e.getLogs(Hs);if(Ws.length===0){this.#o<Ps-60&&(this.#o=Ps-60);return}for(const Zs of Ws)this.#e.emit(this.#t,Zs),this.#o=Zs.blockNumber}start(){this.#n||(this.#n=!0,this.#o===-2&&this.#e.getBlockNumber().then(Ps=>{this.#o=Ps}),this.#e.on("block",this.#r))}stop(){this.#n&&(this.#n=!1,this.#e.off("block",this.#r))}pause(Ps){this.stop(),Ps&&(this.#o=-2)}resume(){this.start()}}const BN_2=BigInt(2),MAX_CCIP_REDIRECTS=10;function isPromise(Fs){return Fs&&typeof Fs.then=="function"}function getTag(Fs,Ps){return Fs+":"+JSON.stringify(Ps,(Hs,Ws)=>{if(Ws==null)return"null";if(typeof Ws=="bigint")return`bigint:${Ws.toString()}`;if(typeof Ws=="string")return Ws.toLowerCase();if(typeof Ws=="object"&&!Array.isArray(Ws)){const Zs=Object.keys(Ws);return Zs.sort(),Zs.reduce((zs,Ys)=>(zs[Ys]=Ws[Ys],zs),{})}return Ws})}class UnmanagedSubscriber{name;constructor(Ps){defineProperties(this,{name:Ps})}start(){}stop(){}pause(Ps){}resume(){}}function copy$1(Fs){return JSON.parse(JSON.stringify(Fs))}function concisify(Fs){return Fs=Array.from(new Set(Fs).values()),Fs.sort(),Fs}async function getSubscription(Fs,Ps){if(Fs==null)throw new Error("invalid event");if(Array.isArray(Fs)&&(Fs={topics:Fs}),typeof Fs=="string")switch(Fs){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:Fs,tag:Fs}}if(isHexString(Fs,32)){const Hs=Fs.toLowerCase();return{type:"transaction",tag:getTag("tx",{hash:Hs}),hash:Hs}}if(Fs.orphan){const Hs=Fs;return{type:"orphan",tag:getTag("orphan",Hs),filter:copy$1(Hs)}}if(Fs.address||Fs.topics){const Hs=Fs,Ws={topics:(Hs.topics||[]).map(Zs=>Zs==null?null:Array.isArray(Zs)?concisify(Zs.map(zs=>zs.toLowerCase())):Zs.toLowerCase())};if(Hs.address){const Zs=[],zs=[],Ys=Va=>{isHexString(Va)?Zs.push(Va):zs.push((async()=>{Zs.push(await resolveAddress(Va,Ps))})())};Array.isArray(Hs.address)?Hs.address.forEach(Ys):Ys(Hs.address),zs.length&&await Promise.all(zs),Ws.address=concisify(Zs.map(Va=>Va.toLowerCase()))}return{filter:Ws,tag:getTag("event",Ws),type:"event"}}assertArgument(!1,"unknown ProviderEvent","event",Fs)}function getTime(){return new Date().getTime()}const defaultOptions$1={cacheTimeout:250,pollingInterval:4e3};class AbstractProvider{#e;#t;#r;#n;#o;#s;#i;#a;#d;#l;#p;#g;constructor(Ps,Hs){if(this.#g=Object.assign({},defaultOptions$1,Hs||{}),Ps==="any")this.#s=!0,this.#o=null;else if(Ps){const Ws=Network.from(Ps);this.#s=!1,this.#o=Promise.resolve(Ws),setTimeout(()=>{this.emit("network",Ws,null)},0)}else this.#s=!1,this.#o=null;this.#a=-1,this.#i=new Map,this.#e=new Map,this.#t=new Map,this.#r=null,this.#n=!1,this.#d=1,this.#l=new Map,this.#p=!1}get pollingInterval(){return this.#g.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#t.values())}attachPlugin(Ps){if(this.#t.get(Ps.name))throw new Error(`cannot replace existing plugin: ${Ps.name} `);return this.#t.set(Ps.name,Ps.connect(this)),this}getPlugin(Ps){return this.#t.get(Ps)||null}get disableCcipRead(){return this.#p}set disableCcipRead(Ps){this.#p=!!Ps}async#c(Ps){const Hs=this.#g.cacheTimeout;if(Hs<0)return await this._perform(Ps);const Ws=getTag(Ps.method,Ps);let Zs=this.#i.get(Ws);return Zs||(Zs=this._perform(Ps),this.#i.set(Ws,Zs),setTimeout(()=>{this.#i.get(Ws)===Zs&&this.#i.delete(Ws)},Hs)),await Zs}async ccipReadFetch(Ps,Hs,Ws){if(this.disableCcipRead||Ws.length===0||Ps.to==null)return null;const Zs=Ps.to.toLowerCase(),zs=Hs.toLowerCase(),Ys=[];for(let Va=0;Va<Ws.length;Va++){const Xs=Ws[Va],Ma=Xs.replace("{sender}",Zs).replace("{data}",zs),qs=new FetchRequest(Ma);Xs.indexOf("{data}")===-1&&(qs.body={data:zs,sender:Zs}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:qs,index:Va,urls:Ws});let Js="unknown error",Mc;try{Mc=await qs.send()}catch(ol){Ys.push(ol.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:qs,result:{error:ol}});continue}try{const ol=Mc.bodyJson;if(ol.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:qs,result:ol}),ol.data;ol.message&&(Js=ol.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:qs,result:ol})}catch{}assert(Mc.statusCode<400||Mc.statusCode>=500,`response not found during CCIP fetch: ${Js}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:Ps,info:{url:Xs,errorMessage:Js}}),Ys.push(Js)}assert(!1,`error encountered during CCIP fetch: ${Ys.map(Va=>JSON.stringify(Va)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:Ps,info:{urls:Ws,errorMessages:Ys}})}_wrapBlock(Ps,Hs){return new Block(formatBlock(Ps),this)}_wrapLog(Ps,Hs){return new Log(formatLog(Ps),this)}_wrapTransactionReceipt(Ps,Hs){return new TransactionReceipt(formatTransactionReceipt(Ps),this)}_wrapTransactionResponse(Ps,Hs){return new TransactionResponse(formatTransactionResponse(Ps),this)}_detectNetwork(){assert(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(Ps){assert(!1,`unsupported method: ${Ps.method}`,"UNSUPPORTED_OPERATION",{operation:Ps.method,info:Ps})}async getBlockNumber(){const Ps=getNumber(await this.#c({method:"getBlockNumber"}),"%response");return this.#a>=0&&(this.#a=Ps),Ps}_getAddress(Ps){return resolveAddress(Ps,this)}_getBlockTag(Ps){if(Ps==null)return"latest";switch(Ps){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return Ps}if(isHexString(Ps))return isHexString(Ps,32)?Ps:toQuantity(Ps);if(typeof Ps=="bigint"&&(Ps=getNumber(Ps,"blockTag")),typeof Ps=="number")return Ps>=0?toQuantity(Ps):this.#a>=0?toQuantity(this.#a+Ps):this.getBlockNumber().then(Hs=>toQuantity(Hs+Ps));assertArgument(!1,"invalid blockTag","blockTag",Ps)}_getFilter(Ps){const Hs=(Ps.topics||[]).map(Xs=>Xs==null?null:Array.isArray(Xs)?concisify(Xs.map(Ma=>Ma.toLowerCase())):Xs.toLowerCase()),Ws="blockHash"in Ps?Ps.blockHash:void 0,Zs=(Xs,Ma,qs)=>{let Js;switch(Xs.length){case 0:break;case 1:Js=Xs[0];break;default:Xs.sort(),Js=Xs}if(Ws&&(Ma!=null||qs!=null))throw new Error("invalid filter");const Mc={};return Js&&(Mc.address=Js),Hs.length&&(Mc.topics=Hs),Ma&&(Mc.fromBlock=Ma),qs&&(Mc.toBlock=qs),Ws&&(Mc.blockHash=Ws),Mc};let zs=[];if(Ps.address)if(Array.isArray(Ps.address))for(const Xs of Ps.address)zs.push(this._getAddress(Xs));else zs.push(this._getAddress(Ps.address));let Ys;"fromBlock"in Ps&&(Ys=this._getBlockTag(Ps.fromBlock));let Va;return"toBlock"in Ps&&(Va=this._getBlockTag(Ps.toBlock)),zs.filter(Xs=>typeof Xs!="string").length||Ys!=null&&typeof Ys!="string"||Va!=null&&typeof Va!="string"?Promise.all([Promise.all(zs),Ys,Va]).then(Xs=>Zs(Xs[0],Xs[1],Xs[2])):Zs(zs,Ys,Va)}_getTransactionRequest(Ps){const Hs=copyRequest(Ps),Ws=[];if(["to","from"].forEach(Zs=>{if(Hs[Zs]==null)return;const zs=resolveAddress(Hs[Zs],this);isPromise(zs)?Ws.push((async function(){Hs[Zs]=await zs})()):Hs[Zs]=zs}),Hs.blockTag!=null){const Zs=this._getBlockTag(Hs.blockTag);isPromise(Zs)?Ws.push((async function(){Hs.blockTag=await Zs})()):Hs.blockTag=Zs}return Ws.length?(async function(){return await Promise.all(Ws),Hs})():Hs}async getNetwork(){if(this.#o==null){const Zs=(async()=>{try{const zs=await this._detectNetwork();return this.emit("network",zs,null),zs}catch(zs){throw this.#o===Zs&&(this.#o=null),zs}})();return this.#o=Zs,(await Zs).clone()}const Ps=this.#o,[Hs,Ws]=await Promise.all([Ps,this._detectNetwork()]);return Hs.chainId!==Ws.chainId&&(this.#s?(this.emit("network",Ws,Hs),this.#o===Ps&&(this.#o=Promise.resolve(Ws))):assert(!1,`network changed: ${Hs.chainId} => ${Ws.chainId} `,"NETWORK_ERROR",{event:"changed"})),Hs.clone()}async getFeeData(){const Ps=await this.getNetwork(),Hs=async()=>{const{_block:Zs,gasPrice:zs,priorityFee:Ys}=await resolveProperties({_block:this.#y("latest",!1),gasPrice:(async()=>{try{const qs=await this.#c({method:"getGasPrice"});return getBigInt(qs,"%response")}catch{}return null})(),priorityFee:(async()=>{try{const qs=await this.#c({method:"getPriorityFee"});return getBigInt(qs,"%response")}catch{}return null})()});let Va=null,Xs=null;const Ma=this._wrapBlock(Zs,Ps);return Ma&&Ma.baseFeePerGas&&(Xs=Ys??BigInt("1000000000"),Va=Ma.baseFeePerGas*BN_2+Xs),new FeeData(zs,Va,Xs)},Ws=Ps.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(Ws){const Zs=new FetchRequest(Ws.url),zs=await Ws.processFunc(Hs,this,Zs);return new FeeData(zs.gasPrice,zs.maxFeePerGas,zs.maxPriorityFeePerGas)}return await Hs()}async estimateGas(Ps){let Hs=this._getTransactionRequest(Ps);return isPromise(Hs)&&(Hs=await Hs),getBigInt(await this.#c({method:"estimateGas",transaction:Hs}),"%response")}async#u(Ps,Hs,Ws){assert(Ws<MAX_CCIP_REDIRECTS,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},Ps,{blockTag:Hs,enableCcipRead:!0})});const Zs=copyRequest(Ps);try{return hexlify(await this._perform({method:"call",transaction:Zs,blockTag:Hs}))}catch(zs){if(!this.disableCcipRead&&isCallException(zs)&&zs.data&&Ws>=0&&Hs==="latest"&&Zs.to!=null&&dataSlice(zs.data,0,4)==="0x556f1830"){const Ys=zs.data,Va=await resolveAddress(Zs.to,this);let Xs;try{Xs=parseOffchainLookup(dataSlice(zs.data,4))}catch(Js){assert(!1,Js.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:Zs,info:{data:Ys}})}assert(Xs.sender.toLowerCase()===Va.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:Ys,reason:"OffchainLookup",transaction:Zs,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:Xs.errorArgs}});const Ma=await this.ccipReadFetch(Zs,Xs.calldata,Xs.urls);assert(Ma!=null,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:Zs,info:{data:zs.data,errorArgs:Xs.errorArgs}});const qs={to:Va,data:concat([Xs.selector,encodeBytes([Ma,Xs.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:qs});try{const Js=await this.#u(qs,Hs,Ws+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},qs),result:Js}),Js}catch(Js){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},qs),error:Js}),Js}}throw zs}}async#f(Ps){const{value:Hs}=await resolveProperties({network:this.getNetwork(),value:Ps});return Hs}async call(Ps){const{tx:Hs,blockTag:Ws}=await resolveProperties({tx:this._getTransactionRequest(Ps),blockTag:this._getBlockTag(Ps.blockTag)});return await this.#f(this.#u(Hs,Ws,Ps.enableCcipRead?0:-1))}async#h(Ps,Hs,Ws){let Zs=this._getAddress(Hs),zs=this._getBlockTag(Ws);return(typeof Zs!="string"||typeof zs!="string")&&([Zs,zs]=await Promise.all([Zs,zs])),await this.#f(this.#c(Object.assign(Ps,{address:Zs,blockTag:zs})))}async getBalance(Ps,Hs){return getBigInt(await this.#h({method:"getBalance"},Ps,Hs),"%response")}async getTransactionCount(Ps,Hs){return getNumber(await this.#h({method:"getTransactionCount"},Ps,Hs),"%response")}async getCode(Ps,Hs){return hexlify(await this.#h({method:"getCode"},Ps,Hs))}async getStorage(Ps,Hs,Ws){const Zs=getBigInt(Hs,"position");return hexlify(await this.#h({method:"getStorage",position:Zs},Ps,Ws))}async broadcastTransaction(Ps){const{blockNumber:Hs,hash:Ws,network:Zs}=await resolveProperties({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:Ps}),network:this.getNetwork()}),zs=Transaction.from(Ps);if(zs.hash!==Ws)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(zs,Zs).replaceableTransaction(Hs)}async#y(Ps,Hs){if(isHexString(Ps,32))return await this.#c({method:"getBlock",blockHash:Ps,includeTransactions:Hs});let Ws=this._getBlockTag(Ps);return typeof Ws!="string"&&(Ws=await Ws),await this.#c({method:"getBlock",blockTag:Ws,includeTransactions:Hs})}async getBlock(Ps,Hs){const{network:Ws,params:Zs}=await resolveProperties({network:this.getNetwork(),params:this.#y(Ps,!!Hs)});return Zs==null?null:this._wrapBlock(Zs,Ws)}async getTransaction(Ps){const{network:Hs,params:Ws}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getTransaction",hash:Ps})});return Ws==null?null:this._wrapTransactionResponse(Ws,Hs)}async getTransactionReceipt(Ps){const{network:Hs,params:Ws}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getTransactionReceipt",hash:Ps})});if(Ws==null)return null;if(Ws.gasPrice==null&&Ws.effectiveGasPrice==null){const Zs=await this.#c({method:"getTransaction",hash:Ps});if(Zs==null)throw new Error("report this; could not find tx or effectiveGasPrice");Ws.effectiveGasPrice=Zs.gasPrice}return this._wrapTransactionReceipt(Ws,Hs)}async getTransactionResult(Ps){const{result:Hs}=await resolveProperties({network:this.getNetwork(),result:this.#c({method:"getTransactionResult",hash:Ps})});return Hs==null?null:hexlify(Hs)}async getLogs(Ps){let Hs=this._getFilter(Ps);isPromise(Hs)&&(Hs=await Hs);const{network:Ws,params:Zs}=await resolveProperties({network:this.getNetwork(),params:this.#c({method:"getLogs",filter:Hs})});return Zs.map(zs=>this._wrapLog(zs,Ws))}_getProvider(Ps){assert(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(Ps){return await EnsResolver.fromName(this,Ps)}async getAvatar(Ps){const Hs=await this.getResolver(Ps);return Hs?await Hs.getAvatar():null}async resolveName(Ps){const Hs=await this.getResolver(Ps);return Hs?await Hs.getAddress():null}async lookupAddress(Ps){Ps=getAddress(Ps);const Hs=namehash(Ps.substring(2).toLowerCase()+".addr.reverse");try{const Ws=await EnsResolver.getEnsAddress(this),zs=await new Contract(Ws,["function resolver(bytes32) view returns (address)"],this).resolver(Hs);if(zs==null||zs===ZeroAddress)return null;const Va=await new Contract(zs,["function name(bytes32) view returns (string)"],this).name(Hs);return await this.resolveName(Va)!==Ps?null:Va}catch(Ws){if(isError(Ws,"BAD_DATA")&&Ws.value==="0x"||isError(Ws,"CALL_EXCEPTION"))return null;throw Ws}return null}async waitForTransaction(Ps,Hs,Ws){const Zs=Hs??1;return Zs===0?this.getTransactionReceipt(Ps):new Promise(async(zs,Ys)=>{let Va=null;const Xs=(async Ma=>{try{const qs=await this.getTransactionReceipt(Ps);if(qs!=null&&Ma-qs.blockNumber+1>=Zs){zs(qs),Va&&(clearTimeout(Va),Va=null);return}}catch(qs){console.log("EEE",qs)}this.once("block",Xs)});Ws!=null&&(Va=setTimeout(()=>{Va!=null&&(Va=null,this.off("block",Xs),Ys(makeError("timeout","TIMEOUT",{reason:"timeout"})))},Ws)),Xs(await this.getBlockNumber())})}async waitForBlock(Ps){assert(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(Ps){const Hs=this.#l.get(Ps);Hs&&(Hs.timer&&clearTimeout(Hs.timer),this.#l.delete(Ps))}_setTimeout(Ps,Hs){Hs==null&&(Hs=0);const Ws=this.#d++,Zs=()=>{this.#l.delete(Ws),Ps()};if(this.paused)this.#l.set(Ws,{timer:null,func:Zs,time:Hs});else{const zs=setTimeout(Zs,Hs);this.#l.set(Ws,{timer:zs,func:Zs,time:getTime()})}return Ws}_forEachSubscriber(Ps){for(const Hs of this.#e.values())Ps(Hs.subscriber)}_getSubscriber(Ps){switch(Ps.type){case"debug":case"error":case"network":return new UnmanagedSubscriber(Ps.type);case"block":{const Hs=new PollingBlockSubscriber(this);return Hs.pollingInterval=this.pollingInterval,Hs}case"safe":case"finalized":return new PollingBlockTagSubscriber(this,Ps.type);case"event":return new PollingEventSubscriber(this,Ps.filter);case"transaction":return new PollingTransactionSubscriber(this,Ps.hash);case"orphan":return new PollingOrphanSubscriber(this,Ps.filter)}throw new Error(`unsupported event: ${Ps.type}`)}_recoverSubscriber(Ps,Hs){for(const Ws of this.#e.values())if(Ws.subscriber===Ps){Ws.started&&Ws.subscriber.stop(),Ws.subscriber=Hs,Ws.started&&Hs.start(),this.#r!=null&&Hs.pause(this.#r);break}}async#m(Ps,Hs){let Ws=await getSubscription(Ps,this);return Ws.type==="event"&&Hs&&Hs.length>0&&Hs[0].removed===!0&&(Ws=await getSubscription({orphan:"drop-log",log:Hs[0]},this)),this.#e.get(Ws.tag)||null}async#b(Ps){const Hs=await getSubscription(Ps,this),Ws=Hs.tag;let Zs=this.#e.get(Ws);return Zs||(Zs={subscriber:this._getSubscriber(Hs),tag:Ws,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#e.set(Ws,Zs)),Zs}async on(Ps,Hs){const Ws=await this.#b(Ps);return Ws.listeners.push({listener:Hs,once:!1}),Ws.started||(Ws.subscriber.start(),Ws.started=!0,this.#r!=null&&Ws.subscriber.pause(this.#r)),this}async once(Ps,Hs){const Ws=await this.#b(Ps);return Ws.listeners.push({listener:Hs,once:!0}),Ws.started||(Ws.subscriber.start(),Ws.started=!0,this.#r!=null&&Ws.subscriber.pause(this.#r)),this}async emit(Ps,...Hs){const Ws=await this.#m(Ps,Hs);if(!Ws||Ws.listeners.length===0)return!1;const Zs=Ws.listeners.length;return Ws.listeners=Ws.listeners.filter(({listener:zs,once:Ys})=>{const Va=new EventPayload(this,Ys?null:zs,Ps);try{zs.call(this,...Hs,Va)}catch{}return!Ys}),Ws.listeners.length===0&&(Ws.started&&Ws.subscriber.stop(),this.#e.delete(Ws.tag)),Zs>0}async listenerCount(Ps){if(Ps){const Ws=await this.#m(Ps);return Ws?Ws.listeners.length:0}let Hs=0;for(const{listeners:Ws}of this.#e.values())Hs+=Ws.length;return Hs}async listeners(Ps){if(Ps){const Ws=await this.#m(Ps);return Ws?Ws.listeners.map(({listener:Zs})=>Zs):[]}let Hs=[];for(const{listeners:Ws}of this.#e.values())Hs=Hs.concat(Ws.map(({listener:Zs})=>Zs));return Hs}async off(Ps,Hs){const Ws=await this.#m(Ps);if(!Ws)return this;if(Hs){const Zs=Ws.listeners.map(({listener:zs})=>zs).indexOf(Hs);Zs>=0&&Ws.listeners.splice(Zs,1)}return(!Hs||Ws.listeners.length===0)&&(Ws.started&&Ws.subscriber.stop(),this.#e.delete(Ws.tag)),this}async removeAllListeners(Ps){if(Ps){const{tag:Hs,started:Ws,subscriber:Zs}=await this.#b(Ps);Ws&&Zs.stop(),this.#e.delete(Hs)}else for(const[Hs,{started:Ws,subscriber:Zs}]of this.#e)Ws&&Zs.stop(),this.#e.delete(Hs);return this}async addListener(Ps,Hs){return await this.on(Ps,Hs)}async removeListener(Ps,Hs){return this.off(Ps,Hs)}get destroyed(){return this.#n}destroy(){this.removeAllListeners();for(const Ps of this.#l.keys())this._clearTimeout(Ps);this.#n=!0}get paused(){return this.#r!=null}set paused(Ps){!!Ps!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(Ps){if(this.#a=-1,this.#r!=null){if(this.#r==!!Ps)return;assert(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(Hs=>Hs.pause(Ps)),this.#r=!!Ps;for(const Hs of this.#l.values())Hs.timer&&clearTimeout(Hs.timer),Hs.time=getTime()-Hs.time}resume(){if(this.#r!=null){this._forEachSubscriber(Ps=>Ps.resume()),this.#r=null;for(const Ps of this.#l.values()){let Hs=Ps.time;Hs<0&&(Hs=0),Ps.time=getTime(),setTimeout(Ps.func,Hs)}}}}function _parseString(Fs,Ps){try{const Hs=_parseBytes(Fs,Ps);if(Hs)return toUtf8String(Hs)}catch{}return null}function _parseBytes(Fs,Ps){if(Fs==="0x")return null;try{const Hs=getNumber(dataSlice(Fs,Ps,Ps+32)),Ws=getNumber(dataSlice(Fs,Hs,Hs+32));return dataSlice(Fs,Hs+32,Hs+32+Ws)}catch{}return null}function numPad(Fs){const Ps=toBeArray(Fs);if(Ps.length>32)throw new Error("internal; should not happen");const Hs=new Uint8Array(32);return Hs.set(Ps,32-Ps.length),Hs}function bytesPad(Fs){if(Fs.length%32===0)return Fs;const Ps=new Uint8Array(Math.ceil(Fs.length/32)*32);return Ps.set(Fs),Ps}const empty=new Uint8Array([]);function encodeBytes(Fs){const Ps=[];let Hs=0;for(let Ws=0;Ws<Fs.length;Ws++)Ps.push(empty),Hs+=32;for(let Ws=0;Ws<Fs.length;Ws++){const Zs=getBytes(Fs[Ws]);Ps[Ws]=numPad(Hs),Ps.push(numPad(Zs.length)),Ps.push(bytesPad(Zs)),Hs+=32+Math.ceil(Zs.length/32)*32}return concat(Ps)}const zeros="0x0000000000000000000000000000000000000000000000000000000000000000";function parseOffchainLookup(Fs){const Ps={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};assert(dataLength(Fs)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const Hs=dataSlice(Fs,0,32);assert(dataSlice(Hs,0,12)===dataSlice(zeros,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),Ps.sender=dataSlice(Hs,12);try{const Ws=[],Zs=getNumber(dataSlice(Fs,32,64)),zs=getNumber(dataSlice(Fs,Zs,Zs+32)),Ys=dataSlice(Fs,Zs+32);for(let Va=0;Va<zs;Va++){const Xs=_parseString(Ys,Va*32);if(Xs==null)throw new Error("abort");Ws.push(Xs)}Ps.urls=Ws}catch{assert(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const Ws=_parseBytes(Fs,64);if(Ws==null)throw new Error("abort");Ps.calldata=Ws}catch{assert(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}assert(dataSlice(Fs,100,128)===dataSlice(zeros,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),Ps.selector=dataSlice(Fs,96,100);try{const Ws=_parseBytes(Fs,128);if(Ws==null)throw new Error("abort");Ps.extraData=Ws}catch{assert(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return Ps.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map(Ws=>Ps[Ws]),Ps}function checkProvider(Fs,Ps){if(Fs.provider)return Fs.provider;assert(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:Ps})}async function populate(Fs,Ps){let Hs=copyRequest(Ps);if(Hs.to!=null&&(Hs.to=resolveAddress(Hs.to,Fs)),Hs.from!=null){const Ws=Hs.from;Hs.from=Promise.all([Fs.getAddress(),resolveAddress(Ws,Fs)]).then(([Zs,zs])=>(assertArgument(Zs.toLowerCase()===zs.toLowerCase(),"transaction from mismatch","tx.from",zs),Zs))}else Hs.from=Fs.getAddress();return await resolveProperties(Hs)}class AbstractSigner{provider;constructor(Ps){defineProperties(this,{provider:Ps||null})}async getNonce(Ps){return checkProvider(this,"getTransactionCount").getTransactionCount(await this.getAddress(),Ps)}async populateCall(Ps){return await populate(this,Ps)}async populateTransaction(Ps){const Hs=checkProvider(this,"populateTransaction"),Ws=await populate(this,Ps);Ws.nonce==null&&(Ws.nonce=await this.getNonce("pending")),Ws.gasLimit==null&&(Ws.gasLimit=await this.estimateGas(Ws));const Zs=await this.provider.getNetwork();if(Ws.chainId!=null){const Ys=getBigInt(Ws.chainId);assertArgument(Ys===Zs.chainId,"transaction chainId mismatch","tx.chainId",Ps.chainId)}else Ws.chainId=Zs.chainId;const zs=Ws.maxFeePerGas!=null||Ws.maxPriorityFeePerGas!=null;if(Ws.gasPrice!=null&&(Ws.type===2||zs)?assertArgument(!1,"eip-1559 transaction do not support gasPrice","tx",Ps):(Ws.type===0||Ws.type===1)&&zs&&assertArgument(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",Ps),(Ws.type===2||Ws.type==null)&&Ws.maxFeePerGas!=null&&Ws.maxPriorityFeePerGas!=null)Ws.type=2;else if(Ws.type===0||Ws.type===1){const Ys=await Hs.getFeeData();assert(Ys.gasPrice!=null,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),Ws.gasPrice==null&&(Ws.gasPrice=Ys.gasPrice)}else{const Ys=await Hs.getFeeData();if(Ws.type==null)if(Ys.maxFeePerGas!=null&&Ys.maxPriorityFeePerGas!=null)if(Ws.authorizationList&&Ws.authorizationList.length?Ws.type=4:Ws.type=2,Ws.gasPrice!=null){const Va=Ws.gasPrice;delete Ws.gasPrice,Ws.maxFeePerGas=Va,Ws.maxPriorityFeePerGas=Va}else Ws.maxFeePerGas==null&&(Ws.maxFeePerGas=Ys.maxFeePerGas),Ws.maxPriorityFeePerGas==null&&(Ws.maxPriorityFeePerGas=Ys.maxPriorityFeePerGas);else Ys.gasPrice!=null?(assert(!zs,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),Ws.gasPrice==null&&(Ws.gasPrice=Ys.gasPrice),Ws.type=0):assert(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else(Ws.type===2||Ws.type===3||Ws.type===4)&&(Ws.maxFeePerGas==null&&(Ws.maxFeePerGas=Ys.maxFeePerGas),Ws.maxPriorityFeePerGas==null&&(Ws.maxPriorityFeePerGas=Ys.maxPriorityFeePerGas))}return await resolveProperties(Ws)}async populateAuthorization(Ps){const Hs=Object.assign({},Ps);return Hs.chainId==null&&(Hs.chainId=(await checkProvider(this,"getNetwork").getNetwork()).chainId),Hs.nonce==null&&(Hs.nonce=await this.getNonce()),Hs}async estimateGas(Ps){return checkProvider(this,"estimateGas").estimateGas(await this.populateCall(Ps))}async call(Ps){return checkProvider(this,"call").call(await this.populateCall(Ps))}async resolveName(Ps){return await checkProvider(this,"resolveName").resolveName(Ps)}async sendTransaction(Ps){const Hs=checkProvider(this,"sendTransaction"),Ws=await this.populateTransaction(Ps);delete Ws.from;const Zs=Transaction.from(Ws);return await Hs.broadcastTransaction(await this.signTransaction(Zs))}authorize(Ps){assert(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}function copy(Fs){return JSON.parse(JSON.stringify(Fs))}class FilterIdSubscriber{#e;#t;#r;#n;#o;#s;constructor(Ps){this.#e=Ps,this.#t=null,this.#r=this.#i.bind(this),this.#n=!1,this.#o=null,this.#s=!1}_subscribe(Ps){throw new Error("subclasses must override this")}_emitResults(Ps,Hs){throw new Error("subclasses must override this")}_recover(Ps){throw new Error("subclasses must override this")}async#i(Ps){try{this.#t==null&&(this.#t=this._subscribe(this.#e));let Hs=null;try{Hs=await this.#t}catch(zs){if(!isError(zs,"UNSUPPORTED_OPERATION")||zs.operation!=="eth_newFilter")throw zs}if(Hs==null){this.#t=null,this.#e._recoverSubscriber(this,this._recover(this.#e));return}const Ws=await this.#e.getNetwork();if(this.#o||(this.#o=Ws),this.#o.chainId!==Ws.chainId)throw new Error("chaid changed");if(this.#s)return;const Zs=await this.#e.send("eth_getFilterChanges",[Hs]);await this._emitResults(this.#e,Zs)}catch(Hs){console.log("@TODO",Hs)}this.#e.once("block",this.#r)}#a(){const Ps=this.#t;Ps&&(this.#t=null,Ps.then(Hs=>{this.#e.destroyed||this.#e.send("eth_uninstallFilter",[Hs])}))}start(){this.#n||(this.#n=!0,this.#i(-2))}stop(){this.#n&&(this.#n=!1,this.#s=!0,this.#a(),this.#e.off("block",this.#r))}pause(Ps){Ps&&this.#a(),this.#e.off("block",this.#r)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#e;constructor(Ps,Hs){super(Ps),this.#e=copy(Hs)}_recover(Ps){return new PollingEventSubscriber(Ps,this.#e)}async _subscribe(Ps){return await Ps.send("eth_newFilter",[this.#e])}async _emitResults(Ps,Hs){for(const Ws of Hs)Ps.emit(this.#e,Ps._wrapLog(Ws,Ps._network))}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(Ps){return await Ps.send("eth_newPendingTransactionFilter",[])}async _emitResults(Ps,Hs){for(const Ws of Hs)Ps.emit("pending",Ws)}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(Fs){if(Fs==null||Primitive.indexOf(typeof Fs)>=0||typeof Fs.getAddress=="function")return Fs;if(Array.isArray(Fs))return Fs.map(deepCopy);if(typeof Fs=="object")return Object.keys(Fs).reduce((Ps,Hs)=>(Ps[Hs]=Fs[Hs],Ps),{});throw new Error(`should not happen: ${Fs} (${typeof Fs})`)}function stall(Fs){return new Promise(Ps=>{setTimeout(Ps,Fs)})}function getLowerCase(Fs){return Fs&&Fs.toLowerCase()}function isPollable(Fs){return Fs&&typeof Fs.pollingInterval=="number"}const defaultOptions={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class JsonRpcSigner extends AbstractSigner{address;constructor(Ps,Hs){super(Ps),Hs=getAddress(Hs),defineProperties(this,{address:Hs})}connect(Ps){assert(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(Ps){return await this.populateCall(Ps)}async sendUncheckedTransaction(Ps){const Hs=deepCopy(Ps),Ws=[];if(Hs.from){const zs=Hs.from;Ws.push((async()=>{const Ys=await resolveAddress(zs,this.provider);assertArgument(Ys!=null&&Ys.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",Ps),Hs.from=Ys})())}else Hs.from=this.address;if(Hs.gasLimit==null&&Ws.push((async()=>{Hs.gasLimit=await this.provider.estimateGas({...Hs,from:this.address})})()),Hs.to!=null){const zs=Hs.to;Ws.push((async()=>{Hs.to=await resolveAddress(zs,this.provider)})())}Ws.length&&await Promise.all(Ws);const Zs=this.provider.getRpcTransaction(Hs);return this.provider.send("eth_sendTransaction",[Zs])}async sendTransaction(Ps){const Hs=await this.provider.getBlockNumber(),Ws=await this.sendUncheckedTransaction(Ps);return await new Promise((Zs,zs)=>{const Ys=[1e3,100];let Va=0;const Xs=async()=>{try{const Ma=await this.provider.getTransaction(Ws);if(Ma!=null){Zs(Ma.replaceableTransaction(Hs));return}}catch(Ma){if(isError(Ma,"CANCELLED")||isError(Ma,"BAD_DATA")||isError(Ma,"NETWORK_ERROR")||isError(Ma,"UNSUPPORTED_OPERATION")){Ma.info==null&&(Ma.info={}),Ma.info.sendTransactionHash=Ws,zs(Ma);return}if(isError(Ma,"INVALID_ARGUMENT")&&(Va++,Ma.info==null&&(Ma.info={}),Ma.info.sendTransactionHash=Ws,Va>10)){zs(Ma);return}this.provider.emit("error",makeError("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:Ma}))}this.provider._setTimeout(()=>{Xs()},Ys.pop()||4e3)};Xs()})}async signTransaction(Ps){const Hs=deepCopy(Ps);if(Hs.from){const Zs=await resolveAddress(Hs.from,this.provider);assertArgument(Zs!=null&&Zs.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",Ps),Hs.from=Zs}else Hs.from=this.address;const Ws=this.provider.getRpcTransaction(Hs);return await this.provider.send("eth_signTransaction",[Ws])}async signMessage(Ps){const Hs=typeof Ps=="string"?toUtf8Bytes(Ps):Ps;return await this.provider.send("personal_sign",[hexlify(Hs),this.address.toLowerCase()])}async signTypedData(Ps,Hs,Ws){const Zs=deepCopy(Ws),zs=await TypedDataEncoder.resolveNames(Ps,Hs,Zs,async Ys=>{const Va=await resolveAddress(Ys);return assertArgument(Va!=null,"TypedData does not support null address","value",Ys),Va});return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(zs.domain,Hs,zs.value))])}async unlock(Ps){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),Ps,null])}async _legacySignMessage(Ps){const Hs=typeof Ps=="string"?toUtf8Bytes(Ps):Ps;return await this.provider.send("eth_sign",[this.address.toLowerCase(),hexlify(Hs)])}}class JsonRpcApiProvider extends AbstractProvider{#e;#t;#r;#n;#o;#s;#i;#a(){if(this.#n)return;const Ps=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#n=setTimeout(()=>{this.#n=null;const Hs=this.#r;for(this.#r=[];Hs.length;){const Ws=[Hs.shift()];for(;Hs.length&&Ws.length!==this.#e.batchMaxCount;)if(Ws.push(Hs.shift()),JSON.stringify(Ws.map(zs=>zs.payload)).length>this.#e.batchMaxSize){Hs.unshift(Ws.pop());break}(async()=>{const Zs=Ws.length===1?Ws[0].payload:Ws.map(zs=>zs.payload);this.emit("debug",{action:"sendRpcPayload",payload:Zs});try{const zs=await this._send(Zs);this.emit("debug",{action:"receiveRpcResult",result:zs});for(const{resolve:Ys,reject:Va,payload:Xs}of Ws){if(this.destroyed){Va(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Xs.method}));continue}const Ma=zs.filter(qs=>qs.id===Xs.id)[0];if(Ma==null){const qs=makeError("missing response for request","BAD_DATA",{value:zs,info:{payload:Xs}});this.emit("error",qs),Va(qs);continue}if("error"in Ma){Va(this.getRpcError(Xs,Ma));continue}Ys(Ma.result)}}catch(zs){this.emit("debug",{action:"receiveRpcError",error:zs});for(const{reject:Ys}of Ws)Ys(zs)}})()}},Ps)}constructor(Ps,Hs){super(Ps,Hs),this.#t=1,this.#e=Object.assign({},defaultOptions,Hs||{}),this.#r=[],this.#n=null,this.#s=null,this.#i=null;{let Zs=null;const zs=new Promise(Ys=>{Zs=Ys});this.#o={promise:zs,resolve:Zs}}const Ws=this._getOption("staticNetwork");typeof Ws=="boolean"?(assertArgument(!Ws||Ps!=="any","staticNetwork cannot be used on special network 'any'","options",Hs),Ws&&Ps!=null&&(this.#s=Network.from(Ps))):Ws&&(assertArgument(Ps==null||Ws.matches(Ps),"staticNetwork MUST match network object","options",Hs),this.#s=Ws)}_getOption(Ps){return this.#e[Ps]}get _network(){return assert(this.#s,"network is not available yet","NETWORK_ERROR"),this.#s}async _perform(Ps){if(Ps.method==="call"||Ps.method==="estimateGas"){let Ws=Ps.transaction;if(Ws&&Ws.type!=null&&getBigInt(Ws.type)&&Ws.maxFeePerGas==null&&Ws.maxPriorityFeePerGas==null){const Zs=await this.getFeeData();Zs.maxFeePerGas==null&&Zs.maxPriorityFeePerGas==null&&(Ps=Object.assign({},Ps,{transaction:Object.assign({},Ws,{type:void 0})}))}}const Hs=this.getRpcRequest(Ps);return Hs!=null?await this.send(Hs.method,Hs.args):super._perform(Ps)}async _detectNetwork(){const Ps=this._getOption("staticNetwork");if(Ps)if(Ps===!0){if(this.#s)return this.#s}else return Ps;return this.#i?await this.#i:this.ready?(this.#i=(async()=>{try{const Hs=Network.from(getBigInt(await this.send("eth_chainId",[])));return this.#i=null,Hs}catch(Hs){throw this.#i=null,Hs}})(),await this.#i):(this.#i=(async()=>{const Hs={id:this.#t++,method:"eth_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",{action:"sendRpcPayload",payload:Hs});let Ws;try{Ws=(await this._send(Hs))[0],this.#i=null}catch(Zs){throw this.#i=null,this.emit("debug",{action:"receiveRpcError",error:Zs}),Zs}if(this.emit("debug",{action:"receiveRpcResult",result:Ws}),"result"in Ws)return Network.from(getBigInt(Ws.result));throw this.getRpcError(Hs,Ws)})(),await this.#i)}_start(){this.#o==null||this.#o.resolve==null||(this.#o.resolve(),this.#o=null,(async()=>{for(;this.#s==null&&!this.destroyed;)try{this.#s=await this._detectNetwork()}catch(Ps){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",makeError("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:Ps}})),await stall(1e3)}this.#a()})())}async _waitUntilReady(){if(this.#o!=null)return await this.#o.promise}_getSubscriber(Ps){return Ps.type==="pending"?new FilterIdPendingSubscriber(this):Ps.type==="event"?this._getOption("polling")?new PollingEventSubscriber(this,Ps.filter):new FilterIdEventSubscriber(this,Ps.filter):Ps.type==="orphan"&&Ps.filter.orphan==="drop-log"?new UnmanagedSubscriber("orphan"):super._getSubscriber(Ps)}get ready(){return this.#o==null}getRpcTransaction(Ps){const Hs={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(Ws=>{if(Ps[Ws]==null)return;let Zs=Ws;Ws==="gasLimit"&&(Zs="gas"),Hs[Zs]=toQuantity(getBigInt(Ps[Ws],`tx.${Ws}`))}),["from","to","data"].forEach(Ws=>{Ps[Ws]!=null&&(Hs[Ws]=hexlify(Ps[Ws]))}),Ps.accessList&&(Hs.accessList=accessListify(Ps.accessList)),Ps.blobVersionedHashes&&(Hs.blobVersionedHashes=Ps.blobVersionedHashes.map(Ws=>Ws.toLowerCase())),Ps.authorizationList&&(Hs.authorizationList=Ps.authorizationList.map(Ws=>{const Zs=authorizationify(Ws);return{address:Zs.address,nonce:toQuantity(Zs.nonce),chainId:toQuantity(Zs.chainId),yParity:toQuantity(Zs.signature.yParity),r:toQuantity(Zs.signature.r),s:toQuantity(Zs.signature.s)}})),Hs}getRpcRequest(Ps){switch(Ps.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getCode":return{method:"eth_getCode",args:[getLowerCase(Ps.address),Ps.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[getLowerCase(Ps.address),"0x"+Ps.position.toString(16),Ps.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[Ps.signedTransaction]};case"getBlock":if("blockTag"in Ps)return{method:"eth_getBlockByNumber",args:[Ps.blockTag,!!Ps.includeTransactions]};if("blockHash"in Ps)return{method:"eth_getBlockByHash",args:[Ps.blockHash,!!Ps.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[Ps.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[Ps.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(Ps.transaction),Ps.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(Ps.transaction)]};case"getLogs":return Ps.filter&&Ps.filter.address!=null&&(Array.isArray(Ps.filter.address)?Ps.filter.address=Ps.filter.address.map(getLowerCase):Ps.filter.address=getLowerCase(Ps.filter.address)),{method:"eth_getLogs",args:[Ps.filter]}}return null}getRpcError(Ps,Hs){const{method:Ws}=Ps,{error:Zs}=Hs;if(Ws==="eth_estimateGas"&&Zs.message){const Va=Zs.message;if(!Va.match(/revert/i)&&Va.match(/insufficient funds/i))return makeError("insufficient funds","INSUFFICIENT_FUNDS",{transaction:Ps.params[0],info:{payload:Ps,error:Zs}});if(Va.match(/nonce/i)&&Va.match(/too low/i))return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:Ps.params[0],info:{payload:Ps,error:Zs}})}if(Ws==="eth_call"||Ws==="eth_estimateGas"){const Va=spelunkData(Zs),Xs=AbiCoder.getBuiltinCallException(Ws==="eth_call"?"call":"estimateGas",Ps.params[0],Va?Va.data:null);return Xs.info={error:Zs,payload:Ps},Xs}const zs=JSON.stringify(spelunkMessage(Zs));if(typeof Zs.message=="string"&&Zs.message.match(/user denied|ethers-user-denied/i))return makeError("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[Ws]||"unknown",reason:"rejected",info:{payload:Ps,error:Zs}});if(Ws==="eth_sendRawTransaction"||Ws==="eth_sendTransaction"){const Va=Ps.params[0];if(zs.match(/insufficient funds|base fee exceeds gas limit/i))return makeError("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:Va,info:{error:Zs}});if(zs.match(/nonce/i)&&zs.match(/too low/i))return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:Va,info:{error:Zs}});if(zs.match(/replacement transaction/i)&&zs.match(/underpriced/i))return makeError("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:Va,info:{error:Zs}});if(zs.match(/only replay-protected/i))return makeError("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:Ws,info:{transaction:Va,info:{error:Zs}}})}let Ys=!!zs.match(/the method .* does not exist/i);return Ys||Zs&&Zs.details&&Zs.details.startsWith("Unauthorized method:")&&(Ys=!0),Ys?makeError("unsupported operation","UNSUPPORTED_OPERATION",{operation:Ps.method,info:{error:Zs,payload:Ps}}):makeError("could not coalesce error","UNKNOWN_ERROR",{error:Zs,payload:Ps})}send(Ps,Hs){if(this.destroyed)return Promise.reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Ps}));const Ws=this.#t++,Zs=new Promise((zs,Ys)=>{this.#r.push({resolve:zs,reject:Ys,payload:{method:Ps,params:Hs,id:Ws,jsonrpc:"2.0"}})});return this.#a(),Zs}async getSigner(Ps){Ps==null&&(Ps=0);const Hs=this.send("eth_accounts",[]);if(typeof Ps=="number"){const Zs=await Hs;if(Ps>=Zs.length)throw new Error("no such account");return new JsonRpcSigner(this,Zs[Ps])}const{accounts:Ws}=await resolveProperties({network:this.getNetwork(),accounts:Hs});Ps=getAddress(Ps);for(const Zs of Ws)if(getAddress(Zs)===Ps)return new JsonRpcSigner(this,Ps);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map(Hs=>new JsonRpcSigner(this,Hs))}destroy(){this.#n&&(clearTimeout(this.#n),this.#n=null);for(const{payload:Ps,reject:Hs}of this.#r)Hs(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:Ps.method}));this.#r=[],super.destroy()}}class JsonRpcApiPollingProvider extends JsonRpcApiProvider{#e;constructor(Ps,Hs){super(Ps,Hs);let Ws=this._getOption("pollingInterval");Ws==null&&(Ws=defaultOptions.pollingInterval),this.#e=Ws}_getSubscriber(Ps){const Hs=super._getSubscriber(Ps);return isPollable(Hs)&&(Hs.pollingInterval=this.#e),Hs}get pollingInterval(){return this.#e}set pollingInterval(Ps){if(!Number.isInteger(Ps)||Ps<0)throw new Error("invalid interval");this.#e=Ps,this._forEachSubscriber(Hs=>{isPollable(Hs)&&(Hs.pollingInterval=this.#e)})}}function spelunkData(Fs){if(Fs==null)return null;if(typeof Fs.message=="string"&&Fs.message.match(/revert/i)&&isHexString(Fs.data))return{message:Fs.message,data:Fs.data};if(typeof Fs=="object"){for(const Ps in Fs){const Hs=spelunkData(Fs[Ps]);if(Hs)return Hs}return null}if(typeof Fs=="string")try{return spelunkData(JSON.parse(Fs))}catch{}return null}function _spelunkMessage(Fs,Ps){if(Fs!=null){if(typeof Fs.message=="string"&&Ps.push(Fs.message),typeof Fs=="object")for(const Hs in Fs)_spelunkMessage(Fs[Hs],Ps);if(typeof Fs=="string")try{return _spelunkMessage(JSON.parse(Fs),Ps)}catch{}}}function spelunkMessage(Fs){const Ps=[];return _spelunkMessage(Fs,Ps),Ps}class BrowserProvider extends JsonRpcApiPollingProvider{#e;#t;constructor(Ps,Hs,Ws){const Zs=Object.assign({},Ws??{},{batchMaxCount:1});assertArgument(Ps&&Ps.request,"invalid EIP-1193 provider","ethereum",Ps),super(Hs,Zs),this.#t=null,Ws&&Ws.providerInfo&&(this.#t=Ws.providerInfo),this.#e=async(zs,Ys)=>{const Va={method:zs,params:Ys};this.emit("debug",{action:"sendEip1193Request",payload:Va});try{const Xs=await Ps.request(Va);return this.emit("debug",{action:"receiveEip1193Result",result:Xs}),Xs}catch(Xs){const Ma=new Error(Xs.message);throw Ma.code=Xs.code,Ma.data=Xs.data,Ma.payload=Va,this.emit("debug",{action:"receiveEip1193Error",error:Ma}),Ma}}}get providerInfo(){return this.#t}async send(Ps,Hs){return await this._start(),await super.send(Ps,Hs)}async _send(Ps){assertArgument(!Array.isArray(Ps),"EIP-1193 does not support batch request","payload",Ps);try{const Hs=await this.#e(Ps.method,Ps.params||[]);return[{id:Ps.id,result:Hs}]}catch(Hs){return[{id:Ps.id,error:{code:Hs.code,data:Hs.data,message:Hs.message}}]}}getRpcError(Ps,Hs){switch(Hs=JSON.parse(JSON.stringify(Hs)),Hs.error.code||-1){case 4001:Hs.error.message=`ethers-user-denied: ${Hs.error.message}`;break;case 4200:Hs.error.message=`ethers-unsupported: ${Hs.error.message}`;break}return super.getRpcError(Ps,Hs)}async hasSigner(Ps){Ps==null&&(Ps=0);const Hs=await this.send("eth_accounts",[]);return typeof Ps=="number"?Hs.length>Ps:(Ps=Ps.toLowerCase(),Hs.filter(Ws=>Ws.toLowerCase()===Ps).length!==0)}async getSigner(Ps){if(Ps==null&&(Ps=0),!await this.hasSigner(Ps))try{await this.#e("eth_requestAccounts",[])}catch(Hs){const Ws=Hs.payload;throw this.getRpcError(Ws,{id:Ws.id,error:Hs})}return await super.getSigner(Ps)}static async discover(Ps){if(Ps==null&&(Ps={}),Ps.provider)return new BrowserProvider(Ps.provider);const Hs=Ps.window?Ps.window:typeof window<"u"?window:null;if(Hs==null)return null;const Ws=Ps.anyProvider;if(Ws&&Hs.ethereum)return new BrowserProvider(Hs.ethereum);if(!("addEventListener"in Hs&&"dispatchEvent"in Hs&&"removeEventListener"in Hs))return null;const Zs=Ps.timeout?Ps.timeout:300;return Zs===0?null:await new Promise((zs,Ys)=>{let Va=[];const Xs=Js=>{Va.push(Js.detail),Ws&&Ma()},Ma=()=>{if(clearTimeout(qs),Va.length)if(Ps&&Ps.filter){const Js=Ps.filter(Va.map(Mc=>Object.assign({},Mc.info)));if(Js==null)zs(null);else if(Js instanceof BrowserProvider)zs(Js);else{let Mc=null;if(Js.uuid&&(Mc=Va.filter(Vc=>Js.uuid===Vc.info.uuid)[0]),Mc){const{provider:ol,info:Vc}=Mc;zs(new BrowserProvider(ol,void 0,{providerInfo:Vc}))}else Ys(makeError("filter returned unknown info","UNSUPPORTED_OPERATION",{value:Js}))}}else{const{provider:Js,info:Mc}=Va[0];zs(new BrowserProvider(Js,void 0,{providerInfo:Mc}))}else zs(null);Hs.removeEventListener("eip6963:announceProvider",Xs)},qs=setTimeout(()=>{Ma()},Zs);Hs.addEventListener("eip6963:announceProvider",Xs),Hs.dispatchEvent(new Event("eip6963:requestProvider"))})}}function defineChain(Fs){return{formatters:void 0,fees:void 0,serializers:void 0,...Fs}}defineChain({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),defineChain({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"}),defineChain({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"}),defineChain({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),defineChain({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0}),defineChain({id:"00000008819873e925422c1ff0f99f7c",caipNetworkId:"bip122:00000008819873e925422c1ff0f99f7c",chainNamespace:"bip122",name:"Bitcoin Signet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const hederaNamespace="hedera",HederaChainDefinition={Native:{Mainnet:defineChain({id:"mainnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:mainnet",name:"Hedera Mainnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/mainnet"}},testnet:!1}),Testnet:defineChain({id:"testnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:testnet",name:"Hedera Testnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})},EVM:{Mainnet:defineChain({id:295,name:"Hedera Mainnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:295",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!1}),Testnet:defineChain({id:296,name:"Hedera Testnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:296",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})}};function createNamespaces(Fs){return Fs.reduce((Ps,Hs)=>{const{id:Ws,chainNamespace:Zs,rpcUrls:zs}=Hs,Ys=zs.default.http[0],Va=Zs=="hedera"?Object.values(HederaJsonRpcMethod):WcHelpersUtil.getMethodsByChainNamespace(Zs);Ps[Zs]||(Ps[Zs]={methods:Va,events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}});const Xs=`${Zs}:${Ws}`,Ma=Ps[Zs];return Ma.chains.push(Xs),Ma?.rpcMap&&Ys&&(Ma.rpcMap[Ws]=Ys),Ps},{})}function getChainsFromApprovedSession(Fs){return Fs.map(Ps=>`${Ps.split(":")[0]}:${Ps.split(":")[1]}`)}function getChainId(Fs){return Fs.includes(":")?Fs.split(":")[1]:Fs}function mergeRequiredOptionalNamespaces(Fs={},Ps={}){const Hs=xe(Fs),Ws=xe(Ps);return merge(Hs,Ws)}function merge(Fs,Ps){var Hs,Ws,Zs;const zs=Object.assign({},Fs);for(const[Ys,Va]of Object.entries(Ps))zs[Ys]?zs[Ys]=Object.assign(Object.assign(Object.assign({},zs[Ys]),Va),{chains:ut$3(Va.chains,(Hs=zs[Ys])===null||Hs===void 0?void 0:Hs.chains),methods:ut$3(Va.methods||[],((Ws=zs[Ys])===null||Ws===void 0?void 0:Ws.methods)||[]),events:ut$3(Va.events||[],((Zs=zs[Ys])===null||Zs===void 0?void 0:Zs.events)||[])}):zs[Ys]=Va;return zs}const RPC_URL="https://rpc.walletconnect.org/v1/",BUNDLER_URL=`${RPC_URL}bundler`;var Eip155JsonRpcMethod;(function(Fs){Fs.PersonalSign="personal_sign",Fs.Sign="eth_sign",Fs.SignTransaction="eth_signTransaction",Fs.SignTypedData="eth_signTypedData",Fs.SignTypedDataV3="eth_signTypedData_v3",Fs.SignTypedDataV4="eth_signTypedData_v4",Fs.SendRawTransaction="eth_sendRawTransaction",Fs.SendTransaction="eth_sendTransaction"})(Eip155JsonRpcMethod||(Eip155JsonRpcMethod={}));const logger=createLogger("AccountUtils");async function getAccountBalance(Fs,Ps){const Hs=Fs===r$y.TESTNET?a$u.forTestnet():a$u.forMainnet();let Ws;try{Ws=y$f.fromString(Ps)}catch{if(Ps.startsWith("0x"))try{Ws=y$f.fromEvmAddress(0,0,Ps),Ws.num.isZero()&&Ws.evmAddress!=null&&await Ws.populateAccountNum(Hs)}catch{return logger.debug("No Hedera account found for EVM address:",Ps),null}else return logger.debug("Invalid address format:",Ps),null}try{return await new e$x().setAccountId(Ws).execute(Hs)}catch(Zs){return logger.debug("Failed to get account balance:",Zs),null}}class HederaConnector{constructor({provider:Ps,caipNetworks:Hs,namespace:Ws}){this.id=ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT,this.name=PresetsUtil.ConnectorNamesMap[ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=PresetsUtil.ConnectorImageIds[ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=Hs,this.provider=Ps,this.chain=Ws}get chains(){return this.caipNetworks}async connectWalletConnect(){const Hs={optionalNamespaces:createNamespaces(this.caipNetworks)};return await this.provider.connect(Hs),{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){return!1}}class HederaAdapter extends AdapterBlueprint{constructor(Ps){var Hs,Ws;if(Ps.namespace!==hederaNamespace&&Ps.namespace!=="eip155")throw new Error('Namespace must be "hedera" or "eip155"');if(Ps.namespace=="eip155"){if(!((Hs=Ps.networks)===null||Hs===void 0)&&Hs.some(Zs=>Zs.chainNamespace!="eip155"))throw new Error("Invalid networks for eip155 namespace")}else if(!((Ws=Ps.networks)===null||Ws===void 0)&&Ws.some(Zs=>Zs.chainNamespace!=hederaNamespace))throw new Error("Invalid networks for hedera namespace");super(Object.assign({},Ps)),this.logger=createLogger("HederaAdapter"),this.getCaipNetworks=Zs=>{const zs=Zs||this.namespace;return zs==="eip155"?[HederaChainDefinition.EVM.Mainnet,HederaChainDefinition.EVM.Testnet]:zs===hederaNamespace?[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet]:[HederaChainDefinition.EVM.Mainnet,HederaChainDefinition.EVM.Testnet,HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet]}}async setUniversalProvider(Ps){this.addConnector(new HederaConnector({provider:Ps,caipNetworks:this.getCaipNetworks()||[],namespace:this.namespace}))}async connect(Ps){this.logger.debug("connect called with params:",Ps);const Hs=this.getWalletConnectConnector();return Hs&&"connectWalletConnect"in Hs?(this.logger.debug("Calling HederaConnector.connectWalletConnect"),await Hs.connectWalletConnect()):this.logger.warn("HederaConnector not found or connectWalletConnect method missing"),Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(Ps.chainId),provider:this.provider,address:""})}async disconnect(Ps){try{await this.getWalletConnectConnector().disconnect()}catch(Hs){this.logger.warn("disconnect - error",Hs)}return{connections:[]}}async getAccounts({namespace:Ps}){var Hs,Ws,Zs,zs;const Ys=this.provider,Va=((zs=(Zs=(Ws=(Hs=Ys?.session)===null||Hs===void 0?void 0:Hs.namespaces)===null||Ws===void 0?void 0:Ws[Ps])===null||Zs===void 0?void 0:Zs.accounts)===null||zs===void 0?void 0:zs.map(Xs=>{const[,,Ma]=Xs.split(":");return Ma}).filter((Xs,Ma,qs)=>qs.indexOf(Xs)===Ma))||[];return Promise.resolve({accounts:Va.map(Xs=>CoreHelperUtil.createAccount(Ps,Xs,"eoa"))})}async syncConnectors(){return Promise.resolve()}async syncConnections(Ps){return Promise.resolve()}async getBalance(Ps){const{address:Hs,caipNetwork:Ws}=Ps;if(!Ws)return Promise.resolve({balance:"0",decimals:0,symbol:""});const Zs=await getAccountBalance(Ws.testnet?r$y.TESTNET:r$y.MAINNET,Hs);return Promise.resolve({balance:Zs?formatUnits(Zs.hbars.toTinybars().toString(),8).toString():"0",decimals:Ws.nativeCurrency.decimals,symbol:Ws.nativeCurrency.symbol})}async signMessage(Ps){const{provider:Hs,message:Ws,address:Zs}=Ps;if(!Hs)throw new Error("Provider is undefined");const zs=Hs;let Ys="";return this.namespace===hederaNamespace?Ys=(await zs.hedera_signMessage({signerAccountId:Zs,message:Ws})).signatureMap:Ys=await zs.eth_signMessage(Ws,Zs),{signature:Ys}}async estimateGas(Ps){const{provider:Hs,caipNetwork:Ws,address:Zs}=Ps;if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");if(!Hs)throw new Error("Provider is undefined");return{gas:await Hs.eth_estimateGas({data:Ps.data,to:Ps.to,address:Zs},Zs,Number(Ws?.id))}}async sendTransaction(Ps){var Hs;if(!Ps.provider)throw new Error("Provider is undefined");const Ws=Ps.provider;if(this.namespace=="eip155")return{hash:await Ws.eth_sendTransaction({value:Ps.value,to:Ps.to,data:Ps.data,gas:Ps.gas,gasPrice:Ps.gasPrice,address:Ps.address},Ps.address,Number((Hs=Ps.caipNetwork)===null||Hs===void 0?void 0:Hs.id))};throw new Error("Namespace is not eip155")}async writeContract(Ps){if(!Ps.provider)throw new Error("Provider is undefined");if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const{provider:Hs,caipNetwork:Ws,caipAddress:Zs,abi:zs,tokenAddress:Ys,method:Va,args:Xs}=Ps,Ma=new BrowserProvider(Hs,Number(Ws?.id)),qs=new JsonRpcSigner(Ma,Zs),Js=new Contract(Ys,zs,qs);if(!Js||!Va)throw new Error("Contract method is undefined");const Mc=Js[Va];if(Mc)return{hash:await Mc(...Xs)};throw new Error("Contract method is undefined")}async getEnsAddress(Ps){if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const{name:Hs,caipNetwork:Ws}=Ps;return Ws&&isReownName(Hs)?{address:await WcHelpersUtil.resolveReownName(Hs)||!1}:{address:!1}}parseUnits(Ps){return parseUnits$1(Ps.value,Ps.decimals)}formatUnits(Ps){return formatUnits(Ps.value,Ps.decimals)}async getCapabilities(Ps){var Hs,Ws;if(this.namespace!=="eip155")throw new Error("Namespace is not eip155");const Zs=this.provider;if(!Zs)throw new Error("Provider is undefined");const zs=(Ws=(Hs=Zs.session)===null||Hs===void 0?void 0:Hs.sessionProperties)===null||Ws===void 0?void 0:Ws.capabilities;if(zs)try{const Va=JSON.parse(zs)[Ps];if(Va)return Va}catch{throw new Error("Error parsing wallet capabilities")}return await Zs.request({method:"wallet_getCapabilities",params:[Ps]})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(Ps){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Ps.chainId,provider:this.provider,address:""})}async switchNetwork(Ps){const{caipNetwork:Hs}=Ps;this.getWalletConnectConnector().provider.setDefaultChain(Hs.caipNetworkId)}getWalletConnectConnector(){const Ps=this.connectors.find(Hs=>Hs.type=="WALLET_CONNECT");if(!Ps)throw new Error("WalletConnectConnector not found");return Ps}getWalletConnectProvider(){const Ps=this.connectors.find(Ws=>Ws.type==="WALLET_CONNECT");return Ps?.provider}async walletGetAssets(Ps){return Promise.resolve({})}}class HIP820Provider{constructor(Ps){this.namespace=Ps.namespace,this.chainId=this.getDefaultChain(),this.events=Ps.events,this.client=Ps.client}get httpProviders(){return{}}updateNamespace(Ps){this.namespace=Object.assign(this.namespace,Ps)}request(Ps){return this.getSigner(Ps.topic).request({method:Ps.request.method,params:Ps.request.params})}async signTransaction(Ps,Hs){return this.getSigner(Hs).signTransaction(Ps)}requestAccounts(){const Ps=this.namespace.accounts;return Ps?Array.from(new Set(Ps.filter(Hs=>Hs.split(":")[1]===this.chainId.toString()).map(Hs=>Hs.split(":")[2]))):[]}setDefaultChain(Ps){this.chainId=Ps,this.namespace.defaultChain=Ps}getDefaultChain(){return this.chainId?this.chainId:this.namespace.defaultChain?this.namespace.defaultChain:(this.namespace.chains[0]||"hedera:mainnet").split(":")[1]}getSigner(Ps){return this.getSigners(Ps)[0]}getSigners(Ps){var Hs;const Ws=(Hs=this.namespace.accounts)===null||Hs===void 0?void 0:Hs.map(Zs=>{const[zs,Ys,Va]=Zs.split(":");return{ledgerId:CAIPChainIdToLedgerId(`${zs}:${Ys}`),accountId:y$f.fromString(Va)}});if(!Ws)throw new Error("Accounts not found");return Ws.map(({accountId:Zs,ledgerId:zs})=>new DAppSigner(Zs,this.client,Ps,zs))}}class EIP155Provider{constructor({client:Ps,events:Hs,namespace:Ws}){this.name="eip155",this.logger=createLogger("EIP155Provider"),this.namespace=Ws,this.events=Hs,this.client=Ps,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(Ps){switch(Ps.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.switchChain(Ps);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCallsStatus":return await this.getCallStatus(Ps)}return this.namespace.methods.includes(Ps.request.method)?await this.client.request(Ps):this.getHttpProvider().request(Ps.request)}updateNamespace(Ps){this.namespace=Object.assign(this.namespace,Ps)}setDefaultChain(Ps,Hs){this.httpProviders[Ps]||this.setHttpProvider(parseInt(Ps),Hs),this.chainId=parseInt(Ps),this.events.emit("default_chain_changed",`${this.name}:${Ps}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){return this.chainId?this.chainId.toString():this.namespace.defaultChain?this.namespace.defaultChain:(this.namespace.chains[0]||"eip155:295").split(":")[1]}createHttpProvider(Ps,Hs){if(!Ps)return;const{Testnet:Ws,Mainnet:Zs}=HederaChainDefinition.EVM,zs=[Zs,Ws].find(Xs=>Xs.id==Ps),Ys=zs?.rpcUrls.default.http[0]||Hs;if(!Ys)throw new Error(`No RPC url provided for chainId: ${Ps}`);return new o$B(new f$o(Ys,!1))}setHttpProvider(Ps,Hs){const Ws=this.createHttpProvider(Ps,Hs);Ws&&(this.httpProviders[Ps]=Ws)}createHttpProviders(){const Ps={};return this.namespace.chains.forEach(Hs=>{var Ws;const Zs=parseInt(getChainId(Hs));Ps[Zs]=this.createHttpProvider(Zs,(Ws=this.namespace.rpcMap)===null||Ws===void 0?void 0:Ws[Hs])}),Ps}getAccounts(){const Ps=this.namespace.accounts;return Ps?Array.from(new Set(Ps.filter(Hs=>Hs.split(":")[1]===this.chainId.toString()).map(Hs=>Hs.split(":")[2]))):[]}getHttpProvider(){const Ps=this.chainId,Hs=this.httpProviders[Ps];if(typeof Hs>"u")throw new Error(`JSON-RPC provider for ${Ps} not found`);return Hs}async switchChain(Ps){var Hs,Ws;let Zs=Ps.request.params?(Hs=Ps.request.params[0])===null||Hs===void 0?void 0:Hs.chainId:"0x0";Zs=Zs.startsWith("0x")?Zs:`0x${Zs}`;const zs=parseInt(Zs,16);if(this.isChainApproved(zs))this.setDefaultChain(`${zs}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:Ps.topic,request:{method:Ps.request.method,params:[{chainId:Zs}]},chainId:(Ws=this.namespace.chains)===null||Ws===void 0?void 0:Ws[0]}),this.setDefaultChain(`${zs}`);else throw new Error(`Failed to switch to chain 'eip155:${zs}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(Ps){return this.namespace.chains.includes(`${this.name}:${Ps}`)}async getCallStatus(Ps){var Hs,Ws;const Zs=this.client.session.get(Ps.topic),zs=(Hs=Zs.sessionProperties)===null||Hs===void 0?void 0:Hs.bundler_name;if(zs){const Va=this.getBundlerUrl(Ps.chainId,zs);try{return await this.getUserOperationReceipt(Va,Ps)}catch(Xs){this.logger.warn("Failed to fetch call status from bundler",Xs,Va)}}const Ys=(Ws=Zs.sessionProperties)===null||Ws===void 0?void 0:Ws.bundler_url;if(Ys)try{return await this.getUserOperationReceipt(Ys,Ps)}catch(Va){this.logger.warn("Failed to fetch call status from custom bundler",Va,Ys)}if(this.namespace.methods.includes(Ps.request.method))return await this.client.request(Ps);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(Ps,Hs){var Ws,Zs;const zs=new URL(Ps),Ys=await fetch(zs,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formatJsonRpcRequest("eth_getUserOperationReceipt",[(Zs=(Ws=Hs.request)===null||Ws===void 0?void 0:Ws.params)===null||Zs===void 0?void 0:Zs[0]]))});if(!Ys.ok)throw new Error(`Failed to fetch user operation receipt - ${Ys.status}`);return await Ys.json()}getBundlerUrl(Ps,Hs){return`${BUNDLER_URL}?projectId=${this.client.core.projectId}&chainId=${Ps}&bundler=${Hs}`}}class HederaProvider extends N$4{constructor(Ps){super(Ps),this.hederaLogger=createLogger("HederaProvider")}static async init(Ps){var Hs,Ws;const Zs=new HederaProvider(Ps);return await Zs.initialize(),Zs.namespaces=Object.assign(Object.assign({},((Hs=Zs.providerOpts)===null||Hs===void 0?void 0:Hs.optionalNamespaces)||{}),((Ws=Zs.providerOpts)===null||Ws===void 0?void 0:Ws.requiredNamespaces)||{}),Zs.session&&Zs.initProviders(),Zs}emit(Ps,Hs){this.events.emit(Ps,Hs)}getAccountAddresses(){if(!this.session)throw new Error("Not initialized. Please call connect()");return Object.values(this.session.namespaces).flatMap(Ps=>{var Hs;return(Hs=Ps.accounts.map(Ws=>Ws.split(":")[2]))!==null&&Hs!==void 0?Hs:[]})}async request(Ps,Hs,Ws){var Zs,zs,Ys,Va,Xs;if(!this.session||!this.namespaces)throw new Error("Please call connect() before request()");let Ma=Hs;if(Object.values(HederaJsonRpcMethod).includes(Ps.method)){if(!this.nativeProvider)throw new Error("nativeProvider not initialized. Please call connect()");return Ma=Ma??((Zs=this.namespaces.hedera)===null||Zs===void 0?void 0:Zs.chains[0]),(zs=this.nativeProvider)===null||zs===void 0?void 0:zs.request({request:Object.assign({},Ps),chainId:Ma,topic:this.session.topic,expiry:Ws})}else{if(!this.eip155Provider)throw new Error("eip155Provider not initialized");return Ma=Ma??((Va=(Ys=this.namespaces)===null||Ys===void 0?void 0:Ys.eip155)===null||Va===void 0?void 0:Va.chains[0]),(Xs=this.eip155Provider)===null||Xs===void 0?void 0:Xs.request({request:Object.assign({},Ps),chainId:Ma,topic:this.session.topic,expiry:Ws})}}async hedera_getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async hedera_executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async hedera_signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async hedera_signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async hedera_signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async hedera_signTransaction(Ps){var Hs,Ws,Zs;if(!this.session)throw new Error("Session not initialized. Please call connect()");if(!this.nativeProvider)throw new Error("nativeProvider not initialized. Please call connect()");if(!(Ps?.transactionBody instanceof L$a))throw new Error("Transaction sent in incorrect format. Ensure transaction body is a Transaction object.");const zs=(Ws=(Hs=Ps?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Ws===void 0?void 0:Ws.pop();if(!((Zs=this.nativeProvider)===null||Zs===void 0?void 0:Zs.requestAccounts().includes(zs??"")))throw new Error(`Signer not found for account ${zs}`);return await this.nativeProvider.signTransaction(Ps.transactionBody,this.session.topic)}async eth_signMessage(Ps,Hs){const Ws=isHexString(Ps)?Ps:hexlify(toUtf8Bytes(Ps));return await this.request({method:"personal_sign",params:[Ws,Hs]})}async eth_estimateGas(Ps,Hs,Ws){if(!Hs)throw new Error("estimateGas - address is undefined");if(Ps.chainNamespace!=="eip155")throw new Error("estimateGas - chainNamespace is not eip155");const Zs={from:Ps.address,to:Ps.to,data:Ps.data,type:0},zs=new BrowserProvider(this,Ws);return await new JsonRpcSigner(zs,Hs).estimateGas(Zs)}async eth_sendTransaction(Ps,Hs,Ws){if(!Hs)throw new Error("sendTransaction - address is undefined");if(Ps.chainNamespace!=="eip155")throw new Error("sendTransaction - chainNamespace is not eip155");const Zs={to:Ps.to,value:Ps.value,gasLimit:Ps.gas,gasPrice:Ps.gasPrice,data:Ps.data,type:0},zs=new BrowserProvider(this,Ws),Xs=await(await new JsonRpcSigner(zs,Hs).sendTransaction(Zs)).wait();return Xs?.hash||null}async eth_writeContract(Ps,Hs,Ws){if(!Hs)throw new Error("writeContract - address is undefined");const Zs=new BrowserProvider(this,Ws),zs=new JsonRpcSigner(Zs,Hs),Ys=new Contract(Ps.tokenAddress,Ps.abi,zs);if(!Ys||!Ps.method)throw new Error("Contract method is undefined");const Va=Ys[Ps.method];if(Va)return await Va(...Ps.args);throw new Error("Contract method is undefined")}async eth_blockNumber(){return this.request({method:"eth_blockNumber",params:[]})}async eth_call(Ps,Hs="latest"){return this.request({method:"eth_call",params:[Ps,Hs]})}async eth_feeHistory(Ps,Hs,Ws){return this.request({method:"eth_feeHistory",params:[toQuantity(Ps),Hs,Ws]})}async eth_gasPrice(){return this.request({method:"eth_gasPrice",params:[]})}async eth_getBlockByHash(Ps,Hs=!1){return this.request({method:"eth_getBlockByHash",params:[Ps,Hs]})}async eth_getBlockByNumber(Ps,Hs=!1){return this.request({method:"eth_getBlockByNumber",params:[Ps,Hs]})}async eth_getBlockTransactionCountByHash(Ps){return this.request({method:"eth_getBlockTransactionCountByHash",params:[Ps]})}async eth_getBlockTransactionCountByNumber(Ps){return this.request({method:"eth_getBlockTransactionCountByNumber",params:[Ps]})}async eth_getCode(Ps,Hs="latest"){return this.request({method:"eth_getCode",params:[Ps,Hs]})}async eth_getFilterLogs(Ps){return this.request({method:"eth_getFilterLogs",params:[Ps]})}async eth_getFilterChanges(Ps){return this.request({method:"eth_getFilterChanges",params:[Ps]})}async eth_getLogs(Ps){return this.request({method:"eth_getLogs",params:[Ps]})}async eth_getStorageAt(Ps,Hs,Ws="latest"){return this.request({method:"eth_getStorageAt",params:[Ps,Hs,Ws]})}async eth_getTransactionByBlockHashAndIndex(Ps,Hs){return await this.request({method:"eth_getTransactionByBlockHashAndIndex",params:[Ps,Hs]})}async eth_getTransactionByBlockNumberAndIndex(Ps,Hs){return this.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[Ps,Hs]})}async eth_getTransactionByHash(Ps){return this.request({method:"eth_getTransactionByHash",params:[Ps]})}async eth_getTransactionCount(Ps,Hs="latest"){return this.request({method:"eth_getTransactionCount",params:[Ps,Hs]})}async eth_getTransactionReceipt(Ps){return this.request({method:"eth_getTransactionReceipt",params:[Ps]})}async eth_hashrate(){return this.request({method:"eth_hashrate",params:[]})}async eth_maxPriorityFeePerGas(){return this.request({method:"eth_maxPriorityFeePerGas",params:[]})}async eth_mining(){return this.request({method:"eth_mining",params:[]})}async eth_newBlockFilter(){return this.request({method:"eth_newBlockFilter",params:[]})}async eth_newFilter(Ps){return this.request({method:"eth_newFilter",params:[Ps]})}async eth_submitWork(Ps){return this.request({method:"eth_submitWork",params:Ps})}async eth_syncing(){return this.request({method:"eth_syncing",params:[]})}async eth_uninstallFilter(Ps){return this.request({method:"eth_uninstallFilter",params:[Ps]})}async net_listening(){return this.request({method:"net_listening",params:[]})}async net_version(){return this.request({method:"net_version",params:[]})}async web3_clientVersion(){return this.request({method:"web3_clientVersion",params:[]})}async eth_chainId(){return this.request({method:"eth_chainId",params:[]})}async connect(Ps){this.hederaLogger.debug("connect called with params:",Ps),Ps&&(Ps.requiredNamespaces&&(this.hederaLogger.debug("Setting requiredNamespaces:",Ps.requiredNamespaces),this.requiredNamespaces=Ps.requiredNamespaces),Ps.optionalNamespaces&&(this.hederaLogger.debug("Setting optionalNamespaces:",Ps.requiredNamespaces),this.optionalNamespaces=Ps.optionalNamespaces),Ps.namespaces&&(this.hederaLogger.debug("Setting namespaces:",Ps.namespaces),this.namespaces=Ps.namespaces)),this.hederaLogger.debug("Calling super.connect with params");let Hs;try{Hs=await super.connect(Ps)}catch(Ws){throw this.hederaLogger.error("Error in super.connect:",Ws),Ws}return this.hederaLogger.info("super.connect completed successfully"),this.hederaLogger.debug("Result from super.connect:",Hs),this.initProviders(),Hs}async pair(Ps){console.log(Ps),console.log(this.requiredNamespaces);const Hs=await super.pair(Ps);return this.initProviders(),Hs}initProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session||!this.namespaces)return{};const Ps=Object.keys(this.namespaces),Hs={};return Ps.forEach(Ws=>{var Zs,zs,Ys,Va;const Xs=((zs=(Zs=this.session)===null||Zs===void 0?void 0:Zs.namespaces[Ws])===null||zs===void 0?void 0:zs.accounts)||[],Ma=getChainsFromApprovedSession(Xs),qs=mergeRequiredOptionalNamespaces(this.namespaces,this.optionalNamespaces),Js=Object.assign(Object.assign(Object.assign({},qs[Ws]),{accounts:Xs,chains:Ma}),((Va=(Ys=this.optionalNamespaces)===null||Ys===void 0?void 0:Ys[Ws])===null||Va===void 0?void 0:Va.rpcMap)&&{rpcMap:this.optionalNamespaces[Ws].rpcMap});switch(Ws){case"hedera":{const Mc=new HIP820Provider({namespace:Js,events:this.events,client:this.client});this.nativeProvider=Mc,Hs[Ws]=Mc;break}case"eip155":{const Mc=new EIP155Provider({namespace:Js,events:this.events,client:this.client});this.eip155Provider=Mc,Hs[Ws]=Mc;break}default:throw new Error(`Unsupported namespace: ${Ws}`)}}),Hs}get rpcProviders(){return!this.nativeProvider&&!this.eip155Provider?this.initProviders():{hedera:this.nativeProvider,eip155:this.eip155Provider}}set rpcProviders(Ps){}}const LEVEL_ORDER={error:0,warn:1,info:2,debug:3};class Logger{constructor(){this.level="info"}setLogLevel(Ps){this.level=Ps}error(Ps,...Hs){this.shouldLog("error")&&console.error(Ps,...Hs)}warn(Ps,...Hs){this.shouldLog("warn")&&console.warn(Ps,...Hs)}info(Ps,...Hs){this.shouldLog("info")&&console.info(Ps,...Hs)}debug(Ps,...Hs){this.shouldLog("debug")&&console.debug(Ps,...Hs)}shouldLog(Ps){return LEVEL_ORDER[Ps]<=LEVEL_ORDER[this.level]}}var fetchRetry_umd$1={exports:{}},fetchRetry_umd=fetchRetry_umd$1.exports,hasRequiredFetchRetry_umd;function requireFetchRetry_umd(){return hasRequiredFetchRetry_umd||(hasRequiredFetchRetry_umd=1,(function(Fs,Ps){(function(Hs,Ws){Fs.exports=Ws()})(fetchRetry_umd,(function(){var Hs=function(zs,Ys){if(Ys=Ys||{},typeof zs!="function")throw new Zs("fetch must be a function");if(typeof Ys!="object")throw new Zs("defaults must be an object");if(Ys.retries!==void 0&&!Ws(Ys.retries))throw new Zs("retries must be a positive integer");if(Ys.retryDelay!==void 0&&!Ws(Ys.retryDelay)&&typeof Ys.retryDelay!="function")throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(Ys.retryOn!==void 0&&!Array.isArray(Ys.retryOn)&&typeof Ys.retryOn!="function")throw new Zs("retryOn property expects an array or function");var Va={retries:3,retryDelay:1e3,retryOn:[]};return Ys=Object.assign(Va,Ys),function(Ma,qs){var Js=Ys.retries,Mc=Ys.retryDelay,ol=Ys.retryOn;if(qs&&qs.retries!==void 0)if(Ws(qs.retries))Js=qs.retries;else throw new Zs("retries must be a positive integer");if(qs&&qs.retryDelay!==void 0)if(Ws(qs.retryDelay)||typeof qs.retryDelay=="function")Mc=qs.retryDelay;else throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(qs&&qs.retryOn)if(Array.isArray(qs.retryOn)||typeof qs.retryOn=="function")ol=qs.retryOn;else throw new Zs("retryOn property expects an array or function");return new Promise(function(Vc,Dc){var sl=function(hl){var pl=typeof Request<"u"&&Ma instanceof Request?Ma.clone():Ma;zs(pl,qs).then(function(gl){if(Array.isArray(ol)&&ol.indexOf(gl.status)===-1)Vc(gl);else if(typeof ol=="function")try{return Promise.resolve(ol(hl,null,gl)).then(function(yl){yl?ll(hl,null,gl):Vc(gl)}).catch(Dc)}catch(yl){Dc(yl)}else hl<Js?ll(hl,null,gl):Vc(gl)}).catch(function(gl){if(typeof ol=="function")try{Promise.resolve(ol(hl,gl,null)).then(function(yl){yl?ll(hl,gl,null):Dc(gl)}).catch(function(yl){Dc(yl)})}catch(yl){Dc(yl)}else hl<Js?ll(hl,gl,null):Dc(gl)})};function ll(hl,pl,gl){var yl=typeof Mc=="function"?Mc(hl,pl,gl):Mc;setTimeout(function(){sl(++hl)},yl)}sl(0)})}};function Ws(zs){return Number.isInteger(zs)&&zs>=0}function Zs(zs){this.name="ArgumentError",this.message=zs}return Hs}))})(fetchRetry_umd$1)),fetchRetry_umd$1.exports}var fetchRetry_umdExports=requireFetchRetry_umd();const retryFetch=getDefaultExportFromCjs$1(fetchRetry_umdExports),fetchWithRetry=()=>retryFetch(fetch,{retries:3});var Name=(Fs=>(Fs.Contractcall="CONTRACTCALL",Fs.Cryptotransfer="CRYPTOTRANSFER",Fs))(Name||{}),Result=(Fs=>(Fs.Success="SUCCESS",Fs))(Result||{});function ensureGlobalHTMLElement(){typeof globalThis>"u"||typeof globalThis.HTMLElement>"u"&&(globalThis.HTMLElement=class{})}ensureGlobalHTMLElement();const HASH_PACK_WALLET_ID="a29498d225fa4b13468ff4d6cf4ae0ea4adcbd95f07ce8a843a1dee10b632f3f",Nd=class Nd{constructor(Ps,Hs){this.reownAppKit=null,this.reownAppKitKey=null,this.extensionCheckInterval=null,this.hasCalledExtensionCallback=!1,this.logger=Ps||new Logger,this.network=Hs||r$y.MAINNET}get dAppConnector(){return Nd.dAppConnectorInstance}static getInstance(Ps,Hs){let Ws=Nd?.instance;return Ws||(Nd.instance=new Nd(Ps,Hs),Ws=Nd.instance,Nd.proxyInstance=null),Hs&&Ws.setNetwork(Hs),Nd.proxyInstance||(Nd.proxyInstance=new Proxy(Ws,{get(Zs,zs,Ys){const Va=Reflect.get(Zs,zs,Ys);return typeof Va=="function"?Va.bind(Zs):Va}})),Nd.proxyInstance}setLogger(Ps){this.logger=Ps}setNetwork(Ps){this.network=Ps}getNetwork(){return this.network}setReownAppKit(Ps){this.reownAppKit=Ps}async ensureReownAppKit(Ps,Hs,Ws){if(typeof window>"u")return;const Zs=`${Ps}:${Ws.toString()}`;if(!(this.reownAppKit&&this.reownAppKitKey===Zs))try{let zs=HederaChainDefinition.Native.Mainnet;Ws.toString()==="testnet"&&(zs=HederaChainDefinition.Native.Testnet);const Ys=new HederaAdapter({projectId:Ps,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],namespace:hederaNamespace}),Va=await HederaProvider.init({projectId:Ps,metadata:Hs});this.reownAppKit=createAppKit({adapters:[Ys],universalProvider:Va,projectId:Ps,metadata:Hs,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],defaultNetwork:zs,enableWalletGuide:!1,enableWallets:!0,featuredWalletIds:[HASH_PACK_WALLET_ID],includeWalletIds:[HASH_PACK_WALLET_ID]}),this.reownAppKitKey=Zs}catch(zs){this.logger.warn("Failed to initialize Reown AppKit",zs),this.reownAppKit=null,this.reownAppKitKey=null}}setLogLevel(Ps){this.logger instanceof Logger&&this.logger.setLogLevel(Ps)}async init(Ps,Hs,Ws,Zs){const zs=Ws||this.network,Ys=zs.toString()==="mainnet";return Nd.dAppConnectorInstance||(Nd.dAppConnectorInstance=new DAppConnector(Hs,zs,Ps,Object.values(HederaJsonRpcMethod),[HederaSessionEvent.ChainChanged,HederaSessionEvent.AccountsChanged],[Ys?HederaChainId.Mainnet:HederaChainId.Testnet],"debug"),await Nd.dAppConnectorInstance.init({logger:"error"}),await this.ensureReownAppKit(Ps,Hs,zs),Nd.dAppConnectorInstance.onSessionIframeCreated=Va=>{this.logger.info("new session from from iframe",Va),this.handleNewSession(Va),Zs&&Zs(Va)},this.logger.info(`Hedera Wallet Connect SDK initialized on ${zs}`)),Nd.dAppConnectorInstance}async connect(Ps){this.ensureInitialized();const Hs=Ps?.pairingTopic,Ws=this.reownAppKit;if(Ws){const zs=await this.connectUsingReownAppKit(Ws,Hs);return this.handleNewSession(zs),zs}const Zs=await this.dAppConnector.openModal(Hs);return this.handleNewSession(Zs),Zs}async connectUsingReownAppKit(Ps,Hs){if(this.ensureInitialized(),!Ps)throw new Error("AppKit instance is required.");try{return await this.dAppConnector.connect(Ws=>{Ps.open({view:"Connect",uri:Ws}).catch(Zs=>{this.logger.error("Failed to open Reown AppKit modal",Zs)})},Hs)}finally{try{await Ps.close()}catch(Ws){this.logger.warn("Failed to close Reown AppKit modal",Ws)}}}async disconnect(){try{this.ensureInitialized();const Ps=this.getAccountInfo(),Hs=Ps?.accountId,Ws=Ps?.network,Zs=this?.dAppConnector?.signers.find(zs=>zs.getAccountId().toString()===Hs);return await this.dAppConnector?.disconnect(Zs?.topic),this.logger.info(`Disconnected from ${Hs} on ${Ws}`),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async disconnectAll(){try{return this.ensureInitialized(),await this.dAppConnector?.disconnectAll(),this.logger.info("Disconnected from all wallets"),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async executeTransaction(Ps,Hs=!1){this.ensureInitialized();const Zs=this.getAccountInfo()?.accountId,zs=this.dAppConnector.signers.find(Ys=>Ys.getAccountId().toString()===Zs);if(!zs)throw new Error("No signer available. Please ensure wallet is connected.");try{return Hs?await(await Ps.executeWithSigner(zs)).getReceiptWithSigner(zs):await(await(await Ps.freezeWithSigner(zs)).executeWithSigner(zs)).getReceiptWithSigner(zs)}catch(Ys){throw(Ys.message??"").toLowerCase().includes("nodeaccountid")?new Error("Transaction execution failed because nodeAccountId is not set. Set node account IDs on the transaction before calling executeTransaction."):Ys}}async executeTransactionWithErrorHandling(Ps,Hs){try{return{result:await this.executeTransaction(Ps,Hs),error:void 0}}catch(Ws){const zs=Ws.message?.toLowerCase();if(this.logger.error("Failed to execute transaction",Ws),this.logger.error("Failure reason for transaction is",zs),zs.includes("insufficient payer balance"))return{result:void 0,error:"Insufficient balance to complete the transaction."};if(zs.includes("reject"))return{result:void 0,error:"You rejected the transaction"};if(zs.includes("invalid signature"))return{result:void 0,error:"Invalid signature. Please check your account and try again."};if(zs.includes("transaction expired"))return{result:void 0,error:"Transaction expired. Please try again."};if(zs.includes("account not found"))return{result:void 0,error:"Account not found. Please check the account ID and try again."};if(zs.includes("unauthorized"))return{result:void 0,error:"Unauthorized. You may not have the necessary permissions for this action."};if(zs.includes("busy"))return{result:void 0,error:"The network is busy. Please try again later."};if(zs.includes("invalid transaction"))return{result:void 0,error:"Invalid transaction. Please check your inputs and try again."}}}async submitMessageToTopic(Ps,Hs,Ws){this.ensureInitialized();let Zs=new u$u().setTopicId(d$s.fromString(Ps)).setMessage(Hs);return Ws&&(Zs=await Zs.sign(Ws)),this.executeTransaction(Zs)}async transferHbar(Ps,Hs,Ws){this.ensureInitialized();const Zs=new T$a().setTransactionId(i$s.generate(Ps)).addHbarTransfer(y$f.fromString(Ps),new e$F(-Ws)).addHbarTransfer(y$f.fromString(Hs),new e$F(Ws));return this.executeTransaction(Zs)}async executeSmartContract(Ps,Hs,Ws,Zs=1e5){this.ensureInitialized();const zs=new i$o().setContractId(g$p.fromString(Ps)).setGas(Zs).setFunction(Hs,Ws);return this.executeTransaction(zs)}handleNewSession(Ps){const Ws=Ps.namespaces?.hedera?.accounts?.[0]?.split(":"),Zs=Ws.pop(),zs=Ws.pop();if(this.logger.info("sessionAccount is",Zs,zs),Zs)this.saveConnectionInfo(Zs,zs);else{this.logger.error("No account id found in the session");return}}getNetworkPrefix(){const Hs=this.getAccountInfo()?.network;if(!Hs){this.logger.warn("Network is not set on SDK, defaulting.");const Ws=localStorage.getItem("connectedNetwork");return Ws||"mainnet-public"}return Hs!==this.network&&(this.logger.warn("Detected network mismatch, reverting to signer network",Hs),this.network=Hs),Hs.isMainnet()?"mainnet-public":"testnet"}async requestAccount(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/accounts/${Ps}`,Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to make request to mirror node for account: ${Zs.status}`);return await Zs.json()}catch(Hs){throw this.logger.error("Failed to fetch account",Hs),Hs}}async getAccountBalance(){this.ensureInitialized();const Hs=this.getAccountInfo()?.accountId;if(!Hs)return null;const Ws=await this.requestAccount(Hs);if(!Ws)throw new Error("Failed to fetch account. Try again or check if the Account ID is valid.");const Zs=Ws.balance.balance/10**8;return Number(Zs).toLocaleString("en-US")}getAccountInfo(){const{accountId:Ps}=this.loadConnectionInfo();if(!Ps||!this?.dAppConnector?.signers?.length)return null;const Ws=this.dAppConnector.signers.find(Ys=>Ys.getAccountId().toString()===Ps);if(!Ws)return null;const Zs=Ws?.getAccountId()?.toString();if(!Zs)return null;const zs=Ws.getLedgerId();return{accountId:Zs,network:zs}}async createTopic(Ps,Hs,Ws){this.ensureInitialized();let Zs=new c$w().setTopicMemo(Ps||"");if(Hs){const Ys=g$q.fromString(Hs);Zs.setAdminKey(Ys.publicKey),Zs=await Zs.sign(Ys)}return Ws&&Zs.setSubmitKey(g$q.fromString(Ws).publicKey),(await this.executeTransaction(Zs)).topicId.toString()}async createToken(Ps,Hs,Ws,Zs,zs,Ys,Va){this.ensureInitialized();let Xs=new c$x().setTokenName(Ps).setTokenSymbol(Hs).setDecimals(Zs).setInitialSupply(Ws).setTreasuryAccountId(y$f.fromString(zs)).setTokenType(e$l.NonFungibleUnique).setSupplyType(e$k.Finite);return Va&&(Xs=Xs.setSupplyKey(g$q.fromString(Va))),Ys&&(Xs=Xs.setAdminKey(g$q.fromString(Ys)),Xs=await Xs.sign(g$q.fromString(Ys))),(await this.executeTransaction(Xs)).tokenId.toString()}async mintNFT(Ps,Hs,Ws){this.ensureInitialized();let Zs=await new r$n().setTokenId(Ps).setMetadata([Buffer$1.from(Hs,"utf-8")]).sign(Ws);return this.executeTransaction(Zs)}async getMessages(Ps,Hs,Ws=!1,Zs){const Ys=`https://${Zs||this.getNetworkPrefix()}.mirrornode.hedera.com`,Va=Number(Hs)>0&&!Ws?`&timestamp=gt:${Hs}`:"",Xs=`${Ys}/api/v1/topics/${Ps}/messages?limit=200${Va}`;try{const Ma=await fetchWithRetry()(Xs);if(!Ma.ok)throw new Error(`Failed to make request to mirror node: ${Ma.status}`);const qs=await Ma.json(),Js=qs?.messages||[],Mc=qs?.links?.next,ol=Js.map(Vc=>({...JSON.parse(atob(Vc.message)),payer:Vc.payer_account_id,created:new Date(Number(Vc.consensus_timestamp)*1e3),consensus_timestamp:Vc.consensus_timestamp,sequence_number:Vc.sequence_number}));if(Mc){const Vc=await this.getMessages(Ps,Number(ol[ol.length-1]?.consensus_timestamp),Ws);ol.push(...Vc.messages)}return{messages:ol.sort((Vc,Dc)=>Vc.sequence_number-Dc.sequence_number),error:""}}catch(Ma){return this.logger.error("Error fetching topic data:",Ma),{messages:[],error:Ma.toString()}}}async signMessage(Ps){const Hs=this.dAppConnector;if(!Hs)throw new Error("No active connection or signer");const Zs=this.getAccountInfo()?.accountId,zs={signerAccountId:`hedera:${this.network}:${Zs}`,message:Ps};return{userSignature:(await Hs.signMessage(zs)).signatureMap}}saveConnectionInfo(Ps,Hs){if(!Ps)localStorage.removeItem("connectedAccountId"),localStorage.removeItem("connectedNetwork");else{const Ws=Hs?.replace(/['"]+/g,"");localStorage.setItem("connectedNetwork",Ws),localStorage.setItem("connectedAccountId",Ps)}}loadConnectionInfo(){return{accountId:localStorage.getItem("connectedAccountId"),network:localStorage.getItem("connectedNetwork")}}async connectWallet(Ps,Hs,Ws){try{await this.init(Ps,Hs,Ws);const Zs=await this.connect(),Ys=this.getAccountInfo()?.accountId,Va=await this.getAccountBalance(),Xs=this.getNetworkPrefix();return this.saveConnectionInfo(Ys,Xs),{accountId:Ys,balance:Va,session:Zs}}catch(Zs){throw this.logger.error("Failed to connect wallet:",Zs),Zs}}async disconnectWallet(Ps=!0){try{const Hs=await this.disconnect();return Hs&&Ps&&localStorage.clear(),this.saveConnectionInfo(void 0),Hs}catch(Hs){return this.logger.error("Failed to disconnect wallet:",Hs),!1}}async initAccount(Ps,Hs,Ws,Zs=()=>{}){const{accountId:zs,network:Ys}=this.loadConnectionInfo();if(zs&&Ys)try{const Va=Ys==="mainnet"?r$y.MAINNET:r$y.TESTNET,Xs=Ws||Va;await this.init(Ps,Hs,Xs,Zs);const Ma=await this.getAccountBalance();return{accountId:zs,balance:Ma}}catch(Va){return this.logger.error("Failed to reconnect:",Va),this.saveConnectionInfo(void 0,void 0),null}else if(Ws)try{this.logger.info("initializing normally through override.",Ws),await this.init(Ps,Hs,Ws,Zs),this.logger.info("initialized",Ws),await this.connectViaDappBrowser(),this.logger.info("connected via dapp browser")}catch(Va){return this.logger.error("Failed to fallback connect:",Va),this.saveConnectionInfo(void 0,void 0),null}return null}subscribeToExtensions(Ps){return this.extensionCheckInterval&&clearInterval(this.extensionCheckInterval),this.hasCalledExtensionCallback=!1,this.extensionCheckInterval=setInterval(()=>{const Ws=(this.dAppConnector?.extensions||[]).find(Zs=>Zs.availableInIframe);Ws&&!this.hasCalledExtensionCallback&&(this.hasCalledExtensionCallback=!0,Ps(Ws),this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null))},1e3),()=>{this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null),this.hasCalledExtensionCallback=!1}}async connectViaDappBrowser(){const Ps=this.dAppConnector.extensions||[],Hs=Ps.find(Ws=>(this.logger.info("Checking extension",Ws),Ws.availableInIframe));this.logger.info("extensions are",Ps,Hs),Hs?await this.connectToExtension(Hs):this.subscribeToExtensions(async Ws=>{await this.connectToExtension(Ws)})}async connectToExtension(Ps){this.logger.info("found extension, connecting to iframe.",Ps);const Hs=await this.dAppConnector.connectExtension(Ps.id),Ws=this.dAppConnector.onSessionIframeCreated;Ws&&Ws(Hs)}ensureInitialized(){if(!this.dAppConnector)throw new Error("SDK not initialized. Call init() first.")}static run(){try{typeof window<"u"&&(window.HashinalsWalletConnectSDK=Nd.getInstance(),window.HashgraphSDK=HashgraphSDK)}catch{console.error("[ERROR]: failed setting sdk on window")}}async transferToken(Ps,Hs,Ws,Zs){this.ensureInitialized();const zs=new T$a().setTransactionId(i$s.generate(Hs)).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Hs),-Zs).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Ws),Zs);return this.executeTransaction(zs)}async createAccount(Ps){this.ensureInitialized();const Hs=new h$m().setInitialBalance(new e$F(Ps));return this.executeTransaction(Hs)}async associateTokenToAccount(Ps,Hs){this.ensureInitialized();const Ws=new r$t().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Hs)]);return this.executeTransaction(Ws)}async dissociateTokenFromAccount(Ps,Hs){this.ensureInitialized();const Ws=new r$s().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Hs)]);return this.executeTransaction(Ws)}async updateAccount(Ps,Hs){this.ensureInitialized();const Ws=new s$G().setAccountId(y$f.fromString(Ps)).setMaxAutomaticTokenAssociations(Hs);return this.executeTransaction(Ws)}async approveAllowance(Ps,Hs,Ws,Zs){this.ensureInitialized();const zs=new A$c().approveTokenAllowance(c$E.fromString(Hs),y$f.fromString(Zs),y$f.fromString(Ps),Ws);return this.executeTransaction(zs)}async getAccountTokens(Ps){this.ensureInitialized();const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com`,Zs=`${Ws}/api/v1/accounts/${Ps}/tokens?limit=200`;try{const zs=await fetchWithRetry()(Zs);if(!zs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${zs.status}`);const Ys=await zs.json(),Va=[];for(const Ma of Ys.tokens)Ma.token_id&&Va.push({tokenId:Ma.token_id,balance:Ma.balance,decimals:Ma.decimals,formatted_balance:(Ma.balance/10**Ma.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Ma.created_timestamp)*1e3)});let Xs=Ys.links?.next;for(;Xs;){const Ma=`${Ws}${Xs}`,qs=await fetchWithRetry()(Ma);if(!qs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${qs.status}, page: ${Ma}`);const Js=await qs.json();for(const Mc of Js.tokens)Mc.token_id&&Va.push({tokenId:Mc.token_id,balance:Mc.balance,decimals:Mc.decimals,formatted_balance:(Mc.balance/10**Mc.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Mc.created_timestamp)*1e3)});Xs=Js.links?.next}return{tokens:Va}}catch(zs){throw this.logger.error("Error fetching account tokens:",zs),zs}}async getTransaction(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions/${Ps}`;this.logger.debug("Fetching transaction",Ws);const Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to fetch transaction: ${Zs.status}`);return await Zs.json()}catch(Hs){return this.logger.error("Failed to get transaction",Hs),null}}async getTransactionByTimestamp(Ps){try{const Ws=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions?timestamp=${Ps}`;this.logger.debug("Fetching transaction by timestamp",Ws);const Zs=await fetchWithRetry()(Ws);if(!Zs.ok)throw new Error(`Failed to fetch transaction by timestamp: ${Zs.status}`);const Ys=(await Zs.json())?.transactions?.[0];return Ys?await this.getTransaction(Ys.transaction_id):null}catch(Hs){return this.logger.error("Failed to get transaction by timestamp",Hs),null}}async getAccountNFTs(Ps,Hs){try{const Ws=this.getNetworkPrefix(),Zs=Hs?`&token.id=${Hs}`:"",zs=`https://${Ws}.mirrornode.hedera.com/api/v1/accounts/${Ps}/nfts?limit=200${Zs}`,Ys=await fetchWithRetry()(zs);if(!Ys.ok)throw new Error(`Failed to fetch NFTs for account: ${Ys.status}`);const Va=await Ys.json();let Xs=Va?.links?.next||null,Ma=Va.nfts||[];for(;Xs;)try{const qs=await fetchWithRetry()(`https://${Ws}.mirrornode.hedera.com${Xs}`);if(!qs.ok)throw new Error(`Failed to fetch next page of NFTs: ${qs.status}`);const Js=await qs.json(),Mc=Js?.nfts||[];Ma=[...Ma,...Mc],Xs=Js?.links?.next&&Xs!==Js?.links?.next?Js.links.next:null}catch(qs){this.logger.error("Failed to fetch next page of NFTs",qs);break}return Ma.map(qs=>{try{qs.token_uri=Buffer$1.from(qs.metadata,"base64").toString("ascii")}catch(Js){this.logger.error("Failed to decode NFT metadata",Js)}return qs})}catch(Ws){return this.logger.error("Failed to get account NFTs",Ws),[]}}async validateNFTOwnership(Ps,Hs,Ws){return(await this.getAccountNFTs(Hs,Ws)).find(zs=>zs.token_id===Ws&&zs.serial_number.toString()===Ps)||null}async readSmartContract(Ps,Hs,Ws,Zs=!0,zs=0){try{const Ys=this.getNetworkPrefix(),Va={block:"latest",data:Ps,estimate:Zs,from:Hs.toSolidityAddress(),to:Ws.toSolidityAddress(),value:zs};Zs||(Va.gas=3e5,Va.gasPrice=1e8);const Xs=`https://${Ys}.mirrornode.hedera.com/api/v1/contracts/call`,Ma=await fetchWithRetry()(Xs,{method:"POST",body:JSON.stringify(Va),headers:{"Content-Type":"application/json"}});if(!Ma.ok)throw new Error(`Failed to make contract call: ${Ma.status}`);return await Ma.json()}catch(Ys){return this.logger.error("Failed to make contract call",Ys),null}}};Nd.proxyInstance=null;let HashinalsWalletConnectSDK=Nd;HashinalsWalletConnectSDK.run();class ReownAuthenticationMessenger{constructor(Ps){this.getNonce=Ps.getNonce}async createMessage(Ps){const Hs={accountAddress:Ps.accountAddress,chainId:Ps.chainId,version:"1",domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,resources:this.resources,nonce:await this.getNonce(Ps),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(Hs,{toString:()=>this.stringify(Hs)})}stringify(Ps){const Hs=this.getNetworkName(Ps.chainId);return[`${Ps.domain} wants you to sign in with your ${Hs} account:`,Ps.accountAddress,Ps.statement?`
467
467
  ${Ps.statement}
468
468
  `:"",`URI: ${Ps.uri}`,`Version: ${Ps.version}`,`Chain ID: ${Ps.chainId}`,`Nonce: ${Ps.nonce}`,Ps.issuedAt&&`Issued At: ${Ps.issuedAt}`,Ps.expirationTime&&`Expiration Time: ${Ps.expirationTime}`,Ps.notBefore&&`Not Before: ${Ps.notBefore}`,Ps.requestId&&`Request ID: ${Ps.requestId}`,Ps.resources?.length&&Ps.resources.reduce((Ws,Zs)=>`${Ws}
469
469
  - ${Zs}`,"Resources:")].filter(Ws=>typeof Ws=="string").join(`