diff --git a/assets/ccip-BuUYLUEo.js b/assets/ccip-d6sEp144.js similarity index 97% rename from assets/ccip-BuUYLUEo.js rename to assets/ccip-d6sEp144.js index 91e9b99..ae52688 100644 --- a/assets/ccip-BuUYLUEo.js +++ b/assets/ccip-d6sEp144.js @@ -1 +1 @@ -import{d as p,g as m,e as y,f as k,i as b,j as O,k as E,l as L,H as h,m as x}from"./index-jkWzPUAB.js";class M extends p{constructor({callbackSelector:r,cause:a,data:o,extraData:i,sender:d,urls:t}){var n;super(a.shortMessage||"An error occurred while fetching for an offchain result.",{cause:a,metaMessages:[...a.metaMessages||[],(n=a.metaMessages)!=null&&n.length?"":[],"Offchain Gateway Call:",t&&[" Gateway URL(s):",...t.map(f=>` ${m(f)}`)],` Sender: ${d}`,` Data: ${o}`,` Callback selector: ${r}`,` Extra data: ${i}`].flat(),name:"OffchainLookupError"})}}class R extends p{constructor({result:r,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${m(a)}`,`Response: ${y(r)}`],name:"OffchainLookupResponseMalformedError"})}}class S extends p{constructor({sender:r,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${r}`],name:"OffchainLookupSenderMismatchError"})}}const A="0x556f1830",$={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function C(c,{blockNumber:r,blockTag:a,data:o,to:i}){const{args:d}=k({data:o,abi:[$]}),[t,n,f,u,s]=d,{ccipRead:e}=c,g=e&&typeof(e==null?void 0:e.request)=="function"?e.request:T;try{if(!b(i,t))throw new S({sender:t,to:i});const l=await g({data:f,sender:t,urls:n}),{data:w}=await O(c,{blockNumber:r,blockTag:a,data:E([u,L([{type:"bytes"},{type:"bytes"}],[l,s])]),to:i});return w}catch(l){throw new M({callbackSelector:u,cause:l,data:o,extraData:s,sender:t,urls:n})}}async function T({data:c,sender:r,urls:a}){var i;let o=new Error("An unknown error occurred.");for(let d=0;d` ${m(f)}`)],` Sender: ${d}`,` Data: ${o}`,` Callback selector: ${r}`,` Extra data: ${i}`].flat(),name:"OffchainLookupError"})}}class R extends p{constructor({result:r,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${m(a)}`,`Response: ${y(r)}`],name:"OffchainLookupResponseMalformedError"})}}class S extends p{constructor({sender:r,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${r}`],name:"OffchainLookupSenderMismatchError"})}}const A="0x556f1830",$={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function C(c,{blockNumber:r,blockTag:a,data:o,to:i}){const{args:d}=k({data:o,abi:[$]}),[t,n,f,u,s]=d,{ccipRead:e}=c,g=e&&typeof(e==null?void 0:e.request)=="function"?e.request:T;try{if(!b(i,t))throw new S({sender:t,to:i});const l=await g({data:f,sender:t,urls:n}),{data:w}=await O(c,{blockNumber:r,blockTag:a,data:E([u,L([{type:"bytes"},{type:"bytes"}],[l,s])]),to:i});return w}catch(l){throw new M({callbackSelector:u,cause:l,data:o,extraData:s,sender:t,urls:n})}}async function T({data:c,sender:r,urls:a}){var i;let o=new Error("An unknown error occurred.");for(let d=0;di.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/webcrypto-CJZUMDsH.js","assets/utils-B7bt9iXy.js","assets/nodecrypto-pMA0JG-7.js"])))=>i.map(i=>d[i]); var hS=Object.defineProperty;var pS=(fr,br,wr)=>br in fr?hS(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr;var _f=(fr,br,wr)=>pS(fr,typeof br!="symbol"?br+"":br,wr);function _mergeNamespaces(fr,br){for(var wr=0;wrEr[kr]})}}}return Object.freeze(Object.defineProperty(fr,Symbol.toStringTag,{value:"Module"}))}(function(){const br=document.createElement("link").relList;if(br&&br.supports&&br.supports("modulepreload"))return;for(const kr of document.querySelectorAll('link[rel="modulepreload"]'))Er(kr);new MutationObserver(kr=>{for(const jr of kr)if(jr.type==="childList")for(const Br of jr.addedNodes)Br.tagName==="LINK"&&Br.rel==="modulepreload"&&Er(Br)}).observe(document,{childList:!0,subtree:!0});function wr(kr){const jr={};return kr.integrity&&(jr.integrity=kr.integrity),kr.referrerPolicy&&(jr.referrerPolicy=kr.referrerPolicy),kr.crossOrigin==="use-credentials"?jr.credentials="include":kr.crossOrigin==="anonymous"?jr.credentials="omit":jr.credentials="same-origin",jr}function Er(kr){if(kr.ep)return;kr.ep=!0;const jr=wr(kr);fetch(kr.href,jr)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs$2(fr){return fr&&fr.__esModule&&Object.prototype.hasOwnProperty.call(fr,"default")?fr.default:fr}function getAugmentedNamespace(fr){if(fr.__esModule)return fr;var br=fr.default;if(typeof br=="function"){var wr=function Er(){return this instanceof Er?Reflect.construct(br,arguments,this.constructor):br.apply(this,arguments)};wr.prototype=br.prototype}else wr={};return Object.defineProperty(wr,"__esModule",{value:!0}),Object.keys(fr).forEach(function(Er){var kr=Object.getOwnPropertyDescriptor(fr,Er);Object.defineProperty(wr,Er,kr.get?kr:{enumerable:!0,get:function(){return fr[Er]}})}),wr}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={},react={exports:{}},react_production_min={};/** * @license React * react.production.min.js @@ -2008,10 +2008,10 @@ ${prettyStateOverride(Xr)}`),super(br.shortMessage,{cause:br,docsPath:Er,metaMes `),{cause:br,name:"NonceTooLowError"})}}Object.defineProperty(NonceTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class NonceMaxValueError extends BaseError{constructor({cause:br,nonce:wr}={}){super(`Nonce provided for the transaction ${wr?`(${wr}) `:""}exceeds the maximum allowed nonce.`,{cause:br,name:"NonceMaxValueError"})}}Object.defineProperty(NonceMaxValueError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class InsufficientFundsError extends BaseError{constructor({cause:br}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` `),{cause:br,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(InsufficientFundsError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class IntrinsicGasTooHighError extends BaseError{constructor({cause:br,gas:wr}={}){super(`The amount of gas ${wr?`(${wr}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:br,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(IntrinsicGasTooHighError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class IntrinsicGasTooLowError extends BaseError{constructor({cause:br,gas:wr}={}){super(`The amount of gas ${wr?`(${wr}) `:""}provided for the transaction is too low.`,{cause:br,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(IntrinsicGasTooLowError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class TransactionTypeNotSupportedError extends BaseError{constructor({cause:br}){super("The transaction type is not supported for this chain.",{cause:br,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(TransactionTypeNotSupportedError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class TipAboveFeeCapError extends BaseError{constructor({cause:br,maxPriorityFeePerGas:wr,maxFeePerGas:Er}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${wr?` = ${formatGwei$1(wr)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${Er?` = ${formatGwei$1(Er)} gwei`:""}).`].join(` `),{cause:br,name:"TipAboveFeeCapError"})}}Object.defineProperty(TipAboveFeeCapError,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class UnknownNodeError extends BaseError{constructor({cause:br}){super(`An error occurred while executing: ${br==null?void 0:br.shortMessage}`,{cause:br,name:"UnknownNodeError"})}}function getNodeError$1(fr,br){const wr=(fr.details||"").toLowerCase(),Er=fr instanceof BaseError?fr.walk(kr=>(kr==null?void 0:kr.code)===ExecutionRevertedError.code):fr;return Er instanceof BaseError?new ExecutionRevertedError({cause:fr,message:Er.details}):ExecutionRevertedError.nodeMessage.test(wr)?new ExecutionRevertedError({cause:fr,message:fr.details}):FeeCapTooHighError.nodeMessage.test(wr)?new FeeCapTooHighError({cause:fr,maxFeePerGas:br==null?void 0:br.maxFeePerGas}):FeeCapTooLowError.nodeMessage.test(wr)?new FeeCapTooLowError({cause:fr,maxFeePerGas:br==null?void 0:br.maxFeePerGas}):NonceTooHighError.nodeMessage.test(wr)?new NonceTooHighError({cause:fr,nonce:br==null?void 0:br.nonce}):NonceTooLowError.nodeMessage.test(wr)?new NonceTooLowError({cause:fr,nonce:br==null?void 0:br.nonce}):NonceMaxValueError.nodeMessage.test(wr)?new NonceMaxValueError({cause:fr,nonce:br==null?void 0:br.nonce}):InsufficientFundsError.nodeMessage.test(wr)?new InsufficientFundsError({cause:fr}):IntrinsicGasTooHighError.nodeMessage.test(wr)?new IntrinsicGasTooHighError({cause:fr,gas:br==null?void 0:br.gas}):IntrinsicGasTooLowError.nodeMessage.test(wr)?new IntrinsicGasTooLowError({cause:fr,gas:br==null?void 0:br.gas}):TransactionTypeNotSupportedError.nodeMessage.test(wr)?new TransactionTypeNotSupportedError({cause:fr}):TipAboveFeeCapError.nodeMessage.test(wr)?new TipAboveFeeCapError({cause:fr,maxFeePerGas:br==null?void 0:br.maxFeePerGas,maxPriorityFeePerGas:br==null?void 0:br.maxPriorityFeePerGas}):new UnknownNodeError({cause:fr})}function getEstimateGasError$1(fr,{docsPath:br,...wr}){const Er=(()=>{const kr=getNodeError$1(fr,wr);return kr instanceof UnknownNodeError?fr:kr})();return new EstimateGasExecutionError(Er,{docsPath:br,...wr})}function extract$1(fr,{format:br}){if(!br)return{};const wr={};function Er(jr){const Br=Object.keys(jr);for(const qr of Br)qr in fr&&(wr[qr]=fr[qr]),jr[qr]&&typeof jr[qr]=="object"&&!Array.isArray(jr[qr])&&Er(jr[qr])}const kr=br(fr||{});return Er(kr),wr}function defineFormatter(fr,br){return({exclude:wr,format:Er})=>({exclude:wr,format:kr=>{const jr=br(kr);if(wr)for(const Br of wr)delete jr[Br];return{...jr,...Er(kr)}},type:fr})}const rpcTransactionType={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function formatTransactionRequest(fr){const br={};return typeof fr.authorizationList<"u"&&(br.authorizationList=formatAuthorizationList$1(fr.authorizationList)),typeof fr.accessList<"u"&&(br.accessList=fr.accessList),typeof fr.blobVersionedHashes<"u"&&(br.blobVersionedHashes=fr.blobVersionedHashes),typeof fr.blobs<"u"&&(typeof fr.blobs[0]!="string"?br.blobs=fr.blobs.map(wr=>bytesToHex$4(wr)):br.blobs=fr.blobs),typeof fr.data<"u"&&(br.data=fr.data),typeof fr.from<"u"&&(br.from=fr.from),typeof fr.gas<"u"&&(br.gas=numberToHex(fr.gas)),typeof fr.gasPrice<"u"&&(br.gasPrice=numberToHex(fr.gasPrice)),typeof fr.maxFeePerBlobGas<"u"&&(br.maxFeePerBlobGas=numberToHex(fr.maxFeePerBlobGas)),typeof fr.maxFeePerGas<"u"&&(br.maxFeePerGas=numberToHex(fr.maxFeePerGas)),typeof fr.maxPriorityFeePerGas<"u"&&(br.maxPriorityFeePerGas=numberToHex(fr.maxPriorityFeePerGas)),typeof fr.nonce<"u"&&(br.nonce=numberToHex(fr.nonce)),typeof fr.to<"u"&&(br.to=fr.to),typeof fr.type<"u"&&(br.type=rpcTransactionType[fr.type]),typeof fr.value<"u"&&(br.value=numberToHex(fr.value)),br}const defineTransactionRequest=defineFormatter("transactionRequest",formatTransactionRequest);function formatAuthorizationList$1(fr){return fr.map(br=>({address:br.contractAddress,r:br.r,s:br.s,chainId:numberToHex(br.chainId),nonce:numberToHex(br.nonce),...typeof br.yParity<"u"?{yParity:numberToHex(br.yParity)}:{},...typeof br.v<"u"&&typeof br.yParity>"u"?{v:numberToHex(br.v)}:{}}))}function serializeStateMapping(fr){if(!(!fr||fr.length===0))return fr.reduce((br,{slot:wr,value:Er})=>{if(wr.length!==66)throw new InvalidBytesLengthError({size:wr.length,targetSize:66,type:"hex"});if(Er.length!==66)throw new InvalidBytesLengthError({size:Er.length,targetSize:66,type:"hex"});return br[wr]=Er,br},{})}function serializeAccountStateOverride(fr){const{balance:br,nonce:wr,state:Er,stateDiff:kr,code:jr}=fr,Br={};if(jr!==void 0&&(Br.code=jr),br!==void 0&&(Br.balance=numberToHex(br)),wr!==void 0&&(Br.nonce=numberToHex(wr)),Er!==void 0&&(Br.state=serializeStateMapping(Er)),kr!==void 0){if(Br.state)throw new StateAssignmentConflictError;Br.stateDiff=serializeStateMapping(kr)}return Br}function serializeStateOverride(fr){if(!fr)return;const br={};for(const{address:wr,...Er}of fr){if(!isAddress$1(wr,{strict:!1}))throw new InvalidAddressError({address:wr});if(br[wr])throw new AccountStateConflictError({address:wr});br[wr]=serializeAccountStateOverride(Er)}return br}const maxUint16=2n**16n-1n,maxUint256=2n**256n-1n;function assertRequest$1(fr){const{account:br,gasPrice:wr,maxFeePerGas:Er,maxPriorityFeePerGas:kr,to:jr}=fr,Br=br?parseAccount$1(br):void 0;if(Br&&!isAddress$1(Br.address))throw new InvalidAddressError({address:Br.address});if(jr&&!isAddress$1(jr))throw new InvalidAddressError({address:jr});if(typeof wr<"u"&&(typeof Er<"u"||typeof kr<"u"))throw new FeeConflictError;if(Er&&Er>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:Er});if(kr&&Er&&kr>Er)throw new TipAboveFeeCapError({maxFeePerGas:Er,maxPriorityFeePerGas:kr})}class BaseFeeScalarError extends BaseError{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Eip1559FeesNotSupportedError extends BaseError{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class MaxFeePerGasTooLowError extends BaseError{constructor({maxPriorityFeePerGas:br}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei$1(br)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class BlockNotFoundError extends BaseError{constructor({blockHash:br,blockNumber:wr}){let Er="Block";br&&(Er=`Block at hash "${br}"`),wr&&(Er=`Block at number "${wr}"`),super(`${Er} could not be found.`,{name:"BlockNotFoundError"})}}const transactionType={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function formatTransaction(fr){const br={...fr,blockHash:fr.blockHash?fr.blockHash:null,blockNumber:fr.blockNumber?BigInt(fr.blockNumber):null,chainId:fr.chainId?hexToNumber$2(fr.chainId):void 0,gas:fr.gas?BigInt(fr.gas):void 0,gasPrice:fr.gasPrice?BigInt(fr.gasPrice):void 0,maxFeePerBlobGas:fr.maxFeePerBlobGas?BigInt(fr.maxFeePerBlobGas):void 0,maxFeePerGas:fr.maxFeePerGas?BigInt(fr.maxFeePerGas):void 0,maxPriorityFeePerGas:fr.maxPriorityFeePerGas?BigInt(fr.maxPriorityFeePerGas):void 0,nonce:fr.nonce?hexToNumber$2(fr.nonce):void 0,to:fr.to?fr.to:null,transactionIndex:fr.transactionIndex?Number(fr.transactionIndex):null,type:fr.type?transactionType[fr.type]:void 0,typeHex:fr.type?fr.type:void 0,value:fr.value?BigInt(fr.value):void 0,v:fr.v?BigInt(fr.v):void 0};return fr.authorizationList&&(br.authorizationList=formatAuthorizationList(fr.authorizationList)),br.yParity=(()=>{if(fr.yParity)return Number(fr.yParity);if(typeof br.v=="bigint"){if(br.v===0n||br.v===27n)return 0;if(br.v===1n||br.v===28n)return 1;if(br.v>=35n)return br.v%2n===0n?1:0}})(),br.type==="legacy"&&(delete br.accessList,delete br.maxFeePerBlobGas,delete br.maxFeePerGas,delete br.maxPriorityFeePerGas,delete br.yParity),br.type==="eip2930"&&(delete br.maxFeePerBlobGas,delete br.maxFeePerGas,delete br.maxPriorityFeePerGas),br.type==="eip1559"&&delete br.maxFeePerBlobGas,br}const defineTransaction=defineFormatter("transaction",formatTransaction);function formatAuthorizationList(fr){return fr.map(br=>({contractAddress:br.address,chainId:Number(br.chainId),nonce:Number(br.nonce),r:br.r,s:br.s,yParity:Number(br.yParity)}))}function formatBlock(fr){const br=(fr.transactions??[]).map(wr=>typeof wr=="string"?wr:formatTransaction(wr));return{...fr,baseFeePerGas:fr.baseFeePerGas?BigInt(fr.baseFeePerGas):null,blobGasUsed:fr.blobGasUsed?BigInt(fr.blobGasUsed):void 0,difficulty:fr.difficulty?BigInt(fr.difficulty):void 0,excessBlobGas:fr.excessBlobGas?BigInt(fr.excessBlobGas):void 0,gasLimit:fr.gasLimit?BigInt(fr.gasLimit):void 0,gasUsed:fr.gasUsed?BigInt(fr.gasUsed):void 0,hash:fr.hash?fr.hash:null,logsBloom:fr.logsBloom?fr.logsBloom:null,nonce:fr.nonce?fr.nonce:null,number:fr.number?BigInt(fr.number):null,size:fr.size?BigInt(fr.size):void 0,timestamp:fr.timestamp?BigInt(fr.timestamp):void 0,transactions:br,totalDifficulty:fr.totalDifficulty?BigInt(fr.totalDifficulty):null}}const defineBlock=defineFormatter("block",formatBlock);async function getBlock$1(fr,{blockHash:br,blockNumber:wr,blockTag:Er,includeTransactions:kr}={}){var Hr,Zr,Jr;const jr=Er??"latest",Br=kr??!1,qr=wr!==void 0?numberToHex(wr):void 0;let Wr=null;if(br?Wr=await fr.request({method:"eth_getBlockByHash",params:[br,Br]},{dedupe:!0}):Wr=await fr.request({method:"eth_getBlockByNumber",params:[qr||jr,Br]},{dedupe:!!qr}),!Wr)throw new BlockNotFoundError({blockHash:br,blockNumber:wr});return(((Jr=(Zr=(Hr=fr.chain)==null?void 0:Hr.formatters)==null?void 0:Zr.block)==null?void 0:Jr.format)||formatBlock)(Wr)}async function getGasPrice$1(fr){const br=await fr.request({method:"eth_gasPrice"});return BigInt(br)}async function estimateMaxPriorityFeePerGas$1(fr,br){return internal_estimateMaxPriorityFeePerGas(fr,br)}async function internal_estimateMaxPriorityFeePerGas(fr,br){var jr,Br;const{block:wr,chain:Er=fr.chain,request:kr}=br||{};try{const qr=((jr=Er==null?void 0:Er.fees)==null?void 0:jr.maxPriorityFeePerGas)??((Br=Er==null?void 0:Er.fees)==null?void 0:Br.defaultPriorityFee);if(typeof qr=="function"){const Vr=wr||await getAction$1(fr,getBlock$1,"getBlock")({}),Hr=await qr({block:Vr,client:fr,request:kr});if(Hr===null)throw new Error;return Hr}if(typeof qr<"u")return qr;const Wr=await fr.request({method:"eth_maxPriorityFeePerGas"});return hexToBigInt(Wr)}catch{const[qr,Wr]=await Promise.all([wr?Promise.resolve(wr):getAction$1(fr,getBlock$1,"getBlock")({}),getAction$1(fr,getGasPrice$1,"getGasPrice")({})]);if(typeof qr.baseFeePerGas!="bigint")throw new Eip1559FeesNotSupportedError;const Vr=Wr-qr.baseFeePerGas;return Vr<0n?0n:Vr}}async function estimateFeesPerGas$2(fr,br){return internal_estimateFeesPerGas(fr,br)}async function internal_estimateFeesPerGas(fr,br){var Jr,Xr;const{block:wr,chain:Er=fr.chain,request:kr,type:jr="eip1559"}=br||{},Br=await(async()=>{var En,wn;return typeof((En=Er==null?void 0:Er.fees)==null?void 0:En.baseFeeMultiplier)=="function"?Er.fees.baseFeeMultiplier({block:wr,client:fr,request:kr}):((wn=Er==null?void 0:Er.fees)==null?void 0:wn.baseFeeMultiplier)??1.2})();if(Br<1)throw new BaseFeeScalarError;const Wr=10**(((Jr=Br.toString().split(".")[1])==null?void 0:Jr.length)??0),Vr=En=>En*BigInt(Math.ceil(Br*Wr))/BigInt(Wr),Hr=wr||await getAction$1(fr,getBlock$1,"getBlock")({});if(typeof((Xr=Er==null?void 0:Er.fees)==null?void 0:Xr.estimateFeesPerGas)=="function"){const En=await Er.fees.estimateFeesPerGas({block:wr,client:fr,multiply:Vr,request:kr,type:jr});if(En!==null)return En}if(jr==="eip1559"){if(typeof Hr.baseFeePerGas!="bigint")throw new Eip1559FeesNotSupportedError;const En=typeof(kr==null?void 0:kr.maxPriorityFeePerGas)=="bigint"?kr.maxPriorityFeePerGas:await internal_estimateMaxPriorityFeePerGas(fr,{block:Hr,chain:Er,request:kr}),wn=Vr(Hr.baseFeePerGas);return{maxFeePerGas:(kr==null?void 0:kr.maxFeePerGas)??wn+En,maxPriorityFeePerGas:En}}return{gasPrice:(kr==null?void 0:kr.gasPrice)??Vr(await getAction$1(fr,getGasPrice$1,"getGasPrice")({}))}}async function getTransactionCount$1(fr,{address:br,blockTag:wr="latest",blockNumber:Er}){const kr=await fr.request({method:"eth_getTransactionCount",params:[br,Er?numberToHex(Er):wr]},{dedupe:!!Er});return hexToNumber$2(kr)}function blobsToCommitments$1(fr){const{kzg:br}=fr,wr=fr.to??(typeof fr.blobs[0]=="string"?"hex":"bytes"),Er=typeof fr.blobs[0]=="string"?fr.blobs.map(jr=>hexToBytes$4(jr)):fr.blobs,kr=[];for(const jr of Er)kr.push(Uint8Array.from(br.blobToKzgCommitment(jr)));return wr==="bytes"?kr:kr.map(jr=>bytesToHex$4(jr))}function blobsToProofs$1(fr){const{kzg:br}=fr,wr=fr.to??(typeof fr.blobs[0]=="string"?"hex":"bytes"),Er=typeof fr.blobs[0]=="string"?fr.blobs.map(Br=>hexToBytes$4(Br)):fr.blobs,kr=typeof fr.commitments[0]=="string"?fr.commitments.map(Br=>hexToBytes$4(Br)):fr.commitments,jr=[];for(let Br=0;BrbytesToHex$4(Br))}function setBigUint64$2(fr,br,wr,Er){if(typeof fr.setBigUint64=="function")return fr.setBigUint64(br,wr,Er);const kr=BigInt(32),jr=BigInt(4294967295),Br=Number(wr>>kr&jr),qr=Number(wr&jr),Wr=Er?4:0,Vr=Er?0:4;fr.setUint32(br+Wr,Br,Er),fr.setUint32(br+Vr,qr,Er)}const Chi$2=(fr,br,wr)=>fr&br^~fr&wr,Maj$2=(fr,br,wr)=>fr&br^fr&wr^br≀let HashMD$2=class extends Hash$3{constructor(br,wr,Er,kr){super(),this.blockLen=br,this.outputLen=wr,this.padOffset=Er,this.isLE=kr,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(br),this.view=createView$2(this.buffer)}update(br){exists(this);const{view:wr,buffer:Er,blockLen:kr}=this;br=toBytes$3(br);const jr=br.length;for(let Br=0;Brkr-Br&&(this.process(Er,0),Br=0);for(let Zr=Br;ZrHr.length)throw new Error("_sha2: outputLen bigger than state");for(let Zr=0;Zr>>3,wn=rotr$2(Xr,17)^rotr$2(Xr,19)^Xr>>>10;SHA256_W$2[Zr]=wn+SHA256_W$2[Zr-7]+En+SHA256_W$2[Zr-16]|0}let{A:Er,B:kr,C:jr,D:Br,E:qr,F:Wr,G:Vr,H:Hr}=this;for(let Zr=0;Zr<64;Zr++){const Jr=rotr$2(qr,6)^rotr$2(qr,11)^rotr$2(qr,25),Xr=Hr+Jr+Chi$2(qr,Wr,Vr)+SHA256_K$2[Zr]+SHA256_W$2[Zr]|0,wn=(rotr$2(Er,2)^rotr$2(Er,13)^rotr$2(Er,22))+Maj$2(Er,kr,jr)|0;Hr=Vr,Vr=Wr,Wr=qr,qr=Br+Xr|0,Br=jr,jr=kr,kr=Er,Er=Xr+wn|0}Er=Er+this.A|0,kr=kr+this.B|0,jr=jr+this.C|0,Br=Br+this.D|0,qr=qr+this.E|0,Wr=Wr+this.F|0,Vr=Vr+this.G|0,Hr=Hr+this.H|0,this.set(Er,kr,jr,Br,qr,Wr,Vr,Hr)}roundClean(){SHA256_W$2.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const sha256$a=wrapConstructor$2(()=>new SHA256$2);function sha256$9(fr,br){const wr=br||"hex",Er=sha256$a(isHex$1(fr,{strict:!1})?toBytes$4(fr):fr);return wr==="bytes"?Er:toHex$1(Er)}function commitmentToVersionedHash$1(fr){const{commitment:br,version:wr=1}=fr,Er=fr.to??(typeof br=="string"?"hex":"bytes"),kr=sha256$9(br,"bytes");return kr.set([wr],0),Er==="bytes"?kr:bytesToHex$4(kr)}function commitmentsToVersionedHashes$1(fr){const{commitments:br,version:wr}=fr,Er=fr.to??(typeof br[0]=="string"?"hex":"bytes"),kr=[];for(const jr of br)kr.push(commitmentToVersionedHash$1({commitment:jr,to:Er,version:wr}));return kr}const blobsPerTransaction=6,bytesPerFieldElement=32,fieldElementsPerBlob=4096,bytesPerBlob=bytesPerFieldElement*fieldElementsPerBlob,maxBytesPerTransaction=bytesPerBlob*blobsPerTransaction-1-1*fieldElementsPerBlob*blobsPerTransaction,versionedHashVersionKzg=1;class BlobSizeTooLargeError extends BaseError{constructor({maxSize:br,size:wr}){super("Blob size is too large.",{metaMessages:[`Max: ${br} bytes`,`Given: ${wr} bytes`],name:"BlobSizeTooLargeError"})}}class EmptyBlobError extends BaseError{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class InvalidVersionedHashSizeError extends BaseError{constructor({hash:br,size:wr}){super(`Versioned hash "${br}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${wr}`],name:"InvalidVersionedHashSizeError"})}}class InvalidVersionedHashVersionError extends BaseError{constructor({hash:br,version:wr}){super(`Versioned hash "${br}" version is invalid.`,{metaMessages:[`Expected: ${versionedHashVersionKzg}`,`Received: ${wr}`],name:"InvalidVersionedHashVersionError"})}}function toBlobs$1(fr){const br=fr.to??(typeof fr.data=="string"?"hex":"bytes"),wr=typeof fr.data=="string"?hexToBytes$4(fr.data):fr.data,Er=size$2(wr);if(!Er)throw new EmptyBlobError;if(Er>maxBytesPerTransaction)throw new BlobSizeTooLargeError({maxSize:maxBytesPerTransaction,size:Er});const kr=[];let jr=!0,Br=0;for(;jr;){const qr=createCursor(new Uint8Array(bytesPerBlob));let Wr=0;for(;Wrqr.bytes):kr.map(qr=>bytesToHex$4(qr.bytes))}function toBlobSidecars$1(fr){const{data:br,kzg:wr,to:Er}=fr,kr=fr.blobs??toBlobs$1({data:br,to:Er}),jr=fr.commitments??blobsToCommitments$1({blobs:kr,kzg:wr,to:Er}),Br=fr.proofs??blobsToProofs$1({blobs:kr,commitments:jr,kzg:wr,to:Er}),qr=[];for(let Wr=0;Wr"u"&&Zr)if(Wr){const Tn=await $n();Jr.nonce=await Wr.consume({address:Zr.address,chainId:Tn,client:fr})}else Jr.nonce=await getAction$1(fr,getTransactionCount$1,"getTransactionCount")({address:Zr.address,blockTag:"pending"});if((Vr.includes("fees")||Vr.includes("type"))&&typeof Hr>"u")try{Jr.type=getTransactionType$1(Jr)}catch{const Tn=await En();Jr.type=typeof(Tn==null?void 0:Tn.baseFeePerGas)=="bigint"?"eip1559":"legacy"}if(Vr.includes("fees"))if(Jr.type!=="legacy"&&Jr.type!=="eip2930"){if(typeof Jr.maxFeePerGas>"u"||typeof Jr.maxPriorityFeePerGas>"u"){const Tn=await En(),{maxFeePerGas:In,maxPriorityFeePerGas:jn}=await internal_estimateFeesPerGas(fr,{block:Tn,chain:kr,request:Jr});if(typeof br.maxPriorityFeePerGas>"u"&&br.maxFeePerGas&&br.maxFeePerGas"u"&&(Jr.gas=await getAction$1(fr,estimateGas$4,"estimateGas")({...Jr,account:Zr&&{address:Zr.address,type:"json-rpc"}})),assertRequest$1(Jr),delete Jr.parameters,Jr}async function getBalance$1(fr,{address:br,blockNumber:wr,blockTag:Er="latest"}){const kr=wr?numberToHex(wr):void 0,jr=await fr.request({method:"eth_getBalance",params:[br,kr||Er]});return BigInt(jr)}async function estimateGas$4(fr,br){var kr,jr,Br;const{account:wr=fr.account}=br,Er=wr?parseAccount$1(wr):void 0;try{let Gr=function(Sn){const{block:An,request:Pn,rpcStateOverride:Nn}=Sn;return fr.request({method:"eth_estimateGas",params:Nn?[Pn,An??"latest",Nn]:An?[Pn,An]:[Pn]})};const{accessList:qr,authorizationList:Wr,blobs:Vr,blobVersionedHashes:Hr,blockNumber:Zr,blockTag:Jr,data:Xr,gas:En,gasPrice:wn,maxFeePerBlobGas:$n,maxFeePerGas:Tn,maxPriorityFeePerGas:In,nonce:jn,value:Yn,stateOverride:ga,...na}=await prepareTransactionRequest$1(fr,{...br,parameters:(Er==null?void 0:Er.type)==="local"?void 0:["blobVersionedHashes"]}),ro=(Zr?numberToHex(Zr):void 0)||Jr,to=serializeStateOverride(ga),io=await(async()=>{if(na.to)return na.to;if(Wr&&Wr.length>0)return await recoverAuthorizationAddress$1({authorization:Wr[0]}).catch(()=>{throw new BaseError("`to` is required. Could not infer from `authorizationList`")})})();assertRequest$1(br);const no=(Br=(jr=(kr=fr.chain)==null?void 0:kr.formatters)==null?void 0:jr.transactionRequest)==null?void 0:Br.format,Rn=(no||formatTransactionRequest)({...extract$1(na,{format:no}),from:Er==null?void 0:Er.address,accessList:qr,authorizationList:Wr,blobs:Vr,blobVersionedHashes:Hr,data:Xr,gas:En,gasPrice:wn,maxFeePerBlobGas:$n,maxFeePerGas:Tn,maxPriorityFeePerGas:In,nonce:jn,to:io,value:Yn});let Yr=BigInt(await Gr({block:ro,request:Rn,rpcStateOverride:to}));if(Wr){const Sn=await getBalance$1(fr,{address:Rn.from}),An=await Promise.all(Wr.map(async Pn=>{const{contractAddress:Nn}=Pn,zn=await Gr({block:ro,request:{authorizationList:void 0,data:Xr,from:Er==null?void 0:Er.address,to:Nn,value:numberToHex(Sn)},rpcStateOverride:to}).catch(()=>100000n);return 2n*BigInt(zn)}));Yr+=An.reduce((Pn,Nn)=>Pn+Nn,0n)}return Yr}catch(qr){throw getEstimateGasError$1(qr,{...br,account:Er,chain:fr.chain})}}async function estimateContractGas$1(fr,br){const{abi:wr,address:Er,args:kr,functionName:jr,...Br}=br,qr=encodeFunctionData$1({abi:wr,args:kr,functionName:jr});try{return await getAction$1(fr,estimateGas$4,"estimateGas")({data:qr,to:Er,...Br})}catch(Wr){const Vr=Br.account?parseAccount$1(Br.account):void 0;throw getContractError$1(Wr,{abi:wr,address:Er,args:kr,docsPath:"/docs/contract/estimateContractGas",functionName:jr,sender:Vr==null?void 0:Vr.address})}}function isAddressEqual$1(fr,br){if(!isAddress$1(fr,{strict:!1}))throw new InvalidAddressError({address:fr});if(!isAddress$1(br,{strict:!1}))throw new InvalidAddressError({address:br});return fr.toLowerCase()===br.toLowerCase()}const docsPath$2="/docs/contract/decodeEventLog";function decodeEventLog$1(fr){const{abi:br,data:wr,strict:Er,topics:kr}=fr,jr=Er??!0,[Br,...qr]=kr;if(!Br)throw new AbiEventSignatureEmptyTopicsError({docsPath:docsPath$2});const Wr=br.length===1?br[0]:br.find(wn=>wn.type==="event"&&Br===toEventSelector$1(formatAbiItem$1(wn)));if(!(Wr&&"name"in Wr)||Wr.type!=="event")throw new AbiEventSignatureNotFoundError(Br,{docsPath:docsPath$2});const{name:Vr,inputs:Hr}=Wr,Zr=Hr==null?void 0:Hr.some(wn=>!("name"in wn&&wn.name));let Jr=Zr?[]:{};const Xr=Hr.filter(wn=>"indexed"in wn&&wn.indexed);for(let wn=0;wn!("indexed"in wn&&wn.indexed));if(En.length>0){if(wr&&wr!=="0x")try{const wn=decodeAbiParameters$1(En,wr);if(wn)if(Zr)Jr=[...Jr,...wn];else for(let $n=0;$n0?Jr:void 0}}function decodeTopic({param:fr,value:br}){return fr.type==="string"||fr.type==="bytes"||fr.type==="tuple"||fr.type.match(/^(.*)\[(\d+)?\]$/)?br:(decodeAbiParameters$1([fr],br)||[])[0]}function parseEventLogs$1(fr){const{abi:br,args:wr,logs:Er,strict:kr=!0}=fr,jr=(()=>{if(fr.eventName)return Array.isArray(fr.eventName)?fr.eventName:[fr.eventName]})();return Er.map(Br=>{var qr;try{const Wr=br.find(Hr=>Hr.type==="event"&&Br.topics[0]===toEventSelector$1(Hr));if(!Wr)return null;const Vr=decodeEventLog$1({...Br,abi:[Wr],strict:kr});return jr&&!jr.includes(Vr.eventName)||!includesArgs({args:Vr.args,inputs:Wr.inputs,matchArgs:wr})?null:{...Vr,...Br}}catch(Wr){let Vr,Hr;if(Wr instanceof AbiEventSignatureNotFoundError)return null;if(Wr instanceof DecodeLogDataMismatch||Wr instanceof DecodeLogTopicsMismatch){if(kr)return null;Vr=Wr.abiItem.name,Hr=(qr=Wr.abiItem.inputs)==null?void 0:qr.some(Zr=>!("name"in Zr&&Zr.name))}return{...Br,args:Hr?[]:{},eventName:Vr}}}).filter(Boolean)}function includesArgs(fr){const{args:br,inputs:wr,matchArgs:Er}=fr;if(!Er)return!0;if(!br)return!1;function kr(jr,Br,qr){try{return jr.type==="address"?isAddressEqual$1(Br,qr):jr.type==="string"||jr.type==="bytes"?keccak256$1(toBytes$4(Br))===qr:Br===qr}catch{return!1}}return Array.isArray(br)&&Array.isArray(Er)?Er.every((jr,Br)=>{if(jr==null)return!0;const qr=wr[Br];return qr?(Array.isArray(jr)?jr:[jr]).some(Vr=>kr(qr,Vr,br[Br])):!1}):typeof br=="object"&&!Array.isArray(br)&&typeof Er=="object"&&!Array.isArray(Er)?Object.entries(Er).every(([jr,Br])=>{if(Br==null)return!0;const qr=wr.find(Vr=>Vr.name===jr);return qr?(Array.isArray(Br)?Br:[Br]).some(Vr=>kr(qr,Vr,br[jr])):!1}):!1}function formatLog(fr,{args:br,eventName:wr}={}){return{...fr,blockHash:fr.blockHash?fr.blockHash:null,blockNumber:fr.blockNumber?BigInt(fr.blockNumber):null,logIndex:fr.logIndex?Number(fr.logIndex):null,transactionHash:fr.transactionHash?fr.transactionHash:null,transactionIndex:fr.transactionIndex?Number(fr.transactionIndex):null,...wr?{args:br,eventName:wr}:{}}}async function getLogs$1(fr,{address:br,blockHash:wr,fromBlock:Er,toBlock:kr,event:jr,events:Br,args:qr,strict:Wr}={}){const Vr=Wr??!1,Hr=Br??(jr?[jr]:void 0);let Zr=[];Hr&&(Zr=[Hr.flatMap(wn=>encodeEventTopics$1({abi:[wn],eventName:wn.name,args:Br?void 0:qr}))],jr&&(Zr=Zr[0]));let Jr;wr?Jr=await fr.request({method:"eth_getLogs",params:[{address:br,topics:Zr,blockHash:wr}]}):Jr=await fr.request({method:"eth_getLogs",params:[{address:br,topics:Zr,fromBlock:typeof Er=="bigint"?numberToHex(Er):Er,toBlock:typeof kr=="bigint"?numberToHex(kr):kr}]});const Xr=Jr.map(En=>formatLog(En));return Hr?parseEventLogs$1({abi:Hr,args:qr,logs:Xr,strict:Vr}):Xr}async function getContractEvents$1(fr,br){const{abi:wr,address:Er,args:kr,blockHash:jr,eventName:Br,fromBlock:qr,toBlock:Wr,strict:Vr}=br,Hr=Br?getAbiItem$1({abi:wr,name:Br}):void 0,Zr=Hr?void 0:wr.filter(Jr=>Jr.type==="event");return getAction$1(fr,getLogs$1,"getLogs")({address:Er,args:kr,blockHash:jr,event:Hr,events:Zr,fromBlock:qr,toBlock:Wr,strict:Vr})}const docsPath$1="/docs/contract/decodeFunctionResult";function decodeFunctionResult$1(fr){const{abi:br,args:wr,functionName:Er,data:kr}=fr;let jr=br[0];if(Er){const qr=getAbiItem$1({abi:br,args:wr,name:Er});if(!qr)throw new AbiFunctionNotFoundError(Er,{docsPath:docsPath$1});jr=qr}if(jr.type!=="function")throw new AbiFunctionNotFoundError(void 0,{docsPath:docsPath$1});if(!jr.outputs)throw new AbiFunctionOutputsNotFoundError(jr.name,{docsPath:docsPath$1});const Br=decodeAbiParameters$1(jr.outputs,kr);if(Br&&Br.length>1)return Br;if(Br&&Br.length===1)return Br[0]}const multicall3Abi=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"}],universalResolverErrors=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],universalResolverResolveAbi=[...universalResolverErrors,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],universalResolverReverseAbi=[...universalResolverErrors,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],textResolverAbi=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],addressResolverAbi=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],universalSignatureValidatorAbi=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],aggregate3Signature="0x82ad56cb",deploylessCallViaBytecodeBytecode="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",deploylessCallViaFactoryBytecode="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",universalSignatureValidatorByteCode="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class ChainDoesNotSupportContract extends BaseError{constructor({blockNumber:br,chain:wr,contract:Er}){super(`Chain "${wr.name}" does not support contract "${Er.name}".`,{metaMessages:["This could be due to any of the following:",...br&&Er.blockCreated&&Er.blockCreated>br?[`- The contract "${Er.name}" was not deployed until block ${Er.blockCreated} (current block ${br}).`]:[`- The chain does not have the contract "${Er.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class ChainMismatchError extends BaseError{constructor({chain:br,currentChainId:wr}){super(`The current chain of the wallet (id: ${wr}) does not match the target chain for the transaction (id: ${br.id} – ${br.name}).`,{metaMessages:[`Current Chain ID: ${wr}`,`Expected Chain ID: ${br.id} – ${br.name}`],name:"ChainMismatchError"})}}class ChainNotFoundError extends BaseError{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` -`),{name:"ChainNotFoundError"})}}class ClientChainNotConfiguredError extends BaseError{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class InvalidChainIdError extends BaseError{constructor({chainId:br}){super(typeof br=="number"?`Chain ID "${br}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const docsPath="/docs/contract/encodeDeployData";function encodeDeployData$1(fr){const{abi:br,args:wr,bytecode:Er}=fr;if(!wr||wr.length===0)return Er;const kr=br.find(Br=>"type"in Br&&Br.type==="constructor");if(!kr)throw new AbiConstructorNotFoundError({docsPath});if(!("inputs"in kr))throw new AbiConstructorParamsNotFoundError({docsPath});if(!kr.inputs||kr.inputs.length===0)throw new AbiConstructorParamsNotFoundError({docsPath});const jr=encodeAbiParameters$1(kr.inputs,wr);return concatHex([Er,jr])}function getChainContractAddress$1({blockNumber:fr,chain:br,contract:wr}){var kr;const Er=(kr=br==null?void 0:br.contracts)==null?void 0:kr[wr];if(!Er)throw new ChainDoesNotSupportContract({chain:br,contract:{name:wr}});if(fr&&Er.blockCreated&&Er.blockCreated>fr)throw new ChainDoesNotSupportContract({blockNumber:fr,chain:br,contract:{name:wr,blockCreated:Er.blockCreated}});return Er.address}function getCallError$1(fr,{docsPath:br,...wr}){const Er=(()=>{const kr=getNodeError$1(fr,wr);return kr instanceof UnknownNodeError?fr:kr})();return new CallExecutionError(Er,{docsPath:br,...wr})}function withResolvers$1(){let fr=()=>{},br=()=>{};return{promise:new Promise((Er,kr)=>{fr=Er,br=kr}),resolve:fr,reject:br}}const schedulerCache=new Map;function createBatchScheduler$1({fn:fr,id:br,shouldSplitBatch:wr,wait:Er=0,sort:kr}){const jr=async()=>{const Hr=Wr();Br();const Zr=Hr.map(({args:Jr})=>Jr);Zr.length!==0&&fr(Zr).then(Jr=>{kr&&Array.isArray(Jr)&&Jr.sort(kr);for(let Xr=0;Xr{for(let Xr=0;XrschedulerCache.delete(br),qr=()=>Wr().map(({args:Hr})=>Hr),Wr=()=>schedulerCache.get(br)||[],Vr=Hr=>schedulerCache.set(br,[...Wr(),Hr]);return{flush:Br,async schedule(Hr){const{promise:Zr,resolve:Jr,reject:Xr}=withResolvers$1();return(wr==null?void 0:wr([...qr(),Hr]))&&jr(),Wr().length>0?(Vr({args:Hr,resolve:Jr,reject:Xr}),Zr):(Vr({args:Hr,resolve:Jr,reject:Xr}),setTimeout(jr,Er),Zr)}}}async function call$1(fr,br){var no,$a,Rn,Gr;const{account:wr=fr.account,batch:Er=!!((no=fr.batch)!=null&&no.multicall),blockNumber:kr,blockTag:jr="latest",accessList:Br,blobs:qr,code:Wr,data:Vr,factory:Hr,factoryData:Zr,gas:Jr,gasPrice:Xr,maxFeePerBlobGas:En,maxFeePerGas:wn,maxPriorityFeePerGas:$n,nonce:Tn,to:In,value:jn,stateOverride:Yn,...ga}=br,na=wr?parseAccount$1(wr):void 0;if(Wr&&(Hr||Zr))throw new BaseError("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(Wr&&In)throw new BaseError("Cannot provide both `code` & `to` as parameters.");const _i=Wr&&Vr,ro=Hr&&Zr&&In&&Vr,to=_i||ro,io=_i?toDeploylessCallViaBytecodeData({code:Wr,data:Vr}):ro?toDeploylessCallViaFactoryData({data:Vr,factory:Hr,factoryData:Zr,to:In}):Vr;try{assertRequest$1(br);const Sn=(kr?numberToHex(kr):void 0)||jr,An=serializeStateOverride(Yn),Pn=(Gr=(Rn=($a=fr.chain)==null?void 0:$a.formatters)==null?void 0:Rn.transactionRequest)==null?void 0:Gr.format,zn=(Pn||formatTransactionRequest)({...extract$1(ga,{format:Pn}),from:na==null?void 0:na.address,accessList:Br,blobs:qr,data:io,gas:Jr,gasPrice:Xr,maxFeePerBlobGas:En,maxFeePerGas:wn,maxPriorityFeePerGas:$n,nonce:Tn,to:to?void 0:In,value:jn});if(Er&&shouldPerformMulticall({request:zn})&&!An)try{return await scheduleMulticall(fr,{...zn,blockNumber:kr,blockTag:jr})}catch(_n){if(!(_n instanceof ClientChainNotConfiguredError)&&!(_n instanceof ChainDoesNotSupportContract))throw _n}const On=await fr.request({method:"eth_call",params:An?[zn,Sn,An]:[zn,Sn]});return On==="0x"?{data:void 0}:{data:On}}catch(Yr){const Sn=getRevertErrorData(Yr),{offchainLookup:An,offchainLookupSignature:Pn}=await __vitePreload(async()=>{const{offchainLookup:Nn,offchainLookupSignature:zn}=await import("./ccip-BuUYLUEo.js");return{offchainLookup:Nn,offchainLookupSignature:zn}},[]);if(fr.ccipRead!==!1&&(Sn==null?void 0:Sn.slice(0,10))===Pn&&In)return{data:await An(fr,{data:Sn,to:In})};throw to&&(Sn==null?void 0:Sn.slice(0,10))==="0x101bb98d"?new CounterfactualDeploymentFailedError({factory:Hr}):getCallError$1(Yr,{...br,account:na,chain:fr.chain})}}function shouldPerformMulticall({request:fr}){const{data:br,to:wr,...Er}=fr;return!(!br||br.startsWith(aggregate3Signature)||!wr||Object.values(Er).filter(kr=>typeof kr<"u").length>0)}async function scheduleMulticall(fr,br){var wn;const{batchSize:wr=1024,wait:Er=0}=typeof((wn=fr.batch)==null?void 0:wn.multicall)=="object"?fr.batch.multicall:{},{blockNumber:kr,blockTag:jr="latest",data:Br,multicallAddress:qr,to:Wr}=br;let Vr=qr;if(!Vr){if(!fr.chain)throw new ClientChainNotConfiguredError;Vr=getChainContractAddress$1({blockNumber:kr,chain:fr.chain,contract:"multicall3"})}const Zr=(kr?numberToHex(kr):void 0)||jr,{schedule:Jr}=createBatchScheduler$1({id:`${fr.uid}.${Zr}`,wait:Er,shouldSplitBatch($n){return $n.reduce((In,{data:jn})=>In+(jn.length-2),0)>wr*2},fn:async $n=>{const Tn=$n.map(Yn=>({allowFailure:!0,callData:Yn.data,target:Yn.to})),In=encodeFunctionData$1({abi:multicall3Abi,args:[Tn],functionName:"aggregate3"}),jn=await fr.request({method:"eth_call",params:[{data:In,to:Vr},Zr]});return decodeFunctionResult$1({abi:multicall3Abi,args:[Tn],functionName:"aggregate3",data:jn||"0x"})}}),[{returnData:Xr,success:En}]=await Jr({data:Br,to:Wr});if(!En)throw new RawContractError({data:Xr});return Xr==="0x"?{data:void 0}:{data:Xr}}function toDeploylessCallViaBytecodeData(fr){const{code:br,data:wr}=fr;return encodeDeployData$1({abi:parseAbi(["constructor(bytes, bytes)"]),bytecode:deploylessCallViaBytecodeBytecode,args:[br,wr]})}function toDeploylessCallViaFactoryData(fr){const{data:br,factory:wr,factoryData:Er,to:kr}=fr;return encodeDeployData$1({abi:parseAbi(["constructor(address, bytes, address, bytes)"]),bytecode:deploylessCallViaFactoryBytecode,args:[kr,br,wr,Er]})}function getRevertErrorData(fr){var wr;if(!(fr instanceof BaseError))return;const br=fr.walk();return typeof(br==null?void 0:br.data)=="object"?(wr=br.data)==null?void 0:wr.data:br.data}async function readContract$1(fr,br){const{abi:wr,address:Er,args:kr,functionName:jr,...Br}=br,qr=encodeFunctionData$1({abi:wr,args:kr,functionName:jr});try{const{data:Wr}=await getAction$1(fr,call$1,"call")({...Br,data:qr,to:Er});return decodeFunctionResult$1({abi:wr,args:kr,functionName:jr,data:Wr||"0x"})}catch(Wr){throw getContractError$1(Wr,{abi:wr,address:Er,args:kr,docsPath:"/docs/contract/readContract",functionName:jr})}}async function simulateContract$1(fr,br){const{abi:wr,address:Er,args:kr,dataSuffix:jr,functionName:Br,...qr}=br,Wr=qr.account?parseAccount$1(qr.account):fr.account,Vr=encodeFunctionData$1({abi:wr,args:kr,functionName:Br});try{const{data:Hr}=await getAction$1(fr,call$1,"call")({batch:!1,data:`${Vr}${jr?jr.replace("0x",""):""}`,to:Er,...qr,account:Wr}),Zr=decodeFunctionResult$1({abi:wr,args:kr,functionName:Br,data:Hr||"0x"}),Jr=wr.filter(Xr=>"name"in Xr&&Xr.name===br.functionName);return{result:Zr,request:{abi:Jr,address:Er,args:kr,dataSuffix:jr,functionName:Br,...qr,account:Wr}}}catch(Hr){throw getContractError$1(Hr,{abi:wr,address:Er,args:kr,docsPath:"/docs/contract/simulateContract",functionName:Br,sender:Wr==null?void 0:Wr.address})}}const listenersCache=new Map,cleanupCache=new Map;let callbackCount=0;function observe$1(fr,br,wr){const Er=++callbackCount,kr=()=>listenersCache.get(fr)||[],jr=()=>{const Hr=kr();listenersCache.set(fr,Hr.filter(Zr=>Zr.id!==Er))},Br=()=>{const Hr=cleanupCache.get(fr);kr().length===1&&Hr&&Hr(),jr()},qr=kr();if(listenersCache.set(fr,[...qr,{id:Er,fns:br}]),qr&&qr.length>0)return Br;const Wr={};for(const Hr in br)Wr[Hr]=(...Zr)=>{var Xr,En;const Jr=kr();if(Jr.length!==0)for(const wn of Jr)(En=(Xr=wn.fns)[Hr])==null||En.call(Xr,...Zr)};const Vr=wr(Wr);return typeof Vr=="function"&&cleanupCache.set(fr,Vr),Br}async function wait$1(fr){return new Promise(br=>setTimeout(br,fr))}function poll$1(fr,{emitOnBegin:br,initialWaitTime:wr,interval:Er}){let kr=!0;const jr=()=>kr=!1;return(async()=>{let qr;br&&(qr=await fr({unpoll:jr}));const Wr=await(wr==null?void 0:wr(qr))??Er;await wait$1(Wr);const Vr=async()=>{kr&&(await fr({unpoll:jr}),await wait$1(Er),Vr())};Vr()})(),jr}const promiseCache$1=new Map,responseCache=new Map;function getCache(fr){const br=(kr,jr)=>({clear:()=>jr.delete(kr),get:()=>jr.get(kr),set:Br=>jr.set(kr,Br)}),wr=br(fr,promiseCache$1),Er=br(fr,responseCache);return{clear:()=>{wr.clear(),Er.clear()},promise:wr,response:Er}}async function withCache$1(fr,{cacheKey:br,cacheTime:wr=Number.POSITIVE_INFINITY}){const Er=getCache(br),kr=Er.response.get();if(kr&&wr>0&&new Date().getTime()-kr.created.getTime()`blockNumber.${fr}`;async function getBlockNumber$1(fr,{cacheTime:br=fr.cacheTime}={}){const wr=await withCache$1(()=>fr.request({method:"eth_blockNumber"}),{cacheKey:cacheKey(fr.uid),cacheTime:br});return BigInt(wr)}async function getFilterChanges$1(fr,{filter:br}){const wr="strict"in br&&br.strict,Er=await br.request({method:"eth_getFilterChanges",params:[br.id]});if(typeof Er[0]=="string")return Er;const kr=Er.map(jr=>formatLog(jr));return!("abi"in br)||!br.abi?kr:parseEventLogs$1({abi:br.abi,logs:kr,strict:wr})}async function uninstallFilter$1(fr,{filter:br}){return br.request({method:"eth_uninstallFilter",params:[br.id]})}function watchContractEvent$1(fr,br){const{abi:wr,address:Er,args:kr,batch:jr=!0,eventName:Br,fromBlock:qr,onError:Wr,onLogs:Vr,poll:Hr,pollingInterval:Zr=fr.pollingInterval,strict:Jr}=br;return(typeof Hr<"u"?Hr:typeof qr=="bigint"?!0:!(fr.transport.type==="webSocket"||fr.transport.type==="fallback"&&fr.transport.transports[0].config.type==="webSocket"))?(()=>{const $n=Jr??!1,Tn=stringify$5(["watchContractEvent",Er,kr,jr,fr.uid,Br,Zr,$n,qr]);return observe$1(Tn,{onLogs:Vr,onError:Wr},In=>{let jn;qr!==void 0&&(jn=qr-1n);let Yn,ga=!1;const na=poll$1(async()=>{var _i;if(!ga){try{Yn=await getAction$1(fr,createContractEventFilter$1,"createContractEventFilter")({abi:wr,address:Er,args:kr,eventName:Br,strict:$n,fromBlock:qr})}catch{}ga=!0;return}try{let ro;if(Yn)ro=await getAction$1(fr,getFilterChanges$1,"getFilterChanges")({filter:Yn});else{const to=await getAction$1(fr,getBlockNumber$1,"getBlockNumber")({});jn&&jn{Yn&&await getAction$1(fr,uninstallFilter$1,"uninstallFilter")({filter:Yn}),na()}})})():(()=>{const $n=Jr??!1,Tn=stringify$5(["watchContractEvent",Er,kr,jr,fr.uid,Br,Zr,$n]);let In=!0,jn=()=>In=!1;return observe$1(Tn,{onLogs:Vr,onError:Wr},Yn=>((async()=>{try{const ga=(()=>{if(fr.transport.type==="fallback"){const ro=fr.transport.transports.find(to=>to.config.type==="webSocket");return ro?ro.value:fr.transport}return fr.transport})(),na=Br?encodeEventTopics$1({abi:wr,eventName:Br,args:kr}):[],{unsubscribe:_i}=await ga.subscribe({params:["logs",{address:Er,topics:na}],onData(ro){var io;if(!In)return;const to=ro.result;try{const{eventName:no,args:$a}=decodeEventLog$1({abi:wr,data:to.data,topics:to.topics,strict:Jr}),Rn=formatLog(to,{args:$a,eventName:no});Yn.onLogs([Rn])}catch(no){let $a,Rn;if(no instanceof DecodeLogDataMismatch||no instanceof DecodeLogTopicsMismatch){if(Jr)return;$a=no.abiItem.name,Rn=(io=no.abiItem.inputs)==null?void 0:io.some(Yr=>!("name"in Yr&&Yr.name))}const Gr=formatLog(to,{args:Rn?[]:{},eventName:$a});Yn.onLogs([Gr])}},onError(ro){var to;(to=Yn.onError)==null||to.call(Yn,ro)}});jn=_i,In||jn()}catch(ga){Wr==null||Wr(ga)}})(),()=>jn()))})()}class AccountNotFoundError extends BaseError{constructor({docsPath:br}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{name:"ChainNotFoundError"})}}class ClientChainNotConfiguredError extends BaseError{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class InvalidChainIdError extends BaseError{constructor({chainId:br}){super(typeof br=="number"?`Chain ID "${br}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const docsPath="/docs/contract/encodeDeployData";function encodeDeployData$1(fr){const{abi:br,args:wr,bytecode:Er}=fr;if(!wr||wr.length===0)return Er;const kr=br.find(Br=>"type"in Br&&Br.type==="constructor");if(!kr)throw new AbiConstructorNotFoundError({docsPath});if(!("inputs"in kr))throw new AbiConstructorParamsNotFoundError({docsPath});if(!kr.inputs||kr.inputs.length===0)throw new AbiConstructorParamsNotFoundError({docsPath});const jr=encodeAbiParameters$1(kr.inputs,wr);return concatHex([Er,jr])}function getChainContractAddress$1({blockNumber:fr,chain:br,contract:wr}){var kr;const Er=(kr=br==null?void 0:br.contracts)==null?void 0:kr[wr];if(!Er)throw new ChainDoesNotSupportContract({chain:br,contract:{name:wr}});if(fr&&Er.blockCreated&&Er.blockCreated>fr)throw new ChainDoesNotSupportContract({blockNumber:fr,chain:br,contract:{name:wr,blockCreated:Er.blockCreated}});return Er.address}function getCallError$1(fr,{docsPath:br,...wr}){const Er=(()=>{const kr=getNodeError$1(fr,wr);return kr instanceof UnknownNodeError?fr:kr})();return new CallExecutionError(Er,{docsPath:br,...wr})}function withResolvers$1(){let fr=()=>{},br=()=>{};return{promise:new Promise((Er,kr)=>{fr=Er,br=kr}),resolve:fr,reject:br}}const schedulerCache=new Map;function createBatchScheduler$1({fn:fr,id:br,shouldSplitBatch:wr,wait:Er=0,sort:kr}){const jr=async()=>{const Hr=Wr();Br();const Zr=Hr.map(({args:Jr})=>Jr);Zr.length!==0&&fr(Zr).then(Jr=>{kr&&Array.isArray(Jr)&&Jr.sort(kr);for(let Xr=0;Xr{for(let Xr=0;XrschedulerCache.delete(br),qr=()=>Wr().map(({args:Hr})=>Hr),Wr=()=>schedulerCache.get(br)||[],Vr=Hr=>schedulerCache.set(br,[...Wr(),Hr]);return{flush:Br,async schedule(Hr){const{promise:Zr,resolve:Jr,reject:Xr}=withResolvers$1();return(wr==null?void 0:wr([...qr(),Hr]))&&jr(),Wr().length>0?(Vr({args:Hr,resolve:Jr,reject:Xr}),Zr):(Vr({args:Hr,resolve:Jr,reject:Xr}),setTimeout(jr,Er),Zr)}}}async function call$1(fr,br){var no,$a,Rn,Gr;const{account:wr=fr.account,batch:Er=!!((no=fr.batch)!=null&&no.multicall),blockNumber:kr,blockTag:jr="latest",accessList:Br,blobs:qr,code:Wr,data:Vr,factory:Hr,factoryData:Zr,gas:Jr,gasPrice:Xr,maxFeePerBlobGas:En,maxFeePerGas:wn,maxPriorityFeePerGas:$n,nonce:Tn,to:In,value:jn,stateOverride:Yn,...ga}=br,na=wr?parseAccount$1(wr):void 0;if(Wr&&(Hr||Zr))throw new BaseError("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(Wr&&In)throw new BaseError("Cannot provide both `code` & `to` as parameters.");const _i=Wr&&Vr,ro=Hr&&Zr&&In&&Vr,to=_i||ro,io=_i?toDeploylessCallViaBytecodeData({code:Wr,data:Vr}):ro?toDeploylessCallViaFactoryData({data:Vr,factory:Hr,factoryData:Zr,to:In}):Vr;try{assertRequest$1(br);const Sn=(kr?numberToHex(kr):void 0)||jr,An=serializeStateOverride(Yn),Pn=(Gr=(Rn=($a=fr.chain)==null?void 0:$a.formatters)==null?void 0:Rn.transactionRequest)==null?void 0:Gr.format,zn=(Pn||formatTransactionRequest)({...extract$1(ga,{format:Pn}),from:na==null?void 0:na.address,accessList:Br,blobs:qr,data:io,gas:Jr,gasPrice:Xr,maxFeePerBlobGas:En,maxFeePerGas:wn,maxPriorityFeePerGas:$n,nonce:Tn,to:to?void 0:In,value:jn});if(Er&&shouldPerformMulticall({request:zn})&&!An)try{return await scheduleMulticall(fr,{...zn,blockNumber:kr,blockTag:jr})}catch(_n){if(!(_n instanceof ClientChainNotConfiguredError)&&!(_n instanceof ChainDoesNotSupportContract))throw _n}const On=await fr.request({method:"eth_call",params:An?[zn,Sn,An]:[zn,Sn]});return On==="0x"?{data:void 0}:{data:On}}catch(Yr){const Sn=getRevertErrorData(Yr),{offchainLookup:An,offchainLookupSignature:Pn}=await __vitePreload(async()=>{const{offchainLookup:Nn,offchainLookupSignature:zn}=await import("./ccip-d6sEp144.js");return{offchainLookup:Nn,offchainLookupSignature:zn}},[]);if(fr.ccipRead!==!1&&(Sn==null?void 0:Sn.slice(0,10))===Pn&&In)return{data:await An(fr,{data:Sn,to:In})};throw to&&(Sn==null?void 0:Sn.slice(0,10))==="0x101bb98d"?new CounterfactualDeploymentFailedError({factory:Hr}):getCallError$1(Yr,{...br,account:na,chain:fr.chain})}}function shouldPerformMulticall({request:fr}){const{data:br,to:wr,...Er}=fr;return!(!br||br.startsWith(aggregate3Signature)||!wr||Object.values(Er).filter(kr=>typeof kr<"u").length>0)}async function scheduleMulticall(fr,br){var wn;const{batchSize:wr=1024,wait:Er=0}=typeof((wn=fr.batch)==null?void 0:wn.multicall)=="object"?fr.batch.multicall:{},{blockNumber:kr,blockTag:jr="latest",data:Br,multicallAddress:qr,to:Wr}=br;let Vr=qr;if(!Vr){if(!fr.chain)throw new ClientChainNotConfiguredError;Vr=getChainContractAddress$1({blockNumber:kr,chain:fr.chain,contract:"multicall3"})}const Zr=(kr?numberToHex(kr):void 0)||jr,{schedule:Jr}=createBatchScheduler$1({id:`${fr.uid}.${Zr}`,wait:Er,shouldSplitBatch($n){return $n.reduce((In,{data:jn})=>In+(jn.length-2),0)>wr*2},fn:async $n=>{const Tn=$n.map(Yn=>({allowFailure:!0,callData:Yn.data,target:Yn.to})),In=encodeFunctionData$1({abi:multicall3Abi,args:[Tn],functionName:"aggregate3"}),jn=await fr.request({method:"eth_call",params:[{data:In,to:Vr},Zr]});return decodeFunctionResult$1({abi:multicall3Abi,args:[Tn],functionName:"aggregate3",data:jn||"0x"})}}),[{returnData:Xr,success:En}]=await Jr({data:Br,to:Wr});if(!En)throw new RawContractError({data:Xr});return Xr==="0x"?{data:void 0}:{data:Xr}}function toDeploylessCallViaBytecodeData(fr){const{code:br,data:wr}=fr;return encodeDeployData$1({abi:parseAbi(["constructor(bytes, bytes)"]),bytecode:deploylessCallViaBytecodeBytecode,args:[br,wr]})}function toDeploylessCallViaFactoryData(fr){const{data:br,factory:wr,factoryData:Er,to:kr}=fr;return encodeDeployData$1({abi:parseAbi(["constructor(address, bytes, address, bytes)"]),bytecode:deploylessCallViaFactoryBytecode,args:[kr,br,wr,Er]})}function getRevertErrorData(fr){var wr;if(!(fr instanceof BaseError))return;const br=fr.walk();return typeof(br==null?void 0:br.data)=="object"?(wr=br.data)==null?void 0:wr.data:br.data}async function readContract$1(fr,br){const{abi:wr,address:Er,args:kr,functionName:jr,...Br}=br,qr=encodeFunctionData$1({abi:wr,args:kr,functionName:jr});try{const{data:Wr}=await getAction$1(fr,call$1,"call")({...Br,data:qr,to:Er});return decodeFunctionResult$1({abi:wr,args:kr,functionName:jr,data:Wr||"0x"})}catch(Wr){throw getContractError$1(Wr,{abi:wr,address:Er,args:kr,docsPath:"/docs/contract/readContract",functionName:jr})}}async function simulateContract$1(fr,br){const{abi:wr,address:Er,args:kr,dataSuffix:jr,functionName:Br,...qr}=br,Wr=qr.account?parseAccount$1(qr.account):fr.account,Vr=encodeFunctionData$1({abi:wr,args:kr,functionName:Br});try{const{data:Hr}=await getAction$1(fr,call$1,"call")({batch:!1,data:`${Vr}${jr?jr.replace("0x",""):""}`,to:Er,...qr,account:Wr}),Zr=decodeFunctionResult$1({abi:wr,args:kr,functionName:Br,data:Hr||"0x"}),Jr=wr.filter(Xr=>"name"in Xr&&Xr.name===br.functionName);return{result:Zr,request:{abi:Jr,address:Er,args:kr,dataSuffix:jr,functionName:Br,...qr,account:Wr}}}catch(Hr){throw getContractError$1(Hr,{abi:wr,address:Er,args:kr,docsPath:"/docs/contract/simulateContract",functionName:Br,sender:Wr==null?void 0:Wr.address})}}const listenersCache=new Map,cleanupCache=new Map;let callbackCount=0;function observe$1(fr,br,wr){const Er=++callbackCount,kr=()=>listenersCache.get(fr)||[],jr=()=>{const Hr=kr();listenersCache.set(fr,Hr.filter(Zr=>Zr.id!==Er))},Br=()=>{const Hr=cleanupCache.get(fr);kr().length===1&&Hr&&Hr(),jr()},qr=kr();if(listenersCache.set(fr,[...qr,{id:Er,fns:br}]),qr&&qr.length>0)return Br;const Wr={};for(const Hr in br)Wr[Hr]=(...Zr)=>{var Xr,En;const Jr=kr();if(Jr.length!==0)for(const wn of Jr)(En=(Xr=wn.fns)[Hr])==null||En.call(Xr,...Zr)};const Vr=wr(Wr);return typeof Vr=="function"&&cleanupCache.set(fr,Vr),Br}async function wait$1(fr){return new Promise(br=>setTimeout(br,fr))}function poll$1(fr,{emitOnBegin:br,initialWaitTime:wr,interval:Er}){let kr=!0;const jr=()=>kr=!1;return(async()=>{let qr;br&&(qr=await fr({unpoll:jr}));const Wr=await(wr==null?void 0:wr(qr))??Er;await wait$1(Wr);const Vr=async()=>{kr&&(await fr({unpoll:jr}),await wait$1(Er),Vr())};Vr()})(),jr}const promiseCache$1=new Map,responseCache=new Map;function getCache(fr){const br=(kr,jr)=>({clear:()=>jr.delete(kr),get:()=>jr.get(kr),set:Br=>jr.set(kr,Br)}),wr=br(fr,promiseCache$1),Er=br(fr,responseCache);return{clear:()=>{wr.clear(),Er.clear()},promise:wr,response:Er}}async function withCache$1(fr,{cacheKey:br,cacheTime:wr=Number.POSITIVE_INFINITY}){const Er=getCache(br),kr=Er.response.get();if(kr&&wr>0&&new Date().getTime()-kr.created.getTime()`blockNumber.${fr}`;async function getBlockNumber$1(fr,{cacheTime:br=fr.cacheTime}={}){const wr=await withCache$1(()=>fr.request({method:"eth_blockNumber"}),{cacheKey:cacheKey(fr.uid),cacheTime:br});return BigInt(wr)}async function getFilterChanges$1(fr,{filter:br}){const wr="strict"in br&&br.strict,Er=await br.request({method:"eth_getFilterChanges",params:[br.id]});if(typeof Er[0]=="string")return Er;const kr=Er.map(jr=>formatLog(jr));return!("abi"in br)||!br.abi?kr:parseEventLogs$1({abi:br.abi,logs:kr,strict:wr})}async function uninstallFilter$1(fr,{filter:br}){return br.request({method:"eth_uninstallFilter",params:[br.id]})}function watchContractEvent$1(fr,br){const{abi:wr,address:Er,args:kr,batch:jr=!0,eventName:Br,fromBlock:qr,onError:Wr,onLogs:Vr,poll:Hr,pollingInterval:Zr=fr.pollingInterval,strict:Jr}=br;return(typeof Hr<"u"?Hr:typeof qr=="bigint"?!0:!(fr.transport.type==="webSocket"||fr.transport.type==="fallback"&&fr.transport.transports[0].config.type==="webSocket"))?(()=>{const $n=Jr??!1,Tn=stringify$5(["watchContractEvent",Er,kr,jr,fr.uid,Br,Zr,$n,qr]);return observe$1(Tn,{onLogs:Vr,onError:Wr},In=>{let jn;qr!==void 0&&(jn=qr-1n);let Yn,ga=!1;const na=poll$1(async()=>{var _i;if(!ga){try{Yn=await getAction$1(fr,createContractEventFilter$1,"createContractEventFilter")({abi:wr,address:Er,args:kr,eventName:Br,strict:$n,fromBlock:qr})}catch{}ga=!0;return}try{let ro;if(Yn)ro=await getAction$1(fr,getFilterChanges$1,"getFilterChanges")({filter:Yn});else{const to=await getAction$1(fr,getBlockNumber$1,"getBlockNumber")({});jn&&jn{Yn&&await getAction$1(fr,uninstallFilter$1,"uninstallFilter")({filter:Yn}),na()}})})():(()=>{const $n=Jr??!1,Tn=stringify$5(["watchContractEvent",Er,kr,jr,fr.uid,Br,Zr,$n]);let In=!0,jn=()=>In=!1;return observe$1(Tn,{onLogs:Vr,onError:Wr},Yn=>((async()=>{try{const ga=(()=>{if(fr.transport.type==="fallback"){const ro=fr.transport.transports.find(to=>to.config.type==="webSocket");return ro?ro.value:fr.transport}return fr.transport})(),na=Br?encodeEventTopics$1({abi:wr,eventName:Br,args:kr}):[],{unsubscribe:_i}=await ga.subscribe({params:["logs",{address:Er,topics:na}],onData(ro){var io;if(!In)return;const to=ro.result;try{const{eventName:no,args:$a}=decodeEventLog$1({abi:wr,data:to.data,topics:to.topics,strict:Jr}),Rn=formatLog(to,{args:$a,eventName:no});Yn.onLogs([Rn])}catch(no){let $a,Rn;if(no instanceof DecodeLogDataMismatch||no instanceof DecodeLogTopicsMismatch){if(Jr)return;$a=no.abiItem.name,Rn=(io=no.abiItem.inputs)==null?void 0:io.some(Yr=>!("name"in Yr&&Yr.name))}const Gr=formatLog(to,{args:Rn?[]:{},eventName:$a});Yn.onLogs([Gr])}},onError(ro){var to;(to=Yn.onError)==null||to.call(Yn,ro)}});jn=_i,In||jn()}catch(ga){Wr==null||Wr(ga)}})(),()=>jn()))})()}class AccountNotFoundError extends BaseError{constructor({docsPath:br}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` `),{docsPath:br,docsSlug:"account",name:"AccountNotFoundError"})}}class AccountTypeNotSupportedError extends BaseError{constructor({docsPath:br,metaMessages:wr,type:Er}){super(`Account type "${Er}" is not supported.`,{docsPath:br,metaMessages:wr,name:"AccountTypeNotSupportedError"})}}function assertCurrentChain$1({chain:fr,currentChainId:br}){if(!fr)throw new ChainNotFoundError;if(br!==fr.id)throw new ChainMismatchError({chain:fr,currentChainId:br})}function getTransactionError$1(fr,{docsPath:br,...wr}){const Er=(()=>{const kr=getNodeError$1(fr,wr);return kr instanceof UnknownNodeError?fr:kr})();return new TransactionExecutionError(Er,{docsPath:br,...wr})}async function sendRawTransaction$1(fr,{serializedTransaction:br}){return fr.request({method:"eth_sendRawTransaction",params:[br]},{retryCount:0})}const supportsWalletNamespace=new LruMap(128);async function sendTransaction$1(fr,br){var Tn,In,jn,Yn;const{account:wr=fr.account,chain:Er=fr.chain,accessList:kr,authorizationList:jr,blobs:Br,data:qr,gas:Wr,gasPrice:Vr,maxFeePerBlobGas:Hr,maxFeePerGas:Zr,maxPriorityFeePerGas:Jr,nonce:Xr,value:En,...wn}=br;if(typeof wr>"u")throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/sendTransaction"});const $n=wr?parseAccount$1(wr):null;try{assertRequest$1(br);const ga=await(async()=>{if(br.to)return br.to;if(jr&&jr.length>0)return await recoverAuthorizationAddress$1({authorization:jr[0]}).catch(()=>{throw new BaseError("`to` is required. Could not infer from `authorizationList`.")})})();if(($n==null?void 0:$n.type)==="json-rpc"||$n===null){let na;Er!==null&&(na=await getAction$1(fr,getChainId$1,"getChainId")({}),assertCurrentChain$1({currentChainId:na,chain:Er}));const _i=(jn=(In=(Tn=fr.chain)==null?void 0:Tn.formatters)==null?void 0:In.transactionRequest)==null?void 0:jn.format,to=(_i||formatTransactionRequest)({...extract$1(wn,{format:_i}),accessList:kr,authorizationList:jr,blobs:Br,chainId:na,data:qr,from:$n==null?void 0:$n.address,gas:Wr,gasPrice:Vr,maxFeePerBlobGas:Hr,maxFeePerGas:Zr,maxPriorityFeePerGas:Jr,nonce:Xr,to:ga,value:En}),io=supportsWalletNamespace.get(fr.uid),no=io?"wallet_sendTransaction":"eth_sendTransaction";try{return await fr.request({method:no,params:[to]},{retryCount:0})}catch($a){if(io===!1)throw $a;const Rn=$a;if(Rn.name==="InvalidInputRpcError"||Rn.name==="InvalidParamsRpcError"||Rn.name==="MethodNotFoundRpcError"||Rn.name==="MethodNotSupportedRpcError")return await fr.request({method:"wallet_sendTransaction",params:[to]},{retryCount:0}).then(Gr=>(supportsWalletNamespace.set(fr.uid,!0),Gr)).catch(Gr=>{const Yr=Gr;throw Yr.name==="MethodNotFoundRpcError"||Yr.name==="MethodNotSupportedRpcError"?(supportsWalletNamespace.set(fr.uid,!1),Rn):Yr});throw Rn}}if(($n==null?void 0:$n.type)==="local"){const na=await getAction$1(fr,prepareTransactionRequest$1,"prepareTransactionRequest")({account:$n,accessList:kr,authorizationList:jr,blobs:Br,chain:Er,data:qr,gas:Wr,gasPrice:Vr,maxFeePerBlobGas:Hr,maxFeePerGas:Zr,maxPriorityFeePerGas:Jr,nonce:Xr,nonceManager:$n.nonceManager,parameters:[...defaultParameters,"sidecars"],value:En,...wn,to:ga}),_i=(Yn=Er==null?void 0:Er.serializers)==null?void 0:Yn.transaction,ro=await $n.signTransaction(na,{serializer:_i});return await getAction$1(fr,sendRawTransaction$1,"sendRawTransaction")({serializedTransaction:ro})}throw($n==null?void 0:$n.type)==="smart"?new AccountTypeNotSupportedError({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new AccountTypeNotSupportedError({docsPath:"/docs/actions/wallet/sendTransaction",type:$n==null?void 0:$n.type})}catch(ga){throw ga instanceof AccountTypeNotSupportedError?ga:getTransactionError$1(ga,{...br,account:$n,chain:br.chain||void 0})}}async function writeContract$1(fr,br){const{abi:wr,account:Er=fr.account,address:kr,args:jr,dataSuffix:Br,functionName:qr,...Wr}=br;if(typeof Er>"u")throw new AccountNotFoundError({docsPath:"/docs/contract/writeContract"});const Vr=Er?parseAccount$1(Er):null,Hr=encodeFunctionData$1({abi:wr,args:jr,functionName:qr});try{return await getAction$1(fr,sendTransaction$1,"sendTransaction")({data:`${Hr}${Br?Br.replace("0x",""):""}`,to:kr,account:Vr,...Wr})}catch(Zr){throw getContractError$1(Zr,{abi:wr,address:kr,args:jr,docsPath:"/docs/contract/writeContract",functionName:qr,sender:Vr==null?void 0:Vr.address})}}class Eip712DomainNotFoundError extends BaseError{constructor({address:br}){super(`No EIP-712 domain found on contract "${br}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${br}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function getEip712Domain$3(fr,br){const{address:wr,factory:Er,factoryData:kr}=br;try{const[jr,Br,qr,Wr,Vr,Hr,Zr]=await getAction$1(fr,readContract$1,"readContract")({abi:abi$3,address:wr,functionName:"eip712Domain",factory:Er,factoryData:kr});return{domain:{name:Br,version:qr,chainId:Number(Wr),verifyingContract:Vr,salt:Hr},extensions:Zr,fields:jr}}catch(jr){const Br=jr;throw Br.name==="ContractFunctionExecutionError"&&Br.cause.name==="ContractFunctionZeroDataError"?new Eip712DomainNotFoundError({address:wr}):Br}}const abi$3=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];async function addChain$1(fr,{chain:br}){const{id:wr,name:Er,nativeCurrency:kr,rpcUrls:jr,blockExplorers:Br}=br;await fr.request({method:"wallet_addEthereumChain",params:[{chainId:numberToHex(wr),chainName:Er,nativeCurrency:kr,rpcUrls:jr.default.http,blockExplorerUrls:Br?Object.values(Br).map(({url:qr})=>qr):void 0}]},{dedupe:!0,retryCount:0})}const size$1=256;let index=size$1,buffer$1;function uid$1(fr=11){if(!buffer$1||index+fr>size$1*2){buffer$1="",index=0;for(let br=0;br{const In=Tn($n);for(const Yn in En)delete In[Yn];const jn={...$n,...In};return Object.assign(jn,{extend:wn(jn)})}}return Object.assign(En,{extend:wn(En)})}const promiseCache=new LruMap(8192);function withDedupe$1(fr,{enabled:br=!0,id:wr}){if(!br||!wr)return fr();if(promiseCache.get(wr))return promiseCache.get(wr);const Er=fr().finally(()=>promiseCache.delete(wr));return promiseCache.set(wr,Er),Er}function withRetry$1(fr,{delay:br=100,retryCount:wr=2,shouldRetry:Er=()=>!0}={}){return new Promise((kr,jr)=>{const Br=async({count:qr=0}={})=>{const Wr=async({error:Vr})=>{const Hr=typeof br=="function"?br({count:qr,error:Vr}):br;Hr&&await wait$1(Hr),Br({count:qr+1})};try{const Vr=await fr();kr(Vr)}catch(Vr){if(qr{const{dedupe:kr=!1,retryDelay:jr=150,retryCount:Br=3,uid:qr}={...br,...Er},Wr=kr?keccak256$1(stringToHex(`${qr}.${stringify$5(wr)}`)):void 0;return withDedupe$1(()=>withRetry$1(async()=>{try{return await fr(wr)}catch(Vr){const Hr=Vr;switch(Hr.code){case ParseRpcError.code:throw new ParseRpcError(Hr);case InvalidRequestRpcError.code:throw new InvalidRequestRpcError(Hr);case MethodNotFoundRpcError.code:throw new MethodNotFoundRpcError(Hr,{method:wr.method});case InvalidParamsRpcError.code:throw new InvalidParamsRpcError(Hr);case InternalRpcError.code:throw new InternalRpcError(Hr);case InvalidInputRpcError.code:throw new InvalidInputRpcError(Hr);case ResourceNotFoundRpcError.code:throw new ResourceNotFoundRpcError(Hr);case ResourceUnavailableRpcError.code:throw new ResourceUnavailableRpcError(Hr);case TransactionRejectedRpcError.code:throw new TransactionRejectedRpcError(Hr);case MethodNotSupportedRpcError.code:throw new MethodNotSupportedRpcError(Hr,{method:wr.method});case LimitExceededRpcError.code:throw new LimitExceededRpcError(Hr);case JsonRpcVersionUnsupportedError.code:throw new JsonRpcVersionUnsupportedError(Hr);case UserRejectedRequestError.code:throw new UserRejectedRequestError(Hr);case UnauthorizedProviderError.code:throw new UnauthorizedProviderError(Hr);case UnsupportedProviderMethodError.code:throw new UnsupportedProviderMethodError(Hr);case ProviderDisconnectedError.code:throw new ProviderDisconnectedError(Hr);case ChainDisconnectedError.code:throw new ChainDisconnectedError(Hr);case SwitchChainError.code:throw new SwitchChainError(Hr);case 5e3:throw new UserRejectedRequestError(Hr);default:throw Vr instanceof BaseError?Vr:new UnknownRpcError(Hr)}}},{delay:({count:Vr,error:Hr})=>{var Zr;if(Hr&&Hr instanceof HttpRequestError){const Jr=(Zr=Hr==null?void 0:Hr.headers)==null?void 0:Zr.get("Retry-After");if(Jr!=null&&Jr.match(/\d/))return Number.parseInt(Jr)*1e3}return~~(1<shouldRetry(Vr)}),{enabled:kr,id:Wr})}}function shouldRetry(fr){return"code"in fr&&typeof fr.code=="number"?fr.code===-1||fr.code===LimitExceededRpcError.code||fr.code===InternalRpcError.code:fr instanceof HttpRequestError&&fr.status?fr.status===403||fr.status===408||fr.status===413||fr.status===429||fr.status===500||fr.status===502||fr.status===503||fr.status===504:!0}function createTransport$1({key:fr,name:br,request:wr,retryCount:Er=3,retryDelay:kr=150,timeout:jr,type:Br},qr){const Wr=uid$1();return{config:{key:fr,name:br,request:wr,retryCount:Er,retryDelay:kr,timeout:jr,type:Br},request:buildRequest$1(wr,{retryCount:Er,retryDelay:kr,uid:Wr}),value:qr}}function custom$1(fr,br={}){const{key:wr="custom",name:Er="Custom Provider",retryDelay:kr}=br;return({retryCount:jr})=>createTransport$1({key:wr,name:Er,request:fr.request.bind(fr),retryCount:br.retryCount??jr,retryDelay:kr,type:"custom"})}class UrlRequiredError extends BaseError{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function withTimeout$1(fr,{errorInstance:br=new Error("timed out"),timeout:wr,signal:Er}){return new Promise((kr,jr)=>{(async()=>{let Br;try{const qr=new AbortController;wr>0&&(Br=setTimeout(()=>{Er?qr.abort():jr(br)},wr)),kr(await fr({signal:(qr==null?void 0:qr.signal)||null}))}catch(qr){(qr==null?void 0:qr.name)==="AbortError"&&jr(br),jr(qr)}finally{clearTimeout(Br)}})()})}function createIdStore(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const idCache=createIdStore();function getHttpRpcClient(fr,br={}){return{async request(wr){var Zr;const{body:Er,onRequest:kr=br.onRequest,onResponse:jr=br.onResponse,timeout:Br=br.timeout??1e4}=wr,qr={...br.fetchOptions??{},...wr.fetchOptions??{}},{headers:Wr,method:Vr,signal:Hr}=qr;try{const Jr=await withTimeout$1(async({signal:En})=>{const wn={...qr,body:Array.isArray(Er)?stringify$5(Er.map(jn=>({jsonrpc:"2.0",id:jn.id??idCache.take(),...jn}))):stringify$5({jsonrpc:"2.0",id:Er.id??idCache.take(),...Er}),headers:{"Content-Type":"application/json",...Wr},method:Vr||"POST",signal:Hr||(Br>0?En:null)},$n=new Request(fr,wn),Tn=await(kr==null?void 0:kr($n,wn))??{...wn,url:fr};return await fetch(Tn.url??fr,Tn)},{errorInstance:new TimeoutError({body:Er,url:fr}),timeout:Br,signal:!0});jr&&await jr(Jr);let Xr;if((Zr=Jr.headers.get("Content-Type"))!=null&&Zr.startsWith("application/json"))Xr=await Jr.json();else{Xr=await Jr.text();try{Xr=JSON.parse(Xr||"{}")}catch(En){if(Jr.ok)throw En;Xr={error:Xr}}}if(!Jr.ok)throw new HttpRequestError({body:Er,details:stringify$5(Xr.error)||Jr.statusText,headers:Jr.headers,status:Jr.status,url:fr});return Xr}catch(Jr){throw Jr instanceof HttpRequestError||Jr instanceof TimeoutError?Jr:new HttpRequestError({body:Er,cause:Jr,url:fr})}}}}function http$2(fr,br={}){const{batch:wr,fetchOptions:Er,key:kr="http",name:jr="HTTP JSON-RPC",onFetchRequest:Br,onFetchResponse:qr,retryDelay:Wr}=br;return({chain:Vr,retryCount:Hr,timeout:Zr})=>{const{batchSize:Jr=1e3,wait:Xr=0}=typeof wr=="object"?wr:{},En=br.retryCount??Hr,wn=Zr??br.timeout??1e4,$n=fr||(Vr==null?void 0:Vr.rpcUrls.default.http[0]);if(!$n)throw new UrlRequiredError;const Tn=getHttpRpcClient($n,{fetchOptions:Er,onRequest:Br,onResponse:qr,timeout:wn});return createTransport$1({key:kr,name:jr,async request({method:In,params:jn}){const Yn={method:In,params:jn},{schedule:ga}=createBatchScheduler$1({id:$n,wait:Xr,shouldSplitBatch(to){return to.length>Jr},fn:to=>Tn.request({body:to}),sort:(to,io)=>to.id-io.id}),na=async to=>wr?ga(to):[await Tn.request({body:to})],[{error:_i,result:ro}]=await na(Yn);if(_i)throw new RpcRequestError({body:Yn,error:_i,url:$n});return ro},retryCount:En,retryDelay:Wr,timeout:wn,type:"http"},{fetchOptions:Er,url:$n})}}function isNullUniversalResolverError(fr,br){var Er,kr,jr,Br,qr,Wr;if(!(fr instanceof BaseError))return!1;const wr=fr.walk(Vr=>Vr instanceof ContractFunctionRevertedError);return wr instanceof ContractFunctionRevertedError?!!(((Er=wr.data)==null?void 0:Er.errorName)==="ResolverNotFound"||((kr=wr.data)==null?void 0:kr.errorName)==="ResolverWildcardNotSupported"||((jr=wr.data)==null?void 0:jr.errorName)==="ResolverNotContract"||((Br=wr.data)==null?void 0:Br.errorName)==="ResolverError"||((qr=wr.data)==null?void 0:qr.errorName)==="HttpError"||(Wr=wr.reason)!=null&&Wr.includes("Wildcard on non-extended resolvers is not supported")||br==="reverse"&&wr.reason===panicReasons[50]):!1}function encodedLabelToLabelhash$1(fr){if(fr.length!==66||fr.indexOf("[")!==0||fr.indexOf("]")!==65)return null;const br=`0x${fr.slice(1,65)}`;return isHex$1(br)?br:null}function namehash$1(fr){let br=new Uint8Array(32).fill(0);if(!fr)return bytesToHex$4(br);const wr=fr.split(".");for(let Er=wr.length-1;Er>=0;Er-=1){const kr=encodedLabelToLabelhash$1(wr[Er]),jr=kr?toBytes$4(kr):keccak256$1(stringToBytes$1(wr[Er]),"bytes");br=keccak256$1(concat$2([br,jr]),"bytes")}return bytesToHex$4(br)}function encodeLabelhash$1(fr){return`[${fr.slice(2)}]`}function labelhash$1(fr){const br=new Uint8Array(32).fill(0);return fr?encodedLabelToLabelhash$1(fr)||keccak256$1(stringToBytes$1(fr)):bytesToHex$4(br)}function packetToBytes$1(fr){const br=fr.replace(/^\.|\.$/gm,"");if(br.length===0)return new Uint8Array(1);const wr=new Uint8Array(stringToBytes$1(br).byteLength+2);let Er=0;const kr=br.split(".");for(let jr=0;jr255&&(Br=stringToBytes$1(encodeLabelhash$1(labelhash$1(kr[jr])))),wr[Er]=Br.length,wr.set(Br,Er+1),Er+=Br.length+1}return wr.byteLength!==Er+1?wr.slice(0,Er+1):wr}async function getEnsAddress$1(fr,{blockNumber:br,blockTag:wr,coinType:Er,name:kr,gatewayUrls:jr,strict:Br,universalResolverAddress:qr}){let Wr=qr;if(!Wr){if(!fr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");Wr=getChainContractAddress$1({blockNumber:br,chain:fr.chain,contract:"ensUniversalResolver"})}try{const Vr=encodeFunctionData$1({abi:addressResolverAbi,functionName:"addr",...Er!=null?{args:[namehash$1(kr),BigInt(Er)]}:{args:[namehash$1(kr)]}}),Hr={address:Wr,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex$1(packetToBytes$1(kr)),Vr],blockNumber:br,blockTag:wr},Zr=getAction$1(fr,readContract$1,"readContract"),Jr=jr?await Zr({...Hr,args:[...Hr.args,jr]}):await Zr(Hr);if(Jr[0]==="0x")return null;const Xr=decodeFunctionResult$1({abi:addressResolverAbi,args:Er!=null?[namehash$1(kr),BigInt(Er)]:void 0,functionName:"addr",data:Jr[0]});return Xr==="0x"||trim$1(Xr)==="0x00"?null:Xr}catch(Vr){if(Br)throw Vr;if(isNullUniversalResolverError(Vr,"resolve"))return null;throw Vr}}class EnsAvatarInvalidMetadataError extends BaseError{constructor({data:br}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(br)}`],name:"EnsAvatarInvalidMetadataError"})}}class EnsAvatarInvalidNftUriError extends BaseError{constructor({reason:br}){super(`ENS NFT avatar URI is invalid. ${br}`,{name:"EnsAvatarInvalidNftUriError"})}}class EnsAvatarUriResolutionError extends BaseError{constructor({uri:br}){super(`Unable to resolve ENS avatar URI "${br}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class EnsAvatarUnsupportedNamespaceError extends BaseError{constructor({namespace:br}){super(`ENS NFT avatar namespace "${br}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const networkRegex=/(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,ipfsHashRegex=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,base64Regex=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,dataURIRegex=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function isImageUri(fr){try{const br=await fetch(fr,{method:"HEAD"});if(br.status===200){const wr=br.headers.get("content-type");return wr==null?void 0:wr.startsWith("image/")}return!1}catch(br){return typeof br=="object"&&typeof br.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(wr=>{const Er=new Image;Er.onload=()=>{wr(!0)},Er.onerror=()=>{wr(!1)},Er.src=fr})}}function getGateway(fr,br){return fr?fr.endsWith("/")?fr.slice(0,-1):fr:br}function resolveAvatarUri({uri:fr,gatewayUrls:br}){const wr=base64Regex.test(fr);if(wr)return{uri:fr,isOnChain:!0,isEncoded:wr};const Er=getGateway(br==null?void 0:br.ipfs,"https://ipfs.io"),kr=getGateway(br==null?void 0:br.arweave,"https://arweave.net"),jr=fr.match(networkRegex),{protocol:Br,subpath:qr,target:Wr,subtarget:Vr=""}=(jr==null?void 0:jr.groups)||{},Hr=Br==="ipns:/"||qr==="ipns/",Zr=Br==="ipfs:/"||qr==="ipfs/"||ipfsHashRegex.test(fr);if(fr.startsWith("http")&&!Hr&&!Zr){let Xr=fr;return br!=null&&br.arweave&&(Xr=fr.replace(/https:\/\/arweave.net/g,br==null?void 0:br.arweave)),{uri:Xr,isOnChain:!1,isEncoded:!1}}if((Hr||Zr)&&Wr)return{uri:`${Er}/${Hr?"ipns":"ipfs"}/${Wr}${Vr}`,isOnChain:!1,isEncoded:!1};if(Br==="ar:/"&&Wr)return{uri:`${kr}/${Wr}${Vr||""}`,isOnChain:!1,isEncoded:!1};let Jr=fr.replace(dataURIRegex,"");if(Jr.startsWith("kr.json());return await parseAvatarUri({gatewayUrls:fr,uri:getJsonImage(wr)})}catch{throw new EnsAvatarUriResolutionError({uri:br})}}async function parseAvatarUri({gatewayUrls:fr,uri:br}){const{uri:wr,isOnChain:Er}=resolveAvatarUri({uri:br,gatewayUrls:fr});if(Er||await isImageUri(wr))return wr;throw new EnsAvatarUriResolutionError({uri:br})}function parseNftUri(fr){let br=fr;br.startsWith("did:nft:")&&(br=br.replace("did:nft:","").replace(/_/g,"/"));const[wr,Er,kr]=br.split("/"),[jr,Br]=wr.split(":"),[qr,Wr]=Er.split(":");if(!jr||jr.toLowerCase()!=="eip155")throw new EnsAvatarInvalidNftUriError({reason:"Only EIP-155 supported"});if(!Br)throw new EnsAvatarInvalidNftUriError({reason:"Chain ID not found"});if(!Wr)throw new EnsAvatarInvalidNftUriError({reason:"Contract address not found"});if(!kr)throw new EnsAvatarInvalidNftUriError({reason:"Token ID not found"});if(!qr)throw new EnsAvatarInvalidNftUriError({reason:"ERC namespace not found"});return{chainID:Number.parseInt(Br),namespace:qr.toLowerCase(),contractAddress:Wr,tokenID:kr}}async function getNftTokenUri(fr,{nft:br}){if(br.namespace==="erc721")return readContract$1(fr,{address:br.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(br.tokenID)]});if(br.namespace==="erc1155")return readContract$1(fr,{address:br.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(br.tokenID)]});throw new EnsAvatarUnsupportedNamespaceError({namespace:br.namespace})}async function parseAvatarRecord$1(fr,{gatewayUrls:br,record:wr}){return/eip155:/i.test(wr)?parseNftAvatarUri(fr,{gatewayUrls:br,record:wr}):parseAvatarUri({uri:wr,gatewayUrls:br})}async function parseNftAvatarUri(fr,{gatewayUrls:br,record:wr}){const Er=parseNftUri(wr),kr=await getNftTokenUri(fr,{nft:Er}),{uri:jr,isOnChain:Br,isEncoded:qr}=resolveAvatarUri({uri:kr,gatewayUrls:br});if(Br&&(jr.includes("data:application/json;base64,")||jr.startsWith("{"))){const Vr=qr?atob(jr.replace("data:application/json;base64,","")):jr,Hr=JSON.parse(Vr);return parseAvatarUri({uri:getJsonImage(Hr),gatewayUrls:br})}let Wr=Er.tokenID;return Er.namespace==="erc1155"&&(Wr=Wr.replace("0x","").padStart(64,"0")),getMetadataAvatarUri({gatewayUrls:br,uri:jr.replace(/(?:0x)?{id}/,Wr)})}async function getEnsText$1(fr,{blockNumber:br,blockTag:wr,name:Er,key:kr,gatewayUrls:jr,strict:Br,universalResolverAddress:qr}){let Wr=qr;if(!Wr){if(!fr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");Wr=getChainContractAddress$1({blockNumber:br,chain:fr.chain,contract:"ensUniversalResolver"})}try{const Vr={address:Wr,abi:universalResolverResolveAbi,functionName:"resolve",args:[toHex$1(packetToBytes$1(Er)),encodeFunctionData$1({abi:textResolverAbi,functionName:"text",args:[namehash$1(Er),kr]})],blockNumber:br,blockTag:wr},Hr=getAction$1(fr,readContract$1,"readContract"),Zr=jr?await Hr({...Vr,args:[...Vr.args,jr]}):await Hr(Vr);if(Zr[0]==="0x")return null;const Jr=decodeFunctionResult$1({abi:textResolverAbi,functionName:"text",data:Zr[0]});return Jr===""?null:Jr}catch(Vr){if(Br)throw Vr;if(isNullUniversalResolverError(Vr,"resolve"))return null;throw Vr}}async function getEnsAvatar$1(fr,{blockNumber:br,blockTag:wr,assetGatewayUrls:Er,name:kr,gatewayUrls:jr,strict:Br,universalResolverAddress:qr}){const Wr=await getAction$1(fr,getEnsText$1,"getEnsText")({blockNumber:br,blockTag:wr,key:"avatar",name:kr,universalResolverAddress:qr,gatewayUrls:jr,strict:Br});if(!Wr)return null;try{return await parseAvatarRecord$1(fr,{record:Wr,gatewayUrls:Er})}catch{return null}}async function getEnsName$1(fr,{address:br,blockNumber:wr,blockTag:Er,gatewayUrls:kr,strict:jr,universalResolverAddress:Br}){let qr=Br;if(!qr){if(!fr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");qr=getChainContractAddress$1({blockNumber:wr,chain:fr.chain,contract:"ensUniversalResolver"})}const Wr=`${br.toLowerCase().substring(2)}.addr.reverse`;try{const Vr={address:qr,abi:universalResolverReverseAbi,functionName:"reverse",args:[toHex$1(packetToBytes$1(Wr))],blockNumber:wr,blockTag:Er},Hr=getAction$1(fr,readContract$1,"readContract"),[Zr,Jr]=kr?await Hr({...Vr,args:[...Vr.args,kr]}):await Hr(Vr);return br.toLowerCase()!==Jr.toLowerCase()?null:Zr}catch(Vr){if(jr)throw Vr;if(isNullUniversalResolverError(Vr,"reverse"))return null;throw Vr}}async function getEnsResolver$1(fr,{blockNumber:br,blockTag:wr,name:Er,universalResolverAddress:kr}){let jr=kr;if(!jr){if(!fr.chain)throw new Error("client chain not configured. universalResolverAddress is required.");jr=getChainContractAddress$1({blockNumber:br,chain:fr.chain,contract:"ensUniversalResolver"})}const[Br]=await getAction$1(fr,readContract$1,"readContract")({address:jr,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[toHex$1(packetToBytes$1(Er))],blockNumber:br,blockTag:wr});return Br}async function createBlockFilter$1(fr){const br=createFilterRequestScope$1(fr,{method:"eth_newBlockFilter"}),wr=await fr.request({method:"eth_newBlockFilter"});return{id:wr,request:br(wr),type:"block"}}async function createEventFilter$1(fr,{address:br,args:wr,event:Er,events:kr,fromBlock:jr,strict:Br,toBlock:qr}={}){const Wr=kr??(Er?[Er]:void 0),Vr=createFilterRequestScope$1(fr,{method:"eth_newFilter"});let Hr=[];Wr&&(Hr=[Wr.flatMap(Xr=>encodeEventTopics$1({abi:[Xr],eventName:Xr.name,args:wr}))],Er&&(Hr=Hr[0]));const Zr=await fr.request({method:"eth_newFilter",params:[{address:br,fromBlock:typeof jr=="bigint"?numberToHex(jr):jr,toBlock:typeof qr=="bigint"?numberToHex(qr):qr,...Hr.length?{topics:Hr}:{}}]});return{abi:Wr,args:wr,eventName:Er?Er.name:void 0,fromBlock:jr,id:Zr,request:Vr(Zr),strict:!!Br,toBlock:qr,type:"event"}}async function createPendingTransactionFilter$1(fr){const br=createFilterRequestScope$1(fr,{method:"eth_newPendingTransactionFilter"}),wr=await fr.request({method:"eth_newPendingTransactionFilter"});return{id:wr,request:br(wr),type:"transaction"}}async function getBlobBaseFee$1(fr){const br=await fr.request({method:"eth_blobBaseFee"});return BigInt(br)}async function getBlockTransactionCount$1(fr,{blockHash:br,blockNumber:wr,blockTag:Er="latest"}={}){const kr=wr!==void 0?numberToHex(wr):void 0;let jr;return br?jr=await fr.request({method:"eth_getBlockTransactionCountByHash",params:[br]},{dedupe:!0}):jr=await fr.request({method:"eth_getBlockTransactionCountByNumber",params:[kr||Er]},{dedupe:!!kr}),hexToNumber$2(jr)}async function getCode$1(fr,{address:br,blockNumber:wr,blockTag:Er="latest"}){const kr=wr!==void 0?numberToHex(wr):void 0,jr=await fr.request({method:"eth_getCode",params:[br,kr||Er]},{dedupe:!!kr});if(jr!=="0x")return jr}function formatFeeHistory(fr){var br;return{baseFeePerGas:fr.baseFeePerGas.map(wr=>BigInt(wr)),gasUsedRatio:fr.gasUsedRatio,oldestBlock:BigInt(fr.oldestBlock),reward:(br=fr.reward)==null?void 0:br.map(wr=>wr.map(Er=>BigInt(Er)))}}async function getFeeHistory$1(fr,{blockCount:br,blockNumber:wr,blockTag:Er="latest",rewardPercentiles:kr}){const jr=wr?numberToHex(wr):void 0,Br=await fr.request({method:"eth_feeHistory",params:[numberToHex(br),jr||Er,kr]},{dedupe:!!jr});return formatFeeHistory(Br)}async function getFilterLogs$1(fr,{filter:br}){const wr=br.strict??!1,kr=(await br.request({method:"eth_getFilterLogs",params:[br.id]})).map(jr=>formatLog(jr));return br.abi?parseEventLogs$1({abi:br.abi,logs:kr,strict:wr}):kr}function defineChain$1(fr){return{formatters:void 0,fees:void 0,serializers:void 0,...fr}}const arrayRegex=/^(.*)\[([0-9]*)\]$/,bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,integerRegex=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;class InvalidDomainError extends BaseError{constructor({domain:br}){super(`Invalid domain "${stringify$5(br)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class InvalidPrimaryTypeError extends BaseError{constructor({primaryType:br,types:wr}){super(`Invalid primary type \`${br}\` must be one of \`${JSON.stringify(Object.keys(wr))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class InvalidStructTypeError extends BaseError{constructor({type:br}){super(`Struct type "${br}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function hashTypedData$1(fr){const{domain:br={},message:wr,primaryType:Er}=fr,kr={EIP712Domain:getTypesForEIP712Domain({domain:br}),...fr.types};validateTypedData({domain:br,message:wr,primaryType:Er,types:kr});const jr=["0x1901"];return br&&jr.push(hashDomain({domain:br,types:kr})),Er!=="EIP712Domain"&&jr.push(hashStruct({data:wr,primaryType:Er,types:kr})),keccak256$1(concat$2(jr))}function hashDomain({domain:fr,types:br}){return hashStruct({data:fr,primaryType:"EIP712Domain",types:br})}function hashStruct({data:fr,primaryType:br,types:wr}){const Er=encodeData$2({data:fr,primaryType:br,types:wr});return keccak256$1(Er)}function encodeData$2({data:fr,primaryType:br,types:wr}){const Er=[{type:"bytes32"}],kr=[hashType({primaryType:br,types:wr})];for(const jr of wr[br]){const[Br,qr]=encodeField({types:wr,name:jr.name,type:jr.type,value:fr[jr.name]});Er.push(Br),kr.push(qr)}return encodeAbiParameters$1(Er,kr)}function hashType({primaryType:fr,types:br}){const wr=toHex$1(encodeType({primaryType:fr,types:br}));return keccak256$1(wr)}function encodeType({primaryType:fr,types:br}){let wr="";const Er=findTypeDependencies({primaryType:fr,types:br});Er.delete(fr);const kr=[fr,...Array.from(Er).sort()];for(const jr of kr)wr+=`${jr}(${br[jr].map(({name:Br,type:qr})=>`${qr} ${Br}`).join(",")})`;return wr}function findTypeDependencies({primaryType:fr,types:br},wr=new Set){const Er=fr.match(/^\w*/u),kr=Er==null?void 0:Er[0];if(wr.has(kr)||br[kr]===void 0)return wr;wr.add(kr);for(const jr of br[kr])findTypeDependencies({primaryType:jr.type,types:br},wr);return wr}function encodeField({types:fr,name:br,type:wr,value:Er}){if(fr[wr]!==void 0)return[{type:"bytes32"},keccak256$1(encodeData$2({data:Er,primaryType:wr,types:fr}))];if(wr==="bytes")return Er=`0x${(Er.length%2?"0":"")+Er.slice(2)}`,[{type:"bytes32"},keccak256$1(Er)];if(wr==="string")return[{type:"bytes32"},keccak256$1(toHex$1(Er))];if(wr.lastIndexOf("]")===wr.length-1){const kr=wr.slice(0,wr.lastIndexOf("[")),jr=Er.map(Br=>encodeField({name:br,type:kr,types:fr,value:Br}));return[{type:"bytes32"},keccak256$1(encodeAbiParameters$1(jr.map(([Br])=>Br),jr.map(([,Br])=>Br)))]}return[{type:wr},Er]}function serializeTypedData(fr){const{domain:br,message:wr,primaryType:Er,types:kr}=fr,jr=(Wr,Vr)=>{const Hr={...Vr};for(const Zr of Wr){const{name:Jr,type:Xr}=Zr;Xr==="address"&&(Hr[Jr]=Hr[Jr].toLowerCase())}return Hr},Br=kr.EIP712Domain?br?jr(kr.EIP712Domain,br):{}:{},qr=(()=>{if(Er!=="EIP712Domain")return jr(kr[Er],wr)})();return stringify$5({domain:Br,message:qr,primaryType:Er,types:kr})}function validateTypedData(fr){const{domain:br,message:wr,primaryType:Er,types:kr}=fr,jr=(Br,qr)=>{for(const Wr of Br){const{name:Vr,type:Hr}=Wr,Zr=qr[Vr],Jr=Hr.match(integerRegex);if(Jr&&(typeof Zr=="number"||typeof Zr=="bigint")){const[wn,$n,Tn]=Jr;numberToHex(Zr,{signed:$n==="int",size:Number.parseInt(Tn)/8})}if(Hr==="address"&&typeof Zr=="string"&&!isAddress$1(Zr))throw new InvalidAddressError({address:Zr});const Xr=Hr.match(bytesRegex);if(Xr){const[wn,$n]=Xr;if($n&&size$2(Zr)!==Number.parseInt($n))throw new BytesSizeMismatchError({expectedSize:Number.parseInt($n),givenSize:size$2(Zr)})}const En=kr[Hr];En&&(validateReference(Hr),jr(En,Zr))}};if(kr.EIP712Domain&&br){if(typeof br!="object")throw new InvalidDomainError({domain:br});jr(kr.EIP712Domain,br)}if(Er!=="EIP712Domain")if(kr[Er])jr(kr[Er],wr);else throw new InvalidPrimaryTypeError({primaryType:Er,types:kr})}function getTypesForEIP712Domain({domain:fr}){return[typeof(fr==null?void 0:fr.name)=="string"&&{name:"name",type:"string"},(fr==null?void 0:fr.version)&&{name:"version",type:"string"},typeof(fr==null?void 0:fr.chainId)=="number"&&{name:"chainId",type:"uint256"},(fr==null?void 0:fr.verifyingContract)&&{name:"verifyingContract",type:"address"},(fr==null?void 0:fr.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function validateReference(fr){if(fr==="address"||fr==="bool"||fr==="string"||fr.startsWith("bytes")||fr.startsWith("uint")||fr.startsWith("int"))throw new InvalidStructTypeError({type:fr})}function encodePacked$1(fr,br){if(fr.length!==br.length)throw new AbiEncodingLengthMismatchError({expectedLength:fr.length,givenLength:br.length});const wr=[];for(let Er=0;ErformatLog(wr)):null,to:fr.to?fr.to:null,transactionIndex:fr.transactionIndex?hexToNumber$2(fr.transactionIndex):null,status:fr.status?receiptStatuses[fr.status]:null,type:fr.type?transactionType[fr.type]||fr.type:null};return fr.blobGasPrice&&(br.blobGasPrice=BigInt(fr.blobGasPrice)),fr.blobGasUsed&&(br.blobGasUsed=BigInt(fr.blobGasUsed)),br}const defineTransactionReceipt=defineFormatter("transactionReceipt",formatTransactionReceipt),Rho$1=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id$1=new Uint8Array(new Array(16).fill(0).map((fr,br)=>br)),Pi$1=Id$1.map(fr=>(9*fr+5)%16);let idxL$1=[Id$1],idxR$1=[Pi$1];for(let fr=0;fr<4;fr++)for(let br of[idxL$1,idxR$1])br.push(br[fr].map(wr=>Rho$1[wr]));const shifts$1=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(fr=>new Uint8Array(fr)),shiftsL$1=idxL$1.map((fr,br)=>fr.map(wr=>shifts$1[br][wr])),shiftsR$1=idxR$1.map((fr,br)=>fr.map(wr=>shifts$1[br][wr])),Kl$1=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Kr$1=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function f$8(fr,br,wr,Er){return fr===0?br^wr^Er:fr===1?br&wr|~br&Er:fr===2?(br|~wr)^Er:fr===3?br&Er|wr&~Er:br^(wr|~Er)}const R_BUF$1=new Uint32Array(16);let RIPEMD160$1=class extends HashMD$2{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:br,h1:wr,h2:Er,h3:kr,h4:jr}=this;return[br,wr,Er,kr,jr]}set(br,wr,Er,kr,jr){this.h0=br|0,this.h1=wr|0,this.h2=Er|0,this.h3=kr|0,this.h4=jr|0}process(br,wr){for(let Xr=0;Xr<16;Xr++,wr+=4)R_BUF$1[Xr]=br.getUint32(wr,!0);let Er=this.h0|0,kr=Er,jr=this.h1|0,Br=jr,qr=this.h2|0,Wr=qr,Vr=this.h3|0,Hr=Vr,Zr=this.h4|0,Jr=Zr;for(let Xr=0;Xr<5;Xr++){const En=4-Xr,wn=Kl$1[Xr],$n=Kr$1[Xr],Tn=idxL$1[Xr],In=idxR$1[Xr],jn=shiftsL$1[Xr],Yn=shiftsR$1[Xr];for(let ga=0;ga<16;ga++){const na=rotl$1(Er+f$8(Xr,jr,qr,Vr)+R_BUF$1[Tn[ga]]+wn,jn[ga])+Zr|0;Er=Zr,Zr=Vr,Vr=rotl$1(qr,10)|0,qr=jr,jr=na}for(let ga=0;ga<16;ga++){const na=rotl$1(kr+f$8(En,Br,Wr,Hr)+R_BUF$1[In[ga]]+$n,Yn[ga])+Jr|0;kr=Jr,Jr=Hr,Hr=rotl$1(Wr,10)|0,Wr=Br,Br=na}}this.set(this.h1+qr+Hr|0,this.h2+Vr+Jr|0,this.h3+Zr+kr|0,this.h4+Er+Br|0,this.h0+jr+Wr|0)}roundClean(){R_BUF$1.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};const ripemd160$4=wrapConstructor$2(()=>new RIPEMD160$1),presignMessagePrefix=`Ethereum Signed Message: `;function toPrefixedMessage$1(fr){const br=typeof fr=="string"?stringToHex(fr):typeof fr.raw=="string"?fr.raw:bytesToHex$4(fr.raw),wr=stringToHex(`${presignMessagePrefix}${size$2(br)}`);return concat$2([wr,br])}function hashMessage$1(fr,br){return keccak256$1(toPrefixedMessage$1(fr),br)}const erc6492MagicBytes="0x6492649264926492649264926492649264926492649264926492649264926492";function isErc6492Signature$1(fr){return sliceHex(fr,-32)===erc6492MagicBytes}function serializeErc6492Signature$1(fr){const{address:br,data:wr,signature:Er,to:kr="hex"}=fr,jr=concatHex([encodeAbiParameters$1([{type:"address"},{type:"bytes"},{type:"bytes"}],[br,wr,Er]),erc6492MagicBytes]);return kr==="hex"?jr:hexToBytes$4(jr)}function assertTransactionEIP7702(fr){const{authorizationList:br}=fr;if(br)for(const wr of br){const{contractAddress:Er,chainId:kr}=wr;if(!isAddress$1(Er))throw new InvalidAddressError({address:Er});if(kr<0)throw new InvalidChainIdError({chainId:kr})}assertTransactionEIP1559(fr)}function assertTransactionEIP4844(fr){const{blobVersionedHashes:br}=fr;if(br){if(br.length===0)throw new EmptyBlobError;for(const wr of br){const Er=size$2(wr),kr=hexToNumber$2(slice$1(wr,0,1));if(Er!==32)throw new InvalidVersionedHashSizeError({hash:wr,size:Er});if(kr!==versionedHashVersionKzg)throw new InvalidVersionedHashVersionError({hash:wr,version:kr})}}assertTransactionEIP1559(fr)}function assertTransactionEIP1559(fr){const{chainId:br,maxPriorityFeePerGas:wr,maxFeePerGas:Er,to:kr}=fr;if(br<=0)throw new InvalidChainIdError({chainId:br});if(kr&&!isAddress$1(kr))throw new InvalidAddressError({address:kr});if(Er&&Er>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:Er});if(wr&&Er&&wr>Er)throw new TipAboveFeeCapError({maxFeePerGas:Er,maxPriorityFeePerGas:wr})}function assertTransactionEIP2930(fr){const{chainId:br,maxPriorityFeePerGas:wr,gasPrice:Er,maxFeePerGas:kr,to:jr}=fr;if(br<=0)throw new InvalidChainIdError({chainId:br});if(jr&&!isAddress$1(jr))throw new InvalidAddressError({address:jr});if(wr||kr)throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(Er&&Er>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:Er})}function assertTransactionLegacy(fr){const{chainId:br,maxPriorityFeePerGas:wr,gasPrice:Er,maxFeePerGas:kr,to:jr}=fr;if(jr&&!isAddress$1(jr))throw new InvalidAddressError({address:jr});if(typeof br<"u"&&br<=0)throw new InvalidChainIdError({chainId:br});if(wr||kr)throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(Er&&Er>maxUint256)throw new FeeCapTooHighError({maxFeePerGas:Er})}function serializeAuthorizationList$1(fr){if(!fr||fr.length===0)return[];const br=[];for(const wr of fr){const{contractAddress:Er,chainId:kr,nonce:jr,...Br}=wr;br.push([kr?toHex$1(kr):"0x",Er,jr?toHex$1(jr):"0x",...toYParitySignatureArray({},Br)])}return br}function serializeAccessList$1(fr){if(!fr||fr.length===0)return[];const br=[];for(let wr=0;wr"u"||typeof Xr>"u")){const jn=typeof fr.blobs[0]=="string"?fr.blobs:fr.blobs.map(na=>bytesToHex$4(na)),Yn=fr.kzg,ga=blobsToCommitments$1({blobs:jn,kzg:Yn});if(typeof Jr>"u"&&(Jr=commitmentsToVersionedHashes$1({commitments:ga})),typeof Xr>"u"){const na=blobsToProofs$1({blobs:jn,commitments:ga,kzg:Yn});Xr=toBlobSidecars$1({blobs:jn,commitments:ga,proofs:na})}}const En=serializeAccessList$1(Hr),wn=[toHex$1(wr),kr?toHex$1(kr):"0x",Vr?toHex$1(Vr):"0x",Wr?toHex$1(Wr):"0x",Er?toHex$1(Er):"0x",jr??"0x",Br?toHex$1(Br):"0x",Zr??"0x",En,qr?toHex$1(qr):"0x",Jr??[],...toYParitySignatureArray(fr,br)],$n=[],Tn=[],In=[];if(Xr)for(let jn=0;jn{if(br.v>=35n)return(br.v-35n)/2n>0?br.v:27n+(br.v===35n?0n:1n);if(wr>0)return BigInt(wr*2)+BigInt(35n+br.v-27n);const Xr=27n+(br.v===27n?0n:1n);if(br.v!==Xr)throw new InvalidLegacyVError({v:br.v});return Xr})(),Zr=trim$1(br.r),Jr=trim$1(br.s);Vr=[...Vr,toHex$1(Hr),Zr==="0x00"?"0x":Zr,Jr==="0x00"?"0x":Jr]}else wr>0&&(Vr=[...Vr,toHex$1(wr),"0x","0x"]);return toRlp$1(Vr)}function toYParitySignatureArray(fr,br){const wr=br??fr,{v:Er,yParity:kr}=wr;if(typeof wr.r>"u")return[];if(typeof wr.s>"u")return[];if(typeof Er>"u"&&typeof kr>"u")return[];const jr=trim$1(wr.r),Br=trim$1(wr.s);return[typeof kr=="number"?kr?toHex$1(1):"0x":Er===0n?"0x":Er===1n?toHex$1(1):Er===27n?"0x":toHex$1(1),jr==="0x00"?"0x":jr,Br==="0x00"?"0x":Br]}class InvalidDecimalNumberError extends BaseError{constructor({value:br}){super(`Number \`${br}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}function parseUnits$1(fr,br){if(!/^(-?)([0-9]*)\.?([0-9]*)$/.test(fr))throw new InvalidDecimalNumberError({value:fr});let[wr,Er="0"]=fr.split(".");const kr=wr.startsWith("-");if(kr&&(wr=wr.slice(1)),Er=Er.replace(/(0+)$/,""),br===0)Math.round(+`.${Er}`)===1&&(wr=`${BigInt(wr)+1n}`),Er="";else if(Er.length>br){const[jr,Br,qr]=[Er.slice(0,br-1),Er.slice(br-1,br),Er.slice(br)],Wr=Math.round(+`${Br}.${qr}`);Wr>9?Er=`${BigInt(jr)+BigInt(1)}0`.padStart(jr.length+1,"0"):Er=`${jr}${Wr}`,Er.length>br&&(Er=Er.slice(1),wr=`${BigInt(wr)+1n}`),Er=Er.slice(0,br)}else Er=Er.padEnd(br,"0");return BigInt(`${kr?"-":""}${wr}${Er}`)}function parseEther$2(fr,br="wei"){return parseUnits$1(fr,etherUnits[br])}function formatStorageProof(fr){return fr.map(br=>({...br,value:BigInt(br.value)}))}function formatProof(fr){return{...fr,balance:fr.balance?BigInt(fr.balance):void 0,nonce:fr.nonce?hexToNumber$2(fr.nonce):void 0,storageProof:fr.storageProof?formatStorageProof(fr.storageProof):void 0}}async function getProof$1(fr,{address:br,blockNumber:wr,blockTag:Er,storageKeys:kr}){const jr=Er??"latest",Br=wr!==void 0?numberToHex(wr):void 0,qr=await fr.request({method:"eth_getProof",params:[br,kr,Br||jr]});return formatProof(qr)}async function getStorageAt$1(fr,{address:br,blockNumber:wr,blockTag:Er="latest",slot:kr}){const jr=wr!==void 0?numberToHex(wr):void 0;return await fr.request({method:"eth_getStorageAt",params:[br,kr,jr||Er]})}async function getTransaction$1(fr,{blockHash:br,blockNumber:wr,blockTag:Er,hash:kr,index:jr}){var Hr,Zr,Jr;const Br=Er||"latest",qr=wr!==void 0?numberToHex(wr):void 0;let Wr=null;if(kr?Wr=await fr.request({method:"eth_getTransactionByHash",params:[kr]},{dedupe:!0}):br?Wr=await fr.request({method:"eth_getTransactionByBlockHashAndIndex",params:[br,numberToHex(jr)]},{dedupe:!0}):(qr||Br)&&(Wr=await fr.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[qr||Br,numberToHex(jr)]},{dedupe:!!qr})),!Wr)throw new TransactionNotFoundError({blockHash:br,blockNumber:wr,blockTag:Br,hash:kr,index:jr});return(((Jr=(Zr=(Hr=fr.chain)==null?void 0:Hr.formatters)==null?void 0:Zr.transaction)==null?void 0:Jr.format)||formatTransaction)(Wr)}async function getTransactionConfirmations$1(fr,{hash:br,transactionReceipt:wr}){const[Er,kr]=await Promise.all([getAction$1(fr,getBlockNumber$1,"getBlockNumber")({}),br?getAction$1(fr,getTransaction$1,"getTransaction")({hash:br}):void 0]),jr=(wr==null?void 0:wr.blockNumber)||(kr==null?void 0:kr.blockNumber);return jr?Er-jr+1n:0n}async function getTransactionReceipt$1(fr,{hash:br}){var kr,jr,Br;const wr=await fr.request({method:"eth_getTransactionReceipt",params:[br]},{dedupe:!0});if(!wr)throw new TransactionReceiptNotFoundError({hash:br});return(((Br=(jr=(kr=fr.chain)==null?void 0:kr.formatters)==null?void 0:jr.transactionReceipt)==null?void 0:Br.format)||formatTransactionReceipt)(wr)}async function multicall$1(fr,br){var $n;const{allowFailure:wr=!0,batchSize:Er,blockNumber:kr,blockTag:jr,multicallAddress:Br,stateOverride:qr}=br,Wr=br.contracts,Vr=Er??(typeof(($n=fr.batch)==null?void 0:$n.multicall)=="object"&&fr.batch.multicall.batchSize||1024);let Hr=Br;if(!Hr){if(!fr.chain)throw new Error("client chain not configured. multicallAddress is required.");Hr=getChainContractAddress$1({blockNumber:kr,chain:fr.chain,contract:"multicall3"})}const Zr=[[]];let Jr=0,Xr=0;for(let Tn=0;Tn0&&Xr>Vr&&Zr[Jr].length>0&&(Jr++,Xr=(na.length-2)/2,Zr[Jr]=[]),Zr[Jr]=[...Zr[Jr],{allowFailure:!0,callData:na,target:jn}]}catch(na){const _i=getContractError$1(na,{abi:In,address:jn,args:Yn,docsPath:"/docs/contract/multicall",functionName:ga});if(!wr)throw _i;Zr[Jr]=[...Zr[Jr],{allowFailure:!0,callData:"0x",target:jn}]}}const En=await Promise.allSettled(Zr.map(Tn=>getAction$1(fr,readContract$1,"readContract")({abi:multicall3Abi,address:Hr,args:[Tn],blockNumber:kr,blockTag:jr,functionName:"aggregate3",stateOverride:qr}))),wn=[];for(let Tn=0;Tnkr?br.create().update(Er).digest():Er);for(let Br=0;Brnew HMAC$3(fr,br).update(wr).digest();hmac$6.create=(fr,br)=>new HMAC$3(fr,br);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$8=BigInt(0),_1n$b=BigInt(1),_2n$7=BigInt(2);function isBytes$8(fr){return fr instanceof Uint8Array||fr!=null&&typeof fr=="object"&&fr.constructor.name==="Uint8Array"}function abytes$3(fr){if(!isBytes$8(fr))throw new Error("Uint8Array expected")}function abool$1(fr,br){if(typeof br!="boolean")throw new Error(`${fr} must be valid boolean, got "${br}".`)}const hexes$2=Array.from({length:256},(fr,br)=>br.toString(16).padStart(2,"0"));function bytesToHex$2(fr){abytes$3(fr);let br="";for(let wr=0;wr=asciis$2._0&&fr<=asciis$2._9)return fr-asciis$2._0;if(fr>=asciis$2._A&&fr<=asciis$2._F)return fr-(asciis$2._A-10);if(fr>=asciis$2._a&&fr<=asciis$2._f)return fr-(asciis$2._a-10)}function hexToBytes$2(fr){if(typeof fr!="string")throw new Error("hex string expected, got "+typeof fr);const br=fr.length,wr=br/2;if(br%2)throw new Error("padded hex string expected, got unpadded hex of length "+br);const Er=new Uint8Array(wr);for(let kr=0,jr=0;krtypeof fr=="bigint"&&_0n$8<=fr;function inRange$2(fr,br,wr){return isPosBig$1(fr)&&isPosBig$1(br)&&isPosBig$1(wr)&&br<=fr&&fr_0n$8;fr>>=_1n$b,br+=1);return br}function bitGet$1(fr,br){return fr>>BigInt(br)&_1n$b}function bitSet$1(fr,br,wr){return fr|(wr?_1n$b:_0n$8)<(_2n$7<new Uint8Array(fr),u8fr$1=fr=>Uint8Array.from(fr);function createHmacDrbg$1(fr,br,wr){if(typeof fr!="number"||fr<2)throw new Error("hashLen must be a number");if(typeof br!="number"||br<2)throw new Error("qByteLen must be a number");if(typeof wr!="function")throw new Error("hmacFn must be a function");let Er=u8n$1(fr),kr=u8n$1(fr),jr=0;const Br=()=>{Er.fill(1),kr.fill(0),jr=0},qr=(...Zr)=>wr(kr,Er,...Zr),Wr=(Zr=u8n$1())=>{kr=qr(u8fr$1([0]),Zr),Er=qr(),Zr.length!==0&&(kr=qr(u8fr$1([1]),Zr),Er=qr())},Vr=()=>{if(jr++>=1e3)throw new Error("drbg: tried 1000 values");let Zr=0;const Jr=[];for(;Zr{Br(),Wr(Zr);let Xr;for(;!(Xr=Jr(Vr()));)Wr();return Br(),Xr}}const validatorFns$1={bigint:fr=>typeof fr=="bigint",function:fr=>typeof fr=="function",boolean:fr=>typeof fr=="boolean",string:fr=>typeof fr=="string",stringOrUint8Array:fr=>typeof fr=="string"||isBytes$8(fr),isSafeInteger:fr=>Number.isSafeInteger(fr),array:fr=>Array.isArray(fr),field:(fr,br)=>br.Fp.isValid(fr),hash:fr=>typeof fr=="function"&&Number.isSafeInteger(fr.outputLen)};function validateObject$1(fr,br,wr={}){const Er=(kr,jr,Br)=>{const qr=validatorFns$1[jr];if(typeof qr!="function")throw new Error(`Invalid validator "${jr}", expected function`);const Wr=fr[kr];if(!(Br&&Wr===void 0)&&!qr(Wr,fr))throw new Error(`Invalid param ${String(kr)}=${Wr} (${typeof Wr}), expected ${jr}`)};for(const[kr,jr]of Object.entries(br))Er(kr,jr,!1);for(const[kr,jr]of Object.entries(wr))Er(kr,jr,!0);return fr}const notImplemented$1=()=>{throw new Error("not implemented")};function memoized$1(fr){const br=new WeakMap;return(wr,...Er)=>{const kr=br.get(wr);if(kr!==void 0)return kr;const jr=fr(wr,...Er);return br.set(wr,jr),jr}}const ut$3=Object.freeze(Object.defineProperty({__proto__:null,aInRange:aInRange$1,abool:abool$1,abytes:abytes$3,bitGet:bitGet$1,bitLen:bitLen$1,bitMask:bitMask$1,bitSet:bitSet$1,bytesToHex:bytesToHex$2,bytesToNumberBE:bytesToNumberBE$1,bytesToNumberLE:bytesToNumberLE$1,concatBytes:concatBytes$3,createHmacDrbg:createHmacDrbg$1,ensureBytes:ensureBytes$1,equalBytes:equalBytes$1,hexToBytes:hexToBytes$2,hexToNumber:hexToNumber$1,inRange:inRange$2,isBytes:isBytes$8,memoized:memoized$1,notImplemented:notImplemented$1,numberToBytesBE:numberToBytesBE$1,numberToBytesLE:numberToBytesLE$1,numberToHexUnpadded:numberToHexUnpadded$1,numberToVarBytesBE:numberToVarBytesBE$1,utf8ToBytes:utf8ToBytes$3,validateObject:validateObject$1},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$7=BigInt(0),_1n$a=BigInt(1),_2n$6=BigInt(2),_3n$3=BigInt(3),_4n$1=BigInt(4),_5n$2=BigInt(5),_8n$3=BigInt(8);BigInt(9);BigInt(16);function mod$1(fr,br){const wr=fr%br;return wr>=_0n$7?wr:br+wr}function pow$1(fr,br,wr){if(wr<=_0n$7||br<_0n$7)throw new Error("Expected power/modulo > 0");if(wr===_1n$a)return _0n$7;let Er=_1n$a;for(;br>_0n$7;)br&_1n$a&&(Er=Er*fr%wr),fr=fr*fr%wr,br>>=_1n$a;return Er}function pow2$1(fr,br,wr){let Er=fr;for(;br-- >_0n$7;)Er*=Er,Er%=wr;return Er}function invert$1(fr,br){if(fr===_0n$7||br<=_0n$7)throw new Error(`invert: expected positive integers, got n=${fr} mod=${br}`);let wr=mod$1(fr,br),Er=br,kr=_0n$7,jr=_1n$a;for(;wr!==_0n$7;){const qr=Er/wr,Wr=Er%wr,Vr=kr-jr*qr;Er=wr,wr=Wr,kr=jr,jr=Vr}if(Er!==_1n$a)throw new Error("invert: does not exist");return mod$1(kr,br)}function tonelliShanks$1(fr){const br=(fr-_1n$a)/_2n$6;let wr,Er,kr;for(wr=fr-_1n$a,Er=0;wr%_2n$6===_0n$7;wr/=_2n$6,Er++);for(kr=_2n$6;kr(Er[kr]="function",Er),br);return validateObject$1(fr,wr)}function FpPow$1(fr,br,wr){if(wr<_0n$7)throw new Error("Expected power > 0");if(wr===_0n$7)return fr.ONE;if(wr===_1n$a)return br;let Er=fr.ONE,kr=br;for(;wr>_0n$7;)wr&_1n$a&&(Er=fr.mul(Er,kr)),kr=fr.sqr(kr),wr>>=_1n$a;return Er}function FpInvertBatch$1(fr,br){const wr=new Array(br.length),Er=br.reduce((jr,Br,qr)=>fr.is0(Br)?jr:(wr[qr]=jr,fr.mul(jr,Br)),fr.ONE),kr=fr.inv(Er);return br.reduceRight((jr,Br,qr)=>fr.is0(Br)?jr:(wr[qr]=fr.mul(jr,wr[qr]),fr.mul(jr,Br)),kr),wr}function nLength$1(fr,br){const wr=br!==void 0?br:fr.toString(2).length,Er=Math.ceil(wr/8);return{nBitLength:wr,nByteLength:Er}}function Field$1(fr,br,wr=!1,Er={}){if(fr<=_0n$7)throw new Error(`Expected Field ORDER > 0, got ${fr}`);const{nBitLength:kr,nByteLength:jr}=nLength$1(fr,br);if(jr>2048)throw new Error("Field lengths over 2048 bytes are not supported");const Br=FpSqrt$1(fr),qr=Object.freeze({ORDER:fr,BITS:kr,BYTES:jr,MASK:bitMask$1(kr),ZERO:_0n$7,ONE:_1n$a,create:Wr=>mod$1(Wr,fr),isValid:Wr=>{if(typeof Wr!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof Wr}`);return _0n$7<=Wr&&WrWr===_0n$7,isOdd:Wr=>(Wr&_1n$a)===_1n$a,neg:Wr=>mod$1(-Wr,fr),eql:(Wr,Vr)=>Wr===Vr,sqr:Wr=>mod$1(Wr*Wr,fr),add:(Wr,Vr)=>mod$1(Wr+Vr,fr),sub:(Wr,Vr)=>mod$1(Wr-Vr,fr),mul:(Wr,Vr)=>mod$1(Wr*Vr,fr),pow:(Wr,Vr)=>FpPow$1(qr,Wr,Vr),div:(Wr,Vr)=>mod$1(Wr*invert$1(Vr,fr),fr),sqrN:Wr=>Wr*Wr,addN:(Wr,Vr)=>Wr+Vr,subN:(Wr,Vr)=>Wr-Vr,mulN:(Wr,Vr)=>Wr*Vr,inv:Wr=>invert$1(Wr,fr),sqrt:Er.sqrt||(Wr=>Br(qr,Wr)),invertBatch:Wr=>FpInvertBatch$1(qr,Wr),cmov:(Wr,Vr,Hr)=>Hr?Vr:Wr,toBytes:Wr=>wr?numberToBytesLE$1(Wr,jr):numberToBytesBE$1(Wr,jr),fromBytes:Wr=>{if(Wr.length!==jr)throw new Error(`Fp.fromBytes: expected ${jr}, got ${Wr.length}`);return wr?bytesToNumberLE$1(Wr):bytesToNumberBE$1(Wr)}});return Object.freeze(qr)}function getFieldBytesLength$1(fr){if(typeof fr!="bigint")throw new Error("field order must be bigint");const br=fr.toString(2).length;return Math.ceil(br/8)}function getMinHashLength$1(fr){const br=getFieldBytesLength$1(fr);return br+Math.ceil(br/2)}function mapHashToField$1(fr,br,wr=!1){const Er=fr.length,kr=getFieldBytesLength$1(br),jr=getMinHashLength$1(br);if(Er<16||Er1024)throw new Error(`expected ${jr}-1024 bytes of input, got ${Er}`);const Br=wr?bytesToNumberBE$1(fr):bytesToNumberLE$1(fr),qr=mod$1(Br,br-_1n$a)+_1n$a;return wr?numberToBytesLE$1(qr,kr):numberToBytesBE$1(qr,kr)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$6=BigInt(0),_1n$9=BigInt(1),pointPrecomputes$1=new WeakMap,pointWindowSizes$1=new WeakMap;function wNAF$1(fr,br){const wr=(jr,Br)=>{const qr=Br.negate();return jr?qr:Br},Er=jr=>{if(!Number.isSafeInteger(jr)||jr<=0||jr>br)throw new Error(`Wrong window size=${jr}, should be [1..${br}]`)},kr=jr=>{Er(jr);const Br=Math.ceil(br/jr)+1,qr=2**(jr-1);return{windows:Br,windowSize:qr}};return{constTimeNegate:wr,unsafeLadder(jr,Br){let qr=fr.ZERO,Wr=jr;for(;Br>_0n$6;)Br&_1n$9&&(qr=qr.add(Wr)),Wr=Wr.double(),Br>>=_1n$9;return qr},precomputeWindow(jr,Br){const{windows:qr,windowSize:Wr}=kr(Br),Vr=[];let Hr=jr,Zr=Hr;for(let Jr=0;Jr>=En,Tn>Vr&&(Tn-=Xr,qr+=_1n$9);const In=$n,jn=$n+Math.abs(Tn)-1,Yn=wn%2!==0,ga=Tn<0;Tn===0?Zr=Zr.add(wr(Yn,Br[In])):Hr=Hr.add(wr(ga,Br[jn]))}return{p:Hr,f:Zr}},wNAFCached(jr,Br,qr){const Wr=pointWindowSizes$1.get(jr)||1;let Vr=pointPrecomputes$1.get(jr);return Vr||(Vr=this.precomputeWindow(jr,Wr),Wr!==1&&pointPrecomputes$1.set(jr,qr(Vr))),this.wNAF(Wr,Vr,Br)},setWindowSize(jr,Br){Er(Br),pointWindowSizes$1.set(jr,Br),pointPrecomputes$1.delete(jr)}}}function pippenger$1(fr,br,wr,Er){if(!Array.isArray(wr)||!Array.isArray(Er)||Er.length!==wr.length)throw new Error("arrays of points and scalars must have equal length");Er.forEach((Hr,Zr)=>{if(!br.isValid(Hr))throw new Error(`wrong scalar at index ${Zr}`)}),wr.forEach((Hr,Zr)=>{if(!(Hr instanceof fr))throw new Error(`wrong point at index ${Zr}`)});const kr=bitLen$1(BigInt(wr.length)),jr=kr>12?kr-3:kr>4?kr-2:kr?2:1,Br=(1<=0;Hr-=jr){qr.fill(fr.ZERO);for(let Jr=0;Jr>BigInt(Hr)&BigInt(Br));qr[En]=qr[En].add(wr[Jr])}let Zr=fr.ZERO;for(let Jr=qr.length-1,Xr=fr.ZERO;Jr>0;Jr--)Xr=Xr.add(qr[Jr]),Zr=Zr.add(Xr);if(Vr=Vr.add(Zr),Hr!==0)for(let Jr=0;Jr{const{Err:wr}=DER$1;if(fr<0||fr>256)throw new wr("tlv.encode: wrong tag");if(br.length&1)throw new wr("tlv.encode: unpadded data");const Er=br.length/2,kr=numberToHexUnpadded$1(Er);if(kr.length/2&128)throw new wr("tlv.encode: long form length too big");const jr=Er>127?numberToHexUnpadded$1(kr.length/2|128):"";return`${numberToHexUnpadded$1(fr)}${jr}${kr}${br}`},decode(fr,br){const{Err:wr}=DER$1;let Er=0;if(fr<0||fr>256)throw new wr("tlv.encode: wrong tag");if(br.length<2||br[Er++]!==fr)throw new wr("tlv.decode: wrong tlv");const kr=br[Er++],jr=!!(kr&128);let Br=0;if(!jr)Br=kr;else{const Wr=kr&127;if(!Wr)throw new wr("tlv.decode(long): indefinite length not supported");if(Wr>4)throw new wr("tlv.decode(long): byte length is too big");const Vr=br.subarray(Er,Er+Wr);if(Vr.length!==Wr)throw new wr("tlv.decode: length bytes not complete");if(Vr[0]===0)throw new wr("tlv.decode(long): zero leftmost byte");for(const Hr of Vr)Br=Br<<8|Hr;if(Er+=Wr,Br<128)throw new wr("tlv.decode(long): not minimal encoding")}const qr=br.subarray(Er,Er+Br);if(qr.length!==Br)throw new wr("tlv.decode: wrong value length");return{v:qr,l:br.subarray(Er+Br)}}},_int:{encode(fr){const{Err:br}=DER$1;if(fr<_0n$5)throw new br("integer: negative integers are not allowed");let wr=numberToHexUnpadded$1(fr);if(Number.parseInt(wr[0],16)&8&&(wr="00"+wr),wr.length&1)throw new br("unexpected assertion");return wr},decode(fr){const{Err:br}=DER$1;if(fr[0]&128)throw new br("Invalid signature integer: negative");if(fr[0]===0&&!(fr[1]&128))throw new br("Invalid signature integer: unnecessary leading zero");return b2n$1(fr)}},toSig(fr){const{Err:br,_int:wr,_tlv:Er}=DER$1,kr=typeof fr=="string"?h2b$1(fr):fr;abytes$3(kr);const{v:jr,l:Br}=Er.decode(48,kr);if(Br.length)throw new br("Invalid signature: left bytes after parsing");const{v:qr,l:Wr}=Er.decode(2,jr),{v:Vr,l:Hr}=Er.decode(2,Wr);if(Hr.length)throw new br("Invalid signature: left bytes after parsing");return{r:wr.decode(qr),s:wr.decode(Vr)}},hexFromSig(fr){const{_tlv:br,_int:wr}=DER$1,Er=`${br.encode(2,wr.encode(fr.r))}${br.encode(2,wr.encode(fr.s))}`;return br.encode(48,Er)}},_0n$5=BigInt(0),_1n$8=BigInt(1);BigInt(2);const _3n$2=BigInt(3);BigInt(4);function weierstrassPoints$1(fr){const br=validatePointOpts$1(fr),{Fp:wr}=br,Er=Field$1(br.n,br.nBitLength),kr=br.toBytes||((wn,$n,Tn)=>{const In=$n.toAffine();return concatBytes$3(Uint8Array.from([4]),wr.toBytes(In.x),wr.toBytes(In.y))}),jr=br.fromBytes||(wn=>{const $n=wn.subarray(1),Tn=wr.fromBytes($n.subarray(0,wr.BYTES)),In=wr.fromBytes($n.subarray(wr.BYTES,2*wr.BYTES));return{x:Tn,y:In}});function Br(wn){const{a:$n,b:Tn}=br,In=wr.sqr(wn),jn=wr.mul(In,wn);return wr.add(wr.add(jn,wr.mul(wn,$n)),Tn)}if(!wr.eql(wr.sqr(br.Gy),Br(br.Gx)))throw new Error("bad generator point: equation left != right");function qr(wn){return inRange$2(wn,_1n$8,br.n)}function Wr(wn){const{allowedPrivateKeyLengths:$n,nByteLength:Tn,wrapPrivateKey:In,n:jn}=br;if($n&&typeof wn!="bigint"){if(isBytes$8(wn)&&(wn=bytesToHex$2(wn)),typeof wn!="string"||!$n.includes(wn.length))throw new Error("Invalid key");wn=wn.padStart(Tn*2,"0")}let Yn;try{Yn=typeof wn=="bigint"?wn:bytesToNumberBE$1(ensureBytes$1("private key",wn,Tn))}catch{throw new Error(`private key must be ${Tn} bytes, hex or bigint, not ${typeof wn}`)}return In&&(Yn=mod$1(Yn,jn)),aInRange$1("private key",Yn,_1n$8,jn),Yn}function Vr(wn){if(!(wn instanceof Jr))throw new Error("ProjectivePoint expected")}const Hr=memoized$1((wn,$n)=>{const{px:Tn,py:In,pz:jn}=wn;if(wr.eql(jn,wr.ONE))return{x:Tn,y:In};const Yn=wn.is0();$n==null&&($n=Yn?wr.ONE:wr.inv(jn));const ga=wr.mul(Tn,$n),na=wr.mul(In,$n),_i=wr.mul(jn,$n);if(Yn)return{x:wr.ZERO,y:wr.ZERO};if(!wr.eql(_i,wr.ONE))throw new Error("invZ was invalid");return{x:ga,y:na}}),Zr=memoized$1(wn=>{if(wn.is0()){if(br.allowInfinityPoint&&!wr.is0(wn.py))return;throw new Error("bad point: ZERO")}const{x:$n,y:Tn}=wn.toAffine();if(!wr.isValid($n)||!wr.isValid(Tn))throw new Error("bad point: x or y not FE");const In=wr.sqr(Tn),jn=Br($n);if(!wr.eql(In,jn))throw new Error("bad point: equation left != right");if(!wn.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class Jr{constructor($n,Tn,In){if(this.px=$n,this.py=Tn,this.pz=In,$n==null||!wr.isValid($n))throw new Error("x required");if(Tn==null||!wr.isValid(Tn))throw new Error("y required");if(In==null||!wr.isValid(In))throw new Error("z required");Object.freeze(this)}static fromAffine($n){const{x:Tn,y:In}=$n||{};if(!$n||!wr.isValid(Tn)||!wr.isValid(In))throw new Error("invalid affine point");if($n instanceof Jr)throw new Error("projective point not allowed");const jn=Yn=>wr.eql(Yn,wr.ZERO);return jn(Tn)&&jn(In)?Jr.ZERO:new Jr(Tn,In,wr.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ($n){const Tn=wr.invertBatch($n.map(In=>In.pz));return $n.map((In,jn)=>In.toAffine(Tn[jn])).map(Jr.fromAffine)}static fromHex($n){const Tn=Jr.fromAffine(jr(ensureBytes$1("pointHex",$n)));return Tn.assertValidity(),Tn}static fromPrivateKey($n){return Jr.BASE.multiply(Wr($n))}static msm($n,Tn){return pippenger$1(Jr,Er,$n,Tn)}_setWindowSize($n){En.setWindowSize(this,$n)}assertValidity(){Zr(this)}hasEvenY(){const{y:$n}=this.toAffine();if(wr.isOdd)return!wr.isOdd($n);throw new Error("Field doesn't support isOdd")}equals($n){Vr($n);const{px:Tn,py:In,pz:jn}=this,{px:Yn,py:ga,pz:na}=$n,_i=wr.eql(wr.mul(Tn,na),wr.mul(Yn,jn)),ro=wr.eql(wr.mul(In,na),wr.mul(ga,jn));return _i&&ro}negate(){return new Jr(this.px,wr.neg(this.py),this.pz)}double(){const{a:$n,b:Tn}=br,In=wr.mul(Tn,_3n$2),{px:jn,py:Yn,pz:ga}=this;let na=wr.ZERO,_i=wr.ZERO,ro=wr.ZERO,to=wr.mul(jn,jn),io=wr.mul(Yn,Yn),no=wr.mul(ga,ga),$a=wr.mul(jn,Yn);return $a=wr.add($a,$a),ro=wr.mul(jn,ga),ro=wr.add(ro,ro),na=wr.mul($n,ro),_i=wr.mul(In,no),_i=wr.add(na,_i),na=wr.sub(io,_i),_i=wr.add(io,_i),_i=wr.mul(na,_i),na=wr.mul($a,na),ro=wr.mul(In,ro),no=wr.mul($n,no),$a=wr.sub(to,no),$a=wr.mul($n,$a),$a=wr.add($a,ro),ro=wr.add(to,to),to=wr.add(ro,to),to=wr.add(to,no),to=wr.mul(to,$a),_i=wr.add(_i,to),no=wr.mul(Yn,ga),no=wr.add(no,no),to=wr.mul(no,$a),na=wr.sub(na,to),ro=wr.mul(no,io),ro=wr.add(ro,ro),ro=wr.add(ro,ro),new Jr(na,_i,ro)}add($n){Vr($n);const{px:Tn,py:In,pz:jn}=this,{px:Yn,py:ga,pz:na}=$n;let _i=wr.ZERO,ro=wr.ZERO,to=wr.ZERO;const io=br.a,no=wr.mul(br.b,_3n$2);let $a=wr.mul(Tn,Yn),Rn=wr.mul(In,ga),Gr=wr.mul(jn,na),Yr=wr.add(Tn,In),Sn=wr.add(Yn,ga);Yr=wr.mul(Yr,Sn),Sn=wr.add($a,Rn),Yr=wr.sub(Yr,Sn),Sn=wr.add(Tn,jn);let An=wr.add(Yn,na);return Sn=wr.mul(Sn,An),An=wr.add($a,Gr),Sn=wr.sub(Sn,An),An=wr.add(In,jn),_i=wr.add(ga,na),An=wr.mul(An,_i),_i=wr.add(Rn,Gr),An=wr.sub(An,_i),to=wr.mul(io,Sn),_i=wr.mul(no,Gr),to=wr.add(_i,to),_i=wr.sub(Rn,to),to=wr.add(Rn,to),ro=wr.mul(_i,to),Rn=wr.add($a,$a),Rn=wr.add(Rn,$a),Gr=wr.mul(io,Gr),Sn=wr.mul(no,Sn),Rn=wr.add(Rn,Gr),Gr=wr.sub($a,Gr),Gr=wr.mul(io,Gr),Sn=wr.add(Sn,Gr),$a=wr.mul(Rn,Sn),ro=wr.add(ro,$a),$a=wr.mul(An,Sn),_i=wr.mul(Yr,_i),_i=wr.sub(_i,$a),$a=wr.mul(Yr,Rn),to=wr.mul(An,to),to=wr.add(to,$a),new Jr(_i,ro,to)}subtract($n){return this.add($n.negate())}is0(){return this.equals(Jr.ZERO)}wNAF($n){return En.wNAFCached(this,$n,Jr.normalizeZ)}multiplyUnsafe($n){aInRange$1("scalar",$n,_0n$5,br.n);const Tn=Jr.ZERO;if($n===_0n$5)return Tn;if($n===_1n$8)return this;const{endo:In}=br;if(!In)return En.unsafeLadder(this,$n);let{k1neg:jn,k1:Yn,k2neg:ga,k2:na}=In.splitScalar($n),_i=Tn,ro=Tn,to=this;for(;Yn>_0n$5||na>_0n$5;)Yn&_1n$8&&(_i=_i.add(to)),na&_1n$8&&(ro=ro.add(to)),to=to.double(),Yn>>=_1n$8,na>>=_1n$8;return jn&&(_i=_i.negate()),ga&&(ro=ro.negate()),ro=new Jr(wr.mul(ro.px,In.beta),ro.py,ro.pz),_i.add(ro)}multiply($n){const{endo:Tn,n:In}=br;aInRange$1("scalar",$n,_1n$8,In);let jn,Yn;if(Tn){const{k1neg:ga,k1:na,k2neg:_i,k2:ro}=Tn.splitScalar($n);let{p:to,f:io}=this.wNAF(na),{p:no,f:$a}=this.wNAF(ro);to=En.constTimeNegate(ga,to),no=En.constTimeNegate(_i,no),no=new Jr(wr.mul(no.px,Tn.beta),no.py,no.pz),jn=to.add(no),Yn=io.add($a)}else{const{p:ga,f:na}=this.wNAF($n);jn=ga,Yn=na}return Jr.normalizeZ([jn,Yn])[0]}multiplyAndAddUnsafe($n,Tn,In){const jn=Jr.BASE,Yn=(na,_i)=>_i===_0n$5||_i===_1n$8||!na.equals(jn)?na.multiplyUnsafe(_i):na.multiply(_i),ga=Yn(this,Tn).add(Yn($n,In));return ga.is0()?void 0:ga}toAffine($n){return Hr(this,$n)}isTorsionFree(){const{h:$n,isTorsionFree:Tn}=br;if($n===_1n$8)return!0;if(Tn)return Tn(Jr,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:$n,clearCofactor:Tn}=br;return $n===_1n$8?this:Tn?Tn(Jr,this):this.multiplyUnsafe(br.h)}toRawBytes($n=!0){return abool$1("isCompressed",$n),this.assertValidity(),kr(Jr,this,$n)}toHex($n=!0){return abool$1("isCompressed",$n),bytesToHex$2(this.toRawBytes($n))}}Jr.BASE=new Jr(br.Gx,br.Gy,wr.ONE),Jr.ZERO=new Jr(wr.ZERO,wr.ONE,wr.ZERO);const Xr=br.nBitLength,En=wNAF$1(Jr,br.endo?Math.ceil(Xr/2):Xr);return{CURVE:br,ProjectivePoint:Jr,normPrivateKeyToScalar:Wr,weierstrassEquation:Br,isWithinCurveOrder:qr}}function validateOpts$2(fr){const br=validateBasic$1(fr);return validateObject$1(br,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...br})}function weierstrass$2(fr){const br=validateOpts$2(fr),{Fp:wr,n:Er}=br,kr=wr.BYTES+1,jr=2*wr.BYTES+1;function Br(Gr){return mod$1(Gr,Er)}function qr(Gr){return invert$1(Gr,Er)}const{ProjectivePoint:Wr,normPrivateKeyToScalar:Vr,weierstrassEquation:Hr,isWithinCurveOrder:Zr}=weierstrassPoints$1({...br,toBytes(Gr,Yr,Sn){const An=Yr.toAffine(),Pn=wr.toBytes(An.x),Nn=concatBytes$3;return abool$1("isCompressed",Sn),Sn?Nn(Uint8Array.from([Yr.hasEvenY()?2:3]),Pn):Nn(Uint8Array.from([4]),Pn,wr.toBytes(An.y))},fromBytes(Gr){const Yr=Gr.length,Sn=Gr[0],An=Gr.subarray(1);if(Yr===kr&&(Sn===2||Sn===3)){const Pn=bytesToNumberBE$1(An);if(!inRange$2(Pn,_1n$8,wr.ORDER))throw new Error("Point is not on curve");const Nn=Hr(Pn);let zn;try{zn=wr.sqrt(Nn)}catch(Zn){const oo=Zn instanceof Error?": "+Zn.message:"";throw new Error("Point is not on curve"+oo)}const On=(zn&_1n$8)===_1n$8;return(Sn&1)===1!==On&&(zn=wr.neg(zn)),{x:Pn,y:zn}}else if(Yr===jr&&Sn===4){const Pn=wr.fromBytes(An.subarray(0,wr.BYTES)),Nn=wr.fromBytes(An.subarray(wr.BYTES,2*wr.BYTES));return{x:Pn,y:Nn}}else throw new Error(`Point of length ${Yr} was invalid. Expected ${kr} compressed bytes or ${jr} uncompressed bytes`)}}),Jr=Gr=>bytesToHex$2(numberToBytesBE$1(Gr,br.nByteLength));function Xr(Gr){const Yr=Er>>_1n$8;return Gr>Yr}function En(Gr){return Xr(Gr)?Br(-Gr):Gr}const wn=(Gr,Yr,Sn)=>bytesToNumberBE$1(Gr.slice(Yr,Sn));class $n{constructor(Yr,Sn,An){this.r=Yr,this.s=Sn,this.recovery=An,this.assertValidity()}static fromCompact(Yr){const Sn=br.nByteLength;return Yr=ensureBytes$1("compactSignature",Yr,Sn*2),new $n(wn(Yr,0,Sn),wn(Yr,Sn,2*Sn))}static fromDER(Yr){const{r:Sn,s:An}=DER$1.toSig(ensureBytes$1("DER",Yr));return new $n(Sn,An)}assertValidity(){aInRange$1("r",this.r,_1n$8,Er),aInRange$1("s",this.s,_1n$8,Er)}addRecoveryBit(Yr){return new $n(this.r,this.s,Yr)}recoverPublicKey(Yr){const{r:Sn,s:An,recovery:Pn}=this,Nn=na(ensureBytes$1("msgHash",Yr));if(Pn==null||![0,1,2,3].includes(Pn))throw new Error("recovery id invalid");const zn=Pn===2||Pn===3?Sn+br.n:Sn;if(zn>=wr.ORDER)throw new Error("recovery id 2 or 3 invalid");const On=Pn&1?"03":"02",_n=Wr.fromHex(On+Jr(zn)),Zn=qr(zn),oo=Br(-Nn*Zn),uo=Br(An*Zn),lo=Wr.BASE.multiplyAndAddUnsafe(_n,oo,uo);if(!lo)throw new Error("point at infinify");return lo.assertValidity(),lo}hasHighS(){return Xr(this.s)}normalizeS(){return this.hasHighS()?new $n(this.r,Br(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes$2(this.toDERHex())}toDERHex(){return DER$1.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes$2(this.toCompactHex())}toCompactHex(){return Jr(this.r)+Jr(this.s)}}const Tn={isValidPrivateKey(Gr){try{return Vr(Gr),!0}catch{return!1}},normPrivateKeyToScalar:Vr,randomPrivateKey:()=>{const Gr=getMinHashLength$1(br.n);return mapHashToField$1(br.randomBytes(Gr),br.n)},precompute(Gr=8,Yr=Wr.BASE){return Yr._setWindowSize(Gr),Yr.multiply(BigInt(3)),Yr}};function In(Gr,Yr=!0){return Wr.fromPrivateKey(Gr).toRawBytes(Yr)}function jn(Gr){const Yr=isBytes$8(Gr),Sn=typeof Gr=="string",An=(Yr||Sn)&&Gr.length;return Yr?An===kr||An===jr:Sn?An===2*kr||An===2*jr:Gr instanceof Wr}function Yn(Gr,Yr,Sn=!0){if(jn(Gr))throw new Error("first arg must be private key");if(!jn(Yr))throw new Error("second arg must be public key");return Wr.fromHex(Yr).multiply(Vr(Gr)).toRawBytes(Sn)}const ga=br.bits2int||function(Gr){const Yr=bytesToNumberBE$1(Gr),Sn=Gr.length*8-br.nBitLength;return Sn>0?Yr>>BigInt(Sn):Yr},na=br.bits2int_modN||function(Gr){return Br(ga(Gr))},_i=bitMask$1(br.nBitLength);function ro(Gr){return aInRange$1(`num < 2^${br.nBitLength}`,Gr,_0n$5,_i),numberToBytesBE$1(Gr,br.nByteLength)}function to(Gr,Yr,Sn=io){if(["recovered","canonical"].some(so=>so in Sn))throw new Error("sign() legacy options not supported");const{hash:An,randomBytes:Pn}=br;let{lowS:Nn,prehash:zn,extraEntropy:On}=Sn;Nn==null&&(Nn=!0),Gr=ensureBytes$1("msgHash",Gr),validateSigVerOpts$1(Sn),zn&&(Gr=ensureBytes$1("prehashed msgHash",An(Gr)));const _n=na(Gr),Zn=Vr(Yr),oo=[ro(Zn),ro(_n)];if(On!=null&&On!==!1){const so=On===!0?Pn(wr.BYTES):On;oo.push(ensureBytes$1("extraEntropy",so))}const uo=concatBytes$3(...oo),lo=_n;function co(so){const yo=ga(so);if(!Zr(yo))return;const fo=qr(yo),ho=Wr.BASE.multiply(yo).toAffine(),vo=Br(ho.x);if(vo===_0n$5)return;const Io=Br(fo*Br(lo+vo*Zn));if(Io===_0n$5)return;let Ro=(ho.x===vo?0:2)|Number(ho.y&_1n$8),To=Io;return Nn&&Xr(Io)&&(To=En(Io),Ro^=1),new $n(vo,To,Ro)}return{seed:uo,k2sig:co}}const io={lowS:br.lowS,prehash:!1},no={lowS:br.lowS,prehash:!1};function $a(Gr,Yr,Sn=io){const{seed:An,k2sig:Pn}=to(Gr,Yr,Sn),Nn=br;return createHmacDrbg$1(Nn.hash.outputLen,Nn.nByteLength,Nn.hmac)(An,Pn)}Wr.BASE._setWindowSize(8);function Rn(Gr,Yr,Sn,An=no){var ho;const Pn=Gr;if(Yr=ensureBytes$1("msgHash",Yr),Sn=ensureBytes$1("publicKey",Sn),"strict"in An)throw new Error("options.strict was renamed to lowS");validateSigVerOpts$1(An);const{lowS:Nn,prehash:zn}=An;let On,_n;try{if(typeof Pn=="string"||isBytes$8(Pn))try{On=$n.fromDER(Pn)}catch(vo){if(!(vo instanceof DER$1.Err))throw vo;On=$n.fromCompact(Pn)}else if(typeof Pn=="object"&&typeof Pn.r=="bigint"&&typeof Pn.s=="bigint"){const{r:vo,s:Io}=Pn;On=new $n(vo,Io)}else throw new Error("PARSE");_n=Wr.fromHex(Sn)}catch(vo){if(vo.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(Nn&&On.hasHighS())return!1;zn&&(Yr=br.hash(Yr));const{r:Zn,s:oo}=On,uo=na(Yr),lo=qr(oo),co=Br(uo*lo),so=Br(Zn*lo),yo=(ho=Wr.BASE.multiplyAndAddUnsafe(_n,co,so))==null?void 0:ho.toAffine();return yo?Br(yo.x)===Zn:!1}return{CURVE:br,getPublicKey:In,getSharedSecret:Yn,sign:$a,verify:Rn,ProjectivePoint:Wr,Signature:$n,utils:Tn}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash$1(fr){return{hash:fr,hmac:(br,...wr)=>hmac$6(fr,br,concatBytes$5(...wr)),randomBytes:randomBytes$2}}function createCurve$1(fr,br){const wr=Er=>weierstrass$2({...fr,...getHash$1(Er)});return Object.freeze({...wr(br),create:wr})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P$1=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$7=BigInt(1),_2n$5=BigInt(2),divNearest$1=(fr,br)=>(fr+br/_2n$5)/br;function sqrtMod$1(fr){const br=secp256k1P$1,wr=BigInt(3),Er=BigInt(6),kr=BigInt(11),jr=BigInt(22),Br=BigInt(23),qr=BigInt(44),Wr=BigInt(88),Vr=fr*fr*fr%br,Hr=Vr*Vr*fr%br,Zr=pow2$1(Hr,wr,br)*Hr%br,Jr=pow2$1(Zr,wr,br)*Hr%br,Xr=pow2$1(Jr,_2n$5,br)*Vr%br,En=pow2$1(Xr,kr,br)*Xr%br,wn=pow2$1(En,jr,br)*En%br,$n=pow2$1(wn,qr,br)*wn%br,Tn=pow2$1($n,Wr,br)*$n%br,In=pow2$1(Tn,qr,br)*wn%br,jn=pow2$1(In,wr,br)*Hr%br,Yn=pow2$1(jn,Br,br)*En%br,ga=pow2$1(Yn,Er,br)*Vr%br,na=pow2$1(ga,_2n$5,br);if(!Fp$1.eql(Fp$1.sqr(na),fr))throw new Error("Cannot find square root");return na}const Fp$1=Field$1(secp256k1P$1,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1$3=createCurve$1({a:BigInt(0),b:BigInt(7),Fp:Fp$1,n:secp256k1N$1,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:fr=>{const br=secp256k1N$1,wr=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Er=-_1n$7*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),kr=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),jr=wr,Br=BigInt("0x100000000000000000000000000000000"),qr=divNearest$1(jr*fr,br),Wr=divNearest$1(-Er*fr,br);let Vr=mod$1(fr-qr*wr-Wr*kr,br),Hr=mod$1(-qr*Er-Wr*jr,br);const Zr=Vr>Br,Jr=Hr>Br;if(Zr&&(Vr=br-Vr),Jr&&(Hr=br-Hr),Vr>Br||Hr>Br)throw new Error("splitScalar: Endomorphism failed, k="+fr);return{k1neg:Zr,k1:Vr,k2neg:Jr,k2:Hr}}}},sha256$a);BigInt(0);secp256k1$3.ProjectivePoint;const secp256k1$4=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:secp256k1$3},Symbol.toStringTag,{value:"Module"}));function serializeSignature$1({r:fr,s:br,to:wr="hex",v:Er,yParity:kr}){const jr=(()=>{if(kr===0||kr===1)return kr;if(Er&&(Er===27n||Er===28n||Er>=35n))return Er%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),Br=`0x${new secp256k1$3.Signature(hexToBigInt(fr),hexToBigInt(br)).toCompactHex()}${jr===0?"1b":"1c"}`;return wr==="hex"?Br:hexToBytes$4(Br)}async function verifyHash$2(fr,br){var Zr,Jr,Xr;const{address:wr,factory:Er,factoryData:kr,hash:jr,signature:Br,universalSignatureVerifierAddress:qr=(Xr=(Jr=(Zr=fr.chain)==null?void 0:Zr.contracts)==null?void 0:Jr.universalSignatureVerifier)==null?void 0:Xr.address,...Wr}=br,Vr=isHex$1(Br)?Br:typeof Br=="object"&&"r"in Br&&"s"in Br?serializeSignature$1(Br):bytesToHex$4(Br),Hr=await(async()=>!Er&&!kr||isErc6492Signature$1(Vr)?Vr:serializeErc6492Signature$1({address:Er,data:kr,signature:Vr}))();try{const En=qr?{to:qr,data:encodeFunctionData$1({abi:universalSignatureValidatorAbi,functionName:"isValidSig",args:[wr,jr,Hr]}),...Wr}:{data:encodeDeployData$1({abi:universalSignatureValidatorAbi,args:[wr,jr,Hr],bytecode:universalSignatureValidatorByteCode}),...Wr},{data:wn}=await getAction$1(fr,call$1,"call")(En);return hexToBool(wn??"0x0")}catch(En){try{if(isAddressEqual$1(getAddress$1(wr),await recoverAddress$1({hash:jr,signature:Br})))return!0}catch{}if(En instanceof CallExecutionError)return!1;throw En}}async function verifyMessage$2(fr,{address:br,message:wr,factory:Er,factoryData:kr,signature:jr,...Br}){const qr=hashMessage$1(wr);return verifyHash$2(fr,{address:br,factory:Er,factoryData:kr,hash:qr,signature:jr,...Br})}async function verifyTypedData$2(fr,br){const{address:wr,factory:Er,factoryData:kr,signature:jr,message:Br,primaryType:qr,types:Wr,domain:Vr,...Hr}=br,Zr=hashTypedData$1({message:Br,primaryType:qr,types:Wr,domain:Vr});return verifyHash$2(fr,{address:wr,factory:Er,factoryData:kr,hash:Zr,signature:jr,...Hr})}function watchBlockNumber$1(fr,{emitOnBegin:br=!1,emitMissed:wr=!1,onBlockNumber:Er,onError:kr,poll:jr,pollingInterval:Br=fr.pollingInterval}){const qr=typeof jr<"u"?jr:!(fr.transport.type==="webSocket"||fr.transport.type==="fallback"&&fr.transport.transports[0].config.type==="webSocket");let Wr;return qr?(()=>{const Zr=stringify$5(["watchBlockNumber",fr.uid,br,wr,Br]);return observe$1(Zr,{onBlockNumber:Er,onError:kr},Jr=>poll$1(async()=>{var Xr;try{const En=await getAction$1(fr,getBlockNumber$1,"getBlockNumber")({cacheTime:0});if(Wr){if(En===Wr)return;if(En-Wr>1&&wr)for(let wn=Wr+1n;wnWr)&&(Jr.onBlockNumber(En,Wr),Wr=En)}catch(En){(Xr=Jr.onError)==null||Xr.call(Jr,En)}},{emitOnBegin:br,interval:Br}))})():(()=>{const Zr=stringify$5(["watchBlockNumber",fr.uid,br,wr]);return observe$1(Zr,{onBlockNumber:Er,onError:kr},Jr=>{let Xr=!0,En=()=>Xr=!1;return(async()=>{try{const wn=(()=>{if(fr.transport.type==="fallback"){const Tn=fr.transport.transports.find(In=>In.config.type==="webSocket");return Tn?Tn.value:fr.transport}return fr.transport})(),{unsubscribe:$n}=await wn.subscribe({params:["newHeads"],onData(Tn){var jn;if(!Xr)return;const In=hexToBigInt((jn=Tn.result)==null?void 0:jn.number);Jr.onBlockNumber(In,Wr),Wr=In},onError(Tn){var In;(In=Jr.onError)==null||In.call(Jr,Tn)}});En=$n,Xr||En()}catch(wn){kr==null||kr(wn)}})(),()=>En()})})()}async function waitForTransactionReceipt$1(fr,{confirmations:br=1,hash:wr,onReplaced:Er,pollingInterval:kr=fr.pollingInterval,retryCount:jr=6,retryDelay:Br=({count:Wr})=>~~(1<wn(new WaitForTransactionReceiptTimeoutError({hash:wr})),qr):void 0,Tn=observe$1(Wr,{onReplaced:Er,resolve:En,reject:wn},In=>{const jn=getAction$1(fr,watchBlockNumber$1,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:kr,async onBlockNumber(Yn){const ga=_i=>{clearTimeout($n),jn(),_i(),Tn()};let na=Yn;if(!Jr)try{if(Zr){if(br>1&&(!Zr.blockNumber||na-Zr.blockNumber+1nIn.resolve(Zr));return}if(Vr||(Jr=!0,await withRetry$1(async()=>{Vr=await getAction$1(fr,getTransaction$1,"getTransaction")({hash:wr}),Vr.blockNumber&&(na=Vr.blockNumber)},{delay:Br,retryCount:jr}),Jr=!1),Zr=await getAction$1(fr,getTransactionReceipt$1,"getTransactionReceipt")({hash:wr}),br>1&&(!Zr.blockNumber||na-Zr.blockNumber+1nIn.resolve(Zr))}catch(_i){if(_i instanceof TransactionNotFoundError||_i instanceof TransactionReceiptNotFoundError){if(!Vr){Jr=!1;return}try{Hr=Vr,Jr=!0;const ro=await withRetry$1(()=>getAction$1(fr,getBlock$1,"getBlock")({blockNumber:na,includeTransactions:!0}),{delay:Br,retryCount:jr,shouldRetry:({error:no})=>no instanceof BlockNotFoundError});Jr=!1;const to=ro.transactions.find(({from:no,nonce:$a})=>no===Hr.from&&$a===Hr.nonce);if(!to||(Zr=await getAction$1(fr,getTransactionReceipt$1,"getTransactionReceipt")({hash:to.hash}),br>1&&(!Zr.blockNumber||na-Zr.blockNumber+1n{var no;(no=In.onReplaced)==null||no.call(In,{reason:io,replacedTransaction:Hr,transaction:to,transactionReceipt:Zr}),In.resolve(Zr)})}catch(ro){ga(()=>In.reject(ro))}}else ga(()=>In.reject(_i))}}})});return Xr}function watchBlocks$1(fr,{blockTag:br="latest",emitMissed:wr=!1,emitOnBegin:Er=!1,onBlock:kr,onError:jr,includeTransactions:Br,poll:qr,pollingInterval:Wr=fr.pollingInterval}){const Vr=typeof qr<"u"?qr:!(fr.transport.type==="webSocket"||fr.transport.type==="fallback"&&fr.transport.transports[0].config.type==="webSocket"),Hr=Br??!1;let Zr;return Vr?(()=>{const En=stringify$5(["watchBlocks",fr.uid,br,wr,Er,Hr,Wr]);return observe$1(En,{onBlock:kr,onError:jr},wn=>poll$1(async()=>{var $n;try{const Tn=await getAction$1(fr,getBlock$1,"getBlock")({blockTag:br,includeTransactions:Hr});if(Tn.number&&(Zr!=null&&Zr.number)){if(Tn.number===Zr.number)return;if(Tn.number-Zr.number>1&&wr)for(let In=(Zr==null?void 0:Zr.number)+1n;InZr.number)&&(wn.onBlock(Tn,Zr),Zr=Tn)}catch(Tn){($n=wn.onError)==null||$n.call(wn,Tn)}},{emitOnBegin:Er,interval:Wr}))})():(()=>{let En=!0,wn=!0,$n=()=>En=!1;return(async()=>{try{Er&&getAction$1(fr,getBlock$1,"getBlock")({blockTag:br,includeTransactions:Hr}).then(jn=>{En&&wn&&(kr(jn,void 0),wn=!1)});const Tn=(()=>{if(fr.transport.type==="fallback"){const jn=fr.transport.transports.find(Yn=>Yn.config.type==="webSocket");return jn?jn.value:fr.transport}return fr.transport})(),{unsubscribe:In}=await Tn.subscribe({params:["newHeads"],async onData(jn){if(!En)return;const Yn=await getAction$1(fr,getBlock$1,"getBlock")({blockNumber:jn.blockNumber,includeTransactions:Hr}).catch(()=>{});En&&(kr(Yn,Zr),wn=!1,Zr=Yn)},onError(jn){jr==null||jr(jn)}});$n=In,En||$n()}catch(Tn){jr==null||jr(Tn)}})(),()=>$n()})()}function watchEvent$1(fr,{address:br,args:wr,batch:Er=!0,event:kr,events:jr,fromBlock:Br,onError:qr,onLogs:Wr,poll:Vr,pollingInterval:Hr=fr.pollingInterval,strict:Zr}){const Jr=typeof Vr<"u"?Vr:typeof Br=="bigint"?!0:!(fr.transport.type==="webSocket"||fr.transport.type==="fallback"&&fr.transport.transports[0].config.type==="webSocket"),Xr=Zr??!1;return Jr?(()=>{const $n=stringify$5(["watchEvent",br,wr,Er,fr.uid,kr,Hr,Br]);return observe$1($n,{onLogs:Wr,onError:qr},Tn=>{let In;Br!==void 0&&(In=Br-1n);let jn,Yn=!1;const ga=poll$1(async()=>{var na;if(!Yn){try{jn=await getAction$1(fr,createEventFilter$1,"createEventFilter")({address:br,args:wr,event:kr,events:jr,strict:Xr,fromBlock:Br})}catch{}Yn=!0;return}try{let _i;if(jn)_i=await getAction$1(fr,getFilterChanges$1,"getFilterChanges")({filter:jn});else{const ro=await getAction$1(fr,getBlockNumber$1,"getBlockNumber")({});In&&In!==ro?_i=await getAction$1(fr,getLogs$1,"getLogs")({address:br,args:wr,event:kr,events:jr,fromBlock:In+1n,toBlock:ro}):_i=[],In=ro}if(_i.length===0)return;if(Er)Tn.onLogs(_i);else for(const ro of _i)Tn.onLogs([ro])}catch(_i){jn&&_i instanceof InvalidInputRpcError&&(Yn=!1),(na=Tn.onError)==null||na.call(Tn,_i)}},{emitOnBegin:!0,interval:Hr});return async()=>{jn&&await getAction$1(fr,uninstallFilter$1,"uninstallFilter")({filter:jn}),ga()}})})():(()=>{let $n=!0,Tn=()=>$n=!1;return(async()=>{try{const In=(()=>{if(fr.transport.type==="fallback"){const na=fr.transport.transports.find(_i=>_i.config.type==="webSocket");return na?na.value:fr.transport}return fr.transport})(),jn=jr??(kr?[kr]:void 0);let Yn=[];jn&&(Yn=[jn.flatMap(_i=>encodeEventTopics$1({abi:[_i],eventName:_i.name,args:wr}))],kr&&(Yn=Yn[0]));const{unsubscribe:ga}=await In.subscribe({params:["logs",{address:br,topics:Yn}],onData(na){var ro;if(!$n)return;const _i=na.result;try{const{eventName:to,args:io}=decodeEventLog$1({abi:jn??[],data:_i.data,topics:_i.topics,strict:Xr}),no=formatLog(_i,{args:io,eventName:to});Wr([no])}catch(to){let io,no;if(to instanceof DecodeLogDataMismatch||to instanceof DecodeLogTopicsMismatch){if(Zr)return;io=to.abiItem.name,no=(ro=to.abiItem.inputs)==null?void 0:ro.some(Rn=>!("name"in Rn&&Rn.name))}const $a=formatLog(_i,{args:no?[]:{},eventName:io});Wr([$a])}},onError(na){qr==null||qr(na)}});Tn=ga,$n||Tn()}catch(In){qr==null||qr(In)}})(),()=>Tn()})()}function watchPendingTransactions$1(fr,{batch:br=!0,onError:wr,onTransactions:Er,poll:kr,pollingInterval:jr=fr.pollingInterval}){return(typeof kr<"u"?kr:fr.transport.type!=="webSocket")?(()=>{const Vr=stringify$5(["watchPendingTransactions",fr.uid,br,jr]);return observe$1(Vr,{onTransactions:Er,onError:wr},Hr=>{let Zr;const Jr=poll$1(async()=>{var Xr;try{if(!Zr)try{Zr=await getAction$1(fr,createPendingTransactionFilter$1,"createPendingTransactionFilter")({});return}catch(wn){throw Jr(),wn}const En=await getAction$1(fr,getFilterChanges$1,"getFilterChanges")({filter:Zr});if(En.length===0)return;if(br)Hr.onTransactions(En);else for(const wn of En)Hr.onTransactions([wn])}catch(En){(Xr=Hr.onError)==null||Xr.call(Hr,En)}},{emitOnBegin:!0,interval:jr});return async()=>{Zr&&await getAction$1(fr,uninstallFilter$1,"uninstallFilter")({filter:Zr}),Jr()}})})():(()=>{let Vr=!0,Hr=()=>Vr=!1;return(async()=>{try{const{unsubscribe:Zr}=await fr.transport.subscribe({params:["newPendingTransactions"],onData(Jr){if(!Vr)return;const Xr=Jr.result;Er([Xr])},onError(Jr){wr==null||wr(Jr)}});Hr=Zr,Vr||Hr()}catch(Zr){wr==null||wr(Zr)}})(),()=>Hr()})()}function parseSiweMessage$1(fr){var Zr,Jr,Xr;const{scheme:br,statement:wr,...Er}=((Zr=fr.match(prefixRegex))==null?void 0:Zr.groups)??{},{chainId:kr,expirationTime:jr,issuedAt:Br,notBefore:qr,requestId:Wr,...Vr}=((Jr=fr.match(suffixRegex))==null?void 0:Jr.groups)??{},Hr=(Xr=fr.split("Resources:")[1])==null?void 0:Xr.split(` -- `).slice(1);return{...Er,...Vr,...kr?{chainId:Number(kr)}:{},...jr?{expirationTime:new Date(jr)}:{},...Br?{issuedAt:new Date(Br)}:{},...qr?{notBefore:new Date(qr)}:{},...Wr?{requestId:Wr}:{},...Hr?{resources:Hr}:{},...br?{scheme:br}:{},...wr?{statement:wr}:{}}}const prefixRegex=/^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,suffixRegex=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/;function validateSiweMessage$1(fr){const{address:br,domain:wr,message:Er,nonce:kr,scheme:jr,time:Br=new Date}=fr;if(wr&&Er.domain!==wr||kr&&Er.nonce!==kr||jr&&Er.scheme!==jr||Er.expirationTime&&Br>=Er.expirationTime||Er.notBefore&&Brcall$1(fr,br),createBlockFilter:()=>createBlockFilter$1(fr),createContractEventFilter:br=>createContractEventFilter$1(fr,br),createEventFilter:br=>createEventFilter$1(fr,br),createPendingTransactionFilter:()=>createPendingTransactionFilter$1(fr),estimateContractGas:br=>estimateContractGas$1(fr,br),estimateGas:br=>estimateGas$4(fr,br),getBalance:br=>getBalance$1(fr,br),getBlobBaseFee:()=>getBlobBaseFee$1(fr),getBlock:br=>getBlock$1(fr,br),getBlockNumber:br=>getBlockNumber$1(fr,br),getBlockTransactionCount:br=>getBlockTransactionCount$1(fr,br),getBytecode:br=>getCode$1(fr,br),getChainId:()=>getChainId$1(fr),getCode:br=>getCode$1(fr,br),getContractEvents:br=>getContractEvents$1(fr,br),getEip712Domain:br=>getEip712Domain$3(fr,br),getEnsAddress:br=>getEnsAddress$1(fr,br),getEnsAvatar:br=>getEnsAvatar$1(fr,br),getEnsName:br=>getEnsName$1(fr,br),getEnsResolver:br=>getEnsResolver$1(fr,br),getEnsText:br=>getEnsText$1(fr,br),getFeeHistory:br=>getFeeHistory$1(fr,br),estimateFeesPerGas:br=>estimateFeesPerGas$2(fr,br),getFilterChanges:br=>getFilterChanges$1(fr,br),getFilterLogs:br=>getFilterLogs$1(fr,br),getGasPrice:()=>getGasPrice$1(fr),getLogs:br=>getLogs$1(fr,br),getProof:br=>getProof$1(fr,br),estimateMaxPriorityFeePerGas:br=>estimateMaxPriorityFeePerGas$1(fr,br),getStorageAt:br=>getStorageAt$1(fr,br),getTransaction:br=>getTransaction$1(fr,br),getTransactionConfirmations:br=>getTransactionConfirmations$1(fr,br),getTransactionCount:br=>getTransactionCount$1(fr,br),getTransactionReceipt:br=>getTransactionReceipt$1(fr,br),multicall:br=>multicall$1(fr,br),prepareTransactionRequest:br=>prepareTransactionRequest$1(fr,br),readContract:br=>readContract$1(fr,br),sendRawTransaction:br=>sendRawTransaction$1(fr,br),simulateContract:br=>simulateContract$1(fr,br),verifyMessage:br=>verifyMessage$2(fr,br),verifySiweMessage:br=>verifySiweMessage$1(fr,br),verifyTypedData:br=>verifyTypedData$2(fr,br),uninstallFilter:br=>uninstallFilter$1(fr,br),waitForTransactionReceipt:br=>waitForTransactionReceipt$1(fr,br),watchBlocks:br=>watchBlocks$1(fr,br),watchBlockNumber:br=>watchBlockNumber$1(fr,br),watchContractEvent:br=>watchContractEvent$1(fr,br),watchEvent:br=>watchEvent$1(fr,br),watchPendingTransactions:br=>watchPendingTransactions$1(fr,br)}}function createPublicClient$1(fr){const{key:br="public",name:wr="Public Client"}=fr;return createClient$1({...fr,key:br,name:wr,type:"publicClient"}).extend(publicActions)}function deployContract$1(fr,br){const{abi:wr,args:Er,bytecode:kr,...jr}=br,Br=encodeDeployData$1({abi:wr,args:Er,bytecode:kr});return sendTransaction$1(fr,{...jr,data:Br})}async function getAddresses$1(fr){var wr;return((wr=fr.account)==null?void 0:wr.type)==="local"?[fr.account.address]:(await fr.request({method:"eth_accounts"},{dedupe:!0})).map(Er=>checksumAddress(Er))}async function getPermissions$1(fr){return await fr.request({method:"wallet_getPermissions"},{dedupe:!0})}async function requestAddresses$1(fr){return(await fr.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(wr=>getAddress$1(wr))}async function requestPermissions$1(fr,br){return fr.request({method:"wallet_requestPermissions",params:[br]},{retryCount:0})}async function signMessage$3(fr,{account:br=fr.account,message:wr}){if(!br)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signMessage"});const Er=parseAccount$1(br);if(Er.signMessage)return Er.signMessage({message:wr});const kr=typeof wr=="string"?stringToHex(wr):wr.raw instanceof Uint8Array?toHex$1(wr.raw):wr.raw;return fr.request({method:"personal_sign",params:[kr,Er.address]},{retryCount:0})}async function signTransaction$3(fr,br){var Vr,Hr,Zr,Jr;const{account:wr=fr.account,chain:Er=fr.chain,...kr}=br;if(!wr)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTransaction"});const jr=parseAccount$1(wr);assertRequest$1({account:jr,...br});const Br=await getAction$1(fr,getChainId$1,"getChainId")({});Er!==null&&assertCurrentChain$1({currentChainId:Br,chain:Er});const qr=(Er==null?void 0:Er.formatters)||((Vr=fr.chain)==null?void 0:Vr.formatters),Wr=((Hr=qr==null?void 0:qr.transactionRequest)==null?void 0:Hr.format)||formatTransactionRequest;return jr.signTransaction?jr.signTransaction({...kr,chainId:Br},{serializer:(Jr=(Zr=fr.chain)==null?void 0:Zr.serializers)==null?void 0:Jr.transaction}):await fr.request({method:"eth_signTransaction",params:[{...Wr(kr),chainId:numberToHex(Br),from:jr.address}]},{retryCount:0})}async function signTypedData$3(fr,br){const{account:wr=fr.account,domain:Er,message:kr,primaryType:jr}=br;if(!wr)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTypedData"});const Br=parseAccount$1(wr),qr={EIP712Domain:getTypesForEIP712Domain({domain:Er}),...br.types};if(validateTypedData({domain:Er,message:kr,primaryType:jr,types:qr}),Br.signTypedData)return Br.signTypedData({domain:Er,message:kr,primaryType:jr,types:qr});const Wr=serializeTypedData({domain:Er,message:kr,primaryType:jr,types:qr});return fr.request({method:"eth_signTypedData_v4",params:[Br.address,Wr]},{retryCount:0})}async function switchChain$1(fr,{id:br}){await fr.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(br)}]},{retryCount:0})}async function watchAsset$1(fr,br){return await fr.request({method:"wallet_watchAsset",params:br},{retryCount:0})}function walletActions(fr){return{addChain:br=>addChain$1(fr,br),deployContract:br=>deployContract$1(fr,br),getAddresses:()=>getAddresses$1(fr),getChainId:()=>getChainId$1(fr),getPermissions:()=>getPermissions$1(fr),prepareTransactionRequest:br=>prepareTransactionRequest$1(fr,br),requestAddresses:()=>requestAddresses$1(fr),requestPermissions:br=>requestPermissions$1(fr,br),sendRawTransaction:br=>sendRawTransaction$1(fr,br),sendTransaction:br=>sendTransaction$1(fr,br),signMessage:br=>signMessage$3(fr,br),signTransaction:br=>signTransaction$3(fr,br),signTypedData:br=>signTypedData$3(fr,br),switchChain:br=>switchChain$1(fr,br),watchAsset:br=>watchAsset$1(fr,br),writeContract:br=>writeContract$1(fr,br)}}function createWalletClient$1(fr){const{key:br="wallet",name:wr="Wallet Client",transport:Er}=fr;return createClient$1({...fr,key:br,name:wr,transport:Er,type:"walletClient"}).extend(walletActions)}const crypto$5=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function anumber$3(fr){if(!Number.isSafeInteger(fr)||fr<0)throw new Error("positive integer expected, got "+fr)}function isBytes$7(fr){return fr instanceof Uint8Array||ArrayBuffer.isView(fr)&&fr.constructor.name==="Uint8Array"}function abytes$2(fr,...br){if(!isBytes$7(fr))throw new Error("Uint8Array expected");if(br.length>0&&!br.includes(fr.length))throw new Error("Uint8Array expected of length "+br+", got length="+fr.length)}function ahash$1(fr){if(typeof fr!="function"||typeof fr.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");anumber$3(fr.outputLen),anumber$3(fr.blockLen)}function aexists$1(fr,br=!0){if(fr.destroyed)throw new Error("Hash instance has been destroyed");if(br&&fr.finished)throw new Error("Hash#digest() has already been called")}function aoutput$1(fr,br){abytes$2(fr);const wr=br.outputLen;if(fr.lengthnew Uint8Array(fr.buffer,fr.byteOffset,fr.byteLength),u32$1=fr=>new Uint32Array(fr.buffer,fr.byteOffset,Math.floor(fr.byteLength/4)),createView$1=fr=>new DataView(fr.buffer,fr.byteOffset,fr.byteLength),rotr$1=(fr,br)=>fr<<32-br|fr>>>br,rotl=(fr,br)=>fr<>>32-br>>>0,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,byteSwap=fr=>fr<<24&4278190080|fr<<8&16711680|fr>>>8&65280|fr>>>24&255,byteSwapIfBE=isLE?fr=>fr:fr=>byteSwap(fr);function byteSwap32(fr){for(let br=0;brbr.toString(16).padStart(2,"0"));function bytesToHex$1(fr){abytes$2(fr);let br="";for(let wr=0;wr=asciis$1._0&&fr<=asciis$1._9)return fr-asciis$1._0;if(fr>=asciis$1.A&&fr<=asciis$1.F)return fr-(asciis$1.A-10);if(fr>=asciis$1.a&&fr<=asciis$1.f)return fr-(asciis$1.a-10)}function hexToBytes$1(fr){if(typeof fr!="string")throw new Error("hex string expected, got "+typeof fr);const br=fr.length,wr=br/2;if(br%2)throw new Error("hex string expected, got unpadded hex of length "+br);const Er=new Uint8Array(wr);for(let kr=0,jr=0;kr{};async function asyncLoop(fr,br,wr){let Er=Date.now();for(let kr=0;kr=0&&jrfr().update(toBytes$2(Er)).digest(),wr=fr();return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=()=>fr(),br}function wrapConstructorWithOpts(fr){const br=(Er,kr)=>fr(kr).update(toBytes$2(Er)).digest(),wr=fr({});return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=Er=>fr(Er),br}function wrapXOFConstructorWithOpts(fr){const br=(Er,kr)=>fr(kr).update(toBytes$2(Er)).digest(),wr=fr({});return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=Er=>fr(Er),br}function randomBytes$1(fr=32){if(crypto$5&&typeof crypto$5.getRandomValues=="function")return crypto$5.getRandomValues(new Uint8Array(fr));if(crypto$5&&typeof crypto$5.randomBytes=="function")return crypto$5.randomBytes(fr);throw new Error("crypto.getRandomValues must be defined")}const utils$h=Object.freeze(Object.defineProperty({__proto__:null,Hash:Hash$2,asyncLoop,byteSwap,byteSwap32,byteSwapIfBE,bytesToHex:bytesToHex$1,checkOpts,concatBytes:concatBytes$2,createView:createView$1,hexToBytes:hexToBytes$1,isBytes:isBytes$6,isLE,nextTick,randomBytes:randomBytes$1,rotl,rotr:rotr$1,toBytes:toBytes$2,u32:u32$1,u8:u8$1,utf8ToBytes:utf8ToBytes$2,wrapConstructor:wrapConstructor$1,wrapConstructorWithOpts,wrapXOFConstructorWithOpts},Symbol.toStringTag,{value:"Module"})),xv=class xv{};_f(xv,"initialize",async(br,wr="WALLETCLIENT")=>wr==="DYNAMIC"?xv.convertDynamicProvider(br):xv.convertViemWalletClient(br)),_f(xv,"convertViemWalletClient",async br=>{try{const wr=br.account;if(!wr)throw new Error("WalletClient Account Undefined");const Er=await br.getChainId(),kr=async jr=>{const Br=await br.signMessage({message:jr,account:wr});return hexToBytes$1(Br.replace("0x",""))};return{account:`eip155:${Er}:${getAddress$1(wr.address)}`,signMessage:kr}}catch{throw new Error("Invalid WalletClient")}}),_f(xv,"convertDynamicProvider",async br=>{try{let wr=br.address;isAddress$1(wr,{strict:!1})&&(wr=getAddress$1(wr));const Er=chainToNamespace[br.chain];if(Er===void 0)throw new Error("Unsupported Namespace");let kr=await br.getNetwork();Er==="solana"&&(kr=networkToSolChainId[kr]);const jr=async Br=>{let qr=typeof Br=="string"?Br:bytesToString(Br);br.key==="coinbase"&&br.chain==="EVM"&&qr.startsWith("0x")&&(qr=stringToHex(qr));const Wr=await br.signMessage(qr);return isHex$1(Wr)?hexToBytes$1(Wr.replace("0x","")):Buffer$2.from(Wr,"base64")};return{account:`${Er}:${kr}:${wr}`,signMessage:jr}}catch{throw new Error("Invalid Dynamic Provider")}});let PushSigner=xv;const WalletContext=reactExports.createContext({handleUserLoggedIn:()=>{},handleLogOutEvent:()=>{},handleAppConnectionSuccess:()=>{},handleAppConnectionRejected:()=>{},handleRejectAllAppConnections:()=>{}});function useEventEmitterContext(){const fr=reactExports.useContext(WalletContext);if(!fr)throw new Error("useWalletState must be used within a WalletProvider");return fr}const EventEmitterProvider=({children:fr})=>{const{dispatch:br,state:wr}=useGlobalState(),[Er,kr]=reactExports.useState(!1),jr=reactExports.useRef(wr.wallet);jr.current=wr.wallet,reactExports.useEffect(()=>{jr.current&&!Er&&(kr(!0),Xr())},[jr.current]);const Br=reactExports.useRef(null);reactExports.useEffect(()=>{wr.dynamicWallet&&!Er&&(async()=>(Br.current=await PushSigner.initialize(wr.dynamicWallet,"DYNAMIC"),kr(!0),Xr()))()},[wr.dynamicWallet]),reactExports.useEffect(()=>{getAppParamValue()&&(window.onbeforeunload=()=>{window.opener&&wn()});const $n=Tn=>{if(Tn.origin===getAppParamValue())switch(Tn.data.type){case APP_TO_WALLET_ACTION.NEW_CONNECTION_REQUEST:Wr(Tn.origin);break;case APP_TO_WALLET_ACTION.SIGN_MESSAGE:console.log("Signing Message on wallet tab"),Jr(Tn.data.data,Tn.origin);break;default:console.warn("Unknown message type:",Tn.data.type)}};return window.addEventListener("message",$n),()=>{window.removeEventListener("message",$n)}},[]);const qr=$n=>{if(window.opener)try{window.opener.postMessage($n,getAppParamValue())}catch(Tn){console.error("Error sending message to main tab:",Tn)}},Wr=$n=>{const Tn=requestToConnectPushWallet($n);if(Tn.find(jn=>jn.origin===$n).appConnectionStatus==="connected"){Vr($n);return}br({type:"SET_APP_CONNECTIONS",payload:Tn})},Vr=$n=>{const Tn=acceptPushWalletConnectionRequest($n);br({type:"SET_APP_CONNECTIONS",payload:Tn}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_SUCCESS,data:{account:jr.current.signerAccount}})},Hr=$n=>{const Tn=rejectPushWalletConnectionRequest($n);br({type:"SET_APP_CONNECTIONS",payload:Tn}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_REJECTED,data:{account:null}})},Zr=()=>{const $n=rejectAllPushWalletConnectionRequests();br({type:"SET_APP_CONNECTIONS",payload:$n}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_REJECTED,data:{account:null}})},Jr=async($n,Tn)=>{var In,jn;console.log("Signing message",$n,Tn);try{br({type:"SET_MESSAGE_SIGN_STATE",payload:"loading"});const Yn=Br!=null&&Br.current?await((In=Br==null?void 0:Br.current)==null?void 0:In.signMessage($n)):await jr.current.sign($n,Tn,getAllAppConnections());console.log("Signature signed",Yn),qr({type:WALLET_TO_APP_ACTION.SIGNATURE,data:{signature:Yn}}),(jn=Br==null?void 0:Br.current)!=null&&jn.account?br({type:"SET_MESSAGE_SIGN_STATE",payload:"idle"}):setTimeout(()=>br({type:"SET_MESSAGE_SIGN_STATE",payload:"idle"}),2e3)}catch(Yn){console.log(Yn),br({type:"SET_MESSAGE_SIGN_STATE",payload:"rejected"})}},Xr=()=>{var $n,Tn;qr({type:WALLET_TO_APP_ACTION.IS_LOGGED_IN,data:{account:(($n=Br==null?void 0:Br.current)==null?void 0:$n.account)??null}}),(Tn=Br==null?void 0:Br.current)!=null&&Tn.account&&br({type:"SET_EXTERNAL_WALLET_APP_CONNECTION_STATUS",payload:"connected"})},En=()=>{qr({type:WALLET_TO_APP_ACTION.IS_LOGGED_OUT,data:{account:null}}),kr(!1),jr.current=null,Br.current=null,getAppParamValue()&&window.close()},wn=()=>{};return jsxRuntimeExports.jsx(WalletContext.Provider,{value:{handleUserLoggedIn:Xr,handleLogOutEvent:En,handleAppConnectionSuccess:Vr,handleAppConnectionRejected:Hr,handleRejectAllAppConnections:Zr},children:fr})},WalletProfile=({selectedWallet:fr})=>{const{primaryWallet:br,handleLogOut:wr}=useDynamicContext(),Er=(fr==null?void 0:fr.address)||(br==null?void 0:br.address),kr=(fr==null?void 0:fr.name)??"External Wallet",[jr,Br]=reactExports.useState(!1),{dispatch:qr}=useGlobalState(),{handleLogOutEvent:Wr}=useEventEmitterContext(),Vr=useNavigate(),Hr=()=>{var Zr;qr({type:"RESET_WALLET"}),(Zr=br==null?void 0:br.connector)==null||Zr.endSession(),wr(),Wr(),sessionStorage.removeItem("jwt"),localStorage.clear(),Vr(APP_ROUTES.AUTH)};return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:"spacing-sm",width:"-webkit-fill-available",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"space-between",width:"-webkit-fill-available",children:[jsxRuntimeExports.jsx(PushLogo,{height:48,width:48}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:"spacing-xxs",children:jsxRuntimeExports.jsx(Dropdown,{overlay:jsxRuntimeExports.jsx(Menu,{children:jsxRuntimeExports.jsx(MenuItem,{label:"Log Out",icon:jsxRuntimeExports.jsx(Logout,{}),onClick:()=>{Hr()}})}),children:jsxRuntimeExports.jsx(Box,{cursor:"pointer",children:jsxRuntimeExports.jsx(Settings,{size:24,color:"icon-primary"})})})})]}),jsxRuntimeExports.jsx(Box,{width:"56px",height:"56px",borderRadius:"radius-xl",overflow:"hidden",alignSelf:"center",children:jsxRuntimeExports.jsx(BlockiesSvg,{address:Er})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",alignItems:"center",gap:"spacing-xxxs",children:[jsxRuntimeExports.jsx(Text,{variant:"bl-semibold",children:kr}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:"spacing-xxxs",children:[jsxRuntimeExports.jsx(Text,{variant:"bes-semibold",color:"text-tertiary",children:centerMaskWalletAddress(Er)}),jsxRuntimeExports.jsx(Box,{cursor:"pointer",children:jsxRuntimeExports.jsx(Tooltip,{title:jr?"Copy":"Copied",children:jr?jsxRuntimeExports.jsx(TickCircleFilled,{autoSize:!0,size:16,color:"icon-state-success-bold"}):jsxRuntimeExports.jsx(Copy,{color:"icon-tertiary",onClick:()=>handleCopy(Er,Br)})})})]})]})]})};var src$5={};const require$$0$c=getAugmentedNamespace(tslib_es6$4);var lib$1={},pushNetwork={},block$3={},validator$1={},utils$g={},hasRequiredUtils$d;function requireUtils$d(){if(hasRequiredUtils$d)return utils$g;hasRequiredUtils$d=1,Object.defineProperty(utils$g,"__esModule",{value:!0}),utils$g.getRandomElement=void 0;const fr=br=>{if(br.length===0)throw new Error("Array cannot be empty");const wr=Math.floor(Math.random()*br.length);return br[wr]};return utils$g.getRandomElement=fr,utils$g}const require$$2$4=getAugmentedNamespace(axios);var _cjs={};const require$$0$b=getAugmentedNamespace(exports$1);var getContract={},getAction={},hasRequiredGetAction;function requireGetAction(){if(hasRequiredGetAction)return getAction;hasRequiredGetAction=1,Object.defineProperty(getAction,"__esModule",{value:!0}),getAction.getAction=fr;function fr(br,wr,Er){const kr=br[wr.name];if(typeof kr=="function")return kr;const jr=br[Er];return typeof jr=="function"?jr:Br=>wr(br,Br)}return getAction}var createContractEventFilter={},encodeEventTopics={},abi$2={},formatAbiItem={},hasRequiredFormatAbiItem;function requireFormatAbiItem(){if(hasRequiredFormatAbiItem)return formatAbiItem;hasRequiredFormatAbiItem=1,Object.defineProperty(formatAbiItem,"__esModule",{value:!0}),formatAbiItem.formatAbiItem=br,formatAbiItem.formatAbiParams=wr;const fr=requireAbi();function br(kr,{includeName:jr=!1}={}){if(kr.type!=="function"&&kr.type!=="event"&&kr.type!=="error")throw new fr.InvalidDefinitionTypeError(kr.type);return`${kr.name}(${wr(kr.inputs,{includeName:jr})})`}function wr(kr,{includeName:jr=!1}={}){return kr?kr.map(Br=>Er(Br,{includeName:jr})).join(jr?", ":","):""}function Er(kr,{includeName:jr}){return kr.type.startsWith("tuple")?`(${wr(kr.components,{includeName:jr})})${kr.type.slice(5)}`:kr.type+(jr&&kr.name?` ${kr.name}`:"")}return formatAbiItem}var size={},isHex={},hasRequiredIsHex;function requireIsHex(){if(hasRequiredIsHex)return isHex;hasRequiredIsHex=1,Object.defineProperty(isHex,"__esModule",{value:!0}),isHex.isHex=fr;function fr(br,{strict:wr=!0}={}){return!br||typeof br!="string"?!1:wr?/^0x[0-9a-fA-F]*$/.test(br):br.startsWith("0x")}return isHex}var hasRequiredSize;function requireSize(){if(hasRequiredSize)return size;hasRequiredSize=1,Object.defineProperty(size,"__esModule",{value:!0}),size.size=br;const fr=requireIsHex();function br(wr){return(0,fr.isHex)(wr,{strict:!1})?Math.ceil((wr.length-2)/2):wr.length}return size}var base$9={},version$g={},hasRequiredVersion$1;function requireVersion$1(){return hasRequiredVersion$1||(hasRequiredVersion$1=1,Object.defineProperty(version$g,"__esModule",{value:!0}),version$g.version=void 0,version$g.version="2.21.53"),version$g}var hasRequiredBase$3;function requireBase$3(){if(hasRequiredBase$3)return base$9;hasRequiredBase$3=1,Object.defineProperty(base$9,"__esModule",{value:!0}),base$9.BaseError=void 0,base$9.setErrorConfig=wr;const fr=requireVersion$1();let br={getDocsUrl:({docsBaseUrl:jr,docsPath:Br="",docsSlug:qr})=>Br?`${jr??"https://viem.sh"}${Br}${qr?`#${qr}`:""}`:void 0,version:`viem@${fr.version}`};function wr(jr){br=jr}class Er extends Error{constructor(Br,qr={}){var Jr;const Wr=(()=>{var Xr;return qr.cause instanceof Er?qr.cause.details:(Xr=qr.cause)!=null&&Xr.message?qr.cause.message:qr.details})(),Vr=qr.cause instanceof Er&&qr.cause.docsPath||qr.docsPath,Hr=(Jr=br.getDocsUrl)==null?void 0:Jr.call(br,{...qr,docsPath:Vr}),Zr=[Br||"An error occurred.","",...qr.metaMessages?[...qr.metaMessages,""]:[],...Hr?[`Docs: ${Hr}`]:[],...Wr?[`Details: ${Wr}`]:[],...br.version?[`Version: ${br.version}`]:[]].join(` +- `).slice(1);return{...Er,...Vr,...kr?{chainId:Number(kr)}:{},...jr?{expirationTime:new Date(jr)}:{},...Br?{issuedAt:new Date(Br)}:{},...qr?{notBefore:new Date(qr)}:{},...Wr?{requestId:Wr}:{},...Hr?{resources:Hr}:{},...br?{scheme:br}:{},...wr?{statement:wr}:{}}}const prefixRegex=/^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,suffixRegex=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/;function validateSiweMessage$1(fr){const{address:br,domain:wr,message:Er,nonce:kr,scheme:jr,time:Br=new Date}=fr;if(wr&&Er.domain!==wr||kr&&Er.nonce!==kr||jr&&Er.scheme!==jr||Er.expirationTime&&Br>=Er.expirationTime||Er.notBefore&&Brcall$1(fr,br),createBlockFilter:()=>createBlockFilter$1(fr),createContractEventFilter:br=>createContractEventFilter$1(fr,br),createEventFilter:br=>createEventFilter$1(fr,br),createPendingTransactionFilter:()=>createPendingTransactionFilter$1(fr),estimateContractGas:br=>estimateContractGas$1(fr,br),estimateGas:br=>estimateGas$4(fr,br),getBalance:br=>getBalance$1(fr,br),getBlobBaseFee:()=>getBlobBaseFee$1(fr),getBlock:br=>getBlock$1(fr,br),getBlockNumber:br=>getBlockNumber$1(fr,br),getBlockTransactionCount:br=>getBlockTransactionCount$1(fr,br),getBytecode:br=>getCode$1(fr,br),getChainId:()=>getChainId$1(fr),getCode:br=>getCode$1(fr,br),getContractEvents:br=>getContractEvents$1(fr,br),getEip712Domain:br=>getEip712Domain$3(fr,br),getEnsAddress:br=>getEnsAddress$1(fr,br),getEnsAvatar:br=>getEnsAvatar$1(fr,br),getEnsName:br=>getEnsName$1(fr,br),getEnsResolver:br=>getEnsResolver$1(fr,br),getEnsText:br=>getEnsText$1(fr,br),getFeeHistory:br=>getFeeHistory$1(fr,br),estimateFeesPerGas:br=>estimateFeesPerGas$2(fr,br),getFilterChanges:br=>getFilterChanges$1(fr,br),getFilterLogs:br=>getFilterLogs$1(fr,br),getGasPrice:()=>getGasPrice$1(fr),getLogs:br=>getLogs$1(fr,br),getProof:br=>getProof$1(fr,br),estimateMaxPriorityFeePerGas:br=>estimateMaxPriorityFeePerGas$1(fr,br),getStorageAt:br=>getStorageAt$1(fr,br),getTransaction:br=>getTransaction$1(fr,br),getTransactionConfirmations:br=>getTransactionConfirmations$1(fr,br),getTransactionCount:br=>getTransactionCount$1(fr,br),getTransactionReceipt:br=>getTransactionReceipt$1(fr,br),multicall:br=>multicall$1(fr,br),prepareTransactionRequest:br=>prepareTransactionRequest$1(fr,br),readContract:br=>readContract$1(fr,br),sendRawTransaction:br=>sendRawTransaction$1(fr,br),simulateContract:br=>simulateContract$1(fr,br),verifyMessage:br=>verifyMessage$2(fr,br),verifySiweMessage:br=>verifySiweMessage$1(fr,br),verifyTypedData:br=>verifyTypedData$2(fr,br),uninstallFilter:br=>uninstallFilter$1(fr,br),waitForTransactionReceipt:br=>waitForTransactionReceipt$1(fr,br),watchBlocks:br=>watchBlocks$1(fr,br),watchBlockNumber:br=>watchBlockNumber$1(fr,br),watchContractEvent:br=>watchContractEvent$1(fr,br),watchEvent:br=>watchEvent$1(fr,br),watchPendingTransactions:br=>watchPendingTransactions$1(fr,br)}}function createPublicClient$1(fr){const{key:br="public",name:wr="Public Client"}=fr;return createClient$1({...fr,key:br,name:wr,type:"publicClient"}).extend(publicActions)}function deployContract$1(fr,br){const{abi:wr,args:Er,bytecode:kr,...jr}=br,Br=encodeDeployData$1({abi:wr,args:Er,bytecode:kr});return sendTransaction$1(fr,{...jr,data:Br})}async function getAddresses$1(fr){var wr;return((wr=fr.account)==null?void 0:wr.type)==="local"?[fr.account.address]:(await fr.request({method:"eth_accounts"},{dedupe:!0})).map(Er=>checksumAddress(Er))}async function getPermissions$1(fr){return await fr.request({method:"wallet_getPermissions"},{dedupe:!0})}async function requestAddresses$1(fr){return(await fr.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(wr=>getAddress$1(wr))}async function requestPermissions$1(fr,br){return fr.request({method:"wallet_requestPermissions",params:[br]},{retryCount:0})}async function signMessage$3(fr,{account:br=fr.account,message:wr}){if(!br)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signMessage"});const Er=parseAccount$1(br);if(Er.signMessage)return Er.signMessage({message:wr});const kr=typeof wr=="string"?stringToHex(wr):wr.raw instanceof Uint8Array?toHex$1(wr.raw):wr.raw;return fr.request({method:"personal_sign",params:[kr,Er.address]},{retryCount:0})}async function signTransaction$3(fr,br){var Vr,Hr,Zr,Jr;const{account:wr=fr.account,chain:Er=fr.chain,...kr}=br;if(!wr)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTransaction"});const jr=parseAccount$1(wr);assertRequest$1({account:jr,...br});const Br=await getAction$1(fr,getChainId$1,"getChainId")({});Er!==null&&assertCurrentChain$1({currentChainId:Br,chain:Er});const qr=(Er==null?void 0:Er.formatters)||((Vr=fr.chain)==null?void 0:Vr.formatters),Wr=((Hr=qr==null?void 0:qr.transactionRequest)==null?void 0:Hr.format)||formatTransactionRequest;return jr.signTransaction?jr.signTransaction({...kr,chainId:Br},{serializer:(Jr=(Zr=fr.chain)==null?void 0:Zr.serializers)==null?void 0:Jr.transaction}):await fr.request({method:"eth_signTransaction",params:[{...Wr(kr),chainId:numberToHex(Br),from:jr.address}]},{retryCount:0})}async function signTypedData$3(fr,br){const{account:wr=fr.account,domain:Er,message:kr,primaryType:jr}=br;if(!wr)throw new AccountNotFoundError({docsPath:"/docs/actions/wallet/signTypedData"});const Br=parseAccount$1(wr),qr={EIP712Domain:getTypesForEIP712Domain({domain:Er}),...br.types};if(validateTypedData({domain:Er,message:kr,primaryType:jr,types:qr}),Br.signTypedData)return Br.signTypedData({domain:Er,message:kr,primaryType:jr,types:qr});const Wr=serializeTypedData({domain:Er,message:kr,primaryType:jr,types:qr});return fr.request({method:"eth_signTypedData_v4",params:[Br.address,Wr]},{retryCount:0})}async function switchChain$1(fr,{id:br}){await fr.request({method:"wallet_switchEthereumChain",params:[{chainId:numberToHex(br)}]},{retryCount:0})}async function watchAsset$1(fr,br){return await fr.request({method:"wallet_watchAsset",params:br},{retryCount:0})}function walletActions(fr){return{addChain:br=>addChain$1(fr,br),deployContract:br=>deployContract$1(fr,br),getAddresses:()=>getAddresses$1(fr),getChainId:()=>getChainId$1(fr),getPermissions:()=>getPermissions$1(fr),prepareTransactionRequest:br=>prepareTransactionRequest$1(fr,br),requestAddresses:()=>requestAddresses$1(fr),requestPermissions:br=>requestPermissions$1(fr,br),sendRawTransaction:br=>sendRawTransaction$1(fr,br),sendTransaction:br=>sendTransaction$1(fr,br),signMessage:br=>signMessage$3(fr,br),signTransaction:br=>signTransaction$3(fr,br),signTypedData:br=>signTypedData$3(fr,br),switchChain:br=>switchChain$1(fr,br),watchAsset:br=>watchAsset$1(fr,br),writeContract:br=>writeContract$1(fr,br)}}function createWalletClient$1(fr){const{key:br="wallet",name:wr="Wallet Client",transport:Er}=fr;return createClient$1({...fr,key:br,name:wr,transport:Er,type:"walletClient"}).extend(walletActions)}const crypto$5=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function anumber$3(fr){if(!Number.isSafeInteger(fr)||fr<0)throw new Error("positive integer expected, got "+fr)}function isBytes$7(fr){return fr instanceof Uint8Array||ArrayBuffer.isView(fr)&&fr.constructor.name==="Uint8Array"}function abytes$2(fr,...br){if(!isBytes$7(fr))throw new Error("Uint8Array expected");if(br.length>0&&!br.includes(fr.length))throw new Error("Uint8Array expected of length "+br+", got length="+fr.length)}function ahash$1(fr){if(typeof fr!="function"||typeof fr.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");anumber$3(fr.outputLen),anumber$3(fr.blockLen)}function aexists$1(fr,br=!0){if(fr.destroyed)throw new Error("Hash instance has been destroyed");if(br&&fr.finished)throw new Error("Hash#digest() has already been called")}function aoutput$1(fr,br){abytes$2(fr);const wr=br.outputLen;if(fr.lengthnew Uint8Array(fr.buffer,fr.byteOffset,fr.byteLength),u32$1=fr=>new Uint32Array(fr.buffer,fr.byteOffset,Math.floor(fr.byteLength/4)),createView$1=fr=>new DataView(fr.buffer,fr.byteOffset,fr.byteLength),rotr$1=(fr,br)=>fr<<32-br|fr>>>br,rotl=(fr,br)=>fr<>>32-br>>>0,isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,byteSwap=fr=>fr<<24&4278190080|fr<<8&16711680|fr>>>8&65280|fr>>>24&255,byteSwapIfBE=isLE?fr=>fr:fr=>byteSwap(fr);function byteSwap32(fr){for(let br=0;brbr.toString(16).padStart(2,"0"));function bytesToHex$1(fr){abytes$2(fr);let br="";for(let wr=0;wr=asciis$1._0&&fr<=asciis$1._9)return fr-asciis$1._0;if(fr>=asciis$1.A&&fr<=asciis$1.F)return fr-(asciis$1.A-10);if(fr>=asciis$1.a&&fr<=asciis$1.f)return fr-(asciis$1.a-10)}function hexToBytes$1(fr){if(typeof fr!="string")throw new Error("hex string expected, got "+typeof fr);const br=fr.length,wr=br/2;if(br%2)throw new Error("hex string expected, got unpadded hex of length "+br);const Er=new Uint8Array(wr);for(let kr=0,jr=0;kr{};async function asyncLoop(fr,br,wr){let Er=Date.now();for(let kr=0;kr=0&&jrfr().update(toBytes$2(Er)).digest(),wr=fr();return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=()=>fr(),br}function wrapConstructorWithOpts(fr){const br=(Er,kr)=>fr(kr).update(toBytes$2(Er)).digest(),wr=fr({});return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=Er=>fr(Er),br}function wrapXOFConstructorWithOpts(fr){const br=(Er,kr)=>fr(kr).update(toBytes$2(Er)).digest(),wr=fr({});return br.outputLen=wr.outputLen,br.blockLen=wr.blockLen,br.create=Er=>fr(Er),br}function randomBytes$1(fr=32){if(crypto$5&&typeof crypto$5.getRandomValues=="function")return crypto$5.getRandomValues(new Uint8Array(fr));if(crypto$5&&typeof crypto$5.randomBytes=="function")return crypto$5.randomBytes(fr);throw new Error("crypto.getRandomValues must be defined")}const utils$h=Object.freeze(Object.defineProperty({__proto__:null,Hash:Hash$2,asyncLoop,byteSwap,byteSwap32,byteSwapIfBE,bytesToHex:bytesToHex$1,checkOpts,concatBytes:concatBytes$2,createView:createView$1,hexToBytes:hexToBytes$1,isBytes:isBytes$6,isLE,nextTick,randomBytes:randomBytes$1,rotl,rotr:rotr$1,toBytes:toBytes$2,u32:u32$1,u8:u8$1,utf8ToBytes:utf8ToBytes$2,wrapConstructor:wrapConstructor$1,wrapConstructorWithOpts,wrapXOFConstructorWithOpts},Symbol.toStringTag,{value:"Module"})),xv=class xv{};_f(xv,"initialize",async(br,wr="WALLETCLIENT")=>wr==="DYNAMIC"?xv.convertDynamicProvider(br):xv.convertViemWalletClient(br)),_f(xv,"convertViemWalletClient",async br=>{try{const wr=br.account;if(!wr)throw new Error("WalletClient Account Undefined");const Er=await br.getChainId(),kr=async jr=>{const Br=await br.signMessage({message:jr,account:wr});return hexToBytes$1(Br.replace("0x",""))};return{account:`eip155:${Er}:${getAddress$1(wr.address)}`,signMessage:kr}}catch{throw new Error("Invalid WalletClient")}}),_f(xv,"convertDynamicProvider",async br=>{try{let wr=br.address;isAddress$1(wr,{strict:!1})&&(wr=getAddress$1(wr));const Er=chainToNamespace[br.chain];if(Er===void 0)throw new Error("Unsupported Namespace");let kr=await br.getNetwork();Er==="solana"&&(kr=networkToSolChainId[kr]);const jr=async Br=>{let qr=typeof Br=="string"?Br:bytesToString(Br);br.key==="coinbase"&&br.chain==="EVM"&&qr.startsWith("0x")&&(qr=stringToHex(qr));const Wr=await br.signMessage(qr);return isHex$1(Wr)?hexToBytes$1(Wr.replace("0x","")):Buffer$2.from(Wr,"base64")};return{account:`${Er}:${kr}:${wr}`,signMessage:jr}}catch{throw new Error("Invalid Dynamic Provider")}});let PushSigner=xv;const WalletContext=reactExports.createContext({handleUserLoggedIn:()=>{},handleLogOutEvent:()=>{},handleAppConnectionSuccess:()=>{},handleAppConnectionRejected:()=>{},handleRejectAllAppConnections:()=>{}});function useEventEmitterContext(){const fr=reactExports.useContext(WalletContext);if(!fr)throw new Error("useWalletState must be used within a WalletProvider");return fr}const EventEmitterProvider=({children:fr})=>{const{dispatch:br,state:wr}=useGlobalState(),[Er,kr]=reactExports.useState(!1),jr=reactExports.useRef(wr.wallet);jr.current=wr.wallet,reactExports.useEffect(()=>{jr.current&&!Er&&(kr(!0),Xr())},[jr.current]);const Br=reactExports.useRef(null);reactExports.useEffect(()=>{wr.dynamicWallet&&!Er&&(async()=>(Br.current=await PushSigner.initialize(wr.dynamicWallet,"DYNAMIC"),kr(!0),Xr()))()},[wr.dynamicWallet]),reactExports.useEffect(()=>{getAppParamValue()&&(window.onbeforeunload=()=>{window.opener&&wn()});const $n=Tn=>{if(Tn.origin===getAppParamValue())switch(Tn.data.type){case APP_TO_WALLET_ACTION.NEW_CONNECTION_REQUEST:Wr(Tn.origin);break;case APP_TO_WALLET_ACTION.SIGN_MESSAGE:console.log("Signing Message on wallet tab"),Jr(Tn.data.data,Tn.origin);break;default:console.warn("Unknown message type:",Tn.data.type)}};return window.addEventListener("message",$n),()=>{window.removeEventListener("message",$n)}},[]);const qr=$n=>{if(window.opener)try{window.opener.postMessage($n,getAppParamValue())}catch(Tn){console.error("Error sending message to main tab:",Tn)}},Wr=$n=>{const Tn=requestToConnectPushWallet($n);if(Tn.find(jn=>jn.origin===$n).appConnectionStatus==="connected"){Vr($n);return}br({type:"SET_APP_CONNECTIONS",payload:Tn})},Vr=$n=>{const Tn=acceptPushWalletConnectionRequest($n);br({type:"SET_APP_CONNECTIONS",payload:Tn}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_SUCCESS,data:{account:jr.current.signerAccount}})},Hr=$n=>{const Tn=rejectPushWalletConnectionRequest($n);br({type:"SET_APP_CONNECTIONS",payload:Tn}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_REJECTED,data:{account:null}})},Zr=()=>{const $n=rejectAllPushWalletConnectionRequests();br({type:"SET_APP_CONNECTIONS",payload:$n}),qr({type:WALLET_TO_APP_ACTION.APP_CONNECTION_REJECTED,data:{account:null}})},Jr=async($n,Tn)=>{var In,jn;console.log("Signing message",$n,Tn);try{br({type:"SET_MESSAGE_SIGN_STATE",payload:"loading"});const Yn=Br!=null&&Br.current?await((In=Br==null?void 0:Br.current)==null?void 0:In.signMessage($n)):await jr.current.sign($n,Tn,getAllAppConnections());console.log("Signature signed",Yn),qr({type:WALLET_TO_APP_ACTION.SIGNATURE,data:{signature:Yn}}),(jn=Br==null?void 0:Br.current)!=null&&jn.account?br({type:"SET_MESSAGE_SIGN_STATE",payload:"idle"}):setTimeout(()=>br({type:"SET_MESSAGE_SIGN_STATE",payload:"idle"}),2e3)}catch(Yn){console.log(Yn),br({type:"SET_MESSAGE_SIGN_STATE",payload:"rejected"})}},Xr=()=>{var $n,Tn;qr({type:WALLET_TO_APP_ACTION.IS_LOGGED_IN,data:{account:(($n=Br==null?void 0:Br.current)==null?void 0:$n.account)??null}}),(Tn=Br==null?void 0:Br.current)!=null&&Tn.account&&br({type:"SET_EXTERNAL_WALLET_APP_CONNECTION_STATUS",payload:"connected"})},En=()=>{qr({type:WALLET_TO_APP_ACTION.IS_LOGGED_OUT,data:{account:null}}),kr(!1),jr.current=null,Br.current=null,setTimeout(()=>{getAppParamValue()&&window.close()},1e3)},wn=()=>{};return jsxRuntimeExports.jsx(WalletContext.Provider,{value:{handleUserLoggedIn:Xr,handleLogOutEvent:En,handleAppConnectionSuccess:Vr,handleAppConnectionRejected:Hr,handleRejectAllAppConnections:Zr},children:fr})},WalletProfile=({selectedWallet:fr})=>{const{primaryWallet:br,handleLogOut:wr}=useDynamicContext(),Er=(fr==null?void 0:fr.address)||(br==null?void 0:br.address),kr=(fr==null?void 0:fr.name)??"External Wallet",[jr,Br]=reactExports.useState(!1),{dispatch:qr}=useGlobalState(),{handleLogOutEvent:Wr}=useEventEmitterContext(),Vr=useNavigate(),Hr=()=>{var Zr;qr({type:"RESET_WALLET"}),(Zr=br==null?void 0:br.connector)==null||Zr.endSession(),wr(),sessionStorage.removeItem("jwt"),localStorage.clear(),Vr(APP_ROUTES.AUTH),Wr()};return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:"spacing-sm",width:"-webkit-fill-available",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"space-between",width:"-webkit-fill-available",children:[jsxRuntimeExports.jsx(PushLogo,{height:48,width:48}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:"spacing-xxs",children:jsxRuntimeExports.jsx(Dropdown,{overlay:jsxRuntimeExports.jsx(Menu,{children:jsxRuntimeExports.jsx(MenuItem,{label:"Log Out",icon:jsxRuntimeExports.jsx(Logout,{}),onClick:()=>{Hr()}})}),children:jsxRuntimeExports.jsx(Box,{cursor:"pointer",children:jsxRuntimeExports.jsx(Settings,{size:24,color:"icon-primary"})})})})]}),jsxRuntimeExports.jsx(Box,{width:"56px",height:"56px",borderRadius:"radius-xl",overflow:"hidden",alignSelf:"center",children:jsxRuntimeExports.jsx(BlockiesSvg,{address:Er})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",alignItems:"center",gap:"spacing-xxxs",children:[jsxRuntimeExports.jsx(Text,{variant:"bl-semibold",children:kr}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:"spacing-xxxs",children:[jsxRuntimeExports.jsx(Text,{variant:"bes-semibold",color:"text-tertiary",children:centerMaskWalletAddress(Er)}),jsxRuntimeExports.jsx(Box,{cursor:"pointer",children:jsxRuntimeExports.jsx(Tooltip,{title:jr?"Copy":"Copied",children:jr?jsxRuntimeExports.jsx(TickCircleFilled,{autoSize:!0,size:16,color:"icon-state-success-bold"}):jsxRuntimeExports.jsx(Copy,{color:"icon-tertiary",onClick:()=>handleCopy(Er,Br)})})})]})]})]})};var src$5={};const require$$0$c=getAugmentedNamespace(tslib_es6$4);var lib$1={},pushNetwork={},block$3={},validator$1={},utils$g={},hasRequiredUtils$d;function requireUtils$d(){if(hasRequiredUtils$d)return utils$g;hasRequiredUtils$d=1,Object.defineProperty(utils$g,"__esModule",{value:!0}),utils$g.getRandomElement=void 0;const fr=br=>{if(br.length===0)throw new Error("Array cannot be empty");const wr=Math.floor(Math.random()*br.length);return br[wr]};return utils$g.getRandomElement=fr,utils$g}const require$$2$4=getAugmentedNamespace(axios);var _cjs={};const require$$0$b=getAugmentedNamespace(exports$1);var getContract={},getAction={},hasRequiredGetAction;function requireGetAction(){if(hasRequiredGetAction)return getAction;hasRequiredGetAction=1,Object.defineProperty(getAction,"__esModule",{value:!0}),getAction.getAction=fr;function fr(br,wr,Er){const kr=br[wr.name];if(typeof kr=="function")return kr;const jr=br[Er];return typeof jr=="function"?jr:Br=>wr(br,Br)}return getAction}var createContractEventFilter={},encodeEventTopics={},abi$2={},formatAbiItem={},hasRequiredFormatAbiItem;function requireFormatAbiItem(){if(hasRequiredFormatAbiItem)return formatAbiItem;hasRequiredFormatAbiItem=1,Object.defineProperty(formatAbiItem,"__esModule",{value:!0}),formatAbiItem.formatAbiItem=br,formatAbiItem.formatAbiParams=wr;const fr=requireAbi();function br(kr,{includeName:jr=!1}={}){if(kr.type!=="function"&&kr.type!=="event"&&kr.type!=="error")throw new fr.InvalidDefinitionTypeError(kr.type);return`${kr.name}(${wr(kr.inputs,{includeName:jr})})`}function wr(kr,{includeName:jr=!1}={}){return kr?kr.map(Br=>Er(Br,{includeName:jr})).join(jr?", ":","):""}function Er(kr,{includeName:jr}){return kr.type.startsWith("tuple")?`(${wr(kr.components,{includeName:jr})})${kr.type.slice(5)}`:kr.type+(jr&&kr.name?` ${kr.name}`:"")}return formatAbiItem}var size={},isHex={},hasRequiredIsHex;function requireIsHex(){if(hasRequiredIsHex)return isHex;hasRequiredIsHex=1,Object.defineProperty(isHex,"__esModule",{value:!0}),isHex.isHex=fr;function fr(br,{strict:wr=!0}={}){return!br||typeof br!="string"?!1:wr?/^0x[0-9a-fA-F]*$/.test(br):br.startsWith("0x")}return isHex}var hasRequiredSize;function requireSize(){if(hasRequiredSize)return size;hasRequiredSize=1,Object.defineProperty(size,"__esModule",{value:!0}),size.size=br;const fr=requireIsHex();function br(wr){return(0,fr.isHex)(wr,{strict:!1})?Math.ceil((wr.length-2)/2):wr.length}return size}var base$9={},version$g={},hasRequiredVersion$1;function requireVersion$1(){return hasRequiredVersion$1||(hasRequiredVersion$1=1,Object.defineProperty(version$g,"__esModule",{value:!0}),version$g.version=void 0,version$g.version="2.21.53"),version$g}var hasRequiredBase$3;function requireBase$3(){if(hasRequiredBase$3)return base$9;hasRequiredBase$3=1,Object.defineProperty(base$9,"__esModule",{value:!0}),base$9.BaseError=void 0,base$9.setErrorConfig=wr;const fr=requireVersion$1();let br={getDocsUrl:({docsBaseUrl:jr,docsPath:Br="",docsSlug:qr})=>Br?`${jr??"https://viem.sh"}${Br}${qr?`#${qr}`:""}`:void 0,version:`viem@${fr.version}`};function wr(jr){br=jr}class Er extends Error{constructor(Br,qr={}){var Jr;const Wr=(()=>{var Xr;return qr.cause instanceof Er?qr.cause.details:(Xr=qr.cause)!=null&&Xr.message?qr.cause.message:qr.details})(),Vr=qr.cause instanceof Er&&qr.cause.docsPath||qr.docsPath,Hr=(Jr=br.getDocsUrl)==null?void 0:Jr.call(br,{...qr,docsPath:Vr}),Zr=[Br||"An error occurred.","",...qr.metaMessages?[...qr.metaMessages,""]:[],...Hr?[`Docs: ${Hr}`]:[],...Wr?[`Details: ${Wr}`]:[],...br.version?[`Version: ${br.version}`]:[]].join(` `);super(Zr,qr.cause?{cause:qr.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=Wr,this.docsPath=Vr,this.metaMessages=qr.metaMessages,this.name=qr.name??this.name,this.shortMessage=Br,this.version=fr.version}walk(Br){return kr(this,Br)}}base$9.BaseError=Er;function kr(jr,Br){return Br!=null&&Br(jr)?jr:jr&&typeof jr=="object"&&"cause"in jr&&jr.cause!==void 0?kr(jr.cause,Br):Br?null:jr}return base$9}var hasRequiredAbi;function requireAbi(){if(hasRequiredAbi)return abi$2;hasRequiredAbi=1,Object.defineProperty(abi$2,"__esModule",{value:!0}),abi$2.UnsupportedPackedAbiType=abi$2.InvalidDefinitionTypeError=abi$2.InvalidArrayError=abi$2.InvalidAbiDecodingTypeError=abi$2.InvalidAbiEncodingTypeError=abi$2.DecodeLogTopicsMismatch=abi$2.DecodeLogDataMismatch=abi$2.BytesSizeMismatchError=abi$2.AbiItemAmbiguityError=abi$2.AbiFunctionSignatureNotFoundError=abi$2.AbiFunctionOutputsNotFoundError=abi$2.AbiFunctionNotFoundError=abi$2.AbiEventNotFoundError=abi$2.AbiEventSignatureNotFoundError=abi$2.AbiEventSignatureEmptyTopicsError=abi$2.AbiErrorSignatureNotFoundError=abi$2.AbiErrorNotFoundError=abi$2.AbiErrorInputsNotFoundError=abi$2.AbiEncodingLengthMismatchError=abi$2.AbiEncodingBytesSizeMismatchError=abi$2.AbiEncodingArrayLengthMismatchError=abi$2.AbiDecodingZeroDataError=abi$2.AbiDecodingDataSizeTooSmallError=abi$2.AbiDecodingDataSizeInvalidError=abi$2.AbiConstructorParamsNotFoundError=abi$2.AbiConstructorNotFoundError=void 0;const fr=requireFormatAbiItem(),br=requireSize(),wr=requireBase$3();class Er extends wr.BaseError{constructor({docsPath:Gr}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` `),{docsPath:Gr,name:"AbiConstructorNotFoundError"})}}abi$2.AbiConstructorNotFoundError=Er;class kr extends wr.BaseError{constructor({docsPath:Gr}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(` `),{docsPath:Gr,name:"AbiConstructorParamsNotFoundError"})}}abi$2.AbiConstructorParamsNotFoundError=kr;class jr extends wr.BaseError{constructor({data:Gr,size:Yr}){super([`Data size of ${Yr} bytes is invalid.`,"Size must be in increments of 32 bytes (size % 32 === 0)."].join(` @@ -4153,7 +4153,7 @@ https://github.com/browserify/crypto-browserify`)},cryptoBrowserify.constants={D background: #fff; `,height:"52px",width:"52px",justifyContent:"center",alignItems:"center",borderRadius:"radius-xl",children:jsxRuntimeExports.jsx(PushLogo,{height:32,width:32})}),jsxRuntimeExports.jsx(Text,{variant:"h6-regular",textAlign:"center",children:br==null?void 0:br.origin})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:"spacing-xxxs",children:[jsxRuntimeExports.jsx(Text,{variant:"h4-semibold",textAlign:"center",children:"Connect to this site"}),jsxRuntimeExports.jsxs(Text,{variant:"bs-regular",textAlign:"center",color:"text-tertiary",children:["Allow the site to see account balance,",jsxRuntimeExports.jsx("br",{})," activity and suggest transactions to approve"]})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",padding:"spacing-xs",gap:"spacing-sm",borderRadius:"radius-sm",backgroundColor:"surface-secondary",flexDirection:"column",width:"100%",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",gap:"spacing-xs",children:[jsxRuntimeExports.jsx(Box,{width:"40px",height:"40px",borderRadius:"radius-xl",overflow:"hidden",alignSelf:"center",children:jsxRuntimeExports.jsx(BlockiesSvg,{address:"321ed12e"})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",children:[jsxRuntimeExports.jsx(Text,{variant:"bm-semibold",children:"Push Wallet"}),jsxRuntimeExports.jsx(Text,{variant:"bes-semibold",color:"text-tertiary",children:centerMaskWalletAddress(jr)})]})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:"spacing-xs",children:[jsxRuntimeExports.jsx(Button,{size:"small",variant:"outline",onClick:()=>Er(br==null?void 0:br.origin),children:"Reject"}),jsxRuntimeExports.jsx(Button,{size:"small",variant:"primary",css:Ae$2` width: 66%; - `,onClick:()=>wr(br==null?void 0:br.origin),children:"Connect"})]})]})]})},PushWalletAppConnection=({selectedWallet:fr})=>{const{state:br}=useGlobalState(),{handleAppConnectionRejected:wr,handleAppConnectionSuccess:Er,handleRejectAllAppConnections:kr}=useEventEmitterContext(),[jr,Br]=reactExports.useState(null),qr=wn=>{Er(wn),Br("connected")},Wr=wn=>{wr(wn),Br("rejected")},Vr=async()=>{kr(),Br("notVisible")},Hr=()=>Br("notVisible"),Zr=()=>Br("notVisible"),Jr=()=>{window.close()},Xr=br==null?void 0:br.appConnections.some(wn=>wn.appConnectionStatus==="pending"),En=br==null?void 0:br.appConnections[(br==null?void 0:br.appConnections.length)-1];return Xr&&(En==null?void 0:En.appConnectionStatus)==="pending"?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(AppConnectionStatus,{selectedWallet:fr,appConnection:En,onSuccess:qr,onReject:Wr,onRejectAll:Vr})}):jr==="connected"&&(En==null?void 0:En.appConnectionStatus)==="connected"&&getAppParamValue()?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(ConnectionSuccess,{onClose:Hr})}):jr==="rejected"?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(ErrorContent,{icon:jsxRuntimeExports.jsx(Info,{size:32,color:"icon-state-danger-subtle"}),title:"Could not verify",subTitle:"Please go back to the app and retry",retryText:"Close",onClose:Zr,onRetry:Jr,note:"Closing this window will log you out."})}):null};var WALLET_TO_APP_ACTION=(fr=>(fr.IS_LOGGED_IN="isLoggedIn",fr.APP_CONNECTION_REJECTED="appConnectionRejected",fr.APP_CONNECTION_SUCCESS="appConnectionSuccess",fr.SIGNATURE="signature",fr.IS_LOGGED_OUT="loggedOut",fr.TAB_CLOSED="tabClosed",fr))(WALLET_TO_APP_ACTION||{}),APP_TO_WALLET_ACTION=(fr=>(fr.NEW_CONNECTION_REQUEST="newConnectionRequest",fr.SIGN_MESSAGE="signMessage",fr))(APP_TO_WALLET_ACTION||{});const initialState={wallet:null,appConnections:getAllAppConnections(),dynamicWallet:null,theme:"light",user:null,isAuthenticated:!1,jwt:null,walletLoadState:"idle",messageSignState:"idle",externalWalletAppConnectionStatus:"pending"};function globalReducer(fr,br){switch(br.type){case"INITIALIZE_WALLET":return{...fr,wallet:br.payload};case"SET_APP_CONNECTIONS":return{...fr,appConnections:br.payload};case"SET_DYNAMIC_WALLET":return{...fr,dynamicWallet:br.payload};case"RESET_WALLET":return{...fr,...initialState};case"SET_THEME":return{...fr,theme:br.payload};case"SET_USER":return{...fr,user:br.payload};case"SET_AUTHENTICATED":return{...fr,isAuthenticated:br.payload};case"SET_JWT":return{...fr,jwt:br.payload};case"SET_WALLET_LOAD_STATE":return{...fr,walletLoadState:br.payload};case"SET_MESSAGE_SIGN_STATE":return{...fr,messageSignState:br.payload};case"SET_EXTERNAL_WALLET_APP_CONNECTION_STATUS":return{...fr,externalWalletAppConnectionStatus:br.payload};default:return fr}}const GlobalContext=reactExports.createContext({state:initialState,dispatch:()=>null});function useGlobalState(){const fr=reactExports.useContext(GlobalContext);if(!fr)throw new Error("useGlobalState must be used within a GlobalProvider");return fr}const GlobalProvider=({children:fr})=>{const[br,wr]=reactExports.useReducer(globalReducer,initialState),{primaryWallet:Er,sdkHasLoaded:kr}=useDynamicContext(),jr=extractStateFromUrl(),Br=sessionStorage.getItem("jwt");return reactExports.useEffect(()=>{(async()=>{try{if(wr({type:"SET_WALLET_LOAD_STATE",payload:"loading"}),console.log("State Param",jr),jr){const Wr=await fetchJwtUsingState({stateParam:jr});sessionStorage.setItem("jwt",Wr),wr({type:"SET_JWT",payload:Wr});const Vr=new URL(window.location.href);Vr.searchParams.delete("state"),window.history.replaceState({},document.title,Vr.toString()),wr({type:"SET_WALLET_LOAD_STATE",payload:"success"})}Br&&(wr({type:"SET_JWT",payload:Br}),wr({type:"SET_WALLET_LOAD_STATE",payload:"success"})),Er&&(wr({type:"SET_WALLET_LOAD_STATE",payload:"success"}),wr({type:"SET_DYNAMIC_WALLET",payload:Er})),!jr&&!Br&&!Er&&kr&&wr({type:"SET_WALLET_LOAD_STATE",payload:"rejected"})}catch(Wr){throw wr({type:"SET_WALLET_LOAD_STATE",payload:"rejected"}),console.error("Error creating wallet:",Wr),Wr}})()},[jr,Br,Er,kr]),jsxRuntimeExports.jsx(GlobalContext.Provider,{value:{state:br,dispatch:wr},children:fr})},__vite_import_meta_env__={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_BACKEND_URL:"https://push-auth.push.org",VITE_APP_DYNAMIC_ENV_ID:"82e8732d-11b8-428d-a553-7087d0c44171",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"};var define_process_env_default$3={};function getAppBasePath(){if(typeof import.meta<"u"&&__vite_import_meta_env__)return"/push-wallet/";if(typeof process$1$1<"u"&&define_process_env_default$3){if(define_process_env_default$3.VITE_DEV_MODE==="preview")return"/push-wallet/pr-preview/";if(define_process_env_default$3.VITE_DEV_MODE==="testing")return"/push-wallet/"}return"/"}typeof window<"u"&&(window.global=globalThis,Object.assign(window,{Buffer:Buffer$1$1}));var version$d="3.8.2",version$c="3.8.2";function __awaiter$c(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,br||[])).next())})}function __classPrivateFieldGet$4(fr,br,wr,Er){if(wr==="a"&&!Er)throw new TypeError("Private accessor was defined without a getter");if(typeof br=="function"?fr!==br||!Er:!br.has(fr))throw new TypeError("Cannot read private member from an object whose class did not declare it");return wr==="m"?Er:wr==="a"?Er.call(fr):Er?Er.value:br.get(fr)}function __classPrivateFieldSet$4(fr,br,wr,Er,kr){if(typeof br=="function"?fr!==br||!kr:!br.has(fr))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kr?kr.value=wr:br.set(fr,wr),wr}typeof SuppressedError=="function"&&SuppressedError;const DEFAULT_JWK_MEMBER_BYTE_LENGTH=32;function stringToBase64urlString(fr){const br=btoa$1(fr);return base64StringToBase64UrlEncodedString(br)}function hexStringToBase64url(fr,br){const wr=fr.padStart(Math.ceil(fr.length/2)*2,"0"),Er=uint8ArrayFromHexString(wr,br);return stringToBase64urlString(Er.reduce((kr,jr)=>kr+String.fromCharCode(jr),""))}function base64StringToBase64UrlEncodedString(fr){return fr.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uint8ArrayToHexString(fr){return fr.reduce((br,wr)=>br+wr.toString(16).padStart(2,"0"),"")}const uint8ArrayFromHexString=(fr,br)=>{const wr=/^[0-9A-Fa-f]+$/;if(!fr||fr.length%2!=0||!wr.test(fr))throw new Error(`cannot create uint8array from invalid hex string: "${fr}"`);const Er=new Uint8Array(fr.match(/../g).map(jr=>parseInt(jr,16)));if(!br)return Er;if(fr.length/2>br)throw new Error("hex value cannot fit in a buffer of "+br+" byte(s)");let kr=new Uint8Array(br);return kr.set(Er,br-Er.length),kr};function btoa$1(fr){if(arguments.length===0)throw new TypeError("1 argument required, but only 0 present.");let br;for(fr=`${fr}`,br=0;br255)throw new Error(`InvalidCharacterError: found code point greater than 255:${fr.charCodeAt(br)} at position ${br}`);let wr="";for(br=0;br>2,Er[1]=(fr.charCodeAt(br)&3)<<4,fr.length>br+1&&(Er[1]|=fr.charCodeAt(br+1)>>4,Er[2]=(fr.charCodeAt(br+1)&15)<<2),fr.length>br+2&&(Er[2]|=fr.charCodeAt(br+2)>>6,Er[3]=fr.charCodeAt(br+2)&63);for(let kr=0;kr"u"?wr+="=":wr+=btoaLookup(Er[kr])}return wr}function btoaLookup(fr){const br="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";if(fr>=0&&fr<64)return br[fr]}const stampHeaderName$2="X-Stamp",isCryptoEnabledBrowser=typeof window<"u"&&typeof window.document<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u",isNode=typeof process$1$1<"u"&&process$1$1.versions!=null&&process$1$1.versions.node!=null,signWithApiKey=async fr=>isCryptoEnabledBrowser?(await __vitePreload(()=>import("./webcrypto-DQKOHd8b.js"),__vite__mapDeps([0,1])).then(wr=>wr.signWithApiKey))(fr):isNode?(await __vitePreload(()=>import("./nodecrypto-B3VJzu49.js"),__vite__mapDeps([2,1])).then(wr=>wr.signWithApiKey))(fr):(await __vitePreload(()=>import("./purejs-CR9yUBx8.js"),[]).then(wr=>wr.signWithApiKey))(fr);class ApiKeyStamper{constructor(br){this.apiPublicKey=br.apiPublicKey,this.apiPrivateKey=br.apiPrivateKey}async stamp(br){const wr=await signWithApiKey({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:br}),Er={publicKey:this.apiPublicKey,scheme:"SIGNATURE_SCHEME_TK_API_P256",signature:wr};return{stampHeaderName:stampHeaderName$2,stampHeaderValue:stringToBase64urlString(JSON.stringify(Er))}}}const base64UrlEncode=fr=>Buffer$2.from(fr).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),generateRandomBuffer=()=>{const fr=new Uint8Array(32);return crypto.getRandomValues(fr),fr.buffer},transportMap={AUTHENTICATOR_TRANSPORT_BLE:AuthenticatorTransportProtocol.Ble,AUTHENTICATOR_TRANSPORT_HYBRID:AuthenticatorTransportProtocol.Hybrid,AUTHENTICATOR_TRANSPORT_INTERNAL:AuthenticatorTransportProtocol.Internal,AUTHENTICATOR_TRANSPORT_NFC:AuthenticatorTransportProtocol.Nfc,AUTHENTICATOR_TRANSPORT_USB:AuthenticatorTransportProtocol.Usb},convertAttestationTransports=fr=>fr.map(br=>transportMap[br]),TURNKEY_API_BASE_URL="https://api.turnkey.com",TURNKEY_API_KEY_EXPIRY_MESSAGE="Turnkey error 16: expired api key",TURNKEY_API_KEY_NOT_FOUND_MESSAGE="Turnkey error 16: could not find public key",WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE="The operation either timed out or was not allowed",WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",INVALID_PASSKEY_SELECTED_ERROR_MESSAGE="Turnkey error 5: webauthn authenticator not found in organization or parent organization",USER_CANCELLED_REQUEST_ERROR_MESSAGE="The user cancelled the request",TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS=[TURNKEY_API_KEY_EXPIRY_MESSAGE,TURNKEY_API_KEY_NOT_FOUND_MESSAGE],TURNKEY_SDK_BENIGN_ERRORS=[WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE,WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE,INVALID_PASSKEY_SELECTED_ERROR_MESSAGE,USER_CANCELLED_REQUEST_ERROR_MESSAGE];class DynamicEmbeddedWalletsLogger extends Logger$1{constructor(br,wr){super(br,wr)}error(br,...wr){const[Er]=wr;!(Er!=null&&Er.message)||!TURNKEY_SDK_BENIGN_ERRORS.some(kr=>Er.message.includes(kr))?(Logger$1.events.emit("error",br),this.log(LogLevel.ERROR,br,...wr)):this.warn(br,...wr)}}const logger$4=new DynamicEmbeddedWalletsLogger("Dynamic embedded wallets",LogLevel.INFO),stampHeaderName$1="X-Stamp";var IframeEventType;(function(fr){fr.PublicKeyReady="PUBLIC_KEY_READY",fr.InjectCredentialBundle="INJECT_CREDENTIAL_BUNDLE",fr.InjectKeyExportBundle="INJECT_KEY_EXPORT_BUNDLE",fr.InjectWalletExportBundle="INJECT_WALLET_EXPORT_BUNDLE",fr.InjectImportBundle="INJECT_IMPORT_BUNDLE",fr.ExtractWalletEncryptedBundle="EXTRACT_WALLET_ENCRYPTED_BUNDLE",fr.ExtractKeyEncryptedBundle="EXTRACT_KEY_ENCRYPTED_BUNDLE",fr.ApplySettings="APPLY_SETTINGS",fr.BundleInjected="BUNDLE_INJECTED",fr.EncryptedBundleExtracted="ENCRYPTED_BUNDLE_EXTRACTED",fr.SettingsApplied="SETTINGS_APPLIED",fr.StampRequest="STAMP_REQUEST",fr.Stamp="STAMP",fr.Error="ERROR"})(IframeEventType||(IframeEventType={}));var KeyFormat;(function(fr){fr.Hexadecimal="HEXADECIMAL",fr.Solana="SOLANA"})(KeyFormat||(KeyFormat={}));class IframeStamper{constructor(br){if(typeof window>"u")throw new Error("Cannot initialize iframe in non-browser environment");if(!br.iframeContainer)throw new Error("Iframe container cannot be found");if(this.container=br.iframeContainer,this.container.querySelector(`#${br.iframeElementId}`))throw new Error(`Iframe element with ID ${br.iframeElementId} already exists`);let wr=window.document.createElement("iframe");wr.setAttribute("sandbox","allow-scripts allow-same-origin"),wr.id=br.iframeElementId,wr.src=br.iframeUrl,this.iframe=wr;const Er=new URL(br.iframeUrl);this.iframeOrigin=Er.origin,this.iframePublicKey=null}async init(){return this.container.appendChild(this.iframe),new Promise((br,wr)=>{window.addEventListener("message",Er=>{var kr;Er.origin===this.iframeOrigin&&((kr=Er.data)==null?void 0:kr.type)===IframeEventType.PublicKeyReady&&(this.iframePublicKey=Er.data.value,br(Er.data.value))},!1)})}clear(){this.iframe.remove()}publicKey(){return this.iframePublicKey}async injectCredentialBundle(br){return new Promise((wr,Er)=>{var kr;(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectCredentialBundle,value:br},"*"),window.addEventListener("message",jr=>{var Br,qr;jr.origin===this.iframeOrigin&&(((Br=jr.data)==null?void 0:Br.type)===IframeEventType.BundleInjected&&wr(jr.data.value),((qr=jr.data)==null?void 0:qr.type)===IframeEventType.Error&&Er(jr.data.value))},!1)})}async injectKeyExportBundle(br,wr,Er){var kr;return(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectKeyExportBundle,value:br,keyFormat:Er,organizationId:wr},"*"),new Promise((jr,Br)=>{window.addEventListener("message",qr=>{var Wr,Vr;qr.origin===this.iframeOrigin&&(((Wr=qr.data)==null?void 0:Wr.type)===IframeEventType.BundleInjected&&jr(qr.data.value),((Vr=qr.data)==null?void 0:Vr.type)===IframeEventType.Error&&Br(qr.data.value))},!1)})}async injectWalletExportBundle(br,wr){var Er;return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.InjectWalletExportBundle,value:br,organizationId:wr},"*"),new Promise((kr,jr)=>{window.addEventListener("message",Br=>{var qr,Wr;Br.origin===this.iframeOrigin&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.BundleInjected&&kr(Br.data.value),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}async injectImportBundle(br,wr,Er){var kr;return(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectImportBundle,value:br,organizationId:wr,userId:Er},"*"),new Promise((jr,Br)=>{window.addEventListener("message",qr=>{var Wr,Vr;qr.origin===this.iframeOrigin&&(((Wr=qr.data)==null?void 0:Wr.type)===IframeEventType.BundleInjected&&jr(qr.data.value),((Vr=qr.data)==null?void 0:Vr.type)===IframeEventType.Error&&Br(qr.data.value))},!1)})}async extractWalletEncryptedBundle(){var br;return(br=this.iframe.contentWindow)==null||br.postMessage({type:IframeEventType.ExtractWalletEncryptedBundle},"*"),new Promise((wr,Er)=>{window.addEventListener("message",kr=>{var jr,Br;kr.origin===this.iframeOrigin&&(((jr=kr.data)==null?void 0:jr.type)===IframeEventType.EncryptedBundleExtracted&&wr(kr.data.value),((Br=kr.data)==null?void 0:Br.type)===IframeEventType.Error&&Er(kr.data.value))},!1)})}async extractKeyEncryptedBundle(br){var wr;return(wr=this.iframe.contentWindow)==null||wr.postMessage({type:IframeEventType.ExtractKeyEncryptedBundle,keyFormat:br},"*"),new Promise((Er,kr)=>{window.addEventListener("message",jr=>{var Br,qr;jr.origin===this.iframeOrigin&&(((Br=jr.data)==null?void 0:Br.type)===IframeEventType.EncryptedBundleExtracted&&Er(jr.data.value),((qr=jr.data)==null?void 0:qr.type)===IframeEventType.Error&&kr(jr.data.value))},!1)})}async applySettings(br){var Er;const wr=JSON.stringify(br);return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.ApplySettings,value:wr},"*"),new Promise((kr,jr)=>{window.addEventListener("message",Br=>{var qr,Wr;Br.origin===this.iframeOrigin&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.SettingsApplied&&kr(Br.data.value),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}async stamp(br){var Er;if(this.iframePublicKey===null)throw new Error("null iframe public key. Have you called/awaited .init()?");const wr=this.iframeOrigin;return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.StampRequest,value:br},"*"),new Promise(function(kr,jr){window.addEventListener("message",Br=>{var qr,Wr;Br.origin===wr&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.Stamp&&kr({stampHeaderName:stampHeaderName$1,stampHeaderValue:Br.data.value}),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}}var browserPonyfill={exports:{}};(function(fr,br){var wr=typeof self<"u"?self:commonjsGlobal,Er=function(){function jr(){this.fetch=!1,this.DOMException=wr.DOMException}return jr.prototype=wr,new jr}();(function(jr){(function(Br){var qr={searchParams:"URLSearchParams"in jr,iterable:"Symbol"in jr&&"iterator"in Symbol,blob:"FileReader"in jr&&"Blob"in jr&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in jr,arrayBuffer:"ArrayBuffer"in jr};function Wr(Gr){return Gr&&DataView.prototype.isPrototypeOf(Gr)}if(qr.arrayBuffer)var Vr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Hr=ArrayBuffer.isView||function(Gr){return Gr&&Vr.indexOf(Object.prototype.toString.call(Gr))>-1};function Zr(Gr){if(typeof Gr!="string"&&(Gr=String(Gr)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(Gr))throw new TypeError("Invalid character in header field name");return Gr.toLowerCase()}function Jr(Gr){return typeof Gr!="string"&&(Gr=String(Gr)),Gr}function Xr(Gr){var Yr={next:function(){var Sn=Gr.shift();return{done:Sn===void 0,value:Sn}}};return qr.iterable&&(Yr[Symbol.iterator]=function(){return Yr}),Yr}function En(Gr){this.map={},Gr instanceof En?Gr.forEach(function(Yr,Sn){this.append(Sn,Yr)},this):Array.isArray(Gr)?Gr.forEach(function(Yr){this.append(Yr[0],Yr[1])},this):Gr&&Object.getOwnPropertyNames(Gr).forEach(function(Yr){this.append(Yr,Gr[Yr])},this)}En.prototype.append=function(Gr,Yr){Gr=Zr(Gr),Yr=Jr(Yr);var Sn=this.map[Gr];this.map[Gr]=Sn?Sn+", "+Yr:Yr},En.prototype.delete=function(Gr){delete this.map[Zr(Gr)]},En.prototype.get=function(Gr){return Gr=Zr(Gr),this.has(Gr)?this.map[Gr]:null},En.prototype.has=function(Gr){return this.map.hasOwnProperty(Zr(Gr))},En.prototype.set=function(Gr,Yr){this.map[Zr(Gr)]=Jr(Yr)},En.prototype.forEach=function(Gr,Yr){for(var Sn in this.map)this.map.hasOwnProperty(Sn)&&Gr.call(Yr,this.map[Sn],Sn,this)},En.prototype.keys=function(){var Gr=[];return this.forEach(function(Yr,Sn){Gr.push(Sn)}),Xr(Gr)},En.prototype.values=function(){var Gr=[];return this.forEach(function(Yr){Gr.push(Yr)}),Xr(Gr)},En.prototype.entries=function(){var Gr=[];return this.forEach(function(Yr,Sn){Gr.push([Sn,Yr])}),Xr(Gr)},qr.iterable&&(En.prototype[Symbol.iterator]=En.prototype.entries);function wn(Gr){if(Gr.bodyUsed)return Promise.reject(new TypeError("Already read"));Gr.bodyUsed=!0}function $n(Gr){return new Promise(function(Yr,Sn){Gr.onload=function(){Yr(Gr.result)},Gr.onerror=function(){Sn(Gr.error)}})}function Tn(Gr){var Yr=new FileReader,Sn=$n(Yr);return Yr.readAsArrayBuffer(Gr),Sn}function In(Gr){var Yr=new FileReader,Sn=$n(Yr);return Yr.readAsText(Gr),Sn}function jn(Gr){for(var Yr=new Uint8Array(Gr),Sn=new Array(Yr.length),An=0;An-1?Yr:Gr}function ro(Gr,Yr){Yr=Yr||{};var Sn=Yr.body;if(Gr instanceof ro){if(Gr.bodyUsed)throw new TypeError("Already read");this.url=Gr.url,this.credentials=Gr.credentials,Yr.headers||(this.headers=new En(Gr.headers)),this.method=Gr.method,this.mode=Gr.mode,this.signal=Gr.signal,!Sn&&Gr._bodyInit!=null&&(Sn=Gr._bodyInit,Gr.bodyUsed=!0)}else this.url=String(Gr);if(this.credentials=Yr.credentials||this.credentials||"same-origin",(Yr.headers||!this.headers)&&(this.headers=new En(Yr.headers)),this.method=_i(Yr.method||this.method||"GET"),this.mode=Yr.mode||this.mode||null,this.signal=Yr.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&Sn)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(Sn)}ro.prototype.clone=function(){return new ro(this,{body:this._bodyInit})};function to(Gr){var Yr=new FormData;return Gr.trim().split("&").forEach(function(Sn){if(Sn){var An=Sn.split("="),Pn=An.shift().replace(/\+/g," "),Nn=An.join("=").replace(/\+/g," ");Yr.append(decodeURIComponent(Pn),decodeURIComponent(Nn))}}),Yr}function io(Gr){var Yr=new En,Sn=Gr.replace(/\r?\n[\t ]+/g," ");return Sn.split(/\r?\n/).forEach(function(An){var Pn=An.split(":"),Nn=Pn.shift().trim();if(Nn){var zn=Pn.join(":").trim();Yr.append(Nn,zn)}}),Yr}ga.call(ro.prototype);function no(Gr,Yr){Yr||(Yr={}),this.type="default",this.status=Yr.status===void 0?200:Yr.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in Yr?Yr.statusText:"OK",this.headers=new En(Yr.headers),this.url=Yr.url||"",this._initBody(Gr)}ga.call(no.prototype),no.prototype.clone=function(){return new no(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new En(this.headers),url:this.url})},no.error=function(){var Gr=new no(null,{status:0,statusText:""});return Gr.type="error",Gr};var $a=[301,302,303,307,308];no.redirect=function(Gr,Yr){if($a.indexOf(Yr)===-1)throw new RangeError("Invalid status code");return new no(null,{status:Yr,headers:{location:Gr}})},Br.DOMException=jr.DOMException;try{new Br.DOMException}catch{Br.DOMException=function(Yr,Sn){this.message=Yr,this.name=Sn;var An=Error(Yr);this.stack=An.stack},Br.DOMException.prototype=Object.create(Error.prototype),Br.DOMException.prototype.constructor=Br.DOMException}function Rn(Gr,Yr){return new Promise(function(Sn,An){var Pn=new ro(Gr,Yr);if(Pn.signal&&Pn.signal.aborted)return An(new Br.DOMException("Aborted","AbortError"));var Nn=new XMLHttpRequest;function zn(){Nn.abort()}Nn.onload=function(){var On={status:Nn.status,statusText:Nn.statusText,headers:io(Nn.getAllResponseHeaders()||"")};On.url="responseURL"in Nn?Nn.responseURL:On.headers.get("X-Request-URL");var _n="response"in Nn?Nn.response:Nn.responseText;Sn(new no(_n,On))},Nn.onerror=function(){An(new TypeError("Network request failed"))},Nn.ontimeout=function(){An(new TypeError("Network request failed"))},Nn.onabort=function(){An(new Br.DOMException("Aborted","AbortError"))},Nn.open(Pn.method,Pn.url,!0),Pn.credentials==="include"?Nn.withCredentials=!0:Pn.credentials==="omit"&&(Nn.withCredentials=!1),"responseType"in Nn&&qr.blob&&(Nn.responseType="blob"),Pn.headers.forEach(function(On,_n){Nn.setRequestHeader(_n,On)}),Pn.signal&&(Pn.signal.addEventListener("abort",zn),Nn.onreadystatechange=function(){Nn.readyState===4&&Pn.signal.removeEventListener("abort",zn)}),Nn.send(typeof Pn._bodyInit>"u"?null:Pn._bodyInit)})}return Rn.polyfill=!0,jr.fetch||(jr.fetch=Rn,jr.Headers=En,jr.Request=ro,jr.Response=no),Br.Headers=En,Br.Request=ro,Br.Response=no,Br.fetch=Rn,Object.defineProperty(Br,"__esModule",{value:!0}),Br})({})})(Er),Er.fetch.ponyfill=!0,delete Er.fetch.polyfill;var kr=Er;br=kr.fetch,br.default=kr.fetch,br.fetch=kr.fetch,br.Headers=kr.Headers,br.Request=kr.Request,br.Response=kr.Response,fr.exports=br})(browserPonyfill,browserPonyfill.exports);var browserPonyfillExports=browserPonyfill.exports;const o$2=getDefaultExportFromCjs$2(browserPonyfillExports),fetch$1=browserPonyfillExports.fetch;class TurnkeyRequestError extends Error{constructor(br){let wr=`Turnkey error ${br.code}: ${br.message}`;br.details!=null&&(wr+=` (Details: ${JSON.stringify(br.details)})`),super(wr),this.name="TurnkeyRequestError",this.details=br.details??null,this.code=br.code}}const VERSION$1="@turnkey/http@2.12.2";class TurnkeyClient{constructor(br,wr){if(this.getActivity=async Er=>this.request("/public/v1/query/get_activity",Er),this.stampGetActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getApiKey=async Er=>this.request("/public/v1/query/get_api_key",Er),this.stampGetApiKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_api_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getApiKeys=async Er=>this.request("/public/v1/query/get_api_keys",Er),this.stampGetApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAttestationDocument=async Er=>this.request("/public/v1/query/get_attestation",Er),this.stampGetAttestationDocument=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_attestation",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAuthenticator=async Er=>this.request("/public/v1/query/get_authenticator",Er),this.stampGetAuthenticator=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_authenticator",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAuthenticators=async Er=>this.request("/public/v1/query/get_authenticators",Er),this.stampGetAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOauthProviders=async Er=>this.request("/public/v1/query/get_oauth_providers",Er),this.stampGetOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOrganization=async Er=>this.request("/public/v1/query/get_organization",Er),this.stampGetOrganization=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_organization",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOrganizationConfigs=async Er=>this.request("/public/v1/query/get_organization_configs",Er),this.stampGetOrganizationConfigs=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_organization_configs",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPolicy=async Er=>this.request("/public/v1/query/get_policy",Er),this.stampGetPolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPrivateKey=async Er=>this.request("/public/v1/query/get_private_key",Er),this.stampGetPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getUser=async Er=>this.request("/public/v1/query/get_user",Er),this.stampGetUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWallet=async Er=>this.request("/public/v1/query/get_wallet",Er),this.stampGetWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getActivities=async Er=>this.request("/public/v1/query/list_activities",Er),this.stampGetActivities=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_activities",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPolicies=async Er=>this.request("/public/v1/query/list_policies",Er),this.stampGetPolicies=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_policies",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.listPrivateKeyTags=async Er=>this.request("/public/v1/query/list_private_key_tags",Er),this.stampListPrivateKeyTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_private_key_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPrivateKeys=async Er=>this.request("/public/v1/query/list_private_keys",Er),this.stampGetPrivateKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_private_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getSubOrgIds=async Er=>this.request("/public/v1/query/list_suborgs",Er),this.stampGetSubOrgIds=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_suborgs",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.listUserTags=async Er=>this.request("/public/v1/query/list_user_tags",Er),this.stampListUserTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_user_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getUsers=async Er=>this.request("/public/v1/query/list_users",Er),this.stampGetUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWalletAccounts=async Er=>this.request("/public/v1/query/list_wallet_accounts",Er),this.stampGetWalletAccounts=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_wallet_accounts",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWallets=async Er=>this.request("/public/v1/query/list_wallets",Er),this.stampGetWallets=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_wallets",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWhoami=async Er=>this.request("/public/v1/query/whoami",Er),this.stampGetWhoami=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/whoami",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.approveActivity=async Er=>this.request("/public/v1/submit/approve_activity",Er),this.stampApproveActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/approve_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createApiKeys=async Er=>this.request("/public/v1/submit/create_api_keys",Er),this.stampCreateApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createApiOnlyUsers=async Er=>this.request("/public/v1/submit/create_api_only_users",Er),this.stampCreateApiOnlyUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_api_only_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createAuthenticators=async Er=>this.request("/public/v1/submit/create_authenticators",Er),this.stampCreateAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createInvitations=async Er=>this.request("/public/v1/submit/create_invitations",Er),this.stampCreateInvitations=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_invitations",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createOauthProviders=async Er=>this.request("/public/v1/submit/create_oauth_providers",Er),this.stampCreateOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPolicies=async Er=>this.request("/public/v1/submit/create_policies",Er),this.stampCreatePolicies=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_policies",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPolicy=async Er=>this.request("/public/v1/submit/create_policy",Er),this.stampCreatePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPrivateKeyTag=async Er=>this.request("/public/v1/submit/create_private_key_tag",Er),this.stampCreatePrivateKeyTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_private_key_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPrivateKeys=async Er=>this.request("/public/v1/submit/create_private_keys",Er),this.stampCreatePrivateKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_private_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createReadOnlySession=async Er=>this.request("/public/v1/submit/create_read_only_session",Er),this.stampCreateReadOnlySession=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_read_only_session",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createReadWriteSession=async Er=>this.request("/public/v1/submit/create_read_write_session",Er),this.stampCreateReadWriteSession=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_read_write_session",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createSubOrganization=async Er=>this.request("/public/v1/submit/create_sub_organization",Er),this.stampCreateSubOrganization=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_sub_organization",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createUserTag=async Er=>this.request("/public/v1/submit/create_user_tag",Er),this.stampCreateUserTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_user_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createUsers=async Er=>this.request("/public/v1/submit/create_users",Er),this.stampCreateUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createWallet=async Er=>this.request("/public/v1/submit/create_wallet",Er),this.stampCreateWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createWalletAccounts=async Er=>this.request("/public/v1/submit/create_wallet_accounts",Er),this.stampCreateWalletAccounts=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_wallet_accounts",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteApiKeys=async Er=>this.request("/public/v1/submit/delete_api_keys",Er),this.stampDeleteApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteAuthenticators=async Er=>this.request("/public/v1/submit/delete_authenticators",Er),this.stampDeleteAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteInvitation=async Er=>this.request("/public/v1/submit/delete_invitation",Er),this.stampDeleteInvitation=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_invitation",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteOauthProviders=async Er=>this.request("/public/v1/submit/delete_oauth_providers",Er),this.stampDeleteOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deletePolicy=async Er=>this.request("/public/v1/submit/delete_policy",Er),this.stampDeletePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deletePrivateKeyTags=async Er=>this.request("/public/v1/submit/delete_private_key_tags",Er),this.stampDeletePrivateKeyTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_private_key_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteUserTags=async Er=>this.request("/public/v1/submit/delete_user_tags",Er),this.stampDeleteUserTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_user_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteUsers=async Er=>this.request("/public/v1/submit/delete_users",Er),this.stampDeleteUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.emailAuth=async Er=>this.request("/public/v1/submit/email_auth",Er),this.stampEmailAuth=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/email_auth",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportPrivateKey=async Er=>this.request("/public/v1/submit/export_private_key",Er),this.stampExportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportWallet=async Er=>this.request("/public/v1/submit/export_wallet",Er),this.stampExportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportWalletAccount=async Er=>this.request("/public/v1/submit/export_wallet_account",Er),this.stampExportWalletAccount=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_wallet_account",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.importPrivateKey=async Er=>this.request("/public/v1/submit/import_private_key",Er),this.stampImportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/import_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.importWallet=async Er=>this.request("/public/v1/submit/import_wallet",Er),this.stampImportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/import_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initImportPrivateKey=async Er=>this.request("/public/v1/submit/init_import_private_key",Er),this.stampInitImportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_import_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initImportWallet=async Er=>this.request("/public/v1/submit/init_import_wallet",Er),this.stampInitImportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_import_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initUserEmailRecovery=async Er=>this.request("/public/v1/submit/init_user_email_recovery",Er),this.stampInitUserEmailRecovery=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_user_email_recovery",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.oauth=async Er=>this.request("/public/v1/submit/oauth",Er),this.stampOauth=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/oauth",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.recoverUser=async Er=>this.request("/public/v1/submit/recover_user",Er),this.stampRecoverUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/recover_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.rejectActivity=async Er=>this.request("/public/v1/submit/reject_activity",Er),this.stampRejectActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/reject_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.removeOrganizationFeature=async Er=>this.request("/public/v1/submit/remove_organization_feature",Er),this.stampRemoveOrganizationFeature=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/remove_organization_feature",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.setOrganizationFeature=async Er=>this.request("/public/v1/submit/set_organization_feature",Er),this.stampSetOrganizationFeature=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/set_organization_feature",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signRawPayload=async Er=>this.request("/public/v1/submit/sign_raw_payload",Er),this.stampSignRawPayload=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_raw_payload",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signRawPayloads=async Er=>this.request("/public/v1/submit/sign_raw_payloads",Er),this.stampSignRawPayloads=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_raw_payloads",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signTransaction=async Er=>this.request("/public/v1/submit/sign_transaction",Er),this.stampSignTransaction=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_transaction",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updatePolicy=async Er=>this.request("/public/v1/submit/update_policy",Er),this.stampUpdatePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updatePrivateKeyTag=async Er=>this.request("/public/v1/submit/update_private_key_tag",Er),this.stampUpdatePrivateKeyTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_private_key_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateRootQuorum=async Er=>this.request("/public/v1/submit/update_root_quorum",Er),this.stampUpdateRootQuorum=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_root_quorum",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateUser=async Er=>this.request("/public/v1/submit/update_user",Er),this.stampUpdateUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateUserTag=async Er=>this.request("/public/v1/submit/update_user_tag",Er),this.stampUpdateUserTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_user_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},!br.baseUrl)throw new Error("Missing base URL. Please verify env vars.");this.config=br,this.stamper=wr}async request(br,wr){const Er=this.config.baseUrl+br,kr=JSON.stringify(wr),jr=await this.stamper.stamp(kr),Br=await fetch$1(Er,{method:"POST",headers:{[jr.stampHeaderName]:jr.stampHeaderValue,"X-Client-Version":VERSION$1},body:kr,redirect:"follow"});if(!Br.ok){let Wr;try{Wr=await Br.json()}catch{throw new Error(`${Br.status} ${Br.statusText}`)}throw new TurnkeyRequestError(Wr)}return await Br.json()}}class TurnkeyActivityError extends Error{constructor(br){const{message:wr,cause:Er,activityId:kr,activityStatus:jr,activityType:Br}=br;super(wr),this.name="TurnkeyActivityError",this.activityId=kr??null,this.activityStatus=jr??null,this.activityType=Br??null,this.cause=Er??null}}function bufferToBase64url(fr){const br=new Uint8Array(fr);let wr="";for(const jr of br)wr+=String.fromCharCode(jr);return btoa(wr).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}const copyValue="copy",convertValue="convert";function convert$1(fr,br,wr){if(br===copyValue)return wr;if(br===convertValue)return fr(wr);if(br instanceof Array)return wr.map(Er=>convert$1(fr,br[0],Er));if(br instanceof Object){const Er={};for(const[kr,jr]of Object.entries(br)){if(jr.derive){const Br=jr.derive(wr);Br!==void 0&&(wr[kr]=Br)}if(!(kr in wr)){if(jr.required)throw new Error(`Missing key: ${kr}`);continue}if(wr[kr]==null){Er[kr]=null;continue}Er[kr]=convert$1(fr,jr.schema,wr[kr])}return Er}}function derived(fr,br){return{required:!0,schema:fr,derive:br}}function required(fr){return{required:!0,schema:fr}}function optional$3(fr){return{required:!1,schema:fr}}const simplifiedClientExtensionResultsSchema={appid:optional$3(copyValue),appidExclude:optional$3(copyValue),credProps:optional$3(copyValue)},publicKeyCredentialWithAssertion={type:required(copyValue),id:required(copyValue),rawId:required(convertValue),authenticatorAttachment:optional$3(copyValue),response:required({clientDataJSON:required(convertValue),authenticatorData:required(convertValue),signature:required(convertValue),userHandle:required(convertValue)}),clientExtensionResults:derived(simplifiedClientExtensionResultsSchema,fr=>fr.getClientExtensionResults())};function getResponseToJSON(fr){return convert$1(bufferToBase64url,publicKeyCredentialWithAssertion,fr)}async function get$2(fr){const br=await navigator.credentials.get(fr);return br.toJSON=()=>getResponseToJSON(br),br}const K$2=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998];function createHash(fr){return new Hash}class Hash{constructor(){this.A=1779033703,this.B=-1150833019,this.C=1013904242,this.D=-1521486534,this.E=1359893119,this.F=-1694144372,this.G=528734635,this.H=1541459225,this._size=0,this._sp=0,(!sharedBuffer||sharedOffset>=8e3)&&(sharedBuffer=new ArrayBuffer(8e3),sharedOffset=0),this._byte=new Uint8Array(sharedBuffer,sharedOffset,80),this._word=new Int32Array(sharedBuffer,sharedOffset,20),sharedOffset+=80}update(br){if(typeof br=="string")return this._utf8(br);if(br==null)throw new TypeError("Invalid type: "+typeof br);const wr=br.byteOffset,Er=br.byteLength;let kr=Er/64|0,jr=0;if(kr&&!(wr&3)&&!(this._size%64)){const qr=new Int32Array(br.buffer,wr,kr*16);for(;kr--;)this._int32(qr,jr>>2),jr+=64;this._size+=jr}if(br.BYTES_PER_ELEMENT!==1&&br.buffer){const qr=new Uint8Array(br.buffer,wr+jr,Er-jr);return this._uint8(qr)}return jr===Er?this:this._uint8(br,jr)}_uint8(br,wr){const{_byte:Er,_word:kr}=this,jr=br.length;for(wr=wr|0;wr=64&&this._int32(kr),this._size+=qr-Br}return this}_utf8(br){const{_byte:wr,_word:Er}=this,kr=br.length;let jr=this._sp;for(let Br=0;Br>>6,wr[Wr++]=128|Vr&63):Vr<55296||Vr>57343?(wr[Wr++]=224|Vr>>>12,wr[Wr++]=128|Vr>>>6&63,wr[Wr++]=128|Vr&63):jr?(Vr=((jr&1023)<<10)+(Vr&1023)+65536,wr[Wr++]=240|Vr>>>18,wr[Wr++]=128|Vr>>>12&63,wr[Wr++]=128|Vr>>>6&63,wr[Wr++]=128|Vr&63,jr=0):jr=Vr}Wr>=64&&(this._int32(Er),Er[0]=Er[16]),this._size+=Wr-qr}return this._sp=jr,this}_int32(br,wr){let{A:Er,B:kr,C:jr,D:Br,E:qr,F:Wr,G:Vr,H:Hr}=this,Zr=0;for(wr=wr|0;Zr<16;)W$1[Zr++]=swap32(br[wr++]);for(Zr=16;Zr<64;Zr++)W$1[Zr]=gamma1(W$1[Zr-2])+W$1[Zr-7]+gamma0(W$1[Zr-15])+W$1[Zr-16]|0;for(Zr=0;Zr<64;Zr++){const Jr=Hr+sigma1(qr)+ch(qr,Wr,Vr)+K$2[Zr]+W$1[Zr]|0,Xr=sigma0(Er)+maj(Er,kr,jr)|0;Hr=Vr,Vr=Wr,Wr=qr,qr=Br+Jr|0,Br=jr,jr=kr,kr=Er,Er=Jr+Xr|0}this.A=Er+this.A|0,this.B=kr+this.B|0,this.C=jr+this.C|0,this.D=Br+this.D|0,this.E=qr+this.E|0,this.F=Wr+this.F|0,this.G=Vr+this.G|0,this.H=Hr+this.H|0}digest(br){const{_byte:wr,_word:Er}=this;let kr=this._size%64|0;for(wr[kr++]=128;kr&3;)wr[kr++]=0;if(kr>>=2,kr>14){for(;kr<16;)Er[kr++]=0;kr=0,this._int32(Er)}for(;kr<16;)Er[kr++]=0;const jr=this._size*8,Br=(jr&4294967295)>>>0,qr=(jr-Br)/4294967296;return qr&&(Er[14]=swap32(qr)),Br&&(Er[15]=swap32(Br)),this._int32(Er),br==="hex"?this._hex():this._bin()}_hex(){const{A:br,B:wr,C:Er,D:kr,E:jr,F:Br,G:qr,H:Wr}=this;return hex32(br)+hex32(wr)+hex32(Er)+hex32(kr)+hex32(jr)+hex32(Br)+hex32(qr)+hex32(Wr)}_bin(){const{A:br,B:wr,C:Er,D:kr,E:jr,F:Br,G:qr,H:Wr,_byte:Vr,_word:Hr}=this;return Hr[0]=swap32(br),Hr[1]=swap32(wr),Hr[2]=swap32(Er),Hr[3]=swap32(kr),Hr[4]=swap32(jr),Hr[5]=swap32(Br),Hr[6]=swap32(qr),Hr[7]=swap32(Wr),Vr.slice(0,32)}}const W$1=new Int32Array(64);let sharedBuffer,sharedOffset=0;const hex32=fr=>(fr+4294967296).toString(16).substr(-8),swapLE=fr=>fr<<24&4278190080|fr<<8&16711680|fr>>8&65280|fr>>24&255,swapBE=fr=>fr,swap32=isBE()?swapBE:swapLE,ch=(fr,br,wr)=>wr^fr&(br^wr),maj=(fr,br,wr)=>fr&br|wr&(fr|br),sigma0=fr=>(fr>>>2|fr<<30)^(fr>>>13|fr<<19)^(fr>>>22|fr<<10),sigma1=fr=>(fr>>>6|fr<<26)^(fr>>>11|fr<<21)^(fr>>>25|fr<<7),gamma0=fr=>(fr>>>7|fr<<25)^(fr>>>18|fr<<14)^fr>>>3,gamma1=fr=>(fr>>>17|fr<<15)^(fr>>>19|fr<<13)^fr>>>10;function isBE(){return new Uint8Array(new Uint16Array([65279]).buffer)[0]===254}const stampHeaderName="X-Stamp-Webauthn",defaultTimeout=5*60*1e3,defaultUserVerification="preferred";class WebauthnStamper{constructor(br){this.rpId=br.rpId,this.timeout=br.timeout||defaultTimeout,this.userVerification=br.userVerification||defaultUserVerification,this.allowCredentials=br.allowCredentials||[]}async stamp(br){const wr=getChallengeFromPayload(br),Er={publicKey:{rpId:this.rpId,challenge:wr,allowCredentials:this.allowCredentials,timeout:this.timeout,userVerification:this.userVerification}},jr=(await get$2(Er)).toJSON(),Br={authenticatorData:jr.response.authenticatorData,clientDataJson:jr.response.clientDataJSON,credentialId:jr.id,signature:jr.response.signature};return{stampHeaderName,stampHeaderValue:JSON.stringify(Br)}}}function getChallengeFromPayload(fr){const br=createHash().update(fr).digest("hex");return new TextEncoder().encode(br)}var version$b="3.8.2";class WebauthnNotSupportedError extends Error{constructor(){super("Webauthn is not supported on this device")}}function __awaiter$b(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;function utf8StringToBuffer(fr){return new TextEncoder().encode(fr)}function bufferToBase64URLString(fr){const br=new Uint8Array(fr);let wr="";for(const kr of br)wr+=String.fromCharCode(kr);return btoa(wr).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function base64URLStringToBuffer(fr){const br=fr.replace(/-/g,"+").replace(/_/g,"/"),wr=(4-br.length%4)%4,Er=br.padEnd(br.length+wr,"="),kr=atob(Er),jr=new ArrayBuffer(kr.length),Br=new Uint8Array(jr);for(let qr=0;qrBr.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:fr}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:fr});if(fr.name==="SecurityError"){const jr=window.location.hostname;if(isValidDomain(jr)){if(wr.rp.id!==jr)return new WebAuthnError({message:`The RP ID "${wr.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:fr})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:fr})}else if(fr.name==="TypeError"){if(wr.user.id.byteLength<1||wr.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:fr})}else if(fr.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:fr})}return fr}class BaseWebAuthnAbortService{createNewAbortSignal(){if(this.controller){const wr=new Error("Cancelling existing WebAuthn API call for new one");wr.name="AbortError",this.controller.abort(wr)}const br=new AbortController;return this.controller=br,br.signal}cancelCeremony(){if(this.controller){const br=new Error("Manually cancelling existing WebAuthn API call");br.name="AbortError",this.controller.abort(br),this.controller=void 0}}}const WebAuthnAbortService=new BaseWebAuthnAbortService,attachments=["cross-platform","platform"];function toAuthenticatorAttachment(fr){if(fr&&!(attachments.indexOf(fr)<0))return fr}async function startRegistration(fr){var Jr;if(!browserSupportsWebAuthn())throw new Error("WebAuthn is not supported in this browser");const wr={publicKey:{...fr,challenge:base64URLStringToBuffer(fr.challenge),user:{...fr.user,id:utf8StringToBuffer(fr.user.id)},excludeCredentials:(Jr=fr.excludeCredentials)==null?void 0:Jr.map(toPublicKeyCredentialDescriptor)}};wr.signal=WebAuthnAbortService.createNewAbortSignal();let Er;try{Er=await navigator.credentials.create(wr)}catch(Xr){throw identifyRegistrationError({error:Xr,options:wr})}if(!Er)throw new Error("Registration was not completed");const{id:kr,rawId:jr,response:Br,type:qr}=Er;let Wr;typeof Br.getTransports=="function"&&(Wr=Br.getTransports());let Vr;if(typeof Br.getPublicKeyAlgorithm=="function")try{Vr=Br.getPublicKeyAlgorithm()}catch(Xr){warnOnBrokenImplementation("getPublicKeyAlgorithm()",Xr)}let Hr;if(typeof Br.getPublicKey=="function")try{const Xr=Br.getPublicKey();Xr!==null&&(Hr=bufferToBase64URLString(Xr))}catch(Xr){warnOnBrokenImplementation("getPublicKey()",Xr)}let Zr;if(typeof Br.getAuthenticatorData=="function")try{Zr=bufferToBase64URLString(Br.getAuthenticatorData())}catch(Xr){warnOnBrokenImplementation("getAuthenticatorData()",Xr)}return{id:kr,rawId:bufferToBase64URLString(jr),response:{attestationObject:bufferToBase64URLString(Br.attestationObject),clientDataJSON:bufferToBase64URLString(Br.clientDataJSON),transports:Wr,publicKeyAlgorithm:Vr,publicKey:Hr,authenticatorData:Zr},type:qr,clientExtensionResults:Er.getClientExtensionResults(),authenticatorAttachment:toAuthenticatorAttachment(Er.authenticatorAttachment)}}function warnOnBrokenImplementation(fr,br){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${fr}. You should report this error to them. + `,onClick:()=>wr(br==null?void 0:br.origin),children:"Connect"})]})]})]})},PushWalletAppConnection=({selectedWallet:fr})=>{const{state:br}=useGlobalState(),{handleAppConnectionRejected:wr,handleAppConnectionSuccess:Er,handleRejectAllAppConnections:kr}=useEventEmitterContext(),[jr,Br]=reactExports.useState(null),qr=wn=>{Er(wn),Br("connected")},Wr=wn=>{wr(wn),Br("rejected")},Vr=async()=>{kr(),Br("notVisible")},Hr=()=>Br("notVisible"),Zr=()=>Br("notVisible"),Jr=()=>{window.close()},Xr=br==null?void 0:br.appConnections.some(wn=>wn.appConnectionStatus==="pending"),En=br==null?void 0:br.appConnections[(br==null?void 0:br.appConnections.length)-1];return Xr&&(En==null?void 0:En.appConnectionStatus)==="pending"?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(AppConnectionStatus,{selectedWallet:fr,appConnection:En,onSuccess:qr,onReject:Wr,onRejectAll:Vr})}):jr==="connected"&&(En==null?void 0:En.appConnectionStatus)==="connected"&&getAppParamValue()?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(ConnectionSuccess,{onClose:Hr})}):jr==="rejected"?jsxRuntimeExports.jsx(DrawerWrapper,{children:jsxRuntimeExports.jsx(ErrorContent,{icon:jsxRuntimeExports.jsx(Info,{size:32,color:"icon-state-danger-subtle"}),title:"Could not verify",subTitle:"Please go back to the app and retry",retryText:"Close",onClose:Zr,onRetry:Jr,note:"Closing this window will log you out."})}):null};var WALLET_TO_APP_ACTION=(fr=>(fr.IS_LOGGED_IN="isLoggedIn",fr.APP_CONNECTION_REJECTED="appConnectionRejected",fr.APP_CONNECTION_SUCCESS="appConnectionSuccess",fr.SIGNATURE="signature",fr.IS_LOGGED_OUT="loggedOut",fr.TAB_CLOSED="tabClosed",fr))(WALLET_TO_APP_ACTION||{}),APP_TO_WALLET_ACTION=(fr=>(fr.NEW_CONNECTION_REQUEST="newConnectionRequest",fr.SIGN_MESSAGE="signMessage",fr))(APP_TO_WALLET_ACTION||{});const initialState={wallet:null,appConnections:getAllAppConnections(),dynamicWallet:null,theme:"light",user:null,isAuthenticated:!1,jwt:null,walletLoadState:"idle",messageSignState:"idle",externalWalletAppConnectionStatus:"pending"};function globalReducer(fr,br){switch(br.type){case"INITIALIZE_WALLET":return{...fr,wallet:br.payload};case"SET_APP_CONNECTIONS":return{...fr,appConnections:br.payload};case"SET_DYNAMIC_WALLET":return{...fr,dynamicWallet:br.payload};case"RESET_WALLET":return{...fr,...initialState};case"SET_THEME":return{...fr,theme:br.payload};case"SET_USER":return{...fr,user:br.payload};case"SET_AUTHENTICATED":return{...fr,isAuthenticated:br.payload};case"SET_JWT":return{...fr,jwt:br.payload};case"SET_WALLET_LOAD_STATE":return{...fr,walletLoadState:br.payload};case"SET_MESSAGE_SIGN_STATE":return{...fr,messageSignState:br.payload};case"SET_EXTERNAL_WALLET_APP_CONNECTION_STATUS":return{...fr,externalWalletAppConnectionStatus:br.payload};default:return fr}}const GlobalContext=reactExports.createContext({state:initialState,dispatch:()=>null});function useGlobalState(){const fr=reactExports.useContext(GlobalContext);if(!fr)throw new Error("useGlobalState must be used within a GlobalProvider");return fr}const GlobalProvider=({children:fr})=>{const[br,wr]=reactExports.useReducer(globalReducer,initialState),{primaryWallet:Er,sdkHasLoaded:kr}=useDynamicContext(),jr=extractStateFromUrl(),Br=sessionStorage.getItem("jwt");return reactExports.useEffect(()=>{(async()=>{try{if(wr({type:"SET_WALLET_LOAD_STATE",payload:"loading"}),console.log("State Param",jr),jr){const Wr=await fetchJwtUsingState({stateParam:jr});sessionStorage.setItem("jwt",Wr),wr({type:"SET_JWT",payload:Wr});const Vr=new URL(window.location.href);Vr.searchParams.delete("state"),window.history.replaceState({},document.title,Vr.toString()),wr({type:"SET_WALLET_LOAD_STATE",payload:"success"})}Br&&(wr({type:"SET_JWT",payload:Br}),wr({type:"SET_WALLET_LOAD_STATE",payload:"success"})),Er&&(wr({type:"SET_WALLET_LOAD_STATE",payload:"success"}),wr({type:"SET_DYNAMIC_WALLET",payload:Er})),!jr&&!Br&&!Er&&kr&&wr({type:"SET_WALLET_LOAD_STATE",payload:"rejected"})}catch(Wr){throw wr({type:"SET_WALLET_LOAD_STATE",payload:"rejected"}),console.error("Error creating wallet:",Wr),Wr}})()},[jr,Br,Er,kr]),jsxRuntimeExports.jsx(GlobalContext.Provider,{value:{state:br,dispatch:wr},children:fr})},__vite_import_meta_env__={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_BACKEND_URL:"https://push-auth.push.org",VITE_APP_DYNAMIC_ENV_ID:"82e8732d-11b8-428d-a553-7087d0c44171",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"};var define_process_env_default$3={};function getAppBasePath(){if(typeof import.meta<"u"&&__vite_import_meta_env__)return"/push-wallet/";if(typeof process$1$1<"u"&&define_process_env_default$3){if(define_process_env_default$3.VITE_DEV_MODE==="preview")return"/push-wallet/pr-preview/";if(define_process_env_default$3.VITE_DEV_MODE==="testing")return"/push-wallet/"}return"/"}typeof window<"u"&&(window.global=globalThis,Object.assign(window,{Buffer:Buffer$1$1}));var version$d="3.8.2",version$c="3.8.2";function __awaiter$c(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,br||[])).next())})}function __classPrivateFieldGet$4(fr,br,wr,Er){if(wr==="a"&&!Er)throw new TypeError("Private accessor was defined without a getter");if(typeof br=="function"?fr!==br||!Er:!br.has(fr))throw new TypeError("Cannot read private member from an object whose class did not declare it");return wr==="m"?Er:wr==="a"?Er.call(fr):Er?Er.value:br.get(fr)}function __classPrivateFieldSet$4(fr,br,wr,Er,kr){if(typeof br=="function"?fr!==br||!kr:!br.has(fr))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kr?kr.value=wr:br.set(fr,wr),wr}typeof SuppressedError=="function"&&SuppressedError;const DEFAULT_JWK_MEMBER_BYTE_LENGTH=32;function stringToBase64urlString(fr){const br=btoa$1(fr);return base64StringToBase64UrlEncodedString(br)}function hexStringToBase64url(fr,br){const wr=fr.padStart(Math.ceil(fr.length/2)*2,"0"),Er=uint8ArrayFromHexString(wr,br);return stringToBase64urlString(Er.reduce((kr,jr)=>kr+String.fromCharCode(jr),""))}function base64StringToBase64UrlEncodedString(fr){return fr.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uint8ArrayToHexString(fr){return fr.reduce((br,wr)=>br+wr.toString(16).padStart(2,"0"),"")}const uint8ArrayFromHexString=(fr,br)=>{const wr=/^[0-9A-Fa-f]+$/;if(!fr||fr.length%2!=0||!wr.test(fr))throw new Error(`cannot create uint8array from invalid hex string: "${fr}"`);const Er=new Uint8Array(fr.match(/../g).map(jr=>parseInt(jr,16)));if(!br)return Er;if(fr.length/2>br)throw new Error("hex value cannot fit in a buffer of "+br+" byte(s)");let kr=new Uint8Array(br);return kr.set(Er,br-Er.length),kr};function btoa$1(fr){if(arguments.length===0)throw new TypeError("1 argument required, but only 0 present.");let br;for(fr=`${fr}`,br=0;br255)throw new Error(`InvalidCharacterError: found code point greater than 255:${fr.charCodeAt(br)} at position ${br}`);let wr="";for(br=0;br>2,Er[1]=(fr.charCodeAt(br)&3)<<4,fr.length>br+1&&(Er[1]|=fr.charCodeAt(br+1)>>4,Er[2]=(fr.charCodeAt(br+1)&15)<<2),fr.length>br+2&&(Er[2]|=fr.charCodeAt(br+2)>>6,Er[3]=fr.charCodeAt(br+2)&63);for(let kr=0;kr"u"?wr+="=":wr+=btoaLookup(Er[kr])}return wr}function btoaLookup(fr){const br="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";if(fr>=0&&fr<64)return br[fr]}const stampHeaderName$2="X-Stamp",isCryptoEnabledBrowser=typeof window<"u"&&typeof window.document<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u",isNode=typeof process$1$1<"u"&&process$1$1.versions!=null&&process$1$1.versions.node!=null,signWithApiKey=async fr=>isCryptoEnabledBrowser?(await __vitePreload(()=>import("./webcrypto-CJZUMDsH.js"),__vite__mapDeps([0,1])).then(wr=>wr.signWithApiKey))(fr):isNode?(await __vitePreload(()=>import("./nodecrypto-pMA0JG-7.js"),__vite__mapDeps([2,1])).then(wr=>wr.signWithApiKey))(fr):(await __vitePreload(()=>import("./purejs-B-VHXJWQ.js"),[]).then(wr=>wr.signWithApiKey))(fr);class ApiKeyStamper{constructor(br){this.apiPublicKey=br.apiPublicKey,this.apiPrivateKey=br.apiPrivateKey}async stamp(br){const wr=await signWithApiKey({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:br}),Er={publicKey:this.apiPublicKey,scheme:"SIGNATURE_SCHEME_TK_API_P256",signature:wr};return{stampHeaderName:stampHeaderName$2,stampHeaderValue:stringToBase64urlString(JSON.stringify(Er))}}}const base64UrlEncode=fr=>Buffer$2.from(fr).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),generateRandomBuffer=()=>{const fr=new Uint8Array(32);return crypto.getRandomValues(fr),fr.buffer},transportMap={AUTHENTICATOR_TRANSPORT_BLE:AuthenticatorTransportProtocol.Ble,AUTHENTICATOR_TRANSPORT_HYBRID:AuthenticatorTransportProtocol.Hybrid,AUTHENTICATOR_TRANSPORT_INTERNAL:AuthenticatorTransportProtocol.Internal,AUTHENTICATOR_TRANSPORT_NFC:AuthenticatorTransportProtocol.Nfc,AUTHENTICATOR_TRANSPORT_USB:AuthenticatorTransportProtocol.Usb},convertAttestationTransports=fr=>fr.map(br=>transportMap[br]),TURNKEY_API_BASE_URL="https://api.turnkey.com",TURNKEY_API_KEY_EXPIRY_MESSAGE="Turnkey error 16: expired api key",TURNKEY_API_KEY_NOT_FOUND_MESSAGE="Turnkey error 16: could not find public key",WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE="The operation either timed out or was not allowed",WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",INVALID_PASSKEY_SELECTED_ERROR_MESSAGE="Turnkey error 5: webauthn authenticator not found in organization or parent organization",USER_CANCELLED_REQUEST_ERROR_MESSAGE="The user cancelled the request",TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS=[TURNKEY_API_KEY_EXPIRY_MESSAGE,TURNKEY_API_KEY_NOT_FOUND_MESSAGE],TURNKEY_SDK_BENIGN_ERRORS=[WEBAUTHN_NOT_SUPPORTED_OR_CANCELLED_ERROR_MESSAGE,WEBAUTHN_NOT_SUPPORTED_OR_DISABLED_ERROR_MESSAGE,INVALID_PASSKEY_SELECTED_ERROR_MESSAGE,USER_CANCELLED_REQUEST_ERROR_MESSAGE];class DynamicEmbeddedWalletsLogger extends Logger$1{constructor(br,wr){super(br,wr)}error(br,...wr){const[Er]=wr;!(Er!=null&&Er.message)||!TURNKEY_SDK_BENIGN_ERRORS.some(kr=>Er.message.includes(kr))?(Logger$1.events.emit("error",br),this.log(LogLevel.ERROR,br,...wr)):this.warn(br,...wr)}}const logger$4=new DynamicEmbeddedWalletsLogger("Dynamic embedded wallets",LogLevel.INFO),stampHeaderName$1="X-Stamp";var IframeEventType;(function(fr){fr.PublicKeyReady="PUBLIC_KEY_READY",fr.InjectCredentialBundle="INJECT_CREDENTIAL_BUNDLE",fr.InjectKeyExportBundle="INJECT_KEY_EXPORT_BUNDLE",fr.InjectWalletExportBundle="INJECT_WALLET_EXPORT_BUNDLE",fr.InjectImportBundle="INJECT_IMPORT_BUNDLE",fr.ExtractWalletEncryptedBundle="EXTRACT_WALLET_ENCRYPTED_BUNDLE",fr.ExtractKeyEncryptedBundle="EXTRACT_KEY_ENCRYPTED_BUNDLE",fr.ApplySettings="APPLY_SETTINGS",fr.BundleInjected="BUNDLE_INJECTED",fr.EncryptedBundleExtracted="ENCRYPTED_BUNDLE_EXTRACTED",fr.SettingsApplied="SETTINGS_APPLIED",fr.StampRequest="STAMP_REQUEST",fr.Stamp="STAMP",fr.Error="ERROR"})(IframeEventType||(IframeEventType={}));var KeyFormat;(function(fr){fr.Hexadecimal="HEXADECIMAL",fr.Solana="SOLANA"})(KeyFormat||(KeyFormat={}));class IframeStamper{constructor(br){if(typeof window>"u")throw new Error("Cannot initialize iframe in non-browser environment");if(!br.iframeContainer)throw new Error("Iframe container cannot be found");if(this.container=br.iframeContainer,this.container.querySelector(`#${br.iframeElementId}`))throw new Error(`Iframe element with ID ${br.iframeElementId} already exists`);let wr=window.document.createElement("iframe");wr.setAttribute("sandbox","allow-scripts allow-same-origin"),wr.id=br.iframeElementId,wr.src=br.iframeUrl,this.iframe=wr;const Er=new URL(br.iframeUrl);this.iframeOrigin=Er.origin,this.iframePublicKey=null}async init(){return this.container.appendChild(this.iframe),new Promise((br,wr)=>{window.addEventListener("message",Er=>{var kr;Er.origin===this.iframeOrigin&&((kr=Er.data)==null?void 0:kr.type)===IframeEventType.PublicKeyReady&&(this.iframePublicKey=Er.data.value,br(Er.data.value))},!1)})}clear(){this.iframe.remove()}publicKey(){return this.iframePublicKey}async injectCredentialBundle(br){return new Promise((wr,Er)=>{var kr;(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectCredentialBundle,value:br},"*"),window.addEventListener("message",jr=>{var Br,qr;jr.origin===this.iframeOrigin&&(((Br=jr.data)==null?void 0:Br.type)===IframeEventType.BundleInjected&&wr(jr.data.value),((qr=jr.data)==null?void 0:qr.type)===IframeEventType.Error&&Er(jr.data.value))},!1)})}async injectKeyExportBundle(br,wr,Er){var kr;return(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectKeyExportBundle,value:br,keyFormat:Er,organizationId:wr},"*"),new Promise((jr,Br)=>{window.addEventListener("message",qr=>{var Wr,Vr;qr.origin===this.iframeOrigin&&(((Wr=qr.data)==null?void 0:Wr.type)===IframeEventType.BundleInjected&&jr(qr.data.value),((Vr=qr.data)==null?void 0:Vr.type)===IframeEventType.Error&&Br(qr.data.value))},!1)})}async injectWalletExportBundle(br,wr){var Er;return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.InjectWalletExportBundle,value:br,organizationId:wr},"*"),new Promise((kr,jr)=>{window.addEventListener("message",Br=>{var qr,Wr;Br.origin===this.iframeOrigin&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.BundleInjected&&kr(Br.data.value),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}async injectImportBundle(br,wr,Er){var kr;return(kr=this.iframe.contentWindow)==null||kr.postMessage({type:IframeEventType.InjectImportBundle,value:br,organizationId:wr,userId:Er},"*"),new Promise((jr,Br)=>{window.addEventListener("message",qr=>{var Wr,Vr;qr.origin===this.iframeOrigin&&(((Wr=qr.data)==null?void 0:Wr.type)===IframeEventType.BundleInjected&&jr(qr.data.value),((Vr=qr.data)==null?void 0:Vr.type)===IframeEventType.Error&&Br(qr.data.value))},!1)})}async extractWalletEncryptedBundle(){var br;return(br=this.iframe.contentWindow)==null||br.postMessage({type:IframeEventType.ExtractWalletEncryptedBundle},"*"),new Promise((wr,Er)=>{window.addEventListener("message",kr=>{var jr,Br;kr.origin===this.iframeOrigin&&(((jr=kr.data)==null?void 0:jr.type)===IframeEventType.EncryptedBundleExtracted&&wr(kr.data.value),((Br=kr.data)==null?void 0:Br.type)===IframeEventType.Error&&Er(kr.data.value))},!1)})}async extractKeyEncryptedBundle(br){var wr;return(wr=this.iframe.contentWindow)==null||wr.postMessage({type:IframeEventType.ExtractKeyEncryptedBundle,keyFormat:br},"*"),new Promise((Er,kr)=>{window.addEventListener("message",jr=>{var Br,qr;jr.origin===this.iframeOrigin&&(((Br=jr.data)==null?void 0:Br.type)===IframeEventType.EncryptedBundleExtracted&&Er(jr.data.value),((qr=jr.data)==null?void 0:qr.type)===IframeEventType.Error&&kr(jr.data.value))},!1)})}async applySettings(br){var Er;const wr=JSON.stringify(br);return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.ApplySettings,value:wr},"*"),new Promise((kr,jr)=>{window.addEventListener("message",Br=>{var qr,Wr;Br.origin===this.iframeOrigin&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.SettingsApplied&&kr(Br.data.value),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}async stamp(br){var Er;if(this.iframePublicKey===null)throw new Error("null iframe public key. Have you called/awaited .init()?");const wr=this.iframeOrigin;return(Er=this.iframe.contentWindow)==null||Er.postMessage({type:IframeEventType.StampRequest,value:br},"*"),new Promise(function(kr,jr){window.addEventListener("message",Br=>{var qr,Wr;Br.origin===wr&&(((qr=Br.data)==null?void 0:qr.type)===IframeEventType.Stamp&&kr({stampHeaderName:stampHeaderName$1,stampHeaderValue:Br.data.value}),((Wr=Br.data)==null?void 0:Wr.type)===IframeEventType.Error&&jr(Br.data.value))},!1)})}}var browserPonyfill={exports:{}};(function(fr,br){var wr=typeof self<"u"?self:commonjsGlobal,Er=function(){function jr(){this.fetch=!1,this.DOMException=wr.DOMException}return jr.prototype=wr,new jr}();(function(jr){(function(Br){var qr={searchParams:"URLSearchParams"in jr,iterable:"Symbol"in jr&&"iterator"in Symbol,blob:"FileReader"in jr&&"Blob"in jr&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in jr,arrayBuffer:"ArrayBuffer"in jr};function Wr(Gr){return Gr&&DataView.prototype.isPrototypeOf(Gr)}if(qr.arrayBuffer)var Vr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Hr=ArrayBuffer.isView||function(Gr){return Gr&&Vr.indexOf(Object.prototype.toString.call(Gr))>-1};function Zr(Gr){if(typeof Gr!="string"&&(Gr=String(Gr)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(Gr))throw new TypeError("Invalid character in header field name");return Gr.toLowerCase()}function Jr(Gr){return typeof Gr!="string"&&(Gr=String(Gr)),Gr}function Xr(Gr){var Yr={next:function(){var Sn=Gr.shift();return{done:Sn===void 0,value:Sn}}};return qr.iterable&&(Yr[Symbol.iterator]=function(){return Yr}),Yr}function En(Gr){this.map={},Gr instanceof En?Gr.forEach(function(Yr,Sn){this.append(Sn,Yr)},this):Array.isArray(Gr)?Gr.forEach(function(Yr){this.append(Yr[0],Yr[1])},this):Gr&&Object.getOwnPropertyNames(Gr).forEach(function(Yr){this.append(Yr,Gr[Yr])},this)}En.prototype.append=function(Gr,Yr){Gr=Zr(Gr),Yr=Jr(Yr);var Sn=this.map[Gr];this.map[Gr]=Sn?Sn+", "+Yr:Yr},En.prototype.delete=function(Gr){delete this.map[Zr(Gr)]},En.prototype.get=function(Gr){return Gr=Zr(Gr),this.has(Gr)?this.map[Gr]:null},En.prototype.has=function(Gr){return this.map.hasOwnProperty(Zr(Gr))},En.prototype.set=function(Gr,Yr){this.map[Zr(Gr)]=Jr(Yr)},En.prototype.forEach=function(Gr,Yr){for(var Sn in this.map)this.map.hasOwnProperty(Sn)&&Gr.call(Yr,this.map[Sn],Sn,this)},En.prototype.keys=function(){var Gr=[];return this.forEach(function(Yr,Sn){Gr.push(Sn)}),Xr(Gr)},En.prototype.values=function(){var Gr=[];return this.forEach(function(Yr){Gr.push(Yr)}),Xr(Gr)},En.prototype.entries=function(){var Gr=[];return this.forEach(function(Yr,Sn){Gr.push([Sn,Yr])}),Xr(Gr)},qr.iterable&&(En.prototype[Symbol.iterator]=En.prototype.entries);function wn(Gr){if(Gr.bodyUsed)return Promise.reject(new TypeError("Already read"));Gr.bodyUsed=!0}function $n(Gr){return new Promise(function(Yr,Sn){Gr.onload=function(){Yr(Gr.result)},Gr.onerror=function(){Sn(Gr.error)}})}function Tn(Gr){var Yr=new FileReader,Sn=$n(Yr);return Yr.readAsArrayBuffer(Gr),Sn}function In(Gr){var Yr=new FileReader,Sn=$n(Yr);return Yr.readAsText(Gr),Sn}function jn(Gr){for(var Yr=new Uint8Array(Gr),Sn=new Array(Yr.length),An=0;An-1?Yr:Gr}function ro(Gr,Yr){Yr=Yr||{};var Sn=Yr.body;if(Gr instanceof ro){if(Gr.bodyUsed)throw new TypeError("Already read");this.url=Gr.url,this.credentials=Gr.credentials,Yr.headers||(this.headers=new En(Gr.headers)),this.method=Gr.method,this.mode=Gr.mode,this.signal=Gr.signal,!Sn&&Gr._bodyInit!=null&&(Sn=Gr._bodyInit,Gr.bodyUsed=!0)}else this.url=String(Gr);if(this.credentials=Yr.credentials||this.credentials||"same-origin",(Yr.headers||!this.headers)&&(this.headers=new En(Yr.headers)),this.method=_i(Yr.method||this.method||"GET"),this.mode=Yr.mode||this.mode||null,this.signal=Yr.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&Sn)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(Sn)}ro.prototype.clone=function(){return new ro(this,{body:this._bodyInit})};function to(Gr){var Yr=new FormData;return Gr.trim().split("&").forEach(function(Sn){if(Sn){var An=Sn.split("="),Pn=An.shift().replace(/\+/g," "),Nn=An.join("=").replace(/\+/g," ");Yr.append(decodeURIComponent(Pn),decodeURIComponent(Nn))}}),Yr}function io(Gr){var Yr=new En,Sn=Gr.replace(/\r?\n[\t ]+/g," ");return Sn.split(/\r?\n/).forEach(function(An){var Pn=An.split(":"),Nn=Pn.shift().trim();if(Nn){var zn=Pn.join(":").trim();Yr.append(Nn,zn)}}),Yr}ga.call(ro.prototype);function no(Gr,Yr){Yr||(Yr={}),this.type="default",this.status=Yr.status===void 0?200:Yr.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in Yr?Yr.statusText:"OK",this.headers=new En(Yr.headers),this.url=Yr.url||"",this._initBody(Gr)}ga.call(no.prototype),no.prototype.clone=function(){return new no(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new En(this.headers),url:this.url})},no.error=function(){var Gr=new no(null,{status:0,statusText:""});return Gr.type="error",Gr};var $a=[301,302,303,307,308];no.redirect=function(Gr,Yr){if($a.indexOf(Yr)===-1)throw new RangeError("Invalid status code");return new no(null,{status:Yr,headers:{location:Gr}})},Br.DOMException=jr.DOMException;try{new Br.DOMException}catch{Br.DOMException=function(Yr,Sn){this.message=Yr,this.name=Sn;var An=Error(Yr);this.stack=An.stack},Br.DOMException.prototype=Object.create(Error.prototype),Br.DOMException.prototype.constructor=Br.DOMException}function Rn(Gr,Yr){return new Promise(function(Sn,An){var Pn=new ro(Gr,Yr);if(Pn.signal&&Pn.signal.aborted)return An(new Br.DOMException("Aborted","AbortError"));var Nn=new XMLHttpRequest;function zn(){Nn.abort()}Nn.onload=function(){var On={status:Nn.status,statusText:Nn.statusText,headers:io(Nn.getAllResponseHeaders()||"")};On.url="responseURL"in Nn?Nn.responseURL:On.headers.get("X-Request-URL");var _n="response"in Nn?Nn.response:Nn.responseText;Sn(new no(_n,On))},Nn.onerror=function(){An(new TypeError("Network request failed"))},Nn.ontimeout=function(){An(new TypeError("Network request failed"))},Nn.onabort=function(){An(new Br.DOMException("Aborted","AbortError"))},Nn.open(Pn.method,Pn.url,!0),Pn.credentials==="include"?Nn.withCredentials=!0:Pn.credentials==="omit"&&(Nn.withCredentials=!1),"responseType"in Nn&&qr.blob&&(Nn.responseType="blob"),Pn.headers.forEach(function(On,_n){Nn.setRequestHeader(_n,On)}),Pn.signal&&(Pn.signal.addEventListener("abort",zn),Nn.onreadystatechange=function(){Nn.readyState===4&&Pn.signal.removeEventListener("abort",zn)}),Nn.send(typeof Pn._bodyInit>"u"?null:Pn._bodyInit)})}return Rn.polyfill=!0,jr.fetch||(jr.fetch=Rn,jr.Headers=En,jr.Request=ro,jr.Response=no),Br.Headers=En,Br.Request=ro,Br.Response=no,Br.fetch=Rn,Object.defineProperty(Br,"__esModule",{value:!0}),Br})({})})(Er),Er.fetch.ponyfill=!0,delete Er.fetch.polyfill;var kr=Er;br=kr.fetch,br.default=kr.fetch,br.fetch=kr.fetch,br.Headers=kr.Headers,br.Request=kr.Request,br.Response=kr.Response,fr.exports=br})(browserPonyfill,browserPonyfill.exports);var browserPonyfillExports=browserPonyfill.exports;const o$2=getDefaultExportFromCjs$2(browserPonyfillExports),fetch$1=browserPonyfillExports.fetch;class TurnkeyRequestError extends Error{constructor(br){let wr=`Turnkey error ${br.code}: ${br.message}`;br.details!=null&&(wr+=` (Details: ${JSON.stringify(br.details)})`),super(wr),this.name="TurnkeyRequestError",this.details=br.details??null,this.code=br.code}}const VERSION$1="@turnkey/http@2.12.2";class TurnkeyClient{constructor(br,wr){if(this.getActivity=async Er=>this.request("/public/v1/query/get_activity",Er),this.stampGetActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getApiKey=async Er=>this.request("/public/v1/query/get_api_key",Er),this.stampGetApiKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_api_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getApiKeys=async Er=>this.request("/public/v1/query/get_api_keys",Er),this.stampGetApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAttestationDocument=async Er=>this.request("/public/v1/query/get_attestation",Er),this.stampGetAttestationDocument=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_attestation",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAuthenticator=async Er=>this.request("/public/v1/query/get_authenticator",Er),this.stampGetAuthenticator=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_authenticator",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getAuthenticators=async Er=>this.request("/public/v1/query/get_authenticators",Er),this.stampGetAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOauthProviders=async Er=>this.request("/public/v1/query/get_oauth_providers",Er),this.stampGetOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOrganization=async Er=>this.request("/public/v1/query/get_organization",Er),this.stampGetOrganization=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_organization",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getOrganizationConfigs=async Er=>this.request("/public/v1/query/get_organization_configs",Er),this.stampGetOrganizationConfigs=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_organization_configs",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPolicy=async Er=>this.request("/public/v1/query/get_policy",Er),this.stampGetPolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPrivateKey=async Er=>this.request("/public/v1/query/get_private_key",Er),this.stampGetPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getUser=async Er=>this.request("/public/v1/query/get_user",Er),this.stampGetUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWallet=async Er=>this.request("/public/v1/query/get_wallet",Er),this.stampGetWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/get_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getActivities=async Er=>this.request("/public/v1/query/list_activities",Er),this.stampGetActivities=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_activities",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPolicies=async Er=>this.request("/public/v1/query/list_policies",Er),this.stampGetPolicies=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_policies",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.listPrivateKeyTags=async Er=>this.request("/public/v1/query/list_private_key_tags",Er),this.stampListPrivateKeyTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_private_key_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getPrivateKeys=async Er=>this.request("/public/v1/query/list_private_keys",Er),this.stampGetPrivateKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_private_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getSubOrgIds=async Er=>this.request("/public/v1/query/list_suborgs",Er),this.stampGetSubOrgIds=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_suborgs",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.listUserTags=async Er=>this.request("/public/v1/query/list_user_tags",Er),this.stampListUserTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_user_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getUsers=async Er=>this.request("/public/v1/query/list_users",Er),this.stampGetUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWalletAccounts=async Er=>this.request("/public/v1/query/list_wallet_accounts",Er),this.stampGetWalletAccounts=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_wallet_accounts",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWallets=async Er=>this.request("/public/v1/query/list_wallets",Er),this.stampGetWallets=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/list_wallets",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.getWhoami=async Er=>this.request("/public/v1/query/whoami",Er),this.stampGetWhoami=async Er=>{const kr=this.config.baseUrl+"/public/v1/query/whoami",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.approveActivity=async Er=>this.request("/public/v1/submit/approve_activity",Er),this.stampApproveActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/approve_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createApiKeys=async Er=>this.request("/public/v1/submit/create_api_keys",Er),this.stampCreateApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createApiOnlyUsers=async Er=>this.request("/public/v1/submit/create_api_only_users",Er),this.stampCreateApiOnlyUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_api_only_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createAuthenticators=async Er=>this.request("/public/v1/submit/create_authenticators",Er),this.stampCreateAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createInvitations=async Er=>this.request("/public/v1/submit/create_invitations",Er),this.stampCreateInvitations=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_invitations",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createOauthProviders=async Er=>this.request("/public/v1/submit/create_oauth_providers",Er),this.stampCreateOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPolicies=async Er=>this.request("/public/v1/submit/create_policies",Er),this.stampCreatePolicies=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_policies",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPolicy=async Er=>this.request("/public/v1/submit/create_policy",Er),this.stampCreatePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPrivateKeyTag=async Er=>this.request("/public/v1/submit/create_private_key_tag",Er),this.stampCreatePrivateKeyTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_private_key_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createPrivateKeys=async Er=>this.request("/public/v1/submit/create_private_keys",Er),this.stampCreatePrivateKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_private_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createReadOnlySession=async Er=>this.request("/public/v1/submit/create_read_only_session",Er),this.stampCreateReadOnlySession=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_read_only_session",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createReadWriteSession=async Er=>this.request("/public/v1/submit/create_read_write_session",Er),this.stampCreateReadWriteSession=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_read_write_session",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createSubOrganization=async Er=>this.request("/public/v1/submit/create_sub_organization",Er),this.stampCreateSubOrganization=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_sub_organization",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createUserTag=async Er=>this.request("/public/v1/submit/create_user_tag",Er),this.stampCreateUserTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_user_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createUsers=async Er=>this.request("/public/v1/submit/create_users",Er),this.stampCreateUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createWallet=async Er=>this.request("/public/v1/submit/create_wallet",Er),this.stampCreateWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.createWalletAccounts=async Er=>this.request("/public/v1/submit/create_wallet_accounts",Er),this.stampCreateWalletAccounts=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/create_wallet_accounts",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteApiKeys=async Er=>this.request("/public/v1/submit/delete_api_keys",Er),this.stampDeleteApiKeys=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_api_keys",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteAuthenticators=async Er=>this.request("/public/v1/submit/delete_authenticators",Er),this.stampDeleteAuthenticators=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_authenticators",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteInvitation=async Er=>this.request("/public/v1/submit/delete_invitation",Er),this.stampDeleteInvitation=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_invitation",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteOauthProviders=async Er=>this.request("/public/v1/submit/delete_oauth_providers",Er),this.stampDeleteOauthProviders=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_oauth_providers",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deletePolicy=async Er=>this.request("/public/v1/submit/delete_policy",Er),this.stampDeletePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deletePrivateKeyTags=async Er=>this.request("/public/v1/submit/delete_private_key_tags",Er),this.stampDeletePrivateKeyTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_private_key_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteUserTags=async Er=>this.request("/public/v1/submit/delete_user_tags",Er),this.stampDeleteUserTags=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_user_tags",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.deleteUsers=async Er=>this.request("/public/v1/submit/delete_users",Er),this.stampDeleteUsers=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/delete_users",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.emailAuth=async Er=>this.request("/public/v1/submit/email_auth",Er),this.stampEmailAuth=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/email_auth",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportPrivateKey=async Er=>this.request("/public/v1/submit/export_private_key",Er),this.stampExportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportWallet=async Er=>this.request("/public/v1/submit/export_wallet",Er),this.stampExportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.exportWalletAccount=async Er=>this.request("/public/v1/submit/export_wallet_account",Er),this.stampExportWalletAccount=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/export_wallet_account",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.importPrivateKey=async Er=>this.request("/public/v1/submit/import_private_key",Er),this.stampImportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/import_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.importWallet=async Er=>this.request("/public/v1/submit/import_wallet",Er),this.stampImportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/import_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initImportPrivateKey=async Er=>this.request("/public/v1/submit/init_import_private_key",Er),this.stampInitImportPrivateKey=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_import_private_key",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initImportWallet=async Er=>this.request("/public/v1/submit/init_import_wallet",Er),this.stampInitImportWallet=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_import_wallet",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.initUserEmailRecovery=async Er=>this.request("/public/v1/submit/init_user_email_recovery",Er),this.stampInitUserEmailRecovery=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/init_user_email_recovery",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.oauth=async Er=>this.request("/public/v1/submit/oauth",Er),this.stampOauth=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/oauth",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.recoverUser=async Er=>this.request("/public/v1/submit/recover_user",Er),this.stampRecoverUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/recover_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.rejectActivity=async Er=>this.request("/public/v1/submit/reject_activity",Er),this.stampRejectActivity=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/reject_activity",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.removeOrganizationFeature=async Er=>this.request("/public/v1/submit/remove_organization_feature",Er),this.stampRemoveOrganizationFeature=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/remove_organization_feature",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.setOrganizationFeature=async Er=>this.request("/public/v1/submit/set_organization_feature",Er),this.stampSetOrganizationFeature=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/set_organization_feature",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signRawPayload=async Er=>this.request("/public/v1/submit/sign_raw_payload",Er),this.stampSignRawPayload=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_raw_payload",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signRawPayloads=async Er=>this.request("/public/v1/submit/sign_raw_payloads",Er),this.stampSignRawPayloads=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_raw_payloads",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.signTransaction=async Er=>this.request("/public/v1/submit/sign_transaction",Er),this.stampSignTransaction=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/sign_transaction",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updatePolicy=async Er=>this.request("/public/v1/submit/update_policy",Er),this.stampUpdatePolicy=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_policy",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updatePrivateKeyTag=async Er=>this.request("/public/v1/submit/update_private_key_tag",Er),this.stampUpdatePrivateKeyTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_private_key_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateRootQuorum=async Er=>this.request("/public/v1/submit/update_root_quorum",Er),this.stampUpdateRootQuorum=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_root_quorum",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateUser=async Er=>this.request("/public/v1/submit/update_user",Er),this.stampUpdateUser=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_user",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},this.updateUserTag=async Er=>this.request("/public/v1/submit/update_user_tag",Er),this.stampUpdateUserTag=async Er=>{const kr=this.config.baseUrl+"/public/v1/submit/update_user_tag",jr=JSON.stringify(Er),Br=await this.stamper.stamp(jr);return{body:jr,stamp:Br,url:kr}},!br.baseUrl)throw new Error("Missing base URL. Please verify env vars.");this.config=br,this.stamper=wr}async request(br,wr){const Er=this.config.baseUrl+br,kr=JSON.stringify(wr),jr=await this.stamper.stamp(kr),Br=await fetch$1(Er,{method:"POST",headers:{[jr.stampHeaderName]:jr.stampHeaderValue,"X-Client-Version":VERSION$1},body:kr,redirect:"follow"});if(!Br.ok){let Wr;try{Wr=await Br.json()}catch{throw new Error(`${Br.status} ${Br.statusText}`)}throw new TurnkeyRequestError(Wr)}return await Br.json()}}class TurnkeyActivityError extends Error{constructor(br){const{message:wr,cause:Er,activityId:kr,activityStatus:jr,activityType:Br}=br;super(wr),this.name="TurnkeyActivityError",this.activityId=kr??null,this.activityStatus=jr??null,this.activityType=Br??null,this.cause=Er??null}}function bufferToBase64url(fr){const br=new Uint8Array(fr);let wr="";for(const jr of br)wr+=String.fromCharCode(jr);return btoa(wr).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}const copyValue="copy",convertValue="convert";function convert$1(fr,br,wr){if(br===copyValue)return wr;if(br===convertValue)return fr(wr);if(br instanceof Array)return wr.map(Er=>convert$1(fr,br[0],Er));if(br instanceof Object){const Er={};for(const[kr,jr]of Object.entries(br)){if(jr.derive){const Br=jr.derive(wr);Br!==void 0&&(wr[kr]=Br)}if(!(kr in wr)){if(jr.required)throw new Error(`Missing key: ${kr}`);continue}if(wr[kr]==null){Er[kr]=null;continue}Er[kr]=convert$1(fr,jr.schema,wr[kr])}return Er}}function derived(fr,br){return{required:!0,schema:fr,derive:br}}function required(fr){return{required:!0,schema:fr}}function optional$3(fr){return{required:!1,schema:fr}}const simplifiedClientExtensionResultsSchema={appid:optional$3(copyValue),appidExclude:optional$3(copyValue),credProps:optional$3(copyValue)},publicKeyCredentialWithAssertion={type:required(copyValue),id:required(copyValue),rawId:required(convertValue),authenticatorAttachment:optional$3(copyValue),response:required({clientDataJSON:required(convertValue),authenticatorData:required(convertValue),signature:required(convertValue),userHandle:required(convertValue)}),clientExtensionResults:derived(simplifiedClientExtensionResultsSchema,fr=>fr.getClientExtensionResults())};function getResponseToJSON(fr){return convert$1(bufferToBase64url,publicKeyCredentialWithAssertion,fr)}async function get$2(fr){const br=await navigator.credentials.get(fr);return br.toJSON=()=>getResponseToJSON(br),br}const K$2=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998];function createHash(fr){return new Hash}class Hash{constructor(){this.A=1779033703,this.B=-1150833019,this.C=1013904242,this.D=-1521486534,this.E=1359893119,this.F=-1694144372,this.G=528734635,this.H=1541459225,this._size=0,this._sp=0,(!sharedBuffer||sharedOffset>=8e3)&&(sharedBuffer=new ArrayBuffer(8e3),sharedOffset=0),this._byte=new Uint8Array(sharedBuffer,sharedOffset,80),this._word=new Int32Array(sharedBuffer,sharedOffset,20),sharedOffset+=80}update(br){if(typeof br=="string")return this._utf8(br);if(br==null)throw new TypeError("Invalid type: "+typeof br);const wr=br.byteOffset,Er=br.byteLength;let kr=Er/64|0,jr=0;if(kr&&!(wr&3)&&!(this._size%64)){const qr=new Int32Array(br.buffer,wr,kr*16);for(;kr--;)this._int32(qr,jr>>2),jr+=64;this._size+=jr}if(br.BYTES_PER_ELEMENT!==1&&br.buffer){const qr=new Uint8Array(br.buffer,wr+jr,Er-jr);return this._uint8(qr)}return jr===Er?this:this._uint8(br,jr)}_uint8(br,wr){const{_byte:Er,_word:kr}=this,jr=br.length;for(wr=wr|0;wr=64&&this._int32(kr),this._size+=qr-Br}return this}_utf8(br){const{_byte:wr,_word:Er}=this,kr=br.length;let jr=this._sp;for(let Br=0;Br>>6,wr[Wr++]=128|Vr&63):Vr<55296||Vr>57343?(wr[Wr++]=224|Vr>>>12,wr[Wr++]=128|Vr>>>6&63,wr[Wr++]=128|Vr&63):jr?(Vr=((jr&1023)<<10)+(Vr&1023)+65536,wr[Wr++]=240|Vr>>>18,wr[Wr++]=128|Vr>>>12&63,wr[Wr++]=128|Vr>>>6&63,wr[Wr++]=128|Vr&63,jr=0):jr=Vr}Wr>=64&&(this._int32(Er),Er[0]=Er[16]),this._size+=Wr-qr}return this._sp=jr,this}_int32(br,wr){let{A:Er,B:kr,C:jr,D:Br,E:qr,F:Wr,G:Vr,H:Hr}=this,Zr=0;for(wr=wr|0;Zr<16;)W$1[Zr++]=swap32(br[wr++]);for(Zr=16;Zr<64;Zr++)W$1[Zr]=gamma1(W$1[Zr-2])+W$1[Zr-7]+gamma0(W$1[Zr-15])+W$1[Zr-16]|0;for(Zr=0;Zr<64;Zr++){const Jr=Hr+sigma1(qr)+ch(qr,Wr,Vr)+K$2[Zr]+W$1[Zr]|0,Xr=sigma0(Er)+maj(Er,kr,jr)|0;Hr=Vr,Vr=Wr,Wr=qr,qr=Br+Jr|0,Br=jr,jr=kr,kr=Er,Er=Jr+Xr|0}this.A=Er+this.A|0,this.B=kr+this.B|0,this.C=jr+this.C|0,this.D=Br+this.D|0,this.E=qr+this.E|0,this.F=Wr+this.F|0,this.G=Vr+this.G|0,this.H=Hr+this.H|0}digest(br){const{_byte:wr,_word:Er}=this;let kr=this._size%64|0;for(wr[kr++]=128;kr&3;)wr[kr++]=0;if(kr>>=2,kr>14){for(;kr<16;)Er[kr++]=0;kr=0,this._int32(Er)}for(;kr<16;)Er[kr++]=0;const jr=this._size*8,Br=(jr&4294967295)>>>0,qr=(jr-Br)/4294967296;return qr&&(Er[14]=swap32(qr)),Br&&(Er[15]=swap32(Br)),this._int32(Er),br==="hex"?this._hex():this._bin()}_hex(){const{A:br,B:wr,C:Er,D:kr,E:jr,F:Br,G:qr,H:Wr}=this;return hex32(br)+hex32(wr)+hex32(Er)+hex32(kr)+hex32(jr)+hex32(Br)+hex32(qr)+hex32(Wr)}_bin(){const{A:br,B:wr,C:Er,D:kr,E:jr,F:Br,G:qr,H:Wr,_byte:Vr,_word:Hr}=this;return Hr[0]=swap32(br),Hr[1]=swap32(wr),Hr[2]=swap32(Er),Hr[3]=swap32(kr),Hr[4]=swap32(jr),Hr[5]=swap32(Br),Hr[6]=swap32(qr),Hr[7]=swap32(Wr),Vr.slice(0,32)}}const W$1=new Int32Array(64);let sharedBuffer,sharedOffset=0;const hex32=fr=>(fr+4294967296).toString(16).substr(-8),swapLE=fr=>fr<<24&4278190080|fr<<8&16711680|fr>>8&65280|fr>>24&255,swapBE=fr=>fr,swap32=isBE()?swapBE:swapLE,ch=(fr,br,wr)=>wr^fr&(br^wr),maj=(fr,br,wr)=>fr&br|wr&(fr|br),sigma0=fr=>(fr>>>2|fr<<30)^(fr>>>13|fr<<19)^(fr>>>22|fr<<10),sigma1=fr=>(fr>>>6|fr<<26)^(fr>>>11|fr<<21)^(fr>>>25|fr<<7),gamma0=fr=>(fr>>>7|fr<<25)^(fr>>>18|fr<<14)^fr>>>3,gamma1=fr=>(fr>>>17|fr<<15)^(fr>>>19|fr<<13)^fr>>>10;function isBE(){return new Uint8Array(new Uint16Array([65279]).buffer)[0]===254}const stampHeaderName="X-Stamp-Webauthn",defaultTimeout=5*60*1e3,defaultUserVerification="preferred";class WebauthnStamper{constructor(br){this.rpId=br.rpId,this.timeout=br.timeout||defaultTimeout,this.userVerification=br.userVerification||defaultUserVerification,this.allowCredentials=br.allowCredentials||[]}async stamp(br){const wr=getChallengeFromPayload(br),Er={publicKey:{rpId:this.rpId,challenge:wr,allowCredentials:this.allowCredentials,timeout:this.timeout,userVerification:this.userVerification}},jr=(await get$2(Er)).toJSON(),Br={authenticatorData:jr.response.authenticatorData,clientDataJson:jr.response.clientDataJSON,credentialId:jr.id,signature:jr.response.signature};return{stampHeaderName,stampHeaderValue:JSON.stringify(Br)}}}function getChallengeFromPayload(fr){const br=createHash().update(fr).digest("hex");return new TextEncoder().encode(br)}var version$b="3.8.2";class WebauthnNotSupportedError extends Error{constructor(){super("Webauthn is not supported on this device")}}function __awaiter$b(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;function utf8StringToBuffer(fr){return new TextEncoder().encode(fr)}function bufferToBase64URLString(fr){const br=new Uint8Array(fr);let wr="";for(const kr of br)wr+=String.fromCharCode(kr);return btoa(wr).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function base64URLStringToBuffer(fr){const br=fr.replace(/-/g,"+").replace(/_/g,"/"),wr=(4-br.length%4)%4,Er=br.padEnd(br.length+wr,"="),kr=atob(Er),jr=new ArrayBuffer(kr.length),Br=new Uint8Array(jr);for(let qr=0;qrBr.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:fr}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:fr});if(fr.name==="SecurityError"){const jr=window.location.hostname;if(isValidDomain(jr)){if(wr.rp.id!==jr)return new WebAuthnError({message:`The RP ID "${wr.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:fr})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:fr})}else if(fr.name==="TypeError"){if(wr.user.id.byteLength<1||wr.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:fr})}else if(fr.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:fr})}return fr}class BaseWebAuthnAbortService{createNewAbortSignal(){if(this.controller){const wr=new Error("Cancelling existing WebAuthn API call for new one");wr.name="AbortError",this.controller.abort(wr)}const br=new AbortController;return this.controller=br,br.signal}cancelCeremony(){if(this.controller){const br=new Error("Manually cancelling existing WebAuthn API call");br.name="AbortError",this.controller.abort(br),this.controller=void 0}}}const WebAuthnAbortService=new BaseWebAuthnAbortService,attachments=["cross-platform","platform"];function toAuthenticatorAttachment(fr){if(fr&&!(attachments.indexOf(fr)<0))return fr}async function startRegistration(fr){var Jr;if(!browserSupportsWebAuthn())throw new Error("WebAuthn is not supported in this browser");const wr={publicKey:{...fr,challenge:base64URLStringToBuffer(fr.challenge),user:{...fr.user,id:utf8StringToBuffer(fr.user.id)},excludeCredentials:(Jr=fr.excludeCredentials)==null?void 0:Jr.map(toPublicKeyCredentialDescriptor)}};wr.signal=WebAuthnAbortService.createNewAbortSignal();let Er;try{Er=await navigator.credentials.create(wr)}catch(Xr){throw identifyRegistrationError({error:Xr,options:wr})}if(!Er)throw new Error("Registration was not completed");const{id:kr,rawId:jr,response:Br,type:qr}=Er;let Wr;typeof Br.getTransports=="function"&&(Wr=Br.getTransports());let Vr;if(typeof Br.getPublicKeyAlgorithm=="function")try{Vr=Br.getPublicKeyAlgorithm()}catch(Xr){warnOnBrokenImplementation("getPublicKeyAlgorithm()",Xr)}let Hr;if(typeof Br.getPublicKey=="function")try{const Xr=Br.getPublicKey();Xr!==null&&(Hr=bufferToBase64URLString(Xr))}catch(Xr){warnOnBrokenImplementation("getPublicKey()",Xr)}let Zr;if(typeof Br.getAuthenticatorData=="function")try{Zr=bufferToBase64URLString(Br.getAuthenticatorData())}catch(Xr){warnOnBrokenImplementation("getAuthenticatorData()",Xr)}return{id:kr,rawId:bufferToBase64URLString(jr),response:{attestationObject:bufferToBase64URLString(Br.attestationObject),clientDataJSON:bufferToBase64URLString(Br.clientDataJSON),transports:Wr,publicKeyAlgorithm:Vr,publicKey:Hr,authenticatorData:Zr},type:qr,clientExtensionResults:Er.getClientExtensionResults(),authenticatorAttachment:toAuthenticatorAttachment(Er.authenticatorAttachment)}}function warnOnBrokenImplementation(fr,br){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${fr}. You should report this error to them. `,br)}const logger$3=new Logger$1("Webauthn"),createWebauthnCredential=fr=>__awaiter$b(void 0,void 0,void 0,function*(){if(!browserSupportsWebAuthn())throw new WebauthnNotSupportedError;let br;try{br=yield startRegistration(fr)}catch(wr){throw logger$3.debug("Failed to create webauthn credential",wr),wr}return br}),convertTransportEnumToTurnkeyEnum=fr=>{switch(fr){case"internal":return"AUTHENTICATOR_TRANSPORT_INTERNAL";case"usb":return"AUTHENTICATOR_TRANSPORT_USB";case"nfc":return"AUTHENTICATOR_TRANSPORT_NFC";case"ble":return"AUTHENTICATOR_TRANSPORT_BLE";case"hybrid":return"AUTHENTICATOR_TRANSPORT_HYBRID";default:throw new Error("unsupported transport format "+fr)}},getWebAuthnAttestationTurnkeyAdapter=fr=>__awaiter$b(void 0,void 0,void 0,function*(){var br,wr;if(!fr.publicKey)throw new Error("Invalid options. Public key attribute must be defined");const Er=Object.assign(Object.assign({},fr.publicKey),{challenge:bufferSourceToString(fr.publicKey.challenge),excludeCredentials:(br=fr.publicKey.excludeCredentials)===null||br===void 0?void 0:br.map(jr=>Object.assign(Object.assign({},jr),{id:bufferSourceToString(jr.id)})),user:Object.assign(Object.assign({},fr.publicKey.user),{id:bufferSourceToString(fr.publicKey.user.id)})}),kr=yield createWebauthnCredential(Er);return{attestationObject:kr.response.attestationObject,clientDataJson:kr.response.clientDataJSON,credentialId:kr.rawId,transports:((wr=kr.response.transports)===null||wr===void 0?void 0:wr.map(convertTransportEnumToTurnkeyEnum))||[]}}),bufferSourceToString=fr=>{if(fr instanceof ArrayBuffer)return bufferToBase64URLString(fr);{const br=new Uint8Array(fr.buffer,fr.byteOffset,fr.byteLength);return bufferToBase64URLString(br)}};assertPackageVersion("@dynamic-labs/webauthn",version$b);const createTurnkeyPasskeyService=()=>({createWebauthnStamper:fr=>new WebauthnStamper(fr),getWebAuthnAttestation:getWebAuthnAttestationTurnkeyAdapter});var _a,_PasskeyService_implementation;class PasskeyService{static get implementation(){return __classPrivateFieldGet$4(_a,_a,"f",_PasskeyService_implementation)?__classPrivateFieldGet$4(_a,_a,"f",_PasskeyService_implementation):createTurnkeyPasskeyService()}static set implementation(br){__classPrivateFieldSet$4(_a,_a,br,"f",_PasskeyService_implementation)}static get getWebAuthnAttestation(){return _a.implementation.getWebAuthnAttestation}static get createWebauthnStamper(){return _a.implementation.createWebauthnStamper}}_a=PasskeyService;_PasskeyService_implementation={value:void 0};const turnkeyBaseUrl$1="https://api.turnkey.com",turnkeyPasskeyRecoveryUrl="https://recovery.turnkey.com",turnkeyEmailRecoveryUrl="https://auth.turnkey.com",TURNKEY_RECOVERY_CREDENTIAL_EXPIRATION_SECONDS=900,TURNKEY_SESSION_EXPIRATION_SECONDS=1800,EMAIL_AUTH_CREDENTIAL_TYPE="CREDENTIAL_TYPE_API_KEY_P256",PASSKEY_RECOVERY_CREDENTIAL_TYPE="CREDENTIAL_TYPE_RECOVER_USER_KEY_P256";class TurnkeyAuthenticatorRecoveryHandler{constructor(){this.isSessionActive=()=>!this.__createdAt||this.__recoveryType!=="email"?!1:this.isExpired(this.__createdAt,this.__sessionExpiration||TURNKEY_SESSION_EXPIRATION_SECONDS)?(this.clear(),!1):!0,this.isValidCode=br=>__awaiter$c(this,void 0,void 0,function*(){var wr,Er,kr,jr;if(!br||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");const Br=yield(wr=this.__client)===null||wr===void 0?void 0:wr.getUser({organizationId:br,userId:this.__turnkeyRecoveryUserId}),qr={email:EMAIL_AUTH_CREDENTIAL_TYPE,passkey:PASSKEY_RECOVERY_CREDENTIAL_TYPE},Wr=(jr=(kr=(Er=Br==null?void 0:Br.user)===null||Er===void 0?void 0:Er.apiKeys)===null||kr===void 0?void 0:kr.filter(Hr=>Hr.credential.type===qr[this.__recoveryType]))===null||jr===void 0?void 0:jr.pop();return!Wr||this.isExpired(parseInt(Wr.createdAt.seconds,10),TURNKEY_RECOVERY_CREDENTIAL_EXPIRATION_SECONDS)?!1:(this.__createdAt=parseInt(Wr.createdAt.seconds,10),!0)}),this.isExpired=(br,wr)=>{const Er=br+wr,kr=new Date(Er*1e3);return new Date>=kr}}get publicKey(){return this.__publicKey}get client(){return this.__client}get recoveryType(){return this.__recoveryType}get recoveryUserId(){return this.__turnkeyRecoveryUserId||""}set recoveryUserId(br){this.__turnkeyRecoveryUserId=br}clear(){var br;(br=this.__iframeStamper)===null||br===void 0||br.clear(),this.__recoveryType=void 0,this.__iframeStamper=void 0,this.__publicKey=void 0,this.__client=void 0,this.__turnkeyRecoveryUserId=void 0,this.__createdAt=void 0}initRecovery(br,wr,Er,kr){return __awaiter$c(this,void 0,void 0,function*(){this.__recoveryType&&this.clear(),this.__sessionExpiration=kr,this.__recoveryType=br;const jr=br==="passkey"?turnkeyPasskeyRecoveryUrl:turnkeyEmailRecoveryUrl;return this.__iframeStamper=new IframeStamper({iframeContainer:wr,iframeElementId:Er,iframeUrl:jr}),yield this.__iframeStamper.init(),this.__publicKey=this.__iframeStamper.publicKey(),this.__publicKey})}verifyRecoveryCode(br,wr){return __awaiter$c(this,void 0,void 0,function*(){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");try{if(yield this.__iframeStamper.injectCredentialBundle(br),this.__client=new TurnkeyClient({baseUrl:turnkeyBaseUrl$1},this.__iframeStamper),!wr||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");if(!(yield this.isValidCode(wr)))throw new DynamicError("The code is invalid or expired.")}catch(Er){throw logger$4.error("Error while verifying recovery code",Er),Er instanceof DynamicError?Er:new DynamicError("The code is invalid or expired.")}})}completeRecovery(br){return __awaiter$c(this,arguments,void 0,function*({attestation:wr,challenge:Er,turnkeySubOrganizationId:kr}){if(!this.__client||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");try{return this.__client.recoverUser({organizationId:kr,parameters:{authenticator:{attestation:wr,authenticatorName:"Passkey",challenge:Er},userId:this.__turnkeyRecoveryUserId},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_RECOVER_USER"})}catch(jr){throw logger$4.error("[TK] Error while completing recovery process",jr),jr}})}addPasskeyAuthenticator(br){return __awaiter$c(this,arguments,void 0,function*({attestation:wr,challenge:Er,turnkeySubOrganizationId:kr}){if(!this.__client||!this.__turnkeyRecoveryUserId)throw new DynamicError("Cannot proceed with your request");try{return this.__client.createAuthenticators({organizationId:kr,parameters:{authenticators:[{attestation:wr,authenticatorName:"Passkey",challenge:Er}],userId:this.__turnkeyRecoveryUserId},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2"})}catch(jr){throw logger$4.error("[TK] Error while creating new authenticator",jr),jr}})}addEmailRecovery(br){return __awaiter$c(this,arguments,void 0,function*({organizationId:wr,email:Er,turnkeyUserId:kr}){let jr=getTLD();jr||(jr=PlatformService.getHostname());const Br=PasskeyService.createWebauthnStamper({rpId:jr}),qr=new TurnkeyClient({baseUrl:turnkeyBaseUrl$1},Br);try{return{signedRequest:yield qr.stampUpdateUser({organizationId:wr,parameters:{userEmail:Er,userId:kr,userTagIds:[]},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_UPDATE_USER"}),userId:kr}}catch(Wr){throw logger$4.error("Error while adding email recovery",Wr),Wr}})}}const turnkeyAuthenticatorRecoveryHandler=new TurnkeyAuthenticatorRecoveryHandler,turnkeyBaseUrl="https://api.turnkey.com",turnkeyExportUrl="https://export.turnkey.com";class ExportHandler{get publicKey(){return this.__publicKey}clear(){var br;(br=this.__iframeStamper)===null||br===void 0||br.clear(),this.__iframeStamper=void 0,this.__publicKey=void 0,this.__turnkeyClient=void 0}initExport(br,wr){return __awaiter$c(this,void 0,void 0,function*(){if(this.__iframeStamper=new IframeStamper({iframeContainer:br,iframeElementId:wr,iframeUrl:turnkeyExportUrl}),yield this.__iframeStamper.init(),this.__publicKey=this.__iframeStamper.publicKey(),turnkeyAuthenticatorRecoveryHandler.isSessionActive())this.__turnkeyClient=turnkeyAuthenticatorRecoveryHandler.client;else{let Er=getTLD();Er||(Er=PlatformService.getHostname());const kr=PasskeyService.createWebauthnStamper({rpId:Er}),jr=ExportHandler==null?void 0:ExportHandler.apiKeyStamper,Br=jr??kr;this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},Br)}return this.__publicKey})}verifyExportWallet(br){return __awaiter$c(this,arguments,void 0,function*({exportBundle:wr,organizationId:Er}){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");try{return yield this.__iframeStamper.injectWalletExportBundle(wr,Er)}catch(kr){throw logger$4.error("Error while verifying export wallet",kr),kr}})}verifyExportPrivateKey(br){return __awaiter$c(this,arguments,void 0,function*({exportBundle:wr,organizationId:Er,chain:kr}){if(!this.__iframeStamper)throw new DynamicError("Cannot proceed with your request");const jr=kr==="solana"||kr==="SOL"?KeyFormat.Solana:KeyFormat.Hexadecimal;try{return yield this.__iframeStamper.injectKeyExportBundle(wr,Er,jr)}catch(Br){throw logger$4.error("Error while verifying export private key",Br),Br}})}exportPrivateKey(br){return __awaiter$c(this,arguments,void 0,function*({privateKeyId:wr,organizationId:Er}){const kr=ExportHandler==null?void 0:ExportHandler.apiKeyStamper;if(kr&&(this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},kr)),!this.__iframeStamper||!this.__publicKey||!this.__turnkeyClient||!wr)throw new DynamicError("Cannot proceed with your request");try{return(yield this.__turnkeyClient.exportPrivateKey({organizationId:Er,parameters:{privateKeyId:wr,targetPublicKey:this.__publicKey},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_PRIVATE_KEY"})).activity}catch(jr){throw logger$4.error("[TK] Error while completing export private key process",jr),jr}})}exportWallet(br){return __awaiter$c(this,arguments,void 0,function*({walletId:wr,organizationId:Er,address:kr}){const jr=ExportHandler==null?void 0:ExportHandler.apiKeyStamper;if(jr&&(this.__turnkeyClient=new TurnkeyClient({baseUrl:turnkeyBaseUrl},jr)),!this.__iframeStamper||!this.__publicKey||!this.__turnkeyClient||!wr)throw new DynamicError("Cannot proceed with your request");try{return kr?(yield this.__turnkeyClient.exportWalletAccount({organizationId:Er,parameters:{address:kr,targetPublicKey:this.__publicKey},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT"})).activity:(yield this.__turnkeyClient.exportWallet({organizationId:Er,parameters:{targetPublicKey:this.__publicKey,walletId:wr},timestampMs:String(Date.now()),type:"ACTIVITY_TYPE_EXPORT_WALLET"})).activity}catch(Br){throw logger$4.error("[TK] Error while completing export wallet process",Br),Br}})}}class TurnkeyWalletConnectorBase extends WalletConnectorBase{constructor(br,wr){if(super(wr),this.requiresNonDynamicEmailOtp=!1,this.isEmbeddedWallet=!0,this.removeSessionKeys=()=>__awaiter$c(this,void 0,void 0,function*(){TurnkeyWalletConnectorBase.sessionKeys=void 0,TurnkeyWalletConnectorBase.apiKeyStamper=void 0,ExportHandler.apiKeyStamper=void 0,typeof(this===null||this===void 0?void 0:this.removeSessionKeysFunction)=="function"&&this.removeSessionKeysFunction()}),!wr.appName)throw new Error("appName not set");this.name=br.name,this.overrideKey=br.key,this.appName=wr.appName,this.__authenticatorMethodHandler=turnkeyAuthenticatorRecoveryHandler,this.__exportHandler=new ExportHandler}getWebAuthnAttestation(){return __awaiter$c(this,void 0,void 0,function*(){const br=generateRandomBuffer(),wr=generateRandomBuffer(),{email:Er,passkeyIdentifier:kr}=this;if(!Er&&!kr)throw new Error("Email or passkeyIdentifier must be set to register a webauthn credential.");const jr=Er||`${this.appName} - ${kr}`,Br={publicKey:{authenticatorSelection:{authenticatorAttachment:void 0,requireResidentKey:!1,residentKey:"preferred",userVerification:"discouraged"},challenge:br,pubKeyCredParams:[{alg:-7,type:"public-key"}],rp:{id:getTLD(),name:this.appName},user:{displayName:jr,id:wr,name:Er||`${this.appName} - ${kr}`}}};let qr;try{qr=yield PasskeyService.getWebAuthnAttestation(Br)}catch(Wr){logger$4.warn(`Unable to register webauthn credential on the current page's TLD ${getTLD()}. Falling back to using hostname. ${PlatformService.getHostname()}`,Wr),Br.publicKey.rp.id=PlatformService.getHostname(),qr=yield PasskeyService.getWebAuthnAttestation(Br)}return{attestation:{attestationObject:qr.attestationObject,clientDataJson:qr.clientDataJson,credentialId:qr.credentialId,transports:convertAttestationTransports(qr.transports)},challenge:base64UrlEncode(br),displayName:jr}})}getAuthenticatorHandler(){return this.__authenticatorMethodHandler}getExportHandler(){return this.__exportHandler}get email(){return this._email}setEmail(br){this._email=br}get phone(){return this._phone}setPhone(br){this._phone=br}get passkeyIdentifier(){return this._passkeyIdentifier}setPasskeyIdentifier(br){this._passkeyIdentifier=br}clearEmail(){this._email=null}getAddress(){return __awaiter$c(this,void 0,void 0,function*(){var br;return(br=this.verifiedCredential)===null||br===void 0?void 0:br.address})}getConnectedAccounts(){return __awaiter$c(this,void 0,void 0,function*(){return(this.verifiedCredentials||[]).map(Er=>Er==null?void 0:Er.address).filter(Er=>typeof Er=="string")})}get turnkeyAddress(){var br;const{address:wr}=(br=this.verifiedCredential)!==null&&br!==void 0?br:{};return wr}get walletProperties(){const{walletProperties:br}=this.verifiedCredential||{};return br}set verifiedCredentials(br){this._verifiedCredentials=br}get verifiedCredentials(){return this._verifiedCredentials}set verifiedCredential(br){this._verifiedCredential=br}get verifiedCredential(){return this._verifiedCredential}setSessionKeyFetcher(br){this.createOrRestoreSessionFetcherFunction=br}setSessionKeyRemoveFunction(br){this.removeSessionKeysFunction=br}createOrRestoreSession(){return __awaiter$c(this,arguments,void 0,function*({ignoreRestore:br}={}){if(!this.isSessionKeyCompatible()||TurnkeyWalletConnectorBase.isLoadingSession)return;if(!this.createOrRestoreSessionFetcherFunction)throw new DynamicError("Cannot register session key to init provider");const{sessionKeys:wr}=TurnkeyWalletConnectorBase;if(wr!=null&&wr.publicKey&&!(new Date>=new Date(wr.expirationDate)))return wr.publicKey;try{TurnkeyWalletConnectorBase.isLoadingSession=!0;const Er=yield this.createOrRestoreSessionFetcherFunction({ignoreRestore:br});return TurnkeyWalletConnectorBase.sessionKeys=Er,TurnkeyWalletConnectorBase.apiKeyStamper=new ApiKeyStamper({apiPrivateKey:Er.privateKey,apiPublicKey:Er.publicKey}),ExportHandler.apiKeyStamper=TurnkeyWalletConnectorBase.apiKeyStamper,logger$4.setMetaData("sessionApiPublicKey",Er.publicKey),Er.publicKey}catch{throw new DynamicError("Failed to create or restore session")}finally{TurnkeyWalletConnectorBase.isLoadingSession=!1}})}isSessionKeyCompatible(){var br;const wr=(br=this.verifiedCredential)===null||br===void 0?void 0:br.walletProperties;return!!(wr==null?void 0:wr.isSessionKeyCompatible)}isSessionActive(){return __awaiter$c(this,void 0,void 0,function*(){return!!((yield this.getAddress())&&TurnkeyWalletConnectorBase.sessionKeys&&TurnkeyWalletConnectorBase.apiKeyStamper)})}get sessionKeys(){return TurnkeyWalletConnectorBase.sessionKeys}setLoggerMetadata(){var br,wr,Er;logger$4.setMetaData("turnkeySubOrganizationId",(wr=(br=this._verifiedCredential)===null||br===void 0?void 0:br.walletProperties)===null||wr===void 0?void 0:wr.turnkeySubOrganizationId),logger$4.setMetaData("walletId",(Er=this._verifiedCredential)===null||Er===void 0?void 0:Er.id);let kr="Unknown";this.isSessionKeyCompatible()?kr="SessionKeys":this.__authenticatorMethodHandler.recoveryType==="passkey"?kr="Passkey":this.__authenticatorMethodHandler.recoveryType==="email"&&(kr="EmailAuth"),logger$4.setMetaData("authMethod",kr)}}TurnkeyWalletConnectorBase.isLoadingSession=!1;const TurnkeyWalletConnectorInfo={Turnkey:{key:"turnkey",name:"Turnkey"},TurnkeyHD:{key:"turnkeyhd",name:"Turnkey HD"}},findTurnkeyVerifiedCredentials=(fr,br)=>fr==null?void 0:fr.filter(({walletName:wr,chain:Er})=>(wr==null?void 0:wr.startsWith("turnkey"))&&br===Er),findTurnkeyVerifiedCredentialsWithSmartWalletRef=(fr,br)=>fr==null?void 0:fr.reduce((wr,Er)=>{var kr;if(!((kr=Er.walletName)===null||kr===void 0)&&kr.startsWith("turnkey")&&br===Er.chain){const jr=fr.find(Wr=>Wr.signerRefId===Er.id),Br=jr==null?void 0:jr.id,qr=jr==null?void 0:jr.address;wr.push(Object.assign(Object.assign({},Er),{smartWalletRefAddress:qr,smartWalletRefId:Br}))}return wr},[]);assertPackageVersion("@dynamic-labs/embedded-wallet",version$c);function __awaiter$a(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,br||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;async function createAccount(fr){var jr;const{client:br,organizationId:wr,signWith:Er}=fr;let{ethereumAddress:kr}=fr;if(!Er)throw new TurnkeyActivityError({message:"Missing signWith parameter"});if(isAddress$1(Er))kr=Er;else if(!kr&&(kr=(jr=(await br.getPrivateKey({privateKeyId:Er,organizationId:wr})).privateKey.addresses.find(qr=>qr.format==="ADDRESS_FORMAT_ETHEREUM"))==null?void 0:jr.address,typeof kr!="string"||!kr))throw new TurnkeyActivityError({message:`Unable to find Ethereum address for key ${Er} under organization ${wr}`});return toAccount({address:kr,signMessage:function({message:Br}){return signMessage(br,Br,wr,Er)},signTransaction:function(Br,qr){const Wr=qr!=null&&qr.serializer?qr.serializer:serializeTransaction$5;return signTransaction(br,Br,Wr,wr,Er)},signTypedData:function(Br){return signTypedData(br,Br,wr,Er)}})}async function signMessage(fr,br,wr,Er){const kr=hashMessage$1(br);return`${await signMessageWithErrorWrapping(fr,kr,wr,Er)}`}async function signTransaction(fr,br,wr,Er,kr){const Br=wr(br).replace(/^0x/,"");return await signTransactionWithErrorWrapping(fr,Br,Er,kr)}async function signTypedData(fr,br,wr,Er){const kr=hashTypedData$1(br);return await signMessageWithErrorWrapping(fr,kr,wr,Er)}async function signTransactionWithErrorWrapping(fr,br,wr,Er){let kr;try{kr=await signTransactionImpl(fr,br,wr,Er)}catch(jr){throw jr instanceof TurnkeyActivityError?jr:new TurnkeyActivityError({message:`Failed to sign transaction: ${jr.message}`,cause:jr})}return`0x${kr}`}async function signTransactionImpl(fr,br,wr,Er){var kr,jr;if(fr instanceof TurnkeyClient){const{activity:Br}=await fr.signTransaction({type:"ACTIVITY_TYPE_SIGN_TRANSACTION_V2",organizationId:wr,parameters:{signWith:Er,type:"TRANSACTION_TYPE_ETHEREUM",unsignedTransaction:br},timestampMs:String(Date.now())}),{id:qr,status:Wr,type:Vr}=Br;if(Br.status!=="ACTIVITY_STATUS_COMPLETED")throw new TurnkeyActivityError({message:`Invalid activity status: ${Br.status}`,activityId:qr,activityStatus:Wr,activityType:Vr});return assertNonNull((jr=(kr=Br==null?void 0:Br.result)==null?void 0:kr.signTransactionResult)==null?void 0:jr.signedTransaction)}else{const Br=await fr.signTransaction({signWith:Er,type:"TRANSACTION_TYPE_ETHEREUM",unsignedTransaction:br});return assertNonNull(Br==null?void 0:Br.signedTransaction)}}async function signMessageWithErrorWrapping(fr,br,wr,Er){let kr;try{kr=await signMessageImpl(fr,br,wr,Er)}catch(jr){throw jr instanceof TurnkeyActivityError?jr:new TurnkeyActivityError({message:`Failed to sign: ${jr.message}`,cause:jr})}return kr}async function signMessageImpl(fr,br,wr,Er){var Br;let kr;if(fr instanceof TurnkeyClient){const{activity:qr}=await fr.signRawPayload({type:"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",organizationId:wr,parameters:{signWith:Er,payload:br,encoding:"PAYLOAD_ENCODING_HEXADECIMAL",hashFunction:"HASH_FUNCTION_NO_OP"},timestampMs:String(Date.now())}),{id:Wr,status:Vr,type:Hr}=qr;if(Vr!=="ACTIVITY_STATUS_COMPLETED")throw new TurnkeyActivityError({message:`Invalid activity status: ${qr.status}`,activityId:Wr,activityStatus:Vr,activityType:Hr});kr=assertNonNull((Br=qr==null?void 0:qr.result)==null?void 0:Br.signRawPayloadResult)}else kr=await fr.signRawPayload({signWith:Er,payload:br,encoding:"PAYLOAD_ENCODING_HEXADECIMAL",hashFunction:"HASH_FUNCTION_NO_OP"});let jr=serializeSignature$1({r:`0x${kr.r}`,s:`0x${kr.s}`,v:kr.v==="00"?27n:28n});return assertNonNull(jr)}function assertNonNull(fr){if(fr==null)throw new Error(`Got unexpected ${JSON.stringify(fr)}`);return fr}var version$a="3.8.2";function __awaiter$9(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,br||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const logger$2=new Logger$1("ethereum-core"),gasPriceOracleAbiAddress="0x420000000000000000000000000000000000000F",gasPriceOracleAbi=[{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],estimateL1Fee$1=(fr,br)=>__awaiter$9(void 0,void 0,void 0,function*(){const wr=serializeTransaction$5(Object.assign(Object.assign({chainId:fr.chain.id},br),{type:br.type?br.type:"eip1559"}));return fr.readContract({abi:gasPriceOracleAbi,address:gasPriceOracleAbiAddress,args:[wr],functionName:"getL1Fee"})}),opStackSupportedChains=[optimism.id,optimismGoerli.id,optimismSepolia.id,base$7.id,baseGoerli.id,baseSepolia$1.id],chainsMap=Object.values(viemChains).reduce((fr,br)=>Object.assign(Object.assign({},fr),{[br.id]:br}),{}),erc20Abi=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];class Eip1559FeeFeed{constructor({publicClient:br,initialGasLimit:wr,initialMaxFeePerGas:Er}){this.fee={gas:BigInt(0)},this.publicClient=br,this.initialGasLimit=wr,this.initialMaxFeePerGas=Er}fetchFee(){return __awaiter$9(this,void 0,void 0,function*(){try{const br=yield this.estimateL1Fee();if(this.initialGasLimit&&this.initialMaxFeePerGas){this.fee.gas=this.initialGasLimit*this.initialMaxFeePerGas+br;return}const wr=yield this.estimateGas();if(this.initialMaxFeePerGas){this.fee.gas=wr*this.initialMaxFeePerGas+br;return}const Er=yield this.publicClient.estimateFeesPerGas();if(!Er||!Er.maxFeePerGas)return;this.fee.gas=wr*Er.maxFeePerGas+br,this.maxFeePerGas=Er.maxFeePerGas,this.maxPriorityFeePerGas=Er.maxPriorityFeePerGas}catch(br){logger$2.debug(br);return}})}}const estimateL1Fee=(fr,br)=>__awaiter$9(void 0,void 0,void 0,function*(){const{chain:wr}=fr;if(!wr)throw new Error("Chain is not defined");const Er=fr;if(opStackSupportedChains.includes(wr.id))return estimateL1Fee$1(Er,br);throw new Error("Chain is not supported")}),estimateL1FeeSupportedChains=[...opStackSupportedChains],isL1FeeSupportedByChain=fr=>estimateL1FeeSupportedChains.includes(fr),validateAddressFormat=fr=>/^0x[0-9a-fA-F]{40}$/.test(fr),parseEther=fr=>parseEther$2(fr,"wei"),formatEther=(fr,{precision:br}={})=>formatNumberText(formatEther$2(fr),{precision:br});class ViemUiTransaction extends Eip1559FeeFeed{constructor({transaction:br,onSubmit:wr,publicClient:Er,account:kr}){super({initialGasLimit:br.gas,initialMaxFeePerGas:br.maxFeePerGas,publicClient:Er}),this.chain="EVM",this.validateAddressFormat=validateAddressFormat,this.parse=parseEther,this.parseNonNativeToken=(jr,Br)=>parseUnits$1(jr,Br),this.format=formatEther,this.formatNonNativeToken=(jr,Br)=>formatUnits$1(jr,Br),this.transaction=br,this.onSubmit=wr,this.publicClient=Er,this.address=kr}get to(){return this.transaction.to||void 0}set to(br){this.transaction.to=br}get from(){return this.address}get value(){return this.transaction.value}set value(br){this.transaction.value=br}get nonNativeValue(){return this.transaction.nonNativeValue}set nonNativeValue(br){this.transaction.nonNativeValue=br}get nonNativeAddress(){return this.transaction.nonNativeAddress}set nonNativeAddress(br){this.transaction.nonNativeAddress=br}get nonNativeDecimal(){return this.transaction.nonNativeDecimal}set nonNativeDecimal(br){this.transaction.nonNativeDecimal=br}get data(){return this.transaction.data}submit(){return __awaiter$9(this,void 0,void 0,function*(){return this.onSubmit(this.transaction).catch(br=>{throw br instanceof UserRejectedTransactionError?new TransactionExecutionError(new BaseError(br.message),this.transaction):br})})}getBalance(){return this.publicClient.getBalance({address:this.address})}estimateGas(){return __awaiter$9(this,void 0,void 0,function*(){const br=yield this.publicClient.transport.request({method:"eth_estimateGas",params:[{data:this.data,to:this.to,value:this.convertBigIntToHex(this.value)}]});return hexToBigInt(br)})}convertBigIntToHex(br){return br?toHex$1(br):void 0}estimateL1Fee(){return __awaiter$9(this,void 0,void 0,function*(){var br;return isL1FeeSupportedByChain(((br=this.publicClient.chain)===null||br===void 0?void 0:br.id)||0)?estimateL1Fee(this.publicClient,{data:this.transaction.data,to:this.transaction.to,value:this.transaction.value}):BigInt(0)})}set maxFeePerGas(br){this.transaction.maxFeePerGas=br}set maxPriorityFeePerGas(br){this.transaction.maxPriorityFeePerGas=br}}const createViemUiTransaction=fr=>__awaiter$9(void 0,[fr],void 0,function*({from:br,publicClient:wr,walletClient:Er}){return new ViemUiTransaction({account:br,onSubmit:kr=>__awaiter$9(void 0,void 0,void 0,function*(){return kr.nonNativeAddress?Er.writeContract({abi:erc20Abi,account:br,address:kr.nonNativeAddress,args:[kr.to,kr.nonNativeValue],functionName:"transfer",maxFeePerGas:kr.maxFeePerGas,maxPriorityFeePerGas:kr.maxPriorityFeePerGas}):Er.sendTransaction({account:br,maxFeePerGas:kr.maxFeePerGas,maxPriorityFeePerGas:kr.maxPriorityFeePerGas,to:kr.to,value:kr.value})}),publicClient:wr,transaction:{}})}),getChain=fr=>{for(const br of Object.values(viemChains))if("id"in br&&br.id===fr)return br;throw new Error(`Chain with id ${fr} not found`)},mapChain=fr=>{var br;return{blockExplorers:!((br=fr.blockExplorerUrls)===null||br===void 0)&&br[0]?{default:{name:fr.blockExplorerUrls[0],url:fr.blockExplorerUrls[0]}}:void 0,id:fr.chainId,name:fr.vanityName||fr.name||fr.chainName,nativeCurrency:fr.nativeCurrency,rpcUrls:{default:{http:fr.rpcUrls},public:{http:fr.rpcUrls}}}},getOrMapViemChain=fr=>{let br;try{br=getChain(fr.chainId)}catch{logger$2.debug(`Chain with id ${fr.chainId} not found in viem's chains`)}const wr=mapChain(fr);return br?Object.assign(Object.assign({},br),wr):wr},findEvmNetwork=({chainId:fr,name:br,networks:wr})=>{if(!(!fr&&!br))return fr&&br?wr.find(Er=>Er.chainId===fr&&Er.name===br):fr?wr.find(Er=>Er.chainId===fr):wr.find(Er=>Er.name===br)};var L2ResolverAbi=[{inputs:[{internalType:"contract ENS",name:"ens_",type:"address"},{internalType:"address",name:"registrarController_",type:"address"},{internalType:"address",name:"reverseRegistrar_",type:"address"},{internalType:"address",name:"owner_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AlreadyInitialized",type:"error"},{inputs:[],name:"CantSetSelfAsDelegate",type:"error"},{inputs:[],name:"CantSetSelfAsOperator",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"NoHandoverRequest",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"uint256",name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"address",name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"coinType",type:"uint256"},{indexed:!1,internalType:"bytes",name:"newAddress",type:"bytes"}],name:"AddressChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"address",name:"delegate",type:"address"},{indexed:!0,internalType:"bool",name:"approved",type:"bool"}],name:"Approved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"hash",type:"bytes"}],name:"ContenthashChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"name",type:"bytes"},{indexed:!1,internalType:"uint16",name:"resource",type:"uint16"},{indexed:!1,internalType:"bytes",name:"record",type:"bytes"}],name:"DNSRecordChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"name",type:"bytes"},{indexed:!1,internalType:"uint16",name:"resource",type:"uint16"}],name:"DNSRecordDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"lastzonehash",type:"bytes"},{indexed:!1,internalType:"bytes",name:"zonehash",type:"bytes"}],name:"DNSZonehashChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"bytes4",name:"interfaceID",type:"bytes4"},{indexed:!1,internalType:"address",name:"implementer",type:"address"}],name:"InterfaceChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"string",name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"pendingOwner",type:"address"}],name:"OwnershipHandoverCanceled",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"pendingOwner",type:"address"}],name:"OwnershipHandoverRequested",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"x",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newRegistrarController",type:"address"}],name:"RegistrarControllerUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newReverseRegistrar",type:"address"}],name:"ReverseRegistrarUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!0,internalType:"string",name:"indexedKey",type:"string"},{indexed:!1,internalType:"string",name:"key",type:"string"},{indexed:!1,internalType:"string",name:"value",type:"string"}],name:"TextChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"node",type:"bytes32"},{indexed:!1,internalType:"uint64",name:"newVersion",type:"uint64"}],name:"VersionChanged",type:"event"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"addr",outputs:[{internalType:"address payable",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"coinType",type:"uint256"}],name:"addr",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"delegate",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cancelOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"clearRecords",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"pendingOwner",type:"address"}],name:"completeOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"contenthash",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"name",type:"bytes32"},{internalType:"uint16",name:"resource",type:"uint16"}],name:"dnsRecord",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"ens",outputs:[{internalType:"contract ENS",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"name",type:"bytes32"}],name:"hasDNSRecords",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes4",name:"interfaceID",type:"bytes4"}],name:"interfaceImplementer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"delegate",type:"address"}],name:"isApprovedFor",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes[]",name:"data",type:"bytes[]"}],name:"multicall",outputs:[{internalType:"bytes[]",name:"results",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"nodehash",type:"bytes32"},{internalType:"bytes[]",name:"data",type:"bytes[]"}],name:"multicallWithNodeCheck",outputs:[{internalType:"bytes[]",name:"results",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"pendingOwner",type:"address"}],name:"ownershipHandoverExpiresAt",outputs:[{internalType:"uint256",name:"result",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"pubkey",outputs:[{internalType:"bytes32",name:"x",type:"bytes32"},{internalType:"bytes32",name:"y",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"recordVersions",outputs:[{internalType:"uint64",name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"registrarController",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"requestOwnershipHandover",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes",name:"",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],name:"resolve",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"reverseRegistrar",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"contentType",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setABI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"uint256",name:"coinType",type:"uint256"},{internalType:"bytes",name:"a",type:"bytes"}],name:"setAddr",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"address",name:"a",type:"address"}],name:"setAddr",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"hash",type:"bytes"}],name:"setContenthash",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setDNSRecords",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes4",name:"interfaceID",type:"bytes4"},{internalType:"address",name:"implementer",type:"address"}],name:"setInterface",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"newName",type:"string"}],name:"setName",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes32",name:"x",type:"bytes32"},{internalType:"bytes32",name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"registrarController_",type:"address"}],name:"setRegistrarController",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"reverseRegistrar_",type:"address"}],name:"setReverseRegistrar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"key",type:"string"},{internalType:"string",name:"value",type:"string"}],name:"setText",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"bytes",name:"hash",type:"bytes"}],name:"setZonehash",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"},{internalType:"string",name:"key",type:"string"}],name:"text",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"node",type:"bytes32"}],name:"zonehash",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"}];const getNameservice=fr=>__awaiter$9(void 0,[fr],void 0,function*({rpcProvider:br,address:wr}){const Er={avatar:void 0,name:void 0},kr=yield br.getChainId();if(!kr)return Er;const jr=(qr,Wr)=>{const Vr=qr.toLocaleLowerCase(),Hr=keccak256$1(Vr.substring(2)),Zr=Br(Wr),Jr=namehash$1(`${Zr.toLocaleUpperCase()}.reverse`);return keccak256$1(encodePacked$1(["bytes32","bytes32"],[Jr,Hr]))},Br=qr=>((2147483648|qr)>>>0).toString(16).toLocaleUpperCase();if(kr===8453){const qr=jr(wr,8453);try{const Wr=yield br.readContract({abi:L2ResolverAbi,address:"0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",args:[qr],functionName:"name"});if(Wr)return Er.name=Wr,Er}catch{return Er}}else Er.name=yield br.getEnsName({address:wr}),Er.avatar=Er.name?yield br.getEnsAvatar({name:Er.name}):void 0;return Er}),isTransactionExecutionError=fr=>fr!=null&&typeof fr=="object"&&"walk"in fr&&typeof fr.walk=="function",interceptTransport=({getAccounts:fr,onPersonalSign:br,onSendTransaction:wr,onSignTypedData:Er,transport:kr})=>jr=>{const Br=kr(jr);return custom$1({request:qr=>__awaiter$9(void 0,void 0,void 0,function*(){var Wr;const{method:Vr,params:Hr}=qr;if(fr&&Vr==="eth_accounts")return fr({provider:Br});if(br&&Vr==="personal_sign"){const[Zr]=Hr;return br({args:qr,message:Zr,provider:Br}).catch(Jr=>{throw Jr instanceof UserRejectedRequestError$1?new UserRejectedRequestError(Jr):Jr})}if(wr&&Vr==="eth_sendTransaction"){const[Zr]=Hr;return wr({args:qr,provider:Br,transaction:Zr}).catch(Jr=>{throw isTransactionExecutionError(Jr)&&Jr.walk()instanceof UserRejectedTransactionError?new UserRejectedRequestError(Jr.walk()):Jr instanceof UserRejectedRequestError$1?new UserRejectedRequestError(Jr):Jr})}if(Er&&Vr==="eth_signTypedData_v4"){const[,Zr]=(Wr=Hr)!==null&&Wr!==void 0?Wr:[];return Er({args:qr,message:Zr,provider:Br}).catch(Jr=>{throw Jr instanceof UserRejectedRequestError$1?new UserRejectedRequestError(Jr):Jr})}return Br.request(qr)})})(jr)};class EthereumWallet extends Wallet$2{getPublicClient(){return __awaiter$9(this,void 0,void 0,function*(){const br=yield this._connector.getPublicClient();if(!br)throw new Error("Unable to retrieve PublicClient");return br})}getWalletClient(br){return __awaiter$9(this,void 0,void 0,function*(){const wr=this._connector.getWalletClient(br);if(!wr)throw new Error("Unable to retrieve WalletClient");return createWalletClient$1({account:this.address,chain:wr.chain,transport:interceptTransport({onPersonalSign:Er=>__awaiter$9(this,[Er],void 0,function*({provider:kr,args:jr}){return yield this.sync(),kr.request(jr)}),onSendTransaction:Er=>__awaiter$9(this,[Er],void 0,function*({provider:kr,args:jr}){return yield this.sync(),kr.request(jr)}),onSignTypedData:Er=>__awaiter$9(this,[Er],void 0,function*({provider:kr,args:jr}){return yield this.sync(),kr.request(jr)}),transport:custom$1(wr.transport)})})})}}class EthereumWalletConnector extends WalletConnectorBase{getPublicClient(){return __awaiter$9(this,void 0,void 0,function*(){var br,wr;const Er=(br=yield this.getNetwork())!==null&&br!==void 0?br:1;if(this.evmNetworks.length===0)return;const kr={cosmos:[],evm:this.evmNetworks,solana:[],starknet:void 0};if(!this.chainRpcProviders)return;const jr=this.chainRpcProviders.getProviders(kr);return(wr=this.chainRpcProviders.getEvmProviderByChainId(jr,Er))===null||wr===void 0?void 0:wr.provider})}constructor(br){var wr;super(br),this.ChainWallet=EthereumWallet,this.evmNetworkRpcMap=()=>this.evmNetworks.reduce((Er,kr)=>{var jr;return[Er[kr.chainId]]=!((jr=kr==null?void 0:kr.privateCustomerRpcUrls)===null||jr===void 0)&&jr.length?kr.privateCustomerRpcUrls:kr.rpcUrls,Er},{}),this.evmNetworks=parseEvmNetworks(br.evmNetworks),this.chainRpcProviders=br.chainRpcProviders,(wr=this.chainRpcProviders)===null||wr===void 0||wr.registerEvmProviders()}getNetwork(){return __awaiter$9(this,void 0,void 0,function*(){const br=this.getWalletClient();if(!this.supportsNetworkSwitching||!br)return Promise.resolve(void 0);const wr=yield retryableFn(br.getChainId,{fallbackValue:FALLBACK_UNDEFINED,timeoutMs:1e3});return this.setActiveChain(chainsMap[wr]),wr})}getNameService(br){return __awaiter$9(this,void 0,void 0,function*(){const wr=yield this.getPublicClient();if(wr)return getNameservice({address:br,rpcProvider:wr})})}isTestnet(){return __awaiter$9(this,void 0,void 0,function*(){var br,wr,Er;return(Er=(wr=(br=yield this.getPublicClient())===null||br===void 0?void 0:br.chain)===null||wr===void 0?void 0:wr.testnet)!==null&&Er!==void 0?Er:!1})}parseAddress(br){try{return getAddress$1(br)}catch(wr){logger$7.debug(`Failed to parse EVM address into EIP55 format: error getting checksum, returning default ${br}`,wr)}return br}getSigner(){return __awaiter$9(this,void 0,void 0,function*(){return this.getWalletClient()})}getBalance(br){return __awaiter$9(this,void 0,void 0,function*(){const wr=yield this.getPublicClient(),Er=yield wr==null?void 0:wr.getBalance({address:br});if(!(!Er&&Er!==BigInt(0)))return formatEther$2(Er)})}supportsNetworkSwitching(){return!0}switchNetwork(br){return __awaiter$9(this,arguments,void 0,function*({networkName:wr,networkChainId:Er}){const kr=findEvmNetwork({chainId:Er,name:wr,networks:this.evmNetworks});if(!kr)throw new DynamicError(`Could not find network mapping for chain ${wr||Er}`);if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching is not supported");const jr=this.getWalletClient();if(!jr)throw new DynamicError("Provider not found");return this.providerSwitchNetwork({network:kr,provider:jr})})}chooseAccountsToConnect(){return __awaiter$9(this,void 0,void 0,function*(){var br,wr,Er;const kr=this.getWalletClient();if(!kr)return[];try{const jr=yield kr.requestPermissions({eth_accounts:{}});logger$7.debug("chooseAccountsToConnect - requestPermissions result",jr);const Br=(Er=(wr=(br=jr==null?void 0:jr.find(qr=>qr.parentCapability==="eth_accounts"))===null||br===void 0?void 0:br.caveats)===null||wr===void 0?void 0:wr[0])===null||Er===void 0?void 0:Er.value;return typeof Br=="string"?[Br]:Array.isArray(Br)?Br:[]}catch(jr){if(logger$7.debug("chooseAccountsToConnect - error",jr),jr.code===4001)throw new UserRejectedRequestError$1}return[]})}getConnectedAccounts(){return __awaiter$9(this,void 0,void 0,function*(){const br=this.getWalletClient();if(!br)return[];const wr=yield retryableFn(br.getAddresses,{fallbackValue:[],timeoutMs:500});return wr.length&&this.setActiveAccount(wr[0]),wr})}providerSwitchNetwork(br){return __awaiter$9(this,arguments,void 0,function*({network:wr,provider:Er}){var kr,jr,Br,qr;const{chainId:Wr}=wr,Vr=yield this.getNetwork();if(!(Vr&&Vr===Wr))try{if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching is not supported");const Hr=getOrMapViemChain(wr);if(yield Er.switchChain(Hr),this.key==="magiceden"){const Zr=yield Er.getChainId();this.emit("chainChange",{chain:Zr.toString()})}else this.setActiveChain(Hr)}catch(Hr){if(Hr.code===4902||!((kr=Hr.message)===null||kr===void 0)&&kr.includes("Unrecognized chain")||((Br=(jr=Hr.data)===null||jr===void 0?void 0:jr.orginalError)===null||Br===void 0?void 0:Br.code)===4902)return this.providerAddNetwork({network:wr,provider:Er});throw!((qr=Hr.message)===null||qr===void 0)&&qr.includes("rejected")||typeof Hr=="string"&&Hr.includes("rejected")?new DynamicError("User rejected the wallet's request to switch network"):Hr}})}providerAddNetwork(br){return __awaiter$9(this,arguments,void 0,function*({network:wr,provider:Er}){var kr;try{return yield Er.addChain({chain:getOrMapViemChain(wr)})}catch(jr){throw!((kr=jr.message)===null||kr===void 0)&&kr.includes("rejected")||typeof jr=="string"&&jr.includes("rejected")?new DynamicError("User rejected the wallet's request to add network"):jr}})}setActiveAccount(br){this.activeAccount=br?toAccount(br):void 0}getActiveAccount(){return this.activeAccount}setActiveChain(br){this.activeChain=br}getActiveChain(){return this.activeChain}createUiTransaction(br){return __awaiter$9(this,void 0,void 0,function*(){yield this.validateActiveWallet(br);const wr=yield this.getWalletClient(),Er=yield this.getPublicClient();if(!Er||!wr)throw new DynamicError("No public client available");return createViemUiTransaction({from:br,publicClient:Er,walletClient:wr})})}confirmTransactionStatus(br){return __awaiter$9(this,void 0,void 0,function*(){const wr=yield this.getPublicClient();if(!wr)throw new DynamicError("No public client available");return wr.waitForTransactionReceipt({confirmations:3,hash:br})})}}ChainRpcProviders.getEvmProviderByChainId=(fr,br)=>{var wr;return(wr=fr.evm)===null||wr===void 0?void 0:wr.find(kr=>kr.chainId===br)};ChainRpcProviders.registerEvmProviders=()=>{ChainRpcProviders.registerChainProviders(ProviderChain.EVM,fr=>{const br={};return fr!=null&&fr.evm&&(br.evm=parseEvmNetworks(fr.evm).map(wr=>{var Er;const kr=((Er=wr.privateCustomerRpcUrls)===null||Er===void 0?void 0:Er[0])||wr.rpcUrls[0],jr=createPublicClient$1({chain:getOrMapViemChain(wr),transport:http$2(kr)});return{chainId:wr.chainId,chainName:wr.name,provider:jr}})),br.evm})};const unFormatTransaction=fr=>Object.assign(Object.assign({},fr),{gas:typeof fr.gas<"u"?hexToBigInt(fr.gas):void 0,gasPrice:typeof fr.gasPrice<"u"?hexToBigInt(fr.gasPrice):void 0,maxFeePerGas:typeof fr.maxFeePerGas<"u"?hexToBigInt(fr.maxFeePerGas):void 0,maxPriorityFeePerGas:typeof fr.maxPriorityFeePerGas<"u"?hexToBigInt(fr.maxPriorityFeePerGas):void 0,nonce:typeof fr.nonce<"u"?hexToBigInt(fr.nonce):void 0,value:typeof fr.value<"u"?hexToBigInt(fr.value):void 0}),createAccountWithUiConfirmation=({address:fr,account:br,provider:wr,walletConnector:Er,walletUiUtils:kr})=>toAccount({address:fr,signMessage:(...jr)=>__awaiter$9(void 0,void 0,void 0,function*(){return kr.signMessage({handler:()=>__awaiter$9(void 0,void 0,void 0,function*(){return(yield br()).signMessage(...jr)}),message:(()=>{var Br;const qr=(Br=jr[0])===null||Br===void 0?void 0:Br.message;return qr&&!(typeof qr=="string"&&Array.isArray(qr))?JSON.stringify(qr):qr==null?void 0:qr.toString()})(),walletConnector:Er})}),signTransaction:(...jr)=>__awaiter$9(void 0,void 0,void 0,function*(){const Br=new ViemUiTransaction({account:fr,onSubmit:qr=>__awaiter$9(void 0,void 0,void 0,function*(){return(yield br()).signTransaction(qr)}),publicClient:wr,transaction:jr[0]});return kr.sendTransaction(Er,Br)}),signTypedData:(...jr)=>kr.signMessage({handler:()=>__awaiter$9(void 0,void 0,void 0,function*(){return(yield br()).signTypedData(...jr)}),message:JSON.stringify(jr[0]),walletConnector:Er})}),createWalletClientWithUiConfirmation=({address:fr,account:br,chain:wr,transport:Er,walletConnector:kr,walletUiUtils:jr})=>{let Br=null;const qr=createPublicClient$1({chain:wr,transport:Er}),Wr=createAccountWithUiConfirmation({account:br,address:fr,provider:qr,walletConnector:kr,walletUiUtils:jr}),Vr=interceptTransport({getAccounts:()=>__awaiter$9(void 0,void 0,void 0,function*(){return[fr]}),onPersonalSign:Hr=>__awaiter$9(void 0,[Hr],void 0,function*({message:Zr}){if(!Br)throw new Error("Client not initialized");return Br.signMessage({message:{raw:Zr}})}),onSendTransaction:Hr=>__awaiter$9(void 0,[Hr],void 0,function*({transaction:Zr}){if(!Br)throw new Error("Client not initialized");const Jr=unFormatTransaction(Zr);return Br.sendTransaction(Jr)}),onSignTypedData:Hr=>__awaiter$9(void 0,[Hr],void 0,function*({message:Zr}){if(!Br)throw new Error("Client not initialized");return Br.signTypedData(JSON.parse(Zr))}),transport:Er});return Br=createWalletClient$1({account:Wr,chain:wr,transport:Vr}),Br};assertPackageVersion("@dynamic-labs/ethereum-core",version$a);class TurnkeyEVMWalletConnector extends TurnkeyWalletConnectorBase{constructor(br,wr){var Er;super(br,wr),this.walletFallback={brand:{alt:"Turnkey Wallet",spriteId:"turnkey"},name:"Turnkey HD"},this.ChainWallet=EthereumWallet,this.connectedChain="EVM",this.supportedChains=["ETH","EVM"],this.verifiedCredentialChain="eip155",this.stampCreateWalletAccountRequest=kr=>__awaiter$a(this,[kr],void 0,function*({request:jr}){return yield this.createOrRestoreSession(),this.getTurnkeyClient().stampCreateWalletAccounts(jr)}),this.evmNetworks=parseEvmNetworks(wr.evmNetworks),this.walletUiUtils=wr.walletUiUtils,this._turnkeyAccount=void 0,this._selectedChainId=this.getLastUsedChainId(),this.chainRpcProviders=wr.chainRpcProviders,(Er=this.chainRpcProviders)===null||Er===void 0||Er.registerEvmProviders(),this.__turnkeyClient=this.getTurnkeyClient()}getLastUsedChainId(){var br;if(this.lastUsedChainId)return this.lastUsedChainId;if(!((br=this.evmNetworks)===null||br===void 0)&&br.length)return this.evmNetworks[0].chainId}getNetwork(){return __awaiter$a(this,void 0,void 0,function*(){var br;return(br=yield this.getSigner())===null||br===void 0?void 0:br.getChainId()})}supportsNetworkSwitching(){return!0}switchNetwork(br){return __awaiter$a(this,arguments,void 0,function*({networkChainId:wr}){wr&&(typeof wr=="string"&&(wr=parseInt(wr)),this.lastUsedChainId=wr,this._selectedChainId=wr,yield this.refreshTurnkeyAccount(),this.emit("chainChange",{chain:wr.toString()}))})}setVerifiedCredentials(br){const wr=findTurnkeyVerifiedCredentialsWithSmartWalletRef(br,"eip155"),[Er]=wr;JSON.stringify(this.verifiedCredentials)!==JSON.stringify(wr)&&(this.verifiedCredential=Er,this.verifiedCredentials=wr,this.refreshTurnkeyAccount())}validateActiveWallet(br){return __awaiter$a(this,void 0,void 0,function*(){var wr,Er;const kr=((wr=this.verifiedCredential)===null||wr===void 0?void 0:wr.address)||"";if(!isSameAddress$1(kr,br,this.connectedChain)){const Br=(Er=this.verifiedCredentials)===null||Er===void 0?void 0:Er.find(qr=>(qr==null?void 0:qr.address)===br);if(!Br)throw new DynamicError("Account not found");this.verifiedCredential=Br,this.refreshTurnkeyAccount()}})}getRpcUrl(){const br=this._selectedChainId;return getRpcUrlForChain({chainId:br,networks:this.evmNetworks})}getBalance(br){return __awaiter$a(this,void 0,void 0,function*(){const wr=this.getRpcUrl();if(!wr)return;const kr=yield createPublicClient$1({transport:http$2(wr)}).getBalance({address:br});return formatEther$2(kr)})}signMessage(br){return __awaiter$a(this,void 0,void 0,function*(){const wr=yield this.getSigner();if(!wr)throw new Error("Signer not found");return wr.signMessage({message:br})})}getPublicClient(){return __awaiter$a(this,void 0,void 0,function*(){var br,wr;if(this.evmNetworks.length===0)return;const Er=(br=yield this.getNetwork())!==null&&br!==void 0?br:1,kr={cosmos:[],evm:this.evmNetworks,solana:[],starknet:void 0};if(!this.chainRpcProviders)return;const jr=this.chainRpcProviders.getProviders(kr);return(wr=this.chainRpcProviders.getEvmProviderByChainId(jr,Er))===null||wr===void 0?void 0:wr.provider})}getSigner(){return __awaiter$a(this,void 0,void 0,function*(){return yield this.getTurnkeyAccount(),this.getWalletClient()})}getTurnkeyClient(){var br;let wr=getTLD();wr||(wr=PlatformService.getHostname());const Er=PasskeyService.createWebauthnStamper({rpId:wr}),kr=TurnkeyWalletConnectorBase==null?void 0:TurnkeyWalletConnectorBase.apiKeyStamper,jr=kr??Er;return this.__turnkeyClient=(br=this.getAuthenticatorHandler().client)!==null&&br!==void 0?br:new TurnkeyClient({baseUrl:TURNKEY_API_BASE_URL},jr),this.__turnkeyClient}getAccount(){return __awaiter$a(this,void 0,void 0,function*(){var br,wr,Er;return this.isSessionKeyCompatible()&&((br=this.__turnkeyClient)===null||br===void 0?void 0:br.stamper)instanceof ApiKeyStamper?this._turnkeyAccount:((this.getAuthenticatorHandler().recoveryType==="passkey"&&((wr=this.__turnkeyClient)===null||wr===void 0?void 0:wr.stamper)instanceof IframeStamper||this.getAuthenticatorHandler().recoveryType==="email"&&((Er=this.__turnkeyClient)===null||Er===void 0?void 0:Er.stamper)instanceof WebauthnStamper||this.__turnkeyClient!==this.getAuthenticatorHandler().client)&&(yield this.refreshTurnkeyAccount()),this._turnkeyAccount)})}getWalletClient(){const br=this.networkRpcUrl,wr=this._turnkeyAccount,Er=this.currentEvmNetwork;if(!(!wr||!br||!Er))return createWalletClientWithUiConfirmation({account:this.getAccount.bind(this),address:this.turnkeyAddress,chain:getOrMapViemChain(Er),transport:http$2(br),walletConnector:this,walletUiUtils:this.walletUiUtils})}get currentChainId(){var br,wr,Er;return(br=this._selectedChainId)!==null&&br!==void 0?br:(Er=(wr=this.evmNetworks)===null||wr===void 0?void 0:wr[0])===null||Er===void 0?void 0:Er.chainId}get lastUsedChainId(){const br=localStorage.getItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey);if(br)try{const wr=parseInt(br);if(isNaN(wr))return;if(!this.evmNetworks.some(kr=>kr.chainId===wr)){const kr=this.evmNetworks[0].chainId;return this.lastUsedChainId=kr,this.lastUsedChainId}return wr}catch(wr){logger$4.error(wr);return}}set lastUsedChainId(br){br===void 0?localStorage.removeItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey):localStorage.setItem(TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey,br.toString())}get networkRpcUrl(){const br=this.currentChainId;return this.evmNetworks.find(kr=>kr.chainId===br)?getRpcUrlForChain({chainId:br,networks:this.evmNetworks}):void 0}get currentEvmNetwork(){const br=this.currentChainId;return this.evmNetworks.find(wr=>wr.chainId===br)}internalSignTransaction(br){return __awaiter$a(this,arguments,void 0,function*({transaction:wr,args:Er,address:kr,turnkeySubOrganizationId:jr}){return this.doRetryableTurnkeyAction({action:Br=>Br.signTransaction(wr,Er),activityType:"SignTransaction",address:kr,turnkeySubOrganizationId:jr})})}internalSignTypedData(br){return __awaiter$a(this,arguments,void 0,function*({typedData:wr,address:Er,turnkeySubOrganizationId:kr}){return this.doRetryableTurnkeyAction({action:jr=>jr.signTypedData(wr),activityType:"SignTypedData",address:Er,turnkeySubOrganizationId:kr})})}internalSignMessage(br){return __awaiter$a(this,arguments,void 0,function*({message:wr,address:Er,turnkeySubOrganizationId:kr}){return this.doRetryableTurnkeyAction({action:jr=>jr.signMessage({message:wr}),activityType:"SignMessage",address:Er,turnkeySubOrganizationId:kr})})}doRetryableTurnkeyAction(br){return __awaiter$a(this,arguments,void 0,function*({action:wr,activityType:Er,address:kr,turnkeySubOrganizationId:jr}){yield this.createOrRestoreSession();let Br=yield this.createTurnkeyAccount({address:kr,turnkeySubOrganizationId:jr});try{return yield wr(Br)}catch(qr){if(TURNKEY_SDK_SESSION_KEY_RETRYABLE_ERRORS.some(Wr=>qr.message.includes(Wr)))return yield this.removeSessionKeys(),yield this.createOrRestoreSession({ignoreRestore:!0}),Br=yield this.createTurnkeyAccount({address:kr,turnkeySubOrganizationId:jr}),wr(Br);throw logger$4.error(`[TK] failed to perform ${Er} activity`,qr),qr}})}createTurnkeyAccount(br){return __awaiter$a(this,arguments,void 0,function*({address:wr,turnkeySubOrganizationId:Er}){return createAccount({client:this.getTurnkeyClient(),ethereumAddress:wr,organizationId:Er,signWith:wr})})}refreshTurnkeyAccount(){return __awaiter$a(this,void 0,void 0,function*(){return this._turnkeyAccount=void 0,this.getTurnkeyAccount()})}getTurnkeyAccount(){return __awaiter$a(this,void 0,void 0,function*(){var br,wr;if(this._turnkeyAccount)return this._turnkeyAccount;const{turnkeySubOrganizationId:Er}=(br=this.walletProperties)!==null&&br!==void 0?br:{},{address:kr}=(wr=this.verifiedCredential)!==null&&wr!==void 0?wr:{};if(!(!Er||!kr))return this._turnkeyAccount=toAccount({address:kr,signMessage:jr=>__awaiter$a(this,[jr],void 0,function*({message:Br}){return this.internalSignMessage({address:kr,message:Br,turnkeySubOrganizationId:Er})}),signTransaction:(jr,Br)=>__awaiter$a(this,void 0,void 0,function*(){return this.internalSignTransaction({address:kr,args:Br,transaction:jr,turnkeySubOrganizationId:Er})}),signTypedData:jr=>__awaiter$a(this,void 0,void 0,function*(){return this.internalSignTypedData({address:kr,turnkeySubOrganizationId:Er,typedData:jr})})}),this.setLoggerMetadata(),this._turnkeyAccount})}createUiTransaction(br){return __awaiter$a(this,void 0,void 0,function*(){yield this.validateActiveWallet(br);const wr=this.getWalletClient(),Er=yield this.getPublicClient();if(!Er||!wr)throw new DynamicError("No public client available");return createViemUiTransaction({from:br,publicClient:Er,walletClient:wr})})}}TurnkeyEVMWalletConnector.lastUsedChainIdStorageKey="turnkey-last-used-chain-id";const TurnkeyEVMWalletConnectors=fr=>{var br;return!((br=fr.apiProviders)===null||br===void 0)&&br.turnkey?[TurnkeyEVMWalletConnector.bind(null,TurnkeyWalletConnectorInfo.TurnkeyHD),TurnkeyEVMWalletConnector.bind(null,TurnkeyWalletConnectorInfo.Turnkey)]:[]};assertPackageVersion("@dynamic-labs/embedded-wallet-evm",version$d);var version$9="3.8.2";function __rest$6(fr,br){var wr={};for(var Er in fr)Object.prototype.hasOwnProperty.call(fr,Er)&&br.indexOf(Er)<0&&(wr[Er]=fr[Er]);if(fr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var kr=0,Er=Object.getOwnPropertySymbols(fr);krwr.chain==="evm")}installedProviders(){const br=this.getInjectedConfig();if(!br)return[];const wr=[];if(br.windowLocations)for(const Er of br.windowLocations){const kr=getProvidersFromWindow(Er);kr&&kr.length&&wr.push(...kr)}return window.ethereum&&(!window.ethereum.providers||!window.ethereum.providers.length?wr.push(window.ethereum):window.ethereum.providers.forEach(Er=>wr.push(Er))),wr}installedProviderLookup(br){const wr=this.installedProviders();return ProviderLookup(wr,br)}eip6963ProviderLookup(br){var wr;const{providers:Er}=Eip6963ProviderSingleton.get();return(wr=Er.find(kr=>{var jr;return((jr=kr==null?void 0:kr.info)===null||jr===void 0?void 0:jr.rdns)===br}))===null||wr===void 0?void 0:wr.provider}isInstalledHelper(){return this.findProvider()!==void 0}findProvider(){return this.connector.findProvider()}findWalletClient(br){const wr=this.findProvider();if(wr)return createWalletClient$1({account:this.connector.getActiveAccount(),chain:br?chainsMap[br]:this.connector.getActiveChain(),transport:custom$1(wr)})}getAddress(){return __awaiter$8(this,void 0,void 0,function*(){const br=this.findWalletClient();return br?this.getAddressWithProvider(br):Promise.resolve(void 0)})}getAddressWithProvider(br){return __awaiter$8(this,void 0,void 0,function*(){try{const[wr]=yield br.requestAddresses(),Er=getAddress$1(wr);return this.connector.setActiveAccount(Er),Er}catch(wr){return logger$7.error(wr),Promise.reject(wr)}})}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){const wr=yield this.getAddress();if(!wr)return Promise.resolve(void 0);const Er=this.findWalletClient();return Er?yield Er.signMessage({account:wr,message:br}):Promise.resolve(void 0)})}_setupEventListeners(br){const wr=this.findProvider();if(!wr)return logger$7.warn("Provider not found",{connector:br}),{tearDownEventListeners:()=>{}};if(!wr.on)return logger$7.warn("Provider does not support event listeners",{connector:br,provider:wr}),{tearDownEventListeners:()=>{}};const{handleAccountChange:Er,handleChainChange:kr,handleDisconnect:jr}=eventListenerHandlers(br);return wr.on("accountsChanged",Er),wr.on("chainChanged",kr),wr.on("disconnect",jr),{tearDownEventListeners:()=>{const qr=this.findProvider();qr&&(Er&&qr.removeListener("accountsChanged",Er),kr&&qr.removeListener("chainChanged",kr),jr&&qr.removeListener("disconnect",jr))}}}}var chacha20poly1305={},chacha={},binary={},int={};(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});function br(qr,Wr){var Vr=qr>>>16&65535,Hr=qr&65535,Zr=Wr>>>16&65535,Jr=Wr&65535;return Hr*Jr+(Vr*Jr+Hr*Zr<<16>>>0)|0}fr.mul=Math.imul||br;function wr(qr,Wr){return qr+Wr|0}fr.add=wr;function Er(qr,Wr){return qr-Wr|0}fr.sub=Er;function kr(qr,Wr){return qr<>>32-Wr}fr.rotl=kr;function jr(qr,Wr){return qr<<32-Wr|qr>>>Wr}fr.rotr=jr;function Br(qr){return typeof qr=="number"&&isFinite(qr)&&Math.floor(qr)===qr}fr.isInteger=Number.isInteger||Br,fr.MAX_SAFE_INTEGER=9007199254740991,fr.isSafeInteger=function(qr){return fr.isInteger(qr)&&qr>=-fr.MAX_SAFE_INTEGER&&qr<=fr.MAX_SAFE_INTEGER}})(int);Object.defineProperty(binary,"__esModule",{value:!0});var int_1=int;function readInt16BE(fr,br){return br===void 0&&(br=0),(fr[br+0]<<8|fr[br+1])<<16>>16}binary.readInt16BE=readInt16BE;function readUint16BE(fr,br){return br===void 0&&(br=0),(fr[br+0]<<8|fr[br+1])>>>0}binary.readUint16BE=readUint16BE;function readInt16LE(fr,br){return br===void 0&&(br=0),(fr[br+1]<<8|fr[br])<<16>>16}binary.readInt16LE=readInt16LE;function readUint16LE(fr,br){return br===void 0&&(br=0),(fr[br+1]<<8|fr[br])>>>0}binary.readUint16LE=readUint16LE;function writeUint16BE(fr,br,wr){return br===void 0&&(br=new Uint8Array(2)),wr===void 0&&(wr=0),br[wr+0]=fr>>>8,br[wr+1]=fr>>>0,br}binary.writeUint16BE=writeUint16BE;binary.writeInt16BE=writeUint16BE;function writeUint16LE(fr,br,wr){return br===void 0&&(br=new Uint8Array(2)),wr===void 0&&(wr=0),br[wr+0]=fr>>>0,br[wr+1]=fr>>>8,br}binary.writeUint16LE=writeUint16LE;binary.writeInt16LE=writeUint16LE;function readInt32BE(fr,br){return br===void 0&&(br=0),fr[br]<<24|fr[br+1]<<16|fr[br+2]<<8|fr[br+3]}binary.readInt32BE=readInt32BE;function readUint32BE(fr,br){return br===void 0&&(br=0),(fr[br]<<24|fr[br+1]<<16|fr[br+2]<<8|fr[br+3])>>>0}binary.readUint32BE=readUint32BE;function readInt32LE(fr,br){return br===void 0&&(br=0),fr[br+3]<<24|fr[br+2]<<16|fr[br+1]<<8|fr[br]}binary.readInt32LE=readInt32LE;function readUint32LE(fr,br){return br===void 0&&(br=0),(fr[br+3]<<24|fr[br+2]<<16|fr[br+1]<<8|fr[br])>>>0}binary.readUint32LE=readUint32LE;function writeUint32BE(fr,br,wr){return br===void 0&&(br=new Uint8Array(4)),wr===void 0&&(wr=0),br[wr+0]=fr>>>24,br[wr+1]=fr>>>16,br[wr+2]=fr>>>8,br[wr+3]=fr>>>0,br}binary.writeUint32BE=writeUint32BE;binary.writeInt32BE=writeUint32BE;function writeUint32LE(fr,br,wr){return br===void 0&&(br=new Uint8Array(4)),wr===void 0&&(wr=0),br[wr+0]=fr>>>0,br[wr+1]=fr>>>8,br[wr+2]=fr>>>16,br[wr+3]=fr>>>24,br}binary.writeUint32LE=writeUint32LE;binary.writeInt32LE=writeUint32LE;function readInt64BE(fr,br){br===void 0&&(br=0);var wr=readInt32BE(fr,br),Er=readInt32BE(fr,br+4);return wr*4294967296+Er-(Er>>31)*4294967296}binary.readInt64BE=readInt64BE;function readUint64BE(fr,br){br===void 0&&(br=0);var wr=readUint32BE(fr,br),Er=readUint32BE(fr,br+4);return wr*4294967296+Er}binary.readUint64BE=readUint64BE;function readInt64LE(fr,br){br===void 0&&(br=0);var wr=readInt32LE(fr,br),Er=readInt32LE(fr,br+4);return Er*4294967296+wr-(wr>>31)*4294967296}binary.readInt64LE=readInt64LE;function readUint64LE(fr,br){br===void 0&&(br=0);var wr=readUint32LE(fr,br),Er=readUint32LE(fr,br+4);return Er*4294967296+wr}binary.readUint64LE=readUint64LE;function writeUint64BE(fr,br,wr){return br===void 0&&(br=new Uint8Array(8)),wr===void 0&&(wr=0),writeUint32BE(fr/4294967296>>>0,br,wr),writeUint32BE(fr>>>0,br,wr+4),br}binary.writeUint64BE=writeUint64BE;binary.writeInt64BE=writeUint64BE;function writeUint64LE(fr,br,wr){return br===void 0&&(br=new Uint8Array(8)),wr===void 0&&(wr=0),writeUint32LE(fr>>>0,br,wr),writeUint32LE(fr/4294967296>>>0,br,wr+4),br}binary.writeUint64LE=writeUint64LE;binary.writeInt64LE=writeUint64LE;function readUintBE(fr,br,wr){if(wr===void 0&&(wr=0),fr%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(fr/8>br.length-wr)throw new Error("readUintBE: array is too short for the given bitLength");for(var Er=0,kr=1,jr=fr/8+wr-1;jr>=wr;jr--)Er+=br[jr]*kr,kr*=256;return Er}binary.readUintBE=readUintBE;function readUintLE(fr,br,wr){if(wr===void 0&&(wr=0),fr%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(fr/8>br.length-wr)throw new Error("readUintLE: array is too short for the given bitLength");for(var Er=0,kr=1,jr=wr;jr=Er;jr--)wr[jr]=br/kr&255,kr*=256;return wr}binary.writeUintBE=writeUintBE;function writeUintLE(fr,br,wr,Er){if(wr===void 0&&(wr=new Uint8Array(fr/8)),Er===void 0&&(Er=0),fr%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!int_1.isSafeInteger(br))throw new Error("writeUintLE value must be an integer");for(var kr=1,jr=Er;jr>>16|Yr<<16,no=no+Yr|0,_i^=no,_i=_i>>>20|_i<<12,Yn=Yn+ro|0,Sn^=Yn,Sn=Sn>>>16|Sn<<16,$a=$a+Sn|0,ro^=$a,ro=ro>>>20|ro<<12,ga=ga+to|0,An^=ga,An=An>>>16|An<<16,Rn=Rn+An|0,to^=Rn,to=to>>>20|to<<12,na=na+io|0,Pn^=na,Pn=Pn>>>16|Pn<<16,Gr=Gr+Pn|0,io^=Gr,io=io>>>20|io<<12,ga=ga+to|0,An^=ga,An=An>>>24|An<<8,Rn=Rn+An|0,to^=Rn,to=to>>>25|to<<7,na=na+io|0,Pn^=na,Pn=Pn>>>24|Pn<<8,Gr=Gr+Pn|0,io^=Gr,io=io>>>25|io<<7,Yn=Yn+ro|0,Sn^=Yn,Sn=Sn>>>24|Sn<<8,$a=$a+Sn|0,ro^=$a,ro=ro>>>25|ro<<7,jn=jn+_i|0,Yr^=jn,Yr=Yr>>>24|Yr<<8,no=no+Yr|0,_i^=no,_i=_i>>>25|_i<<7,jn=jn+ro|0,Pn^=jn,Pn=Pn>>>16|Pn<<16,Rn=Rn+Pn|0,ro^=Rn,ro=ro>>>20|ro<<12,Yn=Yn+to|0,Yr^=Yn,Yr=Yr>>>16|Yr<<16,Gr=Gr+Yr|0,to^=Gr,to=to>>>20|to<<12,ga=ga+io|0,Sn^=ga,Sn=Sn>>>16|Sn<<16,no=no+Sn|0,io^=no,io=io>>>20|io<<12,na=na+_i|0,An^=na,An=An>>>16|An<<16,$a=$a+An|0,_i^=$a,_i=_i>>>20|_i<<12,ga=ga+io|0,Sn^=ga,Sn=Sn>>>24|Sn<<8,no=no+Sn|0,io^=no,io=io>>>25|io<<7,na=na+_i|0,An^=na,An=An>>>24|An<<8,$a=$a+An|0,_i^=$a,_i=_i>>>25|_i<<7,Yn=Yn+to|0,Yr^=Yn,Yr=Yr>>>24|Yr<<8,Gr=Gr+Yr|0,to^=Gr,to=to>>>25|to<<7,jn=jn+ro|0,Pn^=jn,Pn=Pn>>>24|Pn<<8,Rn=Rn+Pn|0,ro^=Rn,ro=ro>>>25|ro<<7;binary_1.writeUint32LE(jn+Er|0,fr,0),binary_1.writeUint32LE(Yn+kr|0,fr,4),binary_1.writeUint32LE(ga+jr|0,fr,8),binary_1.writeUint32LE(na+Br|0,fr,12),binary_1.writeUint32LE(_i+qr|0,fr,16),binary_1.writeUint32LE(ro+Wr|0,fr,20),binary_1.writeUint32LE(to+Vr|0,fr,24),binary_1.writeUint32LE(io+Hr|0,fr,28),binary_1.writeUint32LE(no+Zr|0,fr,32),binary_1.writeUint32LE($a+Jr|0,fr,36),binary_1.writeUint32LE(Rn+Xr|0,fr,40),binary_1.writeUint32LE(Gr+En|0,fr,44),binary_1.writeUint32LE(Yr+wn|0,fr,48),binary_1.writeUint32LE(Sn+$n|0,fr,52),binary_1.writeUint32LE(An+Tn|0,fr,56),binary_1.writeUint32LE(Pn+In|0,fr,60)}function streamXOR(fr,br,wr,Er,kr){if(kr===void 0&&(kr=0),fr.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(Er.length>>=8,br++;if(Er>0)throw new Error("ChaCha: counter overflow")}var poly1305={},constantTime={};Object.defineProperty(constantTime,"__esModule",{value:!0});function select(fr,br,wr){return~(fr-1)&br|fr-1&wr}constantTime.select=select;function lessOrEqual(fr,br){return(fr|0)-(br|0)-1>>>31&1}constantTime.lessOrEqual=lessOrEqual;function compare(fr,br){if(fr.length!==br.length)return 0;for(var wr=0,Er=0;Er>>8}constantTime.compare=compare;function equal(fr,br){return fr.length===0||br.length===0?!1:compare(fr,br)!==0}constantTime.equal=equal;(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});var br=constantTime,wr=wipe$1;fr.DIGEST_LENGTH=16;var Er=function(){function Br(qr){this.digestLength=fr.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var Wr=qr[0]|qr[1]<<8;this._r[0]=Wr&8191;var Vr=qr[2]|qr[3]<<8;this._r[1]=(Wr>>>13|Vr<<3)&8191;var Hr=qr[4]|qr[5]<<8;this._r[2]=(Vr>>>10|Hr<<6)&7939;var Zr=qr[6]|qr[7]<<8;this._r[3]=(Hr>>>7|Zr<<9)&8191;var Jr=qr[8]|qr[9]<<8;this._r[4]=(Zr>>>4|Jr<<12)&255,this._r[5]=Jr>>>1&8190;var Xr=qr[10]|qr[11]<<8;this._r[6]=(Jr>>>14|Xr<<2)&8191;var En=qr[12]|qr[13]<<8;this._r[7]=(Xr>>>11|En<<5)&8065;var wn=qr[14]|qr[15]<<8;this._r[8]=(En>>>8|wn<<8)&8191,this._r[9]=wn>>>5&127,this._pad[0]=qr[16]|qr[17]<<8,this._pad[1]=qr[18]|qr[19]<<8,this._pad[2]=qr[20]|qr[21]<<8,this._pad[3]=qr[22]|qr[23]<<8,this._pad[4]=qr[24]|qr[25]<<8,this._pad[5]=qr[26]|qr[27]<<8,this._pad[6]=qr[28]|qr[29]<<8,this._pad[7]=qr[30]|qr[31]<<8}return Br.prototype._blocks=function(qr,Wr,Vr){for(var Hr=this._fin?0:2048,Zr=this._h[0],Jr=this._h[1],Xr=this._h[2],En=this._h[3],wn=this._h[4],$n=this._h[5],Tn=this._h[6],In=this._h[7],jn=this._h[8],Yn=this._h[9],ga=this._r[0],na=this._r[1],_i=this._r[2],ro=this._r[3],to=this._r[4],io=this._r[5],no=this._r[6],$a=this._r[7],Rn=this._r[8],Gr=this._r[9];Vr>=16;){var Yr=qr[Wr+0]|qr[Wr+1]<<8;Zr+=Yr&8191;var Sn=qr[Wr+2]|qr[Wr+3]<<8;Jr+=(Yr>>>13|Sn<<3)&8191;var An=qr[Wr+4]|qr[Wr+5]<<8;Xr+=(Sn>>>10|An<<6)&8191;var Pn=qr[Wr+6]|qr[Wr+7]<<8;En+=(An>>>7|Pn<<9)&8191;var Nn=qr[Wr+8]|qr[Wr+9]<<8;wn+=(Pn>>>4|Nn<<12)&8191,$n+=Nn>>>1&8191;var zn=qr[Wr+10]|qr[Wr+11]<<8;Tn+=(Nn>>>14|zn<<2)&8191;var On=qr[Wr+12]|qr[Wr+13]<<8;In+=(zn>>>11|On<<5)&8191;var _n=qr[Wr+14]|qr[Wr+15]<<8;jn+=(On>>>8|_n<<8)&8191,Yn+=_n>>>5|Hr;var Zn=0,oo=Zn;oo+=Zr*ga,oo+=Jr*(5*Gr),oo+=Xr*(5*Rn),oo+=En*(5*$a),oo+=wn*(5*no),Zn=oo>>>13,oo&=8191,oo+=$n*(5*io),oo+=Tn*(5*to),oo+=In*(5*ro),oo+=jn*(5*_i),oo+=Yn*(5*na),Zn+=oo>>>13,oo&=8191;var uo=Zn;uo+=Zr*na,uo+=Jr*ga,uo+=Xr*(5*Gr),uo+=En*(5*Rn),uo+=wn*(5*$a),Zn=uo>>>13,uo&=8191,uo+=$n*(5*no),uo+=Tn*(5*io),uo+=In*(5*to),uo+=jn*(5*ro),uo+=Yn*(5*_i),Zn+=uo>>>13,uo&=8191;var lo=Zn;lo+=Zr*_i,lo+=Jr*na,lo+=Xr*ga,lo+=En*(5*Gr),lo+=wn*(5*Rn),Zn=lo>>>13,lo&=8191,lo+=$n*(5*$a),lo+=Tn*(5*no),lo+=In*(5*io),lo+=jn*(5*to),lo+=Yn*(5*ro),Zn+=lo>>>13,lo&=8191;var co=Zn;co+=Zr*ro,co+=Jr*_i,co+=Xr*na,co+=En*ga,co+=wn*(5*Gr),Zn=co>>>13,co&=8191,co+=$n*(5*Rn),co+=Tn*(5*$a),co+=In*(5*no),co+=jn*(5*io),co+=Yn*(5*to),Zn+=co>>>13,co&=8191;var so=Zn;so+=Zr*to,so+=Jr*ro,so+=Xr*_i,so+=En*na,so+=wn*ga,Zn=so>>>13,so&=8191,so+=$n*(5*Gr),so+=Tn*(5*Rn),so+=In*(5*$a),so+=jn*(5*no),so+=Yn*(5*io),Zn+=so>>>13,so&=8191;var yo=Zn;yo+=Zr*io,yo+=Jr*to,yo+=Xr*ro,yo+=En*_i,yo+=wn*na,Zn=yo>>>13,yo&=8191,yo+=$n*ga,yo+=Tn*(5*Gr),yo+=In*(5*Rn),yo+=jn*(5*$a),yo+=Yn*(5*no),Zn+=yo>>>13,yo&=8191;var fo=Zn;fo+=Zr*no,fo+=Jr*io,fo+=Xr*to,fo+=En*ro,fo+=wn*_i,Zn=fo>>>13,fo&=8191,fo+=$n*na,fo+=Tn*ga,fo+=In*(5*Gr),fo+=jn*(5*Rn),fo+=Yn*(5*$a),Zn+=fo>>>13,fo&=8191;var ho=Zn;ho+=Zr*$a,ho+=Jr*no,ho+=Xr*io,ho+=En*to,ho+=wn*ro,Zn=ho>>>13,ho&=8191,ho+=$n*_i,ho+=Tn*na,ho+=In*ga,ho+=jn*(5*Gr),ho+=Yn*(5*Rn),Zn+=ho>>>13,ho&=8191;var vo=Zn;vo+=Zr*Rn,vo+=Jr*$a,vo+=Xr*no,vo+=En*io,vo+=wn*to,Zn=vo>>>13,vo&=8191,vo+=$n*ro,vo+=Tn*_i,vo+=In*na,vo+=jn*ga,vo+=Yn*(5*Gr),Zn+=vo>>>13,vo&=8191;var Io=Zn;Io+=Zr*Gr,Io+=Jr*Rn,Io+=Xr*$a,Io+=En*no,Io+=wn*io,Zn=Io>>>13,Io&=8191,Io+=$n*to,Io+=Tn*ro,Io+=In*_i,Io+=jn*na,Io+=Yn*ga,Zn+=Io>>>13,Io&=8191,Zn=(Zn<<2)+Zn|0,Zn=Zn+oo|0,oo=Zn&8191,Zn=Zn>>>13,uo+=Zn,Zr=oo,Jr=uo,Xr=lo,En=co,wn=so,$n=yo,Tn=fo,In=ho,jn=vo,Yn=Io,Wr+=16,Vr-=16}this._h[0]=Zr,this._h[1]=Jr,this._h[2]=Xr,this._h[3]=En,this._h[4]=wn,this._h[5]=$n,this._h[6]=Tn,this._h[7]=In,this._h[8]=jn,this._h[9]=Yn},Br.prototype.finish=function(qr,Wr){Wr===void 0&&(Wr=0);var Vr=new Uint16Array(10),Hr,Zr,Jr,Xr;if(this._leftover){for(Xr=this._leftover,this._buffer[Xr++]=1;Xr<16;Xr++)this._buffer[Xr]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(Hr=this._h[1]>>>13,this._h[1]&=8191,Xr=2;Xr<10;Xr++)this._h[Xr]+=Hr,Hr=this._h[Xr]>>>13,this._h[Xr]&=8191;for(this._h[0]+=Hr*5,Hr=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=Hr,Hr=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=Hr,Vr[0]=this._h[0]+5,Hr=Vr[0]>>>13,Vr[0]&=8191,Xr=1;Xr<10;Xr++)Vr[Xr]=this._h[Xr]+Hr,Hr=Vr[Xr]>>>13,Vr[Xr]&=8191;for(Vr[9]-=8192,Zr=(Hr^1)-1,Xr=0;Xr<10;Xr++)Vr[Xr]&=Zr;for(Zr=~Zr,Xr=0;Xr<10;Xr++)this._h[Xr]=this._h[Xr]&Zr|Vr[Xr];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,Jr=this._h[0]+this._pad[0],this._h[0]=Jr&65535,Xr=1;Xr<8;Xr++)Jr=(this._h[Xr]+this._pad[Xr]|0)+(Jr>>>16)|0,this._h[Xr]=Jr&65535;return qr[Wr+0]=this._h[0]>>>0,qr[Wr+1]=this._h[0]>>>8,qr[Wr+2]=this._h[1]>>>0,qr[Wr+3]=this._h[1]>>>8,qr[Wr+4]=this._h[2]>>>0,qr[Wr+5]=this._h[2]>>>8,qr[Wr+6]=this._h[3]>>>0,qr[Wr+7]=this._h[3]>>>8,qr[Wr+8]=this._h[4]>>>0,qr[Wr+9]=this._h[4]>>>8,qr[Wr+10]=this._h[5]>>>0,qr[Wr+11]=this._h[5]>>>8,qr[Wr+12]=this._h[6]>>>0,qr[Wr+13]=this._h[6]>>>8,qr[Wr+14]=this._h[7]>>>0,qr[Wr+15]=this._h[7]>>>8,this._finished=!0,this},Br.prototype.update=function(qr){var Wr=0,Vr=qr.length,Hr;if(this._leftover){Hr=16-this._leftover,Hr>Vr&&(Hr=Vr);for(var Zr=0;Zr=16&&(Hr=Vr-Vr%16,this._blocks(qr,Wr,Hr),Wr+=Hr,Vr-=Hr),Vr){for(var Zr=0;Zr16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var Xr=new Uint8Array(16);Xr.set(Vr,Xr.length-Vr.length);var En=new Uint8Array(32);br.stream(this._key,Xr,En,4);var wn=Hr.length+this.tagLength,$n;if(Jr){if(Jr.length!==wn)throw new Error("ChaCha20Poly1305: incorrect destination length");$n=Jr}else $n=new Uint8Array(wn);return br.streamXOR(this._key,Xr,Hr,$n,4),this._authenticate($n.subarray($n.length-this.tagLength,$n.length),En,$n.subarray(0,$n.length-this.tagLength),Zr),Er.wipe(Xr),$n},Wr.prototype.open=function(Vr,Hr,Zr,Jr){if(Vr.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(Hr.length0&&Xr.update(Br.subarray(Jr.length%16))),Xr.update(Zr),Zr.length%16>0&&Xr.update(Br.subarray(Zr.length%16));var En=new Uint8Array(8);Jr&&kr.writeUint64LE(Jr.length,En),Xr.update(En),kr.writeUint64LE(Zr.length,En),Xr.update(En);for(var wn=Xr.digest(),$n=0;$nthis.blockSize?this._inner.update(wr).finish(Er).clean():Er.set(wr);for(var kr=0;kr1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},fr.prototype.expand=function(br){for(var wr=new Uint8Array(br),Er=0;Er256)throw new Error("randomString charset is too long");let Jr="";const Xr=Hr.length,En=256-256%Xr;for(;Vr>0;){const wn=kr(Math.ceil(Vr*256/En),Zr);for(let $n=0;$n0;$n++){const Tn=wn[$n];Tn0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=Wr[Hr++],Vr--;this._bufferLength===this.blockSize&&(jr(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(Vr>=this.blockSize&&(Hr=jr(this._temp,this._state,Wr,Hr,Vr),Vr%=this.blockSize);Vr>0;)this._buffer[this._bufferLength++]=Wr[Hr++],Vr--;return this},qr.prototype.finish=function(Wr){if(!this._finished){var Vr=this._bytesHashed,Hr=this._bufferLength,Zr=Vr/536870912|0,Jr=Vr<<3,Xr=Vr%64<56?64:128;this._buffer[Hr]=128;for(var En=Hr+1;En0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},qr.prototype.restoreState=function(Wr){return this._state.set(Wr.state),this._bufferLength=Wr.bufferLength,Wr.buffer&&this._buffer.set(Wr.buffer),this._bytesHashed=Wr.bytesHashed,this._finished=!1,this},qr.prototype.cleanSavedState=function(Wr){wr.wipe(Wr.state),Wr.buffer&&wr.wipe(Wr.buffer),Wr.bufferLength=0,Wr.bytesHashed=0},qr}();fr.SHA256=Er;var kr=new Int32Array([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]);function jr(qr,Wr,Vr,Hr,Zr){for(;Zr>=64;){for(var Jr=Wr[0],Xr=Wr[1],En=Wr[2],wn=Wr[3],$n=Wr[4],Tn=Wr[5],In=Wr[6],jn=Wr[7],Yn=0;Yn<16;Yn++){var ga=Hr+Yn*4;qr[Yn]=br.readUint32BE(Vr,ga)}for(var Yn=16;Yn<64;Yn++){var na=qr[Yn-2],_i=(na>>>17|na<<15)^(na>>>19|na<<13)^na>>>10;na=qr[Yn-15];var ro=(na>>>7|na<<25)^(na>>>18|na<<14)^na>>>3;qr[Yn]=(_i+qr[Yn-7]|0)+(ro+qr[Yn-16]|0)}for(var Yn=0;Yn<64;Yn++){var _i=((($n>>>6|$n<<26)^($n>>>11|$n<<21)^($n>>>25|$n<<7))+($n&Tn^~$n&In)|0)+(jn+(kr[Yn]+qr[Yn]|0)|0)|0,ro=((Jr>>>2|Jr<<30)^(Jr>>>13|Jr<<19)^(Jr>>>22|Jr<<10))+(Jr&Xr^Jr&En^Xr&En)|0;jn=In,In=Tn,Tn=$n,$n=wn+_i|0,wn=En,En=Xr,Xr=Jr,Jr=_i+ro|0}Wr[0]+=Jr,Wr[1]+=Xr,Wr[2]+=En,Wr[3]+=wn,Wr[4]+=$n,Wr[5]+=Tn,Wr[6]+=In,Wr[7]+=jn,Hr+=64,Zr-=64}return Hr}function Br(qr){var Wr=new Er;Wr.update(qr);var Vr=Wr.digest();return Wr.clean(),Vr}fr.hash=Br})(sha256);var x25519={};(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.sharedKey=fr.generateKeyPair=fr.generateKeyPairFromSeed=fr.scalarMultBase=fr.scalarMult=fr.SHARED_KEY_LENGTH=fr.SECRET_KEY_LENGTH=fr.PUBLIC_KEY_LENGTH=void 0;const br=random,wr=wipe$1;fr.PUBLIC_KEY_LENGTH=32,fr.SECRET_KEY_LENGTH=32,fr.SHARED_KEY_LENGTH=32;function Er(Yn){const ga=new Float64Array(16);if(Yn)for(let na=0;na>16&1),na[io-1]&=65535;na[15]=_i[15]-32767-(na[14]>>16&1);const to=na[15]>>16&1;na[14]&=65535,qr(_i,na,1-to)}for(let ro=0;ro<16;ro++)Yn[2*ro]=_i[ro]&255,Yn[2*ro+1]=_i[ro]>>8}function Vr(Yn,ga){for(let na=0;na<16;na++)Yn[na]=ga[2*na]+(ga[2*na+1]<<8);Yn[15]&=32767}function Hr(Yn,ga,na){for(let _i=0;_i<16;_i++)Yn[_i]=ga[_i]+na[_i]}function Zr(Yn,ga,na){for(let _i=0;_i<16;_i++)Yn[_i]=ga[_i]-na[_i]}function Jr(Yn,ga,na){let _i,ro,to=0,io=0,no=0,$a=0,Rn=0,Gr=0,Yr=0,Sn=0,An=0,Pn=0,Nn=0,zn=0,On=0,_n=0,Zn=0,oo=0,uo=0,lo=0,co=0,so=0,yo=0,fo=0,ho=0,vo=0,Io=0,Ro=0,To=0,Wo=0,qo=0,Zo=0,Qo=0,jo=na[0],No=na[1],Tl=na[2],Fo=na[3],Lo=na[4],Rl=na[5],_c=na[6],Ko=na[7],zl=na[8],Sl=na[9],Eo=na[10],bo=na[11],go=na[12],Co=na[13],zo=na[14],Do=na[15];_i=ga[0],to+=_i*jo,io+=_i*No,no+=_i*Tl,$a+=_i*Fo,Rn+=_i*Lo,Gr+=_i*Rl,Yr+=_i*_c,Sn+=_i*Ko,An+=_i*zl,Pn+=_i*Sl,Nn+=_i*Eo,zn+=_i*bo,On+=_i*go,_n+=_i*Co,Zn+=_i*zo,oo+=_i*Do,_i=ga[1],io+=_i*jo,no+=_i*No,$a+=_i*Tl,Rn+=_i*Fo,Gr+=_i*Lo,Yr+=_i*Rl,Sn+=_i*_c,An+=_i*Ko,Pn+=_i*zl,Nn+=_i*Sl,zn+=_i*Eo,On+=_i*bo,_n+=_i*go,Zn+=_i*Co,oo+=_i*zo,uo+=_i*Do,_i=ga[2],no+=_i*jo,$a+=_i*No,Rn+=_i*Tl,Gr+=_i*Fo,Yr+=_i*Lo,Sn+=_i*Rl,An+=_i*_c,Pn+=_i*Ko,Nn+=_i*zl,zn+=_i*Sl,On+=_i*Eo,_n+=_i*bo,Zn+=_i*go,oo+=_i*Co,uo+=_i*zo,lo+=_i*Do,_i=ga[3],$a+=_i*jo,Rn+=_i*No,Gr+=_i*Tl,Yr+=_i*Fo,Sn+=_i*Lo,An+=_i*Rl,Pn+=_i*_c,Nn+=_i*Ko,zn+=_i*zl,On+=_i*Sl,_n+=_i*Eo,Zn+=_i*bo,oo+=_i*go,uo+=_i*Co,lo+=_i*zo,co+=_i*Do,_i=ga[4],Rn+=_i*jo,Gr+=_i*No,Yr+=_i*Tl,Sn+=_i*Fo,An+=_i*Lo,Pn+=_i*Rl,Nn+=_i*_c,zn+=_i*Ko,On+=_i*zl,_n+=_i*Sl,Zn+=_i*Eo,oo+=_i*bo,uo+=_i*go,lo+=_i*Co,co+=_i*zo,so+=_i*Do,_i=ga[5],Gr+=_i*jo,Yr+=_i*No,Sn+=_i*Tl,An+=_i*Fo,Pn+=_i*Lo,Nn+=_i*Rl,zn+=_i*_c,On+=_i*Ko,_n+=_i*zl,Zn+=_i*Sl,oo+=_i*Eo,uo+=_i*bo,lo+=_i*go,co+=_i*Co,so+=_i*zo,yo+=_i*Do,_i=ga[6],Yr+=_i*jo,Sn+=_i*No,An+=_i*Tl,Pn+=_i*Fo,Nn+=_i*Lo,zn+=_i*Rl,On+=_i*_c,_n+=_i*Ko,Zn+=_i*zl,oo+=_i*Sl,uo+=_i*Eo,lo+=_i*bo,co+=_i*go,so+=_i*Co,yo+=_i*zo,fo+=_i*Do,_i=ga[7],Sn+=_i*jo,An+=_i*No,Pn+=_i*Tl,Nn+=_i*Fo,zn+=_i*Lo,On+=_i*Rl,_n+=_i*_c,Zn+=_i*Ko,oo+=_i*zl,uo+=_i*Sl,lo+=_i*Eo,co+=_i*bo,so+=_i*go,yo+=_i*Co,fo+=_i*zo,ho+=_i*Do,_i=ga[8],An+=_i*jo,Pn+=_i*No,Nn+=_i*Tl,zn+=_i*Fo,On+=_i*Lo,_n+=_i*Rl,Zn+=_i*_c,oo+=_i*Ko,uo+=_i*zl,lo+=_i*Sl,co+=_i*Eo,so+=_i*bo,yo+=_i*go,fo+=_i*Co,ho+=_i*zo,vo+=_i*Do,_i=ga[9],Pn+=_i*jo,Nn+=_i*No,zn+=_i*Tl,On+=_i*Fo,_n+=_i*Lo,Zn+=_i*Rl,oo+=_i*_c,uo+=_i*Ko,lo+=_i*zl,co+=_i*Sl,so+=_i*Eo,yo+=_i*bo,fo+=_i*go,ho+=_i*Co,vo+=_i*zo,Io+=_i*Do,_i=ga[10],Nn+=_i*jo,zn+=_i*No,On+=_i*Tl,_n+=_i*Fo,Zn+=_i*Lo,oo+=_i*Rl,uo+=_i*_c,lo+=_i*Ko,co+=_i*zl,so+=_i*Sl,yo+=_i*Eo,fo+=_i*bo,ho+=_i*go,vo+=_i*Co,Io+=_i*zo,Ro+=_i*Do,_i=ga[11],zn+=_i*jo,On+=_i*No,_n+=_i*Tl,Zn+=_i*Fo,oo+=_i*Lo,uo+=_i*Rl,lo+=_i*_c,co+=_i*Ko,so+=_i*zl,yo+=_i*Sl,fo+=_i*Eo,ho+=_i*bo,vo+=_i*go,Io+=_i*Co,Ro+=_i*zo,To+=_i*Do,_i=ga[12],On+=_i*jo,_n+=_i*No,Zn+=_i*Tl,oo+=_i*Fo,uo+=_i*Lo,lo+=_i*Rl,co+=_i*_c,so+=_i*Ko,yo+=_i*zl,fo+=_i*Sl,ho+=_i*Eo,vo+=_i*bo,Io+=_i*go,Ro+=_i*Co,To+=_i*zo,Wo+=_i*Do,_i=ga[13],_n+=_i*jo,Zn+=_i*No,oo+=_i*Tl,uo+=_i*Fo,lo+=_i*Lo,co+=_i*Rl,so+=_i*_c,yo+=_i*Ko,fo+=_i*zl,ho+=_i*Sl,vo+=_i*Eo,Io+=_i*bo,Ro+=_i*go,To+=_i*Co,Wo+=_i*zo,qo+=_i*Do,_i=ga[14],Zn+=_i*jo,oo+=_i*No,uo+=_i*Tl,lo+=_i*Fo,co+=_i*Lo,so+=_i*Rl,yo+=_i*_c,fo+=_i*Ko,ho+=_i*zl,vo+=_i*Sl,Io+=_i*Eo,Ro+=_i*bo,To+=_i*go,Wo+=_i*Co,qo+=_i*zo,Zo+=_i*Do,_i=ga[15],oo+=_i*jo,uo+=_i*No,lo+=_i*Tl,co+=_i*Fo,so+=_i*Lo,yo+=_i*Rl,fo+=_i*_c,ho+=_i*Ko,vo+=_i*zl,Io+=_i*Sl,Ro+=_i*Eo,To+=_i*bo,Wo+=_i*go,qo+=_i*Co,Zo+=_i*zo,Qo+=_i*Do,to+=38*uo,io+=38*lo,no+=38*co,$a+=38*so,Rn+=38*yo,Gr+=38*fo,Yr+=38*ho,Sn+=38*vo,An+=38*Io,Pn+=38*Ro,Nn+=38*To,zn+=38*Wo,On+=38*qo,_n+=38*Zo,Zn+=38*Qo,ro=1,_i=to+ro+65535,ro=Math.floor(_i/65536),to=_i-ro*65536,_i=io+ro+65535,ro=Math.floor(_i/65536),io=_i-ro*65536,_i=no+ro+65535,ro=Math.floor(_i/65536),no=_i-ro*65536,_i=$a+ro+65535,ro=Math.floor(_i/65536),$a=_i-ro*65536,_i=Rn+ro+65535,ro=Math.floor(_i/65536),Rn=_i-ro*65536,_i=Gr+ro+65535,ro=Math.floor(_i/65536),Gr=_i-ro*65536,_i=Yr+ro+65535,ro=Math.floor(_i/65536),Yr=_i-ro*65536,_i=Sn+ro+65535,ro=Math.floor(_i/65536),Sn=_i-ro*65536,_i=An+ro+65535,ro=Math.floor(_i/65536),An=_i-ro*65536,_i=Pn+ro+65535,ro=Math.floor(_i/65536),Pn=_i-ro*65536,_i=Nn+ro+65535,ro=Math.floor(_i/65536),Nn=_i-ro*65536,_i=zn+ro+65535,ro=Math.floor(_i/65536),zn=_i-ro*65536,_i=On+ro+65535,ro=Math.floor(_i/65536),On=_i-ro*65536,_i=_n+ro+65535,ro=Math.floor(_i/65536),_n=_i-ro*65536,_i=Zn+ro+65535,ro=Math.floor(_i/65536),Zn=_i-ro*65536,_i=oo+ro+65535,ro=Math.floor(_i/65536),oo=_i-ro*65536,to+=ro-1+37*(ro-1),ro=1,_i=to+ro+65535,ro=Math.floor(_i/65536),to=_i-ro*65536,_i=io+ro+65535,ro=Math.floor(_i/65536),io=_i-ro*65536,_i=no+ro+65535,ro=Math.floor(_i/65536),no=_i-ro*65536,_i=$a+ro+65535,ro=Math.floor(_i/65536),$a=_i-ro*65536,_i=Rn+ro+65535,ro=Math.floor(_i/65536),Rn=_i-ro*65536,_i=Gr+ro+65535,ro=Math.floor(_i/65536),Gr=_i-ro*65536,_i=Yr+ro+65535,ro=Math.floor(_i/65536),Yr=_i-ro*65536,_i=Sn+ro+65535,ro=Math.floor(_i/65536),Sn=_i-ro*65536,_i=An+ro+65535,ro=Math.floor(_i/65536),An=_i-ro*65536,_i=Pn+ro+65535,ro=Math.floor(_i/65536),Pn=_i-ro*65536,_i=Nn+ro+65535,ro=Math.floor(_i/65536),Nn=_i-ro*65536,_i=zn+ro+65535,ro=Math.floor(_i/65536),zn=_i-ro*65536,_i=On+ro+65535,ro=Math.floor(_i/65536),On=_i-ro*65536,_i=_n+ro+65535,ro=Math.floor(_i/65536),_n=_i-ro*65536,_i=Zn+ro+65535,ro=Math.floor(_i/65536),Zn=_i-ro*65536,_i=oo+ro+65535,ro=Math.floor(_i/65536),oo=_i-ro*65536,to+=ro-1+37*(ro-1),Yn[0]=to,Yn[1]=io,Yn[2]=no,Yn[3]=$a,Yn[4]=Rn,Yn[5]=Gr,Yn[6]=Yr,Yn[7]=Sn,Yn[8]=An,Yn[9]=Pn,Yn[10]=Nn,Yn[11]=zn,Yn[12]=On,Yn[13]=_n,Yn[14]=Zn,Yn[15]=oo}function Xr(Yn,ga){Jr(Yn,ga,ga)}function En(Yn,ga){const na=Er();for(let _i=0;_i<16;_i++)na[_i]=ga[_i];for(let _i=253;_i>=0;_i--)Xr(na,na),_i!==2&&_i!==4&&Jr(na,na,ga);for(let _i=0;_i<16;_i++)Yn[_i]=na[_i]}function wn(Yn,ga){const na=new Uint8Array(32),_i=new Float64Array(80),ro=Er(),to=Er(),io=Er(),no=Er(),$a=Er(),Rn=Er();for(let An=0;An<31;An++)na[An]=Yn[An];na[31]=Yn[31]&127|64,na[0]&=248,Vr(_i,ga);for(let An=0;An<16;An++)to[An]=_i[An];ro[0]=no[0]=1;for(let An=254;An>=0;--An){const Pn=na[An>>>3]>>>(An&7)&1;qr(ro,to,Pn),qr(io,no,Pn),Hr($a,ro,io),Zr(ro,ro,io),Hr(io,to,no),Zr(to,to,no),Xr(no,$a),Xr(Rn,ro),Jr(ro,io,ro),Jr(io,to,$a),Hr($a,ro,io),Zr(ro,ro,io),Xr(to,ro),Zr(io,no,Rn),Jr(ro,io,jr),Hr(ro,ro,no),Jr(io,io,ro),Jr(ro,no,Rn),Jr(no,to,_i),Xr(to,$a),qr(ro,to,Pn),qr(io,no,Pn)}for(let An=0;An<16;An++)_i[An+16]=ro[An],_i[An+32]=io[An],_i[An+48]=to[An],_i[An+64]=no[An];const Gr=_i.subarray(32),Yr=_i.subarray(16);En(Gr,Gr),Jr(Yr,Yr,Gr);const Sn=new Uint8Array(32);return Wr(Sn,Yr),Sn}fr.scalarMult=wn;function $n(Yn){return wn(Yn,kr)}fr.scalarMultBase=$n;function Tn(Yn){if(Yn.length!==fr.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${fr.SECRET_KEY_LENGTH} bytes`);const ga=new Uint8Array(Yn);return{publicKey:$n(ga),secretKey:ga}}fr.generateKeyPairFromSeed=Tn;function In(Yn){const ga=(0,br.randomBytes)(32,Yn),na=Tn(ga);return(0,wr.wipe)(ga),na}fr.generateKeyPair=In;function jn(Yn,ga,na=!1){if(Yn.length!==fr.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(ga.length!==fr.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const _i=wn(Yn,ga);if(na){let ro=0;for(let to=0;to<_i.length;to++)ro|=_i[to];if(ro===0)throw new Error("X25519: invalid shared key")}return _i}fr.sharedKey=jn})(x25519);function asUint8Array(fr){return globalThis.Buffer!=null?new Uint8Array(fr.buffer,fr.byteOffset,fr.byteLength):fr}function allocUnsafe(fr=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?asUint8Array(globalThis.Buffer.allocUnsafe(fr)):new Uint8Array(fr)}function concat(fr,br){br||(br=fr.reduce((kr,jr)=>kr+jr.length,0));const wr=allocUnsafe(br);let Er=0;for(const kr of fr)wr.set(kr,Er),Er+=kr.length;return asUint8Array(wr)}function base$4(fr,br){if(fr.length>=255)throw new TypeError("Alphabet too long");for(var wr=new Uint8Array(256),Er=0;Er>>0,Yn=new Uint8Array(jn);Tn!==In;){for(var ga=En[Tn],na=0,_i=jn-1;(ga!==0||na<$n)&&_i!==-1;_i--,na++)ga+=256*Yn[_i]>>>0,Yn[_i]=ga%qr>>>0,ga=ga/qr>>>0;if(ga!==0)throw new Error("Non-zero carry");$n=na,Tn++}for(var ro=jn-$n;ro!==jn&&Yn[ro]===0;)ro++;for(var to=Wr.repeat(wn);ro>>0,jn=new Uint8Array(In);En[wn];){var Yn=wr[En.charCodeAt(wn)];if(Yn===255)return;for(var ga=0,na=In-1;(Yn!==0||ga>>0,jn[na]=Yn%256>>>0,Yn=Yn/256>>>0;if(Yn!==0)throw new Error("Non-zero carry");Tn=ga,wn++}if(En[wn]!==" "){for(var _i=In-Tn;_i!==In&&jn[_i]===0;)_i++;for(var ro=new Uint8Array($n+(In-_i)),to=$n;_i!==In;)ro[to++]=jn[_i++];return ro}}}function Xr(En){var wn=Jr(En);if(wn)return wn;throw new Error(`Non-${br} character`)}return{encode:Zr,decodeUnsafe:Jr,decode:Xr}}var src$4=base$4,_brrp__multiformats_scope_baseX=src$4;const coerce$3=fr=>{if(fr instanceof Uint8Array&&fr.constructor.name==="Uint8Array")return fr;if(fr instanceof ArrayBuffer)return new Uint8Array(fr);if(ArrayBuffer.isView(fr))return new Uint8Array(fr.buffer,fr.byteOffset,fr.byteLength);throw new Error("Unknown type, must be binary type")},fromString$1=fr=>new TextEncoder().encode(fr),toString$1=fr=>new TextDecoder().decode(fr);class Encoder{constructor(br,wr,Er){this.name=br,this.prefix=wr,this.baseEncode=Er}encode(br){if(br instanceof Uint8Array)return`${this.prefix}${this.baseEncode(br)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(br,wr,Er){if(this.name=br,this.prefix=wr,wr.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=wr.codePointAt(0),this.baseDecode=Er}decode(br){if(typeof br=="string"){if(br.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(br)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(br.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(br){return or$2(this,br)}}class ComposedDecoder{constructor(br){this.decoders=br}or(br){return or$2(this,br)}decode(br){const wr=br[0],Er=this.decoders[wr];if(Er)return Er.decode(br);throw RangeError(`Unable to decode multibase string ${JSON.stringify(br)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const or$2=(fr,br)=>new ComposedDecoder({...fr.decoders||{[fr.prefix]:fr},...br.decoders||{[br.prefix]:br}});class Codec{constructor(br,wr,Er,kr){this.name=br,this.prefix=wr,this.baseEncode=Er,this.baseDecode=kr,this.encoder=new Encoder(br,wr,Er),this.decoder=new Decoder(br,wr,kr)}encode(br){return this.encoder.encode(br)}decode(br){return this.decoder.decode(br)}}const from=({name:fr,prefix:br,encode:wr,decode:Er})=>new Codec(fr,br,wr,Er),baseX=({prefix:fr,name:br,alphabet:wr})=>{const{encode:Er,decode:kr}=_brrp__multiformats_scope_baseX(wr,br);return from({prefix:fr,name:br,encode:Er,decode:jr=>coerce$3(kr(jr))})},decode$2=(fr,br,wr,Er)=>{const kr={};for(let Hr=0;Hr=8&&(qr-=8,Br[Vr++]=255&Wr>>qr)}if(qr>=wr||255&Wr<<8-qr)throw new SyntaxError("Unexpected end of data");return Br},encode$1=(fr,br,wr)=>{const Er=br[br.length-1]==="=",kr=(1<wr;)Br-=wr,jr+=br[kr&qr>>Br];if(Br&&(jr+=br[kr&qr<from({prefix:br,name:fr,encode(kr){return encode$1(kr,Er,wr)},decode(kr){return decode$2(kr,Er,wr,fr)}}),identity=from({prefix:"\0",name:"identity",encode:fr=>toString$1(fr),decode:fr=>fromString$1(fr)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32hex,base32hexpad,base32hexpadupper,base32hexupper,base32pad,base32padupper,base32upper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$1=Object.freeze(Object.defineProperty({__proto__:null,base64,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),alphabet=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars=alphabet.reduce((fr,br,wr)=>(fr[wr]=br,fr),[]),alphabetCharsToBytes=alphabet.reduce((fr,br,wr)=>(fr[br.codePointAt(0)]=wr,fr),[]);function encode(fr){return fr.reduce((br,wr)=>(br+=alphabetBytesToChars[wr],br),"")}function decode$1(fr){const br=[];for(const wr of fr){const Er=alphabetCharsToBytes[wr.codePointAt(0)];if(Er===void 0)throw new Error(`Non-base256emoji character: ${wr}`);br.push(Er)}return new Uint8Array(br)}const base256emoji=from({prefix:"🚀",name:"base256emoji",encode,decode:decode$1}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases={...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$1,...base256emoji$1};function createCodec(fr,br,wr,Er){return{name:fr,prefix:br,encoder:{name:fr,prefix:br,encode:wr},decoder:{decode:Er}}}const string$3=createCodec("utf8","u",fr=>"u"+new TextDecoder("utf8").decode(fr),fr=>new TextEncoder().encode(fr.substring(1))),ascii=createCodec("ascii","a",fr=>{let br="a";for(let wr=0;wr{fr=fr.substring(1);const br=allocUnsafe(fr.length);for(let wr=0;wr"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new ReactNativeInfo:typeof navigator<"u"?parseUserAgent(navigator.userAgent):getNodeVersion()}function matchUserAgent(fr){return fr!==""&&userAgentRules.reduce(function(br,wr){var Er=wr[0],kr=wr[1];if(br)return br;var jr=kr.exec(fr);return!!jr&&[Er,jr]},!1)}function parseUserAgent(fr){var br=matchUserAgent(fr);if(!br)return null;var wr=br[0],Er=br[1];if(wr==="searchbot")return new BotInfo;var kr=Er[1]&&Er[1].split(".").join("_").split("_").slice(0,3);kr?kr.length=xo)return Qr;var Po=eo-Pm(ao);if(Po<1)return ao;var Mo=ko?um(ko,0,Po).join(""):Qr.slice(0,Po);if(mo===wr)return Mo+ao;if(ko&&(Po+=Mo.length-Po),lv(mo)){if(Qr.slice(Po).search(mo)){var _l,wl=Mo;for(mo.global||(mo=Q0(mo.source,Bu(El.exec(mo))+"g")),mo.lastIndex=0;_l=mo.exec(wl);)var Al=_l.index;Mo=Mo.slice(0,Al===wr?Po:Al)}}else if(Qr.indexOf(kp(mo),Po)!=Po){var Gl=Mo.lastIndexOf(mo);Gl>-1&&(Mo=Mo.slice(0,Gl))}return Mo+ao}function g3(Qr){return Qr=Bu(Qr),Qr&&cu.test(Qr)?Qr.replace(yl,Gv):Qr}var y3=Cm(function(Qr,Cn,eo){return Qr+(eo?" ":"")+Cn.toUpperCase()}),mv=B1("toUpperCase");function _x(Qr,Cn,eo){return Qr=Bu(Qr),Cn=eo?wr:Cn,Cn===wr?Wv(Qr)?Yv(Qr):Ov(Qr):Qr.match(Cn)||[]}var wx=Cu(function(Qr,Cn){try{return pp(Qr,wr,Cn)}catch(eo){return Qy(eo)?eo:new xu(eo)}}),_3=fm(function(Qr,Cn){return Ip(Cn,function(eo){eo=Qp(eo),Xp(Qr,eo,Yy(Qr[eo],Qr))}),Qr});function w3(Qr){var Cn=Qr==null?0:Qr.length,eo=lu();return Qr=Cn?Yu(Qr,function(ao){if(typeof ao[1]!="function")throw new Pp(Br);return[eo(ao[0]),ao[1]]}):[],Cu(function(ao){for(var mo=-1;++moPn)return[];var eo=On,ao=hp(Qr,On);Cn=lu(Cn),Qr-=On;for(var mo=J0(ao,Cn);++eo0||Cn<0)?new Ru(eo):(Qr<0?eo=eo.takeRight(-Qr):Qr&&(eo=eo.drop(Qr)),Cn!==wr&&(Cn=$u(Cn),eo=Cn<0?eo.dropRight(-Cn):eo.take(Cn-Qr)),eo)},Ru.prototype.takeRightWhile=function(Qr){return this.reverse().takeWhile(Qr).reverse()},Ru.prototype.toArray=function(){return this.take(On)},Vp(Ru.prototype,function(Qr,Cn){var eo=/^(?:filter|find|map|reject)|While$/.test(Cn),ao=/^(?:head|last)$/.test(Cn),mo=_o[ao?"take"+(Cn=="last"?"Right":""):Cn],xo=ao||/^find/.test(Cn);mo&&(_o.prototype[Cn]=function(){var ko=this.__wrapped__,Po=ao?[1]:arguments,Mo=ko instanceof Ru,_l=Po[0],wl=Mo||Eu(ko),Al=function(Au){var Pu=mo.apply(_o,im([Au],Po));return ao&&Gl?Pu[0]:Pu};wl&&eo&&typeof _l=="function"&&_l.length!=1&&(Mo=wl=!1);var Gl=this.__chain__,eu=!!this.__actions__.length,uu=xo&&!Gl,ku=Mo&&!eu;if(!xo&&wl){ko=ku?ko:new Ru(this);var du=Qr.apply(ko,Po);return du.__actions__.push({func:R1,args:[Al],thisArg:wr}),new jp(du,Gl)}return uu&&ku?Qr.apply(this,Po):(du=this.thru(Al),uu?ao?du.value()[0]:du.value():du)})}),Ip(["pop","push","shift","sort","splice","unshift"],function(Qr){var Cn=g0[Qr],eo=/^(?:push|sort|unshift)$/.test(Qr)?"tap":"thru",ao=/^(?:pop|shift)$/.test(Qr);_o.prototype[Qr]=function(){var mo=arguments;if(ao&&!this.__chain__){var xo=this.value();return Cn.apply(Eu(xo)?xo:[],mo)}return this[eo](function(ko){return Cn.apply(Eu(ko)?ko:[],mo)})}}),Vp(Ru.prototype,function(Qr,Cn){var eo=_o[Cn];if(eo){var ao=eo.name+"";Nu.call(Nm,ao)||(Nm[ao]=[]),Nm[ao].push({name:Cn,func:eo})}}),Nm[B0(wr,Tn).name]=[{name:"wrapper",func:wr}],Ru.prototype.clone=v_,Ru.prototype.reverse=b_,Ru.prototype.value=__,_o.prototype.at=K2,_o.prototype.chain=G2,_o.prototype.commit=Z2,_o.prototype.next=J2,_o.prototype.plant=X2,_o.prototype.reverse=Q2,_o.prototype.toJSON=_o.prototype.valueOf=_o.prototype.value=eE,_o.prototype.first=_o.prototype.head,Zm&&(_o.prototype[Zm]=Y2),_o},jm=Xv();_p?((_p.exports=jm)._=jm,gp._=jm):Hu._=jm}).call(ge)})(Ui,Ui.exports);var Gg=Object.defineProperty,zg=Object.defineProperties,Kg=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yg=Object.prototype.hasOwnProperty,Zg=Object.prototype.propertyIsEnumerable,ya=(fr,br,wr)=>br in fr?Gg(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,cr=(fr,br)=>{for(var wr in br||(br={}))Yg.call(br,wr)&&ya(fr,wr,br[wr]);if(Ea)for(var wr of Ea(br))Zg.call(br,wr)&&ya(fr,wr,br[wr]);return fr},Jg=(fr,br)=>zg(fr,Kg(br));function ft(fr,br,wr){var Er;const kr=ve(fr);return((Er=br.rpcMap)==null?void 0:Er[kr.reference])||`${Bg}?chainId=${kr.namespace}:${kr.reference}&projectId=${wr}`}function Ct(fr){return fr.includes(":")?fr.split(":")[1]:fr}function Sa(fr){return fr.map(br=>`${br.split(":")[0]}:${br.split(":")[1]}`)}function Xg(fr,br){const wr=Object.keys(br.namespaces).filter(kr=>kr.includes(fr));if(!wr.length)return[];const Er=[];return wr.forEach(kr=>{const jr=br.namespaces[kr].accounts;Er.push(...jr)}),Er}function Oa(fr={},br={}){const wr=Ra(fr),Er=Ra(br);return Ui.exports.merge(wr,Er)}function Ra(fr){var br,wr,Er,kr;const jr={};if(!B$2(fr))return jr;for(const[Br,qr]of Object.entries(fr)){const Wr=oe(Br)?[Br]:qr.chains,Vr=qr.methods||[],Hr=qr.events||[],Zr=qr.rpcMap||{},Jr=en(Br);jr[Jr]=Jg(cr(cr({},jr[Jr]),qr),{chains:S$2(Wr,(br=jr[Jr])==null?void 0:br.chains),methods:S$2(Vr,(wr=jr[Jr])==null?void 0:wr.methods),events:S$2(Hr,(Er=jr[Jr])==null?void 0:Er.events),rpcMap:cr(cr({},Zr),(kr=jr[Jr])==null?void 0:kr.rpcMap)})}return jr}function Qg(fr){return fr.includes(":")?fr.split(":")[2]:fr}function Vg(fr){const br={};for(const[wr,Er]of Object.entries(fr)){const kr=Er.methods||[],jr=Er.events||[],Br=Er.accounts||[],qr=oe(wr)?[wr]:Er.chains?Er.chains:Sa(Er.accounts);br[wr]={chains:qr,methods:kr,events:jr,accounts:Br}}return br}function Wi(fr){return typeof fr=="number"?fr:fr.includes("0x")?parseInt(fr,16):(fr=fr.includes(":")?fr.split(":")[1]:fr,isNaN(Number(fr))?fr:Number(fr))}const ba={},z$2=fr=>ba[fr],Fi=(fr,br)=>{ba[fr]=br};class kg{constructor(br){this.name="polkadot",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getAccounts(){const br=this.namespace.accounts;return br?br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2])||[]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class jg{constructor(br){this.name="eip155",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(br){switch(br.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(br);case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(br.request.method)?await this.client.request(br):this.getHttpProvider().request(br.request)}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(parseInt(br),wr),this.chainId=parseInt(br),this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}createHttpProvider(br,wr){const Er=wr||ft(`${this.name}:${br}`,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=parseInt(Ct(wr));br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}getHttpProvider(){const br=this.chainId,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}async handleSwitchChain(br){var wr,Er;let kr=br.request.params?(wr=br.request.params[0])==null?void 0:wr.chainId:"0x0";kr=kr.startsWith("0x")?kr:`0x${kr}`;const jr=parseInt(kr,16);if(this.isChainApproved(jr))this.setDefaultChain(`${jr}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:br.topic,request:{method:br.request.method,params:[{chainId:kr}]},chainId:(Er=this.namespace.chains)==null?void 0:Er[0]}),this.setDefaultChain(`${jr}`);else throw new Error(`Failed to switch to chain 'eip155:${jr}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(br){return this.namespace.chains.includes(`${this.name}:${br}`)}}class nv{constructor(br){this.name="solana",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class tv{constructor(br){this.name="cosmos",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class ev{constructor(br){this.name="cip34",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{const Er=this.getCardanoRPCUrl(wr),kr=Ct(wr);br[kr]=this.createHttpProvider(kr,Er)}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}getCardanoRPCUrl(br){const wr=this.namespace.rpcMap;if(wr)return wr[br]}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||this.getCardanoRPCUrl(br);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class rv{constructor(br){this.name="elrond",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class iv{constructor(br){this.name="multiversx",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class sv{constructor(br){this.name="near",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){if(this.chainId=br,!this.httpProviders[br]){const Er=wr||ft(`${this.name}:${br}`,this.namespace);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);this.setHttpProvider(br,Er)}this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2])||[]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;br[wr]=this.createHttpProvider(wr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace);return typeof Er>"u"?void 0:new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}var uv=Object.defineProperty,av=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,Ta=Object.getOwnPropertySymbols,fv=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,La=(fr,br,wr)=>br in fr?uv(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,hr=(fr,br)=>{for(var wr in br||(br={}))fv.call(br,wr)&&La(fr,wr,br[wr]);if(Ta)for(var wr of Ta(br))cv.call(br,wr)&&La(fr,wr,br[wr]);return fr},Mi=(fr,br)=>av(fr,ov(br));class lr{constructor(br){this.events=new Ug,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=br,this.logger=typeof(br==null?void 0:br.logger)<"u"&&typeof(br==null?void 0:br.logger)!="string"?br.logger:Hg(k$4({level:(br==null?void 0:br.logger)||Ia})),this.disableProviderPing=(br==null?void 0:br.disableProviderPing)||!1}static async init(br){const wr=new lr(br);return await wr.initialize(),wr}async request(br,wr,Er){const[kr,jr]=this.validateChain(wr);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(kr).request({request:hr({},br),chainId:`${kr}:${jr}`,topic:this.session.topic,expiry:Er})}sendAsync(br,wr,Er,kr){const jr=new Date().getTime();this.request(br,Er,kr).then(Br=>wr(null,formatJsonRpcResult(jr,Br))).catch(Br=>wr(Br,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var br;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(br=this.session)==null?void 0:br.topic,reason:U$1("USER_DISCONNECTED")}),await this.cleanup()}async connect(br){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(br),await this.cleanupPendingPairings(),!br.skipPairing)return await this.pair(br.pairingTopic)}on(br,wr){this.events.on(br,wr)}once(br,wr){this.events.once(br,wr)}removeListener(br,wr){this.events.removeListener(br,wr)}off(br,wr){this.events.off(br,wr)}get isWalletConnect(){return!0}async pair(br){this.shouldAbortPairingAttempt=!1;let wr=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(wr>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:Er,approval:kr}=await this.client.connect({pairingTopic:br,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});Er&&(this.uri=Er,this.events.emit("display_uri",Er)),await kr().then(jr=>{this.session=jr;const Br=Vg(jr.namespaces);this.namespaces=Oa(this.namespaces,Br),this.persist("namespaces",this.namespaces)}).catch(jr=>{if(jr.message!==ae)throw jr;wr++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(br,wr){try{if(!this.session)return;const[Er,kr]=this.validateChain(br);this.getProvider(Er).setDefaultChain(kr,wr)}catch(Er){if(!/Please call connect/.test(Er.message))throw Er}}async cleanupPendingPairings(br={}){this.logger.info("Cleaning up inactive pairings...");const wr=this.client.pairing.getAll();if(k$2(wr)){for(const Er of wr)br.deletePairings?this.client.core.expirer.set(Er.topic,0):await this.client.core.relayer.subscriber.unsubscribe(Er.topic);this.logger.info(`Inactive pairings cleared: ${wr.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const br=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[br]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Q$1.init({logger:this.providerOpts.logger||Ia,relayUrl:this.providerOpts.relayUrl||Fg,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const br=[...new Set(Object.keys(this.session.namespaces).map(wr=>en(wr)))];Fi("client",this.client),Fi("events",this.events),Fi("disableProviderPing",this.disableProviderPing),br.forEach(wr=>{if(!this.session)return;const Er=Xg(wr,this.session),kr=Sa(Er),jr=Oa(this.namespaces,this.optionalNamespaces),Br=Mi(hr({},jr[wr]),{accounts:Er,chains:kr});switch(wr){case"eip155":this.rpcProviders[wr]=new jg({namespace:Br});break;case"solana":this.rpcProviders[wr]=new nv({namespace:Br});break;case"cosmos":this.rpcProviders[wr]=new tv({namespace:Br});break;case"polkadot":this.rpcProviders[wr]=new kg({namespace:Br});break;case"cip34":this.rpcProviders[wr]=new ev({namespace:Br});break;case"elrond":this.rpcProviders[wr]=new rv({namespace:Br});break;case"multiversx":this.rpcProviders[wr]=new iv({namespace:Br});break;case"near":this.rpcProviders[wr]=new sv({namespace:Br});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",br=>{this.events.emit("session_ping",br)}),this.client.on("session_event",br=>{const{params:wr}=br,{event:Er}=wr;if(Er.name==="accountsChanged"){const kr=Er.data;kr&&k$2(kr)&&this.events.emit("accountsChanged",kr.map(Qg))}else if(Er.name==="chainChanged"){const kr=wr.chainId,jr=wr.event.data,Br=en(kr),qr=Wi(kr)!==Wi(jr)?`${Br}:${Wi(jr)}`:kr;this.onChainChanged(qr)}else this.events.emit(Er.name,Er.data);this.events.emit("session_event",br)}),this.client.on("session_update",({topic:br,params:wr})=>{var Er;const{namespaces:kr}=wr,jr=(Er=this.client)==null?void 0:Er.session.get(br);this.session=Mi(hr({},jr),{namespaces:kr}),this.onSessionUpdate(),this.events.emit("session_update",{topic:br,params:wr})}),this.client.on("session_delete",async br=>{await this.cleanup(),this.events.emit("session_delete",br),this.events.emit("disconnect",Mi(hr({},U$1("USER_DISCONNECTED")),{data:br.topic}))}),this.on(Vn.DEFAULT_CHAIN_CHANGED,br=>{this.onChainChanged(br,!0)})}getProvider(br){if(!this.rpcProviders[br])throw new Error(`Provider not found: ${br}`);return this.rpcProviders[br]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(br=>{var wr;this.getProvider(br).updateNamespace((wr=this.session)==null?void 0:wr.namespaces[br])})}setNamespaces(br){const{namespaces:wr,optionalNamespaces:Er,sessionProperties:kr}=br;wr&&Object.keys(wr).length&&(this.namespaces=wr),Er&&Object.keys(Er).length&&(this.optionalNamespaces=Er),this.sessionProperties=kr,this.persist("namespaces",wr),this.persist("optionalNamespaces",Er)}validateChain(br){const[wr,Er]=(br==null?void 0:br.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[wr,Er];if(wr&&!Object.keys(this.namespaces||{}).map(Br=>en(Br)).includes(wr))throw new Error(`Namespace '${wr}' is not configured. Please call connect() first with namespace config.`);if(wr&&Er)return[wr,Er];const kr=en(Object.keys(this.namespaces)[0]),jr=this.rpcProviders[kr].getDefaultChain();return[kr,jr]}async requestAccounts(){const[br]=this.validateChain();return await this.getProvider(br).requestAccounts()}onChainChanged(br,wr=!1){if(!this.namespaces)return;const[Er,kr]=this.validateChain(br);kr&&(wr||this.getProvider(Er).setDefaultChain(kr),this.namespaces[Er]?this.namespaces[Er].defaultChain=kr:this.namespaces[`${Er}:${kr}`]?this.namespaces[`${Er}:${kr}`].defaultChain=kr:this.namespaces[`${Er}:${kr}`]={defaultChain:kr},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",kr))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(br,wr){this.client.core.storage.setItem(`${xa}/${br}`,wr)}async getFromStore(br){return await this.client.core.storage.getItem(`${xa}/${br}`)}}const hv=lr,P$2="wc",S$1="ethereum_provider",$$1=`${P$2}@2:${S$1}:`,j$2="https://rpc.walletconnect.com/v1/",u$2=["eth_sendTransaction","personal_sign"],E$1=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m$2=["chainChanged","accountsChanged"],_$2=["chainChanged","accountsChanged","message","disconnect","connect"];var N$1=Object.defineProperty,q$2=Object.defineProperties,D$2=Object.getOwnPropertyDescriptors,y$2=Object.getOwnPropertySymbols,U=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,O$1=(fr,br,wr)=>br in fr?N$1(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,p$2=(fr,br)=>{for(var wr in br||(br={}))U.call(br,wr)&&O$1(fr,wr,br[wr]);if(y$2)for(var wr of y$2(br))Q.call(br,wr)&&O$1(fr,wr,br[wr]);return fr},M$1=(fr,br)=>q$2(fr,D$2(br));function g$2(fr){return Number(fr[0].split(":")[1])}function f$3(fr){return`0x${fr.toString(16)}`}function L$1(fr){const{chains:br,optionalChains:wr,methods:Er,optionalMethods:kr,events:jr,optionalEvents:Br,rpcMap:qr}=fr;if(!k$6(br))throw new Error("Invalid chains");const Wr={chains:br,methods:Er||u$2,events:jr||m$2,rpcMap:p$2({},br.length?{[g$2(br)]:qr[g$2(br)]}:{})},Vr=jr==null?void 0:jr.filter(Xr=>!m$2.includes(Xr)),Hr=Er==null?void 0:Er.filter(Xr=>!u$2.includes(Xr));if(!wr&&!Br&&!kr&&!(Vr!=null&&Vr.length)&&!(Hr!=null&&Hr.length))return{required:br.length?Wr:void 0};const Zr=(Vr==null?void 0:Vr.length)&&(Hr==null?void 0:Hr.length)||!wr,Jr={chains:[...new Set(Zr?Wr.chains.concat(wr||[]):wr)],methods:[...new Set(Wr.methods.concat(kr!=null&&kr.length?kr:E$1))],events:[...new Set(Wr.events.concat(Br!=null&&Br.length?Br:_$2))],rpcMap:qr};return{required:br.length?Wr:void 0,optional:wr.length?Jr:void 0}}let v$2=class uS{constructor(){this.events=new eventsExports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$$1,this.on=(br,wr)=>(this.events.on(br,wr),this),this.once=(br,wr)=>(this.events.once(br,wr),this),this.removeListener=(br,wr)=>(this.events.removeListener(br,wr),this),this.off=(br,wr)=>(this.events.off(br,wr),this),this.parseAccount=br=>this.isCompatibleChainId(br)?this.parseAccountId(br).address:br,this.signer={},this.rpc={}}static async init(br){const wr=new uS;return await wr.initialize(br),wr}async request(br,wr){return await this.signer.request(br,this.formatChainId(this.chainId),wr)}sendAsync(br,wr,Er){this.signer.sendAsync(br,wr,this.formatChainId(this.chainId),Er)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(br){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(br);const{required:wr,optional:Er}=L$1(this.rpc);try{const kr=await new Promise(async(Br,qr)=>{var Wr;this.rpc.showQrModal&&((Wr=this.modal)==null||Wr.subscribeModal(Vr=>{!Vr.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),qr(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M$1(p$2({namespaces:p$2({},wr&&{[this.namespace]:wr})},Er&&{optionalNamespaces:{[this.namespace]:Er}}),{pairingTopic:br==null?void 0:br.pairingTopic})).then(Vr=>{Br(Vr)}).catch(Vr=>{qr(new Error(Vr.message))})});if(!kr)return;const jr=Un(kr.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:jr),this.setAccounts(jr),this.events.emit("connect",{chainId:f$3(this.chainId)})}catch(kr){throw this.signer.logger.error(kr),kr}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",br=>{const{params:wr}=br,{event:Er}=wr;Er.name==="accountsChanged"?(this.accounts=this.parseAccounts(Er.data),this.events.emit("accountsChanged",this.accounts)):Er.name==="chainChanged"?this.setChainId(this.formatChainId(Er.data)):this.events.emit(Er.name,Er.data),this.events.emit("session_event",br)}),this.signer.on("chainChanged",br=>{const wr=parseInt(br);this.chainId=wr,this.events.emit("chainChanged",f$3(this.chainId)),this.persist()}),this.signer.on("session_update",br=>{this.events.emit("session_update",br)}),this.signer.on("session_delete",br=>{this.reset(),this.events.emit("session_delete",br),this.events.emit("disconnect",M$1(p$2({},U$4("USER_DISCONNECTED")),{data:br.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",br=>{var wr,Er;this.rpc.showQrModal&&((wr=this.modal)==null||wr.closeModal(),(Er=this.modal)==null||Er.openModal({uri:br})),this.events.emit("display_uri",br)})}switchEthereumChain(br){this.request({method:"wallet_switchEthereumChain",params:[{chainId:br.toString(16)}]})}isCompatibleChainId(br){return typeof br=="string"?br.startsWith(`${this.namespace}:`):!1}formatChainId(br){return`${this.namespace}:${br}`}parseChainId(br){return Number(br.split(":")[1])}setChainIds(br){const wr=br.filter(Er=>this.isCompatibleChainId(Er)).map(Er=>this.parseChainId(Er));wr.length&&(this.chainId=wr[0],this.events.emit("chainChanged",f$3(this.chainId)),this.persist())}setChainId(br){if(this.isCompatibleChainId(br)){const wr=this.parseChainId(br);this.chainId=wr,this.switchEthereumChain(wr)}}parseAccountId(br){const[wr,Er,kr]=br.split(":");return{chainId:`${wr}:${Er}`,address:kr}}setAccounts(br){this.accounts=br.filter(wr=>this.parseChainId(this.parseAccountId(wr).chainId)===this.chainId).map(wr=>this.parseAccountId(wr).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(br){var wr,Er;const kr=(wr=br==null?void 0:br.chains)!=null?wr:[],jr=(Er=br==null?void 0:br.optionalChains)!=null?Er:[],Br=kr.concat(jr);if(!Br.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const qr=kr.length?(br==null?void 0:br.methods)||u$2:[],Wr=kr.length?(br==null?void 0:br.events)||m$2:[],Vr=(br==null?void 0:br.optionalMethods)||[],Hr=(br==null?void 0:br.optionalEvents)||[],Zr=(br==null?void 0:br.rpcMap)||this.buildRpcMap(Br,br.projectId),Jr=(br==null?void 0:br.qrModalOptions)||void 0;return{chains:kr==null?void 0:kr.map(Xr=>this.formatChainId(Xr)),optionalChains:jr.map(Xr=>this.formatChainId(Xr)),methods:qr,events:Wr,optionalMethods:Vr,optionalEvents:Hr,rpcMap:Zr,showQrModal:!!(br!=null&&br.showQrModal),qrModalOptions:Jr,projectId:br.projectId,metadata:br.metadata}}buildRpcMap(br,wr){const Er={};return br.forEach(kr=>{Er[kr]=this.getRpcUrl(kr,wr)}),Er}async initialize(br){if(this.rpc=this.getRpcConfig(br),this.chainId=this.rpc.chains.length?g$2(this.rpc.chains):g$2(this.rpc.optionalChains),this.signer=await hv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:br.disableProviderPing,relayUrl:br.relayUrl,storageOptions:br.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let wr;try{const{WalletConnectModal:Er}=await __vitePreload(()=>import("./index-BbrMFua0.js").then(kr=>kr.i),[]);wr=Er}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(wr)try{this.modal=new wr(p$2({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(Er){throw this.signer.logger.error(Er),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(br){if(!br)return;const{chains:wr,optionalChains:Er,rpcMap:kr}=br;wr&&k$6(wr)&&(this.rpc.chains=wr.map(jr=>this.formatChainId(jr)),wr.forEach(jr=>{this.rpc.rpcMap[jr]=(kr==null?void 0:kr[jr])||this.getRpcUrl(jr)})),Er&&k$6(Er)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=Er==null?void 0:Er.map(jr=>this.formatChainId(jr)),Er.forEach(jr=>{this.rpc.rpcMap[jr]=(kr==null?void 0:kr[jr])||this.getRpcUrl(jr)}))}getRpcUrl(br,wr){var Er;return((Er=this.rpc.rpcMap)==null?void 0:Er[br])||`${j$2}?chainId=eip155:${br}&projectId=${wr||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const br=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),wr=this.session.namespaces[`${this.namespace}:${br}`]?this.session.namespaces[`${this.namespace}:${br}`]:this.session.namespaces[this.namespace];this.setChainIds(br?[this.formatChainId(br)]:wr==null?void 0:wr.accounts),this.setAccounts(wr==null?void 0:wr.accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(br){return typeof br=="string"||br instanceof String?[this.parseAccount(br)]:br.map(wr=>this.parseAccount(wr))}};const parseIntSafe=(fr,br=10)=>{try{const wr=parseInt(String(fr),br);if(isNaN(wr)){logger$7.error(`Error parsing ${fr}`);return}return wr}catch(wr){logger$7.error(`Error parsing ${fr} to int: ${wr}`)}},activeAccountKey=fr=>`dynamic-wc2-active-account-${fr}`,sessionTopicKey=fr=>`dynamic-wc2-session-topic-${fr}`,swicthedNetworkKey=fr=>`dynamic-wc2-switched-network-${fr}`,currentChainKey=fr=>`dynamic-wc2-current-chain-${fr}`,ee=new EventEmitter$2;class WalletConnect extends EthereumWalletConnector{constructor(br){var wr;super(br),this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.isInitialized=!1,this.canConnectViaQrCode=!0,this.isWalletConnect=!0,this.preferredChains=[],this._hasSwitchedNetwork=!1,this.sessionEventHandler=()=>{},this.sessionDeleteHandler=()=>{},this.name=br.walletName,this.projectId=br.projectId,this.deepLinkPreference=br.deepLinkPreference||"native",this.preferredChains=br.walletConnectPreferredChains||[],this.hasSwitchedNetwork=(wr=!!localStorage.getItem(this.swicthedNetworkKey))!==null&&wr!==void 0?wr:!1;const Er=localStorage.getItem(this.currentChainKey);this.currentChainId=Er?parseIntSafe(Er):void 0}getMappedChains(){return this.evmNetworks.filter(br=>br.chainId!==11297108109).map(br=>`eip155:${br.chainId}`)}getMappedChainsByPreferredOrder(){const br=this.getMappedChains(),wr=this.preferredChains.filter(kr=>br.includes(kr)),Er=br.filter(kr=>!this.preferredChains.includes(kr));return[...wr,...Er].map(kr=>Number(kr.split(":")[1]))}initConnection(){return __awaiter$8(this,void 0,void 0,function*(){const{provider:br}=WalletConnect;if(!br)throw new DynamicError("No provider found (init connection)");br!=null&&br.signer.uri||br.connect().catch(wr=>{logger$7.error(wr),ee.emit("walletconnect_connection_failed",wr)})})}createProvider(){return __awaiter$8(this,void 0,void 0,function*(){return v$2.init({events:["chainChanged","accountsChanged"],methods:[],optionalChains:this.getMappedChainsByPreferredOrder(),optionalMethods:["eth_chainId","eth_signTypedData","eth_signTransaction","eth_sign","personal_sign","eth_sendTransaction","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain"],projectId:this.projectId,rpcMap:this.evmNetworkRpcMap(),showQrModal:!1})})}getWalletClientFromInitializedProvider(){return __awaiter$8(this,void 0,void 0,function*(){const br=this.createProvider();return createWalletClient$1({account:this.getActiveAccount(),transport:custom$1(yield br)})})}createInitProviderPromise(){return __awaiter$8(this,void 0,void 0,function*(){WalletConnect.provider=yield this.createProvider(),this.teardownEventListeners(),this.setupEventListeners()})}initProvider(){return __awaiter$8(this,void 0,void 0,function*(){const{provider:br}=WalletConnect;br||(this.initializePromise===void 0&&(this.initializePromise=this.createInitProviderPromise()),yield this.initializePromise)})}refreshSession(){var br,wr,Er,kr,jr;!((wr=(br=WalletConnect.provider)===null||br===void 0?void 0:br.session)===null||wr===void 0)&&wr.topic&&localStorage.getItem(this.sessionTopicKey)===((kr=(Er=WalletConnect.provider)===null||Er===void 0?void 0:Er.session)===null||kr===void 0?void 0:kr.topic)&&(this.session=WalletConnect.provider.session,this.setActiveAccount((jr=localStorage.getItem(this.activeAccountKey))!==null&&jr!==void 0?jr:void 0))}init(){return __awaiter$8(this,void 0,void 0,function*(){yield this.initProvider(),yield this.initConnection(),this.isInitialized=!0})}get sessionTopicKey(){return sessionTopicKey(this.key)}get activeAccountKey(){return activeAccountKey(this.key)}get swicthedNetworkKey(){return swicthedNetworkKey(this.key)}get currentChainKey(){return currentChainKey(this.key)}set currentChainId(br){this._currentChainId=br,br?localStorage.setItem(this.currentChainKey,br.toString()):localStorage.removeItem(this.currentChainKey)}get currentChainId(){return this._currentChainId}set hasSwitchedNetwork(br){this._hasSwitchedNetwork=br,br?localStorage.setItem(this.swicthedNetworkKey,br.toString()):localStorage.removeItem(this.swicthedNetworkKey)}get hasSwitchedNetwork(){return this._hasSwitchedNetwork}supportsNetworkSwitching(){return!0}setupEventListeners(){WalletConnect.provider&&(this.sessionEventHandler=({params:br})=>{if(logger$7.debug("session_event was called",{params:br}),!br||!br.event){logger$7.debug("session_event was called without params or params.event");return}const{name:wr,data:Er}=br.event;if(wr==="chainChanged"){const kr=parseIntSafe(Er);if(kr===this.currentChainId){logger$7.debug(`ignoring chainChanged event with same chain id as current chain id: ${kr}`);return}if(kr===void 0){logger$7.debug(`received unexpected data for chainChanged: ${Er} with type ${typeof Er}}`);return}this.currentChainId=kr,this.emit("chainChange",{chain:String(kr)}),this.hasSwitchedNetwork=!0,this.switchNetwork({networkChainId:kr})}else if(wr==="accountsChanged"){if(!Array.isArray(Er)){logger$7.debug(`received unexpected data for accountsChanged: ${Er} with type ${typeof Er}}`);return}const kr=Er[0].split(":")[2];this.setWCActiveAccount(kr)}},WalletConnect.provider.on("session_event",this.sessionEventHandler),this.sessionDeleteHandler=()=>__awaiter$8(this,void 0,void 0,function*(){this.endSession(),this.emit("disconnect")}),WalletConnect.provider.on("session_delete",this.sessionDeleteHandler))}teardownEventListeners(){WalletConnect.provider&&(WalletConnect.provider.off("session_event",this.sessionEventHandler),WalletConnect.provider.off("session_delete",this.sessionDeleteHandler))}getWalletClient(br){if(WalletConnect.provider)return createWalletClient$1({account:this.getActiveAccount(),chain:chainsMap[br??String(this.currentChainId)],transport:custom$1(WalletConnect.provider)})}getAddress(br){return __awaiter$8(this,void 0,void 0,function*(){var wr,Er;const kr=this.getActiveAccount();if(kr!=null&&kr.address)return kr.address;if((!WalletConnect.provider||!(!((wr=WalletConnect.provider)===null||wr===void 0)&&wr.signer.uri))&&(logger$7.debug("No WC2 provider found, re-initializing..."),yield this.endSession(),yield this.init(),yield sleep$1(1e3),!WalletConnect.provider||!(!((Er=WalletConnect.provider)===null||Er===void 0)&&Er.signer.uri)))throw logger$7.debug("No WC2 provider found, escaping and throwing error"),new DynamicError("No provider found");const jr=getWalletBookWallet(this.walletBook,this.key,this.walletFallback);return performPlatformSpecificConnectionMethod(WalletConnect.provider.signer.uri,jr,{onDesktopUri:br==null?void 0:br.onDesktopUri,onDisplayUri:br==null?void 0:br.onDisplayUri},this.deepLinkPreference),new Promise((Br,qr)=>{if(!WalletConnect.provider){qr(new DynamicError("No provider found"));return}const Wr=()=>{const Zr=new DynamicError("Connection rejected. Please try again.");Zr.code="connection_rejected",WalletConnect.provider&&(WalletConnect.provider.signer.uri=void 0,this.init()),qr(Zr),Hr()},Vr=()=>{var Zr;const Jr=(Zr=WalletConnect.provider)===null||Zr===void 0?void 0:Zr.session;if(!Jr){qr(new DynamicError("No session found"));return}this.setSession(Jr),this.setWCActiveAccount(Jr.namespaces.eip155.accounts[0].split(":")[2]),this.getNetwork().then(Xr=>{var En;this.currentChainId=Xr,Br((En=this.getActiveAccount())===null||En===void 0?void 0:En.address)}),Hr()},Hr=()=>{var Zr;ee.off("walletconnect_connection_failed",Wr),(Zr=WalletConnect.provider)===null||Zr===void 0||Zr.off("connect",Vr)};ee.on("walletconnect_connection_failed",Wr),WalletConnect.provider.on("connect",Vr)})})}waitForSignMessage(br,wr){return __awaiter$8(this,void 0,void 0,function*(){const kr=yield new Promise((jr,Br)=>{this.on("chainChange",()=>jr({success:!1})),br(wr).then(qr=>jr({signedMessage:qr,success:!0})).catch(Br)});return kr.success===!1?br(wr):kr.signedMessage})}getDeepLink(){var br;if(!this.session)return;const wr=getWalletBookWallet(this.walletBook,this.key),Er=getDeepLink({metadata:wr,mode:"regular",preference:this.deepLinkPreference,uri:(br=WalletConnect.provider)===null||br===void 0?void 0:br.signer.uri});if(Er)return`${Er}?sessionTopic=${this.session.topic}`}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){if(!this.session)throw new DynamicError("no session");const wr=this.getDeepLink();isMobile()&&wr&&(window.location.href=wr);const Er=jr=>__awaiter$8(this,void 0,void 0,function*(){const Br=this.getActiveAccount();return Br?(yield this.getWalletClientFromInitializedProvider()).signMessage({account:Br,message:jr}):void 0});return yield this.waitForSignMessage(Er,br)})}clearActiveAccount(){localStorage.removeItem(this.activeAccountKey),this.setActiveAccount(void 0)}clearSession(){localStorage.removeItem(this.sessionTopicKey),this.session=void 0}setWCActiveAccount(br){localStorage.setItem(this.activeAccountKey,br),this.setActiveAccount(br),this.emit("accountChange",{accounts:[br]})}setSession(br){localStorage.setItem(this.sessionTopicKey,br.topic),this.session=br}endSession(){return __awaiter$8(this,void 0,void 0,function*(){var br;if(this.clearActiveAccount(),this.clearSession(),this.hasSwitchedNetwork=!1,this.currentChainId=void 0,!!(!((br=WalletConnect.provider)===null||br===void 0)&&br.session))try{yield WalletConnect.provider.disconnect(),WalletConnect.provider=void 0}catch(wr){logger$7.debug(wr)}})}getNetwork(){const br=Object.create(null,{getNetwork:{get:()=>super.getNetwork}});return __awaiter$8(this,void 0,void 0,function*(){return this.currentChainId?this.currentChainId:(yield this.initProvider(),br.getNetwork.call(this))})}providerSwitchNetwork(br){const wr=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$8(this,arguments,void 0,function*({network:Er}){const kr=yield this.getSupportedNetworks();if(!(kr!=null&&kr.includes(Er.chainId.toString()))){const qr=new DynamicError("Network switching is not available at this time. The user should manually switch network in their wallet");throw qr.code="network_switching_only_available_in_wallet",qr}const jr=yield this.getNetwork();if(jr&&jr===Er.chainId)return;if(this.switchNetworkOnlyFromWallet)throw new DynamicError("Network switching is only supported through the wallet");if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching not supported");const Br=yield this.getWalletClientFromInitializedProvider();if(this.isMetaMask()){const qr=this.getDeepLink();qr&&(window.location.href=qr)}yield wr.providerSwitchNetwork.call(this,{network:Er,provider:Br}),this.currentChainId=Er.chainId,this.hasSwitchedNetwork=!0,this.emit("chainChange",{chain:String(Er.chainId)})})}getConnectedAccounts(){return __awaiter$8(this,void 0,void 0,function*(){this.isInitialized===!1&&(yield this.initProvider(),this.refreshSession(),this.isInitialized=!0);const br=this.getActiveAccount();return br!=null&&br.address?[br.address]:[]})}isMetaMask(){var br,wr,Er,kr,jr;return(jr=(kr=(Er=(wr=(br=this.session)===null||br===void 0?void 0:br.peer)===null||wr===void 0?void 0:wr.metadata)===null||Er===void 0?void 0:Er.name)===null||kr===void 0?void 0:kr.toLowerCase().startsWith("metamask"))!==null&&jr!==void 0?jr:!1}getSupportedNetworks(){return __awaiter$8(this,void 0,void 0,function*(){var br;if(yield this.initProvider(),this.refreshSession(),this.isMetaMask())return this.hasSwitchedNetwork?[String(this.currentChainId)]:this.evmNetworks.map(Er=>Er.chainId.toString());if(!this.session)return[];const wr=[];return Object.keys(this.session.namespaces).forEach(Er=>{Er.startsWith("eip155:")&&wr.push(Er.split(":")[1])}),(br=this.session.namespaces.eip155)===null||br===void 0||br.accounts.forEach(Er=>wr.push(Er.split(":")[1])),wr.length?wr:this.evmNetworks.map(Er=>Er.chainId.toString())})}}let InjectedWalletBase$1=class extends EthereumWalletConnector{constructor(){super(...arguments),this.supportedChains=["ETH","EVM"],this.connectedChain="EVM",this.walletConnectorFallback=!1}getEthProviderHelper(){return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.wallet&&!this.ethProviderHelper&&(this.ethProviderHelper=new EthProviderHelper(this.wallet,this)),this.ethProviderHelper}getMobileOrInstalledWallet(){var br,wr;return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.isInstalledOnBrowser()?this:!((wr=(br=this.wallet)===null||br===void 0?void 0:br.mobile)===null||wr===void 0)&&wr.inAppBrowser&&this.mobileExperience==="in-app-browser"&&isMobile()?this:this.walletConnectorFallback?new WalletConnect(Object.assign(Object.assign({},this.constructorProps),{walletName:this.name})):this}findProvider(){const br=this.getEthProviderHelper();if(br)return br.getInstalledProvider()}setupEventListeners(){if(!this.getWalletClient())return;const wr=this.getEthProviderHelper();if(!wr)return;const{tearDownEventListeners:Er}=wr._setupEventListeners(this);this.teardownEventListeners=Er}getWalletClient(br){var wr;return(wr=this.getEthProviderHelper())===null||wr===void 0?void 0:wr.findWalletClient(br)}isInstalledOnBrowser(){var br;return((br=this.getEthProviderHelper())===null||br===void 0?void 0:br.findProvider())!==void 0}getAddress(){return __awaiter$8(this,void 0,void 0,function*(){var br;return(br=this.getEthProviderHelper())===null||br===void 0?void 0:br.getAddress()})}connect(){return __awaiter$8(this,void 0,void 0,function*(){yield this.getAddress()})}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){var wr;return(wr=this.getEthProviderHelper())===null||wr===void 0?void 0:wr.signMessage(br)})}proveOwnership(br,wr){return __awaiter$8(this,void 0,void 0,function*(){return yield this.validateActiveWallet(br),this.signMessage(wr)})}endSession(){return __awaiter$8(this,void 0,void 0,function*(){})}providerSwitchNetwork(br){const wr=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$8(this,arguments,void 0,function*({network:Er,provider:kr}){return wr.providerSwitchNetwork.call(this,{network:Er,provider:kr})})}};class PhantomEvm extends InjectedWalletBase$1{constructor(br){super(br),this.name="Phantom",this.overrideKey="phantomevm",this.wallet=findWalletBookWallet(this.walletBook,this.key)}getAddress(){const br=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$8(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return br.getAddress.call(this);isMobile()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}canGetChainAddress(){var br,wr;return!!(!((wr=(br=this.getEthProviderHelper())===null||br===void 0?void 0:br.findProvider())===null||wr===void 0)&&wr.selectedAddress)}}class ExodusEvm extends InjectedWalletBase$1{constructor(br){super(br),this.name="ExodusEvm",this.overrideKey="exodusevm",this.walletConnectorFallback=!0,this.wallet=findWalletBookWallet(this.walletBook,this.key)}}let UnknownInjected$1=class extends InjectedWalletBase$1{constructor(br){super(br),this.name="Unknown",this.overrideKey="unknown",this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}};class FallbackEvmConnector extends InjectedWalletBase$1{constructor(br){super(br),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1,this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}}const injectedWalletOverrides$1=[PhantomEvm,ExodusEvm],filteredInjectedWalletKeysOverrides$1=["phantomevm","coinbase","exodusevm"],fetchInjectedWalletConnector=({walletBook:fr})=>{var br;return Object.entries((br=fr==null?void 0:fr.wallets)!==null&&br!==void 0?br:{}).filter(([wr,Er])=>{var kr;return((kr=Er.injectedConfig)===null||kr===void 0?void 0:kr.find(jr=>jr.chain==="evm"))&&!filteredInjectedWalletKeysOverrides$1.includes(wr)}).map(([wr,Er])=>{const{shortName:kr}=Er,jr=kr||Er.name,Br=!!Er.walletConnect;return class extends InjectedWalletBase$1{constructor(qr){super(Object.assign({},qr)),this.name=jr,this.wallet=Er,this.walletConnectorFallback=Br,this.overrideKey=wr}getAddress(){const qr=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$8(this,void 0,void 0,function*(){var Wr;if(this.isInstalledOnBrowser())return qr.getAddress.call(this);const Vr=(Wr=this.wallet.mobile)===null||Wr===void 0?void 0:Wr.inAppBrowser;if(!Vr){const Hr=new Error(`No inAppBrowserBase found for ${this.name}.`);throw logger$7.error(Hr.message),Hr}window.location.href=`${Vr}/${window.location.href}`})}}})},fetchWalletConnectWallets=({walletBook:fr})=>{var br;return Object.entries((br=fr==null?void 0:fr.wallets)!==null&&br!==void 0?br:{}).filter(([,wr])=>wr.walletConnect&&!wr.filterFromWalletConnect).map(([wr,Er])=>{const{shortName:kr}=Er,jr=kr||Er.name;return class extends WalletConnect{constructor(Br){super(Object.assign(Object.assign({},Br),{walletName:jr})),this.overrideKey=wr}}})},getWalletConnectConnector=()=>class extends WalletConnect{constructor(fr){super(Object.assign(Object.assign({},fr),{walletName:"WalletConnect"}))}};var dist={},CoinbaseWalletSDK$1={},walletLogo$1={};Object.defineProperty(walletLogo$1,"__esModule",{value:!0});walletLogo$1.walletLogo=void 0;const walletLogo=(fr,br)=>{let wr;switch(fr){case"standard":return wr=br,`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return wr=br,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${br}' height='${wr}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return wr=(.1*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return wr=(.25*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return wr=(.1*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return wr=(.25*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return wr=br,`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};walletLogo$1.walletLogo=walletLogo;var CoinbaseWalletProvider$1={};const require$$0$2=getAugmentedNamespace(eventemitter3$1);var error={},constants$2={};Object.defineProperty(constants$2,"__esModule",{value:!0});constants$2.errorValues=constants$2.standardErrorCodes=void 0;constants$2.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};constants$2.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var errors$1={},utils$1={};(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.serialize=fr.getErrorCode=fr.isValidCode=fr.getMessageFromCode=fr.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const br=constants$2,wr="Unspecified error message.";fr.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function Er(Jr,Xr=wr){if(Jr&&Number.isInteger(Jr)){const En=Jr.toString();if(Hr(br.errorValues,En))return br.errorValues[En].message;if(Wr(Jr))return fr.JSON_RPC_SERVER_ERROR_MESSAGE}return Xr}fr.getMessageFromCode=Er;function kr(Jr){if(!Number.isInteger(Jr))return!1;const Xr=Jr.toString();return!!(br.errorValues[Xr]||Wr(Jr))}fr.isValidCode=kr;function jr(Jr){var Xr;if(typeof Jr=="number")return Jr;if(Br(Jr))return(Xr=Jr.code)!==null&&Xr!==void 0?Xr:Jr.errorCode}fr.getErrorCode=jr;function Br(Jr){return typeof Jr=="object"&&Jr!==null&&(typeof Jr.code=="number"||typeof Jr.errorCode=="number")}function qr(Jr,{shouldIncludeStack:Xr=!1}={}){const En={};if(Jr&&typeof Jr=="object"&&!Array.isArray(Jr)&&Hr(Jr,"code")&&kr(Jr.code)){const wn=Jr;En.code=wn.code,wn.message&&typeof wn.message=="string"?(En.message=wn.message,Hr(wn,"data")&&(En.data=wn.data)):(En.message=Er(En.code),En.data={originalError:Vr(Jr)})}else En.code=br.standardErrorCodes.rpc.internal,En.message=Zr(Jr,"message")?Jr.message:wr,En.data={originalError:Vr(Jr)};return Xr&&(En.stack=Zr(Jr,"stack")?Jr.stack:void 0),En}fr.serialize=qr;function Wr(Jr){return Jr>=-32099&&Jr<=-32e3}function Vr(Jr){return Jr&&typeof Jr=="object"&&!Array.isArray(Jr)?Object.assign({},Jr):Jr}function Hr(Jr,Xr){return Object.prototype.hasOwnProperty.call(Jr,Xr)}function Zr(Jr,Xr){return typeof Jr=="object"&&Jr!==null&&Xr in Jr&&typeof Jr[Xr]=="string"}})(utils$1);Object.defineProperty(errors$1,"__esModule",{value:!0});errors$1.standardErrors=void 0;const constants_1$6=constants$2,utils_1$1=utils$1;errors$1.standardErrors={rpc:{parse:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.parse,fr),invalidRequest:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidRequest,fr),invalidParams:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidParams,fr),methodNotFound:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotFound,fr),internal:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.internal,fr),server:fr=>{if(!fr||typeof fr!="object"||Array.isArray(fr))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:br}=fr;if(!Number.isInteger(br)||br>-32005||br<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return getEthJsonRpcError(br,fr)},invalidInput:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidInput,fr),resourceNotFound:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceNotFound,fr),resourceUnavailable:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceUnavailable,fr),transactionRejected:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.transactionRejected,fr),methodNotSupported:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotSupported,fr),limitExceeded:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.limitExceeded,fr)},provider:{userRejectedRequest:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.userRejectedRequest,fr),unauthorized:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unauthorized,fr),unsupportedMethod:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedMethod,fr),disconnected:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.disconnected,fr),chainDisconnected:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.chainDisconnected,fr),unsupportedChain:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedChain,fr),custom:fr=>{if(!fr||typeof fr!="object"||Array.isArray(fr))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:br,message:wr,data:Er}=fr;if(!wr||typeof wr!="string")throw new Error('"message" must be a nonempty string');return new EthereumProviderError(br,wr,Er)}}};function getEthJsonRpcError(fr,br){const[wr,Er]=parseOpts(br);return new EthereumRpcError(fr,wr||(0,utils_1$1.getMessageFromCode)(fr),Er)}function getEthProviderError(fr,br){const[wr,Er]=parseOpts(br);return new EthereumProviderError(fr,wr||(0,utils_1$1.getMessageFromCode)(fr),Er)}function parseOpts(fr){if(fr){if(typeof fr=="string")return[fr];if(typeof fr=="object"&&!Array.isArray(fr)){const{message:br,data:wr}=fr;if(br&&typeof br!="string")throw new Error("Must specify string message.");return[br||void 0,wr]}}return[]}class EthereumRpcError extends Error{constructor(br,wr,Er){if(!Number.isInteger(br))throw new Error('"code" must be an integer.');if(!wr||typeof wr!="string")throw new Error('"message" must be a nonempty string.');super(wr),this.code=br,Er!==void 0&&(this.data=Er)}}class EthereumProviderError extends EthereumRpcError{constructor(br,wr,Er){if(!isValidEthProviderCode(br))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(br,wr,Er)}}function isValidEthProviderCode(fr){return Number.isInteger(fr)&&fr>=1e3&&fr<=4999}(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.standardErrors=fr.standardErrorCodes=void 0;var br=constants$2;Object.defineProperty(fr,"standardErrorCodes",{enumerable:!0,get:function(){return br.standardErrorCodes}});var wr=errors$1;Object.defineProperty(fr,"standardErrors",{enumerable:!0,get:function(){return wr.standardErrors}})})(error);var serialize$1={},Web3Response={};Object.defineProperty(Web3Response,"__esModule",{value:!0});Web3Response.isErrorResponse=void 0;function isErrorResponse(fr){return fr.errorMessage!==void 0}Web3Response.isErrorResponse=isErrorResponse;var version$8={};Object.defineProperty(version$8,"__esModule",{value:!0});version$8.LIB_VERSION=void 0;version$8.LIB_VERSION="4.0.4";Object.defineProperty(serialize$1,"__esModule",{value:!0});serialize$1.serializeError=void 0;const Web3Response_1$2=Web3Response,version_1$3=version$8,constants_1$5=constants$2,utils_1=utils$1;function serializeError(fr,br){const wr=(0,utils_1.serialize)(getErrorObject(fr),{shouldIncludeStack:!0}),Er=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");Er.searchParams.set("version",version_1$3.LIB_VERSION),Er.searchParams.set("code",wr.code.toString());const kr=getMethod(wr.data,br);return kr&&Er.searchParams.set("method",kr),Er.searchParams.set("message",wr.message),Object.assign(Object.assign({},wr),{docUrl:Er.href})}serialize$1.serializeError=serializeError;function getErrorObject(fr){return typeof fr=="string"?{message:fr,code:constants_1$5.standardErrorCodes.rpc.internal}:(0,Web3Response_1$2.isErrorResponse)(fr)?Object.assign(Object.assign({},fr),{message:fr.errorMessage,code:fr.errorCode,data:{method:fr.method}}):fr}function getMethod(fr,br){const wr=fr==null?void 0:fr.method;if(wr)return wr;if(br!==void 0){if(typeof br=="string")return br;if(Array.isArray(br)){if(br.length>0)return br[0].method}else return br.method}}var type$3={};Object.defineProperty(type$3,"__esModule",{value:!0});type$3.RegExpString=type$3.IntNumber=type$3.BigIntString=type$3.AddressString=type$3.HexString=type$3.OpaqueType=void 0;function OpaqueType(){return fr=>fr}type$3.OpaqueType=OpaqueType;type$3.HexString=OpaqueType();type$3.AddressString=OpaqueType();type$3.BigIntString=OpaqueType();function IntNumber(fr){return Math.floor(fr)}type$3.IntNumber=IntNumber;type$3.RegExpString=OpaqueType();var util$6={};Object.defineProperty(util$6,"__esModule",{value:!0});util$6.areAddressArraysEqual=util$6.getFavicon=util$6.range=util$6.isBigNumber=util$6.ensureParsedJSONObject=util$6.ensureBigInt=util$6.ensureRegExpString=util$6.ensureIntNumber=util$6.ensureBuffer=util$6.ensureAddressString=util$6.ensureEvenLengthHexString=util$6.ensureHexString=util$6.isHexString=util$6.prepend0x=util$6.strip0x=util$6.has0xPrefix=util$6.hexStringFromIntNumber=util$6.intNumberFromHexString=util$6.bigIntStringFromBigInt=util$6.hexStringFromBuffer=util$6.hexStringToUint8Array=util$6.uint8ArrayToHex=util$6.randomBytesHex=void 0;const error_1$8=error,_1=type$3,INT_STRING_REGEX=/^[0-9]*$/,HEXADECIMAL_STRING_REGEX=/^[a-f0-9]*$/;function randomBytesHex(fr){return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(fr)))}util$6.randomBytesHex=randomBytesHex;function uint8ArrayToHex(fr){return[...fr].map(br=>br.toString(16).padStart(2,"0")).join("")}util$6.uint8ArrayToHex=uint8ArrayToHex;function hexStringToUint8Array(fr){return new Uint8Array(fr.match(/.{1,2}/g).map(br=>parseInt(br,16)))}util$6.hexStringToUint8Array=hexStringToUint8Array;function hexStringFromBuffer(fr,br=!1){const wr=fr.toString("hex");return(0,_1.HexString)(br?`0x${wr}`:wr)}util$6.hexStringFromBuffer=hexStringFromBuffer;function bigIntStringFromBigInt(fr){return(0,_1.BigIntString)(fr.toString(10))}util$6.bigIntStringFromBigInt=bigIntStringFromBigInt;function intNumberFromHexString(fr){return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(fr,!0))))}util$6.intNumberFromHexString=intNumberFromHexString;function hexStringFromIntNumber(fr){return(0,_1.HexString)(`0x${BigInt(fr).toString(16)}`)}util$6.hexStringFromIntNumber=hexStringFromIntNumber;function has0xPrefix(fr){return fr.startsWith("0x")||fr.startsWith("0X")}util$6.has0xPrefix=has0xPrefix;function strip0x(fr){return has0xPrefix(fr)?fr.slice(2):fr}util$6.strip0x=strip0x;function prepend0x(fr){return has0xPrefix(fr)?`0x${fr.slice(2)}`:`0x${fr}`}util$6.prepend0x=prepend0x;function isHexString$1(fr){if(typeof fr!="string")return!1;const br=strip0x(fr).toLowerCase();return HEXADECIMAL_STRING_REGEX.test(br)}util$6.isHexString=isHexString$1;function ensureHexString(fr,br=!1){if(typeof fr=="string"){const wr=strip0x(fr).toLowerCase();if(HEXADECIMAL_STRING_REGEX.test(wr))return(0,_1.HexString)(br?`0x${wr}`:wr)}throw error_1$8.standardErrors.rpc.invalidParams(`"${String(fr)}" is not a hexadecimal string`)}util$6.ensureHexString=ensureHexString;function ensureEvenLengthHexString(fr,br=!1){let wr=ensureHexString(fr,!1);return wr.length%2===1&&(wr=(0,_1.HexString)(`0${wr}`)),br?(0,_1.HexString)(`0x${wr}`):wr}util$6.ensureEvenLengthHexString=ensureEvenLengthHexString;function ensureAddressString(fr){if(typeof fr=="string"){const br=strip0x(fr).toLowerCase();if(isHexString$1(br)&&br.length===40)return(0,_1.AddressString)(prepend0x(br))}throw error_1$8.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(fr)}`)}util$6.ensureAddressString=ensureAddressString;function ensureBuffer(fr){if(Buffer$2.isBuffer(fr))return fr;if(typeof fr=="string"){if(isHexString$1(fr)){const br=ensureEvenLengthHexString(fr,!1);return Buffer$2.from(br,"hex")}return Buffer$2.from(fr,"utf8")}throw error_1$8.standardErrors.rpc.invalidParams(`Not binary data: ${String(fr)}`)}util$6.ensureBuffer=ensureBuffer;function ensureIntNumber(fr){if(typeof fr=="number"&&Number.isInteger(fr))return(0,_1.IntNumber)(fr);if(typeof fr=="string"){if(INT_STRING_REGEX.test(fr))return(0,_1.IntNumber)(Number(fr));if(isHexString$1(fr))return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(fr,!0))))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(fr)}`)}util$6.ensureIntNumber=ensureIntNumber;function ensureRegExpString(fr){if(fr instanceof RegExp)return(0,_1.RegExpString)(fr.toString());throw error_1$8.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(fr)}`)}util$6.ensureRegExpString=ensureRegExpString;function ensureBigInt(fr){if(fr!==null&&(typeof fr=="bigint"||isBigNumber(fr)))return BigInt(fr.toString(10));if(typeof fr=="number")return BigInt(ensureIntNumber(fr));if(typeof fr=="string"){if(INT_STRING_REGEX.test(fr))return BigInt(fr);if(isHexString$1(fr))return BigInt(ensureEvenLengthHexString(fr,!0))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(fr)}`)}util$6.ensureBigInt=ensureBigInt;function ensureParsedJSONObject(fr){if(typeof fr=="string")return JSON.parse(fr);if(typeof fr=="object")return fr;throw error_1$8.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(fr)}`)}util$6.ensureParsedJSONObject=ensureParsedJSONObject;function isBigNumber(fr){if(fr==null||typeof fr.constructor!="function")return!1;const{constructor:br}=fr;return typeof br.config=="function"&&typeof br.EUCLID=="number"}util$6.isBigNumber=isBigNumber;function range(fr,br){return Array.from({length:br-fr},(wr,Er)=>fr+Er)}util$6.range=range;function getFavicon(){const fr=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:br,host:wr}=document.location,Er=fr?fr.getAttribute("href"):null;return!Er||Er.startsWith("javascript:")||Er.startsWith("vbscript:")?null:Er.startsWith("http://")||Er.startsWith("https://")||Er.startsWith("data:")?Er:Er.startsWith("//")?br+Er:`${br}//${wr}${Er}`}util$6.getFavicon=getFavicon;function areAddressArraysEqual(fr,br){return fr.length===br.length&&fr.every((wr,Er)=>wr===br[Er])}util$6.areAddressArraysEqual=areAddressArraysEqual;var util$5={},SCWSigner$1={},SCWKeyManager$1={},cipher={};Object.defineProperty(cipher,"__esModule",{value:!0});cipher.decryptContent=cipher.encryptContent=cipher.importKeyFromHexString=cipher.exportKeyToHexString=cipher.decrypt=cipher.encrypt=cipher.deriveSharedSecret=cipher.generateKeyPair=void 0;const util_1$b=util$6;async function generateKeyPair(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}cipher.generateKeyPair=generateKeyPair;async function deriveSharedSecret(fr,br){return crypto.subtle.deriveKey({name:"ECDH",public:br},fr,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}cipher.deriveSharedSecret=deriveSharedSecret;async function encrypt(fr,br){const wr=crypto.getRandomValues(new Uint8Array(12)),Er=await crypto.subtle.encrypt({name:"AES-GCM",iv:wr},fr,new TextEncoder().encode(br));return{iv:wr,cipherText:Er}}cipher.encrypt=encrypt;async function decrypt(fr,{iv:br,cipherText:wr}){const Er=await crypto.subtle.decrypt({name:"AES-GCM",iv:br},fr,wr);return new TextDecoder().decode(Er)}cipher.decrypt=decrypt;function getFormat(fr){switch(fr){case"public":return"spki";case"private":return"pkcs8"}}async function exportKeyToHexString(fr,br){const wr=getFormat(fr),Er=await crypto.subtle.exportKey(wr,br);return(0,util_1$b.uint8ArrayToHex)(new Uint8Array(Er))}cipher.exportKeyToHexString=exportKeyToHexString;async function importKeyFromHexString(fr,br){const wr=getFormat(fr),Er=(0,util_1$b.hexStringToUint8Array)(br).buffer;return await crypto.subtle.importKey(wr,Er,{name:"ECDH",namedCurve:"P-256"},!0,fr==="private"?["deriveKey"]:[])}cipher.importKeyFromHexString=importKeyFromHexString;async function encryptContent(fr,br){const wr=JSON.stringify(fr,(Er,kr)=>{if(!(kr instanceof Error))return kr;const jr=kr;return Object.assign(Object.assign({},jr.code?{code:jr.code}:{}),{message:jr.message})});return encrypt(br,wr)}cipher.encryptContent=encryptContent;async function decryptContent(fr,br){return JSON.parse(await decrypt(br,fr))}cipher.decryptContent=decryptContent;var ScopedLocalStorage$1={};Object.defineProperty(ScopedLocalStorage$1,"__esModule",{value:!0});ScopedLocalStorage$1.ScopedLocalStorage=void 0;class ScopedLocalStorage{constructor(br,wr){this.scope=br,this.module=wr}setItem(br,wr){localStorage.setItem(this.scopedKey(br),wr)}getItem(br){return localStorage.getItem(this.scopedKey(br))}removeItem(br){localStorage.removeItem(this.scopedKey(br))}clear(){const br=this.scopedKey(""),wr=[];for(let Er=0;ErlocalStorage.removeItem(Er))}scopedKey(br){return`-${this.scope}${this.module?`:${this.module}`:""}:${br}`}static clearAll(){new ScopedLocalStorage("CBWSDK").clear(),new ScopedLocalStorage("walletlink").clear()}}ScopedLocalStorage$1.ScopedLocalStorage=ScopedLocalStorage;Object.defineProperty(SCWKeyManager$1,"__esModule",{value:!0});SCWKeyManager$1.SCWKeyManager=void 0;const cipher_1$1=cipher,ScopedLocalStorage_1$6=ScopedLocalStorage$1,OWN_PRIVATE_KEY={storageKey:"ownPrivateKey",keyType:"private"},OWN_PUBLIC_KEY={storageKey:"ownPublicKey",keyType:"public"},PEER_PUBLIC_KEY={storageKey:"peerPublicKey",keyType:"public"};class SCWKeyManager{constructor(){this.storage=new ScopedLocalStorage_1$6.ScopedLocalStorage("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(br){this.sharedSecret=null,this.peerPublicKey=br,await this.storeKey(PEER_PUBLIC_KEY,br),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(OWN_PUBLIC_KEY.storageKey),this.storage.removeItem(OWN_PRIVATE_KEY.storageKey),this.storage.removeItem(PEER_PUBLIC_KEY.storageKey)}async generateKeyPair(){const br=await(0,cipher_1$1.generateKeyPair)();this.ownPrivateKey=br.privateKey,this.ownPublicKey=br.publicKey,await this.storeKey(OWN_PRIVATE_KEY,br.privateKey),await this.storeKey(OWN_PUBLIC_KEY,br.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(OWN_PRIVATE_KEY)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(OWN_PUBLIC_KEY)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(PEER_PUBLIC_KEY)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await(0,cipher_1$1.deriveSharedSecret)(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(br){const wr=this.storage.getItem(br.storageKey);return wr?(0,cipher_1$1.importKeyFromHexString)(br.keyType,wr):null}async storeKey(br,wr){const Er=await(0,cipher_1$1.exportKeyToHexString)(br.keyType,wr);this.storage.setItem(br.storageKey,Er)}}SCWKeyManager$1.SCWKeyManager=SCWKeyManager;var SCWStateManager$1={};Object.defineProperty(SCWStateManager$1,"__esModule",{value:!0});SCWStateManager$1.SCWStateManager=void 0;const ScopedLocalStorage_1$5=ScopedLocalStorage$1,ACCOUNTS_KEY="accounts",ACTIVE_CHAIN_STORAGE_KEY="activeChain",AVAILABLE_CHAINS_STORAGE_KEY="availableChains",WALLET_CAPABILITIES_STORAGE_KEY="walletCapabilities";class SCWStateManager{get accounts(){return this._accounts}get activeChain(){return this._activeChain}get walletCapabilities(){return this._walletCapabilities}constructor(br){var wr,Er;this.storage=new ScopedLocalStorage_1$5.ScopedLocalStorage("CBWSDK","SCWStateManager"),this.updateListener=br.updateListener,this.availableChains=this.loadItemFromStorage(AVAILABLE_CHAINS_STORAGE_KEY),this._walletCapabilities=this.loadItemFromStorage(WALLET_CAPABILITIES_STORAGE_KEY);const kr=this.loadItemFromStorage(ACCOUNTS_KEY),jr=this.loadItemFromStorage(ACTIVE_CHAIN_STORAGE_KEY);kr&&this.updateListener.onAccountsUpdate({accounts:kr,source:"storage"}),jr&&this.updateListener.onChainUpdate({chain:jr,source:"storage"}),this._accounts=kr||[],this._activeChain=jr||{id:(Er=(wr=br.appChainIds)===null||wr===void 0?void 0:wr[0])!==null&&Er!==void 0?Er:1}}updateAccounts(br){this._accounts=br,this.storeItemToStorage(ACCOUNTS_KEY,br),this.updateListener.onAccountsUpdate({accounts:br,source:"wallet"})}switchChain(br){var wr;const Er=(wr=this.availableChains)===null||wr===void 0?void 0:wr.find(kr=>kr.id===br);return Er?(Er===this._activeChain||(this._activeChain=Er,this.storeItemToStorage(ACTIVE_CHAIN_STORAGE_KEY,Er),this.updateListener.onChainUpdate({chain:Er,source:"wallet"})),!0):!1}updateAvailableChains(br){if(!br||Object.keys(br).length===0)return;const wr=Object.entries(br).map(([Er,kr])=>({id:Number(Er),rpcUrl:kr}));this.availableChains=wr,this.storeItemToStorage(AVAILABLE_CHAINS_STORAGE_KEY,wr),this.switchChain(this._activeChain.id)}updateWalletCapabilities(br){this._walletCapabilities=br,this.storeItemToStorage(WALLET_CAPABILITIES_STORAGE_KEY,br)}storeItemToStorage(br,wr){this.storage.setItem(br,JSON.stringify(wr))}loadItemFromStorage(br){const wr=this.storage.getItem(br);return wr?JSON.parse(wr):void 0}clear(){this.storage.clear()}}SCWStateManager$1.SCWStateManager=SCWStateManager;Object.defineProperty(SCWSigner$1,"__esModule",{value:!0});SCWSigner$1.SCWSigner=void 0;const SCWKeyManager_1=SCWKeyManager$1,SCWStateManager_1=SCWStateManager$1,error_1$7=error,util_1$a=util$6,cipher_1=cipher;class SCWSigner{constructor(br){this.metadata=br.metadata,this.communicator=br.communicator,this.keyManager=new SCWKeyManager_1.SCWKeyManager,this.stateManager=new SCWStateManager_1.SCWStateManager({appChainIds:this.metadata.appChainIds,updateListener:br.updateListener}),this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(){const br=await this.createRequestMessage({handshake:{method:"eth_requestAccounts",params:this.metadata}}),wr=await this.communicator.postRequestAndWaitForResponse(br);if("failure"in wr.content)throw wr.content.failure;const Er=await(0,cipher_1.importKeyFromHexString)("public",wr.sender);await this.keyManager.setPeerPublicKey(Er);const kr=await this.decryptResponseMessage(wr);this.updateInternalState({method:"eth_requestAccounts"},kr);const jr=kr.result;if("error"in jr)throw jr.error;return this.stateManager.accounts}async request(br){const wr=this.tryLocalHandling(br);if(wr!==void 0){if(wr instanceof Error)throw wr;return wr}await this.communicator.waitForPopupLoaded();const Er=await this.sendEncryptedRequest(br),kr=await this.decryptResponseMessage(Er);this.updateInternalState(br,kr);const jr=kr.result;if("error"in jr)throw jr.error;return jr.value}async disconnect(){this.stateManager.clear(),await this.keyManager.clear()}tryLocalHandling(br){var wr;switch(br.method){case"wallet_switchEthereumChain":{const Er=br.params;if(!Er||!(!((wr=Er[0])===null||wr===void 0)&&wr.chainId))throw error_1$7.standardErrors.rpc.invalidParams();const kr=(0,util_1$a.ensureIntNumber)(Er[0].chainId);return this.stateManager.switchChain(kr)?null:void 0}case"wallet_getCapabilities":{const Er=this.stateManager.walletCapabilities;if(!Er)throw error_1$7.standardErrors.provider.unauthorized("No wallet capabilities found, please disconnect and reconnect");return Er}default:return}}async sendEncryptedRequest(br){const wr=await this.keyManager.getSharedSecret();if(!wr)throw error_1$7.standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");const Er=await(0,cipher_1.encryptContent)({action:br,chainId:this.stateManager.activeChain.id},wr),kr=await this.createRequestMessage({encrypted:Er});return this.communicator.postRequestAndWaitForResponse(kr)}async createRequestMessage(br){const wr=await(0,cipher_1.exportKeyToHexString)("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:wr,content:br,timestamp:new Date}}async decryptResponseMessage(br){const wr=br.content;if("failure"in wr)throw wr.failure;const Er=await this.keyManager.getSharedSecret();if(!Er)throw error_1$7.standardErrors.provider.unauthorized("Invalid session");return(0,cipher_1.decryptContent)(wr.encrypted,Er)}updateInternalState(br,wr){var Er,kr;const jr=(Er=wr.data)===null||Er===void 0?void 0:Er.chains;jr&&this.stateManager.updateAvailableChains(jr);const Br=(kr=wr.data)===null||kr===void 0?void 0:kr.capabilities;Br&&this.stateManager.updateWalletCapabilities(Br);const qr=wr.result;if(!("error"in qr))switch(br.method){case"eth_requestAccounts":{const Wr=qr.value;this.stateManager.updateAccounts(Wr);break}case"wallet_switchEthereumChain":{if(qr.value!==null)return;const Wr=br.params,Vr=(0,util_1$a.ensureIntNumber)(Wr[0].chainId);this.stateManager.switchChain(Vr);break}}}}SCWSigner$1.SCWSigner=SCWSigner;var WalletLinkSigner$1={};const{Transform:Transform$1}=requireReadableBrowser$1();var keccak$2=fr=>class dS extends Transform$1{constructor(wr,Er,kr,jr,Br){super(Br),this._rate=wr,this._capacity=Er,this._delimitedSuffix=kr,this._hashBitLength=jr,this._options=Br,this._state=new fr,this._state.initialize(wr,Er),this._finalized=!1}_transform(wr,Er,kr){let jr=null;try{this.update(wr,Er)}catch(Br){jr=Br}kr(jr)}_flush(wr){let Er=null;try{this.push(this.digest())}catch(kr){Er=kr}wr(Er)}update(wr,Er){if(!Buffer$2.isBuffer(wr)&&typeof wr!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer$2.isBuffer(wr)||(wr=Buffer$2.from(wr,Er)),this._state.absorb(wr),this}digest(wr){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let Er=this._state.squeeze(this._hashBitLength/8);return wr!==void 0&&(Er=Er.toString(wr)),this._resetState(),Er}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const wr=new dS(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(wr._state),wr._finalized=this._finalized,wr}};const{Transform}=requireReadableBrowser$1();var shake=fr=>class fS extends Transform{constructor(wr,Er,kr,jr){super(jr),this._rate=wr,this._capacity=Er,this._delimitedSuffix=kr,this._options=jr,this._state=new fr,this._state.initialize(wr,Er),this._finalized=!1}_transform(wr,Er,kr){let jr=null;try{this.update(wr,Er)}catch(Br){jr=Br}kr(jr)}_flush(){}_read(wr){this.push(this.squeeze(wr))}update(wr,Er){if(!Buffer$2.isBuffer(wr)&&typeof wr!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer$2.isBuffer(wr)||(wr=Buffer$2.from(wr,Er)),this._state.absorb(wr),this}squeeze(wr,Er){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let kr=this._state.squeeze(wr);return Er!==void 0&&(kr=kr.toString(Er)),kr}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const wr=new fS(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(wr._state),wr._finalized=this._finalized,wr}};const createKeccak=keccak$2,createShake=shake;var api=function(fr){const br=createKeccak(fr),wr=createShake(fr);return function(Er,kr){switch(typeof Er=="string"?Er.toLowerCase():Er){case"keccak224":return new br(1152,448,null,224,kr);case"keccak256":return new br(1088,512,null,256,kr);case"keccak384":return new br(832,768,null,384,kr);case"keccak512":return new br(576,1024,null,512,kr);case"sha3-224":return new br(1152,448,6,224,kr);case"sha3-256":return new br(1088,512,6,256,kr);case"sha3-384":return new br(832,768,6,384,kr);case"sha3-512":return new br(576,1024,6,512,kr);case"shake128":return new wr(1344,256,31,kr);case"shake256":return new wr(1088,512,31,kr);default:throw new Error("Invald algorithm: "+Er)}}},keccakStateUnroll={};const P1600_ROUND_CONSTANTS=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];keccakStateUnroll.p1600=function(fr){for(let br=0;br<24;++br){const wr=fr[0]^fr[10]^fr[20]^fr[30]^fr[40],Er=fr[1]^fr[11]^fr[21]^fr[31]^fr[41],kr=fr[2]^fr[12]^fr[22]^fr[32]^fr[42],jr=fr[3]^fr[13]^fr[23]^fr[33]^fr[43],Br=fr[4]^fr[14]^fr[24]^fr[34]^fr[44],qr=fr[5]^fr[15]^fr[25]^fr[35]^fr[45],Wr=fr[6]^fr[16]^fr[26]^fr[36]^fr[46],Vr=fr[7]^fr[17]^fr[27]^fr[37]^fr[47],Hr=fr[8]^fr[18]^fr[28]^fr[38]^fr[48],Zr=fr[9]^fr[19]^fr[29]^fr[39]^fr[49];let Jr=Hr^(kr<<1|jr>>>31),Xr=Zr^(jr<<1|kr>>>31);const En=fr[0]^Jr,wn=fr[1]^Xr,$n=fr[10]^Jr,Tn=fr[11]^Xr,In=fr[20]^Jr,jn=fr[21]^Xr,Yn=fr[30]^Jr,ga=fr[31]^Xr,na=fr[40]^Jr,_i=fr[41]^Xr;Jr=wr^(Br<<1|qr>>>31),Xr=Er^(qr<<1|Br>>>31);const ro=fr[2]^Jr,to=fr[3]^Xr,io=fr[12]^Jr,no=fr[13]^Xr,$a=fr[22]^Jr,Rn=fr[23]^Xr,Gr=fr[32]^Jr,Yr=fr[33]^Xr,Sn=fr[42]^Jr,An=fr[43]^Xr;Jr=kr^(Wr<<1|Vr>>>31),Xr=jr^(Vr<<1|Wr>>>31);const Pn=fr[4]^Jr,Nn=fr[5]^Xr,zn=fr[14]^Jr,On=fr[15]^Xr,_n=fr[24]^Jr,Zn=fr[25]^Xr,oo=fr[34]^Jr,uo=fr[35]^Xr,lo=fr[44]^Jr,co=fr[45]^Xr;Jr=Br^(Hr<<1|Zr>>>31),Xr=qr^(Zr<<1|Hr>>>31);const so=fr[6]^Jr,yo=fr[7]^Xr,fo=fr[16]^Jr,ho=fr[17]^Xr,vo=fr[26]^Jr,Io=fr[27]^Xr,Ro=fr[36]^Jr,To=fr[37]^Xr,Wo=fr[46]^Jr,qo=fr[47]^Xr;Jr=Wr^(wr<<1|Er>>>31),Xr=Vr^(Er<<1|wr>>>31);const Zo=fr[8]^Jr,Qo=fr[9]^Xr,jo=fr[18]^Jr,No=fr[19]^Xr,Tl=fr[28]^Jr,Fo=fr[29]^Xr,Lo=fr[38]^Jr,Rl=fr[39]^Xr,_c=fr[48]^Jr,Ko=fr[49]^Xr,zl=En,Sl=wn,Eo=Tn<<4|$n>>>28,bo=$n<<4|Tn>>>28,go=In<<3|jn>>>29,Co=jn<<3|In>>>29,zo=ga<<9|Yn>>>23,Do=Yn<<9|ga>>>23,Uo=na<<18|_i>>>14,ru=_i<<18|na>>>14,Dl=ro<<1|to>>>31,xl=to<<1|ro>>>31,bu=no<<12|io>>>20,yl=io<<12|no>>>20,Il=$a<<10|Rn>>>22,cu=Rn<<10|$a>>>22,Bl=Yr<<13|Gr>>>19,Pl=Gr<<13|Yr>>>19,wu=Sn<<2|An>>>30,Ol=An<<2|Sn>>>30,Nl=Nn<<30|Pn>>>2,Tu=Pn<<30|Nn>>>2,Ul=zn<<6|On>>>26,Cl=On<<6|zn>>>26,gu=Zn<<11|_n>>>21,wo=_n<<11|Zn>>>21,$o=oo<<15|uo>>>17,Ao=uo<<15|oo>>>17,po=co<<29|lo>>>3,So=lo<<29|co>>>3,Jo=so<<28|yo>>>4,Bo=yo<<28|so>>>4,Ho=ho<<23|fo>>>9,Wl=fo<<23|ho>>>9,El=vo<<25|Io>>>7,$l=Io<<25|vo>>>7,Su=Ro<<21|To>>>11,nu=To<<21|Ro>>>11,pu=qo<<24|Wo>>>8,mu=Wo<<24|qo>>>8,hu=Zo<<27|Qo>>>5,yu=Qo<<27|Zo>>>5,_u=jo<<20|No>>>12,fu=No<<20|jo>>>12,vu=Fo<<7|Tl>>>25,iu=Tl<<7|Fo>>>25,su=Lo<<8|Rl>>>24,tu=Rl<<8|Lo>>>24,Hl=_c<<14|Ko>>>18,Zl=Ko<<14|_c>>>18;fr[0]=zl^~bu&gu,fr[1]=Sl^~yl&wo,fr[10]=Jo^~_u&go,fr[11]=Bo^~fu&Co,fr[20]=Dl^~Ul&El,fr[21]=xl^~Cl&$l,fr[30]=hu^~Eo&Il,fr[31]=yu^~bo&cu,fr[40]=Nl^~Ho&vu,fr[41]=Tu^~Wl&iu,fr[2]=bu^~gu&Su,fr[3]=yl^~wo&nu,fr[12]=_u^~go&Bl,fr[13]=fu^~Co&Pl,fr[22]=Ul^~El&su,fr[23]=Cl^~$l&tu,fr[32]=Eo^~Il&$o,fr[33]=bo^~cu&Ao,fr[42]=Ho^~vu&zo,fr[43]=Wl^~iu&Do,fr[4]=gu^~Su&Hl,fr[5]=wo^~nu&Zl,fr[14]=go^~Bl&po,fr[15]=Co^~Pl&So,fr[24]=El^~su&Uo,fr[25]=$l^~tu&ru,fr[34]=Il^~$o&pu,fr[35]=cu^~Ao&mu,fr[44]=vu^~zo&wu,fr[45]=iu^~Do&Ol,fr[6]=Su^~Hl&zl,fr[7]=nu^~Zl&Sl,fr[16]=Bl^~po&Jo,fr[17]=Pl^~So&Bo,fr[26]=su^~Uo&Dl,fr[27]=tu^~ru&xl,fr[36]=$o^~pu&hu,fr[37]=Ao^~mu&yu,fr[46]=zo^~wu&Nl,fr[47]=Do^~Ol&Tu,fr[8]=Hl^~zl&bu,fr[9]=Zl^~Sl&yl,fr[18]=po^~Jo&_u,fr[19]=So^~Bo&fu,fr[28]=Uo^~Dl&Ul,fr[29]=ru^~xl&Cl,fr[38]=pu^~hu&Eo,fr[39]=mu^~yu&bo,fr[48]=wu^~Nl&Ho,fr[49]=Ol^~Tu&Wl,fr[0]^=P1600_ROUND_CONSTANTS[br*2],fr[1]^=P1600_ROUND_CONSTANTS[br*2+1]}};const keccakState=keccakStateUnroll;function Keccak(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Keccak.prototype.initialize=function(fr,br){for(let wr=0;wr<50;++wr)this.state[wr]=0;this.blockSize=fr/8,this.count=0,this.squeezing=!1};Keccak.prototype.absorb=function(fr){for(let br=0;br>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(keccakState.p1600(this.state),this.count=0);return br};Keccak.prototype.copy=function(fr){for(let br=0;br<50;++br)fr.state[br]=this.state[br];fr.blockSize=this.blockSize,fr.count=this.count,fr.squeezing=this.squeezing};var keccak$1=Keccak,js=api(keccak$1);const createKeccakHash=js;function zeros(fr){return Buffer$2.allocUnsafe(fr).fill(0)}function bitLengthFromBigInt(fr){return fr.toString(2).length}function bufferBEFromBigInt(fr,br){let wr=fr.toString(16);wr.length%2!==0&&(wr="0"+wr);const Er=wr.match(/.{1,2}/g).map(kr=>parseInt(kr,16));for(;Er.length"u")throw new Error("Not an array?");if(wr=parseTypeArray(fr),wr!=="dynamic"&&wr!==0&&br.length>wr)throw new Error("Elements exceed array size: "+wr);kr=[],fr=fr.slice(0,fr.lastIndexOf("[")),typeof br=="string"&&(br=JSON.parse(br));for(jr in br)kr.push(encodeSingle(fr,br[jr]));if(wr==="dynamic"){var Br=encodeSingle("uint256",br.length);kr.unshift(Br)}return Buffer$2.concat(kr)}else{if(fr==="bytes")return br=new Buffer$2(br),kr=Buffer$2.concat([encodeSingle("uint256",br.length),br]),br.length%32!==0&&(kr=Buffer$2.concat([kr,util$3.zeros(32-br.length%32)])),kr;if(fr.startsWith("bytes")){if(wr=parseTypeN(fr),wr<1||wr>32)throw new Error("Invalid bytes width: "+wr);return util$3.setLengthRight(br,32)}else if(fr.startsWith("uint")){if(wr=parseTypeN(fr),wr%8||wr<8||wr>256)throw new Error("Invalid uint width: "+wr);Er=parseNumber(br);const qr=util$3.bitLengthFromBigInt(Er);if(qr>wr)throw new Error("Supplied uint exceeds width: "+wr+" vs "+qr);if(Er<0)throw new Error("Supplied uint is negative");return util$3.bufferBEFromBigInt(Er,32)}else if(fr.startsWith("int")){if(wr=parseTypeN(fr),wr%8||wr<8||wr>256)throw new Error("Invalid int width: "+wr);Er=parseNumber(br);const qr=util$3.bitLengthFromBigInt(Er);if(qr>wr)throw new Error("Supplied int exceeds width: "+wr+" vs "+qr);const Wr=util$3.twosFromBigInt(Er,256);return util$3.bufferBEFromBigInt(Wr,32)}else if(fr.startsWith("ufixed")){if(wr=parseTypeNxM(fr),Er=parseNumber(br),Er<0)throw new Error("Supplied ufixed is negative");return encodeSingle("uint256",Er*BigInt(2)**BigInt(wr[1]))}else if(fr.startsWith("fixed"))return wr=parseTypeNxM(fr),encodeSingle("int256",parseNumber(br)*BigInt(2)**BigInt(wr[1]))}throw new Error("Unsupported or invalid type: "+fr)}function isDynamic(fr){return fr==="string"||fr==="bytes"||parseTypeArray(fr)==="dynamic"}function isArray(fr){return fr.lastIndexOf("]")===fr.length-1}function rawEncode(fr,br){var wr=[],Er=[],kr=32*fr.length;for(var jr in fr){var Br=elementaryName(fr[jr]),qr=br[jr],Wr=encodeSingle(Br,qr);isDynamic(Br)?(wr.push(encodeSingle("uint256",kr)),Er.push(Wr),kr+=Wr.length):wr.push(Wr)}return Buffer$2.concat(wr.concat(Er))}function solidityPack(fr,br){if(fr.length!==br.length)throw new Error("Number of types are not matching the values");for(var wr,Er,kr=[],jr=0;jr32)throw new Error("Invalid bytes width: "+wr);kr.push(util$3.setLengthRight(qr,wr))}else if(Br.startsWith("uint")){if(wr=parseTypeN(Br),wr%8||wr<8||wr>256)throw new Error("Invalid uint width: "+wr);Er=parseNumber(qr);const Wr=util$3.bitLengthFromBigInt(Er);if(Wr>wr)throw new Error("Supplied uint exceeds width: "+wr+" vs "+Wr);kr.push(util$3.bufferBEFromBigInt(Er,wr/8))}else if(Br.startsWith("int")){if(wr=parseTypeN(Br),wr%8||wr<8||wr>256)throw new Error("Invalid int width: "+wr);Er=parseNumber(qr);const Wr=util$3.bitLengthFromBigInt(Er);if(Wr>wr)throw new Error("Supplied int exceeds width: "+wr+" vs "+Wr);const Vr=util$3.twosFromBigInt(Er,wr);kr.push(util$3.bufferBEFromBigInt(Vr,wr/8))}else throw new Error("Unsupported or invalid type: "+Br)}return Buffer$2.concat(kr)}function soliditySHA3(fr,br){return util$3.keccak(solidityPack(fr,br))}var abi$1={rawEncode,solidityPack,soliditySHA3};const util$2=util$4,abi=abi$1,TYPED_MESSAGE_SCHEMA={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},TypedDataUtils={encodeData(fr,br,wr,Er=!0){const kr=["bytes32"],jr=[this.hashType(fr,wr)];if(Er){const Br=(qr,Wr,Vr)=>{if(wr[Wr]!==void 0)return["bytes32",Vr==null?"0x0000000000000000000000000000000000000000000000000000000000000000":util$2.keccak(this.encodeData(Wr,Vr,wr,Er))];if(Vr===void 0)throw new Error(`missing value for field ${qr} of type ${Wr}`);if(Wr==="bytes")return["bytes32",util$2.keccak(Vr)];if(Wr==="string")return typeof Vr=="string"&&(Vr=Buffer$2.from(Vr,"utf8")),["bytes32",util$2.keccak(Vr)];if(Wr.lastIndexOf("]")===Wr.length-1){const Hr=Wr.slice(0,Wr.lastIndexOf("[")),Zr=Vr.map(Jr=>Br(qr,Hr,Jr));return["bytes32",util$2.keccak(abi.rawEncode(Zr.map(([Jr])=>Jr),Zr.map(([,Jr])=>Jr)))]}return[Wr,Vr]};for(const qr of wr[fr]){const[Wr,Vr]=Br(qr.name,qr.type,br[qr.name]);kr.push(Wr),jr.push(Vr)}}else for(const Br of wr[fr]){let qr=br[Br.name];if(qr!==void 0)if(Br.type==="bytes")kr.push("bytes32"),qr=util$2.keccak(qr),jr.push(qr);else if(Br.type==="string")kr.push("bytes32"),typeof qr=="string"&&(qr=Buffer$2.from(qr,"utf8")),qr=util$2.keccak(qr),jr.push(qr);else if(wr[Br.type]!==void 0)kr.push("bytes32"),qr=util$2.keccak(this.encodeData(Br.type,qr,wr,Er)),jr.push(qr);else{if(Br.type.lastIndexOf("]")===Br.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");kr.push(Br.type),jr.push(qr)}}return abi.rawEncode(kr,jr)},encodeType(fr,br){let wr="",Er=this.findTypeDependencies(fr,br).filter(kr=>kr!==fr);Er=[fr].concat(Er.sort());for(const kr of Er){if(!br[kr])throw new Error("No type definition specified: "+kr);wr+=kr+"("+br[kr].map(({name:Br,type:qr})=>qr+" "+Br).join(",")+")"}return wr},findTypeDependencies(fr,br,wr=[]){if(fr=fr.match(/^\w*/)[0],wr.includes(fr)||br[fr]===void 0)return wr;wr.push(fr);for(const Er of br[fr])for(const kr of this.findTypeDependencies(Er.type,br,wr))!wr.includes(kr)&&wr.push(kr);return wr},hashStruct(fr,br,wr,Er=!0){return util$2.keccak(this.encodeData(fr,br,wr,Er))},hashType(fr,br){return util$2.keccak(this.encodeType(fr,br))},sanitizeData(fr){const br={};for(const wr in TYPED_MESSAGE_SCHEMA.properties)fr[wr]&&(br[wr]=fr[wr]);return br.types&&(br.types=Object.assign({EIP712Domain:[]},br.types)),br},hash(fr,br=!0){const wr=this.sanitizeData(fr),Er=[Buffer$2.from("1901","hex")];return Er.push(this.hashStruct("EIP712Domain",wr.domain,wr.types,br)),wr.primaryType!=="EIP712Domain"&&Er.push(this.hashStruct(wr.primaryType,wr.message,wr.types,br)),util$2.keccak(Buffer$2.concat(Er))}};var ethEip712Util={TYPED_MESSAGE_SCHEMA,TypedDataUtils,hashForSignTypedDataLegacy:function(fr){return typedSignatureHashLegacy(fr.data)},hashForSignTypedData_v3:function(fr){return TypedDataUtils.hash(fr.data,!1)},hashForSignTypedData_v4:function(fr){return TypedDataUtils.hash(fr.data)}};function typedSignatureHashLegacy(fr){const br=new Error("Expect argument to be non-empty array");if(typeof fr!="object"||!fr.length)throw br;const wr=fr.map(function(jr){return jr.type==="bytes"?util$2.toBuffer(jr.value):jr.value}),Er=fr.map(function(jr){return jr.type}),kr=fr.map(function(jr){if(!jr.name)throw br;return jr.type+" "+jr.name});return abi.soliditySHA3(["bytes32","bytes32"],[abi.soliditySHA3(new Array(fr.length).fill("string"),kr),abi.soliditySHA3(Er,wr)])}var constants$1={};Object.defineProperty(constants$1,"__esModule",{value:!0});constants$1.APP_VERSION_KEY=constants$1.LOCAL_STORAGE_ADDRESSES_KEY=constants$1.WALLET_USER_NAME_KEY=void 0;constants$1.WALLET_USER_NAME_KEY="walletUsername";constants$1.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";constants$1.APP_VERSION_KEY="AppVersion";var RelayEventManager$1={};Object.defineProperty(RelayEventManager$1,"__esModule",{value:!0});RelayEventManager$1.RelayEventManager=void 0;const util_1$9=util$6;class RelayEventManager{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const br=this._nextRequestId,wr=(0,util_1$9.prepend0x)(br.toString(16));return this.callbacks.get(wr)&&this.callbacks.delete(wr),br}}RelayEventManager$1.RelayEventManager=RelayEventManager;var WalletLinkRelay$1={},WalletLinkConnection$1={},WalletLinkCipher$1={};Object.defineProperty(WalletLinkCipher$1,"__esModule",{value:!0});WalletLinkCipher$1.WalletLinkCipher=void 0;const util_1$8=util$6;class WalletLinkCipher{constructor(br){this.secret=br}async encrypt(br){const wr=this.secret;if(wr.length!==64)throw Error("secret must be 256 bits");const Er=crypto.getRandomValues(new Uint8Array(12)),kr=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(wr),{name:"aes-gcm"},!1,["encrypt","decrypt"]),jr=new TextEncoder,Br=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Er},kr,jr.encode(br)),qr=16,Wr=Br.slice(Br.byteLength-qr),Vr=Br.slice(0,Br.byteLength-qr),Hr=new Uint8Array(Wr),Zr=new Uint8Array(Vr),Jr=new Uint8Array([...Er,...Hr,...Zr]);return(0,util_1$8.uint8ArrayToHex)(Jr)}async decrypt(br){const wr=this.secret;if(wr.length!==64)throw Error("secret must be 256 bits");return new Promise((Er,kr)=>{(async function(){const jr=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(wr),{name:"aes-gcm"},!1,["encrypt","decrypt"]),Br=(0,util_1$8.hexStringToUint8Array)(br),qr=Br.slice(0,12),Wr=Br.slice(12,28),Vr=Br.slice(28),Hr=new Uint8Array([...Vr,...Wr]),Zr={name:"AES-GCM",iv:new Uint8Array(qr)};try{const Jr=await window.crypto.subtle.decrypt(Zr,jr,Hr),Xr=new TextDecoder;Er(Xr.decode(Jr))}catch(Jr){kr(Jr)}})()})}}WalletLinkCipher$1.WalletLinkCipher=WalletLinkCipher;var WalletLinkHTTP$1={};Object.defineProperty(WalletLinkHTTP$1,"__esModule",{value:!0});WalletLinkHTTP$1.WalletLinkHTTP=void 0;class WalletLinkHTTP{constructor(br,wr,Er){this.linkAPIUrl=br,this.sessionId=wr;const kr=`${wr}:${Er}`;this.auth=`Basic ${btoa(kr)}`}async markUnseenEventsAsSeen(br){return Promise.all(br.map(wr=>fetch(`${this.linkAPIUrl}/events/${wr.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(wr=>console.error("Unabled to mark event as failed:",wr))}async fetchUnseenEvents(){var br;const wr=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(wr.ok){const{events:Er,error:kr}=await wr.json();if(kr)throw new Error(`Check unseen events failed: ${kr}`);const jr=(br=Er==null?void 0:Er.filter(Br=>Br.event==="Web3Response").map(Br=>({type:"Event",sessionId:this.sessionId,eventId:Br.id,event:Br.event,data:Br.data})))!==null&&br!==void 0?br:[];return this.markUnseenEventsAsSeen(jr),jr}throw new Error(`Check unseen events failed: ${wr.status}`)}}WalletLinkHTTP$1.WalletLinkHTTP=WalletLinkHTTP;var WalletLinkWebSocket$1={};Object.defineProperty(WalletLinkWebSocket$1,"__esModule",{value:!0});WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket$1.ConnectionState=void 0;var ConnectionState;(function(fr){fr[fr.DISCONNECTED=0]="DISCONNECTED",fr[fr.CONNECTING=1]="CONNECTING",fr[fr.CONNECTED=2]="CONNECTED"})(ConnectionState||(WalletLinkWebSocket$1.ConnectionState=ConnectionState={}));class WalletLinkWebSocket{setConnectionStateListener(br){this.connectionStateListener=br}setIncomingDataListener(br){this.incomingDataListener=br}constructor(br,wr=WebSocket){this.WebSocketClass=wr,this.webSocket=null,this.pendingData=[],this.url=br.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((br,wr)=>{var Er;let kr;try{this.webSocket=kr=new this.WebSocketClass(this.url)}catch(jr){wr(jr);return}(Er=this.connectionStateListener)===null||Er===void 0||Er.call(this,ConnectionState.CONNECTING),kr.onclose=jr=>{var Br;this.clearWebSocket(),wr(new Error(`websocket error ${jr.code}: ${jr.reason}`)),(Br=this.connectionStateListener)===null||Br===void 0||Br.call(this,ConnectionState.DISCONNECTED)},kr.onopen=jr=>{var Br;br(),(Br=this.connectionStateListener)===null||Br===void 0||Br.call(this,ConnectionState.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(Wr=>this.sendData(Wr)),this.pendingData=[])},kr.onmessage=jr=>{var Br,qr;if(jr.data==="h")(Br=this.incomingDataListener)===null||Br===void 0||Br.call(this,{type:"Heartbeat"});else try{const Wr=JSON.parse(jr.data);(qr=this.incomingDataListener)===null||qr===void 0||qr.call(this,Wr)}catch{}}})}disconnect(){var br;const{webSocket:wr}=this;if(wr){this.clearWebSocket(),(br=this.connectionStateListener)===null||br===void 0||br.call(this,ConnectionState.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{wr.close()}catch{}}}sendData(br){const{webSocket:wr}=this;if(!wr){this.pendingData.push(br),this.connect();return}wr.send(br)}clearWebSocket(){const{webSocket:br}=this;br&&(this.webSocket=null,br.onclose=null,br.onerror=null,br.onmessage=null,br.onopen=null)}}WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket;Object.defineProperty(WalletLinkConnection$1,"__esModule",{value:!0});WalletLinkConnection$1.WalletLinkConnection=void 0;const constants_1$4=constants$1,WalletLinkCipher_1=WalletLinkCipher$1,WalletLinkHTTP_1=WalletLinkHTTP$1,WalletLinkWebSocket_1=WalletLinkWebSocket$1,type_1$1=type$3,HEARTBEAT_INTERVAL=1e4,REQUEST_TIMEOUT=6e4;class WalletLinkConnection{constructor({session:br,linkAPIUrl:wr,listener:Er,WebSocketClass:kr=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,type_1$1.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=Br=>{if(!Br)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",Wr=>Br.JsonRpcUrl&&this.handleChainUpdated(Wr,Br.JsonRpcUrl)]]).forEach((Wr,Vr)=>{const Hr=Br[Vr];Hr!==void 0&&Wr(Hr)})},this.handleDestroyed=Br=>{var qr;Br==="1"&&((qr=this.listener)===null||qr===void 0||qr.resetAndReload())},this.handleAccountUpdated=async Br=>{var qr;{const Wr=await this.cipher.decrypt(Br);(qr=this.listener)===null||qr===void 0||qr.accountUpdated(Wr)}},this.handleMetadataUpdated=async(Br,qr)=>{var Wr;{const Vr=await this.cipher.decrypt(qr);(Wr=this.listener)===null||Wr===void 0||Wr.metadataUpdated(Br,Vr)}},this.handleWalletUsernameUpdated=async Br=>{this.handleMetadataUpdated(constants_1$4.WALLET_USER_NAME_KEY,Br)},this.handleAppVersionUpdated=async Br=>{this.handleMetadataUpdated(constants_1$4.APP_VERSION_KEY,Br)},this.handleChainUpdated=async(Br,qr)=>{var Wr;{const Vr=await this.cipher.decrypt(Br),Hr=await this.cipher.decrypt(qr);(Wr=this.listener)===null||Wr===void 0||Wr.chainUpdated(Vr,Hr)}},this.session=br,this.cipher=new WalletLinkCipher_1.WalletLinkCipher(br.secret),this.listener=Er;const jr=new WalletLinkWebSocket_1.WalletLinkWebSocket(`${wr}/rpc`,kr);jr.setConnectionStateListener(async Br=>{let qr=!1;switch(Br){case WalletLinkWebSocket_1.ConnectionState.DISCONNECTED:if(!this.destroyed){const Wr=async()=>{await new Promise(Vr=>setTimeout(Vr,5e3)),this.destroyed||jr.connect().catch(()=>{Wr()})};Wr()}break;case WalletLinkWebSocket_1.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),qr=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},HEARTBEAT_INTERVAL),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case WalletLinkWebSocket_1.ConnectionState.CONNECTING:break}this.connected!==qr&&(this.connected=qr)}),jr.setIncomingDataListener(Br=>{var qr;switch(Br.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const Wr=Br.type==="IsLinkedOK"?Br.linked:void 0;this.linked=Wr||Br.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(Br.metadata);break}case"Event":{this.handleIncomingEvent(Br);break}}Br.id!==void 0&&((qr=this.requestResolutions.get(Br.id))===null||qr===void 0||qr(Br))}),this.ws=jr,this.http=new WalletLinkHTTP_1.WalletLinkHTTP(wr,br.id,br.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}destroy(){this.destroyed=!0,this.ws.disconnect(),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(br){var wr;this._connected=br,br&&((wr=this.onceConnected)===null||wr===void 0||wr.call(this))}setOnceConnected(br){return new Promise(wr=>{this.connected?br().then(wr):this.onceConnected=()=>{br().then(wr),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(br){var wr,Er;this._linked=br,br&&((wr=this.onceLinked)===null||wr===void 0||wr.call(this)),(Er=this.listener)===null||Er===void 0||Er.linkedUpdated(br)}setOnceLinked(br){return new Promise(wr=>{this.linked?br().then(wr):this.onceLinked=()=>{br().then(wr),this.onceLinked=void 0}})}async handleIncomingEvent(br){var wr;if(!(br.type!=="Event"||br.event!=="Web3Response")){const Er=await this.cipher.decrypt(br.data),kr=JSON.parse(Er);if(kr.type!=="WEB3_RESPONSE")return;(wr=this.listener)===null||wr===void 0||wr.handleWeb3ResponseMessage(kr)}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(br=>setTimeout(br,250));try{await this.fetchUnseenEventsAPI()}catch(br){console.error("Unable to check for unseen events",br)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(wr=>this.handleIncomingEvent(wr))}async setSessionMetadata(br,wr){const Er={type:"SetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[br]:wr}};return this.setOnceConnected(async()=>{const kr=await this.makeRequest(Er);if(kr.type==="Fail")throw new Error(kr.error||"failed to set session metadata")})}async publishEvent(br,wr,Er=!1){const kr=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},wr),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),jr={type:"PublishEvent",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:br,data:kr,callWebhook:Er};return this.setOnceLinked(async()=>{const Br=await this.makeRequest(jr);if(Br.type==="Fail")throw new Error(Br.error||"failed to publish event");return Br.eventId})}sendData(br){this.ws.sendData(JSON.stringify(br))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>HEARTBEAT_INTERVAL*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(br,wr=REQUEST_TIMEOUT){const Er=br.id;this.sendData(br);let kr;return Promise.race([new Promise((jr,Br)=>{kr=window.setTimeout(()=>{Br(new Error(`request ${Er} timed out`))},wr)}),new Promise(jr=>{this.requestResolutions.set(Er,Br=>{clearTimeout(kr),jr(Br),this.requestResolutions.delete(Er)})})])}async authenticate(){const br={type:"HostSession",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},wr=await this.makeRequest(br);if(wr.type==="Fail")throw new Error(wr.error||"failed to authenticate")}sendIsLinked(){const br={type:"IsLinked",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(br)}sendGetSessionConfig(){const br={type:"GetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(br)}}WalletLinkConnection$1.WalletLinkConnection=WalletLinkConnection;var WalletLinkSession$1={};Object.defineProperty(WalletLinkSession$1,"__esModule",{value:!0});WalletLinkSession$1.WalletLinkSession=void 0;const sha_js_1=requireSha_js(),util_1$7=util$6,STORAGE_KEY_SESSION_ID="session:id",STORAGE_KEY_SESSION_SECRET="session:secret",STORAGE_KEY_SESSION_LINKED="session:linked";class WalletLinkSession{constructor(br,wr,Er,kr){this._storage=br,this._id=wr||(0,util_1$7.randomBytesHex)(16),this._secret=Er||(0,util_1$7.randomBytesHex)(32),this._key=new sha_js_1.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!kr}static load(br){const wr=br.getItem(STORAGE_KEY_SESSION_ID),Er=br.getItem(STORAGE_KEY_SESSION_LINKED),kr=br.getItem(STORAGE_KEY_SESSION_SECRET);return wr&&kr?new WalletLinkSession(br,wr,kr,Er==="1"):null}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(br){this._linked=br,this.persistLinked()}save(){return this._storage.setItem(STORAGE_KEY_SESSION_ID,this._id),this._storage.setItem(STORAGE_KEY_SESSION_SECRET,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(STORAGE_KEY_SESSION_LINKED,this._linked?"1":"0")}}WalletLinkSession$1.WalletLinkSession=WalletLinkSession;var util$1={};Object.defineProperty(util$1,"__esModule",{value:!0});util$1.isDarkMode=util$1.isMobileWeb=util$1.getLocation=util$1.createQrUrl=void 0;function createQrUrl(fr,br,wr,Er,kr,jr){const Br=Er?"parent-id":"id",qr=new URLSearchParams({[Br]:fr,secret:br,server:wr,v:kr,chainId:jr.toString()}).toString();return`${wr}/#/link?${qr}`}util$1.createQrUrl=createQrUrl;function isInIFrame(){try{return window.frameElement!==null}catch{return!1}}function getLocation(){try{return isInIFrame()&&window.top?window.top.location:window.location}catch{return window.location}}util$1.getLocation=getLocation;function isMobileWeb(){var fr;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((fr=window==null?void 0:window.navigator)===null||fr===void 0?void 0:fr.userAgent)}util$1.isMobileWeb=isMobileWeb;function isDarkMode(){var fr,br;return(br=(fr=window==null?void 0:window.matchMedia)===null||fr===void 0?void 0:fr.call(window,"(prefers-color-scheme: dark)").matches)!==null&&br!==void 0?br:!1}util$1.isDarkMode=isDarkMode;var WalletLinkRelayUI$1={},cssReset={},cssResetCss={};Object.defineProperty(cssResetCss,"__esModule",{value:!0});cssResetCss.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var __importDefault$4=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(cssReset,"__esModule",{value:!0});cssReset.injectCssReset=void 0;const cssReset_css_1=__importDefault$4(cssResetCss);function injectCssReset(){const fr=document.createElement("style");fr.type="text/css",fr.appendChild(document.createTextNode(cssReset_css_1.default)),document.documentElement.appendChild(fr)}cssReset.injectCssReset=injectCssReset;var Snackbar={};function r$2(fr){var br,wr,Er="";if(typeof fr=="string"||typeof fr=="number")Er+=fr;else if(typeof fr=="object")if(Array.isArray(fr))for(br=0;br2&&(Br.children=arguments.length>3?n.call(arguments,2):wr),typeof fr=="function"&&fr.defaultProps!=null)for(jr in fr.defaultProps)Br[jr]===void 0&&(Br[jr]=fr.defaultProps[jr]);return g$1(fr,Br,Er,kr,null)}function g$1(fr,br,wr,Er,kr){var jr={type:fr,props:br,key:wr,ref:Er,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:kr??++u$1,__i:-1,__u:0};return kr==null&&l$1.vnode!=null&&l$1.vnode(jr),jr}function m$1(){return{current:null}}function b$1(fr){return fr.children}function k$1(fr,br){this.props=fr,this.context=br}function x$1(fr,br){if(br==null)return fr.__?x$1(fr.__,fr.__i+1):null;for(var wr;brbr&&i$2.sort(f$2));M.__r=0}function P$1(fr,br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr){var Zr,Jr,Xr,En,wn,$n=Er&&Er.__k||v$1,Tn=br.length;for(wr.__d=Wr,$(wr,br,$n),Wr=wr.__d,Zr=0;Zr0?g$1(kr.type,kr.props,kr.key,kr.ref?kr.ref:null,kr.__v):kr).__=fr,kr.__b=fr.__b+1,jr=null,(qr=kr.__i=L(kr,wr,Br,Hr))!==-1&&(Hr--,(jr=wr[qr])&&(jr.__u|=131072)),jr==null||jr.__v===null?(qr==-1&&Zr--,typeof kr.type!="function"&&(kr.__u|=65536)):qr!==Br&&(qr==Br-1?Zr--:qr==Br+1?Zr++:(qr>Br?Zr--:Zr++,kr.__u|=65536))):kr=fr.__k[Er]=null;if(Hr)for(Er=0;Er(Wr!=null&&!(131072&Wr.__u)?1:0))for(;Br>=0||qr=0){if((Wr=br[Br])&&!(131072&Wr.__u)&&kr==Wr.key&&jr===Wr.type)return Br;Br--}if(qr2&&(qr.children=arguments.length>3?n.call(arguments,2):wr),g$1(fr.type,qr,Er||fr.key,kr||fr.ref,null)}function G(fr,br){var wr={__c:br="__cC"+a$1++,__:fr,Consumer:function(Er,kr){return Er.children(kr)},Provider:function(Er){var kr,jr;return this.getChildContext||(kr=new Set,(jr={})[br]=this,this.getChildContext=function(){return jr},this.componentWillUnmount=function(){kr=null},this.shouldComponentUpdate=function(Br){this.props.value!==Br.value&&kr.forEach(function(qr){qr.__e=!0,S(qr)})},this.sub=function(Br){kr.add(Br);var qr=Br.componentWillUnmount;Br.componentWillUnmount=function(){kr&&kr.delete(Br),qr&&qr.call(Br)}}),Er.children}};return wr.Provider.__=wr.Consumer.contextType=wr}n=v$1.slice,l$1={__e:function(fr,br,wr,Er){for(var kr,jr,Br;br=br.__;)if((kr=br.__c)&&!kr.__)try{if((jr=kr.constructor)&&jr.getDerivedStateFromError!=null&&(kr.setState(jr.getDerivedStateFromError(fr)),Br=kr.__d),kr.componentDidCatch!=null&&(kr.componentDidCatch(fr,Er||{}),Br=kr.__d),Br)return kr.__E=kr}catch(qr){fr=qr}throw fr}},u$1=0,t$1=function(fr){return fr!=null&&fr.constructor==null},k$1.prototype.setState=function(fr,br){var wr;wr=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=d$1({},this.state),typeof fr=="function"&&(fr=fr(d$1({},wr),this.props)),fr&&d$1(wr,fr),fr!=null&&this.__v&&(br&&this._sb.push(br),S(this))},k$1.prototype.forceUpdate=function(fr){this.__v&&(this.__e=!0,fr&&this.__h.push(fr),S(this))},k$1.prototype.render=b$1,i$2=[],r$1=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$2=function(fr,br){return fr.__v.__b-br.__v.__b},M.__r=0,e$1=0,c$1=F$1(!1),s$1=F$1(!0),a$1=0;const preact_module=Object.freeze(Object.defineProperty({__proto__:null,Component:k$1,Fragment:b$1,cloneElement:D$1,createContext:G,createElement:_$1,createRef:m$1,h:_$1,hydrate:B$1,get isValidElement(){return t$1},get options(){return l$1},render:q$1,toChildArray:H},Symbol.toStringTag,{value:"Module"})),require$$1=getAugmentedNamespace(preact_module);var t,r,u,i$1,o=0,f$1=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function d(fr,br){c.__h&&c.__h(r,fr,o||br),o=0;var wr=r.__H||(r.__H={__:[],__h:[]});return fr>=wr.__.length&&wr.__.push({}),wr.__[fr]}function h(fr){return o=1,p(D,fr)}function p(fr,br,wr){var Er=d(t++,2);if(Er.t=fr,!Er.__c&&(Er.__=[wr?wr(br):D(void 0,br),function(qr){var Wr=Er.__N?Er.__N[0]:Er.__[0],Vr=Er.t(Wr,qr);Wr!==Vr&&(Er.__N=[Vr,Er.__[1]],Er.__c.setState({}))}],Er.__c=r,!r.u)){var kr=function(qr,Wr,Vr){if(!Er.__c.__H)return!0;var Hr=Er.__c.__H.__.filter(function(Jr){return!!Jr.__c});if(Hr.every(function(Jr){return!Jr.__N}))return!jr||jr.call(this,qr,Wr,Vr);var Zr=Er.__c.props!==qr;return Hr.forEach(function(Jr){if(Jr.__N){var Xr=Jr.__[0];Jr.__=Jr.__N,Jr.__N=void 0,Xr!==Jr.__[0]&&(Zr=!0)}}),jr&&jr.call(this,qr,Wr,Vr)||Zr};r.u=!0;var jr=r.shouldComponentUpdate,Br=r.componentWillUpdate;r.componentWillUpdate=function(qr,Wr,Vr){if(this.__e){var Hr=jr;jr=void 0,kr(qr,Wr,Vr),jr=Hr}Br&&Br.call(this,qr,Wr,Vr)},r.shouldComponentUpdate=kr}return Er.__N||Er.__}function y(fr,br){var wr=d(t++,3);!c.__s&&C(wr.__H,br)&&(wr.__=fr,wr.i=br,r.__H.__h.push(wr))}function _(fr,br){var wr=d(t++,4);!c.__s&&C(wr.__H,br)&&(wr.__=fr,wr.i=br,r.__h.push(wr))}function A(fr){return o=5,T(function(){return{current:fr}},[])}function F(fr,br,wr){o=6,_(function(){return typeof fr=="function"?(fr(br()),function(){return fr(null)}):fr?(fr.current=br(),function(){return fr.current=null}):void 0},wr==null?wr:wr.concat(fr))}function T(fr,br){var wr=d(t++,7);return C(wr.__H,br)&&(wr.__=fr(),wr.__H=br,wr.__h=fr),wr.__}function q(fr,br){return o=8,T(function(){return fr},br)}function x(fr){var br=r.context[fr.__c],wr=d(t++,9);return wr.c=fr,br?(wr.__==null&&(wr.__=!0,br.sub(r)),br.props.value):fr.__}function P(fr,br){c.useDebugValue&&c.useDebugValue(br?br(fr):fr)}function b(fr){var br=d(t++,10),wr=h();return br.__=fr,r.componentDidCatch||(r.componentDidCatch=function(Er,kr){br.__&&br.__(Er,kr),wr[1](Er)}),[wr[0],function(){wr[1](void 0)}]}function g(){var fr=d(t++,11);if(!fr.__){for(var br=r.__v;br!==null&&!br.__m&&br.__!==null;)br=br.__;var wr=br.__m||(br.__m=[0,0]);fr.__="P"+wr[0]+"-"+wr[1]++}return fr.__}function j(){for(var fr;fr=f$1.shift();)if(fr.__P&&fr.__H)try{fr.__H.__h.forEach(z),fr.__H.__h.forEach(B),fr.__H.__h=[]}catch(br){fr.__H.__h=[],c.__e(br,fr.__v)}}c.__b=function(fr){r=null,e&&e(fr)},c.__=function(fr,br){fr&&br.__k&&br.__k.__m&&(fr.__m=br.__k.__m),s&&s(fr,br)},c.__r=function(fr){a&&a(fr),t=0;var br=(r=fr.__c).__H;br&&(u===r?(br.__h=[],r.__h=[],br.__.forEach(function(wr){wr.__N&&(wr.__=wr.__N),wr.i=wr.__N=void 0})):(br.__h.forEach(z),br.__h.forEach(B),br.__h=[],t=0)),u=r},c.diffed=function(fr){v&&v(fr);var br=fr.__c;br&&br.__H&&(br.__H.__h.length&&(f$1.push(br)!==1&&i$1===c.requestAnimationFrame||((i$1=c.requestAnimationFrame)||w)(j)),br.__H.__.forEach(function(wr){wr.i&&(wr.__H=wr.i),wr.i=void 0})),u=r=null},c.__c=function(fr,br){br.some(function(wr){try{wr.__h.forEach(z),wr.__h=wr.__h.filter(function(Er){return!Er.__||B(Er)})}catch(Er){br.some(function(kr){kr.__h&&(kr.__h=[])}),br=[],c.__e(Er,wr.__v)}}),l&&l(fr,br)},c.unmount=function(fr){m&&m(fr);var br,wr=fr.__c;wr&&wr.__H&&(wr.__H.__.forEach(function(Er){try{z(Er)}catch(kr){br=kr}}),wr.__H=void 0,br&&c.__e(br,wr.__v))};var k=typeof requestAnimationFrame=="function";function w(fr){var br,wr=function(){clearTimeout(Er),k&&cancelAnimationFrame(br),setTimeout(fr)},Er=setTimeout(wr,100);k&&(br=requestAnimationFrame(wr))}function z(fr){var br=r,wr=fr.__c;typeof wr=="function"&&(fr.__c=void 0,wr()),r=br}function B(fr){var br=r;fr.__c=fr.__(),r=br}function C(fr,br){return!fr||fr.length!==br.length||br.some(function(wr,Er){return wr!==fr[Er]})}function D(fr,br){return typeof br=="function"?br(fr):br}const hooks_module=Object.freeze(Object.defineProperty({__proto__:null,useCallback:q,useContext:x,useDebugValue:P,useEffect:y,useErrorBoundary:b,useId:g,useImperativeHandle:F,useLayoutEffect:_,useMemo:T,useReducer:p,useRef:A,useState:h},Symbol.toStringTag,{value:"Module"})),require$$2$1=getAugmentedNamespace(hooks_module);var SnackbarCss={};Object.defineProperty(SnackbarCss,"__esModule",{value:!0});SnackbarCss.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(fr){var br=commonjsGlobal&&commonjsGlobal.__importDefault||function(Jr){return Jr&&Jr.__esModule?Jr:{default:Jr}};Object.defineProperty(fr,"__esModule",{value:!0}),fr.SnackbarInstance=fr.SnackbarContainer=fr.Snackbar=void 0;const wr=br(require$$0$1),Er=require$$1,kr=require$$2$1,jr=util$1,Br=br(SnackbarCss),qr="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",Wr="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class Vr{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=(0,jr.isDarkMode)()}attach(Xr){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",Xr.appendChild(this.root),this.render()}presentItem(Xr){const En=this.nextItemKey++;return this.items.set(En,Xr),this.render(),()=>{this.items.delete(En),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,Er.render)((0,Er.h)("div",null,(0,Er.h)(fr.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([Xr,En])=>(0,Er.h)(fr.SnackbarInstance,Object.assign({},En,{key:Xr}))))),this.root)}}fr.Snackbar=Vr;const Hr=Jr=>(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-container")},(0,Er.h)("style",null,Br.default),(0,Er.h)("div",{class:"-cbwsdk-snackbar"},Jr.children));fr.SnackbarContainer=Hr;const Zr=({autoExpand:Jr,message:Xr,menuItems:En})=>{const[wn,$n]=(0,kr.useState)(!0),[Tn,In]=(0,kr.useState)(Jr??!1);(0,kr.useEffect)(()=>{const Yn=[window.setTimeout(()=>{$n(!1)},1),window.setTimeout(()=>{In(!0)},1e4)];return()=>{Yn.forEach(window.clearTimeout)}});const jn=()=>{In(!Tn)};return(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-instance",wn&&"-cbwsdk-snackbar-instance-hidden",Tn&&"-cbwsdk-snackbar-instance-expanded")},(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:jn},(0,Er.h)("img",{src:qr,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},Xr),(0,Er.h)("div",{class:"-gear-container"},!Tn&&(0,Er.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,Er.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,Er.h)("img",{src:Wr,class:"-gear-icon",title:"Expand"}))),En&&En.length>0&&(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},En.map((Yn,ga)=>(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-instance-menu-item",Yn.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:Yn.onClick,key:ga},(0,Er.h)("svg",{width:Yn.svgWidth,height:Yn.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,Er.h)("path",{"fill-rule":Yn.defaultFillRule,"clip-rule":Yn.defaultClipRule,d:Yn.path,fill:"#AAAAAA"})),(0,Er.h)("span",{class:(0,wr.default)("-cbwsdk-snackbar-instance-menu-item-info",Yn.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},Yn.info)))))};fr.SnackbarInstance=Zr})(Snackbar);Object.defineProperty(WalletLinkRelayUI$1,"__esModule",{value:!0});WalletLinkRelayUI$1.WalletLinkRelayUI=void 0;const cssReset_1$1=cssReset,Snackbar_1$1=Snackbar;class WalletLinkRelayUI{constructor(){this.attached=!1,this.snackbar=new Snackbar_1$1.Snackbar}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const br=document.documentElement,wr=document.createElement("div");wr.className="-cbwsdk-css-reset",br.appendChild(wr),this.snackbar.attach(wr),this.attached=!0,(0,cssReset_1$1.injectCssReset)()}showConnecting(br){let wr;return br.isUnlinkedErrorState?wr={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:br.onResetConnection}]}:wr={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:br.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:br.onResetConnection}]},this.snackbar.presentItem(wr)}}WalletLinkRelayUI$1.WalletLinkRelayUI=WalletLinkRelayUI;var WLMobileRelayUI$1={},RedirectDialog$1={},RedirectDialogCss={};Object.defineProperty(RedirectDialogCss,"__esModule",{value:!0});RedirectDialogCss.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var __importDefault$3=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(RedirectDialog$1,"__esModule",{value:!0});RedirectDialog$1.RedirectDialog=void 0;const clsx_1=__importDefault$3(require$$0$1),preact_1=require$$1,cssReset_1=cssReset,Snackbar_1=Snackbar,util_1$6=util$1,RedirectDialog_css_1=__importDefault$3(RedirectDialogCss);class RedirectDialog{constructor(){this.root=null,this.darkMode=(0,util_1$6.isDarkMode)()}attach(){const br=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",br.appendChild(this.root),(0,cssReset_1.injectCssReset)()}present(br){this.render(br)}clear(){this.render(null)}render(br){this.root&&((0,preact_1.render)(null,this.root),br&&(0,preact_1.render)((0,preact_1.h)(RedirectDialogContent,Object.assign({},br,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}RedirectDialog$1.RedirectDialog=RedirectDialog;const RedirectDialogContent=({title:fr,buttonText:br,darkMode:wr,onButtonClick:Er,onDismiss:kr})=>{const jr=wr?"dark":"light";return(0,preact_1.h)(Snackbar_1.SnackbarContainer,{darkMode:wr},(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,preact_1.h)("style",null,RedirectDialog_css_1.default),(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:kr}),(0,preact_1.h)("div",{class:(0,clsx_1.default)("-cbwsdk-redirect-dialog-box",jr)},(0,preact_1.h)("p",null,fr),(0,preact_1.h)("button",{onClick:Er},br))))};var constants={};Object.defineProperty(constants,"__esModule",{value:!0});constants.CBW_MOBILE_DEEPLINK_URL=constants.WALLETLINK_URL=constants.CB_KEYS_URL=void 0;constants.CB_KEYS_URL="https://keys.coinbase.com/connect";constants.WALLETLINK_URL="https://www.walletlink.org";constants.CBW_MOBILE_DEEPLINK_URL="https://go.cb-w.com/walletlink";Object.defineProperty(WLMobileRelayUI$1,"__esModule",{value:!0});WLMobileRelayUI$1.WLMobileRelayUI=void 0;const RedirectDialog_1=RedirectDialog$1,util_1$5=util$1,constants_1$3=constants;class WLMobileRelayUI{constructor(){this.attached=!1,this.redirectDialog=new RedirectDialog_1.RedirectDialog}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(br){const wr=new URL(constants_1$3.CBW_MOBILE_DEEPLINK_URL);wr.searchParams.append("redirect_url",(0,util_1$5.getLocation)().href),br&&wr.searchParams.append("wl_url",br);const Er=document.createElement("a");Er.target="cbw-opener",Er.href=wr.href,Er.rel="noreferrer noopener",Er.click()}openCoinbaseWalletDeeplink(br){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(br)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(br)},99)}showConnecting(br){return()=>{this.redirectDialog.clear()}}}WLMobileRelayUI$1.WLMobileRelayUI=WLMobileRelayUI;Object.defineProperty(WalletLinkRelay$1,"__esModule",{value:!0});WalletLinkRelay$1.WalletLinkRelay=void 0;const WalletLinkConnection_1=WalletLinkConnection$1,constants_1$2=constants$1,RelayEventManager_1$1=RelayEventManager$1,WalletLinkSession_1=WalletLinkSession$1,Web3Response_1$1=Web3Response,util_1$4=util$1,WalletLinkRelayUI_1=WalletLinkRelayUI$1,WLMobileRelayUI_1=WLMobileRelayUI$1,error_1$6=error,util_2$1=util$6,ScopedLocalStorage_1$4=ScopedLocalStorage$1;class WalletLinkRelay{constructor(br){this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.isMobileWeb=(0,util_1$4.isMobileWeb)(),this.appName="",this.appLogoUrl=null,this.linkedUpdated=jr=>{this.isLinked=jr;const Br=this.storage.getItem(constants_1$2.LOCAL_STORAGE_ADDRESSES_KEY);if(jr&&(this._session.linked=jr),this.isUnlinkedErrorState=!1,Br){const qr=Br.split(" "),Wr=this.storage.getItem("IsStandaloneSigning")==="true";qr[0]!==""&&!jr&&this._session.linked&&!Wr&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(jr,Br)=>{this.storage.setItem(jr,Br)},this.chainUpdated=(jr,Br)=>{this.chainCallbackParams.chainId===jr&&this.chainCallbackParams.jsonRpcUrl===Br||(this.chainCallbackParams={chainId:jr,jsonRpcUrl:Br},this.chainCallback&&this.chainCallback(jr,Br))},this.accountUpdated=jr=>{this.accountsCallback&&this.accountsCallback([jr]),WalletLinkRelay.accountRequestCallbackIds.size>0&&(Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach(Br=>{const qr={type:"WEB3_RESPONSE",id:Br,response:{method:"requestEthereumAccounts",result:[jr]}};this.invokeCallback(Object.assign(Object.assign({},qr),{id:Br}))}),WalletLinkRelay.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=br.linkAPIUrl,this.storage=br.storage;const{session:wr,ui:Er,connection:kr}=this.subscribe();this._session=wr,this.connection=kr,this.relayEventManager=new RelayEventManager_1$1.RelayEventManager,this.ui=Er}subscribe(){const br=WalletLinkSession_1.WalletLinkSession.load(this.storage)||new WalletLinkSession_1.WalletLinkSession(this.storage).save(),{linkAPIUrl:wr}=this,Er=new WalletLinkConnection_1.WalletLinkConnection({session:br,linkAPIUrl:wr,listener:this}),kr=this.isMobileWeb?new WLMobileRelayUI_1.WLMobileRelayUI:new WalletLinkRelayUI_1.WalletLinkRelayUI;return Er.connect(),{session:br,ui:kr,connection:Er}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(br=>setTimeout(()=>br(null),1e3))]).then(()=>{this.connection.destroy();const br=WalletLinkSession_1.WalletLinkSession.load(this.storage);(br==null?void 0:br.id)===this._session.id&&ScopedLocalStorage_1$4.ScopedLocalStorage.clearAll(),document.location.reload()}).catch(br=>{})}setAppInfo(br,wr){this.appName=br,this.appLogoUrl=wr}getStorageItem(br){return this.storage.getItem(br)}setStorageItem(br,wr){this.storage.setItem(br,wr)}signEthereumMessage(br,wr,Er,kr){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(br,!0),address:wr,addPrefix:Er,typedDataJson:kr||null}})}ethereumAddressFromSignedMessage(br,wr,Er){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(br,!0),signature:(0,util_2$1.hexStringFromBuffer)(wr,!0),addPrefix:Er}})}signEthereumTransaction(br){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:br.fromAddress,toAddress:br.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(br.weiValue),data:(0,util_2$1.hexStringFromBuffer)(br.data,!0),nonce:br.nonce,gasPriceInWei:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxFeePerGas:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxPriorityFeePerGas:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,gasLimit:br.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(br.gasLimit):null,chainId:br.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(br){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:br.fromAddress,toAddress:br.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(br.weiValue),data:(0,util_2$1.hexStringFromBuffer)(br.data,!0),nonce:br.nonce,gasPriceInWei:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxFeePerGas:br.maxFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(br.maxFeePerGas):null,maxPriorityFeePerGas:br.maxPriorityFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(br.maxPriorityFeePerGas):null,gasLimit:br.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(br.gasLimit):null,chainId:br.chainId,shouldSubmit:!0}})}submitEthereumTransaction(br,wr){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,util_2$1.hexStringFromBuffer)(br,!0),chainId:wr}})}scanQRCode(br){return this.sendRequest({method:"scanQRCode",params:{regExp:br}})}getWalletLinkSession(){return this._session}genericRequest(br,wr){return this.sendRequest({method:"generic",params:{action:wr,data:br}})}sendGenericMessage(br){return this.sendRequest(br)}sendRequest(br){let wr=null;const Er=(0,util_2$1.randomBytesHex)(8),kr=jr=>{this.publishWeb3RequestCanceledEvent(Er),this.handleErrorResponse(Er,br.method,jr),wr==null||wr()};return new Promise((jr,Br)=>{wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:kr,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(Er,qr=>{if(wr==null||wr(),(0,Web3Response_1$1.isErrorResponse)(qr))return Br(new Error(qr.errorMessage));jr(qr)}),this.publishWeb3RequestEvent(Er,br)})}setAccountsCallback(br){this.accountsCallback=br}setChainCallback(br){this.chainCallback=br}setDappDefaultChainCallback(br){this.dappDefaultChain=br}publishWeb3RequestEvent(br,wr){const Er={type:"WEB3_REQUEST",id:br,request:wr};this.publishEvent("Web3Request",Er,!0).then(kr=>{}).catch(kr=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:Er.id,response:{method:wr.method,errorMessage:kr.message}})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(wr.method)}openCoinbaseWalletDeeplink(br){if(this.ui instanceof WLMobileRelayUI_1.WLMobileRelayUI)switch(br){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(br){const wr={type:"WEB3_REQUEST_CANCELED",id:br};this.publishEvent("Web3RequestCanceled",wr,!1).then()}publishEvent(br,wr,Er){return this.connection.publishEvent(br,wr,Er)}handleWeb3ResponseMessage(br){const{response:wr}=br;if(wr.method==="requestEthereumAccounts"){WalletLinkRelay.accountRequestCallbackIds.forEach(Er=>this.invokeCallback(Object.assign(Object.assign({},br),{id:Er}))),WalletLinkRelay.accountRequestCallbackIds.clear();return}this.invokeCallback(br)}handleErrorResponse(br,wr,Er){var kr;const jr=(kr=Er==null?void 0:Er.message)!==null&&kr!==void 0?kr:"Unspecified error message.";this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:br,response:{method:wr,errorMessage:jr}})}invokeCallback(br){const wr=this.relayEventManager.callbacks.get(br.id);wr&&(wr(br.response),this.relayEventManager.callbacks.delete(br.id))}requestEthereumAccounts(){const br={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},wr=(0,util_2$1.randomBytesHex)(8);return new Promise((Er,kr)=>{this.relayEventManager.callbacks.set(wr,jr=>{if((0,Web3Response_1$1.isErrorResponse)(jr))return kr(new Error(jr.errorMessage));Er(jr)}),WalletLinkRelay.accountRequestCallbackIds.add(wr),this.publishWeb3RequestEvent(wr,br)})}watchAsset(br,wr,Er,kr,jr,Br){const qr={method:"watchAsset",params:{type:br,options:{address:wr,symbol:Er,decimals:kr,image:jr},chainId:Br}};let Wr=null;const Vr=(0,util_2$1.randomBytesHex)(8),Hr=Zr=>{this.publishWeb3RequestCanceledEvent(Vr),this.handleErrorResponse(Vr,qr.method,Zr),Wr==null||Wr()};return Wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:Hr,onResetConnection:this.resetAndReload}),new Promise((Zr,Jr)=>{this.relayEventManager.callbacks.set(Vr,Xr=>{if(Wr==null||Wr(),(0,Web3Response_1$1.isErrorResponse)(Xr))return Jr(new Error(Xr.errorMessage));Zr(Xr)}),this.publishWeb3RequestEvent(Vr,qr)})}addEthereumChain(br,wr,Er,kr,jr,Br){const qr={method:"addEthereumChain",params:{chainId:br,rpcUrls:wr,blockExplorerUrls:kr,chainName:jr,iconUrls:Er,nativeCurrency:Br}};let Wr=null;const Vr=(0,util_2$1.randomBytesHex)(8),Hr=Zr=>{this.publishWeb3RequestCanceledEvent(Vr),this.handleErrorResponse(Vr,qr.method,Zr),Wr==null||Wr()};return Wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:Hr,onResetConnection:this.resetAndReload}),new Promise((Zr,Jr)=>{this.relayEventManager.callbacks.set(Vr,Xr=>{if(Wr==null||Wr(),(0,Web3Response_1$1.isErrorResponse)(Xr))return Jr(new Error(Xr.errorMessage));Zr(Xr)}),this.publishWeb3RequestEvent(Vr,qr)})}switchEthereumChain(br,wr){const Er={method:"switchEthereumChain",params:Object.assign({chainId:br},{address:wr})},kr=(0,util_2$1.randomBytesHex)(8);return new Promise((jr,Br)=>{this.relayEventManager.callbacks.set(kr,qr=>{if((0,Web3Response_1$1.isErrorResponse)(qr)&&qr.errorCode)return Br(error_1$6.standardErrors.provider.custom({code:qr.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Web3Response_1$1.isErrorResponse)(qr))return Br(new Error(qr.errorMessage));jr(qr)}),this.publishWeb3RequestEvent(kr,Er)})}}WalletLinkRelay$1.WalletLinkRelay=WalletLinkRelay;WalletLinkRelay.accountRequestCallbackIds=new Set;var __importDefault$2=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(WalletLinkSigner$1,"__esModule",{value:!0});WalletLinkSigner$1.WalletLinkSigner=void 0;const eth_eip712_util_1=__importDefault$2(ethEip712Util),constants_1$1=constants$1,RelayEventManager_1=RelayEventManager$1,Web3Response_1=Web3Response,WalletLinkRelay_1=WalletLinkRelay$1,constants_2=constants,error_1$5=error,util_1$3=util$6,ScopedLocalStorage_1$3=ScopedLocalStorage$1,DEFAULT_CHAIN_ID_KEY="DefaultChainId",DEFAULT_JSON_RPC_URL="DefaultJsonRpcUrl";class WalletLinkSigner{constructor(br){var wr,Er;this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1;const{appName:kr,appLogoUrl:jr}=br.metadata;this._appName=kr,this._appLogoUrl=jr,this._storage=new ScopedLocalStorage_1$3.ScopedLocalStorage("walletlink",constants_2.WALLETLINK_URL),this.updateListener=br.updateListener,this._relayEventManager=new RelayEventManager_1.RelayEventManager,this._jsonRpcUrlFromOpts="";const Br=this._storage.getItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY);if(Br){const Wr=Br.split(" ");Wr[0]!==""&&(this._addresses=Wr.map(Vr=>(0,util_1$3.ensureAddressString)(Vr)),(wr=this.updateListener)===null||wr===void 0||wr.onAccountsUpdate({accounts:this._addresses,source:"storage"}))}this._storage.getItem(DEFAULT_CHAIN_ID_KEY)&&((Er=this.updateListener)===null||Er===void 0||Er.onChainUpdate({chain:{id:this.getChainId(),rpcUrl:this.jsonRpcUrl},source:"storage"}),this.hasMadeFirstChainChangedEmission=!0),this.initializeRelay()}getSession(){const br=this.initializeRelay(),{id:wr,secret:Er}=br.getWalletLinkSession();return{id:wr,secret:Er}}async handshake(){return await this.request({method:"eth_requestAccounts"})}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var br;return(br=this._storage.getItem(DEFAULT_JSON_RPC_URL))!==null&&br!==void 0?br:this._jsonRpcUrlFromOpts}set jsonRpcUrl(br){this._storage.setItem(DEFAULT_JSON_RPC_URL,br)}updateProviderInfo(br,wr){var Er;this.jsonRpcUrl=br;const kr=this.getChainId();this._storage.setItem(DEFAULT_CHAIN_ID_KEY,wr.toString(10)),((0,util_1$3.ensureIntNumber)(wr)!==kr||!this.hasMadeFirstChainChangedEmission)&&((Er=this.updateListener)===null||Er===void 0||Er.onChainUpdate({chain:{id:wr,rpcUrl:br},source:"wallet"}),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(br,wr,Er,kr,jr,Br){const Wr=await this.initializeRelay().watchAsset(br,wr,Er,kr,jr,Br==null?void 0:Br.toString());return(0,Web3Response_1.isErrorResponse)(Wr)?!1:!!Wr.result}async addEthereumChain(br,wr,Er,kr,jr,Br){var qr,Wr;if((0,util_1$3.ensureIntNumber)(br)===this.getChainId())return!1;const Vr=this.initializeRelay();this._isAuthorized()||await Vr.requestEthereumAccounts();const Hr=await Vr.addEthereumChain(br.toString(),wr,jr,Er,kr,Br);return(0,Web3Response_1.isErrorResponse)(Hr)?!1:(((qr=Hr.result)===null||qr===void 0?void 0:qr.isApproved)===!0&&this.updateProviderInfo(wr[0],br),((Wr=Hr.result)===null||Wr===void 0?void 0:Wr.isApproved)===!0)}async switchEthereumChain(br){const Er=await this.initializeRelay().switchEthereumChain(br.toString(10),this.selectedAddress||void 0);if((0,Web3Response_1.isErrorResponse)(Er)){if(!Er.errorCode)return;throw Er.errorCode===error_1$5.standardErrorCodes.provider.unsupportedChain?error_1$5.standardErrors.provider.unsupportedChain():error_1$5.standardErrors.provider.custom({message:Er.errorMessage,code:Er.errorCode})}const kr=Er.result;kr.isApproved&&kr.rpcUrl.length>0&&this.updateProviderInfo(kr.rpcUrl,br)}async disconnect(){this._relay&&this._relay.resetAndReload(),this._storage.clear()}async request(br){try{return this._request(br).catch(wr=>{throw wr})}catch(wr){return Promise.reject(wr)}}async _request(br){if(!br||typeof br!="object"||Array.isArray(br))throw error_1$5.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:br});const{method:wr,params:Er}=br;if(typeof wr!="string"||wr.length===0)throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:br});if(Er!==void 0&&!Array.isArray(Er)&&(typeof Er!="object"||Er===null))throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:br});const kr=Er===void 0?[]:Er,jr=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:wr,params:kr,jsonrpc:"2.0",id:jr})).result}_setAddresses(br,wr){var Er;if(!Array.isArray(br))throw new Error("addresses is not an array");const kr=br.map(jr=>(0,util_1$3.ensureAddressString)(jr));JSON.stringify(kr)!==JSON.stringify(this._addresses)&&(this._addresses=kr,(Er=this.updateListener)===null||Er===void 0||Er.onAccountsUpdate({accounts:kr,source:"wallet"}),this._storage.setItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY,kr.join(" ")))}_sendRequestAsync(br){return new Promise((wr,Er)=>{try{const kr=this._handleSynchronousMethods(br);if(kr!==void 0)return wr({jsonrpc:"2.0",id:br.id,result:kr})}catch(kr){return Er(kr)}this._handleAsynchronousMethods(br).then(kr=>kr&&wr(Object.assign(Object.assign({},kr),{id:br.id}))).catch(kr=>Er(kr))})}_handleSynchronousMethods(br){const{method:wr}=br;switch(wr){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(br){const{method:wr}=br,Er=br.params||[];switch(wr){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(Er);case"eth_ecRecover":return this._eth_ecRecover(Er);case"personal_sign":return this._personal_sign(Er);case"personal_ecRecover":return this._personal_ecRecover(Er);case"eth_signTransaction":return this._eth_signTransaction(Er);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(Er);case"eth_sendTransaction":return this._eth_sendTransaction(Er);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(Er);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(Er);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(Er);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(Er);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(Er);case"wallet_watchAsset":return this._wallet_watchAsset(Er);default:return this._throwUnsupportedMethodError()}}_isKnownAddress(br){try{const wr=(0,util_1$3.ensureAddressString)(br);return this._addresses.map(kr=>(0,util_1$3.ensureAddressString)(kr)).includes(wr)}catch{}return!1}_ensureKnownAddress(br){if(!this._isKnownAddress(br))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(br){const wr=br.from?(0,util_1$3.ensureAddressString)(br.from):this.selectedAddress;if(!wr)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(wr);const Er=br.to?(0,util_1$3.ensureAddressString)(br.to):null,kr=br.value!=null?(0,util_1$3.ensureBigInt)(br.value):BigInt(0),jr=br.data?(0,util_1$3.ensureBuffer)(br.data):Buffer$2.alloc(0),Br=br.nonce!=null?(0,util_1$3.ensureIntNumber)(br.nonce):null,qr=br.gasPrice!=null?(0,util_1$3.ensureBigInt)(br.gasPrice):null,Wr=br.maxFeePerGas!=null?(0,util_1$3.ensureBigInt)(br.maxFeePerGas):null,Vr=br.maxPriorityFeePerGas!=null?(0,util_1$3.ensureBigInt)(br.maxPriorityFeePerGas):null,Hr=br.gas!=null?(0,util_1$3.ensureBigInt)(br.gas):null,Zr=br.chainId?(0,util_1$3.ensureIntNumber)(br.chainId):this.getChainId();return{fromAddress:wr,toAddress:Er,weiValue:kr,data:jr,nonce:Br,gasPriceInWei:qr,maxFeePerGas:Wr,maxPriorityFeePerGas:Vr,gasLimit:Hr,chainId:Zr}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw error_1$5.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw error_1$5.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(br,wr,Er,kr){this._ensureKnownAddress(wr);try{const Br=await this.initializeRelay().signEthereumMessage(br,wr,Er,kr);if((0,Web3Response_1.isErrorResponse)(Br))throw new Error(Br.errorMessage);return{jsonrpc:"2.0",id:0,result:Br.result}}catch(jr){throw typeof jr.message=="string"&&jr.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied message signature"):jr}}async _ethereumAddressFromSignedMessage(br,wr,Er){const jr=await this.initializeRelay().ethereumAddressFromSignedMessage(br,wr,Er);if((0,Web3Response_1.isErrorResponse)(jr))throw new Error(jr.errorMessage);return{jsonrpc:"2.0",id:0,result:jr.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,util_1$3.hexStringFromIntNumber)(this.getChainId())}getChainId(){const br=this._storage.getItem(DEFAULT_CHAIN_ID_KEY);if(!br)return(0,util_1$3.ensureIntNumber)(1);const wr=parseInt(br,10);return(0,util_1$3.ensureIntNumber)(wr)}async _eth_requestAccounts(){if(this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let br;try{if(br=await this.initializeRelay().requestEthereumAccounts(),(0,Web3Response_1.isErrorResponse)(br))throw new Error(br.errorMessage)}catch(wr){throw typeof wr.message=="string"&&wr.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied account authorization"):wr}if(!br.result)throw new Error("accounts received is empty");return this._setAddresses(br.result),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._signEthereumMessage(Er,wr,!1)}_eth_ecRecover(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._ethereumAddressFromSignedMessage(wr,Er,!1)}_personal_sign(br){this._requireAuthorization();const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureAddressString)(br[1]);return this._signEthereumMessage(wr,Er,!0)}_personal_ecRecover(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._ethereumAddressFromSignedMessage(wr,Er,!0)}async _eth_signTransaction(br){this._requireAuthorization();const wr=this._prepareTransactionParams(br[0]||{});try{const kr=await this.initializeRelay().signEthereumTransaction(wr);if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}catch(Er){throw typeof Er.message=="string"&&Er.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):Er}}async _eth_sendRawTransaction(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),kr=await this.initializeRelay().submitEthereumTransaction(wr,this.getChainId());if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}async _eth_sendTransaction(br){this._requireAuthorization();const wr=this._prepareTransactionParams(br[0]||{});try{const kr=await this.initializeRelay().signAndSubmitEthereumTransaction(wr);if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}catch(Er){throw typeof Er.message=="string"&&Er.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):Er}}async _eth_signTypedData_v1(br){this._requireAuthorization();const wr=(0,util_1$3.ensureParsedJSONObject)(br[0]),Er=(0,util_1$3.ensureAddressString)(br[1]);this._ensureKnownAddress(Er);const kr=eth_eip712_util_1.default.hashForSignTypedDataLegacy({data:wr}),jr=JSON.stringify(wr,null,2);return this._signEthereumMessage(kr,Er,!1,jr)}async _eth_signTypedData_v3(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureParsedJSONObject)(br[1]);this._ensureKnownAddress(wr);const kr=eth_eip712_util_1.default.hashForSignTypedData_v3({data:Er}),jr=JSON.stringify(Er,null,2);return this._signEthereumMessage(kr,wr,!1,jr)}async _eth_signTypedData_v4(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureParsedJSONObject)(br[1]);this._ensureKnownAddress(wr);const kr=eth_eip712_util_1.default.hashForSignTypedData_v4({data:Er}),jr=JSON.stringify(Er,null,2);return this._signEthereumMessage(kr,wr,!1,jr)}async _wallet_addEthereumChain(br){var wr,Er,kr,jr;const Br=br[0];if(((wr=Br.rpcUrls)===null||wr===void 0?void 0:wr.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!Br.chainName||Br.chainName.trim()==="")throw error_1$5.standardErrors.rpc.invalidParams("chainName is a required field");if(!Br.nativeCurrency)throw error_1$5.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const qr=parseInt(Br.chainId,16);return await this.addEthereumChain(qr,(Er=Br.rpcUrls)!==null&&Er!==void 0?Er:[],(kr=Br.blockExplorerUrls)!==null&&kr!==void 0?kr:[],Br.chainName,(jr=Br.iconUrls)!==null&&jr!==void 0?jr:[],Br.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(br){const wr=br[0];return await this.switchEthereumChain(parseInt(wr.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(br){const wr=Array.isArray(br)?br[0]:br;if(!wr.type)throw error_1$5.standardErrors.rpc.invalidParams("Type is required");if((wr==null?void 0:wr.type)!=="ERC20")throw error_1$5.standardErrors.rpc.invalidParams(`Asset of type '${wr.type}' is not supported`);if(!(wr!=null&&wr.options))throw error_1$5.standardErrors.rpc.invalidParams("Options are required");if(!(wr!=null&&wr.options.address))throw error_1$5.standardErrors.rpc.invalidParams("Address is required");const Er=this.getChainId(),{address:kr,symbol:jr,image:Br,decimals:qr}=wr.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(wr.type,kr,jr,qr,Br,Er)}}initializeRelay(){if(!this._relay){const br=new WalletLinkRelay_1.WalletLinkRelay({linkAPIUrl:constants_2.WALLETLINK_URL,storage:this._storage});br.setAppInfo(this._appName,this._appLogoUrl),br.attachUI(),br.setAccountsCallback((wr,Er)=>this._setAddresses(wr,Er)),br.setChainCallback((wr,Er)=>{this.updateProviderInfo(Er,parseInt(wr,10))}),this._relay=br}return this._relay}}WalletLinkSigner$1.WalletLinkSigner=WalletLinkSigner;var provider={};Object.defineProperty(provider,"__esModule",{value:!0});provider.checkErrorForInvalidRequestArgs=provider.getCoinbaseInjectedProvider=provider.getCoinbaseInjectedSigner=provider.fetchRPCRequest=void 0;const version_1$2=version$8,error_1$4=error;async function fetchRPCRequest(fr,br){if(!br.rpcUrl)throw error_1$4.standardErrors.rpc.internal("No RPC URL set for chain");const wr=Object.assign(Object.assign({},fr),{jsonrpc:"2.0",id:crypto.randomUUID()});return(await(await window.fetch(br.rpcUrl,{method:"POST",body:JSON.stringify(wr),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":version_1$2.LIB_VERSION}})).json()).result}provider.fetchRPCRequest=fetchRPCRequest;function getCoinbaseInjectedSigner(){return globalThis.coinbaseWalletSigner}provider.getCoinbaseInjectedSigner=getCoinbaseInjectedSigner;function getCoinbaseInjectedLegacyProvider(){return globalThis.coinbaseWalletExtension}function getInjectedEthereum(){var fr,br;try{const wr=globalThis;return(fr=wr.ethereum)!==null&&fr!==void 0?fr:(br=wr.top)===null||br===void 0?void 0:br.ethereum}catch{return}}function getCoinbaseInjectedProvider({metadata:fr,preference:br}){var wr;if(br.options!=="smartWalletOnly"){if(getCoinbaseInjectedSigner())return;const jr=getCoinbaseInjectedLegacyProvider();if(jr){const{appName:Br,appLogoUrl:qr,appChainIds:Wr}=fr;return(wr=jr.setAppInfo)===null||wr===void 0||wr.call(jr,Br,qr,Wr),jr}}const Er=getInjectedEthereum();if(Er!=null&&Er.isCoinbaseBrowser)return Er}provider.getCoinbaseInjectedProvider=getCoinbaseInjectedProvider;function checkErrorForInvalidRequestArgs(fr){if(!fr||typeof fr!="object"||Array.isArray(fr))return error_1$4.standardErrors.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:fr});const{method:br,params:wr}=fr;if(typeof br!="string"||br.length===0)return error_1$4.standardErrors.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:fr});if(wr!==void 0&&!Array.isArray(wr)&&(typeof wr!="object"||wr===null))return error_1$4.standardErrors.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:fr})}provider.checkErrorForInvalidRequestArgs=checkErrorForInvalidRequestArgs;Object.defineProperty(util$5,"__esModule",{value:!0});util$5.createSigner=util$5.fetchSignerType=util$5.storeSignerType=util$5.loadSignerType=void 0;const SCWSigner_1=SCWSigner$1,WalletLinkSigner_1=WalletLinkSigner$1,error_1$3=error,provider_1$2=provider,ScopedLocalStorage_1$2=ScopedLocalStorage$1,SIGNER_TYPE_KEY="SignerType",storage$1=new ScopedLocalStorage_1$2.ScopedLocalStorage("CBWSDK","SignerConfigurator");function loadSignerType(){return storage$1.getItem(SIGNER_TYPE_KEY)}util$5.loadSignerType=loadSignerType;function storeSignerType(fr){storage$1.setItem(SIGNER_TYPE_KEY,fr)}util$5.storeSignerType=storeSignerType;async function fetchSignerType(fr){const{communicator:br,metadata:wr}=fr;listenForWalletLinkSessionRequest(br,wr).catch(()=>{});const Er={id:crypto.randomUUID(),event:"selectSignerType",data:fr.preference},{data:kr}=await br.postRequestAndWaitForResponse(Er);return kr}util$5.fetchSignerType=fetchSignerType;function createSigner(fr){const{signerType:br,metadata:wr,communicator:Er,updateListener:kr}=fr;switch(br){case"scw":return new SCWSigner_1.SCWSigner({metadata:wr,updateListener:kr,communicator:Er});case"walletlink":return new WalletLinkSigner_1.WalletLinkSigner({metadata:wr,updateListener:kr});case"extension":{const jr=(0,provider_1$2.getCoinbaseInjectedSigner)();if(!jr)throw error_1$3.standardErrors.rpc.internal("injected signer not found");return jr}}}util$5.createSigner=createSigner;async function listenForWalletLinkSessionRequest(fr,br){await fr.onMessage(({event:Er})=>Er==="WalletLinkSessionRequest");const wr=new WalletLinkSigner_1.WalletLinkSigner({metadata:br});fr.postMessage({event:"WalletLinkUpdate",data:{session:wr.getSession()}}),await wr.handshake(),fr.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var Communicator$1={},util={};Object.defineProperty(util,"__esModule",{value:!0});util.closePopup=util.openPopup=void 0;const error_1$2=error,POPUP_WIDTH=420,POPUP_HEIGHT=540;function openPopup(fr){const br=(window.innerWidth-POPUP_WIDTH)/2+window.screenX,wr=(window.innerHeight-POPUP_HEIGHT)/2+window.screenY,Er=window.open(fr,"Smart Wallet",`width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${br}, top=${wr}`);if(Er==null||Er.focus(),!Er)throw error_1$2.standardErrors.rpc.internal("Pop up window failed to open");return Er}util.openPopup=openPopup;function closePopup(fr){fr&&!fr.closed&&fr.close()}util.closePopup=closePopup;Object.defineProperty(Communicator$1,"__esModule",{value:!0});Communicator$1.Communicator=void 0;const version_1$1=version$8,util_1$2=util,constants_1=constants,error_1$1=error;class Communicator{constructor(br=constants_1.CB_KEYS_URL){this.popup=null,this.listeners=new Map,this.postMessage=async wr=>{(await this.waitForPopupLoaded()).postMessage(wr,this.url.origin)},this.postRequestAndWaitForResponse=async wr=>{const Er=this.onMessage(({requestId:kr})=>kr===wr.id);return this.postMessage(wr),await Er},this.onMessage=async wr=>new Promise((Er,kr)=>{const jr=Br=>{if(Br.origin!==this.url.origin)return;const qr=Br.data;wr(qr)&&(Er(qr),window.removeEventListener("message",jr),this.listeners.delete(jr))};window.addEventListener("message",jr),this.listeners.set(jr,{reject:kr})}),this.disconnect=()=>{(0,util_1$2.closePopup)(this.popup),this.popup=null,this.listeners.forEach(({reject:wr},Er)=>{wr(error_1$1.standardErrors.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",Er)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=(0,util_1$2.openPopup)(this.url),this.onMessage(({event:wr})=>wr==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:wr})=>wr==="PopupLoaded").then(wr=>{this.postMessage({requestId:wr.id,data:{version:version_1$1.LIB_VERSION}})}).then(()=>{if(!this.popup)throw error_1$1.standardErrors.rpc.internal();return this.popup})),this.url=new URL(br)}}Communicator$1.Communicator=Communicator;var method={};Object.defineProperty(method,"__esModule",{value:!0});method.determineMethodCategory=void 0;const mapping={handshake:["eth_requestAccounts"],sign:["eth_ecRecover","personal_sign","personal_ecRecover","eth_signTransaction","eth_sendTransaction","eth_signTypedData_v1","eth_signTypedData_v3","eth_signTypedData_v4","eth_signTypedData","wallet_addEthereumChain","wallet_switchEthereumChain","wallet_watchAsset","wallet_getCapabilities","wallet_sendCalls","wallet_showCallsStatus"],state:["eth_chainId","eth_accounts","eth_coinbase","net_version"],deprecated:["eth_sign","eth_signTypedData_v2"],unsupported:["eth_subscribe","eth_unsubscribe"],fetch:[]};function determineMethodCategory(fr){for(const br in mapping){const wr=br;if(mapping[wr].includes(fr))return wr}}method.determineMethodCategory=determineMethodCategory;var __rest$2=commonjsGlobal&&commonjsGlobal.__rest||function(fr,br){var wr={};for(var Er in fr)Object.prototype.hasOwnProperty.call(fr,Er)&&br.indexOf(Er)<0&&(wr[Er]=fr[Er]);if(fr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var kr=0,Er=Object.getOwnPropertySymbols(fr);kr{try{if(this.connected)return this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),this.accounts;const Hr=await this.requestSignerSelection(),Zr=this.initSigner(Hr),Jr=await Zr.handshake();return this.signer=Zr,(0,util_2.storeSignerType)(Hr),this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),Jr}catch(Hr){throw this.handleUnauthorizedError(Hr),Hr}},sign:async Vr=>{if(!this.connected||!this.signer)throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");try{return await this.signer.request(Vr)}catch(Hr){throw this.handleUnauthorizedError(Hr),Hr}},fetch:Vr=>(0,provider_1$1.fetchRPCRequest)(Vr,this.chain),state:Vr=>{const Hr=()=>{if(this.connected)return this.accounts;throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")};switch(Vr.method){case"eth_chainId":return(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id));case"net_version":return this.chain.id;case"eth_accounts":return Hr();case"eth_coinbase":return Hr()[0];default:return this.handlers.unsupported(Vr)}},deprecated:({method:Vr})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${Vr} is deprecated.`)},unsupported:({method:Vr})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${Vr} is not supported.`)}},this.isCoinbaseWallet=!0,this.updateListener={onAccountsUpdate:({accounts:Vr,source:Hr})=>{(0,util_1$1.areAddressArraysEqual)(this.accounts,Vr)||(this.accounts=Vr,Hr!=="storage"&&this.emit("accountsChanged",this.accounts))},onChainUpdate:({chain:Vr,source:Hr})=>{Vr.id===this.chain.id&&Vr.rpcUrl===this.chain.rpcUrl||(this.chain=Vr,Hr!=="storage"&&this.emit("chainChanged",(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(Vr.id))))}},this.metadata=kr,this.preference=qr,this.communicator=new Communicator_1.Communicator(Br),this.chain={id:(Er=(wr=kr.appChainIds)===null||wr===void 0?void 0:wr[0])!==null&&Er!==void 0?Er:1};const Wr=(0,util_2.loadSignerType)();this.signer=Wr?this.initSigner(Wr):null}get connected(){return this.accounts.length>0}async request(br){var wr;try{const Er=(0,provider_1$1.checkErrorForInvalidRequestArgs)(br);if(Er)throw Er;const kr=(wr=(0,method_1.determineMethodCategory)(br.method))!==null&&wr!==void 0?wr:"fetch";return this.handlers[kr](br)}catch(Er){return Promise.reject((0,serialize_1$1.serializeError)(Er,br.method))}}handleUnauthorizedError(br){br.code===error_1.standardErrorCodes.provider.unauthorized&&this.disconnect()}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){this.accounts=[],this.chain={id:1},ScopedLocalStorage_1$1.ScopedLocalStorage.clearAll(),this.emit("disconnect",error_1.standardErrors.provider.disconnected("User initiated disconnection"))}requestSignerSelection(){return(0,util_2.fetchSignerType)({communicator:this.communicator,preference:this.preference,metadata:this.metadata})}initSigner(br){return(0,util_2.createSigner)({signerType:br,metadata:this.metadata,communicator:this.communicator,updateListener:this.updateListener})}}CoinbaseWalletProvider$1.CoinbaseWalletProvider=CoinbaseWalletProvider;Object.defineProperty(CoinbaseWalletSDK$1,"__esModule",{value:!0});CoinbaseWalletSDK$1.CoinbaseWalletSDK=void 0;const wallet_logo_1=walletLogo$1,CoinbaseWalletProvider_1=CoinbaseWalletProvider$1,ScopedLocalStorage_1=ScopedLocalStorage$1,version_1=version$8,util_1=util$6,provider_1=provider;class CoinbaseWalletSDK{constructor(br){this.metadata={appName:br.appName||"Dapp",appLogoUrl:br.appLogoUrl||(0,util_1.getFavicon)(),appChainIds:br.appChainIds||[]},this.storeLatestVersion()}makeWeb3Provider(br={options:"all"}){var wr;const Er={metadata:this.metadata,preference:br};return(wr=(0,provider_1.getCoinbaseInjectedProvider)(Er))!==null&&wr!==void 0?wr:new CoinbaseWalletProvider_1.CoinbaseWalletProvider(Er)}getCoinbaseWalletLogo(br,wr=240){return(0,wallet_logo_1.walletLogo)(br,wr)}storeLatestVersion(){new ScopedLocalStorage_1.ScopedLocalStorage("CBWSDK").setItem("VERSION",version_1.LIB_VERSION)}}CoinbaseWalletSDK$1.CoinbaseWalletSDK=CoinbaseWalletSDK;(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.CoinbaseWalletSDK=void 0;const br=CoinbaseWalletSDK$1;fr.default=br.CoinbaseWalletSDK;var wr=CoinbaseWalletSDK$1;Object.defineProperty(fr,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return wr.CoinbaseWalletSDK}})})(dist);let coinbaseProvider;const baseSepolia=84532,baseMainnet=8453,getCoinbaseProvider=({appLogoUrl:fr,appName:br,evmNetworks:wr,walletPreference:Er}={})=>{const kr=wr==null?void 0:wr.map(qr=>Number(qr.chainId));return(wr==null?void 0:wr.some(qr=>qr.chainId===baseSepolia))&&(kr==null||kr.sort((qr,Wr)=>qr===baseSepolia?-1:Wr===baseSepolia?1:0)),(wr==null?void 0:wr.some(qr=>qr.chainId===baseMainnet))&&(kr==null||kr.sort((qr,Wr)=>qr===baseMainnet?-1:Wr===baseMainnet?1:0)),coinbaseProvider||(coinbaseProvider=new dist.CoinbaseWalletSDK({appChainIds:kr,appLogoUrl:fr,appName:br}).makeWeb3Provider({options:Er??"all"})),coinbaseProvider};class Coinbase extends EthereumWalletConnector{constructor(br){var{appName:wr,appLogoUrl:Er,evmNetworks:kr,coinbaseWalletPreference:jr}=br,Br=__rest$6(br,["appName","appLogoUrl","evmNetworks","coinbaseWalletPreference"]);super(Object.assign({evmNetworks:kr},Br)),this.name="Coinbase",this.overrideKey="coinbase",this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.canConnectViaQrCode=!1,this.canConnectViaCustodialService=!this.isInstalledOnBrowser(),this.coinbaseProviderOpts={appLogoUrl:Er,appName:wr,evmNetworks:kr,walletPreference:jr}}get coinbaseProvider(){return getCoinbaseProvider(this.coinbaseProviderOpts)}getConnectedAccounts(){return __awaiter$8(this,void 0,void 0,function*(){try{const br=yield this.coinbaseProvider.request({method:"eth_accounts"});return br[0]&&this.setActiveAccount(br[0]),br}catch{return[]}})}isInstalledOnBrowser(){var br;return!!(!((br=window==null?void 0:window.coinbaseWalletExtension)===null||br===void 0)&&br.isCoinbaseWallet)}getAddress(){return __awaiter$8(this,void 0,void 0,function*(){const[br]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});return this.setActiveAccount(br),br})}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){const[wr]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});try{return yield this.coinbaseProvider.request({method:"personal_sign",params:[toHex$1(toBytes$4(br)),wr.toLowerCase()]})}catch{return}})}setupEventListeners(){const{handleAccountChange:br,handleChainChange:wr,handleDisconnect:Er}=eventListenerHandlers(this);this.coinbaseProvider.on("accountsChanged",br),this.coinbaseProvider.on("chainChanged",wr),this.coinbaseProvider.on("disconnect",Er),this.teardownEventListeners=()=>{this.coinbaseProvider.removeListener("accountsChanged",br),this.coinbaseProvider.removeListener("chainChanged",wr),this.coinbaseProvider.removeListener("disconnect",Er)}}getWalletClient(br){return createWalletClient$1({account:this.getActiveAccount(),chain:br?chainsMap[br]:void 0,transport:custom$1(this.coinbaseProvider)})}}assertPackageVersion("@dynamic-labs/ethereum",version$9);const EthereumWalletConnectors=fr=>[...injectedWalletOverrides$1,...fetchInjectedWalletConnector(fr),...fetchWalletConnectWallets(fr),...TurnkeyEVMWalletConnectors(fr),Coinbase,UnknownInjected$1,FallbackEvmConnector,getWalletConnectConnector()];var version$7="3.8.2",version$6="3.8.2";function __awaiter$4(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(fr,br=!1){return br?{h:Number(fr&U32_MASK64),l:Number(fr>>_32n&U32_MASK64)}:{h:Number(fr>>_32n&U32_MASK64)|0,l:Number(fr&U32_MASK64)|0}}function split(fr,br=!1){let wr=new Uint32Array(fr.length),Er=new Uint32Array(fr.length);for(let kr=0;krBigInt(fr>>>0)<<_32n|BigInt(br>>>0),shrSH=(fr,br,wr)=>fr>>>wr,shrSL=(fr,br,wr)=>fr<<32-wr|br>>>wr,rotrSH=(fr,br,wr)=>fr>>>wr|br<<32-wr,rotrSL=(fr,br,wr)=>fr<<32-wr|br>>>wr,rotrBH=(fr,br,wr)=>fr<<64-wr|br>>>wr-32,rotrBL=(fr,br,wr)=>fr>>>wr-32|br<<64-wr,rotr32H=(fr,br)=>br,rotr32L=(fr,br)=>fr,rotlSH=(fr,br,wr)=>fr<>>32-wr,rotlSL=(fr,br,wr)=>br<>>32-wr,rotlBH=(fr,br,wr)=>br<>>64-wr,rotlBL=(fr,br,wr)=>fr<>>64-wr;function add(fr,br,wr,Er){const kr=(br>>>0)+(Er>>>0);return{h:fr+wr+(kr/2**32|0)|0,l:kr|0}}const add3L=(fr,br,wr)=>(fr>>>0)+(br>>>0)+(wr>>>0),add3H=(fr,br,wr,Er)=>br+wr+Er+(fr/2**32|0)|0,add4L=(fr,br,wr,Er)=>(fr>>>0)+(br>>>0)+(wr>>>0)+(Er>>>0),add4H=(fr,br,wr,Er,kr)=>br+wr+Er+kr+(fr/2**32|0)|0,add5L=(fr,br,wr,Er,kr)=>(fr>>>0)+(br>>>0)+(wr>>>0)+(Er>>>0)+(kr>>>0),add5H=(fr,br,wr,Er,kr,jr)=>br+wr+Er+kr+jr+(fr/2**32|0)|0,u64$4={fromBig,split,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$4.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(fr=>BigInt(fr))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{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:br,Al:wr,Bh:Er,Bl:kr,Ch:jr,Cl:Br,Dh:qr,Dl:Wr,Eh:Vr,El:Hr,Fh:Zr,Fl:Jr,Gh:Xr,Gl:En,Hh:wn,Hl:$n}=this;return[br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n]}set(br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n){this.Ah=br|0,this.Al=wr|0,this.Bh=Er|0,this.Bl=kr|0,this.Ch=jr|0,this.Cl=Br|0,this.Dh=qr|0,this.Dl=Wr|0,this.Eh=Vr|0,this.El=Hr|0,this.Fh=Zr|0,this.Fl=Jr|0,this.Gh=Xr|0,this.Gl=En|0,this.Hh=wn|0,this.Hl=$n|0}process(br,wr){for(let jn=0;jn<16;jn++,wr+=4)SHA512_W_H[jn]=br.getUint32(wr),SHA512_W_L[jn]=br.getUint32(wr+=4);for(let jn=16;jn<80;jn++){const Yn=SHA512_W_H[jn-15]|0,ga=SHA512_W_L[jn-15]|0,na=u64$4.rotrSH(Yn,ga,1)^u64$4.rotrSH(Yn,ga,8)^u64$4.shrSH(Yn,ga,7),_i=u64$4.rotrSL(Yn,ga,1)^u64$4.rotrSL(Yn,ga,8)^u64$4.shrSL(Yn,ga,7),ro=SHA512_W_H[jn-2]|0,to=SHA512_W_L[jn-2]|0,io=u64$4.rotrSH(ro,to,19)^u64$4.rotrBH(ro,to,61)^u64$4.shrSH(ro,to,6),no=u64$4.rotrSL(ro,to,19)^u64$4.rotrBL(ro,to,61)^u64$4.shrSL(ro,to,6),$a=u64$4.add4L(_i,no,SHA512_W_L[jn-7],SHA512_W_L[jn-16]),Rn=u64$4.add4H($a,na,io,SHA512_W_H[jn-7],SHA512_W_H[jn-16]);SHA512_W_H[jn]=Rn|0,SHA512_W_L[jn]=$a|0}let{Ah:Er,Al:kr,Bh:jr,Bl:Br,Ch:qr,Cl:Wr,Dh:Vr,Dl:Hr,Eh:Zr,El:Jr,Fh:Xr,Fl:En,Gh:wn,Gl:$n,Hh:Tn,Hl:In}=this;for(let jn=0;jn<80;jn++){const Yn=u64$4.rotrSH(Zr,Jr,14)^u64$4.rotrSH(Zr,Jr,18)^u64$4.rotrBH(Zr,Jr,41),ga=u64$4.rotrSL(Zr,Jr,14)^u64$4.rotrSL(Zr,Jr,18)^u64$4.rotrBL(Zr,Jr,41),na=Zr&Xr^~Zr&wn,_i=Jr&En^~Jr&$n,ro=u64$4.add5L(In,ga,_i,SHA512_Kl[jn],SHA512_W_L[jn]),to=u64$4.add5H(ro,Tn,Yn,na,SHA512_Kh[jn],SHA512_W_H[jn]),io=ro|0,no=u64$4.rotrSH(Er,kr,28)^u64$4.rotrBH(Er,kr,34)^u64$4.rotrBH(Er,kr,39),$a=u64$4.rotrSL(Er,kr,28)^u64$4.rotrBL(Er,kr,34)^u64$4.rotrBL(Er,kr,39),Rn=Er&jr^Er&qr^jr&qr,Gr=kr&Br^kr&Wr^Br&Wr;Tn=wn|0,In=$n|0,wn=Xr|0,$n=En|0,Xr=Zr|0,En=Jr|0,{h:Zr,l:Jr}=u64$4.add(Vr|0,Hr|0,to|0,io|0),Vr=qr|0,Hr=Wr|0,qr=jr|0,Wr=Br|0,jr=Er|0,Br=kr|0;const Yr=u64$4.add3L(io,$a,Gr);Er=u64$4.add3H(Yr,to,no,Rn),kr=Yr|0}({h:Er,l:kr}=u64$4.add(this.Ah|0,this.Al|0,Er|0,kr|0)),{h:jr,l:Br}=u64$4.add(this.Bh|0,this.Bl|0,jr|0,Br|0),{h:qr,l:Wr}=u64$4.add(this.Ch|0,this.Cl|0,qr|0,Wr|0),{h:Vr,l:Hr}=u64$4.add(this.Dh|0,this.Dl|0,Vr|0,Hr|0),{h:Zr,l:Jr}=u64$4.add(this.Eh|0,this.El|0,Zr|0,Jr|0),{h:Xr,l:En}=u64$4.add(this.Fh|0,this.Fl|0,Xr|0,En|0),{h:wn,l:$n}=u64$4.add(this.Gh|0,this.Gl|0,wn|0,$n|0),{h:Tn,l:In}=u64$4.add(this.Hh|0,this.Hl|0,Tn|0,In|0),this.set(Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n,Tn,In)}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);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n$1=BigInt(1),_2n$1=BigInt(2),_8n$1=BigInt(8),VERIFY_DEFAULT={zip215:!0};function validateOpts(fr){const br=validateBasic(fr);return validateObject(fr,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...br})}function twistedEdwards(fr){const br=validateOpts(fr),{Fp:wr,n:Er,prehash:kr,hash:jr,randomBytes:Br,nByteLength:qr,h:Wr}=br,Vr=_2n$1<{try{return{isValid:!0,value:wr.sqrt(Sn*wr.inv(An))}}catch{return{isValid:!1,value:_0n}}}),Xr=br.adjustScalarBytes||(Sn=>Sn),En=br.domain||((Sn,An,Pn)=>{if(abool("phflag",Pn),An.length||Pn)throw new Error("Contexts/pre-hash are not supported");return Sn});function wn(Sn,An){aInRange("coordinate "+Sn,An,_0n,Vr)}function $n(Sn){if(!(Sn instanceof jn))throw new Error("ExtendedPoint expected")}const Tn=memoized((Sn,An)=>{const{ex:Pn,ey:Nn,ez:zn}=Sn,On=Sn.is0();An==null&&(An=On?_8n$1:wr.inv(zn));const _n=Hr(Pn*An),Zn=Hr(Nn*An),oo=Hr(zn*An);if(On)return{x:_0n,y:_1n$1};if(oo!==_1n$1)throw new Error("invZ was invalid");return{x:_n,y:Zn}}),In=memoized(Sn=>{const{a:An,d:Pn}=br;if(Sn.is0())throw new Error("bad point: ZERO");const{ex:Nn,ey:zn,ez:On,et:_n}=Sn,Zn=Hr(Nn*Nn),oo=Hr(zn*zn),uo=Hr(On*On),lo=Hr(uo*uo),co=Hr(Zn*An),so=Hr(uo*Hr(co+oo)),yo=Hr(lo+Hr(Pn*Hr(Zn*oo)));if(so!==yo)throw new Error("bad point: equation left != right (1)");const fo=Hr(Nn*zn),ho=Hr(On*_n);if(fo!==ho)throw new Error("bad point: equation left != right (2)");return!0});class jn{constructor(An,Pn,Nn,zn){this.ex=An,this.ey=Pn,this.ez=Nn,this.et=zn,wn("x",An),wn("y",Pn),wn("z",Nn),wn("t",zn),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(An){if(An instanceof jn)throw new Error("extended point not allowed");const{x:Pn,y:Nn}=An||{};return wn("x",Pn),wn("y",Nn),new jn(Pn,Nn,_1n$1,Hr(Pn*Nn))}static normalizeZ(An){const Pn=wr.invertBatch(An.map(Nn=>Nn.ez));return An.map((Nn,zn)=>Nn.toAffine(Pn[zn])).map(jn.fromAffine)}static msm(An,Pn){return pippenger(jn,Zr,An,Pn)}_setWindowSize(An){na.setWindowSize(this,An)}assertValidity(){In(this)}equals(An){$n(An);const{ex:Pn,ey:Nn,ez:zn}=this,{ex:On,ey:_n,ez:Zn}=An,oo=Hr(Pn*Zn),uo=Hr(On*zn),lo=Hr(Nn*Zn),co=Hr(_n*zn);return oo===uo&&lo===co}is0(){return this.equals(jn.ZERO)}negate(){return new jn(Hr(-this.ex),this.ey,this.ez,Hr(-this.et))}double(){const{a:An}=br,{ex:Pn,ey:Nn,ez:zn}=this,On=Hr(Pn*Pn),_n=Hr(Nn*Nn),Zn=Hr(_2n$1*Hr(zn*zn)),oo=Hr(An*On),uo=Pn+Nn,lo=Hr(Hr(uo*uo)-On-_n),co=oo+_n,so=co-Zn,yo=oo-_n,fo=Hr(lo*so),ho=Hr(co*yo),vo=Hr(lo*yo),Io=Hr(so*co);return new jn(fo,ho,Io,vo)}add(An){$n(An);const{a:Pn,d:Nn}=br,{ex:zn,ey:On,ez:_n,et:Zn}=this,{ex:oo,ey:uo,ez:lo,et:co}=An;if(Pn===BigInt(-1)){const jo=Hr((On-zn)*(uo+oo)),No=Hr((On+zn)*(uo-oo)),Tl=Hr(No-jo);if(Tl===_0n)return this.double();const Fo=Hr(_n*_2n$1*co),Lo=Hr(Zn*_2n$1*lo),Rl=Lo+Fo,_c=No+jo,Ko=Lo-Fo,zl=Hr(Rl*Tl),Sl=Hr(_c*Ko),Eo=Hr(Rl*Ko),bo=Hr(Tl*_c);return new jn(zl,Sl,bo,Eo)}const so=Hr(zn*oo),yo=Hr(On*uo),fo=Hr(Zn*Nn*co),ho=Hr(_n*lo),vo=Hr((zn+On)*(oo+uo)-so-yo),Io=ho-fo,Ro=ho+fo,To=Hr(yo-Pn*so),Wo=Hr(vo*Io),qo=Hr(Ro*To),Zo=Hr(vo*To),Qo=Hr(Io*Ro);return new jn(Wo,qo,Qo,Zo)}subtract(An){return this.add(An.negate())}wNAF(An){return na.wNAFCached(this,An,jn.normalizeZ)}multiply(An){const Pn=An;aInRange("scalar",Pn,_1n$1,Er);const{p:Nn,f:zn}=this.wNAF(Pn);return jn.normalizeZ([Nn,zn])[0]}multiplyUnsafe(An,Pn=jn.ZERO){const Nn=An;return aInRange("scalar",Nn,_0n,Er),Nn===_0n?ga:this.is0()||Nn===_1n$1?this:na.wNAFCachedUnsafe(this,Nn,jn.normalizeZ,Pn)}isSmallOrder(){return this.multiplyUnsafe(Wr).is0()}isTorsionFree(){return na.unsafeLadder(this,Er).is0()}toAffine(An){return Tn(this,An)}clearCofactor(){const{h:An}=br;return An===_1n$1?this:this.multiplyUnsafe(An)}static fromHex(An,Pn=!1){const{d:Nn,a:zn}=br,On=wr.BYTES;An=ensureBytes("pointHex",An,On),abool("zip215",Pn);const _n=An.slice(),Zn=An[On-1];_n[On-1]=Zn&-129;const oo=bytesToNumberLE(_n),uo=Pn?Vr:wr.ORDER;aInRange("pointHex.y",oo,_0n,uo);const lo=Hr(oo*oo),co=Hr(lo-_1n$1),so=Hr(Nn*lo-zn);let{isValid:yo,value:fo}=Jr(co,so);if(!yo)throw new Error("Point.fromHex: invalid y coordinate");const ho=(fo&_1n$1)===_1n$1,vo=(Zn&128)!==0;if(!Pn&&fo===_0n&&vo)throw new Error("Point.fromHex: x=0 and x_0=1");return vo!==ho&&(fo=Hr(-fo)),jn.fromAffine({x:fo,y:oo})}static fromPrivateKey(An){return to(An).point}toRawBytes(){const{x:An,y:Pn}=this.toAffine(),Nn=numberToBytesLE(Pn,wr.BYTES);return Nn[Nn.length-1]|=An&_1n$1?128:0,Nn}toHex(){return bytesToHex(this.toRawBytes())}}jn.BASE=new jn(br.Gx,br.Gy,_1n$1,Hr(br.Gx*br.Gy)),jn.ZERO=new jn(_0n,_1n$1,_1n$1,_0n);const{BASE:Yn,ZERO:ga}=jn,na=wNAF(jn,qr*8);function _i(Sn){return mod(Sn,Er)}function ro(Sn){return _i(bytesToNumberLE(Sn))}function to(Sn){const An=wr.BYTES;Sn=ensureBytes("private key",Sn,An);const Pn=ensureBytes("hashed private key",jr(Sn),2*An),Nn=Xr(Pn.slice(0,An)),zn=Pn.slice(An,2*An),On=ro(Nn),_n=Yn.multiply(On),Zn=_n.toRawBytes();return{head:Nn,prefix:zn,scalar:On,point:_n,pointBytes:Zn}}function io(Sn){return to(Sn).pointBytes}function no(Sn=new Uint8Array,...An){const Pn=concatBytes(...An);return ro(jr(En(Pn,ensureBytes("context",Sn),!!kr)))}function $a(Sn,An,Pn={}){Sn=ensureBytes("message",Sn),kr&&(Sn=kr(Sn));const{prefix:Nn,scalar:zn,pointBytes:On}=to(An),_n=no(Pn.context,Nn,Sn),Zn=Yn.multiply(_n).toRawBytes(),oo=no(Pn.context,Zn,On,Sn),uo=_i(_n+oo*zn);aInRange("signature.s",uo,_0n,Er);const lo=concatBytes(Zn,numberToBytesLE(uo,wr.BYTES));return ensureBytes("result",lo,wr.BYTES*2)}const Rn=VERIFY_DEFAULT;function Gr(Sn,An,Pn,Nn=Rn){const{context:zn,zip215:On}=Nn,_n=wr.BYTES;Sn=ensureBytes("signature",Sn,2*_n),An=ensureBytes("message",An),Pn=ensureBytes("publicKey",Pn,_n),On!==void 0&&abool("zip215",On),kr&&(An=kr(An));const Zn=bytesToNumberLE(Sn.slice(_n,2*_n));let oo,uo,lo;try{oo=jn.fromHex(Pn,On),uo=jn.fromHex(Sn.slice(0,_n),On),lo=Yn.multiplyUnsafe(Zn)}catch{return!1}if(!On&&oo.isSmallOrder())return!1;const co=no(zn,uo.toRawBytes(),oo.toRawBytes(),An);return uo.add(oo.multiplyUnsafe(co)).subtract(lo).clearCofactor().equals(jn.ZERO)}return Yn._setWindowSize(8),{CURVE:br,getPublicKey:io,sign:$a,verify:Gr,ExtendedPoint:jn,utils:{getExtendedPublicKey:to,randomPrivateKey:()=>Br(wr.BYTES),precompute(Sn=8,An=jn.BASE){return An._setWindowSize(Sn),An.multiply(BigInt(3)),An}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n=BigInt(1),_2n=BigInt(2);BigInt(3);const _5n=BigInt(5),_8n=BigInt(8);function ed25519_pow_2_252_3(fr){const br=BigInt(10),wr=BigInt(20),Er=BigInt(40),kr=BigInt(80),jr=ED25519_P,qr=fr*fr%jr*fr%jr,Wr=pow2(qr,_2n,jr)*qr%jr,Vr=pow2(Wr,_1n,jr)*fr%jr,Hr=pow2(Vr,_5n,jr)*Vr%jr,Zr=pow2(Hr,br,jr)*Hr%jr,Jr=pow2(Zr,wr,jr)*Zr%jr,Xr=pow2(Jr,Er,jr)*Jr%jr,En=pow2(Xr,kr,jr)*Xr%jr,wn=pow2(En,kr,jr)*Xr%jr,$n=pow2(wn,br,jr)*Hr%jr;return{pow_p_5_8:pow2($n,_2n,jr)*fr%jr,b2:qr}}function adjustScalarBytes(fr){return fr[0]&=248,fr[31]&=127,fr[31]|=64,fr}function uvRatio(fr,br){const wr=ED25519_P,Er=mod(br*br*br,wr),kr=mod(Er*Er*br,wr),jr=ed25519_pow_2_252_3(fr*kr).pow_p_5_8;let Br=mod(fr*Er*jr,wr);const qr=mod(br*Br*Br,wr),Wr=Br,Vr=mod(Br*ED25519_SQRT_M1,wr),Hr=qr===fr,Zr=qr===mod(-fr,wr),Jr=qr===mod(-fr*ED25519_SQRT_M1,wr);return Hr&&(Br=Wr),(Zr||Jr)&&(Br=Vr),isNegativeLE(Br,wr)&&(Br=mod(-Br,wr)),{isValid:Hr||Zr,value:Br}}const Fp=Field(ED25519_P,void 0,!0),ed25519Defaults={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_8n,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512,randomBytes,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults);var bn$3={exports:{}};bn$3.exports;(function(fr){(function(br,wr){function Er(Rn,Gr){if(!Rn)throw new Error(Gr||"Assertion failed")}function kr(Rn,Gr){Rn.super_=Gr;var Yr=function(){};Yr.prototype=Gr.prototype,Rn.prototype=new Yr,Rn.prototype.constructor=Rn}function jr(Rn,Gr,Yr){if(jr.isBN(Rn))return Rn;this.negative=0,this.words=null,this.length=0,this.red=null,Rn!==null&&((Gr==="le"||Gr==="be")&&(Yr=Gr,Gr=10),this._init(Rn||0,Gr||10,Yr||"be"))}typeof br=="object"?br.exports=jr:wr.BN=jr,jr.BN=jr,jr.wordSize=26;var Br;try{typeof window<"u"&&typeof window.Buffer<"u"?Br=window.Buffer:Br=require$$0$9.Buffer}catch{}jr.isBN=function(Gr){return Gr instanceof jr?!0:Gr!==null&&typeof Gr=="object"&&Gr.constructor.wordSize===jr.wordSize&&Array.isArray(Gr.words)},jr.max=function(Gr,Yr){return Gr.cmp(Yr)>0?Gr:Yr},jr.min=function(Gr,Yr){return Gr.cmp(Yr)<0?Gr:Yr},jr.prototype._init=function(Gr,Yr,Sn){if(typeof Gr=="number")return this._initNumber(Gr,Yr,Sn);if(typeof Gr=="object")return this._initArray(Gr,Yr,Sn);Yr==="hex"&&(Yr=16),Er(Yr===(Yr|0)&&Yr>=2&&Yr<=36),Gr=Gr.toString().replace(/\s+/g,"");var An=0;Gr[0]==="-"&&(An++,this.negative=1),An=0;An-=3)Nn=Gr[An]|Gr[An-1]<<8|Gr[An-2]<<16,this.words[Pn]|=Nn<>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);else if(Sn==="le")for(An=0,Pn=0;An>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);return this._strip()};function qr(Rn,Gr){var Yr=Rn.charCodeAt(Gr);if(Yr>=48&&Yr<=57)return Yr-48;if(Yr>=65&&Yr<=70)return Yr-55;if(Yr>=97&&Yr<=102)return Yr-87;Er(!1,"Invalid character in "+Rn)}function Wr(Rn,Gr,Yr){var Sn=qr(Rn,Yr);return Yr-1>=Gr&&(Sn|=qr(Rn,Yr-1)<<4),Sn}jr.prototype._parseHex=function(Gr,Yr,Sn){this.length=Math.ceil((Gr.length-Yr)/6),this.words=new Array(this.length);for(var An=0;An=Yr;An-=2)zn=Wr(Gr,Yr,An)<=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8;else{var On=Gr.length-Yr;for(An=On%2===0?Yr+1:Yr;An=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8}this._strip()};function Vr(Rn,Gr,Yr,Sn){for(var An=0,Pn=0,Nn=Math.min(Rn.length,Yr),zn=Gr;zn=49?Pn=On-49+10:On>=17?Pn=On-17+10:Pn=On,Er(On>=0&&Pn1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},jr.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{jr.prototype[Symbol.for("nodejs.util.inspect.custom")]=Zr}catch{jr.prototype.inspect=Zr}else jr.prototype.inspect=Zr;function Zr(){return(this.red?""}var Jr=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],Xr=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],En=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];jr.prototype.toString=function(Gr,Yr){Gr=Gr||10,Yr=Yr|0||1;var Sn;if(Gr===16||Gr==="hex"){Sn="";for(var An=0,Pn=0,Nn=0;Nn>>24-An&16777215,An+=2,An>=26&&(An-=26,Nn--),Pn!==0||Nn!==this.length-1?Sn=Jr[6-On.length]+On+Sn:Sn=On+Sn}for(Pn!==0&&(Sn=Pn.toString(16)+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}if(Gr===(Gr|0)&&Gr>=2&&Gr<=36){var _n=Xr[Gr],Zn=En[Gr];Sn="";var oo=this.clone();for(oo.negative=0;!oo.isZero();){var uo=oo.modrn(Zn).toString(Gr);oo=oo.idivn(Zn),oo.isZero()?Sn=uo+Sn:Sn=Jr[_n-uo.length]+uo+Sn}for(this.isZero()&&(Sn="0"+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}Er(!1,"Base should be between 2 and 36")},jr.prototype.toNumber=function(){var Gr=this.words[0];return this.length===2?Gr+=this.words[1]*67108864:this.length===3&&this.words[2]===1?Gr+=4503599627370496+this.words[1]*67108864:this.length>2&&Er(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-Gr:Gr},jr.prototype.toJSON=function(){return this.toString(16,2)},Br&&(jr.prototype.toBuffer=function(Gr,Yr){return this.toArrayLike(Br,Gr,Yr)}),jr.prototype.toArray=function(Gr,Yr){return this.toArrayLike(Array,Gr,Yr)};var wn=function(Gr,Yr){return Gr.allocUnsafe?Gr.allocUnsafe(Yr):new Gr(Yr)};jr.prototype.toArrayLike=function(Gr,Yr,Sn){this._strip();var An=this.byteLength(),Pn=Sn||Math.max(1,An);Er(An<=Pn,"byte array longer than desired length"),Er(Pn>0,"Requested array length <= 0");var Nn=wn(Gr,Pn),zn=Yr==="le"?"LE":"BE";return this["_toArrayLike"+zn](Nn,An),Nn},jr.prototype._toArrayLikeLE=function(Gr,Yr){for(var Sn=0,An=0,Pn=0,Nn=0;Pn>8&255),Sn>16&255),Nn===6?(Sn>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn=0&&(Gr[Sn--]=zn>>8&255),Sn>=0&&(Gr[Sn--]=zn>>16&255),Nn===6?(Sn>=0&&(Gr[Sn--]=zn>>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn>=0)for(Gr[Sn--]=An;Sn>=0;)Gr[Sn--]=0},Math.clz32?jr.prototype._countBits=function(Gr){return 32-Math.clz32(Gr)}:jr.prototype._countBits=function(Gr){var Yr=Gr,Sn=0;return Yr>=4096&&(Sn+=13,Yr>>>=13),Yr>=64&&(Sn+=7,Yr>>>=7),Yr>=8&&(Sn+=4,Yr>>>=4),Yr>=2&&(Sn+=2,Yr>>>=2),Sn+Yr},jr.prototype._zeroBits=function(Gr){if(Gr===0)return 26;var Yr=Gr,Sn=0;return Yr&8191||(Sn+=13,Yr>>>=13),Yr&127||(Sn+=7,Yr>>>=7),Yr&15||(Sn+=4,Yr>>>=4),Yr&3||(Sn+=2,Yr>>>=2),Yr&1||Sn++,Sn},jr.prototype.bitLength=function(){var Gr=this.words[this.length-1],Yr=this._countBits(Gr);return(this.length-1)*26+Yr};function $n(Rn){for(var Gr=new Array(Rn.bitLength()),Yr=0;Yr>>An&1}return Gr}jr.prototype.zeroBits=function(){if(this.isZero())return 0;for(var Gr=0,Yr=0;YrGr.length?this.clone().ior(Gr):Gr.clone().ior(this)},jr.prototype.uor=function(Gr){return this.length>Gr.length?this.clone().iuor(Gr):Gr.clone().iuor(this)},jr.prototype.iuand=function(Gr){var Yr;this.length>Gr.length?Yr=Gr:Yr=this;for(var Sn=0;SnGr.length?this.clone().iand(Gr):Gr.clone().iand(this)},jr.prototype.uand=function(Gr){return this.length>Gr.length?this.clone().iuand(Gr):Gr.clone().iuand(this)},jr.prototype.iuxor=function(Gr){var Yr,Sn;this.length>Gr.length?(Yr=this,Sn=Gr):(Yr=Gr,Sn=this);for(var An=0;AnGr.length?this.clone().ixor(Gr):Gr.clone().ixor(this)},jr.prototype.uxor=function(Gr){return this.length>Gr.length?this.clone().iuxor(Gr):Gr.clone().iuxor(this)},jr.prototype.inotn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Math.ceil(Gr/26)|0,Sn=Gr%26;this._expand(Yr),Sn>0&&Yr--;for(var An=0;An0&&(this.words[An]=~this.words[An]&67108863>>26-Sn),this._strip()},jr.prototype.notn=function(Gr){return this.clone().inotn(Gr)},jr.prototype.setn=function(Gr,Yr){Er(typeof Gr=="number"&&Gr>=0);var Sn=Gr/26|0,An=Gr%26;return this._expand(Sn+1),Yr?this.words[Sn]=this.words[Sn]|1<Gr.length?(Sn=this,An=Gr):(Sn=Gr,An=this);for(var Pn=0,Nn=0;Nn>>26;for(;Pn!==0&&Nn>>26;if(this.length=Sn.length,Pn!==0)this.words[this.length]=Pn,this.length++;else if(Sn!==this)for(;NnGr.length?this.clone().iadd(Gr):Gr.clone().iadd(this)},jr.prototype.isub=function(Gr){if(Gr.negative!==0){Gr.negative=0;var Yr=this.iadd(Gr);return Gr.negative=1,Yr._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(Gr),this.negative=1,this._normSign();var Sn=this.cmp(Gr);if(Sn===0)return this.negative=0,this.length=1,this.words[0]=0,this;var An,Pn;Sn>0?(An=this,Pn=Gr):(An=Gr,Pn=this);for(var Nn=0,zn=0;zn>26,this.words[zn]=Yr&67108863;for(;Nn!==0&&zn>26,this.words[zn]=Yr&67108863;if(Nn===0&&zn>>26,oo=On&67108863,uo=Math.min(_n,Gr.length-1),lo=Math.max(0,_n-Rn.length+1);lo<=uo;lo++){var co=_n-lo|0;An=Rn.words[co]|0,Pn=Gr.words[lo]|0,Nn=An*Pn+oo,Zn+=Nn/67108864|0,oo=Nn&67108863}Yr.words[_n]=oo|0,On=Zn|0}return On!==0?Yr.words[_n]=On|0:Yr.length--,Yr._strip()}var In=function(Gr,Yr,Sn){var An=Gr.words,Pn=Yr.words,Nn=Sn.words,zn=0,On,_n,Zn,oo=An[0]|0,uo=oo&8191,lo=oo>>>13,co=An[1]|0,so=co&8191,yo=co>>>13,fo=An[2]|0,ho=fo&8191,vo=fo>>>13,Io=An[3]|0,Ro=Io&8191,To=Io>>>13,Wo=An[4]|0,qo=Wo&8191,Zo=Wo>>>13,Qo=An[5]|0,jo=Qo&8191,No=Qo>>>13,Tl=An[6]|0,Fo=Tl&8191,Lo=Tl>>>13,Rl=An[7]|0,_c=Rl&8191,Ko=Rl>>>13,zl=An[8]|0,Sl=zl&8191,Eo=zl>>>13,bo=An[9]|0,go=bo&8191,Co=bo>>>13,zo=Pn[0]|0,Do=zo&8191,Uo=zo>>>13,ru=Pn[1]|0,Dl=ru&8191,xl=ru>>>13,bu=Pn[2]|0,yl=bu&8191,Il=bu>>>13,cu=Pn[3]|0,Bl=cu&8191,Pl=cu>>>13,wu=Pn[4]|0,Ol=wu&8191,Nl=wu>>>13,Tu=Pn[5]|0,Ul=Tu&8191,Cl=Tu>>>13,gu=Pn[6]|0,wo=gu&8191,$o=gu>>>13,Ao=Pn[7]|0,po=Ao&8191,So=Ao>>>13,Jo=Pn[8]|0,Bo=Jo&8191,Ho=Jo>>>13,Wl=Pn[9]|0,El=Wl&8191,$l=Wl>>>13;Sn.negative=Gr.negative^Yr.negative,Sn.length=19,On=Math.imul(uo,Do),_n=Math.imul(uo,Uo),_n=_n+Math.imul(lo,Do)|0,Zn=Math.imul(lo,Uo);var Su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Su>>>26)|0,Su&=67108863,On=Math.imul(so,Do),_n=Math.imul(so,Uo),_n=_n+Math.imul(yo,Do)|0,Zn=Math.imul(yo,Uo),On=On+Math.imul(uo,Dl)|0,_n=_n+Math.imul(uo,xl)|0,_n=_n+Math.imul(lo,Dl)|0,Zn=Zn+Math.imul(lo,xl)|0;var nu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(nu>>>26)|0,nu&=67108863,On=Math.imul(ho,Do),_n=Math.imul(ho,Uo),_n=_n+Math.imul(vo,Do)|0,Zn=Math.imul(vo,Uo),On=On+Math.imul(so,Dl)|0,_n=_n+Math.imul(so,xl)|0,_n=_n+Math.imul(yo,Dl)|0,Zn=Zn+Math.imul(yo,xl)|0,On=On+Math.imul(uo,yl)|0,_n=_n+Math.imul(uo,Il)|0,_n=_n+Math.imul(lo,yl)|0,Zn=Zn+Math.imul(lo,Il)|0;var pu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(pu>>>26)|0,pu&=67108863,On=Math.imul(Ro,Do),_n=Math.imul(Ro,Uo),_n=_n+Math.imul(To,Do)|0,Zn=Math.imul(To,Uo),On=On+Math.imul(ho,Dl)|0,_n=_n+Math.imul(ho,xl)|0,_n=_n+Math.imul(vo,Dl)|0,Zn=Zn+Math.imul(vo,xl)|0,On=On+Math.imul(so,yl)|0,_n=_n+Math.imul(so,Il)|0,_n=_n+Math.imul(yo,yl)|0,Zn=Zn+Math.imul(yo,Il)|0,On=On+Math.imul(uo,Bl)|0,_n=_n+Math.imul(uo,Pl)|0,_n=_n+Math.imul(lo,Bl)|0,Zn=Zn+Math.imul(lo,Pl)|0;var mu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(mu>>>26)|0,mu&=67108863,On=Math.imul(qo,Do),_n=Math.imul(qo,Uo),_n=_n+Math.imul(Zo,Do)|0,Zn=Math.imul(Zo,Uo),On=On+Math.imul(Ro,Dl)|0,_n=_n+Math.imul(Ro,xl)|0,_n=_n+Math.imul(To,Dl)|0,Zn=Zn+Math.imul(To,xl)|0,On=On+Math.imul(ho,yl)|0,_n=_n+Math.imul(ho,Il)|0,_n=_n+Math.imul(vo,yl)|0,Zn=Zn+Math.imul(vo,Il)|0,On=On+Math.imul(so,Bl)|0,_n=_n+Math.imul(so,Pl)|0,_n=_n+Math.imul(yo,Bl)|0,Zn=Zn+Math.imul(yo,Pl)|0,On=On+Math.imul(uo,Ol)|0,_n=_n+Math.imul(uo,Nl)|0,_n=_n+Math.imul(lo,Ol)|0,Zn=Zn+Math.imul(lo,Nl)|0;var hu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(hu>>>26)|0,hu&=67108863,On=Math.imul(jo,Do),_n=Math.imul(jo,Uo),_n=_n+Math.imul(No,Do)|0,Zn=Math.imul(No,Uo),On=On+Math.imul(qo,Dl)|0,_n=_n+Math.imul(qo,xl)|0,_n=_n+Math.imul(Zo,Dl)|0,Zn=Zn+Math.imul(Zo,xl)|0,On=On+Math.imul(Ro,yl)|0,_n=_n+Math.imul(Ro,Il)|0,_n=_n+Math.imul(To,yl)|0,Zn=Zn+Math.imul(To,Il)|0,On=On+Math.imul(ho,Bl)|0,_n=_n+Math.imul(ho,Pl)|0,_n=_n+Math.imul(vo,Bl)|0,Zn=Zn+Math.imul(vo,Pl)|0,On=On+Math.imul(so,Ol)|0,_n=_n+Math.imul(so,Nl)|0,_n=_n+Math.imul(yo,Ol)|0,Zn=Zn+Math.imul(yo,Nl)|0,On=On+Math.imul(uo,Ul)|0,_n=_n+Math.imul(uo,Cl)|0,_n=_n+Math.imul(lo,Ul)|0,Zn=Zn+Math.imul(lo,Cl)|0;var yu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(yu>>>26)|0,yu&=67108863,On=Math.imul(Fo,Do),_n=Math.imul(Fo,Uo),_n=_n+Math.imul(Lo,Do)|0,Zn=Math.imul(Lo,Uo),On=On+Math.imul(jo,Dl)|0,_n=_n+Math.imul(jo,xl)|0,_n=_n+Math.imul(No,Dl)|0,Zn=Zn+Math.imul(No,xl)|0,On=On+Math.imul(qo,yl)|0,_n=_n+Math.imul(qo,Il)|0,_n=_n+Math.imul(Zo,yl)|0,Zn=Zn+Math.imul(Zo,Il)|0,On=On+Math.imul(Ro,Bl)|0,_n=_n+Math.imul(Ro,Pl)|0,_n=_n+Math.imul(To,Bl)|0,Zn=Zn+Math.imul(To,Pl)|0,On=On+Math.imul(ho,Ol)|0,_n=_n+Math.imul(ho,Nl)|0,_n=_n+Math.imul(vo,Ol)|0,Zn=Zn+Math.imul(vo,Nl)|0,On=On+Math.imul(so,Ul)|0,_n=_n+Math.imul(so,Cl)|0,_n=_n+Math.imul(yo,Ul)|0,Zn=Zn+Math.imul(yo,Cl)|0,On=On+Math.imul(uo,wo)|0,_n=_n+Math.imul(uo,$o)|0,_n=_n+Math.imul(lo,wo)|0,Zn=Zn+Math.imul(lo,$o)|0;var _u=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(_u>>>26)|0,_u&=67108863,On=Math.imul(_c,Do),_n=Math.imul(_c,Uo),_n=_n+Math.imul(Ko,Do)|0,Zn=Math.imul(Ko,Uo),On=On+Math.imul(Fo,Dl)|0,_n=_n+Math.imul(Fo,xl)|0,_n=_n+Math.imul(Lo,Dl)|0,Zn=Zn+Math.imul(Lo,xl)|0,On=On+Math.imul(jo,yl)|0,_n=_n+Math.imul(jo,Il)|0,_n=_n+Math.imul(No,yl)|0,Zn=Zn+Math.imul(No,Il)|0,On=On+Math.imul(qo,Bl)|0,_n=_n+Math.imul(qo,Pl)|0,_n=_n+Math.imul(Zo,Bl)|0,Zn=Zn+Math.imul(Zo,Pl)|0,On=On+Math.imul(Ro,Ol)|0,_n=_n+Math.imul(Ro,Nl)|0,_n=_n+Math.imul(To,Ol)|0,Zn=Zn+Math.imul(To,Nl)|0,On=On+Math.imul(ho,Ul)|0,_n=_n+Math.imul(ho,Cl)|0,_n=_n+Math.imul(vo,Ul)|0,Zn=Zn+Math.imul(vo,Cl)|0,On=On+Math.imul(so,wo)|0,_n=_n+Math.imul(so,$o)|0,_n=_n+Math.imul(yo,wo)|0,Zn=Zn+Math.imul(yo,$o)|0,On=On+Math.imul(uo,po)|0,_n=_n+Math.imul(uo,So)|0,_n=_n+Math.imul(lo,po)|0,Zn=Zn+Math.imul(lo,So)|0;var fu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(fu>>>26)|0,fu&=67108863,On=Math.imul(Sl,Do),_n=Math.imul(Sl,Uo),_n=_n+Math.imul(Eo,Do)|0,Zn=Math.imul(Eo,Uo),On=On+Math.imul(_c,Dl)|0,_n=_n+Math.imul(_c,xl)|0,_n=_n+Math.imul(Ko,Dl)|0,Zn=Zn+Math.imul(Ko,xl)|0,On=On+Math.imul(Fo,yl)|0,_n=_n+Math.imul(Fo,Il)|0,_n=_n+Math.imul(Lo,yl)|0,Zn=Zn+Math.imul(Lo,Il)|0,On=On+Math.imul(jo,Bl)|0,_n=_n+Math.imul(jo,Pl)|0,_n=_n+Math.imul(No,Bl)|0,Zn=Zn+Math.imul(No,Pl)|0,On=On+Math.imul(qo,Ol)|0,_n=_n+Math.imul(qo,Nl)|0,_n=_n+Math.imul(Zo,Ol)|0,Zn=Zn+Math.imul(Zo,Nl)|0,On=On+Math.imul(Ro,Ul)|0,_n=_n+Math.imul(Ro,Cl)|0,_n=_n+Math.imul(To,Ul)|0,Zn=Zn+Math.imul(To,Cl)|0,On=On+Math.imul(ho,wo)|0,_n=_n+Math.imul(ho,$o)|0,_n=_n+Math.imul(vo,wo)|0,Zn=Zn+Math.imul(vo,$o)|0,On=On+Math.imul(so,po)|0,_n=_n+Math.imul(so,So)|0,_n=_n+Math.imul(yo,po)|0,Zn=Zn+Math.imul(yo,So)|0,On=On+Math.imul(uo,Bo)|0,_n=_n+Math.imul(uo,Ho)|0,_n=_n+Math.imul(lo,Bo)|0,Zn=Zn+Math.imul(lo,Ho)|0;var vu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(vu>>>26)|0,vu&=67108863,On=Math.imul(go,Do),_n=Math.imul(go,Uo),_n=_n+Math.imul(Co,Do)|0,Zn=Math.imul(Co,Uo),On=On+Math.imul(Sl,Dl)|0,_n=_n+Math.imul(Sl,xl)|0,_n=_n+Math.imul(Eo,Dl)|0,Zn=Zn+Math.imul(Eo,xl)|0,On=On+Math.imul(_c,yl)|0,_n=_n+Math.imul(_c,Il)|0,_n=_n+Math.imul(Ko,yl)|0,Zn=Zn+Math.imul(Ko,Il)|0,On=On+Math.imul(Fo,Bl)|0,_n=_n+Math.imul(Fo,Pl)|0,_n=_n+Math.imul(Lo,Bl)|0,Zn=Zn+Math.imul(Lo,Pl)|0,On=On+Math.imul(jo,Ol)|0,_n=_n+Math.imul(jo,Nl)|0,_n=_n+Math.imul(No,Ol)|0,Zn=Zn+Math.imul(No,Nl)|0,On=On+Math.imul(qo,Ul)|0,_n=_n+Math.imul(qo,Cl)|0,_n=_n+Math.imul(Zo,Ul)|0,Zn=Zn+Math.imul(Zo,Cl)|0,On=On+Math.imul(Ro,wo)|0,_n=_n+Math.imul(Ro,$o)|0,_n=_n+Math.imul(To,wo)|0,Zn=Zn+Math.imul(To,$o)|0,On=On+Math.imul(ho,po)|0,_n=_n+Math.imul(ho,So)|0,_n=_n+Math.imul(vo,po)|0,Zn=Zn+Math.imul(vo,So)|0,On=On+Math.imul(so,Bo)|0,_n=_n+Math.imul(so,Ho)|0,_n=_n+Math.imul(yo,Bo)|0,Zn=Zn+Math.imul(yo,Ho)|0,On=On+Math.imul(uo,El)|0,_n=_n+Math.imul(uo,$l)|0,_n=_n+Math.imul(lo,El)|0,Zn=Zn+Math.imul(lo,$l)|0;var iu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(iu>>>26)|0,iu&=67108863,On=Math.imul(go,Dl),_n=Math.imul(go,xl),_n=_n+Math.imul(Co,Dl)|0,Zn=Math.imul(Co,xl),On=On+Math.imul(Sl,yl)|0,_n=_n+Math.imul(Sl,Il)|0,_n=_n+Math.imul(Eo,yl)|0,Zn=Zn+Math.imul(Eo,Il)|0,On=On+Math.imul(_c,Bl)|0,_n=_n+Math.imul(_c,Pl)|0,_n=_n+Math.imul(Ko,Bl)|0,Zn=Zn+Math.imul(Ko,Pl)|0,On=On+Math.imul(Fo,Ol)|0,_n=_n+Math.imul(Fo,Nl)|0,_n=_n+Math.imul(Lo,Ol)|0,Zn=Zn+Math.imul(Lo,Nl)|0,On=On+Math.imul(jo,Ul)|0,_n=_n+Math.imul(jo,Cl)|0,_n=_n+Math.imul(No,Ul)|0,Zn=Zn+Math.imul(No,Cl)|0,On=On+Math.imul(qo,wo)|0,_n=_n+Math.imul(qo,$o)|0,_n=_n+Math.imul(Zo,wo)|0,Zn=Zn+Math.imul(Zo,$o)|0,On=On+Math.imul(Ro,po)|0,_n=_n+Math.imul(Ro,So)|0,_n=_n+Math.imul(To,po)|0,Zn=Zn+Math.imul(To,So)|0,On=On+Math.imul(ho,Bo)|0,_n=_n+Math.imul(ho,Ho)|0,_n=_n+Math.imul(vo,Bo)|0,Zn=Zn+Math.imul(vo,Ho)|0,On=On+Math.imul(so,El)|0,_n=_n+Math.imul(so,$l)|0,_n=_n+Math.imul(yo,El)|0,Zn=Zn+Math.imul(yo,$l)|0;var su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(su>>>26)|0,su&=67108863,On=Math.imul(go,yl),_n=Math.imul(go,Il),_n=_n+Math.imul(Co,yl)|0,Zn=Math.imul(Co,Il),On=On+Math.imul(Sl,Bl)|0,_n=_n+Math.imul(Sl,Pl)|0,_n=_n+Math.imul(Eo,Bl)|0,Zn=Zn+Math.imul(Eo,Pl)|0,On=On+Math.imul(_c,Ol)|0,_n=_n+Math.imul(_c,Nl)|0,_n=_n+Math.imul(Ko,Ol)|0,Zn=Zn+Math.imul(Ko,Nl)|0,On=On+Math.imul(Fo,Ul)|0,_n=_n+Math.imul(Fo,Cl)|0,_n=_n+Math.imul(Lo,Ul)|0,Zn=Zn+Math.imul(Lo,Cl)|0,On=On+Math.imul(jo,wo)|0,_n=_n+Math.imul(jo,$o)|0,_n=_n+Math.imul(No,wo)|0,Zn=Zn+Math.imul(No,$o)|0,On=On+Math.imul(qo,po)|0,_n=_n+Math.imul(qo,So)|0,_n=_n+Math.imul(Zo,po)|0,Zn=Zn+Math.imul(Zo,So)|0,On=On+Math.imul(Ro,Bo)|0,_n=_n+Math.imul(Ro,Ho)|0,_n=_n+Math.imul(To,Bo)|0,Zn=Zn+Math.imul(To,Ho)|0,On=On+Math.imul(ho,El)|0,_n=_n+Math.imul(ho,$l)|0,_n=_n+Math.imul(vo,El)|0,Zn=Zn+Math.imul(vo,$l)|0;var tu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(tu>>>26)|0,tu&=67108863,On=Math.imul(go,Bl),_n=Math.imul(go,Pl),_n=_n+Math.imul(Co,Bl)|0,Zn=Math.imul(Co,Pl),On=On+Math.imul(Sl,Ol)|0,_n=_n+Math.imul(Sl,Nl)|0,_n=_n+Math.imul(Eo,Ol)|0,Zn=Zn+Math.imul(Eo,Nl)|0,On=On+Math.imul(_c,Ul)|0,_n=_n+Math.imul(_c,Cl)|0,_n=_n+Math.imul(Ko,Ul)|0,Zn=Zn+Math.imul(Ko,Cl)|0,On=On+Math.imul(Fo,wo)|0,_n=_n+Math.imul(Fo,$o)|0,_n=_n+Math.imul(Lo,wo)|0,Zn=Zn+Math.imul(Lo,$o)|0,On=On+Math.imul(jo,po)|0,_n=_n+Math.imul(jo,So)|0,_n=_n+Math.imul(No,po)|0,Zn=Zn+Math.imul(No,So)|0,On=On+Math.imul(qo,Bo)|0,_n=_n+Math.imul(qo,Ho)|0,_n=_n+Math.imul(Zo,Bo)|0,Zn=Zn+Math.imul(Zo,Ho)|0,On=On+Math.imul(Ro,El)|0,_n=_n+Math.imul(Ro,$l)|0,_n=_n+Math.imul(To,El)|0,Zn=Zn+Math.imul(To,$l)|0;var Hl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Hl>>>26)|0,Hl&=67108863,On=Math.imul(go,Ol),_n=Math.imul(go,Nl),_n=_n+Math.imul(Co,Ol)|0,Zn=Math.imul(Co,Nl),On=On+Math.imul(Sl,Ul)|0,_n=_n+Math.imul(Sl,Cl)|0,_n=_n+Math.imul(Eo,Ul)|0,Zn=Zn+Math.imul(Eo,Cl)|0,On=On+Math.imul(_c,wo)|0,_n=_n+Math.imul(_c,$o)|0,_n=_n+Math.imul(Ko,wo)|0,Zn=Zn+Math.imul(Ko,$o)|0,On=On+Math.imul(Fo,po)|0,_n=_n+Math.imul(Fo,So)|0,_n=_n+Math.imul(Lo,po)|0,Zn=Zn+Math.imul(Lo,So)|0,On=On+Math.imul(jo,Bo)|0,_n=_n+Math.imul(jo,Ho)|0,_n=_n+Math.imul(No,Bo)|0,Zn=Zn+Math.imul(No,Ho)|0,On=On+Math.imul(qo,El)|0,_n=_n+Math.imul(qo,$l)|0,_n=_n+Math.imul(Zo,El)|0,Zn=Zn+Math.imul(Zo,$l)|0;var Zl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Zl>>>26)|0,Zl&=67108863,On=Math.imul(go,Ul),_n=Math.imul(go,Cl),_n=_n+Math.imul(Co,Ul)|0,Zn=Math.imul(Co,Cl),On=On+Math.imul(Sl,wo)|0,_n=_n+Math.imul(Sl,$o)|0,_n=_n+Math.imul(Eo,wo)|0,Zn=Zn+Math.imul(Eo,$o)|0,On=On+Math.imul(_c,po)|0,_n=_n+Math.imul(_c,So)|0,_n=_n+Math.imul(Ko,po)|0,Zn=Zn+Math.imul(Ko,So)|0,On=On+Math.imul(Fo,Bo)|0,_n=_n+Math.imul(Fo,Ho)|0,_n=_n+Math.imul(Lo,Bo)|0,Zn=Zn+Math.imul(Lo,Ho)|0,On=On+Math.imul(jo,El)|0,_n=_n+Math.imul(jo,$l)|0,_n=_n+Math.imul(No,El)|0,Zn=Zn+Math.imul(No,$l)|0;var Jl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Jl>>>26)|0,Jl&=67108863,On=Math.imul(go,wo),_n=Math.imul(go,$o),_n=_n+Math.imul(Co,wo)|0,Zn=Math.imul(Co,$o),On=On+Math.imul(Sl,po)|0,_n=_n+Math.imul(Sl,So)|0,_n=_n+Math.imul(Eo,po)|0,Zn=Zn+Math.imul(Eo,So)|0,On=On+Math.imul(_c,Bo)|0,_n=_n+Math.imul(_c,Ho)|0,_n=_n+Math.imul(Ko,Bo)|0,Zn=Zn+Math.imul(Ko,Ho)|0,On=On+Math.imul(Fo,El)|0,_n=_n+Math.imul(Fo,$l)|0,_n=_n+Math.imul(Lo,El)|0,Zn=Zn+Math.imul(Lo,$l)|0;var Ml=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Ml>>>26)|0,Ml&=67108863,On=Math.imul(go,po),_n=Math.imul(go,So),_n=_n+Math.imul(Co,po)|0,Zn=Math.imul(Co,So),On=On+Math.imul(Sl,Bo)|0,_n=_n+Math.imul(Sl,Ho)|0,_n=_n+Math.imul(Eo,Bo)|0,Zn=Zn+Math.imul(Eo,Ho)|0,On=On+Math.imul(_c,El)|0,_n=_n+Math.imul(_c,$l)|0,_n=_n+Math.imul(Ko,El)|0,Zn=Zn+Math.imul(Ko,$l)|0;var Fl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Fl>>>26)|0,Fl&=67108863,On=Math.imul(go,Bo),_n=Math.imul(go,Ho),_n=_n+Math.imul(Co,Bo)|0,Zn=Math.imul(Co,Ho),On=On+Math.imul(Sl,El)|0,_n=_n+Math.imul(Sl,$l)|0,_n=_n+Math.imul(Eo,El)|0,Zn=Zn+Math.imul(Eo,$l)|0;var Yl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Yl>>>26)|0,Yl&=67108863,On=Math.imul(go,El),_n=Math.imul(go,$l),_n=_n+Math.imul(Co,El)|0,Zn=Math.imul(Co,$l);var Vl=(zn+On|0)+((_n&8191)<<13)|0;return zn=(Zn+(_n>>>13)|0)+(Vl>>>26)|0,Vl&=67108863,Nn[0]=Su,Nn[1]=nu,Nn[2]=pu,Nn[3]=mu,Nn[4]=hu,Nn[5]=yu,Nn[6]=_u,Nn[7]=fu,Nn[8]=vu,Nn[9]=iu,Nn[10]=su,Nn[11]=tu,Nn[12]=Hl,Nn[13]=Zl,Nn[14]=Jl,Nn[15]=Ml,Nn[16]=Fl,Nn[17]=Yl,Nn[18]=Vl,zn!==0&&(Nn[19]=zn,Sn.length++),Sn};Math.imul||(In=Tn);function jn(Rn,Gr,Yr){Yr.negative=Gr.negative^Rn.negative,Yr.length=Rn.length+Gr.length;for(var Sn=0,An=0,Pn=0;Pn>>26)|0,An+=Nn>>>26,Nn&=67108863}Yr.words[Pn]=zn,Sn=Nn,Nn=An}return Sn!==0?Yr.words[Pn]=Sn:Yr.length--,Yr._strip()}function Yn(Rn,Gr,Yr){return jn(Rn,Gr,Yr)}jr.prototype.mulTo=function(Gr,Yr){var Sn,An=this.length+Gr.length;return this.length===10&&Gr.length===10?Sn=In(this,Gr,Yr):An<63?Sn=Tn(this,Gr,Yr):An<1024?Sn=jn(this,Gr,Yr):Sn=Yn(this,Gr,Yr),Sn},jr.prototype.mul=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),this.mulTo(Gr,Yr)},jr.prototype.mulf=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),Yn(this,Gr,Yr)},jr.prototype.imul=function(Gr){return this.clone().mulTo(Gr,this)},jr.prototype.imuln=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(typeof Gr=="number"),Er(Gr<67108864);for(var Sn=0,An=0;An>=26,Sn+=Pn/67108864|0,Sn+=Nn>>>26,this.words[An]=Nn&67108863}return Sn!==0&&(this.words[An]=Sn,this.length++),Yr?this.ineg():this},jr.prototype.muln=function(Gr){return this.clone().imuln(Gr)},jr.prototype.sqr=function(){return this.mul(this)},jr.prototype.isqr=function(){return this.imul(this.clone())},jr.prototype.pow=function(Gr){var Yr=$n(Gr);if(Yr.length===0)return new jr(1);for(var Sn=this,An=0;An=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=67108863>>>26-Yr<<26-Yr,Pn;if(Yr!==0){var Nn=0;for(Pn=0;Pn>>26-Yr}Nn&&(this.words[Pn]=Nn,this.length++)}if(Sn!==0){for(Pn=this.length-1;Pn>=0;Pn--)this.words[Pn+Sn]=this.words[Pn];for(Pn=0;Pn=0);var An;Yr?An=(Yr-Yr%26)/26:An=0;var Pn=Gr%26,Nn=Math.min((Gr-Pn)/26,this.length),zn=67108863^67108863>>>Pn<Nn)for(this.length-=Nn,_n=0;_n=0&&(Zn!==0||_n>=An);_n--){var oo=this.words[_n]|0;this.words[_n]=Zn<<26-Pn|oo>>>Pn,Zn=oo&zn}return On&&Zn!==0&&(On.words[On.length++]=Zn),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},jr.prototype.ishrn=function(Gr,Yr,Sn){return Er(this.negative===0),this.iushrn(Gr,Yr,Sn)},jr.prototype.shln=function(Gr){return this.clone().ishln(Gr)},jr.prototype.ushln=function(Gr){return this.clone().iushln(Gr)},jr.prototype.shrn=function(Gr){return this.clone().ishrn(Gr)},jr.prototype.ushrn=function(Gr){return this.clone().iushrn(Gr)},jr.prototype.testn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<=0);var Yr=Gr%26,Sn=(Gr-Yr)/26;if(Er(this.negative===0,"imaskn works only with positive numbers"),this.length<=Sn)return this;if(Yr!==0&&Sn++,this.length=Math.min(Sn,this.length),Yr!==0){var An=67108863^67108863>>>Yr<=67108864;Yr++)this.words[Yr]-=67108864,Yr===this.length-1?this.words[Yr+1]=1:this.words[Yr+1]++;return this.length=Math.max(this.length,Yr+1),this},jr.prototype.isubn=function(Gr){if(Er(typeof Gr=="number"),Er(Gr<67108864),Gr<0)return this.iaddn(-Gr);if(this.negative!==0)return this.negative=0,this.iaddn(Gr),this.negative=1,this;if(this.words[0]-=Gr,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Yr=0;Yr>26)-(On/67108864|0),this.words[Pn+Sn]=Nn&67108863}for(;Pn>26,this.words[Pn+Sn]=Nn&67108863;if(zn===0)return this._strip();for(Er(zn===-1),zn=0,Pn=0;Pn>26,this.words[Pn]=Nn&67108863;return this.negative=1,this._strip()},jr.prototype._wordDiv=function(Gr,Yr){var Sn=this.length-Gr.length,An=this.clone(),Pn=Gr,Nn=Pn.words[Pn.length-1]|0,zn=this._countBits(Nn);Sn=26-zn,Sn!==0&&(Pn=Pn.ushln(Sn),An.iushln(Sn),Nn=Pn.words[Pn.length-1]|0);var On=An.length-Pn.length,_n;if(Yr!=="mod"){_n=new jr(null),_n.length=On+1,_n.words=new Array(_n.length);for(var Zn=0;Zn<_n.length;Zn++)_n.words[Zn]=0}var oo=An.clone()._ishlnsubmul(Pn,1,On);oo.negative===0&&(An=oo,_n&&(_n.words[On]=1));for(var uo=On-1;uo>=0;uo--){var lo=(An.words[Pn.length+uo]|0)*67108864+(An.words[Pn.length+uo-1]|0);for(lo=Math.min(lo/Nn|0,67108863),An._ishlnsubmul(Pn,lo,uo);An.negative!==0;)lo--,An.negative=0,An._ishlnsubmul(Pn,1,uo),An.isZero()||(An.negative^=1);_n&&(_n.words[uo]=lo)}return _n&&_n._strip(),An._strip(),Yr!=="div"&&Sn!==0&&An.iushrn(Sn),{div:_n||null,mod:An}},jr.prototype.divmod=function(Gr,Yr,Sn){if(Er(!Gr.isZero()),this.isZero())return{div:new jr(0),mod:new jr(0)};var An,Pn,Nn;return this.negative!==0&&Gr.negative===0?(Nn=this.neg().divmod(Gr,Yr),Yr!=="mod"&&(An=Nn.div.neg()),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.iadd(Gr)),{div:An,mod:Pn}):this.negative===0&&Gr.negative!==0?(Nn=this.divmod(Gr.neg(),Yr),Yr!=="mod"&&(An=Nn.div.neg()),{div:An,mod:Nn.mod}):this.negative&Gr.negative?(Nn=this.neg().divmod(Gr.neg(),Yr),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.isub(Gr)),{div:Nn.div,mod:Pn}):Gr.length>this.length||this.cmp(Gr)<0?{div:new jr(0),mod:this}:Gr.length===1?Yr==="div"?{div:this.divn(Gr.words[0]),mod:null}:Yr==="mod"?{div:null,mod:new jr(this.modrn(Gr.words[0]))}:{div:this.divn(Gr.words[0]),mod:new jr(this.modrn(Gr.words[0]))}:this._wordDiv(Gr,Yr)},jr.prototype.div=function(Gr){return this.divmod(Gr,"div",!1).div},jr.prototype.mod=function(Gr){return this.divmod(Gr,"mod",!1).mod},jr.prototype.umod=function(Gr){return this.divmod(Gr,"mod",!0).mod},jr.prototype.divRound=function(Gr){var Yr=this.divmod(Gr);if(Yr.mod.isZero())return Yr.div;var Sn=Yr.div.negative!==0?Yr.mod.isub(Gr):Yr.mod,An=Gr.ushrn(1),Pn=Gr.andln(1),Nn=Sn.cmp(An);return Nn<0||Pn===1&&Nn===0?Yr.div:Yr.div.negative!==0?Yr.div.isubn(1):Yr.div.iaddn(1)},jr.prototype.modrn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=(1<<26)%Gr,An=0,Pn=this.length-1;Pn>=0;Pn--)An=(Sn*An+(this.words[Pn]|0))%Gr;return Yr?-An:An},jr.prototype.modn=function(Gr){return this.modrn(Gr)},jr.prototype.idivn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=0,An=this.length-1;An>=0;An--){var Pn=(this.words[An]|0)+Sn*67108864;this.words[An]=Pn/Gr|0,Sn=Pn%Gr}return this._strip(),Yr?this.ineg():this},jr.prototype.divn=function(Gr){return this.clone().idivn(Gr)},jr.prototype.egcd=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=new jr(0),zn=new jr(1),On=0;Yr.isEven()&&Sn.isEven();)Yr.iushrn(1),Sn.iushrn(1),++On;for(var _n=Sn.clone(),Zn=Yr.clone();!Yr.isZero();){for(var oo=0,uo=1;!(Yr.words[0]&uo)&&oo<26;++oo,uo<<=1);if(oo>0)for(Yr.iushrn(oo);oo-- >0;)(An.isOdd()||Pn.isOdd())&&(An.iadd(_n),Pn.isub(Zn)),An.iushrn(1),Pn.iushrn(1);for(var lo=0,co=1;!(Sn.words[0]&co)&&lo<26;++lo,co<<=1);if(lo>0)for(Sn.iushrn(lo);lo-- >0;)(Nn.isOdd()||zn.isOdd())&&(Nn.iadd(_n),zn.isub(Zn)),Nn.iushrn(1),zn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Nn),Pn.isub(zn)):(Sn.isub(Yr),Nn.isub(An),zn.isub(Pn))}return{a:Nn,b:zn,gcd:Sn.iushln(On)}},jr.prototype._invmp=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=Sn.clone();Yr.cmpn(1)>0&&Sn.cmpn(1)>0;){for(var zn=0,On=1;!(Yr.words[0]&On)&&zn<26;++zn,On<<=1);if(zn>0)for(Yr.iushrn(zn);zn-- >0;)An.isOdd()&&An.iadd(Nn),An.iushrn(1);for(var _n=0,Zn=1;!(Sn.words[0]&Zn)&&_n<26;++_n,Zn<<=1);if(_n>0)for(Sn.iushrn(_n);_n-- >0;)Pn.isOdd()&&Pn.iadd(Nn),Pn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Pn)):(Sn.isub(Yr),Pn.isub(An))}var oo;return Yr.cmpn(1)===0?oo=An:oo=Pn,oo.cmpn(0)<0&&oo.iadd(Gr),oo},jr.prototype.gcd=function(Gr){if(this.isZero())return Gr.abs();if(Gr.isZero())return this.abs();var Yr=this.clone(),Sn=Gr.clone();Yr.negative=0,Sn.negative=0;for(var An=0;Yr.isEven()&&Sn.isEven();An++)Yr.iushrn(1),Sn.iushrn(1);do{for(;Yr.isEven();)Yr.iushrn(1);for(;Sn.isEven();)Sn.iushrn(1);var Pn=Yr.cmp(Sn);if(Pn<0){var Nn=Yr;Yr=Sn,Sn=Nn}else if(Pn===0||Sn.cmpn(1)===0)break;Yr.isub(Sn)}while(!0);return Sn.iushln(An)},jr.prototype.invm=function(Gr){return this.egcd(Gr).a.umod(Gr)},jr.prototype.isEven=function(){return(this.words[0]&1)===0},jr.prototype.isOdd=function(){return(this.words[0]&1)===1},jr.prototype.andln=function(Gr){return this.words[0]&Gr},jr.prototype.bincn=function(Gr){Er(typeof Gr=="number");var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<>>26,zn&=67108863,this.words[Nn]=zn}return Pn!==0&&(this.words[Nn]=Pn,this.length++),this},jr.prototype.isZero=function(){return this.length===1&&this.words[0]===0},jr.prototype.cmpn=function(Gr){var Yr=Gr<0;if(this.negative!==0&&!Yr)return-1;if(this.negative===0&&Yr)return 1;this._strip();var Sn;if(this.length>1)Sn=1;else{Yr&&(Gr=-Gr),Er(Gr<=67108863,"Number is too big");var An=this.words[0]|0;Sn=An===Gr?0:AnGr.length)return 1;if(this.length=0;Sn--){var An=this.words[Sn]|0,Pn=Gr.words[Sn]|0;if(An!==Pn){AnPn&&(Yr=1);break}}return Yr},jr.prototype.gtn=function(Gr){return this.cmpn(Gr)===1},jr.prototype.gt=function(Gr){return this.cmp(Gr)===1},jr.prototype.gten=function(Gr){return this.cmpn(Gr)>=0},jr.prototype.gte=function(Gr){return this.cmp(Gr)>=0},jr.prototype.ltn=function(Gr){return this.cmpn(Gr)===-1},jr.prototype.lt=function(Gr){return this.cmp(Gr)===-1},jr.prototype.lten=function(Gr){return this.cmpn(Gr)<=0},jr.prototype.lte=function(Gr){return this.cmp(Gr)<=0},jr.prototype.eqn=function(Gr){return this.cmpn(Gr)===0},jr.prototype.eq=function(Gr){return this.cmp(Gr)===0},jr.red=function(Gr){return new no(Gr)},jr.prototype.toRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),Er(this.negative===0,"red works only with positives"),Gr.convertTo(this)._forceRed(Gr)},jr.prototype.fromRed=function(){return Er(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},jr.prototype._forceRed=function(Gr){return this.red=Gr,this},jr.prototype.forceRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),this._forceRed(Gr)},jr.prototype.redAdd=function(Gr){return Er(this.red,"redAdd works only with red numbers"),this.red.add(this,Gr)},jr.prototype.redIAdd=function(Gr){return Er(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,Gr)},jr.prototype.redSub=function(Gr){return Er(this.red,"redSub works only with red numbers"),this.red.sub(this,Gr)},jr.prototype.redISub=function(Gr){return Er(this.red,"redISub works only with red numbers"),this.red.isub(this,Gr)},jr.prototype.redShl=function(Gr){return Er(this.red,"redShl works only with red numbers"),this.red.shl(this,Gr)},jr.prototype.redMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.mul(this,Gr)},jr.prototype.redIMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.imul(this,Gr)},jr.prototype.redSqr=function(){return Er(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},jr.prototype.redISqr=function(){return Er(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},jr.prototype.redSqrt=function(){return Er(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},jr.prototype.redInvm=function(){return Er(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},jr.prototype.redNeg=function(){return Er(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},jr.prototype.redPow=function(Gr){return Er(this.red&&!Gr.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,Gr)};var ga={k256:null,p224:null,p192:null,p25519:null};function na(Rn,Gr){this.name=Rn,this.p=new jr(Gr,16),this.n=this.p.bitLength(),this.k=new jr(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}na.prototype._tmp=function(){var Gr=new jr(null);return Gr.words=new Array(Math.ceil(this.n/13)),Gr},na.prototype.ireduce=function(Gr){var Yr=Gr,Sn;do this.split(Yr,this.tmp),Yr=this.imulK(Yr),Yr=Yr.iadd(this.tmp),Sn=Yr.bitLength();while(Sn>this.n);var An=Sn0?Yr.isub(this.p):Yr.strip!==void 0?Yr.strip():Yr._strip(),Yr},na.prototype.split=function(Gr,Yr){Gr.iushrn(this.n,0,Yr)},na.prototype.imulK=function(Gr){return Gr.imul(this.k)};function _i(){na.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}kr(_i,na),_i.prototype.split=function(Gr,Yr){for(var Sn=4194303,An=Math.min(Gr.length,9),Pn=0;Pn>>22,Nn=zn}Nn>>>=22,Gr.words[Pn-10]=Nn,Nn===0&&Gr.length>10?Gr.length-=10:Gr.length-=9},_i.prototype.imulK=function(Gr){Gr.words[Gr.length]=0,Gr.words[Gr.length+1]=0,Gr.length+=2;for(var Yr=0,Sn=0;Sn>>=26,Gr.words[Sn]=Pn,Yr=An}return Yr!==0&&(Gr.words[Gr.length++]=Yr),Gr},jr._prime=function(Gr){if(ga[Gr])return ga[Gr];var Yr;if(Gr==="k256")Yr=new _i;else if(Gr==="p224")Yr=new ro;else if(Gr==="p192")Yr=new to;else if(Gr==="p25519")Yr=new io;else throw new Error("Unknown prime "+Gr);return ga[Gr]=Yr,Yr};function no(Rn){if(typeof Rn=="string"){var Gr=jr._prime(Rn);this.m=Gr.p,this.prime=Gr}else Er(Rn.gtn(1),"modulus must be greater than 1"),this.m=Rn,this.prime=null}no.prototype._verify1=function(Gr){Er(Gr.negative===0,"red works only with positives"),Er(Gr.red,"red works only with red numbers")},no.prototype._verify2=function(Gr,Yr){Er((Gr.negative|Yr.negative)===0,"red works only with positives"),Er(Gr.red&&Gr.red===Yr.red,"red works only with red numbers")},no.prototype.imod=function(Gr){return this.prime?this.prime.ireduce(Gr)._forceRed(this):(Hr(Gr,Gr.umod(this.m)._forceRed(this)),Gr)},no.prototype.neg=function(Gr){return Gr.isZero()?Gr.clone():this.m.sub(Gr)._forceRed(this)},no.prototype.add=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.add(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn._forceRed(this)},no.prototype.iadd=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.iadd(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn},no.prototype.sub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.sub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn._forceRed(this)},no.prototype.isub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.isub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn},no.prototype.shl=function(Gr,Yr){return this._verify1(Gr),this.imod(Gr.ushln(Yr))},no.prototype.imul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.imul(Yr))},no.prototype.mul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.mul(Yr))},no.prototype.isqr=function(Gr){return this.imul(Gr,Gr.clone())},no.prototype.sqr=function(Gr){return this.mul(Gr,Gr)},no.prototype.sqrt=function(Gr){if(Gr.isZero())return Gr.clone();var Yr=this.m.andln(3);if(Er(Yr%2===1),Yr===3){var Sn=this.m.add(new jr(1)).iushrn(2);return this.pow(Gr,Sn)}for(var An=this.m.subn(1),Pn=0;!An.isZero()&&An.andln(1)===0;)Pn++,An.iushrn(1);Er(!An.isZero());var Nn=new jr(1).toRed(this),zn=Nn.redNeg(),On=this.m.subn(1).iushrn(1),_n=this.m.bitLength();for(_n=new jr(2*_n*_n).toRed(this);this.pow(_n,On).cmp(zn)!==0;)_n.redIAdd(zn);for(var Zn=this.pow(_n,An),oo=this.pow(Gr,An.addn(1).iushrn(1)),uo=this.pow(Gr,An),lo=Pn;uo.cmp(Nn)!==0;){for(var co=uo,so=0;co.cmp(Nn)!==0;so++)co=co.redSqr();Er(so=0;Pn--){for(var Zn=Yr.words[Pn],oo=_n-1;oo>=0;oo--){var uo=Zn>>oo&1;if(Nn!==An[0]&&(Nn=this.sqr(Nn)),uo===0&&zn===0){On=0;continue}zn<<=1,zn|=uo,On++,!(On!==Sn&&(Pn!==0||oo!==0))&&(Nn=this.mul(Nn,An[zn]),On=0,zn=0)}_n=26}return Nn},no.prototype.convertTo=function(Gr){var Yr=Gr.umod(this.m);return Yr===Gr?Yr.clone():Yr},no.prototype.convertFrom=function(Gr){var Yr=Gr.clone();return Yr.red=null,Yr},jr.mont=function(Gr){return new $a(Gr)};function $a(Rn){no.call(this,Rn),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new jr(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}kr($a,no),$a.prototype.convertTo=function(Gr){return this.imod(Gr.ushln(this.shift))},$a.prototype.convertFrom=function(Gr){var Yr=this.imod(Gr.mul(this.rinv));return Yr.red=null,Yr},$a.prototype.imul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return Gr.words[0]=0,Gr.length=1,Gr;var Sn=Gr.imul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.mul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return new jr(0)._forceRed(this);var Sn=Gr.mul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.invm=function(Gr){var Yr=this.imod(Gr._invmp(this.m).mul(this.r2));return Yr._forceRed(this)}})(fr,commonjsGlobal)})(bn$3);var bnExports$3=bn$3.exports;const BN$2=getDefaultExportFromCjs$2(bnExports$3);var _Buffer$3=safeBufferExports.Buffer;function base$3(fr){if(fr.length>=255)throw new TypeError("Alphabet too long");for(var br=new Uint8Array(256),wr=0;wr>>0,jn=new Uint8Array(In);$n!==Tn;){for(var Yn=Xr[$n],ga=0,na=In-1;(Yn!==0||ga>>0,jn[na]=Yn%Br>>>0,Yn=Yn/Br>>>0;if(Yn!==0)throw new Error("Non-zero carry");wn=ga,$n++}for(var _i=In-wn;_i!==In&&jn[_i]===0;)_i++;for(var ro=qr.repeat(En);_i>>0,In=new Uint8Array(Tn);En>>0,In[ga]=jn%256>>>0,jn=jn/256>>>0;if(jn!==0)throw new Error("Non-zero carry");$n=Yn,En++}for(var na=Tn-$n;na!==Tn&&In[na]===0;)na++;var _i=_Buffer$3.allocUnsafe(wn+(Tn-na));_i.fill(0,0,wn);for(var ro=wn;na!==Tn;)_i[ro++]=In[na++];return _i}function Jr(Xr){var En=Zr(Xr);if(En)return En;throw new Error("Non-base"+Br+" character")}return{encode:Hr,decodeUnsafe:Zr,decode:Jr}}var src$3=base$3,basex$3=src$3,ALPHABET$3="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",bs58$5=basex$3(ALPHABET$3);const bs58$6=getDefaultExportFromCjs$2(bs58$5);var lib={},bn$2={exports:{}};bn$2.exports;(function(fr){(function(br,wr){function Er(Rn,Gr){if(!Rn)throw new Error(Gr||"Assertion failed")}function kr(Rn,Gr){Rn.super_=Gr;var Yr=function(){};Yr.prototype=Gr.prototype,Rn.prototype=new Yr,Rn.prototype.constructor=Rn}function jr(Rn,Gr,Yr){if(jr.isBN(Rn))return Rn;this.negative=0,this.words=null,this.length=0,this.red=null,Rn!==null&&((Gr==="le"||Gr==="be")&&(Yr=Gr,Gr=10),this._init(Rn||0,Gr||10,Yr||"be"))}typeof br=="object"?br.exports=jr:wr.BN=jr,jr.BN=jr,jr.wordSize=26;var Br;try{typeof window<"u"&&typeof window.Buffer<"u"?Br=window.Buffer:Br=require$$0$9.Buffer}catch{}jr.isBN=function(Gr){return Gr instanceof jr?!0:Gr!==null&&typeof Gr=="object"&&Gr.constructor.wordSize===jr.wordSize&&Array.isArray(Gr.words)},jr.max=function(Gr,Yr){return Gr.cmp(Yr)>0?Gr:Yr},jr.min=function(Gr,Yr){return Gr.cmp(Yr)<0?Gr:Yr},jr.prototype._init=function(Gr,Yr,Sn){if(typeof Gr=="number")return this._initNumber(Gr,Yr,Sn);if(typeof Gr=="object")return this._initArray(Gr,Yr,Sn);Yr==="hex"&&(Yr=16),Er(Yr===(Yr|0)&&Yr>=2&&Yr<=36),Gr=Gr.toString().replace(/\s+/g,"");var An=0;Gr[0]==="-"&&(An++,this.negative=1),An=0;An-=3)Nn=Gr[An]|Gr[An-1]<<8|Gr[An-2]<<16,this.words[Pn]|=Nn<>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);else if(Sn==="le")for(An=0,Pn=0;An>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);return this._strip()};function qr(Rn,Gr){var Yr=Rn.charCodeAt(Gr);if(Yr>=48&&Yr<=57)return Yr-48;if(Yr>=65&&Yr<=70)return Yr-55;if(Yr>=97&&Yr<=102)return Yr-87;Er(!1,"Invalid character in "+Rn)}function Wr(Rn,Gr,Yr){var Sn=qr(Rn,Yr);return Yr-1>=Gr&&(Sn|=qr(Rn,Yr-1)<<4),Sn}jr.prototype._parseHex=function(Gr,Yr,Sn){this.length=Math.ceil((Gr.length-Yr)/6),this.words=new Array(this.length);for(var An=0;An=Yr;An-=2)zn=Wr(Gr,Yr,An)<=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8;else{var On=Gr.length-Yr;for(An=On%2===0?Yr+1:Yr;An=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8}this._strip()};function Vr(Rn,Gr,Yr,Sn){for(var An=0,Pn=0,Nn=Math.min(Rn.length,Yr),zn=Gr;zn=49?Pn=On-49+10:On>=17?Pn=On-17+10:Pn=On,Er(On>=0&&Pn1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},jr.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{jr.prototype[Symbol.for("nodejs.util.inspect.custom")]=Zr}catch{jr.prototype.inspect=Zr}else jr.prototype.inspect=Zr;function Zr(){return(this.red?""}var Jr=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],Xr=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],En=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];jr.prototype.toString=function(Gr,Yr){Gr=Gr||10,Yr=Yr|0||1;var Sn;if(Gr===16||Gr==="hex"){Sn="";for(var An=0,Pn=0,Nn=0;Nn>>24-An&16777215,An+=2,An>=26&&(An-=26,Nn--),Pn!==0||Nn!==this.length-1?Sn=Jr[6-On.length]+On+Sn:Sn=On+Sn}for(Pn!==0&&(Sn=Pn.toString(16)+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}if(Gr===(Gr|0)&&Gr>=2&&Gr<=36){var _n=Xr[Gr],Zn=En[Gr];Sn="";var oo=this.clone();for(oo.negative=0;!oo.isZero();){var uo=oo.modrn(Zn).toString(Gr);oo=oo.idivn(Zn),oo.isZero()?Sn=uo+Sn:Sn=Jr[_n-uo.length]+uo+Sn}for(this.isZero()&&(Sn="0"+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}Er(!1,"Base should be between 2 and 36")},jr.prototype.toNumber=function(){var Gr=this.words[0];return this.length===2?Gr+=this.words[1]*67108864:this.length===3&&this.words[2]===1?Gr+=4503599627370496+this.words[1]*67108864:this.length>2&&Er(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-Gr:Gr},jr.prototype.toJSON=function(){return this.toString(16,2)},Br&&(jr.prototype.toBuffer=function(Gr,Yr){return this.toArrayLike(Br,Gr,Yr)}),jr.prototype.toArray=function(Gr,Yr){return this.toArrayLike(Array,Gr,Yr)};var wn=function(Gr,Yr){return Gr.allocUnsafe?Gr.allocUnsafe(Yr):new Gr(Yr)};jr.prototype.toArrayLike=function(Gr,Yr,Sn){this._strip();var An=this.byteLength(),Pn=Sn||Math.max(1,An);Er(An<=Pn,"byte array longer than desired length"),Er(Pn>0,"Requested array length <= 0");var Nn=wn(Gr,Pn),zn=Yr==="le"?"LE":"BE";return this["_toArrayLike"+zn](Nn,An),Nn},jr.prototype._toArrayLikeLE=function(Gr,Yr){for(var Sn=0,An=0,Pn=0,Nn=0;Pn>8&255),Sn>16&255),Nn===6?(Sn>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn=0&&(Gr[Sn--]=zn>>8&255),Sn>=0&&(Gr[Sn--]=zn>>16&255),Nn===6?(Sn>=0&&(Gr[Sn--]=zn>>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn>=0)for(Gr[Sn--]=An;Sn>=0;)Gr[Sn--]=0},Math.clz32?jr.prototype._countBits=function(Gr){return 32-Math.clz32(Gr)}:jr.prototype._countBits=function(Gr){var Yr=Gr,Sn=0;return Yr>=4096&&(Sn+=13,Yr>>>=13),Yr>=64&&(Sn+=7,Yr>>>=7),Yr>=8&&(Sn+=4,Yr>>>=4),Yr>=2&&(Sn+=2,Yr>>>=2),Sn+Yr},jr.prototype._zeroBits=function(Gr){if(Gr===0)return 26;var Yr=Gr,Sn=0;return Yr&8191||(Sn+=13,Yr>>>=13),Yr&127||(Sn+=7,Yr>>>=7),Yr&15||(Sn+=4,Yr>>>=4),Yr&3||(Sn+=2,Yr>>>=2),Yr&1||Sn++,Sn},jr.prototype.bitLength=function(){var Gr=this.words[this.length-1],Yr=this._countBits(Gr);return(this.length-1)*26+Yr};function $n(Rn){for(var Gr=new Array(Rn.bitLength()),Yr=0;Yr>>An&1}return Gr}jr.prototype.zeroBits=function(){if(this.isZero())return 0;for(var Gr=0,Yr=0;YrGr.length?this.clone().ior(Gr):Gr.clone().ior(this)},jr.prototype.uor=function(Gr){return this.length>Gr.length?this.clone().iuor(Gr):Gr.clone().iuor(this)},jr.prototype.iuand=function(Gr){var Yr;this.length>Gr.length?Yr=Gr:Yr=this;for(var Sn=0;SnGr.length?this.clone().iand(Gr):Gr.clone().iand(this)},jr.prototype.uand=function(Gr){return this.length>Gr.length?this.clone().iuand(Gr):Gr.clone().iuand(this)},jr.prototype.iuxor=function(Gr){var Yr,Sn;this.length>Gr.length?(Yr=this,Sn=Gr):(Yr=Gr,Sn=this);for(var An=0;AnGr.length?this.clone().ixor(Gr):Gr.clone().ixor(this)},jr.prototype.uxor=function(Gr){return this.length>Gr.length?this.clone().iuxor(Gr):Gr.clone().iuxor(this)},jr.prototype.inotn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Math.ceil(Gr/26)|0,Sn=Gr%26;this._expand(Yr),Sn>0&&Yr--;for(var An=0;An0&&(this.words[An]=~this.words[An]&67108863>>26-Sn),this._strip()},jr.prototype.notn=function(Gr){return this.clone().inotn(Gr)},jr.prototype.setn=function(Gr,Yr){Er(typeof Gr=="number"&&Gr>=0);var Sn=Gr/26|0,An=Gr%26;return this._expand(Sn+1),Yr?this.words[Sn]=this.words[Sn]|1<Gr.length?(Sn=this,An=Gr):(Sn=Gr,An=this);for(var Pn=0,Nn=0;Nn>>26;for(;Pn!==0&&Nn>>26;if(this.length=Sn.length,Pn!==0)this.words[this.length]=Pn,this.length++;else if(Sn!==this)for(;NnGr.length?this.clone().iadd(Gr):Gr.clone().iadd(this)},jr.prototype.isub=function(Gr){if(Gr.negative!==0){Gr.negative=0;var Yr=this.iadd(Gr);return Gr.negative=1,Yr._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(Gr),this.negative=1,this._normSign();var Sn=this.cmp(Gr);if(Sn===0)return this.negative=0,this.length=1,this.words[0]=0,this;var An,Pn;Sn>0?(An=this,Pn=Gr):(An=Gr,Pn=this);for(var Nn=0,zn=0;zn>26,this.words[zn]=Yr&67108863;for(;Nn!==0&&zn>26,this.words[zn]=Yr&67108863;if(Nn===0&&zn>>26,oo=On&67108863,uo=Math.min(_n,Gr.length-1),lo=Math.max(0,_n-Rn.length+1);lo<=uo;lo++){var co=_n-lo|0;An=Rn.words[co]|0,Pn=Gr.words[lo]|0,Nn=An*Pn+oo,Zn+=Nn/67108864|0,oo=Nn&67108863}Yr.words[_n]=oo|0,On=Zn|0}return On!==0?Yr.words[_n]=On|0:Yr.length--,Yr._strip()}var In=function(Gr,Yr,Sn){var An=Gr.words,Pn=Yr.words,Nn=Sn.words,zn=0,On,_n,Zn,oo=An[0]|0,uo=oo&8191,lo=oo>>>13,co=An[1]|0,so=co&8191,yo=co>>>13,fo=An[2]|0,ho=fo&8191,vo=fo>>>13,Io=An[3]|0,Ro=Io&8191,To=Io>>>13,Wo=An[4]|0,qo=Wo&8191,Zo=Wo>>>13,Qo=An[5]|0,jo=Qo&8191,No=Qo>>>13,Tl=An[6]|0,Fo=Tl&8191,Lo=Tl>>>13,Rl=An[7]|0,_c=Rl&8191,Ko=Rl>>>13,zl=An[8]|0,Sl=zl&8191,Eo=zl>>>13,bo=An[9]|0,go=bo&8191,Co=bo>>>13,zo=Pn[0]|0,Do=zo&8191,Uo=zo>>>13,ru=Pn[1]|0,Dl=ru&8191,xl=ru>>>13,bu=Pn[2]|0,yl=bu&8191,Il=bu>>>13,cu=Pn[3]|0,Bl=cu&8191,Pl=cu>>>13,wu=Pn[4]|0,Ol=wu&8191,Nl=wu>>>13,Tu=Pn[5]|0,Ul=Tu&8191,Cl=Tu>>>13,gu=Pn[6]|0,wo=gu&8191,$o=gu>>>13,Ao=Pn[7]|0,po=Ao&8191,So=Ao>>>13,Jo=Pn[8]|0,Bo=Jo&8191,Ho=Jo>>>13,Wl=Pn[9]|0,El=Wl&8191,$l=Wl>>>13;Sn.negative=Gr.negative^Yr.negative,Sn.length=19,On=Math.imul(uo,Do),_n=Math.imul(uo,Uo),_n=_n+Math.imul(lo,Do)|0,Zn=Math.imul(lo,Uo);var Su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Su>>>26)|0,Su&=67108863,On=Math.imul(so,Do),_n=Math.imul(so,Uo),_n=_n+Math.imul(yo,Do)|0,Zn=Math.imul(yo,Uo),On=On+Math.imul(uo,Dl)|0,_n=_n+Math.imul(uo,xl)|0,_n=_n+Math.imul(lo,Dl)|0,Zn=Zn+Math.imul(lo,xl)|0;var nu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(nu>>>26)|0,nu&=67108863,On=Math.imul(ho,Do),_n=Math.imul(ho,Uo),_n=_n+Math.imul(vo,Do)|0,Zn=Math.imul(vo,Uo),On=On+Math.imul(so,Dl)|0,_n=_n+Math.imul(so,xl)|0,_n=_n+Math.imul(yo,Dl)|0,Zn=Zn+Math.imul(yo,xl)|0,On=On+Math.imul(uo,yl)|0,_n=_n+Math.imul(uo,Il)|0,_n=_n+Math.imul(lo,yl)|0,Zn=Zn+Math.imul(lo,Il)|0;var pu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(pu>>>26)|0,pu&=67108863,On=Math.imul(Ro,Do),_n=Math.imul(Ro,Uo),_n=_n+Math.imul(To,Do)|0,Zn=Math.imul(To,Uo),On=On+Math.imul(ho,Dl)|0,_n=_n+Math.imul(ho,xl)|0,_n=_n+Math.imul(vo,Dl)|0,Zn=Zn+Math.imul(vo,xl)|0,On=On+Math.imul(so,yl)|0,_n=_n+Math.imul(so,Il)|0,_n=_n+Math.imul(yo,yl)|0,Zn=Zn+Math.imul(yo,Il)|0,On=On+Math.imul(uo,Bl)|0,_n=_n+Math.imul(uo,Pl)|0,_n=_n+Math.imul(lo,Bl)|0,Zn=Zn+Math.imul(lo,Pl)|0;var mu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(mu>>>26)|0,mu&=67108863,On=Math.imul(qo,Do),_n=Math.imul(qo,Uo),_n=_n+Math.imul(Zo,Do)|0,Zn=Math.imul(Zo,Uo),On=On+Math.imul(Ro,Dl)|0,_n=_n+Math.imul(Ro,xl)|0,_n=_n+Math.imul(To,Dl)|0,Zn=Zn+Math.imul(To,xl)|0,On=On+Math.imul(ho,yl)|0,_n=_n+Math.imul(ho,Il)|0,_n=_n+Math.imul(vo,yl)|0,Zn=Zn+Math.imul(vo,Il)|0,On=On+Math.imul(so,Bl)|0,_n=_n+Math.imul(so,Pl)|0,_n=_n+Math.imul(yo,Bl)|0,Zn=Zn+Math.imul(yo,Pl)|0,On=On+Math.imul(uo,Ol)|0,_n=_n+Math.imul(uo,Nl)|0,_n=_n+Math.imul(lo,Ol)|0,Zn=Zn+Math.imul(lo,Nl)|0;var hu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(hu>>>26)|0,hu&=67108863,On=Math.imul(jo,Do),_n=Math.imul(jo,Uo),_n=_n+Math.imul(No,Do)|0,Zn=Math.imul(No,Uo),On=On+Math.imul(qo,Dl)|0,_n=_n+Math.imul(qo,xl)|0,_n=_n+Math.imul(Zo,Dl)|0,Zn=Zn+Math.imul(Zo,xl)|0,On=On+Math.imul(Ro,yl)|0,_n=_n+Math.imul(Ro,Il)|0,_n=_n+Math.imul(To,yl)|0,Zn=Zn+Math.imul(To,Il)|0,On=On+Math.imul(ho,Bl)|0,_n=_n+Math.imul(ho,Pl)|0,_n=_n+Math.imul(vo,Bl)|0,Zn=Zn+Math.imul(vo,Pl)|0,On=On+Math.imul(so,Ol)|0,_n=_n+Math.imul(so,Nl)|0,_n=_n+Math.imul(yo,Ol)|0,Zn=Zn+Math.imul(yo,Nl)|0,On=On+Math.imul(uo,Ul)|0,_n=_n+Math.imul(uo,Cl)|0,_n=_n+Math.imul(lo,Ul)|0,Zn=Zn+Math.imul(lo,Cl)|0;var yu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(yu>>>26)|0,yu&=67108863,On=Math.imul(Fo,Do),_n=Math.imul(Fo,Uo),_n=_n+Math.imul(Lo,Do)|0,Zn=Math.imul(Lo,Uo),On=On+Math.imul(jo,Dl)|0,_n=_n+Math.imul(jo,xl)|0,_n=_n+Math.imul(No,Dl)|0,Zn=Zn+Math.imul(No,xl)|0,On=On+Math.imul(qo,yl)|0,_n=_n+Math.imul(qo,Il)|0,_n=_n+Math.imul(Zo,yl)|0,Zn=Zn+Math.imul(Zo,Il)|0,On=On+Math.imul(Ro,Bl)|0,_n=_n+Math.imul(Ro,Pl)|0,_n=_n+Math.imul(To,Bl)|0,Zn=Zn+Math.imul(To,Pl)|0,On=On+Math.imul(ho,Ol)|0,_n=_n+Math.imul(ho,Nl)|0,_n=_n+Math.imul(vo,Ol)|0,Zn=Zn+Math.imul(vo,Nl)|0,On=On+Math.imul(so,Ul)|0,_n=_n+Math.imul(so,Cl)|0,_n=_n+Math.imul(yo,Ul)|0,Zn=Zn+Math.imul(yo,Cl)|0,On=On+Math.imul(uo,wo)|0,_n=_n+Math.imul(uo,$o)|0,_n=_n+Math.imul(lo,wo)|0,Zn=Zn+Math.imul(lo,$o)|0;var _u=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(_u>>>26)|0,_u&=67108863,On=Math.imul(_c,Do),_n=Math.imul(_c,Uo),_n=_n+Math.imul(Ko,Do)|0,Zn=Math.imul(Ko,Uo),On=On+Math.imul(Fo,Dl)|0,_n=_n+Math.imul(Fo,xl)|0,_n=_n+Math.imul(Lo,Dl)|0,Zn=Zn+Math.imul(Lo,xl)|0,On=On+Math.imul(jo,yl)|0,_n=_n+Math.imul(jo,Il)|0,_n=_n+Math.imul(No,yl)|0,Zn=Zn+Math.imul(No,Il)|0,On=On+Math.imul(qo,Bl)|0,_n=_n+Math.imul(qo,Pl)|0,_n=_n+Math.imul(Zo,Bl)|0,Zn=Zn+Math.imul(Zo,Pl)|0,On=On+Math.imul(Ro,Ol)|0,_n=_n+Math.imul(Ro,Nl)|0,_n=_n+Math.imul(To,Ol)|0,Zn=Zn+Math.imul(To,Nl)|0,On=On+Math.imul(ho,Ul)|0,_n=_n+Math.imul(ho,Cl)|0,_n=_n+Math.imul(vo,Ul)|0,Zn=Zn+Math.imul(vo,Cl)|0,On=On+Math.imul(so,wo)|0,_n=_n+Math.imul(so,$o)|0,_n=_n+Math.imul(yo,wo)|0,Zn=Zn+Math.imul(yo,$o)|0,On=On+Math.imul(uo,po)|0,_n=_n+Math.imul(uo,So)|0,_n=_n+Math.imul(lo,po)|0,Zn=Zn+Math.imul(lo,So)|0;var fu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(fu>>>26)|0,fu&=67108863,On=Math.imul(Sl,Do),_n=Math.imul(Sl,Uo),_n=_n+Math.imul(Eo,Do)|0,Zn=Math.imul(Eo,Uo),On=On+Math.imul(_c,Dl)|0,_n=_n+Math.imul(_c,xl)|0,_n=_n+Math.imul(Ko,Dl)|0,Zn=Zn+Math.imul(Ko,xl)|0,On=On+Math.imul(Fo,yl)|0,_n=_n+Math.imul(Fo,Il)|0,_n=_n+Math.imul(Lo,yl)|0,Zn=Zn+Math.imul(Lo,Il)|0,On=On+Math.imul(jo,Bl)|0,_n=_n+Math.imul(jo,Pl)|0,_n=_n+Math.imul(No,Bl)|0,Zn=Zn+Math.imul(No,Pl)|0,On=On+Math.imul(qo,Ol)|0,_n=_n+Math.imul(qo,Nl)|0,_n=_n+Math.imul(Zo,Ol)|0,Zn=Zn+Math.imul(Zo,Nl)|0,On=On+Math.imul(Ro,Ul)|0,_n=_n+Math.imul(Ro,Cl)|0,_n=_n+Math.imul(To,Ul)|0,Zn=Zn+Math.imul(To,Cl)|0,On=On+Math.imul(ho,wo)|0,_n=_n+Math.imul(ho,$o)|0,_n=_n+Math.imul(vo,wo)|0,Zn=Zn+Math.imul(vo,$o)|0,On=On+Math.imul(so,po)|0,_n=_n+Math.imul(so,So)|0,_n=_n+Math.imul(yo,po)|0,Zn=Zn+Math.imul(yo,So)|0,On=On+Math.imul(uo,Bo)|0,_n=_n+Math.imul(uo,Ho)|0,_n=_n+Math.imul(lo,Bo)|0,Zn=Zn+Math.imul(lo,Ho)|0;var vu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(vu>>>26)|0,vu&=67108863,On=Math.imul(go,Do),_n=Math.imul(go,Uo),_n=_n+Math.imul(Co,Do)|0,Zn=Math.imul(Co,Uo),On=On+Math.imul(Sl,Dl)|0,_n=_n+Math.imul(Sl,xl)|0,_n=_n+Math.imul(Eo,Dl)|0,Zn=Zn+Math.imul(Eo,xl)|0,On=On+Math.imul(_c,yl)|0,_n=_n+Math.imul(_c,Il)|0,_n=_n+Math.imul(Ko,yl)|0,Zn=Zn+Math.imul(Ko,Il)|0,On=On+Math.imul(Fo,Bl)|0,_n=_n+Math.imul(Fo,Pl)|0,_n=_n+Math.imul(Lo,Bl)|0,Zn=Zn+Math.imul(Lo,Pl)|0,On=On+Math.imul(jo,Ol)|0,_n=_n+Math.imul(jo,Nl)|0,_n=_n+Math.imul(No,Ol)|0,Zn=Zn+Math.imul(No,Nl)|0,On=On+Math.imul(qo,Ul)|0,_n=_n+Math.imul(qo,Cl)|0,_n=_n+Math.imul(Zo,Ul)|0,Zn=Zn+Math.imul(Zo,Cl)|0,On=On+Math.imul(Ro,wo)|0,_n=_n+Math.imul(Ro,$o)|0,_n=_n+Math.imul(To,wo)|0,Zn=Zn+Math.imul(To,$o)|0,On=On+Math.imul(ho,po)|0,_n=_n+Math.imul(ho,So)|0,_n=_n+Math.imul(vo,po)|0,Zn=Zn+Math.imul(vo,So)|0,On=On+Math.imul(so,Bo)|0,_n=_n+Math.imul(so,Ho)|0,_n=_n+Math.imul(yo,Bo)|0,Zn=Zn+Math.imul(yo,Ho)|0,On=On+Math.imul(uo,El)|0,_n=_n+Math.imul(uo,$l)|0,_n=_n+Math.imul(lo,El)|0,Zn=Zn+Math.imul(lo,$l)|0;var iu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(iu>>>26)|0,iu&=67108863,On=Math.imul(go,Dl),_n=Math.imul(go,xl),_n=_n+Math.imul(Co,Dl)|0,Zn=Math.imul(Co,xl),On=On+Math.imul(Sl,yl)|0,_n=_n+Math.imul(Sl,Il)|0,_n=_n+Math.imul(Eo,yl)|0,Zn=Zn+Math.imul(Eo,Il)|0,On=On+Math.imul(_c,Bl)|0,_n=_n+Math.imul(_c,Pl)|0,_n=_n+Math.imul(Ko,Bl)|0,Zn=Zn+Math.imul(Ko,Pl)|0,On=On+Math.imul(Fo,Ol)|0,_n=_n+Math.imul(Fo,Nl)|0,_n=_n+Math.imul(Lo,Ol)|0,Zn=Zn+Math.imul(Lo,Nl)|0,On=On+Math.imul(jo,Ul)|0,_n=_n+Math.imul(jo,Cl)|0,_n=_n+Math.imul(No,Ul)|0,Zn=Zn+Math.imul(No,Cl)|0,On=On+Math.imul(qo,wo)|0,_n=_n+Math.imul(qo,$o)|0,_n=_n+Math.imul(Zo,wo)|0,Zn=Zn+Math.imul(Zo,$o)|0,On=On+Math.imul(Ro,po)|0,_n=_n+Math.imul(Ro,So)|0,_n=_n+Math.imul(To,po)|0,Zn=Zn+Math.imul(To,So)|0,On=On+Math.imul(ho,Bo)|0,_n=_n+Math.imul(ho,Ho)|0,_n=_n+Math.imul(vo,Bo)|0,Zn=Zn+Math.imul(vo,Ho)|0,On=On+Math.imul(so,El)|0,_n=_n+Math.imul(so,$l)|0,_n=_n+Math.imul(yo,El)|0,Zn=Zn+Math.imul(yo,$l)|0;var su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(su>>>26)|0,su&=67108863,On=Math.imul(go,yl),_n=Math.imul(go,Il),_n=_n+Math.imul(Co,yl)|0,Zn=Math.imul(Co,Il),On=On+Math.imul(Sl,Bl)|0,_n=_n+Math.imul(Sl,Pl)|0,_n=_n+Math.imul(Eo,Bl)|0,Zn=Zn+Math.imul(Eo,Pl)|0,On=On+Math.imul(_c,Ol)|0,_n=_n+Math.imul(_c,Nl)|0,_n=_n+Math.imul(Ko,Ol)|0,Zn=Zn+Math.imul(Ko,Nl)|0,On=On+Math.imul(Fo,Ul)|0,_n=_n+Math.imul(Fo,Cl)|0,_n=_n+Math.imul(Lo,Ul)|0,Zn=Zn+Math.imul(Lo,Cl)|0,On=On+Math.imul(jo,wo)|0,_n=_n+Math.imul(jo,$o)|0,_n=_n+Math.imul(No,wo)|0,Zn=Zn+Math.imul(No,$o)|0,On=On+Math.imul(qo,po)|0,_n=_n+Math.imul(qo,So)|0,_n=_n+Math.imul(Zo,po)|0,Zn=Zn+Math.imul(Zo,So)|0,On=On+Math.imul(Ro,Bo)|0,_n=_n+Math.imul(Ro,Ho)|0,_n=_n+Math.imul(To,Bo)|0,Zn=Zn+Math.imul(To,Ho)|0,On=On+Math.imul(ho,El)|0,_n=_n+Math.imul(ho,$l)|0,_n=_n+Math.imul(vo,El)|0,Zn=Zn+Math.imul(vo,$l)|0;var tu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(tu>>>26)|0,tu&=67108863,On=Math.imul(go,Bl),_n=Math.imul(go,Pl),_n=_n+Math.imul(Co,Bl)|0,Zn=Math.imul(Co,Pl),On=On+Math.imul(Sl,Ol)|0,_n=_n+Math.imul(Sl,Nl)|0,_n=_n+Math.imul(Eo,Ol)|0,Zn=Zn+Math.imul(Eo,Nl)|0,On=On+Math.imul(_c,Ul)|0,_n=_n+Math.imul(_c,Cl)|0,_n=_n+Math.imul(Ko,Ul)|0,Zn=Zn+Math.imul(Ko,Cl)|0,On=On+Math.imul(Fo,wo)|0,_n=_n+Math.imul(Fo,$o)|0,_n=_n+Math.imul(Lo,wo)|0,Zn=Zn+Math.imul(Lo,$o)|0,On=On+Math.imul(jo,po)|0,_n=_n+Math.imul(jo,So)|0,_n=_n+Math.imul(No,po)|0,Zn=Zn+Math.imul(No,So)|0,On=On+Math.imul(qo,Bo)|0,_n=_n+Math.imul(qo,Ho)|0,_n=_n+Math.imul(Zo,Bo)|0,Zn=Zn+Math.imul(Zo,Ho)|0,On=On+Math.imul(Ro,El)|0,_n=_n+Math.imul(Ro,$l)|0,_n=_n+Math.imul(To,El)|0,Zn=Zn+Math.imul(To,$l)|0;var Hl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Hl>>>26)|0,Hl&=67108863,On=Math.imul(go,Ol),_n=Math.imul(go,Nl),_n=_n+Math.imul(Co,Ol)|0,Zn=Math.imul(Co,Nl),On=On+Math.imul(Sl,Ul)|0,_n=_n+Math.imul(Sl,Cl)|0,_n=_n+Math.imul(Eo,Ul)|0,Zn=Zn+Math.imul(Eo,Cl)|0,On=On+Math.imul(_c,wo)|0,_n=_n+Math.imul(_c,$o)|0,_n=_n+Math.imul(Ko,wo)|0,Zn=Zn+Math.imul(Ko,$o)|0,On=On+Math.imul(Fo,po)|0,_n=_n+Math.imul(Fo,So)|0,_n=_n+Math.imul(Lo,po)|0,Zn=Zn+Math.imul(Lo,So)|0,On=On+Math.imul(jo,Bo)|0,_n=_n+Math.imul(jo,Ho)|0,_n=_n+Math.imul(No,Bo)|0,Zn=Zn+Math.imul(No,Ho)|0,On=On+Math.imul(qo,El)|0,_n=_n+Math.imul(qo,$l)|0,_n=_n+Math.imul(Zo,El)|0,Zn=Zn+Math.imul(Zo,$l)|0;var Zl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Zl>>>26)|0,Zl&=67108863,On=Math.imul(go,Ul),_n=Math.imul(go,Cl),_n=_n+Math.imul(Co,Ul)|0,Zn=Math.imul(Co,Cl),On=On+Math.imul(Sl,wo)|0,_n=_n+Math.imul(Sl,$o)|0,_n=_n+Math.imul(Eo,wo)|0,Zn=Zn+Math.imul(Eo,$o)|0,On=On+Math.imul(_c,po)|0,_n=_n+Math.imul(_c,So)|0,_n=_n+Math.imul(Ko,po)|0,Zn=Zn+Math.imul(Ko,So)|0,On=On+Math.imul(Fo,Bo)|0,_n=_n+Math.imul(Fo,Ho)|0,_n=_n+Math.imul(Lo,Bo)|0,Zn=Zn+Math.imul(Lo,Ho)|0,On=On+Math.imul(jo,El)|0,_n=_n+Math.imul(jo,$l)|0,_n=_n+Math.imul(No,El)|0,Zn=Zn+Math.imul(No,$l)|0;var Jl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Jl>>>26)|0,Jl&=67108863,On=Math.imul(go,wo),_n=Math.imul(go,$o),_n=_n+Math.imul(Co,wo)|0,Zn=Math.imul(Co,$o),On=On+Math.imul(Sl,po)|0,_n=_n+Math.imul(Sl,So)|0,_n=_n+Math.imul(Eo,po)|0,Zn=Zn+Math.imul(Eo,So)|0,On=On+Math.imul(_c,Bo)|0,_n=_n+Math.imul(_c,Ho)|0,_n=_n+Math.imul(Ko,Bo)|0,Zn=Zn+Math.imul(Ko,Ho)|0,On=On+Math.imul(Fo,El)|0,_n=_n+Math.imul(Fo,$l)|0,_n=_n+Math.imul(Lo,El)|0,Zn=Zn+Math.imul(Lo,$l)|0;var Ml=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Ml>>>26)|0,Ml&=67108863,On=Math.imul(go,po),_n=Math.imul(go,So),_n=_n+Math.imul(Co,po)|0,Zn=Math.imul(Co,So),On=On+Math.imul(Sl,Bo)|0,_n=_n+Math.imul(Sl,Ho)|0,_n=_n+Math.imul(Eo,Bo)|0,Zn=Zn+Math.imul(Eo,Ho)|0,On=On+Math.imul(_c,El)|0,_n=_n+Math.imul(_c,$l)|0,_n=_n+Math.imul(Ko,El)|0,Zn=Zn+Math.imul(Ko,$l)|0;var Fl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Fl>>>26)|0,Fl&=67108863,On=Math.imul(go,Bo),_n=Math.imul(go,Ho),_n=_n+Math.imul(Co,Bo)|0,Zn=Math.imul(Co,Ho),On=On+Math.imul(Sl,El)|0,_n=_n+Math.imul(Sl,$l)|0,_n=_n+Math.imul(Eo,El)|0,Zn=Zn+Math.imul(Eo,$l)|0;var Yl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Yl>>>26)|0,Yl&=67108863,On=Math.imul(go,El),_n=Math.imul(go,$l),_n=_n+Math.imul(Co,El)|0,Zn=Math.imul(Co,$l);var Vl=(zn+On|0)+((_n&8191)<<13)|0;return zn=(Zn+(_n>>>13)|0)+(Vl>>>26)|0,Vl&=67108863,Nn[0]=Su,Nn[1]=nu,Nn[2]=pu,Nn[3]=mu,Nn[4]=hu,Nn[5]=yu,Nn[6]=_u,Nn[7]=fu,Nn[8]=vu,Nn[9]=iu,Nn[10]=su,Nn[11]=tu,Nn[12]=Hl,Nn[13]=Zl,Nn[14]=Jl,Nn[15]=Ml,Nn[16]=Fl,Nn[17]=Yl,Nn[18]=Vl,zn!==0&&(Nn[19]=zn,Sn.length++),Sn};Math.imul||(In=Tn);function jn(Rn,Gr,Yr){Yr.negative=Gr.negative^Rn.negative,Yr.length=Rn.length+Gr.length;for(var Sn=0,An=0,Pn=0;Pn>>26)|0,An+=Nn>>>26,Nn&=67108863}Yr.words[Pn]=zn,Sn=Nn,Nn=An}return Sn!==0?Yr.words[Pn]=Sn:Yr.length--,Yr._strip()}function Yn(Rn,Gr,Yr){return jn(Rn,Gr,Yr)}jr.prototype.mulTo=function(Gr,Yr){var Sn,An=this.length+Gr.length;return this.length===10&&Gr.length===10?Sn=In(this,Gr,Yr):An<63?Sn=Tn(this,Gr,Yr):An<1024?Sn=jn(this,Gr,Yr):Sn=Yn(this,Gr,Yr),Sn},jr.prototype.mul=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),this.mulTo(Gr,Yr)},jr.prototype.mulf=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),Yn(this,Gr,Yr)},jr.prototype.imul=function(Gr){return this.clone().mulTo(Gr,this)},jr.prototype.imuln=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(typeof Gr=="number"),Er(Gr<67108864);for(var Sn=0,An=0;An>=26,Sn+=Pn/67108864|0,Sn+=Nn>>>26,this.words[An]=Nn&67108863}return Sn!==0&&(this.words[An]=Sn,this.length++),Yr?this.ineg():this},jr.prototype.muln=function(Gr){return this.clone().imuln(Gr)},jr.prototype.sqr=function(){return this.mul(this)},jr.prototype.isqr=function(){return this.imul(this.clone())},jr.prototype.pow=function(Gr){var Yr=$n(Gr);if(Yr.length===0)return new jr(1);for(var Sn=this,An=0;An=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=67108863>>>26-Yr<<26-Yr,Pn;if(Yr!==0){var Nn=0;for(Pn=0;Pn>>26-Yr}Nn&&(this.words[Pn]=Nn,this.length++)}if(Sn!==0){for(Pn=this.length-1;Pn>=0;Pn--)this.words[Pn+Sn]=this.words[Pn];for(Pn=0;Pn=0);var An;Yr?An=(Yr-Yr%26)/26:An=0;var Pn=Gr%26,Nn=Math.min((Gr-Pn)/26,this.length),zn=67108863^67108863>>>Pn<Nn)for(this.length-=Nn,_n=0;_n=0&&(Zn!==0||_n>=An);_n--){var oo=this.words[_n]|0;this.words[_n]=Zn<<26-Pn|oo>>>Pn,Zn=oo&zn}return On&&Zn!==0&&(On.words[On.length++]=Zn),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},jr.prototype.ishrn=function(Gr,Yr,Sn){return Er(this.negative===0),this.iushrn(Gr,Yr,Sn)},jr.prototype.shln=function(Gr){return this.clone().ishln(Gr)},jr.prototype.ushln=function(Gr){return this.clone().iushln(Gr)},jr.prototype.shrn=function(Gr){return this.clone().ishrn(Gr)},jr.prototype.ushrn=function(Gr){return this.clone().iushrn(Gr)},jr.prototype.testn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<=0);var Yr=Gr%26,Sn=(Gr-Yr)/26;if(Er(this.negative===0,"imaskn works only with positive numbers"),this.length<=Sn)return this;if(Yr!==0&&Sn++,this.length=Math.min(Sn,this.length),Yr!==0){var An=67108863^67108863>>>Yr<=67108864;Yr++)this.words[Yr]-=67108864,Yr===this.length-1?this.words[Yr+1]=1:this.words[Yr+1]++;return this.length=Math.max(this.length,Yr+1),this},jr.prototype.isubn=function(Gr){if(Er(typeof Gr=="number"),Er(Gr<67108864),Gr<0)return this.iaddn(-Gr);if(this.negative!==0)return this.negative=0,this.iaddn(Gr),this.negative=1,this;if(this.words[0]-=Gr,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Yr=0;Yr>26)-(On/67108864|0),this.words[Pn+Sn]=Nn&67108863}for(;Pn>26,this.words[Pn+Sn]=Nn&67108863;if(zn===0)return this._strip();for(Er(zn===-1),zn=0,Pn=0;Pn>26,this.words[Pn]=Nn&67108863;return this.negative=1,this._strip()},jr.prototype._wordDiv=function(Gr,Yr){var Sn=this.length-Gr.length,An=this.clone(),Pn=Gr,Nn=Pn.words[Pn.length-1]|0,zn=this._countBits(Nn);Sn=26-zn,Sn!==0&&(Pn=Pn.ushln(Sn),An.iushln(Sn),Nn=Pn.words[Pn.length-1]|0);var On=An.length-Pn.length,_n;if(Yr!=="mod"){_n=new jr(null),_n.length=On+1,_n.words=new Array(_n.length);for(var Zn=0;Zn<_n.length;Zn++)_n.words[Zn]=0}var oo=An.clone()._ishlnsubmul(Pn,1,On);oo.negative===0&&(An=oo,_n&&(_n.words[On]=1));for(var uo=On-1;uo>=0;uo--){var lo=(An.words[Pn.length+uo]|0)*67108864+(An.words[Pn.length+uo-1]|0);for(lo=Math.min(lo/Nn|0,67108863),An._ishlnsubmul(Pn,lo,uo);An.negative!==0;)lo--,An.negative=0,An._ishlnsubmul(Pn,1,uo),An.isZero()||(An.negative^=1);_n&&(_n.words[uo]=lo)}return _n&&_n._strip(),An._strip(),Yr!=="div"&&Sn!==0&&An.iushrn(Sn),{div:_n||null,mod:An}},jr.prototype.divmod=function(Gr,Yr,Sn){if(Er(!Gr.isZero()),this.isZero())return{div:new jr(0),mod:new jr(0)};var An,Pn,Nn;return this.negative!==0&&Gr.negative===0?(Nn=this.neg().divmod(Gr,Yr),Yr!=="mod"&&(An=Nn.div.neg()),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.iadd(Gr)),{div:An,mod:Pn}):this.negative===0&&Gr.negative!==0?(Nn=this.divmod(Gr.neg(),Yr),Yr!=="mod"&&(An=Nn.div.neg()),{div:An,mod:Nn.mod}):this.negative&Gr.negative?(Nn=this.neg().divmod(Gr.neg(),Yr),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.isub(Gr)),{div:Nn.div,mod:Pn}):Gr.length>this.length||this.cmp(Gr)<0?{div:new jr(0),mod:this}:Gr.length===1?Yr==="div"?{div:this.divn(Gr.words[0]),mod:null}:Yr==="mod"?{div:null,mod:new jr(this.modrn(Gr.words[0]))}:{div:this.divn(Gr.words[0]),mod:new jr(this.modrn(Gr.words[0]))}:this._wordDiv(Gr,Yr)},jr.prototype.div=function(Gr){return this.divmod(Gr,"div",!1).div},jr.prototype.mod=function(Gr){return this.divmod(Gr,"mod",!1).mod},jr.prototype.umod=function(Gr){return this.divmod(Gr,"mod",!0).mod},jr.prototype.divRound=function(Gr){var Yr=this.divmod(Gr);if(Yr.mod.isZero())return Yr.div;var Sn=Yr.div.negative!==0?Yr.mod.isub(Gr):Yr.mod,An=Gr.ushrn(1),Pn=Gr.andln(1),Nn=Sn.cmp(An);return Nn<0||Pn===1&&Nn===0?Yr.div:Yr.div.negative!==0?Yr.div.isubn(1):Yr.div.iaddn(1)},jr.prototype.modrn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=(1<<26)%Gr,An=0,Pn=this.length-1;Pn>=0;Pn--)An=(Sn*An+(this.words[Pn]|0))%Gr;return Yr?-An:An},jr.prototype.modn=function(Gr){return this.modrn(Gr)},jr.prototype.idivn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=0,An=this.length-1;An>=0;An--){var Pn=(this.words[An]|0)+Sn*67108864;this.words[An]=Pn/Gr|0,Sn=Pn%Gr}return this._strip(),Yr?this.ineg():this},jr.prototype.divn=function(Gr){return this.clone().idivn(Gr)},jr.prototype.egcd=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=new jr(0),zn=new jr(1),On=0;Yr.isEven()&&Sn.isEven();)Yr.iushrn(1),Sn.iushrn(1),++On;for(var _n=Sn.clone(),Zn=Yr.clone();!Yr.isZero();){for(var oo=0,uo=1;!(Yr.words[0]&uo)&&oo<26;++oo,uo<<=1);if(oo>0)for(Yr.iushrn(oo);oo-- >0;)(An.isOdd()||Pn.isOdd())&&(An.iadd(_n),Pn.isub(Zn)),An.iushrn(1),Pn.iushrn(1);for(var lo=0,co=1;!(Sn.words[0]&co)&&lo<26;++lo,co<<=1);if(lo>0)for(Sn.iushrn(lo);lo-- >0;)(Nn.isOdd()||zn.isOdd())&&(Nn.iadd(_n),zn.isub(Zn)),Nn.iushrn(1),zn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Nn),Pn.isub(zn)):(Sn.isub(Yr),Nn.isub(An),zn.isub(Pn))}return{a:Nn,b:zn,gcd:Sn.iushln(On)}},jr.prototype._invmp=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=Sn.clone();Yr.cmpn(1)>0&&Sn.cmpn(1)>0;){for(var zn=0,On=1;!(Yr.words[0]&On)&&zn<26;++zn,On<<=1);if(zn>0)for(Yr.iushrn(zn);zn-- >0;)An.isOdd()&&An.iadd(Nn),An.iushrn(1);for(var _n=0,Zn=1;!(Sn.words[0]&Zn)&&_n<26;++_n,Zn<<=1);if(_n>0)for(Sn.iushrn(_n);_n-- >0;)Pn.isOdd()&&Pn.iadd(Nn),Pn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Pn)):(Sn.isub(Yr),Pn.isub(An))}var oo;return Yr.cmpn(1)===0?oo=An:oo=Pn,oo.cmpn(0)<0&&oo.iadd(Gr),oo},jr.prototype.gcd=function(Gr){if(this.isZero())return Gr.abs();if(Gr.isZero())return this.abs();var Yr=this.clone(),Sn=Gr.clone();Yr.negative=0,Sn.negative=0;for(var An=0;Yr.isEven()&&Sn.isEven();An++)Yr.iushrn(1),Sn.iushrn(1);do{for(;Yr.isEven();)Yr.iushrn(1);for(;Sn.isEven();)Sn.iushrn(1);var Pn=Yr.cmp(Sn);if(Pn<0){var Nn=Yr;Yr=Sn,Sn=Nn}else if(Pn===0||Sn.cmpn(1)===0)break;Yr.isub(Sn)}while(!0);return Sn.iushln(An)},jr.prototype.invm=function(Gr){return this.egcd(Gr).a.umod(Gr)},jr.prototype.isEven=function(){return(this.words[0]&1)===0},jr.prototype.isOdd=function(){return(this.words[0]&1)===1},jr.prototype.andln=function(Gr){return this.words[0]&Gr},jr.prototype.bincn=function(Gr){Er(typeof Gr=="number");var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<>>26,zn&=67108863,this.words[Nn]=zn}return Pn!==0&&(this.words[Nn]=Pn,this.length++),this},jr.prototype.isZero=function(){return this.length===1&&this.words[0]===0},jr.prototype.cmpn=function(Gr){var Yr=Gr<0;if(this.negative!==0&&!Yr)return-1;if(this.negative===0&&Yr)return 1;this._strip();var Sn;if(this.length>1)Sn=1;else{Yr&&(Gr=-Gr),Er(Gr<=67108863,"Number is too big");var An=this.words[0]|0;Sn=An===Gr?0:AnGr.length)return 1;if(this.length=0;Sn--){var An=this.words[Sn]|0,Pn=Gr.words[Sn]|0;if(An!==Pn){AnPn&&(Yr=1);break}}return Yr},jr.prototype.gtn=function(Gr){return this.cmpn(Gr)===1},jr.prototype.gt=function(Gr){return this.cmp(Gr)===1},jr.prototype.gten=function(Gr){return this.cmpn(Gr)>=0},jr.prototype.gte=function(Gr){return this.cmp(Gr)>=0},jr.prototype.ltn=function(Gr){return this.cmpn(Gr)===-1},jr.prototype.lt=function(Gr){return this.cmp(Gr)===-1},jr.prototype.lten=function(Gr){return this.cmpn(Gr)<=0},jr.prototype.lte=function(Gr){return this.cmp(Gr)<=0},jr.prototype.eqn=function(Gr){return this.cmpn(Gr)===0},jr.prototype.eq=function(Gr){return this.cmp(Gr)===0},jr.red=function(Gr){return new no(Gr)},jr.prototype.toRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),Er(this.negative===0,"red works only with positives"),Gr.convertTo(this)._forceRed(Gr)},jr.prototype.fromRed=function(){return Er(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},jr.prototype._forceRed=function(Gr){return this.red=Gr,this},jr.prototype.forceRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),this._forceRed(Gr)},jr.prototype.redAdd=function(Gr){return Er(this.red,"redAdd works only with red numbers"),this.red.add(this,Gr)},jr.prototype.redIAdd=function(Gr){return Er(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,Gr)},jr.prototype.redSub=function(Gr){return Er(this.red,"redSub works only with red numbers"),this.red.sub(this,Gr)},jr.prototype.redISub=function(Gr){return Er(this.red,"redISub works only with red numbers"),this.red.isub(this,Gr)},jr.prototype.redShl=function(Gr){return Er(this.red,"redShl works only with red numbers"),this.red.shl(this,Gr)},jr.prototype.redMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.mul(this,Gr)},jr.prototype.redIMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.imul(this,Gr)},jr.prototype.redSqr=function(){return Er(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},jr.prototype.redISqr=function(){return Er(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},jr.prototype.redSqrt=function(){return Er(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},jr.prototype.redInvm=function(){return Er(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},jr.prototype.redNeg=function(){return Er(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},jr.prototype.redPow=function(Gr){return Er(this.red&&!Gr.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,Gr)};var ga={k256:null,p224:null,p192:null,p25519:null};function na(Rn,Gr){this.name=Rn,this.p=new jr(Gr,16),this.n=this.p.bitLength(),this.k=new jr(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}na.prototype._tmp=function(){var Gr=new jr(null);return Gr.words=new Array(Math.ceil(this.n/13)),Gr},na.prototype.ireduce=function(Gr){var Yr=Gr,Sn;do this.split(Yr,this.tmp),Yr=this.imulK(Yr),Yr=Yr.iadd(this.tmp),Sn=Yr.bitLength();while(Sn>this.n);var An=Sn0?Yr.isub(this.p):Yr.strip!==void 0?Yr.strip():Yr._strip(),Yr},na.prototype.split=function(Gr,Yr){Gr.iushrn(this.n,0,Yr)},na.prototype.imulK=function(Gr){return Gr.imul(this.k)};function _i(){na.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}kr(_i,na),_i.prototype.split=function(Gr,Yr){for(var Sn=4194303,An=Math.min(Gr.length,9),Pn=0;Pn>>22,Nn=zn}Nn>>>=22,Gr.words[Pn-10]=Nn,Nn===0&&Gr.length>10?Gr.length-=10:Gr.length-=9},_i.prototype.imulK=function(Gr){Gr.words[Gr.length]=0,Gr.words[Gr.length+1]=0,Gr.length+=2;for(var Yr=0,Sn=0;Sn>>=26,Gr.words[Sn]=Pn,Yr=An}return Yr!==0&&(Gr.words[Gr.length++]=Yr),Gr},jr._prime=function(Gr){if(ga[Gr])return ga[Gr];var Yr;if(Gr==="k256")Yr=new _i;else if(Gr==="p224")Yr=new ro;else if(Gr==="p192")Yr=new to;else if(Gr==="p25519")Yr=new io;else throw new Error("Unknown prime "+Gr);return ga[Gr]=Yr,Yr};function no(Rn){if(typeof Rn=="string"){var Gr=jr._prime(Rn);this.m=Gr.p,this.prime=Gr}else Er(Rn.gtn(1),"modulus must be greater than 1"),this.m=Rn,this.prime=null}no.prototype._verify1=function(Gr){Er(Gr.negative===0,"red works only with positives"),Er(Gr.red,"red works only with red numbers")},no.prototype._verify2=function(Gr,Yr){Er((Gr.negative|Yr.negative)===0,"red works only with positives"),Er(Gr.red&&Gr.red===Yr.red,"red works only with red numbers")},no.prototype.imod=function(Gr){return this.prime?this.prime.ireduce(Gr)._forceRed(this):(Hr(Gr,Gr.umod(this.m)._forceRed(this)),Gr)},no.prototype.neg=function(Gr){return Gr.isZero()?Gr.clone():this.m.sub(Gr)._forceRed(this)},no.prototype.add=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.add(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn._forceRed(this)},no.prototype.iadd=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.iadd(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn},no.prototype.sub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.sub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn._forceRed(this)},no.prototype.isub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.isub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn},no.prototype.shl=function(Gr,Yr){return this._verify1(Gr),this.imod(Gr.ushln(Yr))},no.prototype.imul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.imul(Yr))},no.prototype.mul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.mul(Yr))},no.prototype.isqr=function(Gr){return this.imul(Gr,Gr.clone())},no.prototype.sqr=function(Gr){return this.mul(Gr,Gr)},no.prototype.sqrt=function(Gr){if(Gr.isZero())return Gr.clone();var Yr=this.m.andln(3);if(Er(Yr%2===1),Yr===3){var Sn=this.m.add(new jr(1)).iushrn(2);return this.pow(Gr,Sn)}for(var An=this.m.subn(1),Pn=0;!An.isZero()&&An.andln(1)===0;)Pn++,An.iushrn(1);Er(!An.isZero());var Nn=new jr(1).toRed(this),zn=Nn.redNeg(),On=this.m.subn(1).iushrn(1),_n=this.m.bitLength();for(_n=new jr(2*_n*_n).toRed(this);this.pow(_n,On).cmp(zn)!==0;)_n.redIAdd(zn);for(var Zn=this.pow(_n,An),oo=this.pow(Gr,An.addn(1).iushrn(1)),uo=this.pow(Gr,An),lo=Pn;uo.cmp(Nn)!==0;){for(var co=uo,so=0;co.cmp(Nn)!==0;so++)co=co.redSqr();Er(so=0;Pn--){for(var Zn=Yr.words[Pn],oo=_n-1;oo>=0;oo--){var uo=Zn>>oo&1;if(Nn!==An[0]&&(Nn=this.sqr(Nn)),uo===0&&zn===0){On=0;continue}zn<<=1,zn|=uo,On++,!(On!==Sn&&(Pn!==0||oo!==0))&&(Nn=this.mul(Nn,An[zn]),On=0,zn=0)}_n=26}return Nn},no.prototype.convertTo=function(Gr){var Yr=Gr.umod(this.m);return Yr===Gr?Yr.clone():Yr},no.prototype.convertFrom=function(Gr){var Yr=Gr.clone();return Yr.red=null,Yr},jr.mont=function(Gr){return new $a(Gr)};function $a(Rn){no.call(this,Rn),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new jr(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}kr($a,no),$a.prototype.convertTo=function(Gr){return this.imod(Gr.ushln(this.shift))},$a.prototype.convertFrom=function(Gr){var Yr=this.imod(Gr.mul(this.rinv));return Yr.red=null,Yr},$a.prototype.imul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return Gr.words[0]=0,Gr.length=1,Gr;var Sn=Gr.imul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.mul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return new jr(0)._forceRed(this);var Sn=Gr.mul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.invm=function(Gr){var Yr=this.imod(Gr._invmp(this.m).mul(this.r2));return Yr._forceRed(this)}})(fr,commonjsGlobal)})(bn$2);var bnExports$2=bn$2.exports,_Buffer$2=safeBufferExports.Buffer;function base$2(fr){if(fr.length>=255)throw new TypeError("Alphabet too long");for(var br=new Uint8Array(256),wr=0;wr>>0,jn=new Uint8Array(In);$n!==Tn;){for(var Yn=Xr[$n],ga=0,na=In-1;(Yn!==0||ga>>0,jn[na]=Yn%Br>>>0,Yn=Yn/Br>>>0;if(Yn!==0)throw new Error("Non-zero carry");wn=ga,$n++}for(var _i=In-wn;_i!==In&&jn[_i]===0;)_i++;for(var ro=qr.repeat(En);_i>>0,In=new Uint8Array(Tn);En>>0,In[ga]=jn%256>>>0,jn=jn/256>>>0;if(jn!==0)throw new Error("Non-zero carry");$n=Yn,En++}for(var na=Tn-$n;na!==Tn&&In[na]===0;)na++;var _i=_Buffer$2.allocUnsafe(wn+(Tn-na));_i.fill(0,0,wn);for(var ro=wn;na!==Tn;)_i[ro++]=In[na++];return _i}function Jr(Xr){var En=Zr(Xr);if(En)return En;throw new Error("Non-base"+Br+" character")}return{encode:Hr,decodeUnsafe:Zr,decode:Jr}}var src$2=base$2,basex$2=src$2,ALPHABET$2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",bs58$4=basex$2(ALPHABET$2);function inRange(fr,br,wr){return br<=fr&&fr<=wr}function ToDictionary(fr){if(fr===void 0)return{};if(fr===Object(fr))return fr;throw TypeError("Could not convert argument to dictionary")}function stringToCodePoints(fr){for(var br=String(fr),wr=br.length,Er=0,kr=[];Er57343)kr.push(jr);else if(56320<=jr&&jr<=57343)kr.push(65533);else if(55296<=jr&&jr<=56319)if(Er===wr-1)kr.push(65533);else{var Br=fr.charCodeAt(Er+1);if(56320<=Br&&Br<=57343){var qr=jr&1023,Wr=Br&1023;kr.push(65536+(qr<<10)+Wr),Er+=1}else kr.push(65533)}Er+=1}return kr}function codePointsToString(fr){for(var br="",wr=0;wr>10)+55296,(Er&1023)+56320))}return br}var end_of_stream=-1;function Stream(fr){this.tokens=[].slice.call(fr)}Stream.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():end_of_stream},prepend:function(fr){if(Array.isArray(fr))for(var br=fr;br.length;)this.tokens.unshift(br.pop());else this.tokens.unshift(fr)},push:function(fr){if(Array.isArray(fr))for(var br=fr;br.length;)this.tokens.push(br.shift());else this.tokens.push(fr)}};var finished=-1;function decoderError(fr,br){if(fr)throw TypeError("Decoder error");return br||65533}var DEFAULT_ENCODING="utf-8";function TextDecoder$1(fr,br){if(!(this instanceof TextDecoder$1))return new TextDecoder$1(fr,br);if(fr=fr!==void 0?String(fr).toLowerCase():DEFAULT_ENCODING,fr!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");br=ToDictionary(br),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=!!br.fatal,this._ignoreBOM=!!br.ignoreBOM,Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}TextDecoder$1.prototype={decode:function fr(br,wr){var Er;typeof br=="object"&&br instanceof ArrayBuffer?Er=new Uint8Array(br):typeof br=="object"&&"buffer"in br&&br.buffer instanceof ArrayBuffer?Er=new Uint8Array(br.buffer,br.byteOffset,br.byteLength):Er=new Uint8Array(0),wr=ToDictionary(wr),this._streaming||(this._decoder=new UTF8Decoder({fatal:this._fatal}),this._BOMseen=!1),this._streaming=!!wr.stream;for(var kr=new Stream(Er),jr=[],Br;!kr.endOfStream()&&(Br=this._decoder.handler(kr,kr.read()),Br!==finished);)Br!==null&&(Array.isArray(Br)?jr.push.apply(jr,Br):jr.push(Br));if(!this._streaming){do{if(Br=this._decoder.handler(kr,kr.read()),Br===finished)break;Br!==null&&(Array.isArray(Br)?jr.push.apply(jr,Br):jr.push(Br))}while(!kr.endOfStream());this._decoder=null}return jr.length&&["utf-8"].indexOf(this.encoding)!==-1&&!this._ignoreBOM&&!this._BOMseen&&(jr[0]===65279?(this._BOMseen=!0,jr.shift()):this._BOMseen=!0),codePointsToString(jr)}};function TextEncoder$1(fr,br){if(!(this instanceof TextEncoder$1))return new TextEncoder$1(fr,br);if(fr=fr!==void 0?String(fr).toLowerCase():DEFAULT_ENCODING,fr!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");br=ToDictionary(br),this._streaming=!1,this._encoder=null,this._options={fatal:!!br.fatal},Object.defineProperty(this,"encoding",{value:"utf-8"})}TextEncoder$1.prototype={encode:function fr(br,wr){br=br?String(br):"",wr=ToDictionary(wr),this._streaming||(this._encoder=new UTF8Encoder(this._options)),this._streaming=!!wr.stream;for(var Er=[],kr=new Stream(stringToCodePoints(br)),jr;!kr.endOfStream()&&(jr=this._encoder.handler(kr,kr.read()),jr!==finished);)Array.isArray(jr)?Er.push.apply(Er,jr):Er.push(jr);if(!this._streaming){for(;jr=this._encoder.handler(kr,kr.read()),jr!==finished;)Array.isArray(jr)?Er.push.apply(Er,jr):Er.push(jr);this._encoder=null}return new Uint8Array(Er)}};function UTF8Decoder(fr){var br=fr.fatal,wr=0,Er=0,kr=0,jr=128,Br=191;this.handler=function(qr,Wr){if(Wr===end_of_stream&&kr!==0)return kr=0,decoderError(br);if(Wr===end_of_stream)return finished;if(kr===0){if(inRange(Wr,0,127))return Wr;if(inRange(Wr,194,223))kr=1,wr=Wr-192;else if(inRange(Wr,224,239))Wr===224&&(jr=160),Wr===237&&(Br=159),kr=2,wr=Wr-224;else if(inRange(Wr,240,244))Wr===240&&(jr=144),Wr===244&&(Br=143),kr=3,wr=Wr-240;else return decoderError(br);return wr=wr<<6*kr,null}if(!inRange(Wr,jr,Br))return wr=kr=Er=0,jr=128,Br=191,qr.prepend(Wr),decoderError(br);if(jr=128,Br=191,Er+=1,wr+=Wr-128<<6*(kr-Er),Er!==kr)return null;var Vr=wr;return wr=kr=Er=0,Vr}}function UTF8Encoder(fr){fr.fatal,this.handler=function(br,wr){if(wr===end_of_stream)return finished;if(inRange(wr,0,127))return wr;var Er,kr;inRange(wr,128,2047)?(Er=1,kr=192):inRange(wr,2048,65535)?(Er=2,kr=224):inRange(wr,65536,1114111)&&(Er=3,kr=240);for(var jr=[(wr>>6*Er)+kr];Er>0;){var Br=wr>>6*(Er-1);jr.push(128|Br&63),Er-=1}return jr}}const encoding$1=Object.freeze(Object.defineProperty({__proto__:null,TextDecoder:TextDecoder$1,TextEncoder:TextEncoder$1},Symbol.toStringTag,{value:"Module"})),require$$2=getAugmentedNamespace(encoding$1);var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(fr,br,wr,Er){Er===void 0&&(Er=wr),Object.defineProperty(fr,Er,{enumerable:!0,get:function(){return br[wr]}})}:function(fr,br,wr,Er){Er===void 0&&(Er=wr),fr[Er]=br[wr]}),__setModuleDefault=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(fr,br){Object.defineProperty(fr,"default",{enumerable:!0,value:br})}:function(fr,br){fr.default=br}),__decorate=commonjsGlobal&&commonjsGlobal.__decorate||function(fr,br,wr,Er){var kr=arguments.length,jr=kr<3?br:Er===null?Er=Object.getOwnPropertyDescriptor(br,wr):Er,Br;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")jr=Reflect.decorate(fr,br,wr,Er);else for(var qr=fr.length-1;qr>=0;qr--)(Br=fr[qr])&&(jr=(kr<3?Br(jr):kr>3?Br(br,wr,jr):Br(br,wr))||jr);return kr>3&&jr&&Object.defineProperty(br,wr,jr),jr},__importStar=commonjsGlobal&&commonjsGlobal.__importStar||function(fr){if(fr&&fr.__esModule)return fr;var br={};if(fr!=null)for(var wr in fr)wr!=="default"&&Object.hasOwnProperty.call(fr,wr)&&__createBinding(br,fr,wr);return __setModuleDefault(br,fr),br},__importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(lib,"__esModule",{value:!0});var deserializeUnchecked_1=lib.deserializeUnchecked=deserialize_1=lib.deserialize=serialize_1=lib.serialize=lib.BinaryReader=lib.BinaryWriter=lib.BorshError=lib.baseDecode=lib.baseEncode=void 0;const bn_js_1=__importDefault(bnExports$2),bs58_1=__importDefault(bs58$4),encoding=__importStar(require$$2),ResolvedTextDecoder=typeof TextDecoder!="function"?encoding.TextDecoder:TextDecoder,textDecoder=new ResolvedTextDecoder("utf-8",{fatal:!0});function baseEncode(fr){return typeof fr=="string"&&(fr=Buffer$2.from(fr,"utf8")),bs58_1.default.encode(Buffer$2.from(fr))}lib.baseEncode=baseEncode;function baseDecode(fr){return Buffer$2.from(bs58_1.default.decode(fr))}lib.baseDecode=baseDecode;const INITIAL_LENGTH=1024;class BorshError extends Error{constructor(br){super(br),this.fieldPath=[],this.originalMessage=br}addToFieldPath(br){this.fieldPath.splice(0,0,br),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}lib.BorshError=BorshError;class BinaryWriter{constructor(){this.buf=Buffer$2.alloc(INITIAL_LENGTH),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer$2.concat([this.buf,Buffer$2.alloc(INITIAL_LENGTH)]))}writeU8(br){this.maybeResize(),this.buf.writeUInt8(br,this.length),this.length+=1}writeU16(br){this.maybeResize(),this.buf.writeUInt16LE(br,this.length),this.length+=2}writeU32(br){this.maybeResize(),this.buf.writeUInt32LE(br,this.length),this.length+=4}writeU64(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",8)))}writeU128(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",16)))}writeU256(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",32)))}writeU512(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",64)))}writeBuffer(br){this.buf=Buffer$2.concat([Buffer$2.from(this.buf.subarray(0,this.length)),br,Buffer$2.alloc(INITIAL_LENGTH)]),this.length+=br.length}writeString(br){this.maybeResize();const wr=Buffer$2.from(br,"utf8");this.writeU32(wr.length),this.writeBuffer(wr)}writeFixedArray(br){this.writeBuffer(Buffer$2.from(br))}writeArray(br,wr){this.maybeResize(),this.writeU32(br.length);for(const Er of br)this.maybeResize(),wr(Er)}toArray(){return this.buf.subarray(0,this.length)}}lib.BinaryWriter=BinaryWriter;function handlingRangeError(fr,br,wr){const Er=wr.value;wr.value=function(...kr){try{return Er.apply(this,kr)}catch(jr){if(jr instanceof RangeError){const Br=jr.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(Br)>=0)throw new BorshError("Reached the end of buffer when deserializing")}throw jr}}}class BinaryReader{constructor(br){this.buf=br,this.offset=0}readU8(){const br=this.buf.readUInt8(this.offset);return this.offset+=1,br}readU16(){const br=this.buf.readUInt16LE(this.offset);return this.offset+=2,br}readU32(){const br=this.buf.readUInt32LE(this.offset);return this.offset+=4,br}readU64(){const br=this.readBuffer(8);return new bn_js_1.default(br,"le")}readU128(){const br=this.readBuffer(16);return new bn_js_1.default(br,"le")}readU256(){const br=this.readBuffer(32);return new bn_js_1.default(br,"le")}readU512(){const br=this.readBuffer(64);return new bn_js_1.default(br,"le")}readBuffer(br){if(this.offset+br>this.buf.length)throw new BorshError(`Expected buffer length ${br} isn't within bounds`);const wr=this.buf.slice(this.offset,this.offset+br);return this.offset+=br,wr}readString(){const br=this.readU32(),wr=this.readBuffer(br);try{return textDecoder.decode(wr)}catch(Er){throw new BorshError(`Error decoding UTF-8 string: ${Er}`)}}readFixedArray(br){return new Uint8Array(this.readBuffer(br))}readArray(br){const wr=this.readU32(),Er=Array();for(let kr=0;kr{serializeField(fr,br,jr,Er[0],kr)});else if(Er.kind!==void 0)switch(Er.kind){case"option":{wr==null?kr.writeU8(0):(kr.writeU8(1),serializeField(fr,br,wr,Er.type,kr));break}case"map":{kr.writeU32(wr.size),wr.forEach((jr,Br)=>{serializeField(fr,br,Br,Er.key,kr),serializeField(fr,br,jr,Er.value,kr)});break}default:throw new BorshError(`FieldType ${Er} unrecognized`)}else serializeStruct(fr,wr,kr)}catch(jr){throw jr instanceof BorshError&&jr.addToFieldPath(br),jr}}function serializeStruct(fr,br,wr){if(typeof br.borshSerialize=="function"){br.borshSerialize(wr);return}const Er=fr.get(br.constructor);if(!Er)throw new BorshError(`Class ${br.constructor.name} is missing in schema`);if(Er.kind==="struct")Er.fields.map(([kr,jr])=>{serializeField(fr,kr,br[kr],jr,wr)});else if(Er.kind==="enum"){const kr=br[Er.field];for(let jr=0;jrdeserializeField(fr,br,wr[0],Er))}if(wr.kind==="option")return Er.readU8()?deserializeField(fr,br,wr.type,Er):void 0;if(wr.kind==="map"){let kr=new Map;const jr=Er.readU32();for(let Br=0;Br=Er.values.length)throw new BorshError(`Enum index: ${kr} is out of range`);const[jr,Br]=Er.values[kr],qr=deserializeField(fr,jr,Br,wr);return new br({[jr]:qr})}throw new BorshError(`Unexpected schema kind: ${Er.kind} for ${br.constructor.name}`)}function deserialize(fr,br,wr,Er=BinaryReader){const kr=new Er(wr),jr=deserializeStruct(fr,br,kr);if(kr.offsetthis.span)throw new RangeError("indeterminate span");return this.span}replicate(br){const wr=Object.create(this.constructor.prototype);return Object.assign(wr,this),wr.property=br,wr}fromArray(br){}}Layout$1.Layout=Layout;function nameWithProperty(fr,br){return br.property?fr+"["+br.property+"]":fr}Layout$1.nameWithProperty=nameWithProperty;function bindConstructorLayout(fr,br){if(typeof fr!="function")throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(fr,"layout_"))throw new Error("Class is already bound to a layout");if(!(br&&br instanceof Layout))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(br,"boundConstructor_"))throw new Error("layout is already bound to a constructor");fr.layout_=br,br.boundConstructor_=fr,br.makeDestinationObject=()=>new fr,Object.defineProperty(fr.prototype,"encode",{value(wr,Er){return br.encode(this,wr,Er)},writable:!0}),Object.defineProperty(fr,"decode",{value(wr,Er){return br.decode(wr,Er)},writable:!0})}Layout$1.bindConstructorLayout=bindConstructorLayout;class ExternalLayout extends Layout{isCount(){throw new Error("ExternalLayout is abstract")}}Layout$1.ExternalLayout=ExternalLayout;class GreedyCount extends ExternalLayout{constructor(br=1,wr){if(!Number.isInteger(br)||0>=br)throw new TypeError("elementSpan must be a (positive) integer");super(-1,wr),this.elementSpan=br}isCount(){return!0}decode(br,wr=0){checkUint8Array(br);const Er=br.length-wr;return Math.floor(Er/this.elementSpan)}encode(br,wr,Er){return 0}}Layout$1.GreedyCount=GreedyCount;class OffsetLayout extends ExternalLayout{constructor(br,wr=0,Er){if(!(br instanceof Layout))throw new TypeError("layout must be a Layout");if(!Number.isInteger(wr))throw new TypeError("offset must be integer or undefined");super(br.span,Er||br.property),this.layout=br,this.offset=wr}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(br,wr=0){return this.layout.decode(br,wr+this.offset)}encode(br,wr,Er=0){return this.layout.encode(br,wr,Er+this.offset)}}Layout$1.OffsetLayout=OffsetLayout;class UInt extends Layout{constructor(br,wr){if(super(br,wr),6Br+kr.encode(qr,wr,Er+Br),0);return this.count instanceof ExternalLayout&&this.count.encode(br.length,wr,Er),jr}}Layout$1.Sequence=Sequence;class Structure extends Layout{constructor(br,wr,Er){if(!(Array.isArray(br)&&br.reduce((jr,Br)=>jr&&Br instanceof Layout,!0)))throw new TypeError("fields must be array of Layout instances");typeof wr=="boolean"&&Er===void 0&&(Er=wr,wr=void 0);for(const jr of br)if(0>jr.span&&jr.property===void 0)throw new Error("fields cannot contain unnamed variable-length layout");let kr=-1;try{kr=br.reduce((jr,Br)=>jr+Br.getSpan(),0)}catch{}super(kr,wr),this.fields=br,this.decodePrefixes=!!Er}getSpan(br,wr=0){if(0<=this.span)return this.span;let Er=0;try{Er=this.fields.reduce((kr,jr)=>{const Br=jr.getSpan(br,wr);return wr+=Br,kr+Br},0)}catch{throw new RangeError("indeterminate span")}return Er}decode(br,wr=0){checkUint8Array(br);const Er=this.makeDestinationObject();for(const kr of this.fields)if(kr.property!==void 0&&(Er[kr.property]=kr.decode(br,wr)),wr+=kr.getSpan(br,wr),this.decodePrefixes&&br.length===wr)break;return Er}encode(br,wr,Er=0){const kr=Er;let jr=0,Br=0;for(const qr of this.fields){let Wr=qr.span;if(Br=0Wr&&(Wr=qr.getSpan(wr,Er)))}jr=Er,Er+=Wr}return jr+Br-kr}fromArray(br){const wr=this.makeDestinationObject();for(const Er of this.fields)Er.property!==void 0&&0Er.span?wr=-1:0<=wr&&(wr+=Er.span)}}}Layout$1.Structure=Structure;class UnionDiscriminator{constructor(br){this.property=br}decode(br,wr){throw new Error("UnionDiscriminator is abstract")}encode(br,wr,Er){throw new Error("UnionDiscriminator is abstract")}}Layout$1.UnionDiscriminator=UnionDiscriminator;class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(br,wr){if(!(br instanceof ExternalLayout&&br.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(wr||br.property||"variant"),this.layout=br}decode(br,wr){return this.layout.decode(br,wr)}encode(br,wr,Er){return this.layout.encode(br,wr,Er)}}Layout$1.UnionLayoutDiscriminator=UnionLayoutDiscriminator;class Union extends Layout{constructor(br,wr,Er){let kr;if(br instanceof UInt||br instanceof UIntBE)kr=new UnionLayoutDiscriminator(new OffsetLayout(br));else if(br instanceof ExternalLayout&&br.isCount())kr=new UnionLayoutDiscriminator(br);else if(br instanceof UnionDiscriminator)kr=br;else throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");if(wr===void 0&&(wr=null),!(wr===null||wr instanceof Layout))throw new TypeError("defaultLayout must be null or a Layout");if(wr!==null){if(0>wr.span)throw new Error("defaultLayout must have constant span");wr.property===void 0&&(wr=wr.replicate("content"))}let jr=-1;wr&&(jr=wr.span,0<=jr&&(br instanceof UInt||br instanceof UIntBE)&&(jr+=kr.layout.span)),super(jr,Er),this.discriminator=kr,this.usesPrefixDiscriminator=br instanceof UInt||br instanceof UIntBE,this.defaultLayout=wr,this.registry={};let Br=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(qr){return Br(qr)},this.configGetSourceVariant=function(qr){Br=qr.bind(this)}}getSpan(br,wr=0){if(0<=this.span)return this.span;const Er=this.getVariant(br,wr);if(!Er)throw new Error("unable to determine span for unrecognized variant");return Er.getSpan(br,wr)}defaultGetSourceVariant(br){if(Object.prototype.hasOwnProperty.call(br,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(br,this.defaultLayout.property))return;const wr=this.registry[br[this.discriminator.property]];if(wr&&(!wr.layout||wr.property&&Object.prototype.hasOwnProperty.call(br,wr.property)))return wr}else for(const wr in this.registry){const Er=this.registry[wr];if(Er.property&&Object.prototype.hasOwnProperty.call(br,Er.property))return Er}throw new Error("unable to infer src variant")}decode(br,wr=0){let Er;const kr=this.discriminator,jr=kr.decode(br,wr),Br=this.registry[jr];if(Br===void 0){const qr=this.defaultLayout;let Wr=0;this.usesPrefixDiscriminator&&(Wr=kr.layout.span),Er=this.makeDestinationObject(),Er[kr.property]=jr,Er[qr.property]=qr.decode(br,wr+Wr)}else Er=Br.decode(br,wr);return Er}encode(br,wr,Er=0){const kr=this.getSourceVariant(br);if(kr===void 0){const jr=this.discriminator,Br=this.defaultLayout;let qr=0;return this.usesPrefixDiscriminator&&(qr=jr.layout.span),jr.encode(br[jr.property],wr,Er),qr+Br.encode(br[Br.property],wr,Er+qr)}return kr.encode(br,wr,Er)}addVariant(br,wr,Er){const kr=new VariantLayout(this,br,wr,Er);return this.registry[br]=kr,kr}getVariant(br,wr=0){let Er;return br instanceof Uint8Array?Er=this.discriminator.decode(br,wr):Er=br,this.registry[Er]}}Layout$1.Union=Union;class VariantLayout extends Layout{constructor(br,wr,Er,kr){if(!(br instanceof Union))throw new TypeError("union must be a Union");if(!Number.isInteger(wr)||0>wr)throw new TypeError("variant must be a (non-negative) integer");if(typeof Er=="string"&&kr===void 0&&(kr=Er,Er=null),Er){if(!(Er instanceof Layout))throw new TypeError("layout must be a Layout");if(br.defaultLayout!==null&&0<=Er.span&&Er.span>br.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if(typeof kr!="string")throw new TypeError("variant must have a String property")}let jr=br.span;0>br.span&&(jr=Er?Er.span:0,0<=jr&&br.usesPrefixDiscriminator&&(jr+=br.discriminator.layout.span)),super(jr,kr),this.union=br,this.variant=wr,this.layout=Er||null}getSpan(br,wr=0){if(0<=this.span)return this.span;let Er=0;this.union.usesPrefixDiscriminator&&(Er=this.union.discriminator.layout.span);let kr=0;return this.layout&&(kr=this.layout.getSpan(br,wr+Er)),Er+kr}decode(br,wr=0){const Er=this.makeDestinationObject();if(this!==this.union.getVariant(br,wr))throw new Error("variant mismatch");let kr=0;return this.union.usesPrefixDiscriminator&&(kr=this.union.discriminator.layout.span),this.layout?Er[this.property]=this.layout.decode(br,wr+kr):this.property?Er[this.property]=!0:this.union.usesPrefixDiscriminator&&(Er[this.union.discriminator.property]=this.variant),Er}encode(br,wr,Er=0){let kr=0;if(this.union.usesPrefixDiscriminator&&(kr=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(br,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,wr,Er);let jr=kr;if(this.layout&&(this.layout.encode(br[this.property],wr,Er+kr),jr+=this.layout.getSpan(wr,Er+kr),0<=this.union.span&&jr>this.union.span))throw new Error("encoded variant overruns containing union");return jr}fromArray(br){if(this.layout)return this.layout.fromArray(br)}}Layout$1.VariantLayout=VariantLayout;function fixBitwiseResult(fr){return 0>fr&&(fr+=4294967296),fr}class BitStructure extends Layout{constructor(br,wr,Er){if(!(br instanceof UInt||br instanceof UIntBE))throw new TypeError("word must be a UInt or UIntBE layout");if(typeof wr=="string"&&Er===void 0&&(Er=wr,wr=!1),4=wr)throw new TypeError("bits must be positive integer");const kr=8*br.span,jr=br.fields.reduce((Br,qr)=>Br+qr.bits,0);if(wr+jr>kr)throw new Error("bits too long for span remainder ("+(kr-jr)+" of "+kr+" remain)");this.container=br,this.bits=wr,this.valueMask=(1<>>this.start}encode(br){if(typeof br!="number"||!Number.isInteger(br)||br!==fixBitwiseResult(br&this.valueMask))throw new TypeError(nameWithProperty("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const wr=this.container._packedGetValue(),Er=fixBitwiseResult(br<Er&&(Er=this.length.decode(br,wr)),Er}decode(br,wr=0){let Er=this.span;return 0>Er&&(Er=this.length.decode(br,wr)),uint8ArrayToBuffer(br).slice(wr,wr+Er)}encode(br,wr,Er){let kr=this.length;if(this.length instanceof ExternalLayout&&(kr=br.length),!(br instanceof Uint8Array&&kr===br.length))throw new TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+kr+") Uint8Array as src");if(Er+kr>wr.length)throw new RangeError("encoding overruns Uint8Array");const jr=uint8ArrayToBuffer(br);return uint8ArrayToBuffer(wr).write(jr.toString("hex"),Er,kr,"hex"),this.length instanceof ExternalLayout&&this.length.encode(kr,wr,Er),kr}};Layout$1.Blob=Blob$1;class CString extends Layout{constructor(br){super(-1,br)}getSpan(br,wr=0){checkUint8Array(br);let Er=wr;for(;Erwr.length)throw new RangeError("encoding overruns Buffer");const Br=uint8ArrayToBuffer(wr);return kr.copy(Br,Er),Br[Er+jr]=0,jr+1}}Layout$1.CString=CString;class UTF8 extends Layout{constructor(br,wr){if(typeof br=="string"&&wr===void 0&&(wr=br,br=void 0),br===void 0)br=-1;else if(!Number.isInteger(br))throw new TypeError("maxSpan must be an integer");super(-1,wr),this.maxSpan=br}getSpan(br,wr=0){return checkUint8Array(br),br.length-wr}decode(br,wr=0){const Er=this.getSpan(br,wr);if(0<=this.maxSpan&&this.maxSpanwr.length)throw new RangeError("encoding overruns Buffer");return kr.copy(uint8ArrayToBuffer(wr),Er),jr}}Layout$1.UTF8=UTF8;class Constant extends Layout{constructor(br,wr){super(0,wr),this.value=br}decode(br,wr){return this.value}encode(br,wr,Er){return 0}}Layout$1.Constant=Constant;Layout$1.greedy=(fr,br)=>new GreedyCount(fr,br);var offset=Layout$1.offset=(fr,br,wr)=>new OffsetLayout(fr,br,wr),u8=Layout$1.u8=fr=>new UInt(1,fr),u16=Layout$1.u16=fr=>new UInt(2,fr);Layout$1.u24=fr=>new UInt(3,fr);var u32=Layout$1.u32=fr=>new UInt(4,fr);Layout$1.u40=fr=>new UInt(5,fr);Layout$1.u48=fr=>new UInt(6,fr);var nu64=Layout$1.nu64=fr=>new NearUInt64(fr);Layout$1.u16be=fr=>new UIntBE(2,fr);Layout$1.u24be=fr=>new UIntBE(3,fr);Layout$1.u32be=fr=>new UIntBE(4,fr);Layout$1.u40be=fr=>new UIntBE(5,fr);Layout$1.u48be=fr=>new UIntBE(6,fr);Layout$1.nu64be=fr=>new NearUInt64BE(fr);Layout$1.s8=fr=>new Int(1,fr);Layout$1.s16=fr=>new Int(2,fr);Layout$1.s24=fr=>new Int(3,fr);Layout$1.s32=fr=>new Int(4,fr);Layout$1.s40=fr=>new Int(5,fr);Layout$1.s48=fr=>new Int(6,fr);var ns64=Layout$1.ns64=fr=>new NearInt64(fr);Layout$1.s16be=fr=>new IntBE(2,fr);Layout$1.s24be=fr=>new IntBE(3,fr);Layout$1.s32be=fr=>new IntBE(4,fr);Layout$1.s40be=fr=>new IntBE(5,fr);Layout$1.s48be=fr=>new IntBE(6,fr);Layout$1.ns64be=fr=>new NearInt64BE(fr);Layout$1.f32=fr=>new Float(fr);Layout$1.f32be=fr=>new FloatBE(fr);Layout$1.f64=fr=>new Double(fr);Layout$1.f64be=fr=>new DoubleBE(fr);var struct=Layout$1.struct=(fr,br,wr)=>new Structure(fr,br,wr);Layout$1.bits=(fr,br,wr)=>new BitStructure(fr,br,wr);var seq=Layout$1.seq=(fr,br,wr)=>new Sequence(fr,br,wr);Layout$1.union=(fr,br,wr)=>new Union(fr,br,wr);Layout$1.unionLayoutDiscriminator=(fr,br)=>new UnionLayoutDiscriminator(fr,br);var blob=Layout$1.blob=(fr,br)=>new Blob$1(fr,br);Layout$1.cstr=fr=>new CString(fr);Layout$1.utf8=(fr,br)=>new UTF8(fr,br);Layout$1.constant=(fr,br)=>new Constant(fr,br);var browser$1={};Object.defineProperty(browser$1,"__esModule",{value:!0});function toBigIntLE(fr){{const br=Buffer$2.from(fr);br.reverse();const wr=br.toString("hex");return wr.length===0?BigInt(0):BigInt(`0x${wr}`)}}var toBigIntLE_1=browser$1.toBigIntLE=toBigIntLE;function toBigIntBE(fr){{const br=fr.toString("hex");return br.length===0?BigInt(0):BigInt(`0x${br}`)}}browser$1.toBigIntBE=toBigIntBE;function toBufferLE(fr,br){{const wr=fr.toString(16),Er=Buffer$2.from(wr.padStart(br*2,"0").slice(0,br*2),"hex");return Er.reverse(),Er}}var toBufferLE_1=browser$1.toBufferLE=toBufferLE;function toBufferBE(fr,br){{const wr=fr.toString(16);return Buffer$2.from(wr.padStart(br*2,"0").slice(0,br*2),"hex")}}browser$1.toBufferBE=toBufferBE;let StructError$2=class extends TypeError{constructor(br,wr){let Er;const{message:kr,explanation:jr,...Br}=br,{path:qr}=br,Wr=qr.length===0?kr:`At path: ${qr.join(".")} -- ${kr}`;super(jr??Wr),jr!=null&&(this.cause=Wr),Object.assign(this,Br),this.name=this.constructor.name,this.failures=()=>Er??(Er=[br,...wr()])}};function isIterable$2(fr){return isObject$2(fr)&&typeof fr[Symbol.iterator]=="function"}function isObject$2(fr){return typeof fr=="object"&&fr!=null}function print$2(fr){return typeof fr=="symbol"?fr.toString():typeof fr=="string"?JSON.stringify(fr):`${fr}`}function shiftIterator$2(fr){const{done:br,value:wr}=fr.next();return br?void 0:wr}function toFailure$2(fr,br,wr,Er){if(fr===!0)return;fr===!1?fr={}:typeof fr=="string"&&(fr={message:fr});const{path:kr,branch:jr}=br,{type:Br}=wr,{refinement:qr,message:Wr=`Expected a value of type \`${Br}\`${qr?` with refinement \`${qr}\``:""}, but received: \`${print$2(Er)}\``}=fr;return{value:Er,type:Br,refinement:qr,key:kr[kr.length-1],path:kr,branch:jr,...fr,message:Wr}}function*toFailures$2(fr,br,wr,Er){isIterable$2(fr)||(fr=[fr]);for(const kr of fr){const jr=toFailure$2(kr,br,wr,Er);jr&&(yield jr)}}function*run$2(fr,br,wr={}){const{path:Er=[],branch:kr=[fr],coerce:jr=!1,mask:Br=!1}=wr,qr={path:Er,branch:kr};if(jr&&(fr=br.coercer(fr,qr),Br&&br.type!=="type"&&isObject$2(br.schema)&&isObject$2(fr)&&!Array.isArray(fr)))for(const Vr in fr)br.schema[Vr]===void 0&&delete fr[Vr];let Wr="valid";for(const Vr of br.validator(fr,qr))Vr.explanation=wr.message,Wr="not_valid",yield[Vr,void 0];for(let[Vr,Hr,Zr]of br.entries(fr,qr)){const Jr=run$2(Hr,Zr,{path:Vr===void 0?Er:[...Er,Vr],branch:Vr===void 0?kr:[...kr,Hr],coerce:jr,mask:Br,message:wr.message});for(const Xr of Jr)Xr[0]?(Wr=Xr[0].refinement!=null?"not_refined":"not_valid",yield[Xr[0],void 0]):jr&&(Hr=Xr[1],Vr===void 0?fr=Hr:fr instanceof Map?fr.set(Vr,Hr):fr instanceof Set?fr.add(Hr):isObject$2(fr)&&(Hr!==void 0||Vr in fr)&&(fr[Vr]=Hr))}if(Wr!=="not_valid")for(const Vr of br.refiner(fr,qr))Vr.explanation=wr.message,Wr="not_refined",yield[Vr,void 0];Wr==="valid"&&(yield[void 0,fr])}let Struct$5=class{constructor(br){const{type:wr,schema:Er,validator:kr,refiner:jr,coercer:Br=Wr=>Wr,entries:qr=function*(){}}=br;this.type=wr,this.schema=Er,this.entries=qr,this.coercer=Br,kr?this.validator=(Wr,Vr)=>{const Hr=kr(Wr,Vr);return toFailures$2(Hr,Vr,this,Wr)}:this.validator=()=>[],jr?this.refiner=(Wr,Vr)=>{const Hr=jr(Wr,Vr);return toFailures$2(Hr,Vr,this,Wr)}:this.refiner=()=>[]}assert(br,wr){return assert$3(br,this,wr)}create(br,wr){return create$2(br,this,wr)}is(br){return is$2(br,this)}mask(br,wr){return mask$2(br,this,wr)}validate(br,wr={}){return validate$3(br,this,wr)}};function assert$3(fr,br,wr){const Er=validate$3(fr,br,{message:wr});if(Er[0])throw Er[0]}function create$2(fr,br,wr){const Er=validate$3(fr,br,{coerce:!0,message:wr});if(Er[0])throw Er[0];return Er[1]}function mask$2(fr,br,wr){const Er=validate$3(fr,br,{coerce:!0,mask:!0,message:wr});if(Er[0])throw Er[0];return Er[1]}function is$2(fr,br){return!validate$3(fr,br)[0]}function validate$3(fr,br,wr={}){const Er=run$2(fr,br,wr),kr=shiftIterator$2(Er);return kr[0]?[new StructError$2(kr[0],function*(){for(const Br of Er)Br[0]&&(yield Br[0])}),void 0]:[void 0,kr[1]]}function define$2(fr,br){return new Struct$5({type:fr,schema:null,validator:br})}function any$2(){return define$2("any",()=>!0)}function array$2(fr){return new Struct$5({type:"array",schema:fr,*entries(br){if(fr&&Array.isArray(br))for(const[wr,Er]of br.entries())yield[wr,Er,fr]},coercer(br){return Array.isArray(br)?br.slice():br},validator(br){return Array.isArray(br)||`Expected an array value, but received: ${print$2(br)}`}})}function boolean$2(){return define$2("boolean",fr=>typeof fr=="boolean")}function instance$2(fr){return define$2("instance",br=>br instanceof fr||`Expected a \`${fr.name}\` instance, but received: ${print$2(br)}`)}function literal$2(fr){const br=print$2(fr),wr=typeof fr;return new Struct$5({type:"literal",schema:wr==="string"||wr==="number"||wr==="boolean"?fr:null,validator(Er){return Er===fr||`Expected the literal \`${br}\`, but received: ${print$2(Er)}`}})}function never$2(){return define$2("never",()=>!1)}function nullable$2(fr){return new Struct$5({...fr,validator:(br,wr)=>br===null||fr.validator(br,wr),refiner:(br,wr)=>br===null||fr.refiner(br,wr)})}function number$2(){return define$2("number",fr=>typeof fr=="number"&&!isNaN(fr)||`Expected a number, but received: ${print$2(fr)}`)}function optional$2(fr){return new Struct$5({...fr,validator:(br,wr)=>br===void 0||fr.validator(br,wr),refiner:(br,wr)=>br===void 0||fr.refiner(br,wr)})}function record$2(fr,br){return new Struct$5({type:"record",schema:null,*entries(wr){if(isObject$2(wr))for(const Er in wr){const kr=wr[Er];yield[Er,Er,fr],yield[Er,kr,br]}},validator(wr){return isObject$2(wr)||`Expected an object, but received: ${print$2(wr)}`}})}function string$2(){return define$2("string",fr=>typeof fr=="string"||`Expected a string, but received: ${print$2(fr)}`)}function tuple$2(fr){const br=never$2();return new Struct$5({type:"tuple",schema:null,*entries(wr){if(Array.isArray(wr)){const Er=Math.max(fr.length,wr.length);for(let kr=0;krwr.type).join(" | ");return new Struct$5({type:"union",schema:null,coercer(wr){for(const Er of fr){const[kr,jr]=Er.validate(wr,{coerce:!0});if(!kr)return jr}return wr},validator(wr,Er){const kr=[];for(const jr of fr){const[...Br]=run$2(wr,jr,Er),[qr]=Br;if(qr[0])for(const[Wr]of Br)Wr&&kr.push(Wr);else return[]}return[`Expected the value to satisfy a union of \`${br}\`, but received: ${print$2(wr)}`,...kr]}})}function unknown$2(){return define$2("unknown",()=>!0)}function coerce$2(fr,br,wr){return new Struct$5({...fr,coercer:(Er,kr)=>is$2(Er,br)?fr.coercer(wr(Er,kr),kr):fr.coercer(Er,kr)})}var getRandomValues,rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate$2(fr){return typeof fr=="string"&®EX.test(fr)}var byteToHex=[];for(var i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));function stringify$1(fr){var br=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,wr=(byteToHex[fr[br+0]]+byteToHex[fr[br+1]]+byteToHex[fr[br+2]]+byteToHex[fr[br+3]]+"-"+byteToHex[fr[br+4]]+byteToHex[fr[br+5]]+"-"+byteToHex[fr[br+6]]+byteToHex[fr[br+7]]+"-"+byteToHex[fr[br+8]]+byteToHex[fr[br+9]]+"-"+byteToHex[fr[br+10]]+byteToHex[fr[br+11]]+byteToHex[fr[br+12]]+byteToHex[fr[br+13]]+byteToHex[fr[br+14]]+byteToHex[fr[br+15]]).toLowerCase();if(!validate$2(wr))throw TypeError("Stringified UUID is invalid");return wr}var _nodeId,_clockseq,_lastMSecs=0,_lastNSecs=0;function v1(fr,br,wr){var Er=br&&wr||0,kr=br||new Array(16);fr=fr||{};var jr=fr.node||_nodeId,Br=fr.clockseq!==void 0?fr.clockseq:_clockseq;if(jr==null||Br==null){var qr=fr.random||(fr.rng||rng)();jr==null&&(jr=_nodeId=[qr[0]|1,qr[1],qr[2],qr[3],qr[4],qr[5]]),Br==null&&(Br=_clockseq=(qr[6]<<8|qr[7])&16383)}var Wr=fr.msecs!==void 0?fr.msecs:Date.now(),Vr=fr.nsecs!==void 0?fr.nsecs:_lastNSecs+1,Hr=Wr-_lastMSecs+(Vr-_lastNSecs)/1e4;if(Hr<0&&fr.clockseq===void 0&&(Br=Br+1&16383),(Hr<0||Wr>_lastMSecs)&&fr.nsecs===void 0&&(Vr=0),Vr>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=Wr,_lastNSecs=Vr,_clockseq=Br,Wr+=122192928e5;var Zr=((Wr&268435455)*1e4+Vr)%4294967296;kr[Er++]=Zr>>>24&255,kr[Er++]=Zr>>>16&255,kr[Er++]=Zr>>>8&255,kr[Er++]=Zr&255;var Jr=Wr/4294967296*1e4&268435455;kr[Er++]=Jr>>>8&255,kr[Er++]=Jr&255,kr[Er++]=Jr>>>24&15|16,kr[Er++]=Jr>>>16&255,kr[Er++]=Br>>>8|128,kr[Er++]=Br&255;for(var Xr=0;Xr<6;++Xr)kr[Er+Xr]=jr[Xr];return br||stringify$1(kr)}function parse(fr){if(!validate$2(fr))throw TypeError("Invalid UUID");var br,wr=new Uint8Array(16);return wr[0]=(br=parseInt(fr.slice(0,8),16))>>>24,wr[1]=br>>>16&255,wr[2]=br>>>8&255,wr[3]=br&255,wr[4]=(br=parseInt(fr.slice(9,13),16))>>>8,wr[5]=br&255,wr[6]=(br=parseInt(fr.slice(14,18),16))>>>8,wr[7]=br&255,wr[8]=(br=parseInt(fr.slice(19,23),16))>>>8,wr[9]=br&255,wr[10]=(br=parseInt(fr.slice(24,36),16))/1099511627776&255,wr[11]=br/4294967296&255,wr[12]=br>>>24&255,wr[13]=br>>>16&255,wr[14]=br>>>8&255,wr[15]=br&255,wr}function stringToBytes(fr){fr=unescape(encodeURIComponent(fr));for(var br=[],wr=0;wr>5]>>>kr%32&255,Br=parseInt(Er.charAt(jr>>>4&15)+Er.charAt(jr&15),16);br.push(Br)}return br}function getOutputLength(fr){return(fr+64>>>9<<4)+14+1}function wordsToMd5(fr,br){fr[br>>5]|=128<>5]|=(fr[Er/8]&255)<>16)+(br>>16)+(wr>>16);return Er<<16|wr&65535}function bitRotateLeft(fr,br){return fr<>>32-br}function md5cmn(fr,br,wr,Er,kr,jr){return safeAdd(bitRotateLeft(safeAdd(safeAdd(br,fr),safeAdd(Er,jr)),kr),wr)}function md5ff(fr,br,wr,Er,kr,jr,Br){return md5cmn(br&wr|~br&Er,fr,br,kr,jr,Br)}function md5gg(fr,br,wr,Er,kr,jr,Br){return md5cmn(br&Er|wr&~Er,fr,br,kr,jr,Br)}function md5hh(fr,br,wr,Er,kr,jr,Br){return md5cmn(br^wr^Er,fr,br,kr,jr,Br)}function md5ii(fr,br,wr,Er,kr,jr,Br){return md5cmn(wr^(br|~Er),fr,br,kr,jr,Br)}var v3=v35("v3",48,md5);function v4(fr,br,wr){fr=fr||{};var Er=fr.random||(fr.rng||rng)();if(Er[6]=Er[6]&15|64,Er[8]=Er[8]&63|128,br){wr=wr||0;for(var kr=0;kr<16;++kr)br[wr+kr]=Er[kr];return br}return stringify$1(Er)}function f(fr,br,wr,Er){switch(fr){case 0:return br&wr^~br&Er;case 1:return br^wr^Er;case 2:return br&wr^br&Er^wr&Er;case 3:return br^wr^Er}}function ROTL(fr,br){return fr<>>32-br}function sha1(fr){var br=[1518500249,1859775393,2400959708,3395469782],wr=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof fr=="string"){var Er=unescape(encodeURIComponent(fr));fr=[];for(var kr=0;kr>>0;jn=In,In=Tn,Tn=ROTL($n,30)>>>0,$n=wn,wn=na}wr[0]=wr[0]+wn>>>0,wr[1]=wr[1]+$n>>>0,wr[2]=wr[2]+Tn>>>0,wr[3]=wr[3]+In>>>0,wr[4]=wr[4]+jn>>>0}return[wr[0]>>24&255,wr[0]>>16&255,wr[0]>>8&255,wr[0]&255,wr[1]>>24&255,wr[1]>>16&255,wr[1]>>8&255,wr[1]&255,wr[2]>>24&255,wr[2]>>16&255,wr[2]>>8&255,wr[2]&255,wr[3]>>24&255,wr[3]>>16&255,wr[3]>>8&255,wr[3]&255,wr[4]>>24&255,wr[4]>>16&255,wr[4]>>8&255,wr[4]&255]}var v5=v35("v5",80,sha1);const nil="00000000-0000-0000-0000-000000000000";function version$5(fr){if(!validate$2(fr))throw TypeError("Invalid UUID");return parseInt(fr.substr(14,1),16)}const esmBrowser=Object.freeze(Object.defineProperty({__proto__:null,NIL:nil,parse,stringify:stringify$1,v1,v3,v4,v5,validate:validate$2,version:version$5},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(esmBrowser),uuid$1=require$$0.v4,generateRequest$1=function(fr,br,wr,Er){if(typeof fr!="string")throw new TypeError(fr+" must be a string");Er=Er||{};const kr=typeof Er.version=="number"?Er.version:2;if(kr!==1&&kr!==2)throw new TypeError(kr+" must be 1 or 2");const jr={method:fr};if(kr===2&&(jr.jsonrpc="2.0"),br){if(typeof br!="object"&&!Array.isArray(br))throw new TypeError(br+" must be an object, array or omitted");jr.params=br}if(typeof wr>"u"){const Br=typeof Er.generator=="function"?Er.generator:function(){return uuid$1()};jr.id=Br(jr,Er)}else kr===2&&wr===null?Er.notificationIdNull&&(jr.id=null):jr.id=wr;return jr};var generateRequest_1=generateRequest$1;const uuid=require$$0.v4,generateRequest=generateRequest_1,ClientBrowser=function(fr,br){if(!(this instanceof ClientBrowser))return new ClientBrowser(fr,br);br||(br={}),this.options={reviver:typeof br.reviver<"u"?br.reviver:null,replacer:typeof br.replacer<"u"?br.replacer:null,generator:typeof br.generator<"u"?br.generator:function(){return uuid()},version:typeof br.version<"u"?br.version:2,notificationIdNull:typeof br.notificationIdNull=="boolean"?br.notificationIdNull:!1},this.callServer=fr};var browser=ClientBrowser;ClientBrowser.prototype.request=function(fr,br,wr,Er){const kr=this;let jr=null;const Br=Array.isArray(fr)&&typeof br=="function";if(this.options.version===1&&Br)throw new TypeError("JSON-RPC 1.0 does not support batching");if(Br||!Br&&fr&&typeof fr=="object"&&typeof br=="function")Er=br,jr=fr;else{typeof wr=="function"&&(Er=wr,wr=void 0);const Vr=typeof Er=="function";try{jr=generateRequest(fr,br,wr,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(Hr){if(Vr)return Er(Hr);throw Hr}if(!Vr)return jr}let Wr;try{Wr=JSON.stringify(jr,this.options.replacer)}catch(Vr){return Er(Vr)}return this.callServer(Wr,function(Vr,Hr){kr._parseResponse(Vr,Hr,Er)}),jr};ClientBrowser.prototype._parseResponse=function(fr,br,wr){if(fr){wr(fr);return}if(!br)return wr();let Er;try{Er=JSON.parse(br,this.options.reviver)}catch(kr){return wr(kr)}if(wr.length===3)if(Array.isArray(Er)){const kr=function(Br){return typeof Br.error<"u"},jr=function(Br){return!kr(Br)};return wr(null,Er.filter(kr),Er.filter(jr))}else return wr(null,Er.error,Er.result);wr(null,Er)};const RpcClient=getDefaultExportFromCjs$2(browser);var client={},eventemitter3={exports:{}};(function(fr){var br=Object.prototype.hasOwnProperty,wr="~";function Er(){}Object.create&&(Er.prototype=Object.create(null),new Er().__proto__||(wr=!1));function kr(Wr,Vr,Hr){this.fn=Wr,this.context=Vr,this.once=Hr||!1}function jr(Wr,Vr,Hr,Zr,Jr){if(typeof Hr!="function")throw new TypeError("The listener must be a function");var Xr=new kr(Hr,Zr||Wr,Jr),En=wr?wr+Vr:Vr;return Wr._events[En]?Wr._events[En].fn?Wr._events[En]=[Wr._events[En],Xr]:Wr._events[En].push(Xr):(Wr._events[En]=Xr,Wr._eventsCount++),Wr}function Br(Wr,Vr){--Wr._eventsCount===0?Wr._events=new Er:delete Wr._events[Vr]}function qr(){this._events=new Er,this._eventsCount=0}qr.prototype.eventNames=function(){var Vr=[],Hr,Zr;if(this._eventsCount===0)return Vr;for(Zr in Hr=this._events)br.call(Hr,Zr)&&Vr.push(wr?Zr.slice(1):Zr);return Object.getOwnPropertySymbols?Vr.concat(Object.getOwnPropertySymbols(Hr)):Vr},qr.prototype.listeners=function(Vr){var Hr=wr?wr+Vr:Vr,Zr=this._events[Hr];if(!Zr)return[];if(Zr.fn)return[Zr.fn];for(var Jr=0,Xr=Zr.length,En=new Array(Xr);Jr++this.rpc_id),Hr?this.dataPack=Hr:this.dataPack=new utils_cjs_1.DefaultDataPack,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(wr,Er,kr,jr){return!jr&&typeof kr=="object"&&(jr=kr,kr=null),new Promise((Br,qr)=>{if(!this.ready)return qr(new Error("socket not ready"));const Wr=this.generate_request_id(wr,Er),Vr={jsonrpc:"2.0",method:wr,params:Er||void 0,id:Wr};this.socket.send(this.dataPack.encode(Vr),jr,Hr=>{if(Hr)return qr(Hr);this.queue[Wr]={promise:[Br,qr]},kr&&(this.queue[Wr].timeout=setTimeout(()=>{delete this.queue[Wr],qr(new Error("reply timeout"))},kr))})})}async login(wr){const Er=await this.call("rpc.login",wr);if(!Er)throw new Error("authentication failed");return Er}async listMethods(){return await this.call("__listMethods")}notify(wr,Er){return new Promise((kr,jr)=>{if(!this.ready)return jr(new Error("socket not ready"));const Br={jsonrpc:"2.0",method:wr,params:Er};this.socket.send(this.dataPack.encode(Br),qr=>{if(qr)return jr(qr);kr()})})}async subscribe(wr){typeof wr=="string"&&(wr=[wr]);const Er=await this.call("rpc.on",wr);if(typeof wr=="string"&&Er[wr]!=="ok")throw new Error("Failed subscribing to an event '"+wr+"' with: "+Er[wr]);return Er}async unsubscribe(wr){typeof wr=="string"&&(wr=[wr]);const Er=await this.call("rpc.off",wr);if(typeof wr=="string"&&Er[wr]!=="ok")throw new Error("Failed unsubscribing from an event with: "+Er);return Er}close(wr,Er){this.socket.close(wr||1e3,Er)}setAutoReconnect(wr){this.reconnect=wr}setReconnectInterval(wr){this.reconnect_interval=wr}setMaxReconnects(wr){this.max_reconnects=wr}_connect(wr,Er){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(wr,Er),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:kr})=>{kr instanceof ArrayBuffer&&(kr=Buffer$2.from(kr).toString());try{kr=this.dataPack.decode(kr)}catch{return}if(kr.notification&&this.listeners(kr.notification).length){if(!Object.keys(kr.params).length)return this.emit(kr.notification);const jr=[kr.notification];if(kr.params.constructor===Object)jr.push(kr.params);else for(let Br=0;Br{this.emit.apply(this,jr)})}if(!this.queue[kr.id])return kr.method?Promise.resolve().then(()=>{this.emit(kr.method,kr==null?void 0:kr.params)}):void 0;"error"in kr=="result"in kr&&this.queue[kr.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[kr.id].timeout&&clearTimeout(this.queue[kr.id].timeout),kr.error?this.queue[kr.id].promise[1](kr.error):this.queue[kr.id].promise[0](kr.result),delete this.queue[kr.id]}),this.socket.addEventListener("error",kr=>this.emit("error",kr)),this.socket.addEventListener("close",({code:kr,reason:jr})=>{this.ready&&setTimeout(()=>this.emit("close",kr,jr),0),this.ready=!1,this.socket=void 0,kr!==1e3&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||this.max_reconnects===0)&&(this.reconnect_timer_id=setTimeout(()=>this._connect(wr,Er),this.reconnect_interval)))})}}var _default$1=client.default=CommonClient,websocket_browser={};Object.defineProperty(websocket_browser,"__esModule",{value:!0});const eventemitter3_1=eventemitter3Exports;class WebSocketBrowserImpl extends eventemitter3_1.EventEmitter{constructor(wr,Er,kr){super();_f(this,"socket");this.socket=new window.WebSocket(wr,kr),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=jr=>this.emit("message",jr.data),this.socket.onerror=jr=>this.emit("error",jr),this.socket.onclose=jr=>{this.emit("close",jr.code,jr.reason)}}send(wr,Er,kr){const jr=kr||Er;try{this.socket.send(wr),jr()}catch(Br){jr(Br)}}close(wr,Er){this.socket.close(wr,Er)}addEventListener(wr,Er,kr){this.socket.addEventListener(wr,Er,kr)}}function default_1(fr,br){return new WebSocketBrowserImpl(fr,br)}var _default=websocket_browser.default=default_1;function isOnCurve$2(fr){try{return ed25519.ExtendedPoint.fromHex(fr),!0}catch{return!1}}const sign=(fr,br)=>ed25519.sign(fr,br.slice(0,32)),verify=ed25519.verify,toBuffer$2=fr=>Buffer$1$1.isBuffer(fr)?fr:fr instanceof Uint8Array?Buffer$1$1.from(fr.buffer,fr.byteOffset,fr.byteLength):Buffer$1$1.from(fr);let Struct$4=class{constructor(br){Object.assign(this,br)}encode(){return Buffer$1$1.from(serialize_1(SOLANA_SCHEMA$2,this))}static decode(br){return deserialize_1(SOLANA_SCHEMA$2,this,br)}static decodeUnchecked(br){return deserializeUnchecked_1(SOLANA_SCHEMA$2,this,br)}};const SOLANA_SCHEMA$2=new Map;var _PublicKey$2;const MAX_SEED_LENGTH$2=32,PUBLIC_KEY_LENGTH$2=32;function isPublicKeyData$2(fr){return fr._bn!==void 0}let uniquePublicKeyCounter$2=1,PublicKey$2=class Cv extends Struct$4{constructor(br){if(super({}),this._bn=void 0,isPublicKeyData$2(br))this._bn=br._bn;else{if(typeof br=="string"){const wr=bs58$6.decode(br);if(wr.length!=PUBLIC_KEY_LENGTH$2)throw new Error("Invalid public key input");this._bn=new BN$2(wr)}else this._bn=new BN$2(br);if(this._bn.byteLength()>PUBLIC_KEY_LENGTH$2)throw new Error("Invalid public key input")}}static unique(){const br=new Cv(uniquePublicKeyCounter$2);return uniquePublicKeyCounter$2+=1,new Cv(br.toBuffer())}equals(br){return this._bn.eq(br._bn)}toBase58(){return bs58$6.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const br=this.toBuffer();return new Uint8Array(br.buffer,br.byteOffset,br.byteLength)}toBuffer(){const br=this._bn.toArrayLike(Buffer$1$1);if(br.length===PUBLIC_KEY_LENGTH$2)return br;const wr=Buffer$1$1.alloc(32);return br.copy(wr,32-br.length),wr}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(br,wr,Er){const kr=Buffer$1$1.concat([br.toBuffer(),Buffer$1$1.from(wr),Er.toBuffer()]),jr=sha256$4(kr);return new Cv(jr)}static createProgramAddressSync(br,wr){let Er=Buffer$1$1.alloc(0);br.forEach(function(jr){if(jr.length>MAX_SEED_LENGTH$2)throw new TypeError("Max seed length exceeded");Er=Buffer$1$1.concat([Er,toBuffer$2(jr)])}),Er=Buffer$1$1.concat([Er,wr.toBuffer(),Buffer$1$1.from("ProgramDerivedAddress")]);const kr=sha256$4(Er);if(isOnCurve$2(kr))throw new Error("Invalid seeds, address must fall off the curve");return new Cv(kr)}static async createProgramAddress(br,wr){return this.createProgramAddressSync(br,wr)}static findProgramAddressSync(br,wr){let Er=255,kr;for(;Er!=0;){try{const jr=br.concat(Buffer$1$1.from([Er]));kr=this.createProgramAddressSync(jr,wr)}catch(jr){if(jr instanceof TypeError)throw jr;Er--;continue}return[kr,Er]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(br,wr){return this.findProgramAddressSync(br,wr)}static isOnCurve(br){const wr=new Cv(br);return isOnCurve$2(wr.toBytes())}};_PublicKey$2=PublicKey$2;PublicKey$2.default=new _PublicKey$2("11111111111111111111111111111111");SOLANA_SCHEMA$2.set(PublicKey$2,{kind:"struct",fields:[["_bn","u256"]]});new PublicKey$2("BPFLoader1111111111111111111111111111111111");const PACKET_DATA_SIZE=1232,VERSION_PREFIX_MASK=127,SIGNATURE_LENGTH_IN_BYTES$2=64;class TransactionExpiredBlockheightExceededError extends Error{constructor(br){super(`Signature ${br} has expired: block height exceeded.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(br,wr){super(`Transaction was not confirmed in ${wr.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${br} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});class TransactionExpiredNonceInvalidError extends Error{constructor(br){super(`Signature ${br} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredNonceInvalidError.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MessageAccountKeys{constructor(br,wr){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=br,this.accountKeysFromLookups=wr}keySegments(){const br=[this.staticAccountKeys];return this.accountKeysFromLookups&&(br.push(this.accountKeysFromLookups.writable),br.push(this.accountKeysFromLookups.readonly)),br}get(br){for(const wr of this.keySegments()){if(br256)throw new Error("Account index overflow encountered during compilation");const Er=new Map;this.keySegments().flat().forEach((jr,Br)=>{Er.set(jr.toBase58(),Br)});const kr=jr=>{const Br=Er.get(jr.toBase58());if(Br===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return Br};return br.map(jr=>({programIdIndex:kr(jr.programId),accountKeyIndexes:jr.keys.map(Br=>kr(Br.pubkey)),data:jr.data}))}}const publicKey$3=(fr="publicKey")=>blob(32,fr),signature=(fr="signature")=>blob(64,fr),rustString$2=(fr="string")=>{const br=struct([u32("length"),u32("lengthPadding"),blob(offset(u32(),-8),"chars")],fr),wr=br.decode.bind(br),Er=br.encode.bind(br),kr=br;return kr.decode=(jr,Br)=>wr(jr,Br).chars.toString(),kr.encode=(jr,Br,qr)=>{const Wr={chars:Buffer$1$1.from(jr,"utf8")};return Er(Wr,Br,qr)},kr.alloc=jr=>u32().span+u32().span+Buffer$1$1.from(jr,"utf8").length,kr},authorized$2=(fr="authorized")=>struct([publicKey$3("staker"),publicKey$3("withdrawer")],fr),lockup$2=(fr="lockup")=>struct([ns64("unixTimestamp"),ns64("epoch"),publicKey$3("custodian")],fr),voteInit$2=(fr="voteInit")=>struct([publicKey$3("nodePubkey"),publicKey$3("authorizedVoter"),publicKey$3("authorizedWithdrawer"),u8("commission")],fr),voteAuthorizeWithSeedArgs$2=(fr="voteAuthorizeWithSeedArgs")=>struct([u32("voteAuthorizationType"),publicKey$3("currentAuthorityDerivedKeyOwnerPubkey"),rustString$2("currentAuthorityDerivedKeySeed"),publicKey$3("newAuthorized")],fr);function getAlloc(fr,br){const wr=kr=>{if(kr.span>=0)return kr.span;if(typeof kr.alloc=="function")return kr.alloc(br[kr.property]);if("count"in kr&&"elementLayout"in kr){const jr=br[kr.property];if(Array.isArray(jr))return jr.length*wr(kr.elementLayout)}else if("fields"in kr)return getAlloc({layout:kr},br[kr.property]);return 0};let Er=0;return fr.layout.fields.forEach(kr=>{Er+=wr(kr)}),Er}function decodeLength(fr){let br=0,wr=0;for(;;){let Er=fr.shift();if(br|=(Er&127)<>=7,wr==0){fr.push(Er);break}else Er|=128,fr.push(Er)}}function assert$2(fr,br){if(!fr)throw new Error(br||"Assertion failed")}class CompiledKeys{constructor(br,wr){this.payer=void 0,this.keyMetaMap=void 0,this.payer=br,this.keyMetaMap=wr}static compile(br,wr){const Er=new Map,kr=Br=>{const qr=Br.toBase58();let Wr=Er.get(qr);return Wr===void 0&&(Wr={isSigner:!1,isWritable:!1,isInvoked:!1},Er.set(qr,Wr)),Wr},jr=kr(wr);jr.isSigner=!0,jr.isWritable=!0;for(const Br of br){kr(Br.programId).isInvoked=!0;for(const qr of Br.keys){const Wr=kr(qr.pubkey);Wr.isSigner||(Wr.isSigner=qr.isSigner),Wr.isWritable||(Wr.isWritable=qr.isWritable)}}return new CompiledKeys(wr,Er)}getMessageComponents(){const br=[...this.keyMetaMap.entries()];assert$2(br.length<=256,"Max static account keys length exceeded");const wr=br.filter(([,Wr])=>Wr.isSigner&&Wr.isWritable),Er=br.filter(([,Wr])=>Wr.isSigner&&!Wr.isWritable),kr=br.filter(([,Wr])=>!Wr.isSigner&&Wr.isWritable),jr=br.filter(([,Wr])=>!Wr.isSigner&&!Wr.isWritable),Br={numRequiredSignatures:wr.length+Er.length,numReadonlySignedAccounts:Er.length,numReadonlyUnsignedAccounts:jr.length};{assert$2(wr.length>0,"Expected at least one writable signer key");const[Wr]=wr[0];assert$2(Wr===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const qr=[...wr.map(([Wr])=>new PublicKey$2(Wr)),...Er.map(([Wr])=>new PublicKey$2(Wr)),...kr.map(([Wr])=>new PublicKey$2(Wr)),...jr.map(([Wr])=>new PublicKey$2(Wr))];return[Br,qr]}extractTableLookup(br){const[wr,Er]=this.drainKeysFoundInLookupTable(br.state.addresses,Br=>!Br.isSigner&&!Br.isInvoked&&Br.isWritable),[kr,jr]=this.drainKeysFoundInLookupTable(br.state.addresses,Br=>!Br.isSigner&&!Br.isInvoked&&!Br.isWritable);if(!(wr.length===0&&kr.length===0))return[{accountKey:br.key,writableIndexes:wr,readonlyIndexes:kr},{writable:Er,readonly:jr}]}drainKeysFoundInLookupTable(br,wr){const Er=new Array,kr=new Array;for(const[jr,Br]of this.keyMetaMap.entries())if(wr(Br)){const qr=new PublicKey$2(jr),Wr=br.findIndex(Vr=>Vr.equals(qr));Wr>=0&&(assert$2(Wr<256,"Max lookup table index exceeded"),Er.push(Wr),kr.push(qr),this.keyMetaMap.delete(jr))}return[Er,kr]}}const END_OF_BUFFER_ERROR_MESSAGE="Reached end of buffer unexpectedly";function guardedShift(fr){if(fr.length===0)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return fr.shift()}function guardedSplice(fr,...br){const[wr]=br;if(br.length===2?wr+(br[1]??0)>fr.length:wr>=fr.length)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return fr.splice(...br)}class Message{constructor(br){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=br.header,this.accountKeys=br.accountKeys.map(wr=>new PublicKey$2(wr)),this.recentBlockhash=br.recentBlockhash,this.instructions=br.instructions,this.instructions.forEach(wr=>this.indexToProgramIds.set(wr.programIdIndex,this.accountKeys[wr.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(br=>({programIdIndex:br.programIdIndex,accountKeyIndexes:br.accounts,data:bs58$6.decode(br.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new MessageAccountKeys(this.staticAccountKeys)}static compile(br){const wr=CompiledKeys.compile(br.instructions,br.payerKey),[Er,kr]=wr.getMessageComponents(),Br=new MessageAccountKeys(kr).compileInstructions(br.instructions).map(qr=>({programIdIndex:qr.programIdIndex,accounts:qr.accountKeyIndexes,data:bs58$6.encode(qr.data)}));return new Message({header:Er,accountKeys:kr,recentBlockhash:br.recentBlockhash,instructions:Br})}isAccountSigner(br){return br=this.header.numRequiredSignatures){const Er=br-wr,jr=this.accountKeys.length-wr-this.header.numReadonlyUnsignedAccounts;return Er!this.isProgramId(wr))}serialize(){const br=this.accountKeys.length;let wr=[];encodeLength(wr,br);const Er=this.instructions.map(Zr=>{const{accounts:Jr,programIdIndex:Xr}=Zr,En=Array.from(bs58$6.decode(Zr.data));let wn=[];encodeLength(wn,Jr.length);let $n=[];return encodeLength($n,En.length),{programIdIndex:Xr,keyIndicesCount:Buffer$1$1.from(wn),keyIndices:Jr,dataLength:Buffer$1$1.from($n),data:En}});let kr=[];encodeLength(kr,Er.length);let jr=Buffer$1$1.alloc(PACKET_DATA_SIZE);Buffer$1$1.from(kr).copy(jr);let Br=kr.length;Er.forEach(Zr=>{const Xr=struct([u8("programIdIndex"),blob(Zr.keyIndicesCount.length,"keyIndicesCount"),seq(u8("keyIndex"),Zr.keyIndices.length,"keyIndices"),blob(Zr.dataLength.length,"dataLength"),seq(u8("userdatum"),Zr.data.length,"data")]).encode(Zr,jr,Br);Br+=Xr}),jr=jr.slice(0,Br);const qr=struct([blob(1,"numRequiredSignatures"),blob(1,"numReadonlySignedAccounts"),blob(1,"numReadonlyUnsignedAccounts"),blob(wr.length,"keyCount"),seq(publicKey$3("key"),br,"keys"),publicKey$3("recentBlockhash")]),Wr={numRequiredSignatures:Buffer$1$1.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Buffer$1$1.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Buffer$1$1.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Buffer$1$1.from(wr),keys:this.accountKeys.map(Zr=>toBuffer$2(Zr.toBytes())),recentBlockhash:bs58$6.decode(this.recentBlockhash)};let Vr=Buffer$1$1.alloc(2048);const Hr=qr.encode(Wr,Vr);return jr.copy(Vr,Hr),Vr.slice(0,Hr+jr.length)}static from(br){let wr=[...br];const Er=guardedShift(wr);if(Er!==(Er&VERSION_PREFIX_MASK))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const kr=guardedShift(wr),jr=guardedShift(wr),Br=decodeLength(wr);let qr=[];for(let Jr=0;Jr0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new MessageAccountKeys(this.staticAccountKeys,wr)}isAccountSigner(br){return br=Er){const kr=br-Er,jr=this.addressTableLookups.reduce((Br,qr)=>Br+qr.writableIndexes.length,0);return kr=this.header.numRequiredSignatures){const kr=br-wr,Br=Er-wr-this.header.numReadonlyUnsignedAccounts;return krjr.key.equals(Er.accountKey));if(!kr)throw new Error(`Failed to find address lookup table account for table key ${Er.accountKey.toBase58()}`);for(const jr of Er.writableIndexes)if(jrHr.toBytes()),recentBlockhash:bs58$6.decode(this.recentBlockhash),instructionsLength:new Uint8Array(Er),serializedInstructions:wr,addressTableLookupsLength:new Uint8Array(jr),serializedAddressTableLookups:kr},qr);return qr.slice(0,Vr)}serializeInstructions(){let br=0;const wr=new Uint8Array(PACKET_DATA_SIZE);for(const Er of this.compiledInstructions){const kr=Array();encodeLength(kr,Er.accountKeyIndexes.length);const jr=Array();encodeLength(jr,Er.data.length);const Br=struct([u8("programIdIndex"),blob(kr.length,"encodedAccountKeyIndexesLength"),seq(u8(),Er.accountKeyIndexes.length,"accountKeyIndexes"),blob(jr.length,"encodedDataLength"),blob(Er.data.length,"data")]);br+=Br.encode({programIdIndex:Er.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(kr),accountKeyIndexes:Er.accountKeyIndexes,encodedDataLength:new Uint8Array(jr),data:Er.data},wr,br)}return wr.slice(0,br)}serializeAddressTableLookups(){let br=0;const wr=new Uint8Array(PACKET_DATA_SIZE);for(const Er of this.addressTableLookups){const kr=Array();encodeLength(kr,Er.writableIndexes.length);const jr=Array();encodeLength(jr,Er.readonlyIndexes.length);const Br=struct([publicKey$3("accountKey"),blob(kr.length,"encodedWritableIndexesLength"),seq(u8(),Er.writableIndexes.length,"writableIndexes"),blob(jr.length,"encodedReadonlyIndexesLength"),seq(u8(),Er.readonlyIndexes.length,"readonlyIndexes")]);br+=Br.encode({accountKey:Er.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(kr),writableIndexes:Er.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(jr),readonlyIndexes:Er.readonlyIndexes},wr,br)}return wr.slice(0,br)}static deserialize(br){let wr=[...br];const Er=guardedShift(wr),kr=Er&VERSION_PREFIX_MASK;assert$2(Er!==kr,"Expected versioned message but received legacy message");const jr=kr;assert$2(jr===0,`Expected versioned message with version 0 but found version ${jr}`);const Br={numRequiredSignatures:guardedShift(wr),numReadonlySignedAccounts:guardedShift(wr),numReadonlyUnsignedAccounts:guardedShift(wr)},qr=[],Wr=decodeLength(wr);for(let En=0;En{const br=VersionedMessage.deserializeMessageVersion(fr);if(br==="legacy")return Message.from(fr);if(br===0)return MessageV0.deserialize(fr);throw new Error(`Transaction message version ${br} deserialization is not supported`)}};let TransactionStatus=function(fr){return fr[fr.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",fr[fr.PROCESSED=1]="PROCESSED",fr[fr.TIMED_OUT=2]="TIMED_OUT",fr[fr.NONCE_INVALID=3]="NONCE_INVALID",fr}({});const DEFAULT_SIGNATURE=Buffer$1$1.alloc(SIGNATURE_LENGTH_IN_BYTES$2).fill(0);class TransactionInstruction{constructor(br){this.keys=void 0,this.programId=void 0,this.data=Buffer$1$1.alloc(0),this.programId=br.programId,this.keys=br.keys,br.data&&(this.data=br.data)}toJSON(){return{keys:this.keys.map(({pubkey:br,isSigner:wr,isWritable:Er})=>({pubkey:br.toJSON(),isSigner:wr,isWritable:Er})),programId:this.programId.toJSON(),data:[...this.data]}}}class Transaction{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(br){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!!br)if(br.feePayer&&(this.feePayer=br.feePayer),br.signatures&&(this.signatures=br.signatures),Object.prototype.hasOwnProperty.call(br,"nonceInfo")){const{minContextSlot:wr,nonceInfo:Er}=br;this.minNonceContextSlot=wr,this.nonceInfo=Er}else if(Object.prototype.hasOwnProperty.call(br,"lastValidBlockHeight")){const{blockhash:wr,lastValidBlockHeight:Er}=br;this.recentBlockhash=wr,this.lastValidBlockHeight=Er}else{const{recentBlockhash:wr,nonceInfo:Er}=br;Er&&(this.nonceInfo=Er),this.recentBlockhash=wr}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(br=>br.toJSON()),signers:this.signatures.map(({publicKey:br})=>br.toJSON())}}add(...br){if(br.length===0)throw new Error("No instructions");return br.forEach(wr=>{"instructions"in wr?this.instructions=this.instructions.concat(wr.instructions):"data"in wr&&"programId"in wr&&"keys"in wr?this.instructions.push(wr):this.instructions.push(new TransactionInstruction(wr))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let br,wr;if(this.nonceInfo?(br=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?wr=[this.nonceInfo.nonceInstruction,...this.instructions]:wr=this.instructions):(br=this.recentBlockhash,wr=this.instructions),!br)throw new Error("Transaction recentBlockhash required");wr.length<1&&console.warn("No instructions provided");let Er;if(this.feePayer)Er=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)Er=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let wn=0;wn{wn.keys.forEach(Tn=>{jr.push({...Tn})});const $n=wn.programId.toString();kr.includes($n)||kr.push($n)}),kr.forEach(wn=>{jr.push({pubkey:new PublicKey$2(wn),isSigner:!1,isWritable:!1})});const Br=[];jr.forEach(wn=>{const $n=wn.pubkey.toString(),Tn=Br.findIndex(In=>In.pubkey.toString()===$n);Tn>-1?(Br[Tn].isWritable=Br[Tn].isWritable||wn.isWritable,Br[Tn].isSigner=Br[Tn].isSigner||wn.isSigner):Br.push(wn)}),Br.sort(function(wn,$n){if(wn.isSigner!==$n.isSigner)return wn.isSigner?-1:1;if(wn.isWritable!==$n.isWritable)return wn.isWritable?-1:1;const Tn={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return wn.pubkey.toBase58().localeCompare($n.pubkey.toBase58(),"en",Tn)});const qr=Br.findIndex(wn=>wn.pubkey.equals(Er));if(qr>-1){const[wn]=Br.splice(qr,1);wn.isSigner=!0,wn.isWritable=!0,Br.unshift(wn)}else Br.unshift({pubkey:Er,isSigner:!0,isWritable:!0});for(const wn of this.signatures){const $n=Br.findIndex(Tn=>Tn.pubkey.equals(wn.publicKey));if($n>-1)Br[$n].isSigner||(Br[$n].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw new Error(`unknown signer: ${wn.publicKey.toString()}`)}let Wr=0,Vr=0,Hr=0;const Zr=[],Jr=[];Br.forEach(({pubkey:wn,isSigner:$n,isWritable:Tn})=>{$n?(Zr.push(wn.toString()),Wr+=1,Tn||(Vr+=1)):(Jr.push(wn.toString()),Tn||(Hr+=1))});const Xr=Zr.concat(Jr),En=wr.map(wn=>{const{data:$n,programId:Tn}=wn;return{programIdIndex:Xr.indexOf(Tn.toString()),accounts:wn.keys.map(In=>Xr.indexOf(In.pubkey.toString())),data:bs58$6.encode($n)}});return En.forEach(wn=>{assert$2(wn.programIdIndex>=0),wn.accounts.forEach($n=>assert$2($n>=0))}),new Message({header:{numRequiredSignatures:Wr,numReadonlySignedAccounts:Vr,numReadonlyUnsignedAccounts:Hr},accountKeys:Xr,recentBlockhash:br,instructions:En})}_compile(){const br=this.compileMessage(),wr=br.accountKeys.slice(0,br.header.numRequiredSignatures);return this.signatures.length===wr.length&&this.signatures.every((kr,jr)=>wr[jr].equals(kr.publicKey))||(this.signatures=wr.map(Er=>({signature:null,publicKey:Er}))),br}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(br){return(await br.getFeeForMessage(this.compileMessage())).value}setSigners(...br){if(br.length===0)throw new Error("No signers");const wr=new Set;this.signatures=br.filter(Er=>{const kr=Er.toString();return wr.has(kr)?!1:(wr.add(kr),!0)}).map(Er=>({signature:null,publicKey:Er}))}sign(...br){if(br.length===0)throw new Error("No signers");const wr=new Set,Er=[];for(const jr of br){const Br=jr.publicKey.toString();wr.has(Br)||(wr.add(Br),Er.push(jr))}this.signatures=Er.map(jr=>({signature:null,publicKey:jr.publicKey}));const kr=this._compile();this._partialSign(kr,...Er)}partialSign(...br){if(br.length===0)throw new Error("No signers");const wr=new Set,Er=[];for(const jr of br){const Br=jr.publicKey.toString();wr.has(Br)||(wr.add(Br),Er.push(jr))}const kr=this._compile();this._partialSign(kr,...Er)}_partialSign(br,...wr){const Er=br.serialize();wr.forEach(kr=>{const jr=sign(Er,kr.secretKey);this._addSignature(kr.publicKey,toBuffer$2(jr))})}addSignature(br,wr){this._compile(),this._addSignature(br,wr)}_addSignature(br,wr){assert$2(wr.length===64);const Er=this.signatures.findIndex(kr=>br.equals(kr.publicKey));if(Er<0)throw new Error(`unknown signer: ${br.toString()}`);this.signatures[Er].signature=Buffer$1$1.from(wr)}verifySignatures(br=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),br)}_getMessageSignednessErrors(br,wr){const Er={};for(const{signature:kr,publicKey:jr}of this.signatures)kr===null?wr&&(Er.missing||(Er.missing=[])).push(jr):verify(kr,br,jr.toBytes())||(Er.invalid||(Er.invalid=[])).push(jr);return Er.invalid||Er.missing?Er:void 0}serialize(br){const{requireAllSignatures:wr,verifySignatures:Er}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},br),kr=this.serializeMessage();if(Er){const jr=this._getMessageSignednessErrors(kr,wr);if(jr){let Br="Signature verification failed.";throw jr.invalid&&(Br+=` +}`;var ku=wx(function(){return Ou(xo,eu+"return "+Al).apply(wr,ko)});if(ku.source=Al,Qy(ku))throw ku;return ku}function u3(Qr){return Bu(Qr).toLowerCase()}function d3(Qr){return Bu(Qr).toUpperCase()}function f3(Qr,Cn,eo){if(Qr=Bu(Qr),Qr&&(eo||Cn===wr))return z1(Qr);if(!Qr||!(Cn=kp(Cn)))return Qr;var ao=Lp(Qr),mo=Lp(Cn),xo=H1(ao,mo),ko=V1(ao,mo)+1;return um(ao,xo,ko).join("")}function h3(Qr,Cn,eo){if(Qr=Bu(Qr),Qr&&(eo||Cn===wr))return Qr.slice(0,G1(Qr)+1);if(!Qr||!(Cn=kp(Cn)))return Qr;var ao=Lp(Qr),mo=V1(ao,Lp(Cn))+1;return um(ao,0,mo).join("")}function p3(Qr,Cn,eo){if(Qr=Bu(Qr),Qr&&(eo||Cn===wr))return Qr.replace(wo,"");if(!Qr||!(Cn=kp(Cn)))return Qr;var ao=Lp(Qr),mo=H1(ao,Lp(Cn));return um(ao,mo).join("")}function m3(Qr,Cn){var eo=io,ao=no;if(_h(Cn)){var mo="separator"in Cn?Cn.separator:mo;eo="length"in Cn?$u(Cn.length):eo,ao="omission"in Cn?kp(Cn.omission):ao}Qr=Bu(Qr);var xo=Qr.length;if(Im(Qr)){var ko=Lp(Qr);xo=ko.length}if(eo>=xo)return Qr;var Po=eo-Pm(ao);if(Po<1)return ao;var Mo=ko?um(ko,0,Po).join(""):Qr.slice(0,Po);if(mo===wr)return Mo+ao;if(ko&&(Po+=Mo.length-Po),lv(mo)){if(Qr.slice(Po).search(mo)){var _l,wl=Mo;for(mo.global||(mo=Q0(mo.source,Bu(El.exec(mo))+"g")),mo.lastIndex=0;_l=mo.exec(wl);)var Al=_l.index;Mo=Mo.slice(0,Al===wr?Po:Al)}}else if(Qr.indexOf(kp(mo),Po)!=Po){var Gl=Mo.lastIndexOf(mo);Gl>-1&&(Mo=Mo.slice(0,Gl))}return Mo+ao}function g3(Qr){return Qr=Bu(Qr),Qr&&cu.test(Qr)?Qr.replace(yl,Gv):Qr}var y3=Cm(function(Qr,Cn,eo){return Qr+(eo?" ":"")+Cn.toUpperCase()}),mv=B1("toUpperCase");function _x(Qr,Cn,eo){return Qr=Bu(Qr),Cn=eo?wr:Cn,Cn===wr?Wv(Qr)?Yv(Qr):Ov(Qr):Qr.match(Cn)||[]}var wx=Cu(function(Qr,Cn){try{return pp(Qr,wr,Cn)}catch(eo){return Qy(eo)?eo:new xu(eo)}}),_3=fm(function(Qr,Cn){return Ip(Cn,function(eo){eo=Qp(eo),Xp(Qr,eo,Yy(Qr[eo],Qr))}),Qr});function w3(Qr){var Cn=Qr==null?0:Qr.length,eo=lu();return Qr=Cn?Yu(Qr,function(ao){if(typeof ao[1]!="function")throw new Pp(Br);return[eo(ao[0]),ao[1]]}):[],Cu(function(ao){for(var mo=-1;++moPn)return[];var eo=On,ao=hp(Qr,On);Cn=lu(Cn),Qr-=On;for(var mo=J0(ao,Cn);++eo0||Cn<0)?new Ru(eo):(Qr<0?eo=eo.takeRight(-Qr):Qr&&(eo=eo.drop(Qr)),Cn!==wr&&(Cn=$u(Cn),eo=Cn<0?eo.dropRight(-Cn):eo.take(Cn-Qr)),eo)},Ru.prototype.takeRightWhile=function(Qr){return this.reverse().takeWhile(Qr).reverse()},Ru.prototype.toArray=function(){return this.take(On)},Vp(Ru.prototype,function(Qr,Cn){var eo=/^(?:filter|find|map|reject)|While$/.test(Cn),ao=/^(?:head|last)$/.test(Cn),mo=_o[ao?"take"+(Cn=="last"?"Right":""):Cn],xo=ao||/^find/.test(Cn);mo&&(_o.prototype[Cn]=function(){var ko=this.__wrapped__,Po=ao?[1]:arguments,Mo=ko instanceof Ru,_l=Po[0],wl=Mo||Eu(ko),Al=function(Au){var Pu=mo.apply(_o,im([Au],Po));return ao&&Gl?Pu[0]:Pu};wl&&eo&&typeof _l=="function"&&_l.length!=1&&(Mo=wl=!1);var Gl=this.__chain__,eu=!!this.__actions__.length,uu=xo&&!Gl,ku=Mo&&!eu;if(!xo&&wl){ko=ku?ko:new Ru(this);var du=Qr.apply(ko,Po);return du.__actions__.push({func:R1,args:[Al],thisArg:wr}),new jp(du,Gl)}return uu&&ku?Qr.apply(this,Po):(du=this.thru(Al),uu?ao?du.value()[0]:du.value():du)})}),Ip(["pop","push","shift","sort","splice","unshift"],function(Qr){var Cn=g0[Qr],eo=/^(?:push|sort|unshift)$/.test(Qr)?"tap":"thru",ao=/^(?:pop|shift)$/.test(Qr);_o.prototype[Qr]=function(){var mo=arguments;if(ao&&!this.__chain__){var xo=this.value();return Cn.apply(Eu(xo)?xo:[],mo)}return this[eo](function(ko){return Cn.apply(Eu(ko)?ko:[],mo)})}}),Vp(Ru.prototype,function(Qr,Cn){var eo=_o[Cn];if(eo){var ao=eo.name+"";Nu.call(Nm,ao)||(Nm[ao]=[]),Nm[ao].push({name:Cn,func:eo})}}),Nm[B0(wr,Tn).name]=[{name:"wrapper",func:wr}],Ru.prototype.clone=v_,Ru.prototype.reverse=b_,Ru.prototype.value=__,_o.prototype.at=K2,_o.prototype.chain=G2,_o.prototype.commit=Z2,_o.prototype.next=J2,_o.prototype.plant=X2,_o.prototype.reverse=Q2,_o.prototype.toJSON=_o.prototype.valueOf=_o.prototype.value=eE,_o.prototype.first=_o.prototype.head,Zm&&(_o.prototype[Zm]=Y2),_o},jm=Xv();_p?((_p.exports=jm)._=jm,gp._=jm):Hu._=jm}).call(ge)})(Ui,Ui.exports);var Gg=Object.defineProperty,zg=Object.defineProperties,Kg=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yg=Object.prototype.hasOwnProperty,Zg=Object.prototype.propertyIsEnumerable,ya=(fr,br,wr)=>br in fr?Gg(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,cr=(fr,br)=>{for(var wr in br||(br={}))Yg.call(br,wr)&&ya(fr,wr,br[wr]);if(Ea)for(var wr of Ea(br))Zg.call(br,wr)&&ya(fr,wr,br[wr]);return fr},Jg=(fr,br)=>zg(fr,Kg(br));function ft(fr,br,wr){var Er;const kr=ve(fr);return((Er=br.rpcMap)==null?void 0:Er[kr.reference])||`${Bg}?chainId=${kr.namespace}:${kr.reference}&projectId=${wr}`}function Ct(fr){return fr.includes(":")?fr.split(":")[1]:fr}function Sa(fr){return fr.map(br=>`${br.split(":")[0]}:${br.split(":")[1]}`)}function Xg(fr,br){const wr=Object.keys(br.namespaces).filter(kr=>kr.includes(fr));if(!wr.length)return[];const Er=[];return wr.forEach(kr=>{const jr=br.namespaces[kr].accounts;Er.push(...jr)}),Er}function Oa(fr={},br={}){const wr=Ra(fr),Er=Ra(br);return Ui.exports.merge(wr,Er)}function Ra(fr){var br,wr,Er,kr;const jr={};if(!B$2(fr))return jr;for(const[Br,qr]of Object.entries(fr)){const Wr=oe(Br)?[Br]:qr.chains,Vr=qr.methods||[],Hr=qr.events||[],Zr=qr.rpcMap||{},Jr=en(Br);jr[Jr]=Jg(cr(cr({},jr[Jr]),qr),{chains:S$2(Wr,(br=jr[Jr])==null?void 0:br.chains),methods:S$2(Vr,(wr=jr[Jr])==null?void 0:wr.methods),events:S$2(Hr,(Er=jr[Jr])==null?void 0:Er.events),rpcMap:cr(cr({},Zr),(kr=jr[Jr])==null?void 0:kr.rpcMap)})}return jr}function Qg(fr){return fr.includes(":")?fr.split(":")[2]:fr}function Vg(fr){const br={};for(const[wr,Er]of Object.entries(fr)){const kr=Er.methods||[],jr=Er.events||[],Br=Er.accounts||[],qr=oe(wr)?[wr]:Er.chains?Er.chains:Sa(Er.accounts);br[wr]={chains:qr,methods:kr,events:jr,accounts:Br}}return br}function Wi(fr){return typeof fr=="number"?fr:fr.includes("0x")?parseInt(fr,16):(fr=fr.includes(":")?fr.split(":")[1]:fr,isNaN(Number(fr))?fr:Number(fr))}const ba={},z$2=fr=>ba[fr],Fi=(fr,br)=>{ba[fr]=br};class kg{constructor(br){this.name="polkadot",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getAccounts(){const br=this.namespace.accounts;return br?br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2])||[]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class jg{constructor(br){this.name="eip155",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(br){switch(br.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(br);case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(br.request.method)?await this.client.request(br):this.getHttpProvider().request(br.request)}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(parseInt(br),wr),this.chainId=parseInt(br),this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}createHttpProvider(br,wr){const Er=wr||ft(`${this.name}:${br}`,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=parseInt(Ct(wr));br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}getHttpProvider(){const br=this.chainId,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}async handleSwitchChain(br){var wr,Er;let kr=br.request.params?(wr=br.request.params[0])==null?void 0:wr.chainId:"0x0";kr=kr.startsWith("0x")?kr:`0x${kr}`;const jr=parseInt(kr,16);if(this.isChainApproved(jr))this.setDefaultChain(`${jr}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:br.topic,request:{method:br.request.method,params:[{chainId:kr}]},chainId:(Er=this.namespace.chains)==null?void 0:Er[0]}),this.setDefaultChain(`${jr}`);else throw new Error(`Failed to switch to chain 'eip155:${jr}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(br){return this.namespace.chains.includes(`${this.name}:${br}`)}}class nv{constructor(br){this.name="solana",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class tv{constructor(br){this.name="cosmos",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class ev{constructor(br){this.name="cip34",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{const Er=this.getCardanoRPCUrl(wr),kr=Ct(wr);br[kr]=this.createHttpProvider(kr,Er)}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}getCardanoRPCUrl(br){const wr=this.namespace.rpcMap;if(wr)return wr[br]}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||this.getCardanoRPCUrl(br);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class rv{constructor(br){this.name="elrond",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class iv{constructor(br){this.name="multiversx",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){this.httpProviders[br]||this.setHttpProvider(br,wr),this.chainId=br,this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${br}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}getAccounts(){const br=this.namespace.accounts;return br?[...new Set(br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2]))]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;const kr=Ct(wr);br[kr]=this.createHttpProvider(kr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace,this.client.core.projectId);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);return new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}class sv{constructor(br){this.name="near",this.namespace=br.namespace,this.events=z$2("events"),this.client=z$2("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(br){this.namespace=Object.assign(this.namespace,br)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const br=this.namespace.chains[0];if(!br)throw new Error("ChainId not found");return br.split(":")[1]}request(br){return this.namespace.methods.includes(br.request.method)?this.client.request(br):this.getHttpProvider().request(br.request)}setDefaultChain(br,wr){if(this.chainId=br,!this.httpProviders[br]){const Er=wr||ft(`${this.name}:${br}`,this.namespace);if(!Er)throw new Error(`No RPC url provided for chainId: ${br}`);this.setHttpProvider(br,Er)}this.events.emit(Vn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const br=this.namespace.accounts;return br?br.filter(wr=>wr.split(":")[1]===this.chainId.toString()).map(wr=>wr.split(":")[2])||[]:[]}createHttpProviders(){const br={};return this.namespace.chains.forEach(wr=>{var Er;br[wr]=this.createHttpProvider(wr,(Er=this.namespace.rpcMap)==null?void 0:Er[wr])}),br}getHttpProvider(){const br=`${this.name}:${this.chainId}`,wr=this.httpProviders[br];if(typeof wr>"u")throw new Error(`JSON-RPC provider for ${br} not found`);return wr}setHttpProvider(br,wr){const Er=this.createHttpProvider(br,wr);Er&&(this.httpProviders[br]=Er)}createHttpProvider(br,wr){const Er=wr||ft(br,this.namespace);return typeof Er>"u"?void 0:new JsonRpcProvider(new f$4(Er,z$2("disableProviderPing")))}}var uv=Object.defineProperty,av=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,Ta=Object.getOwnPropertySymbols,fv=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,La=(fr,br,wr)=>br in fr?uv(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,hr=(fr,br)=>{for(var wr in br||(br={}))fv.call(br,wr)&&La(fr,wr,br[wr]);if(Ta)for(var wr of Ta(br))cv.call(br,wr)&&La(fr,wr,br[wr]);return fr},Mi=(fr,br)=>av(fr,ov(br));class lr{constructor(br){this.events=new Ug,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=br,this.logger=typeof(br==null?void 0:br.logger)<"u"&&typeof(br==null?void 0:br.logger)!="string"?br.logger:Hg(k$4({level:(br==null?void 0:br.logger)||Ia})),this.disableProviderPing=(br==null?void 0:br.disableProviderPing)||!1}static async init(br){const wr=new lr(br);return await wr.initialize(),wr}async request(br,wr,Er){const[kr,jr]=this.validateChain(wr);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(kr).request({request:hr({},br),chainId:`${kr}:${jr}`,topic:this.session.topic,expiry:Er})}sendAsync(br,wr,Er,kr){const jr=new Date().getTime();this.request(br,Er,kr).then(Br=>wr(null,formatJsonRpcResult(jr,Br))).catch(Br=>wr(Br,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var br;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(br=this.session)==null?void 0:br.topic,reason:U$1("USER_DISCONNECTED")}),await this.cleanup()}async connect(br){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(br),await this.cleanupPendingPairings(),!br.skipPairing)return await this.pair(br.pairingTopic)}on(br,wr){this.events.on(br,wr)}once(br,wr){this.events.once(br,wr)}removeListener(br,wr){this.events.removeListener(br,wr)}off(br,wr){this.events.off(br,wr)}get isWalletConnect(){return!0}async pair(br){this.shouldAbortPairingAttempt=!1;let wr=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(wr>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:Er,approval:kr}=await this.client.connect({pairingTopic:br,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});Er&&(this.uri=Er,this.events.emit("display_uri",Er)),await kr().then(jr=>{this.session=jr;const Br=Vg(jr.namespaces);this.namespaces=Oa(this.namespaces,Br),this.persist("namespaces",this.namespaces)}).catch(jr=>{if(jr.message!==ae)throw jr;wr++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(br,wr){try{if(!this.session)return;const[Er,kr]=this.validateChain(br);this.getProvider(Er).setDefaultChain(kr,wr)}catch(Er){if(!/Please call connect/.test(Er.message))throw Er}}async cleanupPendingPairings(br={}){this.logger.info("Cleaning up inactive pairings...");const wr=this.client.pairing.getAll();if(k$2(wr)){for(const Er of wr)br.deletePairings?this.client.core.expirer.set(Er.topic,0):await this.client.core.relayer.subscriber.unsubscribe(Er.topic);this.logger.info(`Inactive pairings cleared: ${wr.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const br=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[br]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Q$1.init({logger:this.providerOpts.logger||Ia,relayUrl:this.providerOpts.relayUrl||Fg,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const br=[...new Set(Object.keys(this.session.namespaces).map(wr=>en(wr)))];Fi("client",this.client),Fi("events",this.events),Fi("disableProviderPing",this.disableProviderPing),br.forEach(wr=>{if(!this.session)return;const Er=Xg(wr,this.session),kr=Sa(Er),jr=Oa(this.namespaces,this.optionalNamespaces),Br=Mi(hr({},jr[wr]),{accounts:Er,chains:kr});switch(wr){case"eip155":this.rpcProviders[wr]=new jg({namespace:Br});break;case"solana":this.rpcProviders[wr]=new nv({namespace:Br});break;case"cosmos":this.rpcProviders[wr]=new tv({namespace:Br});break;case"polkadot":this.rpcProviders[wr]=new kg({namespace:Br});break;case"cip34":this.rpcProviders[wr]=new ev({namespace:Br});break;case"elrond":this.rpcProviders[wr]=new rv({namespace:Br});break;case"multiversx":this.rpcProviders[wr]=new iv({namespace:Br});break;case"near":this.rpcProviders[wr]=new sv({namespace:Br});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",br=>{this.events.emit("session_ping",br)}),this.client.on("session_event",br=>{const{params:wr}=br,{event:Er}=wr;if(Er.name==="accountsChanged"){const kr=Er.data;kr&&k$2(kr)&&this.events.emit("accountsChanged",kr.map(Qg))}else if(Er.name==="chainChanged"){const kr=wr.chainId,jr=wr.event.data,Br=en(kr),qr=Wi(kr)!==Wi(jr)?`${Br}:${Wi(jr)}`:kr;this.onChainChanged(qr)}else this.events.emit(Er.name,Er.data);this.events.emit("session_event",br)}),this.client.on("session_update",({topic:br,params:wr})=>{var Er;const{namespaces:kr}=wr,jr=(Er=this.client)==null?void 0:Er.session.get(br);this.session=Mi(hr({},jr),{namespaces:kr}),this.onSessionUpdate(),this.events.emit("session_update",{topic:br,params:wr})}),this.client.on("session_delete",async br=>{await this.cleanup(),this.events.emit("session_delete",br),this.events.emit("disconnect",Mi(hr({},U$1("USER_DISCONNECTED")),{data:br.topic}))}),this.on(Vn.DEFAULT_CHAIN_CHANGED,br=>{this.onChainChanged(br,!0)})}getProvider(br){if(!this.rpcProviders[br])throw new Error(`Provider not found: ${br}`);return this.rpcProviders[br]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(br=>{var wr;this.getProvider(br).updateNamespace((wr=this.session)==null?void 0:wr.namespaces[br])})}setNamespaces(br){const{namespaces:wr,optionalNamespaces:Er,sessionProperties:kr}=br;wr&&Object.keys(wr).length&&(this.namespaces=wr),Er&&Object.keys(Er).length&&(this.optionalNamespaces=Er),this.sessionProperties=kr,this.persist("namespaces",wr),this.persist("optionalNamespaces",Er)}validateChain(br){const[wr,Er]=(br==null?void 0:br.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[wr,Er];if(wr&&!Object.keys(this.namespaces||{}).map(Br=>en(Br)).includes(wr))throw new Error(`Namespace '${wr}' is not configured. Please call connect() first with namespace config.`);if(wr&&Er)return[wr,Er];const kr=en(Object.keys(this.namespaces)[0]),jr=this.rpcProviders[kr].getDefaultChain();return[kr,jr]}async requestAccounts(){const[br]=this.validateChain();return await this.getProvider(br).requestAccounts()}onChainChanged(br,wr=!1){if(!this.namespaces)return;const[Er,kr]=this.validateChain(br);kr&&(wr||this.getProvider(Er).setDefaultChain(kr),this.namespaces[Er]?this.namespaces[Er].defaultChain=kr:this.namespaces[`${Er}:${kr}`]?this.namespaces[`${Er}:${kr}`].defaultChain=kr:this.namespaces[`${Er}:${kr}`]={defaultChain:kr},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",kr))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(br,wr){this.client.core.storage.setItem(`${xa}/${br}`,wr)}async getFromStore(br){return await this.client.core.storage.getItem(`${xa}/${br}`)}}const hv=lr,P$2="wc",S$1="ethereum_provider",$$1=`${P$2}@2:${S$1}:`,j$2="https://rpc.walletconnect.com/v1/",u$2=["eth_sendTransaction","personal_sign"],E$1=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],m$2=["chainChanged","accountsChanged"],_$2=["chainChanged","accountsChanged","message","disconnect","connect"];var N$1=Object.defineProperty,q$2=Object.defineProperties,D$2=Object.getOwnPropertyDescriptors,y$2=Object.getOwnPropertySymbols,U=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,O$1=(fr,br,wr)=>br in fr?N$1(fr,br,{enumerable:!0,configurable:!0,writable:!0,value:wr}):fr[br]=wr,p$2=(fr,br)=>{for(var wr in br||(br={}))U.call(br,wr)&&O$1(fr,wr,br[wr]);if(y$2)for(var wr of y$2(br))Q.call(br,wr)&&O$1(fr,wr,br[wr]);return fr},M$1=(fr,br)=>q$2(fr,D$2(br));function g$2(fr){return Number(fr[0].split(":")[1])}function f$3(fr){return`0x${fr.toString(16)}`}function L$1(fr){const{chains:br,optionalChains:wr,methods:Er,optionalMethods:kr,events:jr,optionalEvents:Br,rpcMap:qr}=fr;if(!k$6(br))throw new Error("Invalid chains");const Wr={chains:br,methods:Er||u$2,events:jr||m$2,rpcMap:p$2({},br.length?{[g$2(br)]:qr[g$2(br)]}:{})},Vr=jr==null?void 0:jr.filter(Xr=>!m$2.includes(Xr)),Hr=Er==null?void 0:Er.filter(Xr=>!u$2.includes(Xr));if(!wr&&!Br&&!kr&&!(Vr!=null&&Vr.length)&&!(Hr!=null&&Hr.length))return{required:br.length?Wr:void 0};const Zr=(Vr==null?void 0:Vr.length)&&(Hr==null?void 0:Hr.length)||!wr,Jr={chains:[...new Set(Zr?Wr.chains.concat(wr||[]):wr)],methods:[...new Set(Wr.methods.concat(kr!=null&&kr.length?kr:E$1))],events:[...new Set(Wr.events.concat(Br!=null&&Br.length?Br:_$2))],rpcMap:qr};return{required:br.length?Wr:void 0,optional:wr.length?Jr:void 0}}let v$2=class uS{constructor(){this.events=new eventsExports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$$1,this.on=(br,wr)=>(this.events.on(br,wr),this),this.once=(br,wr)=>(this.events.once(br,wr),this),this.removeListener=(br,wr)=>(this.events.removeListener(br,wr),this),this.off=(br,wr)=>(this.events.off(br,wr),this),this.parseAccount=br=>this.isCompatibleChainId(br)?this.parseAccountId(br).address:br,this.signer={},this.rpc={}}static async init(br){const wr=new uS;return await wr.initialize(br),wr}async request(br,wr){return await this.signer.request(br,this.formatChainId(this.chainId),wr)}sendAsync(br,wr,Er){this.signer.sendAsync(br,wr,this.formatChainId(this.chainId),Er)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(br){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(br);const{required:wr,optional:Er}=L$1(this.rpc);try{const kr=await new Promise(async(Br,qr)=>{var Wr;this.rpc.showQrModal&&((Wr=this.modal)==null||Wr.subscribeModal(Vr=>{!Vr.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),qr(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(M$1(p$2({namespaces:p$2({},wr&&{[this.namespace]:wr})},Er&&{optionalNamespaces:{[this.namespace]:Er}}),{pairingTopic:br==null?void 0:br.pairingTopic})).then(Vr=>{Br(Vr)}).catch(Vr=>{qr(new Error(Vr.message))})});if(!kr)return;const jr=Un(kr.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:jr),this.setAccounts(jr),this.events.emit("connect",{chainId:f$3(this.chainId)})}catch(kr){throw this.signer.logger.error(kr),kr}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",br=>{const{params:wr}=br,{event:Er}=wr;Er.name==="accountsChanged"?(this.accounts=this.parseAccounts(Er.data),this.events.emit("accountsChanged",this.accounts)):Er.name==="chainChanged"?this.setChainId(this.formatChainId(Er.data)):this.events.emit(Er.name,Er.data),this.events.emit("session_event",br)}),this.signer.on("chainChanged",br=>{const wr=parseInt(br);this.chainId=wr,this.events.emit("chainChanged",f$3(this.chainId)),this.persist()}),this.signer.on("session_update",br=>{this.events.emit("session_update",br)}),this.signer.on("session_delete",br=>{this.reset(),this.events.emit("session_delete",br),this.events.emit("disconnect",M$1(p$2({},U$4("USER_DISCONNECTED")),{data:br.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",br=>{var wr,Er;this.rpc.showQrModal&&((wr=this.modal)==null||wr.closeModal(),(Er=this.modal)==null||Er.openModal({uri:br})),this.events.emit("display_uri",br)})}switchEthereumChain(br){this.request({method:"wallet_switchEthereumChain",params:[{chainId:br.toString(16)}]})}isCompatibleChainId(br){return typeof br=="string"?br.startsWith(`${this.namespace}:`):!1}formatChainId(br){return`${this.namespace}:${br}`}parseChainId(br){return Number(br.split(":")[1])}setChainIds(br){const wr=br.filter(Er=>this.isCompatibleChainId(Er)).map(Er=>this.parseChainId(Er));wr.length&&(this.chainId=wr[0],this.events.emit("chainChanged",f$3(this.chainId)),this.persist())}setChainId(br){if(this.isCompatibleChainId(br)){const wr=this.parseChainId(br);this.chainId=wr,this.switchEthereumChain(wr)}}parseAccountId(br){const[wr,Er,kr]=br.split(":");return{chainId:`${wr}:${Er}`,address:kr}}setAccounts(br){this.accounts=br.filter(wr=>this.parseChainId(this.parseAccountId(wr).chainId)===this.chainId).map(wr=>this.parseAccountId(wr).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(br){var wr,Er;const kr=(wr=br==null?void 0:br.chains)!=null?wr:[],jr=(Er=br==null?void 0:br.optionalChains)!=null?Er:[],Br=kr.concat(jr);if(!Br.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const qr=kr.length?(br==null?void 0:br.methods)||u$2:[],Wr=kr.length?(br==null?void 0:br.events)||m$2:[],Vr=(br==null?void 0:br.optionalMethods)||[],Hr=(br==null?void 0:br.optionalEvents)||[],Zr=(br==null?void 0:br.rpcMap)||this.buildRpcMap(Br,br.projectId),Jr=(br==null?void 0:br.qrModalOptions)||void 0;return{chains:kr==null?void 0:kr.map(Xr=>this.formatChainId(Xr)),optionalChains:jr.map(Xr=>this.formatChainId(Xr)),methods:qr,events:Wr,optionalMethods:Vr,optionalEvents:Hr,rpcMap:Zr,showQrModal:!!(br!=null&&br.showQrModal),qrModalOptions:Jr,projectId:br.projectId,metadata:br.metadata}}buildRpcMap(br,wr){const Er={};return br.forEach(kr=>{Er[kr]=this.getRpcUrl(kr,wr)}),Er}async initialize(br){if(this.rpc=this.getRpcConfig(br),this.chainId=this.rpc.chains.length?g$2(this.rpc.chains):g$2(this.rpc.optionalChains),this.signer=await hv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:br.disableProviderPing,relayUrl:br.relayUrl,storageOptions:br.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let wr;try{const{WalletConnectModal:Er}=await __vitePreload(()=>import("./index-D0Cq9I1E.js").then(kr=>kr.i),[]);wr=Er}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(wr)try{this.modal=new wr(p$2({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(Er){throw this.signer.logger.error(Er),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(br){if(!br)return;const{chains:wr,optionalChains:Er,rpcMap:kr}=br;wr&&k$6(wr)&&(this.rpc.chains=wr.map(jr=>this.formatChainId(jr)),wr.forEach(jr=>{this.rpc.rpcMap[jr]=(kr==null?void 0:kr[jr])||this.getRpcUrl(jr)})),Er&&k$6(Er)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=Er==null?void 0:Er.map(jr=>this.formatChainId(jr)),Er.forEach(jr=>{this.rpc.rpcMap[jr]=(kr==null?void 0:kr[jr])||this.getRpcUrl(jr)}))}getRpcUrl(br,wr){var Er;return((Er=this.rpc.rpcMap)==null?void 0:Er[br])||`${j$2}?chainId=eip155:${br}&projectId=${wr||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const br=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),wr=this.session.namespaces[`${this.namespace}:${br}`]?this.session.namespaces[`${this.namespace}:${br}`]:this.session.namespaces[this.namespace];this.setChainIds(br?[this.formatChainId(br)]:wr==null?void 0:wr.accounts),this.setAccounts(wr==null?void 0:wr.accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(br){return typeof br=="string"||br instanceof String?[this.parseAccount(br)]:br.map(wr=>this.parseAccount(wr))}};const parseIntSafe=(fr,br=10)=>{try{const wr=parseInt(String(fr),br);if(isNaN(wr)){logger$7.error(`Error parsing ${fr}`);return}return wr}catch(wr){logger$7.error(`Error parsing ${fr} to int: ${wr}`)}},activeAccountKey=fr=>`dynamic-wc2-active-account-${fr}`,sessionTopicKey=fr=>`dynamic-wc2-session-topic-${fr}`,swicthedNetworkKey=fr=>`dynamic-wc2-switched-network-${fr}`,currentChainKey=fr=>`dynamic-wc2-current-chain-${fr}`,ee=new EventEmitter$2;class WalletConnect extends EthereumWalletConnector{constructor(br){var wr;super(br),this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.isInitialized=!1,this.canConnectViaQrCode=!0,this.isWalletConnect=!0,this.preferredChains=[],this._hasSwitchedNetwork=!1,this.sessionEventHandler=()=>{},this.sessionDeleteHandler=()=>{},this.name=br.walletName,this.projectId=br.projectId,this.deepLinkPreference=br.deepLinkPreference||"native",this.preferredChains=br.walletConnectPreferredChains||[],this.hasSwitchedNetwork=(wr=!!localStorage.getItem(this.swicthedNetworkKey))!==null&&wr!==void 0?wr:!1;const Er=localStorage.getItem(this.currentChainKey);this.currentChainId=Er?parseIntSafe(Er):void 0}getMappedChains(){return this.evmNetworks.filter(br=>br.chainId!==11297108109).map(br=>`eip155:${br.chainId}`)}getMappedChainsByPreferredOrder(){const br=this.getMappedChains(),wr=this.preferredChains.filter(kr=>br.includes(kr)),Er=br.filter(kr=>!this.preferredChains.includes(kr));return[...wr,...Er].map(kr=>Number(kr.split(":")[1]))}initConnection(){return __awaiter$8(this,void 0,void 0,function*(){const{provider:br}=WalletConnect;if(!br)throw new DynamicError("No provider found (init connection)");br!=null&&br.signer.uri||br.connect().catch(wr=>{logger$7.error(wr),ee.emit("walletconnect_connection_failed",wr)})})}createProvider(){return __awaiter$8(this,void 0,void 0,function*(){return v$2.init({events:["chainChanged","accountsChanged"],methods:[],optionalChains:this.getMappedChainsByPreferredOrder(),optionalMethods:["eth_chainId","eth_signTypedData","eth_signTransaction","eth_sign","personal_sign","eth_sendTransaction","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain"],projectId:this.projectId,rpcMap:this.evmNetworkRpcMap(),showQrModal:!1})})}getWalletClientFromInitializedProvider(){return __awaiter$8(this,void 0,void 0,function*(){const br=this.createProvider();return createWalletClient$1({account:this.getActiveAccount(),transport:custom$1(yield br)})})}createInitProviderPromise(){return __awaiter$8(this,void 0,void 0,function*(){WalletConnect.provider=yield this.createProvider(),this.teardownEventListeners(),this.setupEventListeners()})}initProvider(){return __awaiter$8(this,void 0,void 0,function*(){const{provider:br}=WalletConnect;br||(this.initializePromise===void 0&&(this.initializePromise=this.createInitProviderPromise()),yield this.initializePromise)})}refreshSession(){var br,wr,Er,kr,jr;!((wr=(br=WalletConnect.provider)===null||br===void 0?void 0:br.session)===null||wr===void 0)&&wr.topic&&localStorage.getItem(this.sessionTopicKey)===((kr=(Er=WalletConnect.provider)===null||Er===void 0?void 0:Er.session)===null||kr===void 0?void 0:kr.topic)&&(this.session=WalletConnect.provider.session,this.setActiveAccount((jr=localStorage.getItem(this.activeAccountKey))!==null&&jr!==void 0?jr:void 0))}init(){return __awaiter$8(this,void 0,void 0,function*(){yield this.initProvider(),yield this.initConnection(),this.isInitialized=!0})}get sessionTopicKey(){return sessionTopicKey(this.key)}get activeAccountKey(){return activeAccountKey(this.key)}get swicthedNetworkKey(){return swicthedNetworkKey(this.key)}get currentChainKey(){return currentChainKey(this.key)}set currentChainId(br){this._currentChainId=br,br?localStorage.setItem(this.currentChainKey,br.toString()):localStorage.removeItem(this.currentChainKey)}get currentChainId(){return this._currentChainId}set hasSwitchedNetwork(br){this._hasSwitchedNetwork=br,br?localStorage.setItem(this.swicthedNetworkKey,br.toString()):localStorage.removeItem(this.swicthedNetworkKey)}get hasSwitchedNetwork(){return this._hasSwitchedNetwork}supportsNetworkSwitching(){return!0}setupEventListeners(){WalletConnect.provider&&(this.sessionEventHandler=({params:br})=>{if(logger$7.debug("session_event was called",{params:br}),!br||!br.event){logger$7.debug("session_event was called without params or params.event");return}const{name:wr,data:Er}=br.event;if(wr==="chainChanged"){const kr=parseIntSafe(Er);if(kr===this.currentChainId){logger$7.debug(`ignoring chainChanged event with same chain id as current chain id: ${kr}`);return}if(kr===void 0){logger$7.debug(`received unexpected data for chainChanged: ${Er} with type ${typeof Er}}`);return}this.currentChainId=kr,this.emit("chainChange",{chain:String(kr)}),this.hasSwitchedNetwork=!0,this.switchNetwork({networkChainId:kr})}else if(wr==="accountsChanged"){if(!Array.isArray(Er)){logger$7.debug(`received unexpected data for accountsChanged: ${Er} with type ${typeof Er}}`);return}const kr=Er[0].split(":")[2];this.setWCActiveAccount(kr)}},WalletConnect.provider.on("session_event",this.sessionEventHandler),this.sessionDeleteHandler=()=>__awaiter$8(this,void 0,void 0,function*(){this.endSession(),this.emit("disconnect")}),WalletConnect.provider.on("session_delete",this.sessionDeleteHandler))}teardownEventListeners(){WalletConnect.provider&&(WalletConnect.provider.off("session_event",this.sessionEventHandler),WalletConnect.provider.off("session_delete",this.sessionDeleteHandler))}getWalletClient(br){if(WalletConnect.provider)return createWalletClient$1({account:this.getActiveAccount(),chain:chainsMap[br??String(this.currentChainId)],transport:custom$1(WalletConnect.provider)})}getAddress(br){return __awaiter$8(this,void 0,void 0,function*(){var wr,Er;const kr=this.getActiveAccount();if(kr!=null&&kr.address)return kr.address;if((!WalletConnect.provider||!(!((wr=WalletConnect.provider)===null||wr===void 0)&&wr.signer.uri))&&(logger$7.debug("No WC2 provider found, re-initializing..."),yield this.endSession(),yield this.init(),yield sleep$1(1e3),!WalletConnect.provider||!(!((Er=WalletConnect.provider)===null||Er===void 0)&&Er.signer.uri)))throw logger$7.debug("No WC2 provider found, escaping and throwing error"),new DynamicError("No provider found");const jr=getWalletBookWallet(this.walletBook,this.key,this.walletFallback);return performPlatformSpecificConnectionMethod(WalletConnect.provider.signer.uri,jr,{onDesktopUri:br==null?void 0:br.onDesktopUri,onDisplayUri:br==null?void 0:br.onDisplayUri},this.deepLinkPreference),new Promise((Br,qr)=>{if(!WalletConnect.provider){qr(new DynamicError("No provider found"));return}const Wr=()=>{const Zr=new DynamicError("Connection rejected. Please try again.");Zr.code="connection_rejected",WalletConnect.provider&&(WalletConnect.provider.signer.uri=void 0,this.init()),qr(Zr),Hr()},Vr=()=>{var Zr;const Jr=(Zr=WalletConnect.provider)===null||Zr===void 0?void 0:Zr.session;if(!Jr){qr(new DynamicError("No session found"));return}this.setSession(Jr),this.setWCActiveAccount(Jr.namespaces.eip155.accounts[0].split(":")[2]),this.getNetwork().then(Xr=>{var En;this.currentChainId=Xr,Br((En=this.getActiveAccount())===null||En===void 0?void 0:En.address)}),Hr()},Hr=()=>{var Zr;ee.off("walletconnect_connection_failed",Wr),(Zr=WalletConnect.provider)===null||Zr===void 0||Zr.off("connect",Vr)};ee.on("walletconnect_connection_failed",Wr),WalletConnect.provider.on("connect",Vr)})})}waitForSignMessage(br,wr){return __awaiter$8(this,void 0,void 0,function*(){const kr=yield new Promise((jr,Br)=>{this.on("chainChange",()=>jr({success:!1})),br(wr).then(qr=>jr({signedMessage:qr,success:!0})).catch(Br)});return kr.success===!1?br(wr):kr.signedMessage})}getDeepLink(){var br;if(!this.session)return;const wr=getWalletBookWallet(this.walletBook,this.key),Er=getDeepLink({metadata:wr,mode:"regular",preference:this.deepLinkPreference,uri:(br=WalletConnect.provider)===null||br===void 0?void 0:br.signer.uri});if(Er)return`${Er}?sessionTopic=${this.session.topic}`}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){if(!this.session)throw new DynamicError("no session");const wr=this.getDeepLink();isMobile()&&wr&&(window.location.href=wr);const Er=jr=>__awaiter$8(this,void 0,void 0,function*(){const Br=this.getActiveAccount();return Br?(yield this.getWalletClientFromInitializedProvider()).signMessage({account:Br,message:jr}):void 0});return yield this.waitForSignMessage(Er,br)})}clearActiveAccount(){localStorage.removeItem(this.activeAccountKey),this.setActiveAccount(void 0)}clearSession(){localStorage.removeItem(this.sessionTopicKey),this.session=void 0}setWCActiveAccount(br){localStorage.setItem(this.activeAccountKey,br),this.setActiveAccount(br),this.emit("accountChange",{accounts:[br]})}setSession(br){localStorage.setItem(this.sessionTopicKey,br.topic),this.session=br}endSession(){return __awaiter$8(this,void 0,void 0,function*(){var br;if(this.clearActiveAccount(),this.clearSession(),this.hasSwitchedNetwork=!1,this.currentChainId=void 0,!!(!((br=WalletConnect.provider)===null||br===void 0)&&br.session))try{yield WalletConnect.provider.disconnect(),WalletConnect.provider=void 0}catch(wr){logger$7.debug(wr)}})}getNetwork(){const br=Object.create(null,{getNetwork:{get:()=>super.getNetwork}});return __awaiter$8(this,void 0,void 0,function*(){return this.currentChainId?this.currentChainId:(yield this.initProvider(),br.getNetwork.call(this))})}providerSwitchNetwork(br){const wr=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$8(this,arguments,void 0,function*({network:Er}){const kr=yield this.getSupportedNetworks();if(!(kr!=null&&kr.includes(Er.chainId.toString()))){const qr=new DynamicError("Network switching is not available at this time. The user should manually switch network in their wallet");throw qr.code="network_switching_only_available_in_wallet",qr}const jr=yield this.getNetwork();if(jr&&jr===Er.chainId)return;if(this.switchNetworkOnlyFromWallet)throw new DynamicError("Network switching is only supported through the wallet");if(!this.supportsNetworkSwitching())throw new DynamicError("Network switching not supported");const Br=yield this.getWalletClientFromInitializedProvider();if(this.isMetaMask()){const qr=this.getDeepLink();qr&&(window.location.href=qr)}yield wr.providerSwitchNetwork.call(this,{network:Er,provider:Br}),this.currentChainId=Er.chainId,this.hasSwitchedNetwork=!0,this.emit("chainChange",{chain:String(Er.chainId)})})}getConnectedAccounts(){return __awaiter$8(this,void 0,void 0,function*(){this.isInitialized===!1&&(yield this.initProvider(),this.refreshSession(),this.isInitialized=!0);const br=this.getActiveAccount();return br!=null&&br.address?[br.address]:[]})}isMetaMask(){var br,wr,Er,kr,jr;return(jr=(kr=(Er=(wr=(br=this.session)===null||br===void 0?void 0:br.peer)===null||wr===void 0?void 0:wr.metadata)===null||Er===void 0?void 0:Er.name)===null||kr===void 0?void 0:kr.toLowerCase().startsWith("metamask"))!==null&&jr!==void 0?jr:!1}getSupportedNetworks(){return __awaiter$8(this,void 0,void 0,function*(){var br;if(yield this.initProvider(),this.refreshSession(),this.isMetaMask())return this.hasSwitchedNetwork?[String(this.currentChainId)]:this.evmNetworks.map(Er=>Er.chainId.toString());if(!this.session)return[];const wr=[];return Object.keys(this.session.namespaces).forEach(Er=>{Er.startsWith("eip155:")&&wr.push(Er.split(":")[1])}),(br=this.session.namespaces.eip155)===null||br===void 0||br.accounts.forEach(Er=>wr.push(Er.split(":")[1])),wr.length?wr:this.evmNetworks.map(Er=>Er.chainId.toString())})}}let InjectedWalletBase$1=class extends EthereumWalletConnector{constructor(){super(...arguments),this.supportedChains=["ETH","EVM"],this.connectedChain="EVM",this.walletConnectorFallback=!1}getEthProviderHelper(){return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.wallet&&!this.ethProviderHelper&&(this.ethProviderHelper=new EthProviderHelper(this.wallet,this)),this.ethProviderHelper}getMobileOrInstalledWallet(){var br,wr;return this.wallet||(this.wallet=findWalletBookWallet(this.walletBook,this.key)),this.isInstalledOnBrowser()?this:!((wr=(br=this.wallet)===null||br===void 0?void 0:br.mobile)===null||wr===void 0)&&wr.inAppBrowser&&this.mobileExperience==="in-app-browser"&&isMobile()?this:this.walletConnectorFallback?new WalletConnect(Object.assign(Object.assign({},this.constructorProps),{walletName:this.name})):this}findProvider(){const br=this.getEthProviderHelper();if(br)return br.getInstalledProvider()}setupEventListeners(){if(!this.getWalletClient())return;const wr=this.getEthProviderHelper();if(!wr)return;const{tearDownEventListeners:Er}=wr._setupEventListeners(this);this.teardownEventListeners=Er}getWalletClient(br){var wr;return(wr=this.getEthProviderHelper())===null||wr===void 0?void 0:wr.findWalletClient(br)}isInstalledOnBrowser(){var br;return((br=this.getEthProviderHelper())===null||br===void 0?void 0:br.findProvider())!==void 0}getAddress(){return __awaiter$8(this,void 0,void 0,function*(){var br;return(br=this.getEthProviderHelper())===null||br===void 0?void 0:br.getAddress()})}connect(){return __awaiter$8(this,void 0,void 0,function*(){yield this.getAddress()})}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){var wr;return(wr=this.getEthProviderHelper())===null||wr===void 0?void 0:wr.signMessage(br)})}proveOwnership(br,wr){return __awaiter$8(this,void 0,void 0,function*(){return yield this.validateActiveWallet(br),this.signMessage(wr)})}endSession(){return __awaiter$8(this,void 0,void 0,function*(){})}providerSwitchNetwork(br){const wr=Object.create(null,{providerSwitchNetwork:{get:()=>super.providerSwitchNetwork}});return __awaiter$8(this,arguments,void 0,function*({network:Er,provider:kr}){return wr.providerSwitchNetwork.call(this,{network:Er,provider:kr})})}};class PhantomEvm extends InjectedWalletBase$1{constructor(br){super(br),this.name="Phantom",this.overrideKey="phantomevm",this.wallet=findWalletBookWallet(this.walletBook,this.key)}getAddress(){const br=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$8(this,void 0,void 0,function*(){if(this.isInstalledOnBrowser())return br.getAddress.call(this);isMobile()&&handleMobileWalletRedirect({nativeLink:"phantom://browse",universalLink:"https://phantom.app/ul/browse"})})}canGetChainAddress(){var br,wr;return!!(!((wr=(br=this.getEthProviderHelper())===null||br===void 0?void 0:br.findProvider())===null||wr===void 0)&&wr.selectedAddress)}}class ExodusEvm extends InjectedWalletBase$1{constructor(br){super(br),this.name="ExodusEvm",this.overrideKey="exodusevm",this.walletConnectorFallback=!0,this.wallet=findWalletBookWallet(this.walletBook,this.key)}}let UnknownInjected$1=class extends InjectedWalletBase$1{constructor(br){super(br),this.name="Unknown",this.overrideKey="unknown",this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}};class FallbackEvmConnector extends InjectedWalletBase$1{constructor(br){super(br),this.name="Fallback Connector",this.overrideKey="fallbackconnector",this.isAvailable=!1,this.wallet=findWalletBookWallet(this.walletBook,this.key)}isInstalledOnBrowser(){return!1}}const injectedWalletOverrides$1=[PhantomEvm,ExodusEvm],filteredInjectedWalletKeysOverrides$1=["phantomevm","coinbase","exodusevm"],fetchInjectedWalletConnector=({walletBook:fr})=>{var br;return Object.entries((br=fr==null?void 0:fr.wallets)!==null&&br!==void 0?br:{}).filter(([wr,Er])=>{var kr;return((kr=Er.injectedConfig)===null||kr===void 0?void 0:kr.find(jr=>jr.chain==="evm"))&&!filteredInjectedWalletKeysOverrides$1.includes(wr)}).map(([wr,Er])=>{const{shortName:kr}=Er,jr=kr||Er.name,Br=!!Er.walletConnect;return class extends InjectedWalletBase$1{constructor(qr){super(Object.assign({},qr)),this.name=jr,this.wallet=Er,this.walletConnectorFallback=Br,this.overrideKey=wr}getAddress(){const qr=Object.create(null,{getAddress:{get:()=>super.getAddress}});return __awaiter$8(this,void 0,void 0,function*(){var Wr;if(this.isInstalledOnBrowser())return qr.getAddress.call(this);const Vr=(Wr=this.wallet.mobile)===null||Wr===void 0?void 0:Wr.inAppBrowser;if(!Vr){const Hr=new Error(`No inAppBrowserBase found for ${this.name}.`);throw logger$7.error(Hr.message),Hr}window.location.href=`${Vr}/${window.location.href}`})}}})},fetchWalletConnectWallets=({walletBook:fr})=>{var br;return Object.entries((br=fr==null?void 0:fr.wallets)!==null&&br!==void 0?br:{}).filter(([,wr])=>wr.walletConnect&&!wr.filterFromWalletConnect).map(([wr,Er])=>{const{shortName:kr}=Er,jr=kr||Er.name;return class extends WalletConnect{constructor(Br){super(Object.assign(Object.assign({},Br),{walletName:jr})),this.overrideKey=wr}}})},getWalletConnectConnector=()=>class extends WalletConnect{constructor(fr){super(Object.assign(Object.assign({},fr),{walletName:"WalletConnect"}))}};var dist={},CoinbaseWalletSDK$1={},walletLogo$1={};Object.defineProperty(walletLogo$1,"__esModule",{value:!0});walletLogo$1.walletLogo=void 0;const walletLogo=(fr,br)=>{let wr;switch(fr){case"standard":return wr=br,`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return wr=br,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${br}' height='${wr}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return wr=(.1*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return wr=(.25*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return wr=(.1*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return wr=(.25*br).toFixed(2),`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return wr=br,`data:image/svg+xml,%3Csvg width='${br}' height='${wr}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};walletLogo$1.walletLogo=walletLogo;var CoinbaseWalletProvider$1={};const require$$0$2=getAugmentedNamespace(eventemitter3$1);var error={},constants$2={};Object.defineProperty(constants$2,"__esModule",{value:!0});constants$2.errorValues=constants$2.standardErrorCodes=void 0;constants$2.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};constants$2.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var errors$1={},utils$1={};(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.serialize=fr.getErrorCode=fr.isValidCode=fr.getMessageFromCode=fr.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const br=constants$2,wr="Unspecified error message.";fr.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function Er(Jr,Xr=wr){if(Jr&&Number.isInteger(Jr)){const En=Jr.toString();if(Hr(br.errorValues,En))return br.errorValues[En].message;if(Wr(Jr))return fr.JSON_RPC_SERVER_ERROR_MESSAGE}return Xr}fr.getMessageFromCode=Er;function kr(Jr){if(!Number.isInteger(Jr))return!1;const Xr=Jr.toString();return!!(br.errorValues[Xr]||Wr(Jr))}fr.isValidCode=kr;function jr(Jr){var Xr;if(typeof Jr=="number")return Jr;if(Br(Jr))return(Xr=Jr.code)!==null&&Xr!==void 0?Xr:Jr.errorCode}fr.getErrorCode=jr;function Br(Jr){return typeof Jr=="object"&&Jr!==null&&(typeof Jr.code=="number"||typeof Jr.errorCode=="number")}function qr(Jr,{shouldIncludeStack:Xr=!1}={}){const En={};if(Jr&&typeof Jr=="object"&&!Array.isArray(Jr)&&Hr(Jr,"code")&&kr(Jr.code)){const wn=Jr;En.code=wn.code,wn.message&&typeof wn.message=="string"?(En.message=wn.message,Hr(wn,"data")&&(En.data=wn.data)):(En.message=Er(En.code),En.data={originalError:Vr(Jr)})}else En.code=br.standardErrorCodes.rpc.internal,En.message=Zr(Jr,"message")?Jr.message:wr,En.data={originalError:Vr(Jr)};return Xr&&(En.stack=Zr(Jr,"stack")?Jr.stack:void 0),En}fr.serialize=qr;function Wr(Jr){return Jr>=-32099&&Jr<=-32e3}function Vr(Jr){return Jr&&typeof Jr=="object"&&!Array.isArray(Jr)?Object.assign({},Jr):Jr}function Hr(Jr,Xr){return Object.prototype.hasOwnProperty.call(Jr,Xr)}function Zr(Jr,Xr){return typeof Jr=="object"&&Jr!==null&&Xr in Jr&&typeof Jr[Xr]=="string"}})(utils$1);Object.defineProperty(errors$1,"__esModule",{value:!0});errors$1.standardErrors=void 0;const constants_1$6=constants$2,utils_1$1=utils$1;errors$1.standardErrors={rpc:{parse:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.parse,fr),invalidRequest:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidRequest,fr),invalidParams:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidParams,fr),methodNotFound:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotFound,fr),internal:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.internal,fr),server:fr=>{if(!fr||typeof fr!="object"||Array.isArray(fr))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:br}=fr;if(!Number.isInteger(br)||br>-32005||br<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return getEthJsonRpcError(br,fr)},invalidInput:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.invalidInput,fr),resourceNotFound:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceNotFound,fr),resourceUnavailable:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.resourceUnavailable,fr),transactionRejected:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.transactionRejected,fr),methodNotSupported:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.methodNotSupported,fr),limitExceeded:fr=>getEthJsonRpcError(constants_1$6.standardErrorCodes.rpc.limitExceeded,fr)},provider:{userRejectedRequest:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.userRejectedRequest,fr),unauthorized:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unauthorized,fr),unsupportedMethod:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedMethod,fr),disconnected:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.disconnected,fr),chainDisconnected:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.chainDisconnected,fr),unsupportedChain:fr=>getEthProviderError(constants_1$6.standardErrorCodes.provider.unsupportedChain,fr),custom:fr=>{if(!fr||typeof fr!="object"||Array.isArray(fr))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:br,message:wr,data:Er}=fr;if(!wr||typeof wr!="string")throw new Error('"message" must be a nonempty string');return new EthereumProviderError(br,wr,Er)}}};function getEthJsonRpcError(fr,br){const[wr,Er]=parseOpts(br);return new EthereumRpcError(fr,wr||(0,utils_1$1.getMessageFromCode)(fr),Er)}function getEthProviderError(fr,br){const[wr,Er]=parseOpts(br);return new EthereumProviderError(fr,wr||(0,utils_1$1.getMessageFromCode)(fr),Er)}function parseOpts(fr){if(fr){if(typeof fr=="string")return[fr];if(typeof fr=="object"&&!Array.isArray(fr)){const{message:br,data:wr}=fr;if(br&&typeof br!="string")throw new Error("Must specify string message.");return[br||void 0,wr]}}return[]}class EthereumRpcError extends Error{constructor(br,wr,Er){if(!Number.isInteger(br))throw new Error('"code" must be an integer.');if(!wr||typeof wr!="string")throw new Error('"message" must be a nonempty string.');super(wr),this.code=br,Er!==void 0&&(this.data=Er)}}class EthereumProviderError extends EthereumRpcError{constructor(br,wr,Er){if(!isValidEthProviderCode(br))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(br,wr,Er)}}function isValidEthProviderCode(fr){return Number.isInteger(fr)&&fr>=1e3&&fr<=4999}(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.standardErrors=fr.standardErrorCodes=void 0;var br=constants$2;Object.defineProperty(fr,"standardErrorCodes",{enumerable:!0,get:function(){return br.standardErrorCodes}});var wr=errors$1;Object.defineProperty(fr,"standardErrors",{enumerable:!0,get:function(){return wr.standardErrors}})})(error);var serialize$1={},Web3Response={};Object.defineProperty(Web3Response,"__esModule",{value:!0});Web3Response.isErrorResponse=void 0;function isErrorResponse(fr){return fr.errorMessage!==void 0}Web3Response.isErrorResponse=isErrorResponse;var version$8={};Object.defineProperty(version$8,"__esModule",{value:!0});version$8.LIB_VERSION=void 0;version$8.LIB_VERSION="4.0.4";Object.defineProperty(serialize$1,"__esModule",{value:!0});serialize$1.serializeError=void 0;const Web3Response_1$2=Web3Response,version_1$3=version$8,constants_1$5=constants$2,utils_1=utils$1;function serializeError(fr,br){const wr=(0,utils_1.serialize)(getErrorObject(fr),{shouldIncludeStack:!0}),Er=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");Er.searchParams.set("version",version_1$3.LIB_VERSION),Er.searchParams.set("code",wr.code.toString());const kr=getMethod(wr.data,br);return kr&&Er.searchParams.set("method",kr),Er.searchParams.set("message",wr.message),Object.assign(Object.assign({},wr),{docUrl:Er.href})}serialize$1.serializeError=serializeError;function getErrorObject(fr){return typeof fr=="string"?{message:fr,code:constants_1$5.standardErrorCodes.rpc.internal}:(0,Web3Response_1$2.isErrorResponse)(fr)?Object.assign(Object.assign({},fr),{message:fr.errorMessage,code:fr.errorCode,data:{method:fr.method}}):fr}function getMethod(fr,br){const wr=fr==null?void 0:fr.method;if(wr)return wr;if(br!==void 0){if(typeof br=="string")return br;if(Array.isArray(br)){if(br.length>0)return br[0].method}else return br.method}}var type$3={};Object.defineProperty(type$3,"__esModule",{value:!0});type$3.RegExpString=type$3.IntNumber=type$3.BigIntString=type$3.AddressString=type$3.HexString=type$3.OpaqueType=void 0;function OpaqueType(){return fr=>fr}type$3.OpaqueType=OpaqueType;type$3.HexString=OpaqueType();type$3.AddressString=OpaqueType();type$3.BigIntString=OpaqueType();function IntNumber(fr){return Math.floor(fr)}type$3.IntNumber=IntNumber;type$3.RegExpString=OpaqueType();var util$6={};Object.defineProperty(util$6,"__esModule",{value:!0});util$6.areAddressArraysEqual=util$6.getFavicon=util$6.range=util$6.isBigNumber=util$6.ensureParsedJSONObject=util$6.ensureBigInt=util$6.ensureRegExpString=util$6.ensureIntNumber=util$6.ensureBuffer=util$6.ensureAddressString=util$6.ensureEvenLengthHexString=util$6.ensureHexString=util$6.isHexString=util$6.prepend0x=util$6.strip0x=util$6.has0xPrefix=util$6.hexStringFromIntNumber=util$6.intNumberFromHexString=util$6.bigIntStringFromBigInt=util$6.hexStringFromBuffer=util$6.hexStringToUint8Array=util$6.uint8ArrayToHex=util$6.randomBytesHex=void 0;const error_1$8=error,_1=type$3,INT_STRING_REGEX=/^[0-9]*$/,HEXADECIMAL_STRING_REGEX=/^[a-f0-9]*$/;function randomBytesHex(fr){return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(fr)))}util$6.randomBytesHex=randomBytesHex;function uint8ArrayToHex(fr){return[...fr].map(br=>br.toString(16).padStart(2,"0")).join("")}util$6.uint8ArrayToHex=uint8ArrayToHex;function hexStringToUint8Array(fr){return new Uint8Array(fr.match(/.{1,2}/g).map(br=>parseInt(br,16)))}util$6.hexStringToUint8Array=hexStringToUint8Array;function hexStringFromBuffer(fr,br=!1){const wr=fr.toString("hex");return(0,_1.HexString)(br?`0x${wr}`:wr)}util$6.hexStringFromBuffer=hexStringFromBuffer;function bigIntStringFromBigInt(fr){return(0,_1.BigIntString)(fr.toString(10))}util$6.bigIntStringFromBigInt=bigIntStringFromBigInt;function intNumberFromHexString(fr){return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(fr,!0))))}util$6.intNumberFromHexString=intNumberFromHexString;function hexStringFromIntNumber(fr){return(0,_1.HexString)(`0x${BigInt(fr).toString(16)}`)}util$6.hexStringFromIntNumber=hexStringFromIntNumber;function has0xPrefix(fr){return fr.startsWith("0x")||fr.startsWith("0X")}util$6.has0xPrefix=has0xPrefix;function strip0x(fr){return has0xPrefix(fr)?fr.slice(2):fr}util$6.strip0x=strip0x;function prepend0x(fr){return has0xPrefix(fr)?`0x${fr.slice(2)}`:`0x${fr}`}util$6.prepend0x=prepend0x;function isHexString$1(fr){if(typeof fr!="string")return!1;const br=strip0x(fr).toLowerCase();return HEXADECIMAL_STRING_REGEX.test(br)}util$6.isHexString=isHexString$1;function ensureHexString(fr,br=!1){if(typeof fr=="string"){const wr=strip0x(fr).toLowerCase();if(HEXADECIMAL_STRING_REGEX.test(wr))return(0,_1.HexString)(br?`0x${wr}`:wr)}throw error_1$8.standardErrors.rpc.invalidParams(`"${String(fr)}" is not a hexadecimal string`)}util$6.ensureHexString=ensureHexString;function ensureEvenLengthHexString(fr,br=!1){let wr=ensureHexString(fr,!1);return wr.length%2===1&&(wr=(0,_1.HexString)(`0${wr}`)),br?(0,_1.HexString)(`0x${wr}`):wr}util$6.ensureEvenLengthHexString=ensureEvenLengthHexString;function ensureAddressString(fr){if(typeof fr=="string"){const br=strip0x(fr).toLowerCase();if(isHexString$1(br)&&br.length===40)return(0,_1.AddressString)(prepend0x(br))}throw error_1$8.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(fr)}`)}util$6.ensureAddressString=ensureAddressString;function ensureBuffer(fr){if(Buffer$2.isBuffer(fr))return fr;if(typeof fr=="string"){if(isHexString$1(fr)){const br=ensureEvenLengthHexString(fr,!1);return Buffer$2.from(br,"hex")}return Buffer$2.from(fr,"utf8")}throw error_1$8.standardErrors.rpc.invalidParams(`Not binary data: ${String(fr)}`)}util$6.ensureBuffer=ensureBuffer;function ensureIntNumber(fr){if(typeof fr=="number"&&Number.isInteger(fr))return(0,_1.IntNumber)(fr);if(typeof fr=="string"){if(INT_STRING_REGEX.test(fr))return(0,_1.IntNumber)(Number(fr));if(isHexString$1(fr))return(0,_1.IntNumber)(Number(BigInt(ensureEvenLengthHexString(fr,!0))))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(fr)}`)}util$6.ensureIntNumber=ensureIntNumber;function ensureRegExpString(fr){if(fr instanceof RegExp)return(0,_1.RegExpString)(fr.toString());throw error_1$8.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(fr)}`)}util$6.ensureRegExpString=ensureRegExpString;function ensureBigInt(fr){if(fr!==null&&(typeof fr=="bigint"||isBigNumber(fr)))return BigInt(fr.toString(10));if(typeof fr=="number")return BigInt(ensureIntNumber(fr));if(typeof fr=="string"){if(INT_STRING_REGEX.test(fr))return BigInt(fr);if(isHexString$1(fr))return BigInt(ensureEvenLengthHexString(fr,!0))}throw error_1$8.standardErrors.rpc.invalidParams(`Not an integer: ${String(fr)}`)}util$6.ensureBigInt=ensureBigInt;function ensureParsedJSONObject(fr){if(typeof fr=="string")return JSON.parse(fr);if(typeof fr=="object")return fr;throw error_1$8.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(fr)}`)}util$6.ensureParsedJSONObject=ensureParsedJSONObject;function isBigNumber(fr){if(fr==null||typeof fr.constructor!="function")return!1;const{constructor:br}=fr;return typeof br.config=="function"&&typeof br.EUCLID=="number"}util$6.isBigNumber=isBigNumber;function range(fr,br){return Array.from({length:br-fr},(wr,Er)=>fr+Er)}util$6.range=range;function getFavicon(){const fr=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:br,host:wr}=document.location,Er=fr?fr.getAttribute("href"):null;return!Er||Er.startsWith("javascript:")||Er.startsWith("vbscript:")?null:Er.startsWith("http://")||Er.startsWith("https://")||Er.startsWith("data:")?Er:Er.startsWith("//")?br+Er:`${br}//${wr}${Er}`}util$6.getFavicon=getFavicon;function areAddressArraysEqual(fr,br){return fr.length===br.length&&fr.every((wr,Er)=>wr===br[Er])}util$6.areAddressArraysEqual=areAddressArraysEqual;var util$5={},SCWSigner$1={},SCWKeyManager$1={},cipher={};Object.defineProperty(cipher,"__esModule",{value:!0});cipher.decryptContent=cipher.encryptContent=cipher.importKeyFromHexString=cipher.exportKeyToHexString=cipher.decrypt=cipher.encrypt=cipher.deriveSharedSecret=cipher.generateKeyPair=void 0;const util_1$b=util$6;async function generateKeyPair(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}cipher.generateKeyPair=generateKeyPair;async function deriveSharedSecret(fr,br){return crypto.subtle.deriveKey({name:"ECDH",public:br},fr,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}cipher.deriveSharedSecret=deriveSharedSecret;async function encrypt(fr,br){const wr=crypto.getRandomValues(new Uint8Array(12)),Er=await crypto.subtle.encrypt({name:"AES-GCM",iv:wr},fr,new TextEncoder().encode(br));return{iv:wr,cipherText:Er}}cipher.encrypt=encrypt;async function decrypt(fr,{iv:br,cipherText:wr}){const Er=await crypto.subtle.decrypt({name:"AES-GCM",iv:br},fr,wr);return new TextDecoder().decode(Er)}cipher.decrypt=decrypt;function getFormat(fr){switch(fr){case"public":return"spki";case"private":return"pkcs8"}}async function exportKeyToHexString(fr,br){const wr=getFormat(fr),Er=await crypto.subtle.exportKey(wr,br);return(0,util_1$b.uint8ArrayToHex)(new Uint8Array(Er))}cipher.exportKeyToHexString=exportKeyToHexString;async function importKeyFromHexString(fr,br){const wr=getFormat(fr),Er=(0,util_1$b.hexStringToUint8Array)(br).buffer;return await crypto.subtle.importKey(wr,Er,{name:"ECDH",namedCurve:"P-256"},!0,fr==="private"?["deriveKey"]:[])}cipher.importKeyFromHexString=importKeyFromHexString;async function encryptContent(fr,br){const wr=JSON.stringify(fr,(Er,kr)=>{if(!(kr instanceof Error))return kr;const jr=kr;return Object.assign(Object.assign({},jr.code?{code:jr.code}:{}),{message:jr.message})});return encrypt(br,wr)}cipher.encryptContent=encryptContent;async function decryptContent(fr,br){return JSON.parse(await decrypt(br,fr))}cipher.decryptContent=decryptContent;var ScopedLocalStorage$1={};Object.defineProperty(ScopedLocalStorage$1,"__esModule",{value:!0});ScopedLocalStorage$1.ScopedLocalStorage=void 0;class ScopedLocalStorage{constructor(br,wr){this.scope=br,this.module=wr}setItem(br,wr){localStorage.setItem(this.scopedKey(br),wr)}getItem(br){return localStorage.getItem(this.scopedKey(br))}removeItem(br){localStorage.removeItem(this.scopedKey(br))}clear(){const br=this.scopedKey(""),wr=[];for(let Er=0;ErlocalStorage.removeItem(Er))}scopedKey(br){return`-${this.scope}${this.module?`:${this.module}`:""}:${br}`}static clearAll(){new ScopedLocalStorage("CBWSDK").clear(),new ScopedLocalStorage("walletlink").clear()}}ScopedLocalStorage$1.ScopedLocalStorage=ScopedLocalStorage;Object.defineProperty(SCWKeyManager$1,"__esModule",{value:!0});SCWKeyManager$1.SCWKeyManager=void 0;const cipher_1$1=cipher,ScopedLocalStorage_1$6=ScopedLocalStorage$1,OWN_PRIVATE_KEY={storageKey:"ownPrivateKey",keyType:"private"},OWN_PUBLIC_KEY={storageKey:"ownPublicKey",keyType:"public"},PEER_PUBLIC_KEY={storageKey:"peerPublicKey",keyType:"public"};class SCWKeyManager{constructor(){this.storage=new ScopedLocalStorage_1$6.ScopedLocalStorage("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(br){this.sharedSecret=null,this.peerPublicKey=br,await this.storeKey(PEER_PUBLIC_KEY,br),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(OWN_PUBLIC_KEY.storageKey),this.storage.removeItem(OWN_PRIVATE_KEY.storageKey),this.storage.removeItem(PEER_PUBLIC_KEY.storageKey)}async generateKeyPair(){const br=await(0,cipher_1$1.generateKeyPair)();this.ownPrivateKey=br.privateKey,this.ownPublicKey=br.publicKey,await this.storeKey(OWN_PRIVATE_KEY,br.privateKey),await this.storeKey(OWN_PUBLIC_KEY,br.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(OWN_PRIVATE_KEY)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(OWN_PUBLIC_KEY)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(PEER_PUBLIC_KEY)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await(0,cipher_1$1.deriveSharedSecret)(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(br){const wr=this.storage.getItem(br.storageKey);return wr?(0,cipher_1$1.importKeyFromHexString)(br.keyType,wr):null}async storeKey(br,wr){const Er=await(0,cipher_1$1.exportKeyToHexString)(br.keyType,wr);this.storage.setItem(br.storageKey,Er)}}SCWKeyManager$1.SCWKeyManager=SCWKeyManager;var SCWStateManager$1={};Object.defineProperty(SCWStateManager$1,"__esModule",{value:!0});SCWStateManager$1.SCWStateManager=void 0;const ScopedLocalStorage_1$5=ScopedLocalStorage$1,ACCOUNTS_KEY="accounts",ACTIVE_CHAIN_STORAGE_KEY="activeChain",AVAILABLE_CHAINS_STORAGE_KEY="availableChains",WALLET_CAPABILITIES_STORAGE_KEY="walletCapabilities";class SCWStateManager{get accounts(){return this._accounts}get activeChain(){return this._activeChain}get walletCapabilities(){return this._walletCapabilities}constructor(br){var wr,Er;this.storage=new ScopedLocalStorage_1$5.ScopedLocalStorage("CBWSDK","SCWStateManager"),this.updateListener=br.updateListener,this.availableChains=this.loadItemFromStorage(AVAILABLE_CHAINS_STORAGE_KEY),this._walletCapabilities=this.loadItemFromStorage(WALLET_CAPABILITIES_STORAGE_KEY);const kr=this.loadItemFromStorage(ACCOUNTS_KEY),jr=this.loadItemFromStorage(ACTIVE_CHAIN_STORAGE_KEY);kr&&this.updateListener.onAccountsUpdate({accounts:kr,source:"storage"}),jr&&this.updateListener.onChainUpdate({chain:jr,source:"storage"}),this._accounts=kr||[],this._activeChain=jr||{id:(Er=(wr=br.appChainIds)===null||wr===void 0?void 0:wr[0])!==null&&Er!==void 0?Er:1}}updateAccounts(br){this._accounts=br,this.storeItemToStorage(ACCOUNTS_KEY,br),this.updateListener.onAccountsUpdate({accounts:br,source:"wallet"})}switchChain(br){var wr;const Er=(wr=this.availableChains)===null||wr===void 0?void 0:wr.find(kr=>kr.id===br);return Er?(Er===this._activeChain||(this._activeChain=Er,this.storeItemToStorage(ACTIVE_CHAIN_STORAGE_KEY,Er),this.updateListener.onChainUpdate({chain:Er,source:"wallet"})),!0):!1}updateAvailableChains(br){if(!br||Object.keys(br).length===0)return;const wr=Object.entries(br).map(([Er,kr])=>({id:Number(Er),rpcUrl:kr}));this.availableChains=wr,this.storeItemToStorage(AVAILABLE_CHAINS_STORAGE_KEY,wr),this.switchChain(this._activeChain.id)}updateWalletCapabilities(br){this._walletCapabilities=br,this.storeItemToStorage(WALLET_CAPABILITIES_STORAGE_KEY,br)}storeItemToStorage(br,wr){this.storage.setItem(br,JSON.stringify(wr))}loadItemFromStorage(br){const wr=this.storage.getItem(br);return wr?JSON.parse(wr):void 0}clear(){this.storage.clear()}}SCWStateManager$1.SCWStateManager=SCWStateManager;Object.defineProperty(SCWSigner$1,"__esModule",{value:!0});SCWSigner$1.SCWSigner=void 0;const SCWKeyManager_1=SCWKeyManager$1,SCWStateManager_1=SCWStateManager$1,error_1$7=error,util_1$a=util$6,cipher_1=cipher;class SCWSigner{constructor(br){this.metadata=br.metadata,this.communicator=br.communicator,this.keyManager=new SCWKeyManager_1.SCWKeyManager,this.stateManager=new SCWStateManager_1.SCWStateManager({appChainIds:this.metadata.appChainIds,updateListener:br.updateListener}),this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(){const br=await this.createRequestMessage({handshake:{method:"eth_requestAccounts",params:this.metadata}}),wr=await this.communicator.postRequestAndWaitForResponse(br);if("failure"in wr.content)throw wr.content.failure;const Er=await(0,cipher_1.importKeyFromHexString)("public",wr.sender);await this.keyManager.setPeerPublicKey(Er);const kr=await this.decryptResponseMessage(wr);this.updateInternalState({method:"eth_requestAccounts"},kr);const jr=kr.result;if("error"in jr)throw jr.error;return this.stateManager.accounts}async request(br){const wr=this.tryLocalHandling(br);if(wr!==void 0){if(wr instanceof Error)throw wr;return wr}await this.communicator.waitForPopupLoaded();const Er=await this.sendEncryptedRequest(br),kr=await this.decryptResponseMessage(Er);this.updateInternalState(br,kr);const jr=kr.result;if("error"in jr)throw jr.error;return jr.value}async disconnect(){this.stateManager.clear(),await this.keyManager.clear()}tryLocalHandling(br){var wr;switch(br.method){case"wallet_switchEthereumChain":{const Er=br.params;if(!Er||!(!((wr=Er[0])===null||wr===void 0)&&wr.chainId))throw error_1$7.standardErrors.rpc.invalidParams();const kr=(0,util_1$a.ensureIntNumber)(Er[0].chainId);return this.stateManager.switchChain(kr)?null:void 0}case"wallet_getCapabilities":{const Er=this.stateManager.walletCapabilities;if(!Er)throw error_1$7.standardErrors.provider.unauthorized("No wallet capabilities found, please disconnect and reconnect");return Er}default:return}}async sendEncryptedRequest(br){const wr=await this.keyManager.getSharedSecret();if(!wr)throw error_1$7.standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");const Er=await(0,cipher_1.encryptContent)({action:br,chainId:this.stateManager.activeChain.id},wr),kr=await this.createRequestMessage({encrypted:Er});return this.communicator.postRequestAndWaitForResponse(kr)}async createRequestMessage(br){const wr=await(0,cipher_1.exportKeyToHexString)("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:wr,content:br,timestamp:new Date}}async decryptResponseMessage(br){const wr=br.content;if("failure"in wr)throw wr.failure;const Er=await this.keyManager.getSharedSecret();if(!Er)throw error_1$7.standardErrors.provider.unauthorized("Invalid session");return(0,cipher_1.decryptContent)(wr.encrypted,Er)}updateInternalState(br,wr){var Er,kr;const jr=(Er=wr.data)===null||Er===void 0?void 0:Er.chains;jr&&this.stateManager.updateAvailableChains(jr);const Br=(kr=wr.data)===null||kr===void 0?void 0:kr.capabilities;Br&&this.stateManager.updateWalletCapabilities(Br);const qr=wr.result;if(!("error"in qr))switch(br.method){case"eth_requestAccounts":{const Wr=qr.value;this.stateManager.updateAccounts(Wr);break}case"wallet_switchEthereumChain":{if(qr.value!==null)return;const Wr=br.params,Vr=(0,util_1$a.ensureIntNumber)(Wr[0].chainId);this.stateManager.switchChain(Vr);break}}}}SCWSigner$1.SCWSigner=SCWSigner;var WalletLinkSigner$1={};const{Transform:Transform$1}=requireReadableBrowser$1();var keccak$2=fr=>class dS extends Transform$1{constructor(wr,Er,kr,jr,Br){super(Br),this._rate=wr,this._capacity=Er,this._delimitedSuffix=kr,this._hashBitLength=jr,this._options=Br,this._state=new fr,this._state.initialize(wr,Er),this._finalized=!1}_transform(wr,Er,kr){let jr=null;try{this.update(wr,Er)}catch(Br){jr=Br}kr(jr)}_flush(wr){let Er=null;try{this.push(this.digest())}catch(kr){Er=kr}wr(Er)}update(wr,Er){if(!Buffer$2.isBuffer(wr)&&typeof wr!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer$2.isBuffer(wr)||(wr=Buffer$2.from(wr,Er)),this._state.absorb(wr),this}digest(wr){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let Er=this._state.squeeze(this._hashBitLength/8);return wr!==void 0&&(Er=Er.toString(wr)),this._resetState(),Er}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const wr=new dS(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(wr._state),wr._finalized=this._finalized,wr}};const{Transform}=requireReadableBrowser$1();var shake=fr=>class fS extends Transform{constructor(wr,Er,kr,jr){super(jr),this._rate=wr,this._capacity=Er,this._delimitedSuffix=kr,this._options=jr,this._state=new fr,this._state.initialize(wr,Er),this._finalized=!1}_transform(wr,Er,kr){let jr=null;try{this.update(wr,Er)}catch(Br){jr=Br}kr(jr)}_flush(){}_read(wr){this.push(this.squeeze(wr))}update(wr,Er){if(!Buffer$2.isBuffer(wr)&&typeof wr!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer$2.isBuffer(wr)||(wr=Buffer$2.from(wr,Er)),this._state.absorb(wr),this}squeeze(wr,Er){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let kr=this._state.squeeze(wr);return Er!==void 0&&(kr=kr.toString(Er)),kr}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const wr=new fS(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(wr._state),wr._finalized=this._finalized,wr}};const createKeccak=keccak$2,createShake=shake;var api=function(fr){const br=createKeccak(fr),wr=createShake(fr);return function(Er,kr){switch(typeof Er=="string"?Er.toLowerCase():Er){case"keccak224":return new br(1152,448,null,224,kr);case"keccak256":return new br(1088,512,null,256,kr);case"keccak384":return new br(832,768,null,384,kr);case"keccak512":return new br(576,1024,null,512,kr);case"sha3-224":return new br(1152,448,6,224,kr);case"sha3-256":return new br(1088,512,6,256,kr);case"sha3-384":return new br(832,768,6,384,kr);case"sha3-512":return new br(576,1024,6,512,kr);case"shake128":return new wr(1344,256,31,kr);case"shake256":return new wr(1088,512,31,kr);default:throw new Error("Invald algorithm: "+Er)}}},keccakStateUnroll={};const P1600_ROUND_CONSTANTS=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];keccakStateUnroll.p1600=function(fr){for(let br=0;br<24;++br){const wr=fr[0]^fr[10]^fr[20]^fr[30]^fr[40],Er=fr[1]^fr[11]^fr[21]^fr[31]^fr[41],kr=fr[2]^fr[12]^fr[22]^fr[32]^fr[42],jr=fr[3]^fr[13]^fr[23]^fr[33]^fr[43],Br=fr[4]^fr[14]^fr[24]^fr[34]^fr[44],qr=fr[5]^fr[15]^fr[25]^fr[35]^fr[45],Wr=fr[6]^fr[16]^fr[26]^fr[36]^fr[46],Vr=fr[7]^fr[17]^fr[27]^fr[37]^fr[47],Hr=fr[8]^fr[18]^fr[28]^fr[38]^fr[48],Zr=fr[9]^fr[19]^fr[29]^fr[39]^fr[49];let Jr=Hr^(kr<<1|jr>>>31),Xr=Zr^(jr<<1|kr>>>31);const En=fr[0]^Jr,wn=fr[1]^Xr,$n=fr[10]^Jr,Tn=fr[11]^Xr,In=fr[20]^Jr,jn=fr[21]^Xr,Yn=fr[30]^Jr,ga=fr[31]^Xr,na=fr[40]^Jr,_i=fr[41]^Xr;Jr=wr^(Br<<1|qr>>>31),Xr=Er^(qr<<1|Br>>>31);const ro=fr[2]^Jr,to=fr[3]^Xr,io=fr[12]^Jr,no=fr[13]^Xr,$a=fr[22]^Jr,Rn=fr[23]^Xr,Gr=fr[32]^Jr,Yr=fr[33]^Xr,Sn=fr[42]^Jr,An=fr[43]^Xr;Jr=kr^(Wr<<1|Vr>>>31),Xr=jr^(Vr<<1|Wr>>>31);const Pn=fr[4]^Jr,Nn=fr[5]^Xr,zn=fr[14]^Jr,On=fr[15]^Xr,_n=fr[24]^Jr,Zn=fr[25]^Xr,oo=fr[34]^Jr,uo=fr[35]^Xr,lo=fr[44]^Jr,co=fr[45]^Xr;Jr=Br^(Hr<<1|Zr>>>31),Xr=qr^(Zr<<1|Hr>>>31);const so=fr[6]^Jr,yo=fr[7]^Xr,fo=fr[16]^Jr,ho=fr[17]^Xr,vo=fr[26]^Jr,Io=fr[27]^Xr,Ro=fr[36]^Jr,To=fr[37]^Xr,Wo=fr[46]^Jr,qo=fr[47]^Xr;Jr=Wr^(wr<<1|Er>>>31),Xr=Vr^(Er<<1|wr>>>31);const Zo=fr[8]^Jr,Qo=fr[9]^Xr,jo=fr[18]^Jr,No=fr[19]^Xr,Tl=fr[28]^Jr,Fo=fr[29]^Xr,Lo=fr[38]^Jr,Rl=fr[39]^Xr,_c=fr[48]^Jr,Ko=fr[49]^Xr,zl=En,Sl=wn,Eo=Tn<<4|$n>>>28,bo=$n<<4|Tn>>>28,go=In<<3|jn>>>29,Co=jn<<3|In>>>29,zo=ga<<9|Yn>>>23,Do=Yn<<9|ga>>>23,Uo=na<<18|_i>>>14,ru=_i<<18|na>>>14,Dl=ro<<1|to>>>31,xl=to<<1|ro>>>31,bu=no<<12|io>>>20,yl=io<<12|no>>>20,Il=$a<<10|Rn>>>22,cu=Rn<<10|$a>>>22,Bl=Yr<<13|Gr>>>19,Pl=Gr<<13|Yr>>>19,wu=Sn<<2|An>>>30,Ol=An<<2|Sn>>>30,Nl=Nn<<30|Pn>>>2,Tu=Pn<<30|Nn>>>2,Ul=zn<<6|On>>>26,Cl=On<<6|zn>>>26,gu=Zn<<11|_n>>>21,wo=_n<<11|Zn>>>21,$o=oo<<15|uo>>>17,Ao=uo<<15|oo>>>17,po=co<<29|lo>>>3,So=lo<<29|co>>>3,Jo=so<<28|yo>>>4,Bo=yo<<28|so>>>4,Ho=ho<<23|fo>>>9,Wl=fo<<23|ho>>>9,El=vo<<25|Io>>>7,$l=Io<<25|vo>>>7,Su=Ro<<21|To>>>11,nu=To<<21|Ro>>>11,pu=qo<<24|Wo>>>8,mu=Wo<<24|qo>>>8,hu=Zo<<27|Qo>>>5,yu=Qo<<27|Zo>>>5,_u=jo<<20|No>>>12,fu=No<<20|jo>>>12,vu=Fo<<7|Tl>>>25,iu=Tl<<7|Fo>>>25,su=Lo<<8|Rl>>>24,tu=Rl<<8|Lo>>>24,Hl=_c<<14|Ko>>>18,Zl=Ko<<14|_c>>>18;fr[0]=zl^~bu&gu,fr[1]=Sl^~yl&wo,fr[10]=Jo^~_u&go,fr[11]=Bo^~fu&Co,fr[20]=Dl^~Ul&El,fr[21]=xl^~Cl&$l,fr[30]=hu^~Eo&Il,fr[31]=yu^~bo&cu,fr[40]=Nl^~Ho&vu,fr[41]=Tu^~Wl&iu,fr[2]=bu^~gu&Su,fr[3]=yl^~wo&nu,fr[12]=_u^~go&Bl,fr[13]=fu^~Co&Pl,fr[22]=Ul^~El&su,fr[23]=Cl^~$l&tu,fr[32]=Eo^~Il&$o,fr[33]=bo^~cu&Ao,fr[42]=Ho^~vu&zo,fr[43]=Wl^~iu&Do,fr[4]=gu^~Su&Hl,fr[5]=wo^~nu&Zl,fr[14]=go^~Bl&po,fr[15]=Co^~Pl&So,fr[24]=El^~su&Uo,fr[25]=$l^~tu&ru,fr[34]=Il^~$o&pu,fr[35]=cu^~Ao&mu,fr[44]=vu^~zo&wu,fr[45]=iu^~Do&Ol,fr[6]=Su^~Hl&zl,fr[7]=nu^~Zl&Sl,fr[16]=Bl^~po&Jo,fr[17]=Pl^~So&Bo,fr[26]=su^~Uo&Dl,fr[27]=tu^~ru&xl,fr[36]=$o^~pu&hu,fr[37]=Ao^~mu&yu,fr[46]=zo^~wu&Nl,fr[47]=Do^~Ol&Tu,fr[8]=Hl^~zl&bu,fr[9]=Zl^~Sl&yl,fr[18]=po^~Jo&_u,fr[19]=So^~Bo&fu,fr[28]=Uo^~Dl&Ul,fr[29]=ru^~xl&Cl,fr[38]=pu^~hu&Eo,fr[39]=mu^~yu&bo,fr[48]=wu^~Nl&Ho,fr[49]=Ol^~Tu&Wl,fr[0]^=P1600_ROUND_CONSTANTS[br*2],fr[1]^=P1600_ROUND_CONSTANTS[br*2+1]}};const keccakState=keccakStateUnroll;function Keccak(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Keccak.prototype.initialize=function(fr,br){for(let wr=0;wr<50;++wr)this.state[wr]=0;this.blockSize=fr/8,this.count=0,this.squeezing=!1};Keccak.prototype.absorb=function(fr){for(let br=0;br>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(keccakState.p1600(this.state),this.count=0);return br};Keccak.prototype.copy=function(fr){for(let br=0;br<50;++br)fr.state[br]=this.state[br];fr.blockSize=this.blockSize,fr.count=this.count,fr.squeezing=this.squeezing};var keccak$1=Keccak,js=api(keccak$1);const createKeccakHash=js;function zeros(fr){return Buffer$2.allocUnsafe(fr).fill(0)}function bitLengthFromBigInt(fr){return fr.toString(2).length}function bufferBEFromBigInt(fr,br){let wr=fr.toString(16);wr.length%2!==0&&(wr="0"+wr);const Er=wr.match(/.{1,2}/g).map(kr=>parseInt(kr,16));for(;Er.length"u")throw new Error("Not an array?");if(wr=parseTypeArray(fr),wr!=="dynamic"&&wr!==0&&br.length>wr)throw new Error("Elements exceed array size: "+wr);kr=[],fr=fr.slice(0,fr.lastIndexOf("[")),typeof br=="string"&&(br=JSON.parse(br));for(jr in br)kr.push(encodeSingle(fr,br[jr]));if(wr==="dynamic"){var Br=encodeSingle("uint256",br.length);kr.unshift(Br)}return Buffer$2.concat(kr)}else{if(fr==="bytes")return br=new Buffer$2(br),kr=Buffer$2.concat([encodeSingle("uint256",br.length),br]),br.length%32!==0&&(kr=Buffer$2.concat([kr,util$3.zeros(32-br.length%32)])),kr;if(fr.startsWith("bytes")){if(wr=parseTypeN(fr),wr<1||wr>32)throw new Error("Invalid bytes width: "+wr);return util$3.setLengthRight(br,32)}else if(fr.startsWith("uint")){if(wr=parseTypeN(fr),wr%8||wr<8||wr>256)throw new Error("Invalid uint width: "+wr);Er=parseNumber(br);const qr=util$3.bitLengthFromBigInt(Er);if(qr>wr)throw new Error("Supplied uint exceeds width: "+wr+" vs "+qr);if(Er<0)throw new Error("Supplied uint is negative");return util$3.bufferBEFromBigInt(Er,32)}else if(fr.startsWith("int")){if(wr=parseTypeN(fr),wr%8||wr<8||wr>256)throw new Error("Invalid int width: "+wr);Er=parseNumber(br);const qr=util$3.bitLengthFromBigInt(Er);if(qr>wr)throw new Error("Supplied int exceeds width: "+wr+" vs "+qr);const Wr=util$3.twosFromBigInt(Er,256);return util$3.bufferBEFromBigInt(Wr,32)}else if(fr.startsWith("ufixed")){if(wr=parseTypeNxM(fr),Er=parseNumber(br),Er<0)throw new Error("Supplied ufixed is negative");return encodeSingle("uint256",Er*BigInt(2)**BigInt(wr[1]))}else if(fr.startsWith("fixed"))return wr=parseTypeNxM(fr),encodeSingle("int256",parseNumber(br)*BigInt(2)**BigInt(wr[1]))}throw new Error("Unsupported or invalid type: "+fr)}function isDynamic(fr){return fr==="string"||fr==="bytes"||parseTypeArray(fr)==="dynamic"}function isArray(fr){return fr.lastIndexOf("]")===fr.length-1}function rawEncode(fr,br){var wr=[],Er=[],kr=32*fr.length;for(var jr in fr){var Br=elementaryName(fr[jr]),qr=br[jr],Wr=encodeSingle(Br,qr);isDynamic(Br)?(wr.push(encodeSingle("uint256",kr)),Er.push(Wr),kr+=Wr.length):wr.push(Wr)}return Buffer$2.concat(wr.concat(Er))}function solidityPack(fr,br){if(fr.length!==br.length)throw new Error("Number of types are not matching the values");for(var wr,Er,kr=[],jr=0;jr32)throw new Error("Invalid bytes width: "+wr);kr.push(util$3.setLengthRight(qr,wr))}else if(Br.startsWith("uint")){if(wr=parseTypeN(Br),wr%8||wr<8||wr>256)throw new Error("Invalid uint width: "+wr);Er=parseNumber(qr);const Wr=util$3.bitLengthFromBigInt(Er);if(Wr>wr)throw new Error("Supplied uint exceeds width: "+wr+" vs "+Wr);kr.push(util$3.bufferBEFromBigInt(Er,wr/8))}else if(Br.startsWith("int")){if(wr=parseTypeN(Br),wr%8||wr<8||wr>256)throw new Error("Invalid int width: "+wr);Er=parseNumber(qr);const Wr=util$3.bitLengthFromBigInt(Er);if(Wr>wr)throw new Error("Supplied int exceeds width: "+wr+" vs "+Wr);const Vr=util$3.twosFromBigInt(Er,wr);kr.push(util$3.bufferBEFromBigInt(Vr,wr/8))}else throw new Error("Unsupported or invalid type: "+Br)}return Buffer$2.concat(kr)}function soliditySHA3(fr,br){return util$3.keccak(solidityPack(fr,br))}var abi$1={rawEncode,solidityPack,soliditySHA3};const util$2=util$4,abi=abi$1,TYPED_MESSAGE_SCHEMA={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},TypedDataUtils={encodeData(fr,br,wr,Er=!0){const kr=["bytes32"],jr=[this.hashType(fr,wr)];if(Er){const Br=(qr,Wr,Vr)=>{if(wr[Wr]!==void 0)return["bytes32",Vr==null?"0x0000000000000000000000000000000000000000000000000000000000000000":util$2.keccak(this.encodeData(Wr,Vr,wr,Er))];if(Vr===void 0)throw new Error(`missing value for field ${qr} of type ${Wr}`);if(Wr==="bytes")return["bytes32",util$2.keccak(Vr)];if(Wr==="string")return typeof Vr=="string"&&(Vr=Buffer$2.from(Vr,"utf8")),["bytes32",util$2.keccak(Vr)];if(Wr.lastIndexOf("]")===Wr.length-1){const Hr=Wr.slice(0,Wr.lastIndexOf("[")),Zr=Vr.map(Jr=>Br(qr,Hr,Jr));return["bytes32",util$2.keccak(abi.rawEncode(Zr.map(([Jr])=>Jr),Zr.map(([,Jr])=>Jr)))]}return[Wr,Vr]};for(const qr of wr[fr]){const[Wr,Vr]=Br(qr.name,qr.type,br[qr.name]);kr.push(Wr),jr.push(Vr)}}else for(const Br of wr[fr]){let qr=br[Br.name];if(qr!==void 0)if(Br.type==="bytes")kr.push("bytes32"),qr=util$2.keccak(qr),jr.push(qr);else if(Br.type==="string")kr.push("bytes32"),typeof qr=="string"&&(qr=Buffer$2.from(qr,"utf8")),qr=util$2.keccak(qr),jr.push(qr);else if(wr[Br.type]!==void 0)kr.push("bytes32"),qr=util$2.keccak(this.encodeData(Br.type,qr,wr,Er)),jr.push(qr);else{if(Br.type.lastIndexOf("]")===Br.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");kr.push(Br.type),jr.push(qr)}}return abi.rawEncode(kr,jr)},encodeType(fr,br){let wr="",Er=this.findTypeDependencies(fr,br).filter(kr=>kr!==fr);Er=[fr].concat(Er.sort());for(const kr of Er){if(!br[kr])throw new Error("No type definition specified: "+kr);wr+=kr+"("+br[kr].map(({name:Br,type:qr})=>qr+" "+Br).join(",")+")"}return wr},findTypeDependencies(fr,br,wr=[]){if(fr=fr.match(/^\w*/)[0],wr.includes(fr)||br[fr]===void 0)return wr;wr.push(fr);for(const Er of br[fr])for(const kr of this.findTypeDependencies(Er.type,br,wr))!wr.includes(kr)&&wr.push(kr);return wr},hashStruct(fr,br,wr,Er=!0){return util$2.keccak(this.encodeData(fr,br,wr,Er))},hashType(fr,br){return util$2.keccak(this.encodeType(fr,br))},sanitizeData(fr){const br={};for(const wr in TYPED_MESSAGE_SCHEMA.properties)fr[wr]&&(br[wr]=fr[wr]);return br.types&&(br.types=Object.assign({EIP712Domain:[]},br.types)),br},hash(fr,br=!0){const wr=this.sanitizeData(fr),Er=[Buffer$2.from("1901","hex")];return Er.push(this.hashStruct("EIP712Domain",wr.domain,wr.types,br)),wr.primaryType!=="EIP712Domain"&&Er.push(this.hashStruct(wr.primaryType,wr.message,wr.types,br)),util$2.keccak(Buffer$2.concat(Er))}};var ethEip712Util={TYPED_MESSAGE_SCHEMA,TypedDataUtils,hashForSignTypedDataLegacy:function(fr){return typedSignatureHashLegacy(fr.data)},hashForSignTypedData_v3:function(fr){return TypedDataUtils.hash(fr.data,!1)},hashForSignTypedData_v4:function(fr){return TypedDataUtils.hash(fr.data)}};function typedSignatureHashLegacy(fr){const br=new Error("Expect argument to be non-empty array");if(typeof fr!="object"||!fr.length)throw br;const wr=fr.map(function(jr){return jr.type==="bytes"?util$2.toBuffer(jr.value):jr.value}),Er=fr.map(function(jr){return jr.type}),kr=fr.map(function(jr){if(!jr.name)throw br;return jr.type+" "+jr.name});return abi.soliditySHA3(["bytes32","bytes32"],[abi.soliditySHA3(new Array(fr.length).fill("string"),kr),abi.soliditySHA3(Er,wr)])}var constants$1={};Object.defineProperty(constants$1,"__esModule",{value:!0});constants$1.APP_VERSION_KEY=constants$1.LOCAL_STORAGE_ADDRESSES_KEY=constants$1.WALLET_USER_NAME_KEY=void 0;constants$1.WALLET_USER_NAME_KEY="walletUsername";constants$1.LOCAL_STORAGE_ADDRESSES_KEY="Addresses";constants$1.APP_VERSION_KEY="AppVersion";var RelayEventManager$1={};Object.defineProperty(RelayEventManager$1,"__esModule",{value:!0});RelayEventManager$1.RelayEventManager=void 0;const util_1$9=util$6;class RelayEventManager{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const br=this._nextRequestId,wr=(0,util_1$9.prepend0x)(br.toString(16));return this.callbacks.get(wr)&&this.callbacks.delete(wr),br}}RelayEventManager$1.RelayEventManager=RelayEventManager;var WalletLinkRelay$1={},WalletLinkConnection$1={},WalletLinkCipher$1={};Object.defineProperty(WalletLinkCipher$1,"__esModule",{value:!0});WalletLinkCipher$1.WalletLinkCipher=void 0;const util_1$8=util$6;class WalletLinkCipher{constructor(br){this.secret=br}async encrypt(br){const wr=this.secret;if(wr.length!==64)throw Error("secret must be 256 bits");const Er=crypto.getRandomValues(new Uint8Array(12)),kr=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(wr),{name:"aes-gcm"},!1,["encrypt","decrypt"]),jr=new TextEncoder,Br=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Er},kr,jr.encode(br)),qr=16,Wr=Br.slice(Br.byteLength-qr),Vr=Br.slice(0,Br.byteLength-qr),Hr=new Uint8Array(Wr),Zr=new Uint8Array(Vr),Jr=new Uint8Array([...Er,...Hr,...Zr]);return(0,util_1$8.uint8ArrayToHex)(Jr)}async decrypt(br){const wr=this.secret;if(wr.length!==64)throw Error("secret must be 256 bits");return new Promise((Er,kr)=>{(async function(){const jr=await crypto.subtle.importKey("raw",(0,util_1$8.hexStringToUint8Array)(wr),{name:"aes-gcm"},!1,["encrypt","decrypt"]),Br=(0,util_1$8.hexStringToUint8Array)(br),qr=Br.slice(0,12),Wr=Br.slice(12,28),Vr=Br.slice(28),Hr=new Uint8Array([...Vr,...Wr]),Zr={name:"AES-GCM",iv:new Uint8Array(qr)};try{const Jr=await window.crypto.subtle.decrypt(Zr,jr,Hr),Xr=new TextDecoder;Er(Xr.decode(Jr))}catch(Jr){kr(Jr)}})()})}}WalletLinkCipher$1.WalletLinkCipher=WalletLinkCipher;var WalletLinkHTTP$1={};Object.defineProperty(WalletLinkHTTP$1,"__esModule",{value:!0});WalletLinkHTTP$1.WalletLinkHTTP=void 0;class WalletLinkHTTP{constructor(br,wr,Er){this.linkAPIUrl=br,this.sessionId=wr;const kr=`${wr}:${Er}`;this.auth=`Basic ${btoa(kr)}`}async markUnseenEventsAsSeen(br){return Promise.all(br.map(wr=>fetch(`${this.linkAPIUrl}/events/${wr.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(wr=>console.error("Unabled to mark event as failed:",wr))}async fetchUnseenEvents(){var br;const wr=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(wr.ok){const{events:Er,error:kr}=await wr.json();if(kr)throw new Error(`Check unseen events failed: ${kr}`);const jr=(br=Er==null?void 0:Er.filter(Br=>Br.event==="Web3Response").map(Br=>({type:"Event",sessionId:this.sessionId,eventId:Br.id,event:Br.event,data:Br.data})))!==null&&br!==void 0?br:[];return this.markUnseenEventsAsSeen(jr),jr}throw new Error(`Check unseen events failed: ${wr.status}`)}}WalletLinkHTTP$1.WalletLinkHTTP=WalletLinkHTTP;var WalletLinkWebSocket$1={};Object.defineProperty(WalletLinkWebSocket$1,"__esModule",{value:!0});WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket$1.ConnectionState=void 0;var ConnectionState;(function(fr){fr[fr.DISCONNECTED=0]="DISCONNECTED",fr[fr.CONNECTING=1]="CONNECTING",fr[fr.CONNECTED=2]="CONNECTED"})(ConnectionState||(WalletLinkWebSocket$1.ConnectionState=ConnectionState={}));class WalletLinkWebSocket{setConnectionStateListener(br){this.connectionStateListener=br}setIncomingDataListener(br){this.incomingDataListener=br}constructor(br,wr=WebSocket){this.WebSocketClass=wr,this.webSocket=null,this.pendingData=[],this.url=br.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((br,wr)=>{var Er;let kr;try{this.webSocket=kr=new this.WebSocketClass(this.url)}catch(jr){wr(jr);return}(Er=this.connectionStateListener)===null||Er===void 0||Er.call(this,ConnectionState.CONNECTING),kr.onclose=jr=>{var Br;this.clearWebSocket(),wr(new Error(`websocket error ${jr.code}: ${jr.reason}`)),(Br=this.connectionStateListener)===null||Br===void 0||Br.call(this,ConnectionState.DISCONNECTED)},kr.onopen=jr=>{var Br;br(),(Br=this.connectionStateListener)===null||Br===void 0||Br.call(this,ConnectionState.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(Wr=>this.sendData(Wr)),this.pendingData=[])},kr.onmessage=jr=>{var Br,qr;if(jr.data==="h")(Br=this.incomingDataListener)===null||Br===void 0||Br.call(this,{type:"Heartbeat"});else try{const Wr=JSON.parse(jr.data);(qr=this.incomingDataListener)===null||qr===void 0||qr.call(this,Wr)}catch{}}})}disconnect(){var br;const{webSocket:wr}=this;if(wr){this.clearWebSocket(),(br=this.connectionStateListener)===null||br===void 0||br.call(this,ConnectionState.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{wr.close()}catch{}}}sendData(br){const{webSocket:wr}=this;if(!wr){this.pendingData.push(br),this.connect();return}wr.send(br)}clearWebSocket(){const{webSocket:br}=this;br&&(this.webSocket=null,br.onclose=null,br.onerror=null,br.onmessage=null,br.onopen=null)}}WalletLinkWebSocket$1.WalletLinkWebSocket=WalletLinkWebSocket;Object.defineProperty(WalletLinkConnection$1,"__esModule",{value:!0});WalletLinkConnection$1.WalletLinkConnection=void 0;const constants_1$4=constants$1,WalletLinkCipher_1=WalletLinkCipher$1,WalletLinkHTTP_1=WalletLinkHTTP$1,WalletLinkWebSocket_1=WalletLinkWebSocket$1,type_1$1=type$3,HEARTBEAT_INTERVAL=1e4,REQUEST_TIMEOUT=6e4;class WalletLinkConnection{constructor({session:br,linkAPIUrl:wr,listener:Er,WebSocketClass:kr=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,type_1$1.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=Br=>{if(!Br)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",Wr=>Br.JsonRpcUrl&&this.handleChainUpdated(Wr,Br.JsonRpcUrl)]]).forEach((Wr,Vr)=>{const Hr=Br[Vr];Hr!==void 0&&Wr(Hr)})},this.handleDestroyed=Br=>{var qr;Br==="1"&&((qr=this.listener)===null||qr===void 0||qr.resetAndReload())},this.handleAccountUpdated=async Br=>{var qr;{const Wr=await this.cipher.decrypt(Br);(qr=this.listener)===null||qr===void 0||qr.accountUpdated(Wr)}},this.handleMetadataUpdated=async(Br,qr)=>{var Wr;{const Vr=await this.cipher.decrypt(qr);(Wr=this.listener)===null||Wr===void 0||Wr.metadataUpdated(Br,Vr)}},this.handleWalletUsernameUpdated=async Br=>{this.handleMetadataUpdated(constants_1$4.WALLET_USER_NAME_KEY,Br)},this.handleAppVersionUpdated=async Br=>{this.handleMetadataUpdated(constants_1$4.APP_VERSION_KEY,Br)},this.handleChainUpdated=async(Br,qr)=>{var Wr;{const Vr=await this.cipher.decrypt(Br),Hr=await this.cipher.decrypt(qr);(Wr=this.listener)===null||Wr===void 0||Wr.chainUpdated(Vr,Hr)}},this.session=br,this.cipher=new WalletLinkCipher_1.WalletLinkCipher(br.secret),this.listener=Er;const jr=new WalletLinkWebSocket_1.WalletLinkWebSocket(`${wr}/rpc`,kr);jr.setConnectionStateListener(async Br=>{let qr=!1;switch(Br){case WalletLinkWebSocket_1.ConnectionState.DISCONNECTED:if(!this.destroyed){const Wr=async()=>{await new Promise(Vr=>setTimeout(Vr,5e3)),this.destroyed||jr.connect().catch(()=>{Wr()})};Wr()}break;case WalletLinkWebSocket_1.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),qr=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},HEARTBEAT_INTERVAL),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case WalletLinkWebSocket_1.ConnectionState.CONNECTING:break}this.connected!==qr&&(this.connected=qr)}),jr.setIncomingDataListener(Br=>{var qr;switch(Br.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const Wr=Br.type==="IsLinkedOK"?Br.linked:void 0;this.linked=Wr||Br.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(Br.metadata);break}case"Event":{this.handleIncomingEvent(Br);break}}Br.id!==void 0&&((qr=this.requestResolutions.get(Br.id))===null||qr===void 0||qr(Br))}),this.ws=jr,this.http=new WalletLinkHTTP_1.WalletLinkHTTP(wr,br.id,br.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}destroy(){this.destroyed=!0,this.ws.disconnect(),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(br){var wr;this._connected=br,br&&((wr=this.onceConnected)===null||wr===void 0||wr.call(this))}setOnceConnected(br){return new Promise(wr=>{this.connected?br().then(wr):this.onceConnected=()=>{br().then(wr),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(br){var wr,Er;this._linked=br,br&&((wr=this.onceLinked)===null||wr===void 0||wr.call(this)),(Er=this.listener)===null||Er===void 0||Er.linkedUpdated(br)}setOnceLinked(br){return new Promise(wr=>{this.linked?br().then(wr):this.onceLinked=()=>{br().then(wr),this.onceLinked=void 0}})}async handleIncomingEvent(br){var wr;if(!(br.type!=="Event"||br.event!=="Web3Response")){const Er=await this.cipher.decrypt(br.data),kr=JSON.parse(Er);if(kr.type!=="WEB3_RESPONSE")return;(wr=this.listener)===null||wr===void 0||wr.handleWeb3ResponseMessage(kr)}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(br=>setTimeout(br,250));try{await this.fetchUnseenEventsAPI()}catch(br){console.error("Unable to check for unseen events",br)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(wr=>this.handleIncomingEvent(wr))}async setSessionMetadata(br,wr){const Er={type:"SetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[br]:wr}};return this.setOnceConnected(async()=>{const kr=await this.makeRequest(Er);if(kr.type==="Fail")throw new Error(kr.error||"failed to set session metadata")})}async publishEvent(br,wr,Er=!1){const kr=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},wr),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),jr={type:"PublishEvent",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:br,data:kr,callWebhook:Er};return this.setOnceLinked(async()=>{const Br=await this.makeRequest(jr);if(Br.type==="Fail")throw new Error(Br.error||"failed to publish event");return Br.eventId})}sendData(br){this.ws.sendData(JSON.stringify(br))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>HEARTBEAT_INTERVAL*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(br,wr=REQUEST_TIMEOUT){const Er=br.id;this.sendData(br);let kr;return Promise.race([new Promise((jr,Br)=>{kr=window.setTimeout(()=>{Br(new Error(`request ${Er} timed out`))},wr)}),new Promise(jr=>{this.requestResolutions.set(Er,Br=>{clearTimeout(kr),jr(Br),this.requestResolutions.delete(Er)})})])}async authenticate(){const br={type:"HostSession",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},wr=await this.makeRequest(br);if(wr.type==="Fail")throw new Error(wr.error||"failed to authenticate")}sendIsLinked(){const br={type:"IsLinked",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(br)}sendGetSessionConfig(){const br={type:"GetSessionConfig",id:(0,type_1$1.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(br)}}WalletLinkConnection$1.WalletLinkConnection=WalletLinkConnection;var WalletLinkSession$1={};Object.defineProperty(WalletLinkSession$1,"__esModule",{value:!0});WalletLinkSession$1.WalletLinkSession=void 0;const sha_js_1=requireSha_js(),util_1$7=util$6,STORAGE_KEY_SESSION_ID="session:id",STORAGE_KEY_SESSION_SECRET="session:secret",STORAGE_KEY_SESSION_LINKED="session:linked";class WalletLinkSession{constructor(br,wr,Er,kr){this._storage=br,this._id=wr||(0,util_1$7.randomBytesHex)(16),this._secret=Er||(0,util_1$7.randomBytesHex)(32),this._key=new sha_js_1.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!kr}static load(br){const wr=br.getItem(STORAGE_KEY_SESSION_ID),Er=br.getItem(STORAGE_KEY_SESSION_LINKED),kr=br.getItem(STORAGE_KEY_SESSION_SECRET);return wr&&kr?new WalletLinkSession(br,wr,kr,Er==="1"):null}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(br){this._linked=br,this.persistLinked()}save(){return this._storage.setItem(STORAGE_KEY_SESSION_ID,this._id),this._storage.setItem(STORAGE_KEY_SESSION_SECRET,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(STORAGE_KEY_SESSION_LINKED,this._linked?"1":"0")}}WalletLinkSession$1.WalletLinkSession=WalletLinkSession;var util$1={};Object.defineProperty(util$1,"__esModule",{value:!0});util$1.isDarkMode=util$1.isMobileWeb=util$1.getLocation=util$1.createQrUrl=void 0;function createQrUrl(fr,br,wr,Er,kr,jr){const Br=Er?"parent-id":"id",qr=new URLSearchParams({[Br]:fr,secret:br,server:wr,v:kr,chainId:jr.toString()}).toString();return`${wr}/#/link?${qr}`}util$1.createQrUrl=createQrUrl;function isInIFrame(){try{return window.frameElement!==null}catch{return!1}}function getLocation(){try{return isInIFrame()&&window.top?window.top.location:window.location}catch{return window.location}}util$1.getLocation=getLocation;function isMobileWeb(){var fr;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((fr=window==null?void 0:window.navigator)===null||fr===void 0?void 0:fr.userAgent)}util$1.isMobileWeb=isMobileWeb;function isDarkMode(){var fr,br;return(br=(fr=window==null?void 0:window.matchMedia)===null||fr===void 0?void 0:fr.call(window,"(prefers-color-scheme: dark)").matches)!==null&&br!==void 0?br:!1}util$1.isDarkMode=isDarkMode;var WalletLinkRelayUI$1={},cssReset={},cssResetCss={};Object.defineProperty(cssResetCss,"__esModule",{value:!0});cssResetCss.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var __importDefault$4=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(cssReset,"__esModule",{value:!0});cssReset.injectCssReset=void 0;const cssReset_css_1=__importDefault$4(cssResetCss);function injectCssReset(){const fr=document.createElement("style");fr.type="text/css",fr.appendChild(document.createTextNode(cssReset_css_1.default)),document.documentElement.appendChild(fr)}cssReset.injectCssReset=injectCssReset;var Snackbar={};function r$2(fr){var br,wr,Er="";if(typeof fr=="string"||typeof fr=="number")Er+=fr;else if(typeof fr=="object")if(Array.isArray(fr))for(br=0;br2&&(Br.children=arguments.length>3?n.call(arguments,2):wr),typeof fr=="function"&&fr.defaultProps!=null)for(jr in fr.defaultProps)Br[jr]===void 0&&(Br[jr]=fr.defaultProps[jr]);return g$1(fr,Br,Er,kr,null)}function g$1(fr,br,wr,Er,kr){var jr={type:fr,props:br,key:wr,ref:Er,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:kr??++u$1,__i:-1,__u:0};return kr==null&&l$1.vnode!=null&&l$1.vnode(jr),jr}function m$1(){return{current:null}}function b$1(fr){return fr.children}function k$1(fr,br){this.props=fr,this.context=br}function x$1(fr,br){if(br==null)return fr.__?x$1(fr.__,fr.__i+1):null;for(var wr;brbr&&i$2.sort(f$2));M.__r=0}function P$1(fr,br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr){var Zr,Jr,Xr,En,wn,$n=Er&&Er.__k||v$1,Tn=br.length;for(wr.__d=Wr,$(wr,br,$n),Wr=wr.__d,Zr=0;Zr0?g$1(kr.type,kr.props,kr.key,kr.ref?kr.ref:null,kr.__v):kr).__=fr,kr.__b=fr.__b+1,jr=null,(qr=kr.__i=L(kr,wr,Br,Hr))!==-1&&(Hr--,(jr=wr[qr])&&(jr.__u|=131072)),jr==null||jr.__v===null?(qr==-1&&Zr--,typeof kr.type!="function"&&(kr.__u|=65536)):qr!==Br&&(qr==Br-1?Zr--:qr==Br+1?Zr++:(qr>Br?Zr--:Zr++,kr.__u|=65536))):kr=fr.__k[Er]=null;if(Hr)for(Er=0;Er(Wr!=null&&!(131072&Wr.__u)?1:0))for(;Br>=0||qr=0){if((Wr=br[Br])&&!(131072&Wr.__u)&&kr==Wr.key&&jr===Wr.type)return Br;Br--}if(qr2&&(qr.children=arguments.length>3?n.call(arguments,2):wr),g$1(fr.type,qr,Er||fr.key,kr||fr.ref,null)}function G(fr,br){var wr={__c:br="__cC"+a$1++,__:fr,Consumer:function(Er,kr){return Er.children(kr)},Provider:function(Er){var kr,jr;return this.getChildContext||(kr=new Set,(jr={})[br]=this,this.getChildContext=function(){return jr},this.componentWillUnmount=function(){kr=null},this.shouldComponentUpdate=function(Br){this.props.value!==Br.value&&kr.forEach(function(qr){qr.__e=!0,S(qr)})},this.sub=function(Br){kr.add(Br);var qr=Br.componentWillUnmount;Br.componentWillUnmount=function(){kr&&kr.delete(Br),qr&&qr.call(Br)}}),Er.children}};return wr.Provider.__=wr.Consumer.contextType=wr}n=v$1.slice,l$1={__e:function(fr,br,wr,Er){for(var kr,jr,Br;br=br.__;)if((kr=br.__c)&&!kr.__)try{if((jr=kr.constructor)&&jr.getDerivedStateFromError!=null&&(kr.setState(jr.getDerivedStateFromError(fr)),Br=kr.__d),kr.componentDidCatch!=null&&(kr.componentDidCatch(fr,Er||{}),Br=kr.__d),Br)return kr.__E=kr}catch(qr){fr=qr}throw fr}},u$1=0,t$1=function(fr){return fr!=null&&fr.constructor==null},k$1.prototype.setState=function(fr,br){var wr;wr=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=d$1({},this.state),typeof fr=="function"&&(fr=fr(d$1({},wr),this.props)),fr&&d$1(wr,fr),fr!=null&&this.__v&&(br&&this._sb.push(br),S(this))},k$1.prototype.forceUpdate=function(fr){this.__v&&(this.__e=!0,fr&&this.__h.push(fr),S(this))},k$1.prototype.render=b$1,i$2=[],r$1=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$2=function(fr,br){return fr.__v.__b-br.__v.__b},M.__r=0,e$1=0,c$1=F$1(!1),s$1=F$1(!0),a$1=0;const preact_module=Object.freeze(Object.defineProperty({__proto__:null,Component:k$1,Fragment:b$1,cloneElement:D$1,createContext:G,createElement:_$1,createRef:m$1,h:_$1,hydrate:B$1,get isValidElement(){return t$1},get options(){return l$1},render:q$1,toChildArray:H},Symbol.toStringTag,{value:"Module"})),require$$1=getAugmentedNamespace(preact_module);var t,r,u,i$1,o=0,f$1=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function d(fr,br){c.__h&&c.__h(r,fr,o||br),o=0;var wr=r.__H||(r.__H={__:[],__h:[]});return fr>=wr.__.length&&wr.__.push({}),wr.__[fr]}function h(fr){return o=1,p(D,fr)}function p(fr,br,wr){var Er=d(t++,2);if(Er.t=fr,!Er.__c&&(Er.__=[wr?wr(br):D(void 0,br),function(qr){var Wr=Er.__N?Er.__N[0]:Er.__[0],Vr=Er.t(Wr,qr);Wr!==Vr&&(Er.__N=[Vr,Er.__[1]],Er.__c.setState({}))}],Er.__c=r,!r.u)){var kr=function(qr,Wr,Vr){if(!Er.__c.__H)return!0;var Hr=Er.__c.__H.__.filter(function(Jr){return!!Jr.__c});if(Hr.every(function(Jr){return!Jr.__N}))return!jr||jr.call(this,qr,Wr,Vr);var Zr=Er.__c.props!==qr;return Hr.forEach(function(Jr){if(Jr.__N){var Xr=Jr.__[0];Jr.__=Jr.__N,Jr.__N=void 0,Xr!==Jr.__[0]&&(Zr=!0)}}),jr&&jr.call(this,qr,Wr,Vr)||Zr};r.u=!0;var jr=r.shouldComponentUpdate,Br=r.componentWillUpdate;r.componentWillUpdate=function(qr,Wr,Vr){if(this.__e){var Hr=jr;jr=void 0,kr(qr,Wr,Vr),jr=Hr}Br&&Br.call(this,qr,Wr,Vr)},r.shouldComponentUpdate=kr}return Er.__N||Er.__}function y(fr,br){var wr=d(t++,3);!c.__s&&C(wr.__H,br)&&(wr.__=fr,wr.i=br,r.__H.__h.push(wr))}function _(fr,br){var wr=d(t++,4);!c.__s&&C(wr.__H,br)&&(wr.__=fr,wr.i=br,r.__h.push(wr))}function A(fr){return o=5,T(function(){return{current:fr}},[])}function F(fr,br,wr){o=6,_(function(){return typeof fr=="function"?(fr(br()),function(){return fr(null)}):fr?(fr.current=br(),function(){return fr.current=null}):void 0},wr==null?wr:wr.concat(fr))}function T(fr,br){var wr=d(t++,7);return C(wr.__H,br)&&(wr.__=fr(),wr.__H=br,wr.__h=fr),wr.__}function q(fr,br){return o=8,T(function(){return fr},br)}function x(fr){var br=r.context[fr.__c],wr=d(t++,9);return wr.c=fr,br?(wr.__==null&&(wr.__=!0,br.sub(r)),br.props.value):fr.__}function P(fr,br){c.useDebugValue&&c.useDebugValue(br?br(fr):fr)}function b(fr){var br=d(t++,10),wr=h();return br.__=fr,r.componentDidCatch||(r.componentDidCatch=function(Er,kr){br.__&&br.__(Er,kr),wr[1](Er)}),[wr[0],function(){wr[1](void 0)}]}function g(){var fr=d(t++,11);if(!fr.__){for(var br=r.__v;br!==null&&!br.__m&&br.__!==null;)br=br.__;var wr=br.__m||(br.__m=[0,0]);fr.__="P"+wr[0]+"-"+wr[1]++}return fr.__}function j(){for(var fr;fr=f$1.shift();)if(fr.__P&&fr.__H)try{fr.__H.__h.forEach(z),fr.__H.__h.forEach(B),fr.__H.__h=[]}catch(br){fr.__H.__h=[],c.__e(br,fr.__v)}}c.__b=function(fr){r=null,e&&e(fr)},c.__=function(fr,br){fr&&br.__k&&br.__k.__m&&(fr.__m=br.__k.__m),s&&s(fr,br)},c.__r=function(fr){a&&a(fr),t=0;var br=(r=fr.__c).__H;br&&(u===r?(br.__h=[],r.__h=[],br.__.forEach(function(wr){wr.__N&&(wr.__=wr.__N),wr.i=wr.__N=void 0})):(br.__h.forEach(z),br.__h.forEach(B),br.__h=[],t=0)),u=r},c.diffed=function(fr){v&&v(fr);var br=fr.__c;br&&br.__H&&(br.__H.__h.length&&(f$1.push(br)!==1&&i$1===c.requestAnimationFrame||((i$1=c.requestAnimationFrame)||w)(j)),br.__H.__.forEach(function(wr){wr.i&&(wr.__H=wr.i),wr.i=void 0})),u=r=null},c.__c=function(fr,br){br.some(function(wr){try{wr.__h.forEach(z),wr.__h=wr.__h.filter(function(Er){return!Er.__||B(Er)})}catch(Er){br.some(function(kr){kr.__h&&(kr.__h=[])}),br=[],c.__e(Er,wr.__v)}}),l&&l(fr,br)},c.unmount=function(fr){m&&m(fr);var br,wr=fr.__c;wr&&wr.__H&&(wr.__H.__.forEach(function(Er){try{z(Er)}catch(kr){br=kr}}),wr.__H=void 0,br&&c.__e(br,wr.__v))};var k=typeof requestAnimationFrame=="function";function w(fr){var br,wr=function(){clearTimeout(Er),k&&cancelAnimationFrame(br),setTimeout(fr)},Er=setTimeout(wr,100);k&&(br=requestAnimationFrame(wr))}function z(fr){var br=r,wr=fr.__c;typeof wr=="function"&&(fr.__c=void 0,wr()),r=br}function B(fr){var br=r;fr.__c=fr.__(),r=br}function C(fr,br){return!fr||fr.length!==br.length||br.some(function(wr,Er){return wr!==fr[Er]})}function D(fr,br){return typeof br=="function"?br(fr):br}const hooks_module=Object.freeze(Object.defineProperty({__proto__:null,useCallback:q,useContext:x,useDebugValue:P,useEffect:y,useErrorBoundary:b,useId:g,useImperativeHandle:F,useLayoutEffect:_,useMemo:T,useReducer:p,useRef:A,useState:h},Symbol.toStringTag,{value:"Module"})),require$$2$1=getAugmentedNamespace(hooks_module);var SnackbarCss={};Object.defineProperty(SnackbarCss,"__esModule",{value:!0});SnackbarCss.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(fr){var br=commonjsGlobal&&commonjsGlobal.__importDefault||function(Jr){return Jr&&Jr.__esModule?Jr:{default:Jr}};Object.defineProperty(fr,"__esModule",{value:!0}),fr.SnackbarInstance=fr.SnackbarContainer=fr.Snackbar=void 0;const wr=br(require$$0$1),Er=require$$1,kr=require$$2$1,jr=util$1,Br=br(SnackbarCss),qr="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",Wr="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class Vr{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=(0,jr.isDarkMode)()}attach(Xr){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",Xr.appendChild(this.root),this.render()}presentItem(Xr){const En=this.nextItemKey++;return this.items.set(En,Xr),this.render(),()=>{this.items.delete(En),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,Er.render)((0,Er.h)("div",null,(0,Er.h)(fr.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([Xr,En])=>(0,Er.h)(fr.SnackbarInstance,Object.assign({},En,{key:Xr}))))),this.root)}}fr.Snackbar=Vr;const Hr=Jr=>(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-container")},(0,Er.h)("style",null,Br.default),(0,Er.h)("div",{class:"-cbwsdk-snackbar"},Jr.children));fr.SnackbarContainer=Hr;const Zr=({autoExpand:Jr,message:Xr,menuItems:En})=>{const[wn,$n]=(0,kr.useState)(!0),[Tn,In]=(0,kr.useState)(Jr??!1);(0,kr.useEffect)(()=>{const Yn=[window.setTimeout(()=>{$n(!1)},1),window.setTimeout(()=>{In(!0)},1e4)];return()=>{Yn.forEach(window.clearTimeout)}});const jn=()=>{In(!Tn)};return(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-instance",wn&&"-cbwsdk-snackbar-instance-hidden",Tn&&"-cbwsdk-snackbar-instance-expanded")},(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:jn},(0,Er.h)("img",{src:qr,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},Xr),(0,Er.h)("div",{class:"-gear-container"},!Tn&&(0,Er.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,Er.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,Er.h)("img",{src:Wr,class:"-gear-icon",title:"Expand"}))),En&&En.length>0&&(0,Er.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},En.map((Yn,ga)=>(0,Er.h)("div",{class:(0,wr.default)("-cbwsdk-snackbar-instance-menu-item",Yn.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:Yn.onClick,key:ga},(0,Er.h)("svg",{width:Yn.svgWidth,height:Yn.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,Er.h)("path",{"fill-rule":Yn.defaultFillRule,"clip-rule":Yn.defaultClipRule,d:Yn.path,fill:"#AAAAAA"})),(0,Er.h)("span",{class:(0,wr.default)("-cbwsdk-snackbar-instance-menu-item-info",Yn.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},Yn.info)))))};fr.SnackbarInstance=Zr})(Snackbar);Object.defineProperty(WalletLinkRelayUI$1,"__esModule",{value:!0});WalletLinkRelayUI$1.WalletLinkRelayUI=void 0;const cssReset_1$1=cssReset,Snackbar_1$1=Snackbar;class WalletLinkRelayUI{constructor(){this.attached=!1,this.snackbar=new Snackbar_1$1.Snackbar}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const br=document.documentElement,wr=document.createElement("div");wr.className="-cbwsdk-css-reset",br.appendChild(wr),this.snackbar.attach(wr),this.attached=!0,(0,cssReset_1$1.injectCssReset)()}showConnecting(br){let wr;return br.isUnlinkedErrorState?wr={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:br.onResetConnection}]}:wr={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:br.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:br.onResetConnection}]},this.snackbar.presentItem(wr)}}WalletLinkRelayUI$1.WalletLinkRelayUI=WalletLinkRelayUI;var WLMobileRelayUI$1={},RedirectDialog$1={},RedirectDialogCss={};Object.defineProperty(RedirectDialogCss,"__esModule",{value:!0});RedirectDialogCss.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var __importDefault$3=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(RedirectDialog$1,"__esModule",{value:!0});RedirectDialog$1.RedirectDialog=void 0;const clsx_1=__importDefault$3(require$$0$1),preact_1=require$$1,cssReset_1=cssReset,Snackbar_1=Snackbar,util_1$6=util$1,RedirectDialog_css_1=__importDefault$3(RedirectDialogCss);class RedirectDialog{constructor(){this.root=null,this.darkMode=(0,util_1$6.isDarkMode)()}attach(){const br=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",br.appendChild(this.root),(0,cssReset_1.injectCssReset)()}present(br){this.render(br)}clear(){this.render(null)}render(br){this.root&&((0,preact_1.render)(null,this.root),br&&(0,preact_1.render)((0,preact_1.h)(RedirectDialogContent,Object.assign({},br,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}RedirectDialog$1.RedirectDialog=RedirectDialog;const RedirectDialogContent=({title:fr,buttonText:br,darkMode:wr,onButtonClick:Er,onDismiss:kr})=>{const jr=wr?"dark":"light";return(0,preact_1.h)(Snackbar_1.SnackbarContainer,{darkMode:wr},(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,preact_1.h)("style",null,RedirectDialog_css_1.default),(0,preact_1.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:kr}),(0,preact_1.h)("div",{class:(0,clsx_1.default)("-cbwsdk-redirect-dialog-box",jr)},(0,preact_1.h)("p",null,fr),(0,preact_1.h)("button",{onClick:Er},br))))};var constants={};Object.defineProperty(constants,"__esModule",{value:!0});constants.CBW_MOBILE_DEEPLINK_URL=constants.WALLETLINK_URL=constants.CB_KEYS_URL=void 0;constants.CB_KEYS_URL="https://keys.coinbase.com/connect";constants.WALLETLINK_URL="https://www.walletlink.org";constants.CBW_MOBILE_DEEPLINK_URL="https://go.cb-w.com/walletlink";Object.defineProperty(WLMobileRelayUI$1,"__esModule",{value:!0});WLMobileRelayUI$1.WLMobileRelayUI=void 0;const RedirectDialog_1=RedirectDialog$1,util_1$5=util$1,constants_1$3=constants;class WLMobileRelayUI{constructor(){this.attached=!1,this.redirectDialog=new RedirectDialog_1.RedirectDialog}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(br){const wr=new URL(constants_1$3.CBW_MOBILE_DEEPLINK_URL);wr.searchParams.append("redirect_url",(0,util_1$5.getLocation)().href),br&&wr.searchParams.append("wl_url",br);const Er=document.createElement("a");Er.target="cbw-opener",Er.href=wr.href,Er.rel="noreferrer noopener",Er.click()}openCoinbaseWalletDeeplink(br){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(br)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(br)},99)}showConnecting(br){return()=>{this.redirectDialog.clear()}}}WLMobileRelayUI$1.WLMobileRelayUI=WLMobileRelayUI;Object.defineProperty(WalletLinkRelay$1,"__esModule",{value:!0});WalletLinkRelay$1.WalletLinkRelay=void 0;const WalletLinkConnection_1=WalletLinkConnection$1,constants_1$2=constants$1,RelayEventManager_1$1=RelayEventManager$1,WalletLinkSession_1=WalletLinkSession$1,Web3Response_1$1=Web3Response,util_1$4=util$1,WalletLinkRelayUI_1=WalletLinkRelayUI$1,WLMobileRelayUI_1=WLMobileRelayUI$1,error_1$6=error,util_2$1=util$6,ScopedLocalStorage_1$4=ScopedLocalStorage$1;class WalletLinkRelay{constructor(br){this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.isMobileWeb=(0,util_1$4.isMobileWeb)(),this.appName="",this.appLogoUrl=null,this.linkedUpdated=jr=>{this.isLinked=jr;const Br=this.storage.getItem(constants_1$2.LOCAL_STORAGE_ADDRESSES_KEY);if(jr&&(this._session.linked=jr),this.isUnlinkedErrorState=!1,Br){const qr=Br.split(" "),Wr=this.storage.getItem("IsStandaloneSigning")==="true";qr[0]!==""&&!jr&&this._session.linked&&!Wr&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(jr,Br)=>{this.storage.setItem(jr,Br)},this.chainUpdated=(jr,Br)=>{this.chainCallbackParams.chainId===jr&&this.chainCallbackParams.jsonRpcUrl===Br||(this.chainCallbackParams={chainId:jr,jsonRpcUrl:Br},this.chainCallback&&this.chainCallback(jr,Br))},this.accountUpdated=jr=>{this.accountsCallback&&this.accountsCallback([jr]),WalletLinkRelay.accountRequestCallbackIds.size>0&&(Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach(Br=>{const qr={type:"WEB3_RESPONSE",id:Br,response:{method:"requestEthereumAccounts",result:[jr]}};this.invokeCallback(Object.assign(Object.assign({},qr),{id:Br}))}),WalletLinkRelay.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=br.linkAPIUrl,this.storage=br.storage;const{session:wr,ui:Er,connection:kr}=this.subscribe();this._session=wr,this.connection=kr,this.relayEventManager=new RelayEventManager_1$1.RelayEventManager,this.ui=Er}subscribe(){const br=WalletLinkSession_1.WalletLinkSession.load(this.storage)||new WalletLinkSession_1.WalletLinkSession(this.storage).save(),{linkAPIUrl:wr}=this,Er=new WalletLinkConnection_1.WalletLinkConnection({session:br,linkAPIUrl:wr,listener:this}),kr=this.isMobileWeb?new WLMobileRelayUI_1.WLMobileRelayUI:new WalletLinkRelayUI_1.WalletLinkRelayUI;return Er.connect(),{session:br,ui:kr,connection:Er}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(br=>setTimeout(()=>br(null),1e3))]).then(()=>{this.connection.destroy();const br=WalletLinkSession_1.WalletLinkSession.load(this.storage);(br==null?void 0:br.id)===this._session.id&&ScopedLocalStorage_1$4.ScopedLocalStorage.clearAll(),document.location.reload()}).catch(br=>{})}setAppInfo(br,wr){this.appName=br,this.appLogoUrl=wr}getStorageItem(br){return this.storage.getItem(br)}setStorageItem(br,wr){this.storage.setItem(br,wr)}signEthereumMessage(br,wr,Er,kr){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(br,!0),address:wr,addPrefix:Er,typedDataJson:kr||null}})}ethereumAddressFromSignedMessage(br,wr,Er){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,util_2$1.hexStringFromBuffer)(br,!0),signature:(0,util_2$1.hexStringFromBuffer)(wr,!0),addPrefix:Er}})}signEthereumTransaction(br){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:br.fromAddress,toAddress:br.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(br.weiValue),data:(0,util_2$1.hexStringFromBuffer)(br.data,!0),nonce:br.nonce,gasPriceInWei:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxFeePerGas:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxPriorityFeePerGas:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,gasLimit:br.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(br.gasLimit):null,chainId:br.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(br){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:br.fromAddress,toAddress:br.toAddress,weiValue:(0,util_2$1.bigIntStringFromBigInt)(br.weiValue),data:(0,util_2$1.hexStringFromBuffer)(br.data,!0),nonce:br.nonce,gasPriceInWei:br.gasPriceInWei?(0,util_2$1.bigIntStringFromBigInt)(br.gasPriceInWei):null,maxFeePerGas:br.maxFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(br.maxFeePerGas):null,maxPriorityFeePerGas:br.maxPriorityFeePerGas?(0,util_2$1.bigIntStringFromBigInt)(br.maxPriorityFeePerGas):null,gasLimit:br.gasLimit?(0,util_2$1.bigIntStringFromBigInt)(br.gasLimit):null,chainId:br.chainId,shouldSubmit:!0}})}submitEthereumTransaction(br,wr){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,util_2$1.hexStringFromBuffer)(br,!0),chainId:wr}})}scanQRCode(br){return this.sendRequest({method:"scanQRCode",params:{regExp:br}})}getWalletLinkSession(){return this._session}genericRequest(br,wr){return this.sendRequest({method:"generic",params:{action:wr,data:br}})}sendGenericMessage(br){return this.sendRequest(br)}sendRequest(br){let wr=null;const Er=(0,util_2$1.randomBytesHex)(8),kr=jr=>{this.publishWeb3RequestCanceledEvent(Er),this.handleErrorResponse(Er,br.method,jr),wr==null||wr()};return new Promise((jr,Br)=>{wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:kr,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(Er,qr=>{if(wr==null||wr(),(0,Web3Response_1$1.isErrorResponse)(qr))return Br(new Error(qr.errorMessage));jr(qr)}),this.publishWeb3RequestEvent(Er,br)})}setAccountsCallback(br){this.accountsCallback=br}setChainCallback(br){this.chainCallback=br}setDappDefaultChainCallback(br){this.dappDefaultChain=br}publishWeb3RequestEvent(br,wr){const Er={type:"WEB3_REQUEST",id:br,request:wr};this.publishEvent("Web3Request",Er,!0).then(kr=>{}).catch(kr=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:Er.id,response:{method:wr.method,errorMessage:kr.message}})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(wr.method)}openCoinbaseWalletDeeplink(br){if(this.ui instanceof WLMobileRelayUI_1.WLMobileRelayUI)switch(br){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(br){const wr={type:"WEB3_REQUEST_CANCELED",id:br};this.publishEvent("Web3RequestCanceled",wr,!1).then()}publishEvent(br,wr,Er){return this.connection.publishEvent(br,wr,Er)}handleWeb3ResponseMessage(br){const{response:wr}=br;if(wr.method==="requestEthereumAccounts"){WalletLinkRelay.accountRequestCallbackIds.forEach(Er=>this.invokeCallback(Object.assign(Object.assign({},br),{id:Er}))),WalletLinkRelay.accountRequestCallbackIds.clear();return}this.invokeCallback(br)}handleErrorResponse(br,wr,Er){var kr;const jr=(kr=Er==null?void 0:Er.message)!==null&&kr!==void 0?kr:"Unspecified error message.";this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:br,response:{method:wr,errorMessage:jr}})}invokeCallback(br){const wr=this.relayEventManager.callbacks.get(br.id);wr&&(wr(br.response),this.relayEventManager.callbacks.delete(br.id))}requestEthereumAccounts(){const br={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},wr=(0,util_2$1.randomBytesHex)(8);return new Promise((Er,kr)=>{this.relayEventManager.callbacks.set(wr,jr=>{if((0,Web3Response_1$1.isErrorResponse)(jr))return kr(new Error(jr.errorMessage));Er(jr)}),WalletLinkRelay.accountRequestCallbackIds.add(wr),this.publishWeb3RequestEvent(wr,br)})}watchAsset(br,wr,Er,kr,jr,Br){const qr={method:"watchAsset",params:{type:br,options:{address:wr,symbol:Er,decimals:kr,image:jr},chainId:Br}};let Wr=null;const Vr=(0,util_2$1.randomBytesHex)(8),Hr=Zr=>{this.publishWeb3RequestCanceledEvent(Vr),this.handleErrorResponse(Vr,qr.method,Zr),Wr==null||Wr()};return Wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:Hr,onResetConnection:this.resetAndReload}),new Promise((Zr,Jr)=>{this.relayEventManager.callbacks.set(Vr,Xr=>{if(Wr==null||Wr(),(0,Web3Response_1$1.isErrorResponse)(Xr))return Jr(new Error(Xr.errorMessage));Zr(Xr)}),this.publishWeb3RequestEvent(Vr,qr)})}addEthereumChain(br,wr,Er,kr,jr,Br){const qr={method:"addEthereumChain",params:{chainId:br,rpcUrls:wr,blockExplorerUrls:kr,chainName:jr,iconUrls:Er,nativeCurrency:Br}};let Wr=null;const Vr=(0,util_2$1.randomBytesHex)(8),Hr=Zr=>{this.publishWeb3RequestCanceledEvent(Vr),this.handleErrorResponse(Vr,qr.method,Zr),Wr==null||Wr()};return Wr=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:Hr,onResetConnection:this.resetAndReload}),new Promise((Zr,Jr)=>{this.relayEventManager.callbacks.set(Vr,Xr=>{if(Wr==null||Wr(),(0,Web3Response_1$1.isErrorResponse)(Xr))return Jr(new Error(Xr.errorMessage));Zr(Xr)}),this.publishWeb3RequestEvent(Vr,qr)})}switchEthereumChain(br,wr){const Er={method:"switchEthereumChain",params:Object.assign({chainId:br},{address:wr})},kr=(0,util_2$1.randomBytesHex)(8);return new Promise((jr,Br)=>{this.relayEventManager.callbacks.set(kr,qr=>{if((0,Web3Response_1$1.isErrorResponse)(qr)&&qr.errorCode)return Br(error_1$6.standardErrors.provider.custom({code:qr.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Web3Response_1$1.isErrorResponse)(qr))return Br(new Error(qr.errorMessage));jr(qr)}),this.publishWeb3RequestEvent(kr,Er)})}}WalletLinkRelay$1.WalletLinkRelay=WalletLinkRelay;WalletLinkRelay.accountRequestCallbackIds=new Set;var __importDefault$2=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(WalletLinkSigner$1,"__esModule",{value:!0});WalletLinkSigner$1.WalletLinkSigner=void 0;const eth_eip712_util_1=__importDefault$2(ethEip712Util),constants_1$1=constants$1,RelayEventManager_1=RelayEventManager$1,Web3Response_1=Web3Response,WalletLinkRelay_1=WalletLinkRelay$1,constants_2=constants,error_1$5=error,util_1$3=util$6,ScopedLocalStorage_1$3=ScopedLocalStorage$1,DEFAULT_CHAIN_ID_KEY="DefaultChainId",DEFAULT_JSON_RPC_URL="DefaultJsonRpcUrl";class WalletLinkSigner{constructor(br){var wr,Er;this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1;const{appName:kr,appLogoUrl:jr}=br.metadata;this._appName=kr,this._appLogoUrl=jr,this._storage=new ScopedLocalStorage_1$3.ScopedLocalStorage("walletlink",constants_2.WALLETLINK_URL),this.updateListener=br.updateListener,this._relayEventManager=new RelayEventManager_1.RelayEventManager,this._jsonRpcUrlFromOpts="";const Br=this._storage.getItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY);if(Br){const Wr=Br.split(" ");Wr[0]!==""&&(this._addresses=Wr.map(Vr=>(0,util_1$3.ensureAddressString)(Vr)),(wr=this.updateListener)===null||wr===void 0||wr.onAccountsUpdate({accounts:this._addresses,source:"storage"}))}this._storage.getItem(DEFAULT_CHAIN_ID_KEY)&&((Er=this.updateListener)===null||Er===void 0||Er.onChainUpdate({chain:{id:this.getChainId(),rpcUrl:this.jsonRpcUrl},source:"storage"}),this.hasMadeFirstChainChangedEmission=!0),this.initializeRelay()}getSession(){const br=this.initializeRelay(),{id:wr,secret:Er}=br.getWalletLinkSession();return{id:wr,secret:Er}}async handshake(){return await this.request({method:"eth_requestAccounts"})}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var br;return(br=this._storage.getItem(DEFAULT_JSON_RPC_URL))!==null&&br!==void 0?br:this._jsonRpcUrlFromOpts}set jsonRpcUrl(br){this._storage.setItem(DEFAULT_JSON_RPC_URL,br)}updateProviderInfo(br,wr){var Er;this.jsonRpcUrl=br;const kr=this.getChainId();this._storage.setItem(DEFAULT_CHAIN_ID_KEY,wr.toString(10)),((0,util_1$3.ensureIntNumber)(wr)!==kr||!this.hasMadeFirstChainChangedEmission)&&((Er=this.updateListener)===null||Er===void 0||Er.onChainUpdate({chain:{id:wr,rpcUrl:br},source:"wallet"}),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(br,wr,Er,kr,jr,Br){const Wr=await this.initializeRelay().watchAsset(br,wr,Er,kr,jr,Br==null?void 0:Br.toString());return(0,Web3Response_1.isErrorResponse)(Wr)?!1:!!Wr.result}async addEthereumChain(br,wr,Er,kr,jr,Br){var qr,Wr;if((0,util_1$3.ensureIntNumber)(br)===this.getChainId())return!1;const Vr=this.initializeRelay();this._isAuthorized()||await Vr.requestEthereumAccounts();const Hr=await Vr.addEthereumChain(br.toString(),wr,jr,Er,kr,Br);return(0,Web3Response_1.isErrorResponse)(Hr)?!1:(((qr=Hr.result)===null||qr===void 0?void 0:qr.isApproved)===!0&&this.updateProviderInfo(wr[0],br),((Wr=Hr.result)===null||Wr===void 0?void 0:Wr.isApproved)===!0)}async switchEthereumChain(br){const Er=await this.initializeRelay().switchEthereumChain(br.toString(10),this.selectedAddress||void 0);if((0,Web3Response_1.isErrorResponse)(Er)){if(!Er.errorCode)return;throw Er.errorCode===error_1$5.standardErrorCodes.provider.unsupportedChain?error_1$5.standardErrors.provider.unsupportedChain():error_1$5.standardErrors.provider.custom({message:Er.errorMessage,code:Er.errorCode})}const kr=Er.result;kr.isApproved&&kr.rpcUrl.length>0&&this.updateProviderInfo(kr.rpcUrl,br)}async disconnect(){this._relay&&this._relay.resetAndReload(),this._storage.clear()}async request(br){try{return this._request(br).catch(wr=>{throw wr})}catch(wr){return Promise.reject(wr)}}async _request(br){if(!br||typeof br!="object"||Array.isArray(br))throw error_1$5.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:br});const{method:wr,params:Er}=br;if(typeof wr!="string"||wr.length===0)throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:br});if(Er!==void 0&&!Array.isArray(Er)&&(typeof Er!="object"||Er===null))throw error_1$5.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:br});const kr=Er===void 0?[]:Er,jr=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:wr,params:kr,jsonrpc:"2.0",id:jr})).result}_setAddresses(br,wr){var Er;if(!Array.isArray(br))throw new Error("addresses is not an array");const kr=br.map(jr=>(0,util_1$3.ensureAddressString)(jr));JSON.stringify(kr)!==JSON.stringify(this._addresses)&&(this._addresses=kr,(Er=this.updateListener)===null||Er===void 0||Er.onAccountsUpdate({accounts:kr,source:"wallet"}),this._storage.setItem(constants_1$1.LOCAL_STORAGE_ADDRESSES_KEY,kr.join(" ")))}_sendRequestAsync(br){return new Promise((wr,Er)=>{try{const kr=this._handleSynchronousMethods(br);if(kr!==void 0)return wr({jsonrpc:"2.0",id:br.id,result:kr})}catch(kr){return Er(kr)}this._handleAsynchronousMethods(br).then(kr=>kr&&wr(Object.assign(Object.assign({},kr),{id:br.id}))).catch(kr=>Er(kr))})}_handleSynchronousMethods(br){const{method:wr}=br;switch(wr){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(br){const{method:wr}=br,Er=br.params||[];switch(wr){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(Er);case"eth_ecRecover":return this._eth_ecRecover(Er);case"personal_sign":return this._personal_sign(Er);case"personal_ecRecover":return this._personal_ecRecover(Er);case"eth_signTransaction":return this._eth_signTransaction(Er);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(Er);case"eth_sendTransaction":return this._eth_sendTransaction(Er);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(Er);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(Er);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(Er);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(Er);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(Er);case"wallet_watchAsset":return this._wallet_watchAsset(Er);default:return this._throwUnsupportedMethodError()}}_isKnownAddress(br){try{const wr=(0,util_1$3.ensureAddressString)(br);return this._addresses.map(kr=>(0,util_1$3.ensureAddressString)(kr)).includes(wr)}catch{}return!1}_ensureKnownAddress(br){if(!this._isKnownAddress(br))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(br){const wr=br.from?(0,util_1$3.ensureAddressString)(br.from):this.selectedAddress;if(!wr)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(wr);const Er=br.to?(0,util_1$3.ensureAddressString)(br.to):null,kr=br.value!=null?(0,util_1$3.ensureBigInt)(br.value):BigInt(0),jr=br.data?(0,util_1$3.ensureBuffer)(br.data):Buffer$2.alloc(0),Br=br.nonce!=null?(0,util_1$3.ensureIntNumber)(br.nonce):null,qr=br.gasPrice!=null?(0,util_1$3.ensureBigInt)(br.gasPrice):null,Wr=br.maxFeePerGas!=null?(0,util_1$3.ensureBigInt)(br.maxFeePerGas):null,Vr=br.maxPriorityFeePerGas!=null?(0,util_1$3.ensureBigInt)(br.maxPriorityFeePerGas):null,Hr=br.gas!=null?(0,util_1$3.ensureBigInt)(br.gas):null,Zr=br.chainId?(0,util_1$3.ensureIntNumber)(br.chainId):this.getChainId();return{fromAddress:wr,toAddress:Er,weiValue:kr,data:jr,nonce:Br,gasPriceInWei:qr,maxFeePerGas:Wr,maxPriorityFeePerGas:Vr,gasLimit:Hr,chainId:Zr}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw error_1$5.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw error_1$5.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(br,wr,Er,kr){this._ensureKnownAddress(wr);try{const Br=await this.initializeRelay().signEthereumMessage(br,wr,Er,kr);if((0,Web3Response_1.isErrorResponse)(Br))throw new Error(Br.errorMessage);return{jsonrpc:"2.0",id:0,result:Br.result}}catch(jr){throw typeof jr.message=="string"&&jr.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied message signature"):jr}}async _ethereumAddressFromSignedMessage(br,wr,Er){const jr=await this.initializeRelay().ethereumAddressFromSignedMessage(br,wr,Er);if((0,Web3Response_1.isErrorResponse)(jr))throw new Error(jr.errorMessage);return{jsonrpc:"2.0",id:0,result:jr.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,util_1$3.hexStringFromIntNumber)(this.getChainId())}getChainId(){const br=this._storage.getItem(DEFAULT_CHAIN_ID_KEY);if(!br)return(0,util_1$3.ensureIntNumber)(1);const wr=parseInt(br,10);return(0,util_1$3.ensureIntNumber)(wr)}async _eth_requestAccounts(){if(this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let br;try{if(br=await this.initializeRelay().requestEthereumAccounts(),(0,Web3Response_1.isErrorResponse)(br))throw new Error(br.errorMessage)}catch(wr){throw typeof wr.message=="string"&&wr.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied account authorization"):wr}if(!br.result)throw new Error("accounts received is empty");return this._setAddresses(br.result),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._signEthereumMessage(Er,wr,!1)}_eth_ecRecover(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._ethereumAddressFromSignedMessage(wr,Er,!1)}_personal_sign(br){this._requireAuthorization();const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureAddressString)(br[1]);return this._signEthereumMessage(wr,Er,!0)}_personal_ecRecover(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),Er=(0,util_1$3.ensureBuffer)(br[1]);return this._ethereumAddressFromSignedMessage(wr,Er,!0)}async _eth_signTransaction(br){this._requireAuthorization();const wr=this._prepareTransactionParams(br[0]||{});try{const kr=await this.initializeRelay().signEthereumTransaction(wr);if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}catch(Er){throw typeof Er.message=="string"&&Er.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):Er}}async _eth_sendRawTransaction(br){const wr=(0,util_1$3.ensureBuffer)(br[0]),kr=await this.initializeRelay().submitEthereumTransaction(wr,this.getChainId());if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}async _eth_sendTransaction(br){this._requireAuthorization();const wr=this._prepareTransactionParams(br[0]||{});try{const kr=await this.initializeRelay().signAndSubmitEthereumTransaction(wr);if((0,Web3Response_1.isErrorResponse)(kr))throw new Error(kr.errorMessage);return{jsonrpc:"2.0",id:0,result:kr.result}}catch(Er){throw typeof Er.message=="string"&&Er.message.match(/(denied|rejected)/i)?error_1$5.standardErrors.provider.userRejectedRequest("User denied transaction signature"):Er}}async _eth_signTypedData_v1(br){this._requireAuthorization();const wr=(0,util_1$3.ensureParsedJSONObject)(br[0]),Er=(0,util_1$3.ensureAddressString)(br[1]);this._ensureKnownAddress(Er);const kr=eth_eip712_util_1.default.hashForSignTypedDataLegacy({data:wr}),jr=JSON.stringify(wr,null,2);return this._signEthereumMessage(kr,Er,!1,jr)}async _eth_signTypedData_v3(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureParsedJSONObject)(br[1]);this._ensureKnownAddress(wr);const kr=eth_eip712_util_1.default.hashForSignTypedData_v3({data:Er}),jr=JSON.stringify(Er,null,2);return this._signEthereumMessage(kr,wr,!1,jr)}async _eth_signTypedData_v4(br){this._requireAuthorization();const wr=(0,util_1$3.ensureAddressString)(br[0]),Er=(0,util_1$3.ensureParsedJSONObject)(br[1]);this._ensureKnownAddress(wr);const kr=eth_eip712_util_1.default.hashForSignTypedData_v4({data:Er}),jr=JSON.stringify(Er,null,2);return this._signEthereumMessage(kr,wr,!1,jr)}async _wallet_addEthereumChain(br){var wr,Er,kr,jr;const Br=br[0];if(((wr=Br.rpcUrls)===null||wr===void 0?void 0:wr.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!Br.chainName||Br.chainName.trim()==="")throw error_1$5.standardErrors.rpc.invalidParams("chainName is a required field");if(!Br.nativeCurrency)throw error_1$5.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const qr=parseInt(Br.chainId,16);return await this.addEthereumChain(qr,(Er=Br.rpcUrls)!==null&&Er!==void 0?Er:[],(kr=Br.blockExplorerUrls)!==null&&kr!==void 0?kr:[],Br.chainName,(jr=Br.iconUrls)!==null&&jr!==void 0?jr:[],Br.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(br){const wr=br[0];return await this.switchEthereumChain(parseInt(wr.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(br){const wr=Array.isArray(br)?br[0]:br;if(!wr.type)throw error_1$5.standardErrors.rpc.invalidParams("Type is required");if((wr==null?void 0:wr.type)!=="ERC20")throw error_1$5.standardErrors.rpc.invalidParams(`Asset of type '${wr.type}' is not supported`);if(!(wr!=null&&wr.options))throw error_1$5.standardErrors.rpc.invalidParams("Options are required");if(!(wr!=null&&wr.options.address))throw error_1$5.standardErrors.rpc.invalidParams("Address is required");const Er=this.getChainId(),{address:kr,symbol:jr,image:Br,decimals:qr}=wr.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(wr.type,kr,jr,qr,Br,Er)}}initializeRelay(){if(!this._relay){const br=new WalletLinkRelay_1.WalletLinkRelay({linkAPIUrl:constants_2.WALLETLINK_URL,storage:this._storage});br.setAppInfo(this._appName,this._appLogoUrl),br.attachUI(),br.setAccountsCallback((wr,Er)=>this._setAddresses(wr,Er)),br.setChainCallback((wr,Er)=>{this.updateProviderInfo(Er,parseInt(wr,10))}),this._relay=br}return this._relay}}WalletLinkSigner$1.WalletLinkSigner=WalletLinkSigner;var provider={};Object.defineProperty(provider,"__esModule",{value:!0});provider.checkErrorForInvalidRequestArgs=provider.getCoinbaseInjectedProvider=provider.getCoinbaseInjectedSigner=provider.fetchRPCRequest=void 0;const version_1$2=version$8,error_1$4=error;async function fetchRPCRequest(fr,br){if(!br.rpcUrl)throw error_1$4.standardErrors.rpc.internal("No RPC URL set for chain");const wr=Object.assign(Object.assign({},fr),{jsonrpc:"2.0",id:crypto.randomUUID()});return(await(await window.fetch(br.rpcUrl,{method:"POST",body:JSON.stringify(wr),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":version_1$2.LIB_VERSION}})).json()).result}provider.fetchRPCRequest=fetchRPCRequest;function getCoinbaseInjectedSigner(){return globalThis.coinbaseWalletSigner}provider.getCoinbaseInjectedSigner=getCoinbaseInjectedSigner;function getCoinbaseInjectedLegacyProvider(){return globalThis.coinbaseWalletExtension}function getInjectedEthereum(){var fr,br;try{const wr=globalThis;return(fr=wr.ethereum)!==null&&fr!==void 0?fr:(br=wr.top)===null||br===void 0?void 0:br.ethereum}catch{return}}function getCoinbaseInjectedProvider({metadata:fr,preference:br}){var wr;if(br.options!=="smartWalletOnly"){if(getCoinbaseInjectedSigner())return;const jr=getCoinbaseInjectedLegacyProvider();if(jr){const{appName:Br,appLogoUrl:qr,appChainIds:Wr}=fr;return(wr=jr.setAppInfo)===null||wr===void 0||wr.call(jr,Br,qr,Wr),jr}}const Er=getInjectedEthereum();if(Er!=null&&Er.isCoinbaseBrowser)return Er}provider.getCoinbaseInjectedProvider=getCoinbaseInjectedProvider;function checkErrorForInvalidRequestArgs(fr){if(!fr||typeof fr!="object"||Array.isArray(fr))return error_1$4.standardErrors.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:fr});const{method:br,params:wr}=fr;if(typeof br!="string"||br.length===0)return error_1$4.standardErrors.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:fr});if(wr!==void 0&&!Array.isArray(wr)&&(typeof wr!="object"||wr===null))return error_1$4.standardErrors.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:fr})}provider.checkErrorForInvalidRequestArgs=checkErrorForInvalidRequestArgs;Object.defineProperty(util$5,"__esModule",{value:!0});util$5.createSigner=util$5.fetchSignerType=util$5.storeSignerType=util$5.loadSignerType=void 0;const SCWSigner_1=SCWSigner$1,WalletLinkSigner_1=WalletLinkSigner$1,error_1$3=error,provider_1$2=provider,ScopedLocalStorage_1$2=ScopedLocalStorage$1,SIGNER_TYPE_KEY="SignerType",storage$1=new ScopedLocalStorage_1$2.ScopedLocalStorage("CBWSDK","SignerConfigurator");function loadSignerType(){return storage$1.getItem(SIGNER_TYPE_KEY)}util$5.loadSignerType=loadSignerType;function storeSignerType(fr){storage$1.setItem(SIGNER_TYPE_KEY,fr)}util$5.storeSignerType=storeSignerType;async function fetchSignerType(fr){const{communicator:br,metadata:wr}=fr;listenForWalletLinkSessionRequest(br,wr).catch(()=>{});const Er={id:crypto.randomUUID(),event:"selectSignerType",data:fr.preference},{data:kr}=await br.postRequestAndWaitForResponse(Er);return kr}util$5.fetchSignerType=fetchSignerType;function createSigner(fr){const{signerType:br,metadata:wr,communicator:Er,updateListener:kr}=fr;switch(br){case"scw":return new SCWSigner_1.SCWSigner({metadata:wr,updateListener:kr,communicator:Er});case"walletlink":return new WalletLinkSigner_1.WalletLinkSigner({metadata:wr,updateListener:kr});case"extension":{const jr=(0,provider_1$2.getCoinbaseInjectedSigner)();if(!jr)throw error_1$3.standardErrors.rpc.internal("injected signer not found");return jr}}}util$5.createSigner=createSigner;async function listenForWalletLinkSessionRequest(fr,br){await fr.onMessage(({event:Er})=>Er==="WalletLinkSessionRequest");const wr=new WalletLinkSigner_1.WalletLinkSigner({metadata:br});fr.postMessage({event:"WalletLinkUpdate",data:{session:wr.getSession()}}),await wr.handshake(),fr.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var Communicator$1={},util={};Object.defineProperty(util,"__esModule",{value:!0});util.closePopup=util.openPopup=void 0;const error_1$2=error,POPUP_WIDTH=420,POPUP_HEIGHT=540;function openPopup(fr){const br=(window.innerWidth-POPUP_WIDTH)/2+window.screenX,wr=(window.innerHeight-POPUP_HEIGHT)/2+window.screenY,Er=window.open(fr,"Smart Wallet",`width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${br}, top=${wr}`);if(Er==null||Er.focus(),!Er)throw error_1$2.standardErrors.rpc.internal("Pop up window failed to open");return Er}util.openPopup=openPopup;function closePopup(fr){fr&&!fr.closed&&fr.close()}util.closePopup=closePopup;Object.defineProperty(Communicator$1,"__esModule",{value:!0});Communicator$1.Communicator=void 0;const version_1$1=version$8,util_1$2=util,constants_1=constants,error_1$1=error;class Communicator{constructor(br=constants_1.CB_KEYS_URL){this.popup=null,this.listeners=new Map,this.postMessage=async wr=>{(await this.waitForPopupLoaded()).postMessage(wr,this.url.origin)},this.postRequestAndWaitForResponse=async wr=>{const Er=this.onMessage(({requestId:kr})=>kr===wr.id);return this.postMessage(wr),await Er},this.onMessage=async wr=>new Promise((Er,kr)=>{const jr=Br=>{if(Br.origin!==this.url.origin)return;const qr=Br.data;wr(qr)&&(Er(qr),window.removeEventListener("message",jr),this.listeners.delete(jr))};window.addEventListener("message",jr),this.listeners.set(jr,{reject:kr})}),this.disconnect=()=>{(0,util_1$2.closePopup)(this.popup),this.popup=null,this.listeners.forEach(({reject:wr},Er)=>{wr(error_1$1.standardErrors.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",Er)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=(0,util_1$2.openPopup)(this.url),this.onMessage(({event:wr})=>wr==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:wr})=>wr==="PopupLoaded").then(wr=>{this.postMessage({requestId:wr.id,data:{version:version_1$1.LIB_VERSION}})}).then(()=>{if(!this.popup)throw error_1$1.standardErrors.rpc.internal();return this.popup})),this.url=new URL(br)}}Communicator$1.Communicator=Communicator;var method={};Object.defineProperty(method,"__esModule",{value:!0});method.determineMethodCategory=void 0;const mapping={handshake:["eth_requestAccounts"],sign:["eth_ecRecover","personal_sign","personal_ecRecover","eth_signTransaction","eth_sendTransaction","eth_signTypedData_v1","eth_signTypedData_v3","eth_signTypedData_v4","eth_signTypedData","wallet_addEthereumChain","wallet_switchEthereumChain","wallet_watchAsset","wallet_getCapabilities","wallet_sendCalls","wallet_showCallsStatus"],state:["eth_chainId","eth_accounts","eth_coinbase","net_version"],deprecated:["eth_sign","eth_signTypedData_v2"],unsupported:["eth_subscribe","eth_unsubscribe"],fetch:[]};function determineMethodCategory(fr){for(const br in mapping){const wr=br;if(mapping[wr].includes(fr))return wr}}method.determineMethodCategory=determineMethodCategory;var __rest$2=commonjsGlobal&&commonjsGlobal.__rest||function(fr,br){var wr={};for(var Er in fr)Object.prototype.hasOwnProperty.call(fr,Er)&&br.indexOf(Er)<0&&(wr[Er]=fr[Er]);if(fr!=null&&typeof Object.getOwnPropertySymbols=="function")for(var kr=0,Er=Object.getOwnPropertySymbols(fr);kr{try{if(this.connected)return this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),this.accounts;const Hr=await this.requestSignerSelection(),Zr=this.initSigner(Hr),Jr=await Zr.handshake();return this.signer=Zr,(0,util_2.storeSignerType)(Hr),this.emit("connect",{chainId:(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id))}),Jr}catch(Hr){throw this.handleUnauthorizedError(Hr),Hr}},sign:async Vr=>{if(!this.connected||!this.signer)throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");try{return await this.signer.request(Vr)}catch(Hr){throw this.handleUnauthorizedError(Hr),Hr}},fetch:Vr=>(0,provider_1$1.fetchRPCRequest)(Vr,this.chain),state:Vr=>{const Hr=()=>{if(this.connected)return this.accounts;throw error_1.standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")};switch(Vr.method){case"eth_chainId":return(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(this.chain.id));case"net_version":return this.chain.id;case"eth_accounts":return Hr();case"eth_coinbase":return Hr()[0];default:return this.handlers.unsupported(Vr)}},deprecated:({method:Vr})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${Vr} is deprecated.`)},unsupported:({method:Vr})=>{throw error_1.standardErrors.rpc.methodNotSupported(`Method ${Vr} is not supported.`)}},this.isCoinbaseWallet=!0,this.updateListener={onAccountsUpdate:({accounts:Vr,source:Hr})=>{(0,util_1$1.areAddressArraysEqual)(this.accounts,Vr)||(this.accounts=Vr,Hr!=="storage"&&this.emit("accountsChanged",this.accounts))},onChainUpdate:({chain:Vr,source:Hr})=>{Vr.id===this.chain.id&&Vr.rpcUrl===this.chain.rpcUrl||(this.chain=Vr,Hr!=="storage"&&this.emit("chainChanged",(0,util_1$1.hexStringFromIntNumber)((0,type_1.IntNumber)(Vr.id))))}},this.metadata=kr,this.preference=qr,this.communicator=new Communicator_1.Communicator(Br),this.chain={id:(Er=(wr=kr.appChainIds)===null||wr===void 0?void 0:wr[0])!==null&&Er!==void 0?Er:1};const Wr=(0,util_2.loadSignerType)();this.signer=Wr?this.initSigner(Wr):null}get connected(){return this.accounts.length>0}async request(br){var wr;try{const Er=(0,provider_1$1.checkErrorForInvalidRequestArgs)(br);if(Er)throw Er;const kr=(wr=(0,method_1.determineMethodCategory)(br.method))!==null&&wr!==void 0?wr:"fetch";return this.handlers[kr](br)}catch(Er){return Promise.reject((0,serialize_1$1.serializeError)(Er,br.method))}}handleUnauthorizedError(br){br.code===error_1.standardErrorCodes.provider.unauthorized&&this.disconnect()}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){this.accounts=[],this.chain={id:1},ScopedLocalStorage_1$1.ScopedLocalStorage.clearAll(),this.emit("disconnect",error_1.standardErrors.provider.disconnected("User initiated disconnection"))}requestSignerSelection(){return(0,util_2.fetchSignerType)({communicator:this.communicator,preference:this.preference,metadata:this.metadata})}initSigner(br){return(0,util_2.createSigner)({signerType:br,metadata:this.metadata,communicator:this.communicator,updateListener:this.updateListener})}}CoinbaseWalletProvider$1.CoinbaseWalletProvider=CoinbaseWalletProvider;Object.defineProperty(CoinbaseWalletSDK$1,"__esModule",{value:!0});CoinbaseWalletSDK$1.CoinbaseWalletSDK=void 0;const wallet_logo_1=walletLogo$1,CoinbaseWalletProvider_1=CoinbaseWalletProvider$1,ScopedLocalStorage_1=ScopedLocalStorage$1,version_1=version$8,util_1=util$6,provider_1=provider;class CoinbaseWalletSDK{constructor(br){this.metadata={appName:br.appName||"Dapp",appLogoUrl:br.appLogoUrl||(0,util_1.getFavicon)(),appChainIds:br.appChainIds||[]},this.storeLatestVersion()}makeWeb3Provider(br={options:"all"}){var wr;const Er={metadata:this.metadata,preference:br};return(wr=(0,provider_1.getCoinbaseInjectedProvider)(Er))!==null&&wr!==void 0?wr:new CoinbaseWalletProvider_1.CoinbaseWalletProvider(Er)}getCoinbaseWalletLogo(br,wr=240){return(0,wallet_logo_1.walletLogo)(br,wr)}storeLatestVersion(){new ScopedLocalStorage_1.ScopedLocalStorage("CBWSDK").setItem("VERSION",version_1.LIB_VERSION)}}CoinbaseWalletSDK$1.CoinbaseWalletSDK=CoinbaseWalletSDK;(function(fr){Object.defineProperty(fr,"__esModule",{value:!0}),fr.CoinbaseWalletSDK=void 0;const br=CoinbaseWalletSDK$1;fr.default=br.CoinbaseWalletSDK;var wr=CoinbaseWalletSDK$1;Object.defineProperty(fr,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return wr.CoinbaseWalletSDK}})})(dist);let coinbaseProvider;const baseSepolia=84532,baseMainnet=8453,getCoinbaseProvider=({appLogoUrl:fr,appName:br,evmNetworks:wr,walletPreference:Er}={})=>{const kr=wr==null?void 0:wr.map(qr=>Number(qr.chainId));return(wr==null?void 0:wr.some(qr=>qr.chainId===baseSepolia))&&(kr==null||kr.sort((qr,Wr)=>qr===baseSepolia?-1:Wr===baseSepolia?1:0)),(wr==null?void 0:wr.some(qr=>qr.chainId===baseMainnet))&&(kr==null||kr.sort((qr,Wr)=>qr===baseMainnet?-1:Wr===baseMainnet?1:0)),coinbaseProvider||(coinbaseProvider=new dist.CoinbaseWalletSDK({appChainIds:kr,appLogoUrl:fr,appName:br}).makeWeb3Provider({options:Er??"all"})),coinbaseProvider};class Coinbase extends EthereumWalletConnector{constructor(br){var{appName:wr,appLogoUrl:Er,evmNetworks:kr,coinbaseWalletPreference:jr}=br,Br=__rest$6(br,["appName","appLogoUrl","evmNetworks","coinbaseWalletPreference"]);super(Object.assign({evmNetworks:kr},Br)),this.name="Coinbase",this.overrideKey="coinbase",this.supportedChains=["EVM","ETH"],this.connectedChain="EVM",this.canConnectViaQrCode=!1,this.canConnectViaCustodialService=!this.isInstalledOnBrowser(),this.coinbaseProviderOpts={appLogoUrl:Er,appName:wr,evmNetworks:kr,walletPreference:jr}}get coinbaseProvider(){return getCoinbaseProvider(this.coinbaseProviderOpts)}getConnectedAccounts(){return __awaiter$8(this,void 0,void 0,function*(){try{const br=yield this.coinbaseProvider.request({method:"eth_accounts"});return br[0]&&this.setActiveAccount(br[0]),br}catch{return[]}})}isInstalledOnBrowser(){var br;return!!(!((br=window==null?void 0:window.coinbaseWalletExtension)===null||br===void 0)&&br.isCoinbaseWallet)}getAddress(){return __awaiter$8(this,void 0,void 0,function*(){const[br]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});return this.setActiveAccount(br),br})}signMessage(br){return __awaiter$8(this,void 0,void 0,function*(){const[wr]=yield this.coinbaseProvider.request({method:"eth_requestAccounts"});try{return yield this.coinbaseProvider.request({method:"personal_sign",params:[toHex$1(toBytes$4(br)),wr.toLowerCase()]})}catch{return}})}setupEventListeners(){const{handleAccountChange:br,handleChainChange:wr,handleDisconnect:Er}=eventListenerHandlers(this);this.coinbaseProvider.on("accountsChanged",br),this.coinbaseProvider.on("chainChanged",wr),this.coinbaseProvider.on("disconnect",Er),this.teardownEventListeners=()=>{this.coinbaseProvider.removeListener("accountsChanged",br),this.coinbaseProvider.removeListener("chainChanged",wr),this.coinbaseProvider.removeListener("disconnect",Er)}}getWalletClient(br){return createWalletClient$1({account:this.getActiveAccount(),chain:br?chainsMap[br]:void 0,transport:custom$1(this.coinbaseProvider)})}}assertPackageVersion("@dynamic-labs/ethereum",version$9);const EthereumWalletConnectors=fr=>[...injectedWalletOverrides$1,...fetchInjectedWalletConnector(fr),...fetchWalletConnectWallets(fr),...TurnkeyEVMWalletConnectors(fr),Coinbase,UnknownInjected$1,FallbackEvmConnector,getWalletConnectConnector()];var version$7="3.8.2",version$6="3.8.2";function __awaiter$4(fr,br,wr,Er){function kr(jr){return jr instanceof wr?jr:new wr(function(Br){Br(jr)})}return new(wr||(wr=Promise))(function(jr,Br){function qr(Hr){try{Vr(Er.next(Hr))}catch(Zr){Br(Zr)}}function Wr(Hr){try{Vr(Er.throw(Hr))}catch(Zr){Br(Zr)}}function Vr(Hr){Hr.done?jr(Hr.value):kr(Hr.value).then(qr,Wr)}Vr((Er=Er.apply(fr,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(fr,br=!1){return br?{h:Number(fr&U32_MASK64),l:Number(fr>>_32n&U32_MASK64)}:{h:Number(fr>>_32n&U32_MASK64)|0,l:Number(fr&U32_MASK64)|0}}function split(fr,br=!1){let wr=new Uint32Array(fr.length),Er=new Uint32Array(fr.length);for(let kr=0;krBigInt(fr>>>0)<<_32n|BigInt(br>>>0),shrSH=(fr,br,wr)=>fr>>>wr,shrSL=(fr,br,wr)=>fr<<32-wr|br>>>wr,rotrSH=(fr,br,wr)=>fr>>>wr|br<<32-wr,rotrSL=(fr,br,wr)=>fr<<32-wr|br>>>wr,rotrBH=(fr,br,wr)=>fr<<64-wr|br>>>wr-32,rotrBL=(fr,br,wr)=>fr>>>wr-32|br<<64-wr,rotr32H=(fr,br)=>br,rotr32L=(fr,br)=>fr,rotlSH=(fr,br,wr)=>fr<>>32-wr,rotlSL=(fr,br,wr)=>br<>>32-wr,rotlBH=(fr,br,wr)=>br<>>64-wr,rotlBL=(fr,br,wr)=>fr<>>64-wr;function add(fr,br,wr,Er){const kr=(br>>>0)+(Er>>>0);return{h:fr+wr+(kr/2**32|0)|0,l:kr|0}}const add3L=(fr,br,wr)=>(fr>>>0)+(br>>>0)+(wr>>>0),add3H=(fr,br,wr,Er)=>br+wr+Er+(fr/2**32|0)|0,add4L=(fr,br,wr,Er)=>(fr>>>0)+(br>>>0)+(wr>>>0)+(Er>>>0),add4H=(fr,br,wr,Er,kr)=>br+wr+Er+kr+(fr/2**32|0)|0,add5L=(fr,br,wr,Er,kr)=>(fr>>>0)+(br>>>0)+(wr>>>0)+(Er>>>0)+(kr>>>0),add5H=(fr,br,wr,Er,kr,jr)=>br+wr+Er+kr+jr+(fr/2**32|0)|0,u64$4={fromBig,split,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$4.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(fr=>BigInt(fr))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{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:br,Al:wr,Bh:Er,Bl:kr,Ch:jr,Cl:Br,Dh:qr,Dl:Wr,Eh:Vr,El:Hr,Fh:Zr,Fl:Jr,Gh:Xr,Gl:En,Hh:wn,Hl:$n}=this;return[br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n]}set(br,wr,Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n){this.Ah=br|0,this.Al=wr|0,this.Bh=Er|0,this.Bl=kr|0,this.Ch=jr|0,this.Cl=Br|0,this.Dh=qr|0,this.Dl=Wr|0,this.Eh=Vr|0,this.El=Hr|0,this.Fh=Zr|0,this.Fl=Jr|0,this.Gh=Xr|0,this.Gl=En|0,this.Hh=wn|0,this.Hl=$n|0}process(br,wr){for(let jn=0;jn<16;jn++,wr+=4)SHA512_W_H[jn]=br.getUint32(wr),SHA512_W_L[jn]=br.getUint32(wr+=4);for(let jn=16;jn<80;jn++){const Yn=SHA512_W_H[jn-15]|0,ga=SHA512_W_L[jn-15]|0,na=u64$4.rotrSH(Yn,ga,1)^u64$4.rotrSH(Yn,ga,8)^u64$4.shrSH(Yn,ga,7),_i=u64$4.rotrSL(Yn,ga,1)^u64$4.rotrSL(Yn,ga,8)^u64$4.shrSL(Yn,ga,7),ro=SHA512_W_H[jn-2]|0,to=SHA512_W_L[jn-2]|0,io=u64$4.rotrSH(ro,to,19)^u64$4.rotrBH(ro,to,61)^u64$4.shrSH(ro,to,6),no=u64$4.rotrSL(ro,to,19)^u64$4.rotrBL(ro,to,61)^u64$4.shrSL(ro,to,6),$a=u64$4.add4L(_i,no,SHA512_W_L[jn-7],SHA512_W_L[jn-16]),Rn=u64$4.add4H($a,na,io,SHA512_W_H[jn-7],SHA512_W_H[jn-16]);SHA512_W_H[jn]=Rn|0,SHA512_W_L[jn]=$a|0}let{Ah:Er,Al:kr,Bh:jr,Bl:Br,Ch:qr,Cl:Wr,Dh:Vr,Dl:Hr,Eh:Zr,El:Jr,Fh:Xr,Fl:En,Gh:wn,Gl:$n,Hh:Tn,Hl:In}=this;for(let jn=0;jn<80;jn++){const Yn=u64$4.rotrSH(Zr,Jr,14)^u64$4.rotrSH(Zr,Jr,18)^u64$4.rotrBH(Zr,Jr,41),ga=u64$4.rotrSL(Zr,Jr,14)^u64$4.rotrSL(Zr,Jr,18)^u64$4.rotrBL(Zr,Jr,41),na=Zr&Xr^~Zr&wn,_i=Jr&En^~Jr&$n,ro=u64$4.add5L(In,ga,_i,SHA512_Kl[jn],SHA512_W_L[jn]),to=u64$4.add5H(ro,Tn,Yn,na,SHA512_Kh[jn],SHA512_W_H[jn]),io=ro|0,no=u64$4.rotrSH(Er,kr,28)^u64$4.rotrBH(Er,kr,34)^u64$4.rotrBH(Er,kr,39),$a=u64$4.rotrSL(Er,kr,28)^u64$4.rotrBL(Er,kr,34)^u64$4.rotrBL(Er,kr,39),Rn=Er&jr^Er&qr^jr&qr,Gr=kr&Br^kr&Wr^Br&Wr;Tn=wn|0,In=$n|0,wn=Xr|0,$n=En|0,Xr=Zr|0,En=Jr|0,{h:Zr,l:Jr}=u64$4.add(Vr|0,Hr|0,to|0,io|0),Vr=qr|0,Hr=Wr|0,qr=jr|0,Wr=Br|0,jr=Er|0,Br=kr|0;const Yr=u64$4.add3L(io,$a,Gr);Er=u64$4.add3H(Yr,to,no,Rn),kr=Yr|0}({h:Er,l:kr}=u64$4.add(this.Ah|0,this.Al|0,Er|0,kr|0)),{h:jr,l:Br}=u64$4.add(this.Bh|0,this.Bl|0,jr|0,Br|0),{h:qr,l:Wr}=u64$4.add(this.Ch|0,this.Cl|0,qr|0,Wr|0),{h:Vr,l:Hr}=u64$4.add(this.Dh|0,this.Dl|0,Vr|0,Hr|0),{h:Zr,l:Jr}=u64$4.add(this.Eh|0,this.El|0,Zr|0,Jr|0),{h:Xr,l:En}=u64$4.add(this.Fh|0,this.Fl|0,Xr|0,En|0),{h:wn,l:$n}=u64$4.add(this.Gh|0,this.Gl|0,wn|0,$n|0),{h:Tn,l:In}=u64$4.add(this.Hh|0,this.Hl|0,Tn|0,In|0),this.set(Er,kr,jr,Br,qr,Wr,Vr,Hr,Zr,Jr,Xr,En,wn,$n,Tn,In)}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);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n$1=BigInt(1),_2n$1=BigInt(2),_8n$1=BigInt(8),VERIFY_DEFAULT={zip215:!0};function validateOpts(fr){const br=validateBasic(fr);return validateObject(fr,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...br})}function twistedEdwards(fr){const br=validateOpts(fr),{Fp:wr,n:Er,prehash:kr,hash:jr,randomBytes:Br,nByteLength:qr,h:Wr}=br,Vr=_2n$1<{try{return{isValid:!0,value:wr.sqrt(Sn*wr.inv(An))}}catch{return{isValid:!1,value:_0n}}}),Xr=br.adjustScalarBytes||(Sn=>Sn),En=br.domain||((Sn,An,Pn)=>{if(abool("phflag",Pn),An.length||Pn)throw new Error("Contexts/pre-hash are not supported");return Sn});function wn(Sn,An){aInRange("coordinate "+Sn,An,_0n,Vr)}function $n(Sn){if(!(Sn instanceof jn))throw new Error("ExtendedPoint expected")}const Tn=memoized((Sn,An)=>{const{ex:Pn,ey:Nn,ez:zn}=Sn,On=Sn.is0();An==null&&(An=On?_8n$1:wr.inv(zn));const _n=Hr(Pn*An),Zn=Hr(Nn*An),oo=Hr(zn*An);if(On)return{x:_0n,y:_1n$1};if(oo!==_1n$1)throw new Error("invZ was invalid");return{x:_n,y:Zn}}),In=memoized(Sn=>{const{a:An,d:Pn}=br;if(Sn.is0())throw new Error("bad point: ZERO");const{ex:Nn,ey:zn,ez:On,et:_n}=Sn,Zn=Hr(Nn*Nn),oo=Hr(zn*zn),uo=Hr(On*On),lo=Hr(uo*uo),co=Hr(Zn*An),so=Hr(uo*Hr(co+oo)),yo=Hr(lo+Hr(Pn*Hr(Zn*oo)));if(so!==yo)throw new Error("bad point: equation left != right (1)");const fo=Hr(Nn*zn),ho=Hr(On*_n);if(fo!==ho)throw new Error("bad point: equation left != right (2)");return!0});class jn{constructor(An,Pn,Nn,zn){this.ex=An,this.ey=Pn,this.ez=Nn,this.et=zn,wn("x",An),wn("y",Pn),wn("z",Nn),wn("t",zn),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(An){if(An instanceof jn)throw new Error("extended point not allowed");const{x:Pn,y:Nn}=An||{};return wn("x",Pn),wn("y",Nn),new jn(Pn,Nn,_1n$1,Hr(Pn*Nn))}static normalizeZ(An){const Pn=wr.invertBatch(An.map(Nn=>Nn.ez));return An.map((Nn,zn)=>Nn.toAffine(Pn[zn])).map(jn.fromAffine)}static msm(An,Pn){return pippenger(jn,Zr,An,Pn)}_setWindowSize(An){na.setWindowSize(this,An)}assertValidity(){In(this)}equals(An){$n(An);const{ex:Pn,ey:Nn,ez:zn}=this,{ex:On,ey:_n,ez:Zn}=An,oo=Hr(Pn*Zn),uo=Hr(On*zn),lo=Hr(Nn*Zn),co=Hr(_n*zn);return oo===uo&&lo===co}is0(){return this.equals(jn.ZERO)}negate(){return new jn(Hr(-this.ex),this.ey,this.ez,Hr(-this.et))}double(){const{a:An}=br,{ex:Pn,ey:Nn,ez:zn}=this,On=Hr(Pn*Pn),_n=Hr(Nn*Nn),Zn=Hr(_2n$1*Hr(zn*zn)),oo=Hr(An*On),uo=Pn+Nn,lo=Hr(Hr(uo*uo)-On-_n),co=oo+_n,so=co-Zn,yo=oo-_n,fo=Hr(lo*so),ho=Hr(co*yo),vo=Hr(lo*yo),Io=Hr(so*co);return new jn(fo,ho,Io,vo)}add(An){$n(An);const{a:Pn,d:Nn}=br,{ex:zn,ey:On,ez:_n,et:Zn}=this,{ex:oo,ey:uo,ez:lo,et:co}=An;if(Pn===BigInt(-1)){const jo=Hr((On-zn)*(uo+oo)),No=Hr((On+zn)*(uo-oo)),Tl=Hr(No-jo);if(Tl===_0n)return this.double();const Fo=Hr(_n*_2n$1*co),Lo=Hr(Zn*_2n$1*lo),Rl=Lo+Fo,_c=No+jo,Ko=Lo-Fo,zl=Hr(Rl*Tl),Sl=Hr(_c*Ko),Eo=Hr(Rl*Ko),bo=Hr(Tl*_c);return new jn(zl,Sl,bo,Eo)}const so=Hr(zn*oo),yo=Hr(On*uo),fo=Hr(Zn*Nn*co),ho=Hr(_n*lo),vo=Hr((zn+On)*(oo+uo)-so-yo),Io=ho-fo,Ro=ho+fo,To=Hr(yo-Pn*so),Wo=Hr(vo*Io),qo=Hr(Ro*To),Zo=Hr(vo*To),Qo=Hr(Io*Ro);return new jn(Wo,qo,Qo,Zo)}subtract(An){return this.add(An.negate())}wNAF(An){return na.wNAFCached(this,An,jn.normalizeZ)}multiply(An){const Pn=An;aInRange("scalar",Pn,_1n$1,Er);const{p:Nn,f:zn}=this.wNAF(Pn);return jn.normalizeZ([Nn,zn])[0]}multiplyUnsafe(An,Pn=jn.ZERO){const Nn=An;return aInRange("scalar",Nn,_0n,Er),Nn===_0n?ga:this.is0()||Nn===_1n$1?this:na.wNAFCachedUnsafe(this,Nn,jn.normalizeZ,Pn)}isSmallOrder(){return this.multiplyUnsafe(Wr).is0()}isTorsionFree(){return na.unsafeLadder(this,Er).is0()}toAffine(An){return Tn(this,An)}clearCofactor(){const{h:An}=br;return An===_1n$1?this:this.multiplyUnsafe(An)}static fromHex(An,Pn=!1){const{d:Nn,a:zn}=br,On=wr.BYTES;An=ensureBytes("pointHex",An,On),abool("zip215",Pn);const _n=An.slice(),Zn=An[On-1];_n[On-1]=Zn&-129;const oo=bytesToNumberLE(_n),uo=Pn?Vr:wr.ORDER;aInRange("pointHex.y",oo,_0n,uo);const lo=Hr(oo*oo),co=Hr(lo-_1n$1),so=Hr(Nn*lo-zn);let{isValid:yo,value:fo}=Jr(co,so);if(!yo)throw new Error("Point.fromHex: invalid y coordinate");const ho=(fo&_1n$1)===_1n$1,vo=(Zn&128)!==0;if(!Pn&&fo===_0n&&vo)throw new Error("Point.fromHex: x=0 and x_0=1");return vo!==ho&&(fo=Hr(-fo)),jn.fromAffine({x:fo,y:oo})}static fromPrivateKey(An){return to(An).point}toRawBytes(){const{x:An,y:Pn}=this.toAffine(),Nn=numberToBytesLE(Pn,wr.BYTES);return Nn[Nn.length-1]|=An&_1n$1?128:0,Nn}toHex(){return bytesToHex(this.toRawBytes())}}jn.BASE=new jn(br.Gx,br.Gy,_1n$1,Hr(br.Gx*br.Gy)),jn.ZERO=new jn(_0n,_1n$1,_1n$1,_0n);const{BASE:Yn,ZERO:ga}=jn,na=wNAF(jn,qr*8);function _i(Sn){return mod(Sn,Er)}function ro(Sn){return _i(bytesToNumberLE(Sn))}function to(Sn){const An=wr.BYTES;Sn=ensureBytes("private key",Sn,An);const Pn=ensureBytes("hashed private key",jr(Sn),2*An),Nn=Xr(Pn.slice(0,An)),zn=Pn.slice(An,2*An),On=ro(Nn),_n=Yn.multiply(On),Zn=_n.toRawBytes();return{head:Nn,prefix:zn,scalar:On,point:_n,pointBytes:Zn}}function io(Sn){return to(Sn).pointBytes}function no(Sn=new Uint8Array,...An){const Pn=concatBytes(...An);return ro(jr(En(Pn,ensureBytes("context",Sn),!!kr)))}function $a(Sn,An,Pn={}){Sn=ensureBytes("message",Sn),kr&&(Sn=kr(Sn));const{prefix:Nn,scalar:zn,pointBytes:On}=to(An),_n=no(Pn.context,Nn,Sn),Zn=Yn.multiply(_n).toRawBytes(),oo=no(Pn.context,Zn,On,Sn),uo=_i(_n+oo*zn);aInRange("signature.s",uo,_0n,Er);const lo=concatBytes(Zn,numberToBytesLE(uo,wr.BYTES));return ensureBytes("result",lo,wr.BYTES*2)}const Rn=VERIFY_DEFAULT;function Gr(Sn,An,Pn,Nn=Rn){const{context:zn,zip215:On}=Nn,_n=wr.BYTES;Sn=ensureBytes("signature",Sn,2*_n),An=ensureBytes("message",An),Pn=ensureBytes("publicKey",Pn,_n),On!==void 0&&abool("zip215",On),kr&&(An=kr(An));const Zn=bytesToNumberLE(Sn.slice(_n,2*_n));let oo,uo,lo;try{oo=jn.fromHex(Pn,On),uo=jn.fromHex(Sn.slice(0,_n),On),lo=Yn.multiplyUnsafe(Zn)}catch{return!1}if(!On&&oo.isSmallOrder())return!1;const co=no(zn,uo.toRawBytes(),oo.toRawBytes(),An);return uo.add(oo.multiplyUnsafe(co)).subtract(lo).clearCofactor().equals(jn.ZERO)}return Yn._setWindowSize(8),{CURVE:br,getPublicKey:io,sign:$a,verify:Gr,ExtendedPoint:jn,utils:{getExtendedPublicKey:to,randomPrivateKey:()=>Br(wr.BYTES),precompute(Sn=8,An=jn.BASE){return An._setWindowSize(Sn),An.multiply(BigInt(3)),An}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const _1n=BigInt(1),_2n=BigInt(2);BigInt(3);const _5n=BigInt(5),_8n=BigInt(8);function ed25519_pow_2_252_3(fr){const br=BigInt(10),wr=BigInt(20),Er=BigInt(40),kr=BigInt(80),jr=ED25519_P,qr=fr*fr%jr*fr%jr,Wr=pow2(qr,_2n,jr)*qr%jr,Vr=pow2(Wr,_1n,jr)*fr%jr,Hr=pow2(Vr,_5n,jr)*Vr%jr,Zr=pow2(Hr,br,jr)*Hr%jr,Jr=pow2(Zr,wr,jr)*Zr%jr,Xr=pow2(Jr,Er,jr)*Jr%jr,En=pow2(Xr,kr,jr)*Xr%jr,wn=pow2(En,kr,jr)*Xr%jr,$n=pow2(wn,br,jr)*Hr%jr;return{pow_p_5_8:pow2($n,_2n,jr)*fr%jr,b2:qr}}function adjustScalarBytes(fr){return fr[0]&=248,fr[31]&=127,fr[31]|=64,fr}function uvRatio(fr,br){const wr=ED25519_P,Er=mod(br*br*br,wr),kr=mod(Er*Er*br,wr),jr=ed25519_pow_2_252_3(fr*kr).pow_p_5_8;let Br=mod(fr*Er*jr,wr);const qr=mod(br*Br*Br,wr),Wr=Br,Vr=mod(Br*ED25519_SQRT_M1,wr),Hr=qr===fr,Zr=qr===mod(-fr,wr),Jr=qr===mod(-fr*ED25519_SQRT_M1,wr);return Hr&&(Br=Wr),(Zr||Jr)&&(Br=Vr),isNegativeLE(Br,wr)&&(Br=mod(-Br,wr)),{isValid:Hr||Zr,value:Br}}const Fp=Field(ED25519_P,void 0,!0),ed25519Defaults={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_8n,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sha512,randomBytes,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults);var bn$3={exports:{}};bn$3.exports;(function(fr){(function(br,wr){function Er(Rn,Gr){if(!Rn)throw new Error(Gr||"Assertion failed")}function kr(Rn,Gr){Rn.super_=Gr;var Yr=function(){};Yr.prototype=Gr.prototype,Rn.prototype=new Yr,Rn.prototype.constructor=Rn}function jr(Rn,Gr,Yr){if(jr.isBN(Rn))return Rn;this.negative=0,this.words=null,this.length=0,this.red=null,Rn!==null&&((Gr==="le"||Gr==="be")&&(Yr=Gr,Gr=10),this._init(Rn||0,Gr||10,Yr||"be"))}typeof br=="object"?br.exports=jr:wr.BN=jr,jr.BN=jr,jr.wordSize=26;var Br;try{typeof window<"u"&&typeof window.Buffer<"u"?Br=window.Buffer:Br=require$$0$9.Buffer}catch{}jr.isBN=function(Gr){return Gr instanceof jr?!0:Gr!==null&&typeof Gr=="object"&&Gr.constructor.wordSize===jr.wordSize&&Array.isArray(Gr.words)},jr.max=function(Gr,Yr){return Gr.cmp(Yr)>0?Gr:Yr},jr.min=function(Gr,Yr){return Gr.cmp(Yr)<0?Gr:Yr},jr.prototype._init=function(Gr,Yr,Sn){if(typeof Gr=="number")return this._initNumber(Gr,Yr,Sn);if(typeof Gr=="object")return this._initArray(Gr,Yr,Sn);Yr==="hex"&&(Yr=16),Er(Yr===(Yr|0)&&Yr>=2&&Yr<=36),Gr=Gr.toString().replace(/\s+/g,"");var An=0;Gr[0]==="-"&&(An++,this.negative=1),An=0;An-=3)Nn=Gr[An]|Gr[An-1]<<8|Gr[An-2]<<16,this.words[Pn]|=Nn<>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);else if(Sn==="le")for(An=0,Pn=0;An>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);return this._strip()};function qr(Rn,Gr){var Yr=Rn.charCodeAt(Gr);if(Yr>=48&&Yr<=57)return Yr-48;if(Yr>=65&&Yr<=70)return Yr-55;if(Yr>=97&&Yr<=102)return Yr-87;Er(!1,"Invalid character in "+Rn)}function Wr(Rn,Gr,Yr){var Sn=qr(Rn,Yr);return Yr-1>=Gr&&(Sn|=qr(Rn,Yr-1)<<4),Sn}jr.prototype._parseHex=function(Gr,Yr,Sn){this.length=Math.ceil((Gr.length-Yr)/6),this.words=new Array(this.length);for(var An=0;An=Yr;An-=2)zn=Wr(Gr,Yr,An)<=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8;else{var On=Gr.length-Yr;for(An=On%2===0?Yr+1:Yr;An=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8}this._strip()};function Vr(Rn,Gr,Yr,Sn){for(var An=0,Pn=0,Nn=Math.min(Rn.length,Yr),zn=Gr;zn=49?Pn=On-49+10:On>=17?Pn=On-17+10:Pn=On,Er(On>=0&&Pn1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},jr.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{jr.prototype[Symbol.for("nodejs.util.inspect.custom")]=Zr}catch{jr.prototype.inspect=Zr}else jr.prototype.inspect=Zr;function Zr(){return(this.red?""}var Jr=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],Xr=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],En=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];jr.prototype.toString=function(Gr,Yr){Gr=Gr||10,Yr=Yr|0||1;var Sn;if(Gr===16||Gr==="hex"){Sn="";for(var An=0,Pn=0,Nn=0;Nn>>24-An&16777215,An+=2,An>=26&&(An-=26,Nn--),Pn!==0||Nn!==this.length-1?Sn=Jr[6-On.length]+On+Sn:Sn=On+Sn}for(Pn!==0&&(Sn=Pn.toString(16)+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}if(Gr===(Gr|0)&&Gr>=2&&Gr<=36){var _n=Xr[Gr],Zn=En[Gr];Sn="";var oo=this.clone();for(oo.negative=0;!oo.isZero();){var uo=oo.modrn(Zn).toString(Gr);oo=oo.idivn(Zn),oo.isZero()?Sn=uo+Sn:Sn=Jr[_n-uo.length]+uo+Sn}for(this.isZero()&&(Sn="0"+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}Er(!1,"Base should be between 2 and 36")},jr.prototype.toNumber=function(){var Gr=this.words[0];return this.length===2?Gr+=this.words[1]*67108864:this.length===3&&this.words[2]===1?Gr+=4503599627370496+this.words[1]*67108864:this.length>2&&Er(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-Gr:Gr},jr.prototype.toJSON=function(){return this.toString(16,2)},Br&&(jr.prototype.toBuffer=function(Gr,Yr){return this.toArrayLike(Br,Gr,Yr)}),jr.prototype.toArray=function(Gr,Yr){return this.toArrayLike(Array,Gr,Yr)};var wn=function(Gr,Yr){return Gr.allocUnsafe?Gr.allocUnsafe(Yr):new Gr(Yr)};jr.prototype.toArrayLike=function(Gr,Yr,Sn){this._strip();var An=this.byteLength(),Pn=Sn||Math.max(1,An);Er(An<=Pn,"byte array longer than desired length"),Er(Pn>0,"Requested array length <= 0");var Nn=wn(Gr,Pn),zn=Yr==="le"?"LE":"BE";return this["_toArrayLike"+zn](Nn,An),Nn},jr.prototype._toArrayLikeLE=function(Gr,Yr){for(var Sn=0,An=0,Pn=0,Nn=0;Pn>8&255),Sn>16&255),Nn===6?(Sn>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn=0&&(Gr[Sn--]=zn>>8&255),Sn>=0&&(Gr[Sn--]=zn>>16&255),Nn===6?(Sn>=0&&(Gr[Sn--]=zn>>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn>=0)for(Gr[Sn--]=An;Sn>=0;)Gr[Sn--]=0},Math.clz32?jr.prototype._countBits=function(Gr){return 32-Math.clz32(Gr)}:jr.prototype._countBits=function(Gr){var Yr=Gr,Sn=0;return Yr>=4096&&(Sn+=13,Yr>>>=13),Yr>=64&&(Sn+=7,Yr>>>=7),Yr>=8&&(Sn+=4,Yr>>>=4),Yr>=2&&(Sn+=2,Yr>>>=2),Sn+Yr},jr.prototype._zeroBits=function(Gr){if(Gr===0)return 26;var Yr=Gr,Sn=0;return Yr&8191||(Sn+=13,Yr>>>=13),Yr&127||(Sn+=7,Yr>>>=7),Yr&15||(Sn+=4,Yr>>>=4),Yr&3||(Sn+=2,Yr>>>=2),Yr&1||Sn++,Sn},jr.prototype.bitLength=function(){var Gr=this.words[this.length-1],Yr=this._countBits(Gr);return(this.length-1)*26+Yr};function $n(Rn){for(var Gr=new Array(Rn.bitLength()),Yr=0;Yr>>An&1}return Gr}jr.prototype.zeroBits=function(){if(this.isZero())return 0;for(var Gr=0,Yr=0;YrGr.length?this.clone().ior(Gr):Gr.clone().ior(this)},jr.prototype.uor=function(Gr){return this.length>Gr.length?this.clone().iuor(Gr):Gr.clone().iuor(this)},jr.prototype.iuand=function(Gr){var Yr;this.length>Gr.length?Yr=Gr:Yr=this;for(var Sn=0;SnGr.length?this.clone().iand(Gr):Gr.clone().iand(this)},jr.prototype.uand=function(Gr){return this.length>Gr.length?this.clone().iuand(Gr):Gr.clone().iuand(this)},jr.prototype.iuxor=function(Gr){var Yr,Sn;this.length>Gr.length?(Yr=this,Sn=Gr):(Yr=Gr,Sn=this);for(var An=0;AnGr.length?this.clone().ixor(Gr):Gr.clone().ixor(this)},jr.prototype.uxor=function(Gr){return this.length>Gr.length?this.clone().iuxor(Gr):Gr.clone().iuxor(this)},jr.prototype.inotn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Math.ceil(Gr/26)|0,Sn=Gr%26;this._expand(Yr),Sn>0&&Yr--;for(var An=0;An0&&(this.words[An]=~this.words[An]&67108863>>26-Sn),this._strip()},jr.prototype.notn=function(Gr){return this.clone().inotn(Gr)},jr.prototype.setn=function(Gr,Yr){Er(typeof Gr=="number"&&Gr>=0);var Sn=Gr/26|0,An=Gr%26;return this._expand(Sn+1),Yr?this.words[Sn]=this.words[Sn]|1<Gr.length?(Sn=this,An=Gr):(Sn=Gr,An=this);for(var Pn=0,Nn=0;Nn>>26;for(;Pn!==0&&Nn>>26;if(this.length=Sn.length,Pn!==0)this.words[this.length]=Pn,this.length++;else if(Sn!==this)for(;NnGr.length?this.clone().iadd(Gr):Gr.clone().iadd(this)},jr.prototype.isub=function(Gr){if(Gr.negative!==0){Gr.negative=0;var Yr=this.iadd(Gr);return Gr.negative=1,Yr._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(Gr),this.negative=1,this._normSign();var Sn=this.cmp(Gr);if(Sn===0)return this.negative=0,this.length=1,this.words[0]=0,this;var An,Pn;Sn>0?(An=this,Pn=Gr):(An=Gr,Pn=this);for(var Nn=0,zn=0;zn>26,this.words[zn]=Yr&67108863;for(;Nn!==0&&zn>26,this.words[zn]=Yr&67108863;if(Nn===0&&zn>>26,oo=On&67108863,uo=Math.min(_n,Gr.length-1),lo=Math.max(0,_n-Rn.length+1);lo<=uo;lo++){var co=_n-lo|0;An=Rn.words[co]|0,Pn=Gr.words[lo]|0,Nn=An*Pn+oo,Zn+=Nn/67108864|0,oo=Nn&67108863}Yr.words[_n]=oo|0,On=Zn|0}return On!==0?Yr.words[_n]=On|0:Yr.length--,Yr._strip()}var In=function(Gr,Yr,Sn){var An=Gr.words,Pn=Yr.words,Nn=Sn.words,zn=0,On,_n,Zn,oo=An[0]|0,uo=oo&8191,lo=oo>>>13,co=An[1]|0,so=co&8191,yo=co>>>13,fo=An[2]|0,ho=fo&8191,vo=fo>>>13,Io=An[3]|0,Ro=Io&8191,To=Io>>>13,Wo=An[4]|0,qo=Wo&8191,Zo=Wo>>>13,Qo=An[5]|0,jo=Qo&8191,No=Qo>>>13,Tl=An[6]|0,Fo=Tl&8191,Lo=Tl>>>13,Rl=An[7]|0,_c=Rl&8191,Ko=Rl>>>13,zl=An[8]|0,Sl=zl&8191,Eo=zl>>>13,bo=An[9]|0,go=bo&8191,Co=bo>>>13,zo=Pn[0]|0,Do=zo&8191,Uo=zo>>>13,ru=Pn[1]|0,Dl=ru&8191,xl=ru>>>13,bu=Pn[2]|0,yl=bu&8191,Il=bu>>>13,cu=Pn[3]|0,Bl=cu&8191,Pl=cu>>>13,wu=Pn[4]|0,Ol=wu&8191,Nl=wu>>>13,Tu=Pn[5]|0,Ul=Tu&8191,Cl=Tu>>>13,gu=Pn[6]|0,wo=gu&8191,$o=gu>>>13,Ao=Pn[7]|0,po=Ao&8191,So=Ao>>>13,Jo=Pn[8]|0,Bo=Jo&8191,Ho=Jo>>>13,Wl=Pn[9]|0,El=Wl&8191,$l=Wl>>>13;Sn.negative=Gr.negative^Yr.negative,Sn.length=19,On=Math.imul(uo,Do),_n=Math.imul(uo,Uo),_n=_n+Math.imul(lo,Do)|0,Zn=Math.imul(lo,Uo);var Su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Su>>>26)|0,Su&=67108863,On=Math.imul(so,Do),_n=Math.imul(so,Uo),_n=_n+Math.imul(yo,Do)|0,Zn=Math.imul(yo,Uo),On=On+Math.imul(uo,Dl)|0,_n=_n+Math.imul(uo,xl)|0,_n=_n+Math.imul(lo,Dl)|0,Zn=Zn+Math.imul(lo,xl)|0;var nu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(nu>>>26)|0,nu&=67108863,On=Math.imul(ho,Do),_n=Math.imul(ho,Uo),_n=_n+Math.imul(vo,Do)|0,Zn=Math.imul(vo,Uo),On=On+Math.imul(so,Dl)|0,_n=_n+Math.imul(so,xl)|0,_n=_n+Math.imul(yo,Dl)|0,Zn=Zn+Math.imul(yo,xl)|0,On=On+Math.imul(uo,yl)|0,_n=_n+Math.imul(uo,Il)|0,_n=_n+Math.imul(lo,yl)|0,Zn=Zn+Math.imul(lo,Il)|0;var pu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(pu>>>26)|0,pu&=67108863,On=Math.imul(Ro,Do),_n=Math.imul(Ro,Uo),_n=_n+Math.imul(To,Do)|0,Zn=Math.imul(To,Uo),On=On+Math.imul(ho,Dl)|0,_n=_n+Math.imul(ho,xl)|0,_n=_n+Math.imul(vo,Dl)|0,Zn=Zn+Math.imul(vo,xl)|0,On=On+Math.imul(so,yl)|0,_n=_n+Math.imul(so,Il)|0,_n=_n+Math.imul(yo,yl)|0,Zn=Zn+Math.imul(yo,Il)|0,On=On+Math.imul(uo,Bl)|0,_n=_n+Math.imul(uo,Pl)|0,_n=_n+Math.imul(lo,Bl)|0,Zn=Zn+Math.imul(lo,Pl)|0;var mu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(mu>>>26)|0,mu&=67108863,On=Math.imul(qo,Do),_n=Math.imul(qo,Uo),_n=_n+Math.imul(Zo,Do)|0,Zn=Math.imul(Zo,Uo),On=On+Math.imul(Ro,Dl)|0,_n=_n+Math.imul(Ro,xl)|0,_n=_n+Math.imul(To,Dl)|0,Zn=Zn+Math.imul(To,xl)|0,On=On+Math.imul(ho,yl)|0,_n=_n+Math.imul(ho,Il)|0,_n=_n+Math.imul(vo,yl)|0,Zn=Zn+Math.imul(vo,Il)|0,On=On+Math.imul(so,Bl)|0,_n=_n+Math.imul(so,Pl)|0,_n=_n+Math.imul(yo,Bl)|0,Zn=Zn+Math.imul(yo,Pl)|0,On=On+Math.imul(uo,Ol)|0,_n=_n+Math.imul(uo,Nl)|0,_n=_n+Math.imul(lo,Ol)|0,Zn=Zn+Math.imul(lo,Nl)|0;var hu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(hu>>>26)|0,hu&=67108863,On=Math.imul(jo,Do),_n=Math.imul(jo,Uo),_n=_n+Math.imul(No,Do)|0,Zn=Math.imul(No,Uo),On=On+Math.imul(qo,Dl)|0,_n=_n+Math.imul(qo,xl)|0,_n=_n+Math.imul(Zo,Dl)|0,Zn=Zn+Math.imul(Zo,xl)|0,On=On+Math.imul(Ro,yl)|0,_n=_n+Math.imul(Ro,Il)|0,_n=_n+Math.imul(To,yl)|0,Zn=Zn+Math.imul(To,Il)|0,On=On+Math.imul(ho,Bl)|0,_n=_n+Math.imul(ho,Pl)|0,_n=_n+Math.imul(vo,Bl)|0,Zn=Zn+Math.imul(vo,Pl)|0,On=On+Math.imul(so,Ol)|0,_n=_n+Math.imul(so,Nl)|0,_n=_n+Math.imul(yo,Ol)|0,Zn=Zn+Math.imul(yo,Nl)|0,On=On+Math.imul(uo,Ul)|0,_n=_n+Math.imul(uo,Cl)|0,_n=_n+Math.imul(lo,Ul)|0,Zn=Zn+Math.imul(lo,Cl)|0;var yu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(yu>>>26)|0,yu&=67108863,On=Math.imul(Fo,Do),_n=Math.imul(Fo,Uo),_n=_n+Math.imul(Lo,Do)|0,Zn=Math.imul(Lo,Uo),On=On+Math.imul(jo,Dl)|0,_n=_n+Math.imul(jo,xl)|0,_n=_n+Math.imul(No,Dl)|0,Zn=Zn+Math.imul(No,xl)|0,On=On+Math.imul(qo,yl)|0,_n=_n+Math.imul(qo,Il)|0,_n=_n+Math.imul(Zo,yl)|0,Zn=Zn+Math.imul(Zo,Il)|0,On=On+Math.imul(Ro,Bl)|0,_n=_n+Math.imul(Ro,Pl)|0,_n=_n+Math.imul(To,Bl)|0,Zn=Zn+Math.imul(To,Pl)|0,On=On+Math.imul(ho,Ol)|0,_n=_n+Math.imul(ho,Nl)|0,_n=_n+Math.imul(vo,Ol)|0,Zn=Zn+Math.imul(vo,Nl)|0,On=On+Math.imul(so,Ul)|0,_n=_n+Math.imul(so,Cl)|0,_n=_n+Math.imul(yo,Ul)|0,Zn=Zn+Math.imul(yo,Cl)|0,On=On+Math.imul(uo,wo)|0,_n=_n+Math.imul(uo,$o)|0,_n=_n+Math.imul(lo,wo)|0,Zn=Zn+Math.imul(lo,$o)|0;var _u=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(_u>>>26)|0,_u&=67108863,On=Math.imul(_c,Do),_n=Math.imul(_c,Uo),_n=_n+Math.imul(Ko,Do)|0,Zn=Math.imul(Ko,Uo),On=On+Math.imul(Fo,Dl)|0,_n=_n+Math.imul(Fo,xl)|0,_n=_n+Math.imul(Lo,Dl)|0,Zn=Zn+Math.imul(Lo,xl)|0,On=On+Math.imul(jo,yl)|0,_n=_n+Math.imul(jo,Il)|0,_n=_n+Math.imul(No,yl)|0,Zn=Zn+Math.imul(No,Il)|0,On=On+Math.imul(qo,Bl)|0,_n=_n+Math.imul(qo,Pl)|0,_n=_n+Math.imul(Zo,Bl)|0,Zn=Zn+Math.imul(Zo,Pl)|0,On=On+Math.imul(Ro,Ol)|0,_n=_n+Math.imul(Ro,Nl)|0,_n=_n+Math.imul(To,Ol)|0,Zn=Zn+Math.imul(To,Nl)|0,On=On+Math.imul(ho,Ul)|0,_n=_n+Math.imul(ho,Cl)|0,_n=_n+Math.imul(vo,Ul)|0,Zn=Zn+Math.imul(vo,Cl)|0,On=On+Math.imul(so,wo)|0,_n=_n+Math.imul(so,$o)|0,_n=_n+Math.imul(yo,wo)|0,Zn=Zn+Math.imul(yo,$o)|0,On=On+Math.imul(uo,po)|0,_n=_n+Math.imul(uo,So)|0,_n=_n+Math.imul(lo,po)|0,Zn=Zn+Math.imul(lo,So)|0;var fu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(fu>>>26)|0,fu&=67108863,On=Math.imul(Sl,Do),_n=Math.imul(Sl,Uo),_n=_n+Math.imul(Eo,Do)|0,Zn=Math.imul(Eo,Uo),On=On+Math.imul(_c,Dl)|0,_n=_n+Math.imul(_c,xl)|0,_n=_n+Math.imul(Ko,Dl)|0,Zn=Zn+Math.imul(Ko,xl)|0,On=On+Math.imul(Fo,yl)|0,_n=_n+Math.imul(Fo,Il)|0,_n=_n+Math.imul(Lo,yl)|0,Zn=Zn+Math.imul(Lo,Il)|0,On=On+Math.imul(jo,Bl)|0,_n=_n+Math.imul(jo,Pl)|0,_n=_n+Math.imul(No,Bl)|0,Zn=Zn+Math.imul(No,Pl)|0,On=On+Math.imul(qo,Ol)|0,_n=_n+Math.imul(qo,Nl)|0,_n=_n+Math.imul(Zo,Ol)|0,Zn=Zn+Math.imul(Zo,Nl)|0,On=On+Math.imul(Ro,Ul)|0,_n=_n+Math.imul(Ro,Cl)|0,_n=_n+Math.imul(To,Ul)|0,Zn=Zn+Math.imul(To,Cl)|0,On=On+Math.imul(ho,wo)|0,_n=_n+Math.imul(ho,$o)|0,_n=_n+Math.imul(vo,wo)|0,Zn=Zn+Math.imul(vo,$o)|0,On=On+Math.imul(so,po)|0,_n=_n+Math.imul(so,So)|0,_n=_n+Math.imul(yo,po)|0,Zn=Zn+Math.imul(yo,So)|0,On=On+Math.imul(uo,Bo)|0,_n=_n+Math.imul(uo,Ho)|0,_n=_n+Math.imul(lo,Bo)|0,Zn=Zn+Math.imul(lo,Ho)|0;var vu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(vu>>>26)|0,vu&=67108863,On=Math.imul(go,Do),_n=Math.imul(go,Uo),_n=_n+Math.imul(Co,Do)|0,Zn=Math.imul(Co,Uo),On=On+Math.imul(Sl,Dl)|0,_n=_n+Math.imul(Sl,xl)|0,_n=_n+Math.imul(Eo,Dl)|0,Zn=Zn+Math.imul(Eo,xl)|0,On=On+Math.imul(_c,yl)|0,_n=_n+Math.imul(_c,Il)|0,_n=_n+Math.imul(Ko,yl)|0,Zn=Zn+Math.imul(Ko,Il)|0,On=On+Math.imul(Fo,Bl)|0,_n=_n+Math.imul(Fo,Pl)|0,_n=_n+Math.imul(Lo,Bl)|0,Zn=Zn+Math.imul(Lo,Pl)|0,On=On+Math.imul(jo,Ol)|0,_n=_n+Math.imul(jo,Nl)|0,_n=_n+Math.imul(No,Ol)|0,Zn=Zn+Math.imul(No,Nl)|0,On=On+Math.imul(qo,Ul)|0,_n=_n+Math.imul(qo,Cl)|0,_n=_n+Math.imul(Zo,Ul)|0,Zn=Zn+Math.imul(Zo,Cl)|0,On=On+Math.imul(Ro,wo)|0,_n=_n+Math.imul(Ro,$o)|0,_n=_n+Math.imul(To,wo)|0,Zn=Zn+Math.imul(To,$o)|0,On=On+Math.imul(ho,po)|0,_n=_n+Math.imul(ho,So)|0,_n=_n+Math.imul(vo,po)|0,Zn=Zn+Math.imul(vo,So)|0,On=On+Math.imul(so,Bo)|0,_n=_n+Math.imul(so,Ho)|0,_n=_n+Math.imul(yo,Bo)|0,Zn=Zn+Math.imul(yo,Ho)|0,On=On+Math.imul(uo,El)|0,_n=_n+Math.imul(uo,$l)|0,_n=_n+Math.imul(lo,El)|0,Zn=Zn+Math.imul(lo,$l)|0;var iu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(iu>>>26)|0,iu&=67108863,On=Math.imul(go,Dl),_n=Math.imul(go,xl),_n=_n+Math.imul(Co,Dl)|0,Zn=Math.imul(Co,xl),On=On+Math.imul(Sl,yl)|0,_n=_n+Math.imul(Sl,Il)|0,_n=_n+Math.imul(Eo,yl)|0,Zn=Zn+Math.imul(Eo,Il)|0,On=On+Math.imul(_c,Bl)|0,_n=_n+Math.imul(_c,Pl)|0,_n=_n+Math.imul(Ko,Bl)|0,Zn=Zn+Math.imul(Ko,Pl)|0,On=On+Math.imul(Fo,Ol)|0,_n=_n+Math.imul(Fo,Nl)|0,_n=_n+Math.imul(Lo,Ol)|0,Zn=Zn+Math.imul(Lo,Nl)|0,On=On+Math.imul(jo,Ul)|0,_n=_n+Math.imul(jo,Cl)|0,_n=_n+Math.imul(No,Ul)|0,Zn=Zn+Math.imul(No,Cl)|0,On=On+Math.imul(qo,wo)|0,_n=_n+Math.imul(qo,$o)|0,_n=_n+Math.imul(Zo,wo)|0,Zn=Zn+Math.imul(Zo,$o)|0,On=On+Math.imul(Ro,po)|0,_n=_n+Math.imul(Ro,So)|0,_n=_n+Math.imul(To,po)|0,Zn=Zn+Math.imul(To,So)|0,On=On+Math.imul(ho,Bo)|0,_n=_n+Math.imul(ho,Ho)|0,_n=_n+Math.imul(vo,Bo)|0,Zn=Zn+Math.imul(vo,Ho)|0,On=On+Math.imul(so,El)|0,_n=_n+Math.imul(so,$l)|0,_n=_n+Math.imul(yo,El)|0,Zn=Zn+Math.imul(yo,$l)|0;var su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(su>>>26)|0,su&=67108863,On=Math.imul(go,yl),_n=Math.imul(go,Il),_n=_n+Math.imul(Co,yl)|0,Zn=Math.imul(Co,Il),On=On+Math.imul(Sl,Bl)|0,_n=_n+Math.imul(Sl,Pl)|0,_n=_n+Math.imul(Eo,Bl)|0,Zn=Zn+Math.imul(Eo,Pl)|0,On=On+Math.imul(_c,Ol)|0,_n=_n+Math.imul(_c,Nl)|0,_n=_n+Math.imul(Ko,Ol)|0,Zn=Zn+Math.imul(Ko,Nl)|0,On=On+Math.imul(Fo,Ul)|0,_n=_n+Math.imul(Fo,Cl)|0,_n=_n+Math.imul(Lo,Ul)|0,Zn=Zn+Math.imul(Lo,Cl)|0,On=On+Math.imul(jo,wo)|0,_n=_n+Math.imul(jo,$o)|0,_n=_n+Math.imul(No,wo)|0,Zn=Zn+Math.imul(No,$o)|0,On=On+Math.imul(qo,po)|0,_n=_n+Math.imul(qo,So)|0,_n=_n+Math.imul(Zo,po)|0,Zn=Zn+Math.imul(Zo,So)|0,On=On+Math.imul(Ro,Bo)|0,_n=_n+Math.imul(Ro,Ho)|0,_n=_n+Math.imul(To,Bo)|0,Zn=Zn+Math.imul(To,Ho)|0,On=On+Math.imul(ho,El)|0,_n=_n+Math.imul(ho,$l)|0,_n=_n+Math.imul(vo,El)|0,Zn=Zn+Math.imul(vo,$l)|0;var tu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(tu>>>26)|0,tu&=67108863,On=Math.imul(go,Bl),_n=Math.imul(go,Pl),_n=_n+Math.imul(Co,Bl)|0,Zn=Math.imul(Co,Pl),On=On+Math.imul(Sl,Ol)|0,_n=_n+Math.imul(Sl,Nl)|0,_n=_n+Math.imul(Eo,Ol)|0,Zn=Zn+Math.imul(Eo,Nl)|0,On=On+Math.imul(_c,Ul)|0,_n=_n+Math.imul(_c,Cl)|0,_n=_n+Math.imul(Ko,Ul)|0,Zn=Zn+Math.imul(Ko,Cl)|0,On=On+Math.imul(Fo,wo)|0,_n=_n+Math.imul(Fo,$o)|0,_n=_n+Math.imul(Lo,wo)|0,Zn=Zn+Math.imul(Lo,$o)|0,On=On+Math.imul(jo,po)|0,_n=_n+Math.imul(jo,So)|0,_n=_n+Math.imul(No,po)|0,Zn=Zn+Math.imul(No,So)|0,On=On+Math.imul(qo,Bo)|0,_n=_n+Math.imul(qo,Ho)|0,_n=_n+Math.imul(Zo,Bo)|0,Zn=Zn+Math.imul(Zo,Ho)|0,On=On+Math.imul(Ro,El)|0,_n=_n+Math.imul(Ro,$l)|0,_n=_n+Math.imul(To,El)|0,Zn=Zn+Math.imul(To,$l)|0;var Hl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Hl>>>26)|0,Hl&=67108863,On=Math.imul(go,Ol),_n=Math.imul(go,Nl),_n=_n+Math.imul(Co,Ol)|0,Zn=Math.imul(Co,Nl),On=On+Math.imul(Sl,Ul)|0,_n=_n+Math.imul(Sl,Cl)|0,_n=_n+Math.imul(Eo,Ul)|0,Zn=Zn+Math.imul(Eo,Cl)|0,On=On+Math.imul(_c,wo)|0,_n=_n+Math.imul(_c,$o)|0,_n=_n+Math.imul(Ko,wo)|0,Zn=Zn+Math.imul(Ko,$o)|0,On=On+Math.imul(Fo,po)|0,_n=_n+Math.imul(Fo,So)|0,_n=_n+Math.imul(Lo,po)|0,Zn=Zn+Math.imul(Lo,So)|0,On=On+Math.imul(jo,Bo)|0,_n=_n+Math.imul(jo,Ho)|0,_n=_n+Math.imul(No,Bo)|0,Zn=Zn+Math.imul(No,Ho)|0,On=On+Math.imul(qo,El)|0,_n=_n+Math.imul(qo,$l)|0,_n=_n+Math.imul(Zo,El)|0,Zn=Zn+Math.imul(Zo,$l)|0;var Zl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Zl>>>26)|0,Zl&=67108863,On=Math.imul(go,Ul),_n=Math.imul(go,Cl),_n=_n+Math.imul(Co,Ul)|0,Zn=Math.imul(Co,Cl),On=On+Math.imul(Sl,wo)|0,_n=_n+Math.imul(Sl,$o)|0,_n=_n+Math.imul(Eo,wo)|0,Zn=Zn+Math.imul(Eo,$o)|0,On=On+Math.imul(_c,po)|0,_n=_n+Math.imul(_c,So)|0,_n=_n+Math.imul(Ko,po)|0,Zn=Zn+Math.imul(Ko,So)|0,On=On+Math.imul(Fo,Bo)|0,_n=_n+Math.imul(Fo,Ho)|0,_n=_n+Math.imul(Lo,Bo)|0,Zn=Zn+Math.imul(Lo,Ho)|0,On=On+Math.imul(jo,El)|0,_n=_n+Math.imul(jo,$l)|0,_n=_n+Math.imul(No,El)|0,Zn=Zn+Math.imul(No,$l)|0;var Jl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Jl>>>26)|0,Jl&=67108863,On=Math.imul(go,wo),_n=Math.imul(go,$o),_n=_n+Math.imul(Co,wo)|0,Zn=Math.imul(Co,$o),On=On+Math.imul(Sl,po)|0,_n=_n+Math.imul(Sl,So)|0,_n=_n+Math.imul(Eo,po)|0,Zn=Zn+Math.imul(Eo,So)|0,On=On+Math.imul(_c,Bo)|0,_n=_n+Math.imul(_c,Ho)|0,_n=_n+Math.imul(Ko,Bo)|0,Zn=Zn+Math.imul(Ko,Ho)|0,On=On+Math.imul(Fo,El)|0,_n=_n+Math.imul(Fo,$l)|0,_n=_n+Math.imul(Lo,El)|0,Zn=Zn+Math.imul(Lo,$l)|0;var Ml=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Ml>>>26)|0,Ml&=67108863,On=Math.imul(go,po),_n=Math.imul(go,So),_n=_n+Math.imul(Co,po)|0,Zn=Math.imul(Co,So),On=On+Math.imul(Sl,Bo)|0,_n=_n+Math.imul(Sl,Ho)|0,_n=_n+Math.imul(Eo,Bo)|0,Zn=Zn+Math.imul(Eo,Ho)|0,On=On+Math.imul(_c,El)|0,_n=_n+Math.imul(_c,$l)|0,_n=_n+Math.imul(Ko,El)|0,Zn=Zn+Math.imul(Ko,$l)|0;var Fl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Fl>>>26)|0,Fl&=67108863,On=Math.imul(go,Bo),_n=Math.imul(go,Ho),_n=_n+Math.imul(Co,Bo)|0,Zn=Math.imul(Co,Ho),On=On+Math.imul(Sl,El)|0,_n=_n+Math.imul(Sl,$l)|0,_n=_n+Math.imul(Eo,El)|0,Zn=Zn+Math.imul(Eo,$l)|0;var Yl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Yl>>>26)|0,Yl&=67108863,On=Math.imul(go,El),_n=Math.imul(go,$l),_n=_n+Math.imul(Co,El)|0,Zn=Math.imul(Co,$l);var Vl=(zn+On|0)+((_n&8191)<<13)|0;return zn=(Zn+(_n>>>13)|0)+(Vl>>>26)|0,Vl&=67108863,Nn[0]=Su,Nn[1]=nu,Nn[2]=pu,Nn[3]=mu,Nn[4]=hu,Nn[5]=yu,Nn[6]=_u,Nn[7]=fu,Nn[8]=vu,Nn[9]=iu,Nn[10]=su,Nn[11]=tu,Nn[12]=Hl,Nn[13]=Zl,Nn[14]=Jl,Nn[15]=Ml,Nn[16]=Fl,Nn[17]=Yl,Nn[18]=Vl,zn!==0&&(Nn[19]=zn,Sn.length++),Sn};Math.imul||(In=Tn);function jn(Rn,Gr,Yr){Yr.negative=Gr.negative^Rn.negative,Yr.length=Rn.length+Gr.length;for(var Sn=0,An=0,Pn=0;Pn>>26)|0,An+=Nn>>>26,Nn&=67108863}Yr.words[Pn]=zn,Sn=Nn,Nn=An}return Sn!==0?Yr.words[Pn]=Sn:Yr.length--,Yr._strip()}function Yn(Rn,Gr,Yr){return jn(Rn,Gr,Yr)}jr.prototype.mulTo=function(Gr,Yr){var Sn,An=this.length+Gr.length;return this.length===10&&Gr.length===10?Sn=In(this,Gr,Yr):An<63?Sn=Tn(this,Gr,Yr):An<1024?Sn=jn(this,Gr,Yr):Sn=Yn(this,Gr,Yr),Sn},jr.prototype.mul=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),this.mulTo(Gr,Yr)},jr.prototype.mulf=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),Yn(this,Gr,Yr)},jr.prototype.imul=function(Gr){return this.clone().mulTo(Gr,this)},jr.prototype.imuln=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(typeof Gr=="number"),Er(Gr<67108864);for(var Sn=0,An=0;An>=26,Sn+=Pn/67108864|0,Sn+=Nn>>>26,this.words[An]=Nn&67108863}return Sn!==0&&(this.words[An]=Sn,this.length++),Yr?this.ineg():this},jr.prototype.muln=function(Gr){return this.clone().imuln(Gr)},jr.prototype.sqr=function(){return this.mul(this)},jr.prototype.isqr=function(){return this.imul(this.clone())},jr.prototype.pow=function(Gr){var Yr=$n(Gr);if(Yr.length===0)return new jr(1);for(var Sn=this,An=0;An=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=67108863>>>26-Yr<<26-Yr,Pn;if(Yr!==0){var Nn=0;for(Pn=0;Pn>>26-Yr}Nn&&(this.words[Pn]=Nn,this.length++)}if(Sn!==0){for(Pn=this.length-1;Pn>=0;Pn--)this.words[Pn+Sn]=this.words[Pn];for(Pn=0;Pn=0);var An;Yr?An=(Yr-Yr%26)/26:An=0;var Pn=Gr%26,Nn=Math.min((Gr-Pn)/26,this.length),zn=67108863^67108863>>>Pn<Nn)for(this.length-=Nn,_n=0;_n=0&&(Zn!==0||_n>=An);_n--){var oo=this.words[_n]|0;this.words[_n]=Zn<<26-Pn|oo>>>Pn,Zn=oo&zn}return On&&Zn!==0&&(On.words[On.length++]=Zn),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},jr.prototype.ishrn=function(Gr,Yr,Sn){return Er(this.negative===0),this.iushrn(Gr,Yr,Sn)},jr.prototype.shln=function(Gr){return this.clone().ishln(Gr)},jr.prototype.ushln=function(Gr){return this.clone().iushln(Gr)},jr.prototype.shrn=function(Gr){return this.clone().ishrn(Gr)},jr.prototype.ushrn=function(Gr){return this.clone().iushrn(Gr)},jr.prototype.testn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<=0);var Yr=Gr%26,Sn=(Gr-Yr)/26;if(Er(this.negative===0,"imaskn works only with positive numbers"),this.length<=Sn)return this;if(Yr!==0&&Sn++,this.length=Math.min(Sn,this.length),Yr!==0){var An=67108863^67108863>>>Yr<=67108864;Yr++)this.words[Yr]-=67108864,Yr===this.length-1?this.words[Yr+1]=1:this.words[Yr+1]++;return this.length=Math.max(this.length,Yr+1),this},jr.prototype.isubn=function(Gr){if(Er(typeof Gr=="number"),Er(Gr<67108864),Gr<0)return this.iaddn(-Gr);if(this.negative!==0)return this.negative=0,this.iaddn(Gr),this.negative=1,this;if(this.words[0]-=Gr,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Yr=0;Yr>26)-(On/67108864|0),this.words[Pn+Sn]=Nn&67108863}for(;Pn>26,this.words[Pn+Sn]=Nn&67108863;if(zn===0)return this._strip();for(Er(zn===-1),zn=0,Pn=0;Pn>26,this.words[Pn]=Nn&67108863;return this.negative=1,this._strip()},jr.prototype._wordDiv=function(Gr,Yr){var Sn=this.length-Gr.length,An=this.clone(),Pn=Gr,Nn=Pn.words[Pn.length-1]|0,zn=this._countBits(Nn);Sn=26-zn,Sn!==0&&(Pn=Pn.ushln(Sn),An.iushln(Sn),Nn=Pn.words[Pn.length-1]|0);var On=An.length-Pn.length,_n;if(Yr!=="mod"){_n=new jr(null),_n.length=On+1,_n.words=new Array(_n.length);for(var Zn=0;Zn<_n.length;Zn++)_n.words[Zn]=0}var oo=An.clone()._ishlnsubmul(Pn,1,On);oo.negative===0&&(An=oo,_n&&(_n.words[On]=1));for(var uo=On-1;uo>=0;uo--){var lo=(An.words[Pn.length+uo]|0)*67108864+(An.words[Pn.length+uo-1]|0);for(lo=Math.min(lo/Nn|0,67108863),An._ishlnsubmul(Pn,lo,uo);An.negative!==0;)lo--,An.negative=0,An._ishlnsubmul(Pn,1,uo),An.isZero()||(An.negative^=1);_n&&(_n.words[uo]=lo)}return _n&&_n._strip(),An._strip(),Yr!=="div"&&Sn!==0&&An.iushrn(Sn),{div:_n||null,mod:An}},jr.prototype.divmod=function(Gr,Yr,Sn){if(Er(!Gr.isZero()),this.isZero())return{div:new jr(0),mod:new jr(0)};var An,Pn,Nn;return this.negative!==0&&Gr.negative===0?(Nn=this.neg().divmod(Gr,Yr),Yr!=="mod"&&(An=Nn.div.neg()),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.iadd(Gr)),{div:An,mod:Pn}):this.negative===0&&Gr.negative!==0?(Nn=this.divmod(Gr.neg(),Yr),Yr!=="mod"&&(An=Nn.div.neg()),{div:An,mod:Nn.mod}):this.negative&Gr.negative?(Nn=this.neg().divmod(Gr.neg(),Yr),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.isub(Gr)),{div:Nn.div,mod:Pn}):Gr.length>this.length||this.cmp(Gr)<0?{div:new jr(0),mod:this}:Gr.length===1?Yr==="div"?{div:this.divn(Gr.words[0]),mod:null}:Yr==="mod"?{div:null,mod:new jr(this.modrn(Gr.words[0]))}:{div:this.divn(Gr.words[0]),mod:new jr(this.modrn(Gr.words[0]))}:this._wordDiv(Gr,Yr)},jr.prototype.div=function(Gr){return this.divmod(Gr,"div",!1).div},jr.prototype.mod=function(Gr){return this.divmod(Gr,"mod",!1).mod},jr.prototype.umod=function(Gr){return this.divmod(Gr,"mod",!0).mod},jr.prototype.divRound=function(Gr){var Yr=this.divmod(Gr);if(Yr.mod.isZero())return Yr.div;var Sn=Yr.div.negative!==0?Yr.mod.isub(Gr):Yr.mod,An=Gr.ushrn(1),Pn=Gr.andln(1),Nn=Sn.cmp(An);return Nn<0||Pn===1&&Nn===0?Yr.div:Yr.div.negative!==0?Yr.div.isubn(1):Yr.div.iaddn(1)},jr.prototype.modrn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=(1<<26)%Gr,An=0,Pn=this.length-1;Pn>=0;Pn--)An=(Sn*An+(this.words[Pn]|0))%Gr;return Yr?-An:An},jr.prototype.modn=function(Gr){return this.modrn(Gr)},jr.prototype.idivn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=0,An=this.length-1;An>=0;An--){var Pn=(this.words[An]|0)+Sn*67108864;this.words[An]=Pn/Gr|0,Sn=Pn%Gr}return this._strip(),Yr?this.ineg():this},jr.prototype.divn=function(Gr){return this.clone().idivn(Gr)},jr.prototype.egcd=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=new jr(0),zn=new jr(1),On=0;Yr.isEven()&&Sn.isEven();)Yr.iushrn(1),Sn.iushrn(1),++On;for(var _n=Sn.clone(),Zn=Yr.clone();!Yr.isZero();){for(var oo=0,uo=1;!(Yr.words[0]&uo)&&oo<26;++oo,uo<<=1);if(oo>0)for(Yr.iushrn(oo);oo-- >0;)(An.isOdd()||Pn.isOdd())&&(An.iadd(_n),Pn.isub(Zn)),An.iushrn(1),Pn.iushrn(1);for(var lo=0,co=1;!(Sn.words[0]&co)&&lo<26;++lo,co<<=1);if(lo>0)for(Sn.iushrn(lo);lo-- >0;)(Nn.isOdd()||zn.isOdd())&&(Nn.iadd(_n),zn.isub(Zn)),Nn.iushrn(1),zn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Nn),Pn.isub(zn)):(Sn.isub(Yr),Nn.isub(An),zn.isub(Pn))}return{a:Nn,b:zn,gcd:Sn.iushln(On)}},jr.prototype._invmp=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=Sn.clone();Yr.cmpn(1)>0&&Sn.cmpn(1)>0;){for(var zn=0,On=1;!(Yr.words[0]&On)&&zn<26;++zn,On<<=1);if(zn>0)for(Yr.iushrn(zn);zn-- >0;)An.isOdd()&&An.iadd(Nn),An.iushrn(1);for(var _n=0,Zn=1;!(Sn.words[0]&Zn)&&_n<26;++_n,Zn<<=1);if(_n>0)for(Sn.iushrn(_n);_n-- >0;)Pn.isOdd()&&Pn.iadd(Nn),Pn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Pn)):(Sn.isub(Yr),Pn.isub(An))}var oo;return Yr.cmpn(1)===0?oo=An:oo=Pn,oo.cmpn(0)<0&&oo.iadd(Gr),oo},jr.prototype.gcd=function(Gr){if(this.isZero())return Gr.abs();if(Gr.isZero())return this.abs();var Yr=this.clone(),Sn=Gr.clone();Yr.negative=0,Sn.negative=0;for(var An=0;Yr.isEven()&&Sn.isEven();An++)Yr.iushrn(1),Sn.iushrn(1);do{for(;Yr.isEven();)Yr.iushrn(1);for(;Sn.isEven();)Sn.iushrn(1);var Pn=Yr.cmp(Sn);if(Pn<0){var Nn=Yr;Yr=Sn,Sn=Nn}else if(Pn===0||Sn.cmpn(1)===0)break;Yr.isub(Sn)}while(!0);return Sn.iushln(An)},jr.prototype.invm=function(Gr){return this.egcd(Gr).a.umod(Gr)},jr.prototype.isEven=function(){return(this.words[0]&1)===0},jr.prototype.isOdd=function(){return(this.words[0]&1)===1},jr.prototype.andln=function(Gr){return this.words[0]&Gr},jr.prototype.bincn=function(Gr){Er(typeof Gr=="number");var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<>>26,zn&=67108863,this.words[Nn]=zn}return Pn!==0&&(this.words[Nn]=Pn,this.length++),this},jr.prototype.isZero=function(){return this.length===1&&this.words[0]===0},jr.prototype.cmpn=function(Gr){var Yr=Gr<0;if(this.negative!==0&&!Yr)return-1;if(this.negative===0&&Yr)return 1;this._strip();var Sn;if(this.length>1)Sn=1;else{Yr&&(Gr=-Gr),Er(Gr<=67108863,"Number is too big");var An=this.words[0]|0;Sn=An===Gr?0:AnGr.length)return 1;if(this.length=0;Sn--){var An=this.words[Sn]|0,Pn=Gr.words[Sn]|0;if(An!==Pn){AnPn&&(Yr=1);break}}return Yr},jr.prototype.gtn=function(Gr){return this.cmpn(Gr)===1},jr.prototype.gt=function(Gr){return this.cmp(Gr)===1},jr.prototype.gten=function(Gr){return this.cmpn(Gr)>=0},jr.prototype.gte=function(Gr){return this.cmp(Gr)>=0},jr.prototype.ltn=function(Gr){return this.cmpn(Gr)===-1},jr.prototype.lt=function(Gr){return this.cmp(Gr)===-1},jr.prototype.lten=function(Gr){return this.cmpn(Gr)<=0},jr.prototype.lte=function(Gr){return this.cmp(Gr)<=0},jr.prototype.eqn=function(Gr){return this.cmpn(Gr)===0},jr.prototype.eq=function(Gr){return this.cmp(Gr)===0},jr.red=function(Gr){return new no(Gr)},jr.prototype.toRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),Er(this.negative===0,"red works only with positives"),Gr.convertTo(this)._forceRed(Gr)},jr.prototype.fromRed=function(){return Er(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},jr.prototype._forceRed=function(Gr){return this.red=Gr,this},jr.prototype.forceRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),this._forceRed(Gr)},jr.prototype.redAdd=function(Gr){return Er(this.red,"redAdd works only with red numbers"),this.red.add(this,Gr)},jr.prototype.redIAdd=function(Gr){return Er(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,Gr)},jr.prototype.redSub=function(Gr){return Er(this.red,"redSub works only with red numbers"),this.red.sub(this,Gr)},jr.prototype.redISub=function(Gr){return Er(this.red,"redISub works only with red numbers"),this.red.isub(this,Gr)},jr.prototype.redShl=function(Gr){return Er(this.red,"redShl works only with red numbers"),this.red.shl(this,Gr)},jr.prototype.redMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.mul(this,Gr)},jr.prototype.redIMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.imul(this,Gr)},jr.prototype.redSqr=function(){return Er(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},jr.prototype.redISqr=function(){return Er(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},jr.prototype.redSqrt=function(){return Er(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},jr.prototype.redInvm=function(){return Er(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},jr.prototype.redNeg=function(){return Er(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},jr.prototype.redPow=function(Gr){return Er(this.red&&!Gr.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,Gr)};var ga={k256:null,p224:null,p192:null,p25519:null};function na(Rn,Gr){this.name=Rn,this.p=new jr(Gr,16),this.n=this.p.bitLength(),this.k=new jr(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}na.prototype._tmp=function(){var Gr=new jr(null);return Gr.words=new Array(Math.ceil(this.n/13)),Gr},na.prototype.ireduce=function(Gr){var Yr=Gr,Sn;do this.split(Yr,this.tmp),Yr=this.imulK(Yr),Yr=Yr.iadd(this.tmp),Sn=Yr.bitLength();while(Sn>this.n);var An=Sn0?Yr.isub(this.p):Yr.strip!==void 0?Yr.strip():Yr._strip(),Yr},na.prototype.split=function(Gr,Yr){Gr.iushrn(this.n,0,Yr)},na.prototype.imulK=function(Gr){return Gr.imul(this.k)};function _i(){na.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}kr(_i,na),_i.prototype.split=function(Gr,Yr){for(var Sn=4194303,An=Math.min(Gr.length,9),Pn=0;Pn>>22,Nn=zn}Nn>>>=22,Gr.words[Pn-10]=Nn,Nn===0&&Gr.length>10?Gr.length-=10:Gr.length-=9},_i.prototype.imulK=function(Gr){Gr.words[Gr.length]=0,Gr.words[Gr.length+1]=0,Gr.length+=2;for(var Yr=0,Sn=0;Sn>>=26,Gr.words[Sn]=Pn,Yr=An}return Yr!==0&&(Gr.words[Gr.length++]=Yr),Gr},jr._prime=function(Gr){if(ga[Gr])return ga[Gr];var Yr;if(Gr==="k256")Yr=new _i;else if(Gr==="p224")Yr=new ro;else if(Gr==="p192")Yr=new to;else if(Gr==="p25519")Yr=new io;else throw new Error("Unknown prime "+Gr);return ga[Gr]=Yr,Yr};function no(Rn){if(typeof Rn=="string"){var Gr=jr._prime(Rn);this.m=Gr.p,this.prime=Gr}else Er(Rn.gtn(1),"modulus must be greater than 1"),this.m=Rn,this.prime=null}no.prototype._verify1=function(Gr){Er(Gr.negative===0,"red works only with positives"),Er(Gr.red,"red works only with red numbers")},no.prototype._verify2=function(Gr,Yr){Er((Gr.negative|Yr.negative)===0,"red works only with positives"),Er(Gr.red&&Gr.red===Yr.red,"red works only with red numbers")},no.prototype.imod=function(Gr){return this.prime?this.prime.ireduce(Gr)._forceRed(this):(Hr(Gr,Gr.umod(this.m)._forceRed(this)),Gr)},no.prototype.neg=function(Gr){return Gr.isZero()?Gr.clone():this.m.sub(Gr)._forceRed(this)},no.prototype.add=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.add(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn._forceRed(this)},no.prototype.iadd=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.iadd(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn},no.prototype.sub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.sub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn._forceRed(this)},no.prototype.isub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.isub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn},no.prototype.shl=function(Gr,Yr){return this._verify1(Gr),this.imod(Gr.ushln(Yr))},no.prototype.imul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.imul(Yr))},no.prototype.mul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.mul(Yr))},no.prototype.isqr=function(Gr){return this.imul(Gr,Gr.clone())},no.prototype.sqr=function(Gr){return this.mul(Gr,Gr)},no.prototype.sqrt=function(Gr){if(Gr.isZero())return Gr.clone();var Yr=this.m.andln(3);if(Er(Yr%2===1),Yr===3){var Sn=this.m.add(new jr(1)).iushrn(2);return this.pow(Gr,Sn)}for(var An=this.m.subn(1),Pn=0;!An.isZero()&&An.andln(1)===0;)Pn++,An.iushrn(1);Er(!An.isZero());var Nn=new jr(1).toRed(this),zn=Nn.redNeg(),On=this.m.subn(1).iushrn(1),_n=this.m.bitLength();for(_n=new jr(2*_n*_n).toRed(this);this.pow(_n,On).cmp(zn)!==0;)_n.redIAdd(zn);for(var Zn=this.pow(_n,An),oo=this.pow(Gr,An.addn(1).iushrn(1)),uo=this.pow(Gr,An),lo=Pn;uo.cmp(Nn)!==0;){for(var co=uo,so=0;co.cmp(Nn)!==0;so++)co=co.redSqr();Er(so=0;Pn--){for(var Zn=Yr.words[Pn],oo=_n-1;oo>=0;oo--){var uo=Zn>>oo&1;if(Nn!==An[0]&&(Nn=this.sqr(Nn)),uo===0&&zn===0){On=0;continue}zn<<=1,zn|=uo,On++,!(On!==Sn&&(Pn!==0||oo!==0))&&(Nn=this.mul(Nn,An[zn]),On=0,zn=0)}_n=26}return Nn},no.prototype.convertTo=function(Gr){var Yr=Gr.umod(this.m);return Yr===Gr?Yr.clone():Yr},no.prototype.convertFrom=function(Gr){var Yr=Gr.clone();return Yr.red=null,Yr},jr.mont=function(Gr){return new $a(Gr)};function $a(Rn){no.call(this,Rn),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new jr(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}kr($a,no),$a.prototype.convertTo=function(Gr){return this.imod(Gr.ushln(this.shift))},$a.prototype.convertFrom=function(Gr){var Yr=this.imod(Gr.mul(this.rinv));return Yr.red=null,Yr},$a.prototype.imul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return Gr.words[0]=0,Gr.length=1,Gr;var Sn=Gr.imul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.mul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return new jr(0)._forceRed(this);var Sn=Gr.mul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.invm=function(Gr){var Yr=this.imod(Gr._invmp(this.m).mul(this.r2));return Yr._forceRed(this)}})(fr,commonjsGlobal)})(bn$3);var bnExports$3=bn$3.exports;const BN$2=getDefaultExportFromCjs$2(bnExports$3);var _Buffer$3=safeBufferExports.Buffer;function base$3(fr){if(fr.length>=255)throw new TypeError("Alphabet too long");for(var br=new Uint8Array(256),wr=0;wr>>0,jn=new Uint8Array(In);$n!==Tn;){for(var Yn=Xr[$n],ga=0,na=In-1;(Yn!==0||ga>>0,jn[na]=Yn%Br>>>0,Yn=Yn/Br>>>0;if(Yn!==0)throw new Error("Non-zero carry");wn=ga,$n++}for(var _i=In-wn;_i!==In&&jn[_i]===0;)_i++;for(var ro=qr.repeat(En);_i>>0,In=new Uint8Array(Tn);En>>0,In[ga]=jn%256>>>0,jn=jn/256>>>0;if(jn!==0)throw new Error("Non-zero carry");$n=Yn,En++}for(var na=Tn-$n;na!==Tn&&In[na]===0;)na++;var _i=_Buffer$3.allocUnsafe(wn+(Tn-na));_i.fill(0,0,wn);for(var ro=wn;na!==Tn;)_i[ro++]=In[na++];return _i}function Jr(Xr){var En=Zr(Xr);if(En)return En;throw new Error("Non-base"+Br+" character")}return{encode:Hr,decodeUnsafe:Zr,decode:Jr}}var src$3=base$3,basex$3=src$3,ALPHABET$3="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",bs58$5=basex$3(ALPHABET$3);const bs58$6=getDefaultExportFromCjs$2(bs58$5);var lib={},bn$2={exports:{}};bn$2.exports;(function(fr){(function(br,wr){function Er(Rn,Gr){if(!Rn)throw new Error(Gr||"Assertion failed")}function kr(Rn,Gr){Rn.super_=Gr;var Yr=function(){};Yr.prototype=Gr.prototype,Rn.prototype=new Yr,Rn.prototype.constructor=Rn}function jr(Rn,Gr,Yr){if(jr.isBN(Rn))return Rn;this.negative=0,this.words=null,this.length=0,this.red=null,Rn!==null&&((Gr==="le"||Gr==="be")&&(Yr=Gr,Gr=10),this._init(Rn||0,Gr||10,Yr||"be"))}typeof br=="object"?br.exports=jr:wr.BN=jr,jr.BN=jr,jr.wordSize=26;var Br;try{typeof window<"u"&&typeof window.Buffer<"u"?Br=window.Buffer:Br=require$$0$9.Buffer}catch{}jr.isBN=function(Gr){return Gr instanceof jr?!0:Gr!==null&&typeof Gr=="object"&&Gr.constructor.wordSize===jr.wordSize&&Array.isArray(Gr.words)},jr.max=function(Gr,Yr){return Gr.cmp(Yr)>0?Gr:Yr},jr.min=function(Gr,Yr){return Gr.cmp(Yr)<0?Gr:Yr},jr.prototype._init=function(Gr,Yr,Sn){if(typeof Gr=="number")return this._initNumber(Gr,Yr,Sn);if(typeof Gr=="object")return this._initArray(Gr,Yr,Sn);Yr==="hex"&&(Yr=16),Er(Yr===(Yr|0)&&Yr>=2&&Yr<=36),Gr=Gr.toString().replace(/\s+/g,"");var An=0;Gr[0]==="-"&&(An++,this.negative=1),An=0;An-=3)Nn=Gr[An]|Gr[An-1]<<8|Gr[An-2]<<16,this.words[Pn]|=Nn<>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);else if(Sn==="le")for(An=0,Pn=0;An>>26-zn&67108863,zn+=24,zn>=26&&(zn-=26,Pn++);return this._strip()};function qr(Rn,Gr){var Yr=Rn.charCodeAt(Gr);if(Yr>=48&&Yr<=57)return Yr-48;if(Yr>=65&&Yr<=70)return Yr-55;if(Yr>=97&&Yr<=102)return Yr-87;Er(!1,"Invalid character in "+Rn)}function Wr(Rn,Gr,Yr){var Sn=qr(Rn,Yr);return Yr-1>=Gr&&(Sn|=qr(Rn,Yr-1)<<4),Sn}jr.prototype._parseHex=function(Gr,Yr,Sn){this.length=Math.ceil((Gr.length-Yr)/6),this.words=new Array(this.length);for(var An=0;An=Yr;An-=2)zn=Wr(Gr,Yr,An)<=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8;else{var On=Gr.length-Yr;for(An=On%2===0?Yr+1:Yr;An=18?(Pn-=18,Nn+=1,this.words[Nn]|=zn>>>26):Pn+=8}this._strip()};function Vr(Rn,Gr,Yr,Sn){for(var An=0,Pn=0,Nn=Math.min(Rn.length,Yr),zn=Gr;zn=49?Pn=On-49+10:On>=17?Pn=On-17+10:Pn=On,Er(On>=0&&Pn1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},jr.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{jr.prototype[Symbol.for("nodejs.util.inspect.custom")]=Zr}catch{jr.prototype.inspect=Zr}else jr.prototype.inspect=Zr;function Zr(){return(this.red?""}var Jr=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],Xr=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],En=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];jr.prototype.toString=function(Gr,Yr){Gr=Gr||10,Yr=Yr|0||1;var Sn;if(Gr===16||Gr==="hex"){Sn="";for(var An=0,Pn=0,Nn=0;Nn>>24-An&16777215,An+=2,An>=26&&(An-=26,Nn--),Pn!==0||Nn!==this.length-1?Sn=Jr[6-On.length]+On+Sn:Sn=On+Sn}for(Pn!==0&&(Sn=Pn.toString(16)+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}if(Gr===(Gr|0)&&Gr>=2&&Gr<=36){var _n=Xr[Gr],Zn=En[Gr];Sn="";var oo=this.clone();for(oo.negative=0;!oo.isZero();){var uo=oo.modrn(Zn).toString(Gr);oo=oo.idivn(Zn),oo.isZero()?Sn=uo+Sn:Sn=Jr[_n-uo.length]+uo+Sn}for(this.isZero()&&(Sn="0"+Sn);Sn.length%Yr!==0;)Sn="0"+Sn;return this.negative!==0&&(Sn="-"+Sn),Sn}Er(!1,"Base should be between 2 and 36")},jr.prototype.toNumber=function(){var Gr=this.words[0];return this.length===2?Gr+=this.words[1]*67108864:this.length===3&&this.words[2]===1?Gr+=4503599627370496+this.words[1]*67108864:this.length>2&&Er(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-Gr:Gr},jr.prototype.toJSON=function(){return this.toString(16,2)},Br&&(jr.prototype.toBuffer=function(Gr,Yr){return this.toArrayLike(Br,Gr,Yr)}),jr.prototype.toArray=function(Gr,Yr){return this.toArrayLike(Array,Gr,Yr)};var wn=function(Gr,Yr){return Gr.allocUnsafe?Gr.allocUnsafe(Yr):new Gr(Yr)};jr.prototype.toArrayLike=function(Gr,Yr,Sn){this._strip();var An=this.byteLength(),Pn=Sn||Math.max(1,An);Er(An<=Pn,"byte array longer than desired length"),Er(Pn>0,"Requested array length <= 0");var Nn=wn(Gr,Pn),zn=Yr==="le"?"LE":"BE";return this["_toArrayLike"+zn](Nn,An),Nn},jr.prototype._toArrayLikeLE=function(Gr,Yr){for(var Sn=0,An=0,Pn=0,Nn=0;Pn>8&255),Sn>16&255),Nn===6?(Sn>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn=0&&(Gr[Sn--]=zn>>8&255),Sn>=0&&(Gr[Sn--]=zn>>16&255),Nn===6?(Sn>=0&&(Gr[Sn--]=zn>>24&255),An=0,Nn=0):(An=zn>>>24,Nn+=2)}if(Sn>=0)for(Gr[Sn--]=An;Sn>=0;)Gr[Sn--]=0},Math.clz32?jr.prototype._countBits=function(Gr){return 32-Math.clz32(Gr)}:jr.prototype._countBits=function(Gr){var Yr=Gr,Sn=0;return Yr>=4096&&(Sn+=13,Yr>>>=13),Yr>=64&&(Sn+=7,Yr>>>=7),Yr>=8&&(Sn+=4,Yr>>>=4),Yr>=2&&(Sn+=2,Yr>>>=2),Sn+Yr},jr.prototype._zeroBits=function(Gr){if(Gr===0)return 26;var Yr=Gr,Sn=0;return Yr&8191||(Sn+=13,Yr>>>=13),Yr&127||(Sn+=7,Yr>>>=7),Yr&15||(Sn+=4,Yr>>>=4),Yr&3||(Sn+=2,Yr>>>=2),Yr&1||Sn++,Sn},jr.prototype.bitLength=function(){var Gr=this.words[this.length-1],Yr=this._countBits(Gr);return(this.length-1)*26+Yr};function $n(Rn){for(var Gr=new Array(Rn.bitLength()),Yr=0;Yr>>An&1}return Gr}jr.prototype.zeroBits=function(){if(this.isZero())return 0;for(var Gr=0,Yr=0;YrGr.length?this.clone().ior(Gr):Gr.clone().ior(this)},jr.prototype.uor=function(Gr){return this.length>Gr.length?this.clone().iuor(Gr):Gr.clone().iuor(this)},jr.prototype.iuand=function(Gr){var Yr;this.length>Gr.length?Yr=Gr:Yr=this;for(var Sn=0;SnGr.length?this.clone().iand(Gr):Gr.clone().iand(this)},jr.prototype.uand=function(Gr){return this.length>Gr.length?this.clone().iuand(Gr):Gr.clone().iuand(this)},jr.prototype.iuxor=function(Gr){var Yr,Sn;this.length>Gr.length?(Yr=this,Sn=Gr):(Yr=Gr,Sn=this);for(var An=0;AnGr.length?this.clone().ixor(Gr):Gr.clone().ixor(this)},jr.prototype.uxor=function(Gr){return this.length>Gr.length?this.clone().iuxor(Gr):Gr.clone().iuxor(this)},jr.prototype.inotn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Math.ceil(Gr/26)|0,Sn=Gr%26;this._expand(Yr),Sn>0&&Yr--;for(var An=0;An0&&(this.words[An]=~this.words[An]&67108863>>26-Sn),this._strip()},jr.prototype.notn=function(Gr){return this.clone().inotn(Gr)},jr.prototype.setn=function(Gr,Yr){Er(typeof Gr=="number"&&Gr>=0);var Sn=Gr/26|0,An=Gr%26;return this._expand(Sn+1),Yr?this.words[Sn]=this.words[Sn]|1<Gr.length?(Sn=this,An=Gr):(Sn=Gr,An=this);for(var Pn=0,Nn=0;Nn>>26;for(;Pn!==0&&Nn>>26;if(this.length=Sn.length,Pn!==0)this.words[this.length]=Pn,this.length++;else if(Sn!==this)for(;NnGr.length?this.clone().iadd(Gr):Gr.clone().iadd(this)},jr.prototype.isub=function(Gr){if(Gr.negative!==0){Gr.negative=0;var Yr=this.iadd(Gr);return Gr.negative=1,Yr._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(Gr),this.negative=1,this._normSign();var Sn=this.cmp(Gr);if(Sn===0)return this.negative=0,this.length=1,this.words[0]=0,this;var An,Pn;Sn>0?(An=this,Pn=Gr):(An=Gr,Pn=this);for(var Nn=0,zn=0;zn>26,this.words[zn]=Yr&67108863;for(;Nn!==0&&zn>26,this.words[zn]=Yr&67108863;if(Nn===0&&zn>>26,oo=On&67108863,uo=Math.min(_n,Gr.length-1),lo=Math.max(0,_n-Rn.length+1);lo<=uo;lo++){var co=_n-lo|0;An=Rn.words[co]|0,Pn=Gr.words[lo]|0,Nn=An*Pn+oo,Zn+=Nn/67108864|0,oo=Nn&67108863}Yr.words[_n]=oo|0,On=Zn|0}return On!==0?Yr.words[_n]=On|0:Yr.length--,Yr._strip()}var In=function(Gr,Yr,Sn){var An=Gr.words,Pn=Yr.words,Nn=Sn.words,zn=0,On,_n,Zn,oo=An[0]|0,uo=oo&8191,lo=oo>>>13,co=An[1]|0,so=co&8191,yo=co>>>13,fo=An[2]|0,ho=fo&8191,vo=fo>>>13,Io=An[3]|0,Ro=Io&8191,To=Io>>>13,Wo=An[4]|0,qo=Wo&8191,Zo=Wo>>>13,Qo=An[5]|0,jo=Qo&8191,No=Qo>>>13,Tl=An[6]|0,Fo=Tl&8191,Lo=Tl>>>13,Rl=An[7]|0,_c=Rl&8191,Ko=Rl>>>13,zl=An[8]|0,Sl=zl&8191,Eo=zl>>>13,bo=An[9]|0,go=bo&8191,Co=bo>>>13,zo=Pn[0]|0,Do=zo&8191,Uo=zo>>>13,ru=Pn[1]|0,Dl=ru&8191,xl=ru>>>13,bu=Pn[2]|0,yl=bu&8191,Il=bu>>>13,cu=Pn[3]|0,Bl=cu&8191,Pl=cu>>>13,wu=Pn[4]|0,Ol=wu&8191,Nl=wu>>>13,Tu=Pn[5]|0,Ul=Tu&8191,Cl=Tu>>>13,gu=Pn[6]|0,wo=gu&8191,$o=gu>>>13,Ao=Pn[7]|0,po=Ao&8191,So=Ao>>>13,Jo=Pn[8]|0,Bo=Jo&8191,Ho=Jo>>>13,Wl=Pn[9]|0,El=Wl&8191,$l=Wl>>>13;Sn.negative=Gr.negative^Yr.negative,Sn.length=19,On=Math.imul(uo,Do),_n=Math.imul(uo,Uo),_n=_n+Math.imul(lo,Do)|0,Zn=Math.imul(lo,Uo);var Su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Su>>>26)|0,Su&=67108863,On=Math.imul(so,Do),_n=Math.imul(so,Uo),_n=_n+Math.imul(yo,Do)|0,Zn=Math.imul(yo,Uo),On=On+Math.imul(uo,Dl)|0,_n=_n+Math.imul(uo,xl)|0,_n=_n+Math.imul(lo,Dl)|0,Zn=Zn+Math.imul(lo,xl)|0;var nu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(nu>>>26)|0,nu&=67108863,On=Math.imul(ho,Do),_n=Math.imul(ho,Uo),_n=_n+Math.imul(vo,Do)|0,Zn=Math.imul(vo,Uo),On=On+Math.imul(so,Dl)|0,_n=_n+Math.imul(so,xl)|0,_n=_n+Math.imul(yo,Dl)|0,Zn=Zn+Math.imul(yo,xl)|0,On=On+Math.imul(uo,yl)|0,_n=_n+Math.imul(uo,Il)|0,_n=_n+Math.imul(lo,yl)|0,Zn=Zn+Math.imul(lo,Il)|0;var pu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(pu>>>26)|0,pu&=67108863,On=Math.imul(Ro,Do),_n=Math.imul(Ro,Uo),_n=_n+Math.imul(To,Do)|0,Zn=Math.imul(To,Uo),On=On+Math.imul(ho,Dl)|0,_n=_n+Math.imul(ho,xl)|0,_n=_n+Math.imul(vo,Dl)|0,Zn=Zn+Math.imul(vo,xl)|0,On=On+Math.imul(so,yl)|0,_n=_n+Math.imul(so,Il)|0,_n=_n+Math.imul(yo,yl)|0,Zn=Zn+Math.imul(yo,Il)|0,On=On+Math.imul(uo,Bl)|0,_n=_n+Math.imul(uo,Pl)|0,_n=_n+Math.imul(lo,Bl)|0,Zn=Zn+Math.imul(lo,Pl)|0;var mu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(mu>>>26)|0,mu&=67108863,On=Math.imul(qo,Do),_n=Math.imul(qo,Uo),_n=_n+Math.imul(Zo,Do)|0,Zn=Math.imul(Zo,Uo),On=On+Math.imul(Ro,Dl)|0,_n=_n+Math.imul(Ro,xl)|0,_n=_n+Math.imul(To,Dl)|0,Zn=Zn+Math.imul(To,xl)|0,On=On+Math.imul(ho,yl)|0,_n=_n+Math.imul(ho,Il)|0,_n=_n+Math.imul(vo,yl)|0,Zn=Zn+Math.imul(vo,Il)|0,On=On+Math.imul(so,Bl)|0,_n=_n+Math.imul(so,Pl)|0,_n=_n+Math.imul(yo,Bl)|0,Zn=Zn+Math.imul(yo,Pl)|0,On=On+Math.imul(uo,Ol)|0,_n=_n+Math.imul(uo,Nl)|0,_n=_n+Math.imul(lo,Ol)|0,Zn=Zn+Math.imul(lo,Nl)|0;var hu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(hu>>>26)|0,hu&=67108863,On=Math.imul(jo,Do),_n=Math.imul(jo,Uo),_n=_n+Math.imul(No,Do)|0,Zn=Math.imul(No,Uo),On=On+Math.imul(qo,Dl)|0,_n=_n+Math.imul(qo,xl)|0,_n=_n+Math.imul(Zo,Dl)|0,Zn=Zn+Math.imul(Zo,xl)|0,On=On+Math.imul(Ro,yl)|0,_n=_n+Math.imul(Ro,Il)|0,_n=_n+Math.imul(To,yl)|0,Zn=Zn+Math.imul(To,Il)|0,On=On+Math.imul(ho,Bl)|0,_n=_n+Math.imul(ho,Pl)|0,_n=_n+Math.imul(vo,Bl)|0,Zn=Zn+Math.imul(vo,Pl)|0,On=On+Math.imul(so,Ol)|0,_n=_n+Math.imul(so,Nl)|0,_n=_n+Math.imul(yo,Ol)|0,Zn=Zn+Math.imul(yo,Nl)|0,On=On+Math.imul(uo,Ul)|0,_n=_n+Math.imul(uo,Cl)|0,_n=_n+Math.imul(lo,Ul)|0,Zn=Zn+Math.imul(lo,Cl)|0;var yu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(yu>>>26)|0,yu&=67108863,On=Math.imul(Fo,Do),_n=Math.imul(Fo,Uo),_n=_n+Math.imul(Lo,Do)|0,Zn=Math.imul(Lo,Uo),On=On+Math.imul(jo,Dl)|0,_n=_n+Math.imul(jo,xl)|0,_n=_n+Math.imul(No,Dl)|0,Zn=Zn+Math.imul(No,xl)|0,On=On+Math.imul(qo,yl)|0,_n=_n+Math.imul(qo,Il)|0,_n=_n+Math.imul(Zo,yl)|0,Zn=Zn+Math.imul(Zo,Il)|0,On=On+Math.imul(Ro,Bl)|0,_n=_n+Math.imul(Ro,Pl)|0,_n=_n+Math.imul(To,Bl)|0,Zn=Zn+Math.imul(To,Pl)|0,On=On+Math.imul(ho,Ol)|0,_n=_n+Math.imul(ho,Nl)|0,_n=_n+Math.imul(vo,Ol)|0,Zn=Zn+Math.imul(vo,Nl)|0,On=On+Math.imul(so,Ul)|0,_n=_n+Math.imul(so,Cl)|0,_n=_n+Math.imul(yo,Ul)|0,Zn=Zn+Math.imul(yo,Cl)|0,On=On+Math.imul(uo,wo)|0,_n=_n+Math.imul(uo,$o)|0,_n=_n+Math.imul(lo,wo)|0,Zn=Zn+Math.imul(lo,$o)|0;var _u=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(_u>>>26)|0,_u&=67108863,On=Math.imul(_c,Do),_n=Math.imul(_c,Uo),_n=_n+Math.imul(Ko,Do)|0,Zn=Math.imul(Ko,Uo),On=On+Math.imul(Fo,Dl)|0,_n=_n+Math.imul(Fo,xl)|0,_n=_n+Math.imul(Lo,Dl)|0,Zn=Zn+Math.imul(Lo,xl)|0,On=On+Math.imul(jo,yl)|0,_n=_n+Math.imul(jo,Il)|0,_n=_n+Math.imul(No,yl)|0,Zn=Zn+Math.imul(No,Il)|0,On=On+Math.imul(qo,Bl)|0,_n=_n+Math.imul(qo,Pl)|0,_n=_n+Math.imul(Zo,Bl)|0,Zn=Zn+Math.imul(Zo,Pl)|0,On=On+Math.imul(Ro,Ol)|0,_n=_n+Math.imul(Ro,Nl)|0,_n=_n+Math.imul(To,Ol)|0,Zn=Zn+Math.imul(To,Nl)|0,On=On+Math.imul(ho,Ul)|0,_n=_n+Math.imul(ho,Cl)|0,_n=_n+Math.imul(vo,Ul)|0,Zn=Zn+Math.imul(vo,Cl)|0,On=On+Math.imul(so,wo)|0,_n=_n+Math.imul(so,$o)|0,_n=_n+Math.imul(yo,wo)|0,Zn=Zn+Math.imul(yo,$o)|0,On=On+Math.imul(uo,po)|0,_n=_n+Math.imul(uo,So)|0,_n=_n+Math.imul(lo,po)|0,Zn=Zn+Math.imul(lo,So)|0;var fu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(fu>>>26)|0,fu&=67108863,On=Math.imul(Sl,Do),_n=Math.imul(Sl,Uo),_n=_n+Math.imul(Eo,Do)|0,Zn=Math.imul(Eo,Uo),On=On+Math.imul(_c,Dl)|0,_n=_n+Math.imul(_c,xl)|0,_n=_n+Math.imul(Ko,Dl)|0,Zn=Zn+Math.imul(Ko,xl)|0,On=On+Math.imul(Fo,yl)|0,_n=_n+Math.imul(Fo,Il)|0,_n=_n+Math.imul(Lo,yl)|0,Zn=Zn+Math.imul(Lo,Il)|0,On=On+Math.imul(jo,Bl)|0,_n=_n+Math.imul(jo,Pl)|0,_n=_n+Math.imul(No,Bl)|0,Zn=Zn+Math.imul(No,Pl)|0,On=On+Math.imul(qo,Ol)|0,_n=_n+Math.imul(qo,Nl)|0,_n=_n+Math.imul(Zo,Ol)|0,Zn=Zn+Math.imul(Zo,Nl)|0,On=On+Math.imul(Ro,Ul)|0,_n=_n+Math.imul(Ro,Cl)|0,_n=_n+Math.imul(To,Ul)|0,Zn=Zn+Math.imul(To,Cl)|0,On=On+Math.imul(ho,wo)|0,_n=_n+Math.imul(ho,$o)|0,_n=_n+Math.imul(vo,wo)|0,Zn=Zn+Math.imul(vo,$o)|0,On=On+Math.imul(so,po)|0,_n=_n+Math.imul(so,So)|0,_n=_n+Math.imul(yo,po)|0,Zn=Zn+Math.imul(yo,So)|0,On=On+Math.imul(uo,Bo)|0,_n=_n+Math.imul(uo,Ho)|0,_n=_n+Math.imul(lo,Bo)|0,Zn=Zn+Math.imul(lo,Ho)|0;var vu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(vu>>>26)|0,vu&=67108863,On=Math.imul(go,Do),_n=Math.imul(go,Uo),_n=_n+Math.imul(Co,Do)|0,Zn=Math.imul(Co,Uo),On=On+Math.imul(Sl,Dl)|0,_n=_n+Math.imul(Sl,xl)|0,_n=_n+Math.imul(Eo,Dl)|0,Zn=Zn+Math.imul(Eo,xl)|0,On=On+Math.imul(_c,yl)|0,_n=_n+Math.imul(_c,Il)|0,_n=_n+Math.imul(Ko,yl)|0,Zn=Zn+Math.imul(Ko,Il)|0,On=On+Math.imul(Fo,Bl)|0,_n=_n+Math.imul(Fo,Pl)|0,_n=_n+Math.imul(Lo,Bl)|0,Zn=Zn+Math.imul(Lo,Pl)|0,On=On+Math.imul(jo,Ol)|0,_n=_n+Math.imul(jo,Nl)|0,_n=_n+Math.imul(No,Ol)|0,Zn=Zn+Math.imul(No,Nl)|0,On=On+Math.imul(qo,Ul)|0,_n=_n+Math.imul(qo,Cl)|0,_n=_n+Math.imul(Zo,Ul)|0,Zn=Zn+Math.imul(Zo,Cl)|0,On=On+Math.imul(Ro,wo)|0,_n=_n+Math.imul(Ro,$o)|0,_n=_n+Math.imul(To,wo)|0,Zn=Zn+Math.imul(To,$o)|0,On=On+Math.imul(ho,po)|0,_n=_n+Math.imul(ho,So)|0,_n=_n+Math.imul(vo,po)|0,Zn=Zn+Math.imul(vo,So)|0,On=On+Math.imul(so,Bo)|0,_n=_n+Math.imul(so,Ho)|0,_n=_n+Math.imul(yo,Bo)|0,Zn=Zn+Math.imul(yo,Ho)|0,On=On+Math.imul(uo,El)|0,_n=_n+Math.imul(uo,$l)|0,_n=_n+Math.imul(lo,El)|0,Zn=Zn+Math.imul(lo,$l)|0;var iu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(iu>>>26)|0,iu&=67108863,On=Math.imul(go,Dl),_n=Math.imul(go,xl),_n=_n+Math.imul(Co,Dl)|0,Zn=Math.imul(Co,xl),On=On+Math.imul(Sl,yl)|0,_n=_n+Math.imul(Sl,Il)|0,_n=_n+Math.imul(Eo,yl)|0,Zn=Zn+Math.imul(Eo,Il)|0,On=On+Math.imul(_c,Bl)|0,_n=_n+Math.imul(_c,Pl)|0,_n=_n+Math.imul(Ko,Bl)|0,Zn=Zn+Math.imul(Ko,Pl)|0,On=On+Math.imul(Fo,Ol)|0,_n=_n+Math.imul(Fo,Nl)|0,_n=_n+Math.imul(Lo,Ol)|0,Zn=Zn+Math.imul(Lo,Nl)|0,On=On+Math.imul(jo,Ul)|0,_n=_n+Math.imul(jo,Cl)|0,_n=_n+Math.imul(No,Ul)|0,Zn=Zn+Math.imul(No,Cl)|0,On=On+Math.imul(qo,wo)|0,_n=_n+Math.imul(qo,$o)|0,_n=_n+Math.imul(Zo,wo)|0,Zn=Zn+Math.imul(Zo,$o)|0,On=On+Math.imul(Ro,po)|0,_n=_n+Math.imul(Ro,So)|0,_n=_n+Math.imul(To,po)|0,Zn=Zn+Math.imul(To,So)|0,On=On+Math.imul(ho,Bo)|0,_n=_n+Math.imul(ho,Ho)|0,_n=_n+Math.imul(vo,Bo)|0,Zn=Zn+Math.imul(vo,Ho)|0,On=On+Math.imul(so,El)|0,_n=_n+Math.imul(so,$l)|0,_n=_n+Math.imul(yo,El)|0,Zn=Zn+Math.imul(yo,$l)|0;var su=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(su>>>26)|0,su&=67108863,On=Math.imul(go,yl),_n=Math.imul(go,Il),_n=_n+Math.imul(Co,yl)|0,Zn=Math.imul(Co,Il),On=On+Math.imul(Sl,Bl)|0,_n=_n+Math.imul(Sl,Pl)|0,_n=_n+Math.imul(Eo,Bl)|0,Zn=Zn+Math.imul(Eo,Pl)|0,On=On+Math.imul(_c,Ol)|0,_n=_n+Math.imul(_c,Nl)|0,_n=_n+Math.imul(Ko,Ol)|0,Zn=Zn+Math.imul(Ko,Nl)|0,On=On+Math.imul(Fo,Ul)|0,_n=_n+Math.imul(Fo,Cl)|0,_n=_n+Math.imul(Lo,Ul)|0,Zn=Zn+Math.imul(Lo,Cl)|0,On=On+Math.imul(jo,wo)|0,_n=_n+Math.imul(jo,$o)|0,_n=_n+Math.imul(No,wo)|0,Zn=Zn+Math.imul(No,$o)|0,On=On+Math.imul(qo,po)|0,_n=_n+Math.imul(qo,So)|0,_n=_n+Math.imul(Zo,po)|0,Zn=Zn+Math.imul(Zo,So)|0,On=On+Math.imul(Ro,Bo)|0,_n=_n+Math.imul(Ro,Ho)|0,_n=_n+Math.imul(To,Bo)|0,Zn=Zn+Math.imul(To,Ho)|0,On=On+Math.imul(ho,El)|0,_n=_n+Math.imul(ho,$l)|0,_n=_n+Math.imul(vo,El)|0,Zn=Zn+Math.imul(vo,$l)|0;var tu=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(tu>>>26)|0,tu&=67108863,On=Math.imul(go,Bl),_n=Math.imul(go,Pl),_n=_n+Math.imul(Co,Bl)|0,Zn=Math.imul(Co,Pl),On=On+Math.imul(Sl,Ol)|0,_n=_n+Math.imul(Sl,Nl)|0,_n=_n+Math.imul(Eo,Ol)|0,Zn=Zn+Math.imul(Eo,Nl)|0,On=On+Math.imul(_c,Ul)|0,_n=_n+Math.imul(_c,Cl)|0,_n=_n+Math.imul(Ko,Ul)|0,Zn=Zn+Math.imul(Ko,Cl)|0,On=On+Math.imul(Fo,wo)|0,_n=_n+Math.imul(Fo,$o)|0,_n=_n+Math.imul(Lo,wo)|0,Zn=Zn+Math.imul(Lo,$o)|0,On=On+Math.imul(jo,po)|0,_n=_n+Math.imul(jo,So)|0,_n=_n+Math.imul(No,po)|0,Zn=Zn+Math.imul(No,So)|0,On=On+Math.imul(qo,Bo)|0,_n=_n+Math.imul(qo,Ho)|0,_n=_n+Math.imul(Zo,Bo)|0,Zn=Zn+Math.imul(Zo,Ho)|0,On=On+Math.imul(Ro,El)|0,_n=_n+Math.imul(Ro,$l)|0,_n=_n+Math.imul(To,El)|0,Zn=Zn+Math.imul(To,$l)|0;var Hl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Hl>>>26)|0,Hl&=67108863,On=Math.imul(go,Ol),_n=Math.imul(go,Nl),_n=_n+Math.imul(Co,Ol)|0,Zn=Math.imul(Co,Nl),On=On+Math.imul(Sl,Ul)|0,_n=_n+Math.imul(Sl,Cl)|0,_n=_n+Math.imul(Eo,Ul)|0,Zn=Zn+Math.imul(Eo,Cl)|0,On=On+Math.imul(_c,wo)|0,_n=_n+Math.imul(_c,$o)|0,_n=_n+Math.imul(Ko,wo)|0,Zn=Zn+Math.imul(Ko,$o)|0,On=On+Math.imul(Fo,po)|0,_n=_n+Math.imul(Fo,So)|0,_n=_n+Math.imul(Lo,po)|0,Zn=Zn+Math.imul(Lo,So)|0,On=On+Math.imul(jo,Bo)|0,_n=_n+Math.imul(jo,Ho)|0,_n=_n+Math.imul(No,Bo)|0,Zn=Zn+Math.imul(No,Ho)|0,On=On+Math.imul(qo,El)|0,_n=_n+Math.imul(qo,$l)|0,_n=_n+Math.imul(Zo,El)|0,Zn=Zn+Math.imul(Zo,$l)|0;var Zl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Zl>>>26)|0,Zl&=67108863,On=Math.imul(go,Ul),_n=Math.imul(go,Cl),_n=_n+Math.imul(Co,Ul)|0,Zn=Math.imul(Co,Cl),On=On+Math.imul(Sl,wo)|0,_n=_n+Math.imul(Sl,$o)|0,_n=_n+Math.imul(Eo,wo)|0,Zn=Zn+Math.imul(Eo,$o)|0,On=On+Math.imul(_c,po)|0,_n=_n+Math.imul(_c,So)|0,_n=_n+Math.imul(Ko,po)|0,Zn=Zn+Math.imul(Ko,So)|0,On=On+Math.imul(Fo,Bo)|0,_n=_n+Math.imul(Fo,Ho)|0,_n=_n+Math.imul(Lo,Bo)|0,Zn=Zn+Math.imul(Lo,Ho)|0,On=On+Math.imul(jo,El)|0,_n=_n+Math.imul(jo,$l)|0,_n=_n+Math.imul(No,El)|0,Zn=Zn+Math.imul(No,$l)|0;var Jl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Jl>>>26)|0,Jl&=67108863,On=Math.imul(go,wo),_n=Math.imul(go,$o),_n=_n+Math.imul(Co,wo)|0,Zn=Math.imul(Co,$o),On=On+Math.imul(Sl,po)|0,_n=_n+Math.imul(Sl,So)|0,_n=_n+Math.imul(Eo,po)|0,Zn=Zn+Math.imul(Eo,So)|0,On=On+Math.imul(_c,Bo)|0,_n=_n+Math.imul(_c,Ho)|0,_n=_n+Math.imul(Ko,Bo)|0,Zn=Zn+Math.imul(Ko,Ho)|0,On=On+Math.imul(Fo,El)|0,_n=_n+Math.imul(Fo,$l)|0,_n=_n+Math.imul(Lo,El)|0,Zn=Zn+Math.imul(Lo,$l)|0;var Ml=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Ml>>>26)|0,Ml&=67108863,On=Math.imul(go,po),_n=Math.imul(go,So),_n=_n+Math.imul(Co,po)|0,Zn=Math.imul(Co,So),On=On+Math.imul(Sl,Bo)|0,_n=_n+Math.imul(Sl,Ho)|0,_n=_n+Math.imul(Eo,Bo)|0,Zn=Zn+Math.imul(Eo,Ho)|0,On=On+Math.imul(_c,El)|0,_n=_n+Math.imul(_c,$l)|0,_n=_n+Math.imul(Ko,El)|0,Zn=Zn+Math.imul(Ko,$l)|0;var Fl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Fl>>>26)|0,Fl&=67108863,On=Math.imul(go,Bo),_n=Math.imul(go,Ho),_n=_n+Math.imul(Co,Bo)|0,Zn=Math.imul(Co,Ho),On=On+Math.imul(Sl,El)|0,_n=_n+Math.imul(Sl,$l)|0,_n=_n+Math.imul(Eo,El)|0,Zn=Zn+Math.imul(Eo,$l)|0;var Yl=(zn+On|0)+((_n&8191)<<13)|0;zn=(Zn+(_n>>>13)|0)+(Yl>>>26)|0,Yl&=67108863,On=Math.imul(go,El),_n=Math.imul(go,$l),_n=_n+Math.imul(Co,El)|0,Zn=Math.imul(Co,$l);var Vl=(zn+On|0)+((_n&8191)<<13)|0;return zn=(Zn+(_n>>>13)|0)+(Vl>>>26)|0,Vl&=67108863,Nn[0]=Su,Nn[1]=nu,Nn[2]=pu,Nn[3]=mu,Nn[4]=hu,Nn[5]=yu,Nn[6]=_u,Nn[7]=fu,Nn[8]=vu,Nn[9]=iu,Nn[10]=su,Nn[11]=tu,Nn[12]=Hl,Nn[13]=Zl,Nn[14]=Jl,Nn[15]=Ml,Nn[16]=Fl,Nn[17]=Yl,Nn[18]=Vl,zn!==0&&(Nn[19]=zn,Sn.length++),Sn};Math.imul||(In=Tn);function jn(Rn,Gr,Yr){Yr.negative=Gr.negative^Rn.negative,Yr.length=Rn.length+Gr.length;for(var Sn=0,An=0,Pn=0;Pn>>26)|0,An+=Nn>>>26,Nn&=67108863}Yr.words[Pn]=zn,Sn=Nn,Nn=An}return Sn!==0?Yr.words[Pn]=Sn:Yr.length--,Yr._strip()}function Yn(Rn,Gr,Yr){return jn(Rn,Gr,Yr)}jr.prototype.mulTo=function(Gr,Yr){var Sn,An=this.length+Gr.length;return this.length===10&&Gr.length===10?Sn=In(this,Gr,Yr):An<63?Sn=Tn(this,Gr,Yr):An<1024?Sn=jn(this,Gr,Yr):Sn=Yn(this,Gr,Yr),Sn},jr.prototype.mul=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),this.mulTo(Gr,Yr)},jr.prototype.mulf=function(Gr){var Yr=new jr(null);return Yr.words=new Array(this.length+Gr.length),Yn(this,Gr,Yr)},jr.prototype.imul=function(Gr){return this.clone().mulTo(Gr,this)},jr.prototype.imuln=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(typeof Gr=="number"),Er(Gr<67108864);for(var Sn=0,An=0;An>=26,Sn+=Pn/67108864|0,Sn+=Nn>>>26,this.words[An]=Nn&67108863}return Sn!==0&&(this.words[An]=Sn,this.length++),Yr?this.ineg():this},jr.prototype.muln=function(Gr){return this.clone().imuln(Gr)},jr.prototype.sqr=function(){return this.mul(this)},jr.prototype.isqr=function(){return this.imul(this.clone())},jr.prototype.pow=function(Gr){var Yr=$n(Gr);if(Yr.length===0)return new jr(1);for(var Sn=this,An=0;An=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=67108863>>>26-Yr<<26-Yr,Pn;if(Yr!==0){var Nn=0;for(Pn=0;Pn>>26-Yr}Nn&&(this.words[Pn]=Nn,this.length++)}if(Sn!==0){for(Pn=this.length-1;Pn>=0;Pn--)this.words[Pn+Sn]=this.words[Pn];for(Pn=0;Pn=0);var An;Yr?An=(Yr-Yr%26)/26:An=0;var Pn=Gr%26,Nn=Math.min((Gr-Pn)/26,this.length),zn=67108863^67108863>>>Pn<Nn)for(this.length-=Nn,_n=0;_n=0&&(Zn!==0||_n>=An);_n--){var oo=this.words[_n]|0;this.words[_n]=Zn<<26-Pn|oo>>>Pn,Zn=oo&zn}return On&&Zn!==0&&(On.words[On.length++]=Zn),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},jr.prototype.ishrn=function(Gr,Yr,Sn){return Er(this.negative===0),this.iushrn(Gr,Yr,Sn)},jr.prototype.shln=function(Gr){return this.clone().ishln(Gr)},jr.prototype.ushln=function(Gr){return this.clone().iushln(Gr)},jr.prototype.shrn=function(Gr){return this.clone().ishrn(Gr)},jr.prototype.ushrn=function(Gr){return this.clone().iushrn(Gr)},jr.prototype.testn=function(Gr){Er(typeof Gr=="number"&&Gr>=0);var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<=0);var Yr=Gr%26,Sn=(Gr-Yr)/26;if(Er(this.negative===0,"imaskn works only with positive numbers"),this.length<=Sn)return this;if(Yr!==0&&Sn++,this.length=Math.min(Sn,this.length),Yr!==0){var An=67108863^67108863>>>Yr<=67108864;Yr++)this.words[Yr]-=67108864,Yr===this.length-1?this.words[Yr+1]=1:this.words[Yr+1]++;return this.length=Math.max(this.length,Yr+1),this},jr.prototype.isubn=function(Gr){if(Er(typeof Gr=="number"),Er(Gr<67108864),Gr<0)return this.iaddn(-Gr);if(this.negative!==0)return this.negative=0,this.iaddn(Gr),this.negative=1,this;if(this.words[0]-=Gr,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Yr=0;Yr>26)-(On/67108864|0),this.words[Pn+Sn]=Nn&67108863}for(;Pn>26,this.words[Pn+Sn]=Nn&67108863;if(zn===0)return this._strip();for(Er(zn===-1),zn=0,Pn=0;Pn>26,this.words[Pn]=Nn&67108863;return this.negative=1,this._strip()},jr.prototype._wordDiv=function(Gr,Yr){var Sn=this.length-Gr.length,An=this.clone(),Pn=Gr,Nn=Pn.words[Pn.length-1]|0,zn=this._countBits(Nn);Sn=26-zn,Sn!==0&&(Pn=Pn.ushln(Sn),An.iushln(Sn),Nn=Pn.words[Pn.length-1]|0);var On=An.length-Pn.length,_n;if(Yr!=="mod"){_n=new jr(null),_n.length=On+1,_n.words=new Array(_n.length);for(var Zn=0;Zn<_n.length;Zn++)_n.words[Zn]=0}var oo=An.clone()._ishlnsubmul(Pn,1,On);oo.negative===0&&(An=oo,_n&&(_n.words[On]=1));for(var uo=On-1;uo>=0;uo--){var lo=(An.words[Pn.length+uo]|0)*67108864+(An.words[Pn.length+uo-1]|0);for(lo=Math.min(lo/Nn|0,67108863),An._ishlnsubmul(Pn,lo,uo);An.negative!==0;)lo--,An.negative=0,An._ishlnsubmul(Pn,1,uo),An.isZero()||(An.negative^=1);_n&&(_n.words[uo]=lo)}return _n&&_n._strip(),An._strip(),Yr!=="div"&&Sn!==0&&An.iushrn(Sn),{div:_n||null,mod:An}},jr.prototype.divmod=function(Gr,Yr,Sn){if(Er(!Gr.isZero()),this.isZero())return{div:new jr(0),mod:new jr(0)};var An,Pn,Nn;return this.negative!==0&&Gr.negative===0?(Nn=this.neg().divmod(Gr,Yr),Yr!=="mod"&&(An=Nn.div.neg()),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.iadd(Gr)),{div:An,mod:Pn}):this.negative===0&&Gr.negative!==0?(Nn=this.divmod(Gr.neg(),Yr),Yr!=="mod"&&(An=Nn.div.neg()),{div:An,mod:Nn.mod}):this.negative&Gr.negative?(Nn=this.neg().divmod(Gr.neg(),Yr),Yr!=="div"&&(Pn=Nn.mod.neg(),Sn&&Pn.negative!==0&&Pn.isub(Gr)),{div:Nn.div,mod:Pn}):Gr.length>this.length||this.cmp(Gr)<0?{div:new jr(0),mod:this}:Gr.length===1?Yr==="div"?{div:this.divn(Gr.words[0]),mod:null}:Yr==="mod"?{div:null,mod:new jr(this.modrn(Gr.words[0]))}:{div:this.divn(Gr.words[0]),mod:new jr(this.modrn(Gr.words[0]))}:this._wordDiv(Gr,Yr)},jr.prototype.div=function(Gr){return this.divmod(Gr,"div",!1).div},jr.prototype.mod=function(Gr){return this.divmod(Gr,"mod",!1).mod},jr.prototype.umod=function(Gr){return this.divmod(Gr,"mod",!0).mod},jr.prototype.divRound=function(Gr){var Yr=this.divmod(Gr);if(Yr.mod.isZero())return Yr.div;var Sn=Yr.div.negative!==0?Yr.mod.isub(Gr):Yr.mod,An=Gr.ushrn(1),Pn=Gr.andln(1),Nn=Sn.cmp(An);return Nn<0||Pn===1&&Nn===0?Yr.div:Yr.div.negative!==0?Yr.div.isubn(1):Yr.div.iaddn(1)},jr.prototype.modrn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=(1<<26)%Gr,An=0,Pn=this.length-1;Pn>=0;Pn--)An=(Sn*An+(this.words[Pn]|0))%Gr;return Yr?-An:An},jr.prototype.modn=function(Gr){return this.modrn(Gr)},jr.prototype.idivn=function(Gr){var Yr=Gr<0;Yr&&(Gr=-Gr),Er(Gr<=67108863);for(var Sn=0,An=this.length-1;An>=0;An--){var Pn=(this.words[An]|0)+Sn*67108864;this.words[An]=Pn/Gr|0,Sn=Pn%Gr}return this._strip(),Yr?this.ineg():this},jr.prototype.divn=function(Gr){return this.clone().idivn(Gr)},jr.prototype.egcd=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=new jr(0),zn=new jr(1),On=0;Yr.isEven()&&Sn.isEven();)Yr.iushrn(1),Sn.iushrn(1),++On;for(var _n=Sn.clone(),Zn=Yr.clone();!Yr.isZero();){for(var oo=0,uo=1;!(Yr.words[0]&uo)&&oo<26;++oo,uo<<=1);if(oo>0)for(Yr.iushrn(oo);oo-- >0;)(An.isOdd()||Pn.isOdd())&&(An.iadd(_n),Pn.isub(Zn)),An.iushrn(1),Pn.iushrn(1);for(var lo=0,co=1;!(Sn.words[0]&co)&&lo<26;++lo,co<<=1);if(lo>0)for(Sn.iushrn(lo);lo-- >0;)(Nn.isOdd()||zn.isOdd())&&(Nn.iadd(_n),zn.isub(Zn)),Nn.iushrn(1),zn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Nn),Pn.isub(zn)):(Sn.isub(Yr),Nn.isub(An),zn.isub(Pn))}return{a:Nn,b:zn,gcd:Sn.iushln(On)}},jr.prototype._invmp=function(Gr){Er(Gr.negative===0),Er(!Gr.isZero());var Yr=this,Sn=Gr.clone();Yr.negative!==0?Yr=Yr.umod(Gr):Yr=Yr.clone();for(var An=new jr(1),Pn=new jr(0),Nn=Sn.clone();Yr.cmpn(1)>0&&Sn.cmpn(1)>0;){for(var zn=0,On=1;!(Yr.words[0]&On)&&zn<26;++zn,On<<=1);if(zn>0)for(Yr.iushrn(zn);zn-- >0;)An.isOdd()&&An.iadd(Nn),An.iushrn(1);for(var _n=0,Zn=1;!(Sn.words[0]&Zn)&&_n<26;++_n,Zn<<=1);if(_n>0)for(Sn.iushrn(_n);_n-- >0;)Pn.isOdd()&&Pn.iadd(Nn),Pn.iushrn(1);Yr.cmp(Sn)>=0?(Yr.isub(Sn),An.isub(Pn)):(Sn.isub(Yr),Pn.isub(An))}var oo;return Yr.cmpn(1)===0?oo=An:oo=Pn,oo.cmpn(0)<0&&oo.iadd(Gr),oo},jr.prototype.gcd=function(Gr){if(this.isZero())return Gr.abs();if(Gr.isZero())return this.abs();var Yr=this.clone(),Sn=Gr.clone();Yr.negative=0,Sn.negative=0;for(var An=0;Yr.isEven()&&Sn.isEven();An++)Yr.iushrn(1),Sn.iushrn(1);do{for(;Yr.isEven();)Yr.iushrn(1);for(;Sn.isEven();)Sn.iushrn(1);var Pn=Yr.cmp(Sn);if(Pn<0){var Nn=Yr;Yr=Sn,Sn=Nn}else if(Pn===0||Sn.cmpn(1)===0)break;Yr.isub(Sn)}while(!0);return Sn.iushln(An)},jr.prototype.invm=function(Gr){return this.egcd(Gr).a.umod(Gr)},jr.prototype.isEven=function(){return(this.words[0]&1)===0},jr.prototype.isOdd=function(){return(this.words[0]&1)===1},jr.prototype.andln=function(Gr){return this.words[0]&Gr},jr.prototype.bincn=function(Gr){Er(typeof Gr=="number");var Yr=Gr%26,Sn=(Gr-Yr)/26,An=1<>>26,zn&=67108863,this.words[Nn]=zn}return Pn!==0&&(this.words[Nn]=Pn,this.length++),this},jr.prototype.isZero=function(){return this.length===1&&this.words[0]===0},jr.prototype.cmpn=function(Gr){var Yr=Gr<0;if(this.negative!==0&&!Yr)return-1;if(this.negative===0&&Yr)return 1;this._strip();var Sn;if(this.length>1)Sn=1;else{Yr&&(Gr=-Gr),Er(Gr<=67108863,"Number is too big");var An=this.words[0]|0;Sn=An===Gr?0:AnGr.length)return 1;if(this.length=0;Sn--){var An=this.words[Sn]|0,Pn=Gr.words[Sn]|0;if(An!==Pn){AnPn&&(Yr=1);break}}return Yr},jr.prototype.gtn=function(Gr){return this.cmpn(Gr)===1},jr.prototype.gt=function(Gr){return this.cmp(Gr)===1},jr.prototype.gten=function(Gr){return this.cmpn(Gr)>=0},jr.prototype.gte=function(Gr){return this.cmp(Gr)>=0},jr.prototype.ltn=function(Gr){return this.cmpn(Gr)===-1},jr.prototype.lt=function(Gr){return this.cmp(Gr)===-1},jr.prototype.lten=function(Gr){return this.cmpn(Gr)<=0},jr.prototype.lte=function(Gr){return this.cmp(Gr)<=0},jr.prototype.eqn=function(Gr){return this.cmpn(Gr)===0},jr.prototype.eq=function(Gr){return this.cmp(Gr)===0},jr.red=function(Gr){return new no(Gr)},jr.prototype.toRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),Er(this.negative===0,"red works only with positives"),Gr.convertTo(this)._forceRed(Gr)},jr.prototype.fromRed=function(){return Er(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},jr.prototype._forceRed=function(Gr){return this.red=Gr,this},jr.prototype.forceRed=function(Gr){return Er(!this.red,"Already a number in reduction context"),this._forceRed(Gr)},jr.prototype.redAdd=function(Gr){return Er(this.red,"redAdd works only with red numbers"),this.red.add(this,Gr)},jr.prototype.redIAdd=function(Gr){return Er(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,Gr)},jr.prototype.redSub=function(Gr){return Er(this.red,"redSub works only with red numbers"),this.red.sub(this,Gr)},jr.prototype.redISub=function(Gr){return Er(this.red,"redISub works only with red numbers"),this.red.isub(this,Gr)},jr.prototype.redShl=function(Gr){return Er(this.red,"redShl works only with red numbers"),this.red.shl(this,Gr)},jr.prototype.redMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.mul(this,Gr)},jr.prototype.redIMul=function(Gr){return Er(this.red,"redMul works only with red numbers"),this.red._verify2(this,Gr),this.red.imul(this,Gr)},jr.prototype.redSqr=function(){return Er(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},jr.prototype.redISqr=function(){return Er(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},jr.prototype.redSqrt=function(){return Er(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},jr.prototype.redInvm=function(){return Er(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},jr.prototype.redNeg=function(){return Er(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},jr.prototype.redPow=function(Gr){return Er(this.red&&!Gr.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,Gr)};var ga={k256:null,p224:null,p192:null,p25519:null};function na(Rn,Gr){this.name=Rn,this.p=new jr(Gr,16),this.n=this.p.bitLength(),this.k=new jr(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}na.prototype._tmp=function(){var Gr=new jr(null);return Gr.words=new Array(Math.ceil(this.n/13)),Gr},na.prototype.ireduce=function(Gr){var Yr=Gr,Sn;do this.split(Yr,this.tmp),Yr=this.imulK(Yr),Yr=Yr.iadd(this.tmp),Sn=Yr.bitLength();while(Sn>this.n);var An=Sn0?Yr.isub(this.p):Yr.strip!==void 0?Yr.strip():Yr._strip(),Yr},na.prototype.split=function(Gr,Yr){Gr.iushrn(this.n,0,Yr)},na.prototype.imulK=function(Gr){return Gr.imul(this.k)};function _i(){na.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}kr(_i,na),_i.prototype.split=function(Gr,Yr){for(var Sn=4194303,An=Math.min(Gr.length,9),Pn=0;Pn>>22,Nn=zn}Nn>>>=22,Gr.words[Pn-10]=Nn,Nn===0&&Gr.length>10?Gr.length-=10:Gr.length-=9},_i.prototype.imulK=function(Gr){Gr.words[Gr.length]=0,Gr.words[Gr.length+1]=0,Gr.length+=2;for(var Yr=0,Sn=0;Sn>>=26,Gr.words[Sn]=Pn,Yr=An}return Yr!==0&&(Gr.words[Gr.length++]=Yr),Gr},jr._prime=function(Gr){if(ga[Gr])return ga[Gr];var Yr;if(Gr==="k256")Yr=new _i;else if(Gr==="p224")Yr=new ro;else if(Gr==="p192")Yr=new to;else if(Gr==="p25519")Yr=new io;else throw new Error("Unknown prime "+Gr);return ga[Gr]=Yr,Yr};function no(Rn){if(typeof Rn=="string"){var Gr=jr._prime(Rn);this.m=Gr.p,this.prime=Gr}else Er(Rn.gtn(1),"modulus must be greater than 1"),this.m=Rn,this.prime=null}no.prototype._verify1=function(Gr){Er(Gr.negative===0,"red works only with positives"),Er(Gr.red,"red works only with red numbers")},no.prototype._verify2=function(Gr,Yr){Er((Gr.negative|Yr.negative)===0,"red works only with positives"),Er(Gr.red&&Gr.red===Yr.red,"red works only with red numbers")},no.prototype.imod=function(Gr){return this.prime?this.prime.ireduce(Gr)._forceRed(this):(Hr(Gr,Gr.umod(this.m)._forceRed(this)),Gr)},no.prototype.neg=function(Gr){return Gr.isZero()?Gr.clone():this.m.sub(Gr)._forceRed(this)},no.prototype.add=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.add(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn._forceRed(this)},no.prototype.iadd=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.iadd(Yr);return Sn.cmp(this.m)>=0&&Sn.isub(this.m),Sn},no.prototype.sub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.sub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn._forceRed(this)},no.prototype.isub=function(Gr,Yr){this._verify2(Gr,Yr);var Sn=Gr.isub(Yr);return Sn.cmpn(0)<0&&Sn.iadd(this.m),Sn},no.prototype.shl=function(Gr,Yr){return this._verify1(Gr),this.imod(Gr.ushln(Yr))},no.prototype.imul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.imul(Yr))},no.prototype.mul=function(Gr,Yr){return this._verify2(Gr,Yr),this.imod(Gr.mul(Yr))},no.prototype.isqr=function(Gr){return this.imul(Gr,Gr.clone())},no.prototype.sqr=function(Gr){return this.mul(Gr,Gr)},no.prototype.sqrt=function(Gr){if(Gr.isZero())return Gr.clone();var Yr=this.m.andln(3);if(Er(Yr%2===1),Yr===3){var Sn=this.m.add(new jr(1)).iushrn(2);return this.pow(Gr,Sn)}for(var An=this.m.subn(1),Pn=0;!An.isZero()&&An.andln(1)===0;)Pn++,An.iushrn(1);Er(!An.isZero());var Nn=new jr(1).toRed(this),zn=Nn.redNeg(),On=this.m.subn(1).iushrn(1),_n=this.m.bitLength();for(_n=new jr(2*_n*_n).toRed(this);this.pow(_n,On).cmp(zn)!==0;)_n.redIAdd(zn);for(var Zn=this.pow(_n,An),oo=this.pow(Gr,An.addn(1).iushrn(1)),uo=this.pow(Gr,An),lo=Pn;uo.cmp(Nn)!==0;){for(var co=uo,so=0;co.cmp(Nn)!==0;so++)co=co.redSqr();Er(so=0;Pn--){for(var Zn=Yr.words[Pn],oo=_n-1;oo>=0;oo--){var uo=Zn>>oo&1;if(Nn!==An[0]&&(Nn=this.sqr(Nn)),uo===0&&zn===0){On=0;continue}zn<<=1,zn|=uo,On++,!(On!==Sn&&(Pn!==0||oo!==0))&&(Nn=this.mul(Nn,An[zn]),On=0,zn=0)}_n=26}return Nn},no.prototype.convertTo=function(Gr){var Yr=Gr.umod(this.m);return Yr===Gr?Yr.clone():Yr},no.prototype.convertFrom=function(Gr){var Yr=Gr.clone();return Yr.red=null,Yr},jr.mont=function(Gr){return new $a(Gr)};function $a(Rn){no.call(this,Rn),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new jr(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}kr($a,no),$a.prototype.convertTo=function(Gr){return this.imod(Gr.ushln(this.shift))},$a.prototype.convertFrom=function(Gr){var Yr=this.imod(Gr.mul(this.rinv));return Yr.red=null,Yr},$a.prototype.imul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return Gr.words[0]=0,Gr.length=1,Gr;var Sn=Gr.imul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.mul=function(Gr,Yr){if(Gr.isZero()||Yr.isZero())return new jr(0)._forceRed(this);var Sn=Gr.mul(Yr),An=Sn.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),Pn=Sn.isub(An).iushrn(this.shift),Nn=Pn;return Pn.cmp(this.m)>=0?Nn=Pn.isub(this.m):Pn.cmpn(0)<0&&(Nn=Pn.iadd(this.m)),Nn._forceRed(this)},$a.prototype.invm=function(Gr){var Yr=this.imod(Gr._invmp(this.m).mul(this.r2));return Yr._forceRed(this)}})(fr,commonjsGlobal)})(bn$2);var bnExports$2=bn$2.exports,_Buffer$2=safeBufferExports.Buffer;function base$2(fr){if(fr.length>=255)throw new TypeError("Alphabet too long");for(var br=new Uint8Array(256),wr=0;wr>>0,jn=new Uint8Array(In);$n!==Tn;){for(var Yn=Xr[$n],ga=0,na=In-1;(Yn!==0||ga>>0,jn[na]=Yn%Br>>>0,Yn=Yn/Br>>>0;if(Yn!==0)throw new Error("Non-zero carry");wn=ga,$n++}for(var _i=In-wn;_i!==In&&jn[_i]===0;)_i++;for(var ro=qr.repeat(En);_i>>0,In=new Uint8Array(Tn);En>>0,In[ga]=jn%256>>>0,jn=jn/256>>>0;if(jn!==0)throw new Error("Non-zero carry");$n=Yn,En++}for(var na=Tn-$n;na!==Tn&&In[na]===0;)na++;var _i=_Buffer$2.allocUnsafe(wn+(Tn-na));_i.fill(0,0,wn);for(var ro=wn;na!==Tn;)_i[ro++]=In[na++];return _i}function Jr(Xr){var En=Zr(Xr);if(En)return En;throw new Error("Non-base"+Br+" character")}return{encode:Hr,decodeUnsafe:Zr,decode:Jr}}var src$2=base$2,basex$2=src$2,ALPHABET$2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",bs58$4=basex$2(ALPHABET$2);function inRange(fr,br,wr){return br<=fr&&fr<=wr}function ToDictionary(fr){if(fr===void 0)return{};if(fr===Object(fr))return fr;throw TypeError("Could not convert argument to dictionary")}function stringToCodePoints(fr){for(var br=String(fr),wr=br.length,Er=0,kr=[];Er57343)kr.push(jr);else if(56320<=jr&&jr<=57343)kr.push(65533);else if(55296<=jr&&jr<=56319)if(Er===wr-1)kr.push(65533);else{var Br=fr.charCodeAt(Er+1);if(56320<=Br&&Br<=57343){var qr=jr&1023,Wr=Br&1023;kr.push(65536+(qr<<10)+Wr),Er+=1}else kr.push(65533)}Er+=1}return kr}function codePointsToString(fr){for(var br="",wr=0;wr>10)+55296,(Er&1023)+56320))}return br}var end_of_stream=-1;function Stream(fr){this.tokens=[].slice.call(fr)}Stream.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():end_of_stream},prepend:function(fr){if(Array.isArray(fr))for(var br=fr;br.length;)this.tokens.unshift(br.pop());else this.tokens.unshift(fr)},push:function(fr){if(Array.isArray(fr))for(var br=fr;br.length;)this.tokens.push(br.shift());else this.tokens.push(fr)}};var finished=-1;function decoderError(fr,br){if(fr)throw TypeError("Decoder error");return br||65533}var DEFAULT_ENCODING="utf-8";function TextDecoder$1(fr,br){if(!(this instanceof TextDecoder$1))return new TextDecoder$1(fr,br);if(fr=fr!==void 0?String(fr).toLowerCase():DEFAULT_ENCODING,fr!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");br=ToDictionary(br),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=!!br.fatal,this._ignoreBOM=!!br.ignoreBOM,Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}TextDecoder$1.prototype={decode:function fr(br,wr){var Er;typeof br=="object"&&br instanceof ArrayBuffer?Er=new Uint8Array(br):typeof br=="object"&&"buffer"in br&&br.buffer instanceof ArrayBuffer?Er=new Uint8Array(br.buffer,br.byteOffset,br.byteLength):Er=new Uint8Array(0),wr=ToDictionary(wr),this._streaming||(this._decoder=new UTF8Decoder({fatal:this._fatal}),this._BOMseen=!1),this._streaming=!!wr.stream;for(var kr=new Stream(Er),jr=[],Br;!kr.endOfStream()&&(Br=this._decoder.handler(kr,kr.read()),Br!==finished);)Br!==null&&(Array.isArray(Br)?jr.push.apply(jr,Br):jr.push(Br));if(!this._streaming){do{if(Br=this._decoder.handler(kr,kr.read()),Br===finished)break;Br!==null&&(Array.isArray(Br)?jr.push.apply(jr,Br):jr.push(Br))}while(!kr.endOfStream());this._decoder=null}return jr.length&&["utf-8"].indexOf(this.encoding)!==-1&&!this._ignoreBOM&&!this._BOMseen&&(jr[0]===65279?(this._BOMseen=!0,jr.shift()):this._BOMseen=!0),codePointsToString(jr)}};function TextEncoder$1(fr,br){if(!(this instanceof TextEncoder$1))return new TextEncoder$1(fr,br);if(fr=fr!==void 0?String(fr).toLowerCase():DEFAULT_ENCODING,fr!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");br=ToDictionary(br),this._streaming=!1,this._encoder=null,this._options={fatal:!!br.fatal},Object.defineProperty(this,"encoding",{value:"utf-8"})}TextEncoder$1.prototype={encode:function fr(br,wr){br=br?String(br):"",wr=ToDictionary(wr),this._streaming||(this._encoder=new UTF8Encoder(this._options)),this._streaming=!!wr.stream;for(var Er=[],kr=new Stream(stringToCodePoints(br)),jr;!kr.endOfStream()&&(jr=this._encoder.handler(kr,kr.read()),jr!==finished);)Array.isArray(jr)?Er.push.apply(Er,jr):Er.push(jr);if(!this._streaming){for(;jr=this._encoder.handler(kr,kr.read()),jr!==finished;)Array.isArray(jr)?Er.push.apply(Er,jr):Er.push(jr);this._encoder=null}return new Uint8Array(Er)}};function UTF8Decoder(fr){var br=fr.fatal,wr=0,Er=0,kr=0,jr=128,Br=191;this.handler=function(qr,Wr){if(Wr===end_of_stream&&kr!==0)return kr=0,decoderError(br);if(Wr===end_of_stream)return finished;if(kr===0){if(inRange(Wr,0,127))return Wr;if(inRange(Wr,194,223))kr=1,wr=Wr-192;else if(inRange(Wr,224,239))Wr===224&&(jr=160),Wr===237&&(Br=159),kr=2,wr=Wr-224;else if(inRange(Wr,240,244))Wr===240&&(jr=144),Wr===244&&(Br=143),kr=3,wr=Wr-240;else return decoderError(br);return wr=wr<<6*kr,null}if(!inRange(Wr,jr,Br))return wr=kr=Er=0,jr=128,Br=191,qr.prepend(Wr),decoderError(br);if(jr=128,Br=191,Er+=1,wr+=Wr-128<<6*(kr-Er),Er!==kr)return null;var Vr=wr;return wr=kr=Er=0,Vr}}function UTF8Encoder(fr){fr.fatal,this.handler=function(br,wr){if(wr===end_of_stream)return finished;if(inRange(wr,0,127))return wr;var Er,kr;inRange(wr,128,2047)?(Er=1,kr=192):inRange(wr,2048,65535)?(Er=2,kr=224):inRange(wr,65536,1114111)&&(Er=3,kr=240);for(var jr=[(wr>>6*Er)+kr];Er>0;){var Br=wr>>6*(Er-1);jr.push(128|Br&63),Er-=1}return jr}}const encoding$1=Object.freeze(Object.defineProperty({__proto__:null,TextDecoder:TextDecoder$1,TextEncoder:TextEncoder$1},Symbol.toStringTag,{value:"Module"})),require$$2=getAugmentedNamespace(encoding$1);var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(fr,br,wr,Er){Er===void 0&&(Er=wr),Object.defineProperty(fr,Er,{enumerable:!0,get:function(){return br[wr]}})}:function(fr,br,wr,Er){Er===void 0&&(Er=wr),fr[Er]=br[wr]}),__setModuleDefault=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(fr,br){Object.defineProperty(fr,"default",{enumerable:!0,value:br})}:function(fr,br){fr.default=br}),__decorate=commonjsGlobal&&commonjsGlobal.__decorate||function(fr,br,wr,Er){var kr=arguments.length,jr=kr<3?br:Er===null?Er=Object.getOwnPropertyDescriptor(br,wr):Er,Br;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")jr=Reflect.decorate(fr,br,wr,Er);else for(var qr=fr.length-1;qr>=0;qr--)(Br=fr[qr])&&(jr=(kr<3?Br(jr):kr>3?Br(br,wr,jr):Br(br,wr))||jr);return kr>3&&jr&&Object.defineProperty(br,wr,jr),jr},__importStar=commonjsGlobal&&commonjsGlobal.__importStar||function(fr){if(fr&&fr.__esModule)return fr;var br={};if(fr!=null)for(var wr in fr)wr!=="default"&&Object.hasOwnProperty.call(fr,wr)&&__createBinding(br,fr,wr);return __setModuleDefault(br,fr),br},__importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(fr){return fr&&fr.__esModule?fr:{default:fr}};Object.defineProperty(lib,"__esModule",{value:!0});var deserializeUnchecked_1=lib.deserializeUnchecked=deserialize_1=lib.deserialize=serialize_1=lib.serialize=lib.BinaryReader=lib.BinaryWriter=lib.BorshError=lib.baseDecode=lib.baseEncode=void 0;const bn_js_1=__importDefault(bnExports$2),bs58_1=__importDefault(bs58$4),encoding=__importStar(require$$2),ResolvedTextDecoder=typeof TextDecoder!="function"?encoding.TextDecoder:TextDecoder,textDecoder=new ResolvedTextDecoder("utf-8",{fatal:!0});function baseEncode(fr){return typeof fr=="string"&&(fr=Buffer$2.from(fr,"utf8")),bs58_1.default.encode(Buffer$2.from(fr))}lib.baseEncode=baseEncode;function baseDecode(fr){return Buffer$2.from(bs58_1.default.decode(fr))}lib.baseDecode=baseDecode;const INITIAL_LENGTH=1024;class BorshError extends Error{constructor(br){super(br),this.fieldPath=[],this.originalMessage=br}addToFieldPath(br){this.fieldPath.splice(0,0,br),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}lib.BorshError=BorshError;class BinaryWriter{constructor(){this.buf=Buffer$2.alloc(INITIAL_LENGTH),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer$2.concat([this.buf,Buffer$2.alloc(INITIAL_LENGTH)]))}writeU8(br){this.maybeResize(),this.buf.writeUInt8(br,this.length),this.length+=1}writeU16(br){this.maybeResize(),this.buf.writeUInt16LE(br,this.length),this.length+=2}writeU32(br){this.maybeResize(),this.buf.writeUInt32LE(br,this.length),this.length+=4}writeU64(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",8)))}writeU128(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",16)))}writeU256(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",32)))}writeU512(br){this.maybeResize(),this.writeBuffer(Buffer$2.from(new bn_js_1.default(br).toArray("le",64)))}writeBuffer(br){this.buf=Buffer$2.concat([Buffer$2.from(this.buf.subarray(0,this.length)),br,Buffer$2.alloc(INITIAL_LENGTH)]),this.length+=br.length}writeString(br){this.maybeResize();const wr=Buffer$2.from(br,"utf8");this.writeU32(wr.length),this.writeBuffer(wr)}writeFixedArray(br){this.writeBuffer(Buffer$2.from(br))}writeArray(br,wr){this.maybeResize(),this.writeU32(br.length);for(const Er of br)this.maybeResize(),wr(Er)}toArray(){return this.buf.subarray(0,this.length)}}lib.BinaryWriter=BinaryWriter;function handlingRangeError(fr,br,wr){const Er=wr.value;wr.value=function(...kr){try{return Er.apply(this,kr)}catch(jr){if(jr instanceof RangeError){const Br=jr.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(Br)>=0)throw new BorshError("Reached the end of buffer when deserializing")}throw jr}}}class BinaryReader{constructor(br){this.buf=br,this.offset=0}readU8(){const br=this.buf.readUInt8(this.offset);return this.offset+=1,br}readU16(){const br=this.buf.readUInt16LE(this.offset);return this.offset+=2,br}readU32(){const br=this.buf.readUInt32LE(this.offset);return this.offset+=4,br}readU64(){const br=this.readBuffer(8);return new bn_js_1.default(br,"le")}readU128(){const br=this.readBuffer(16);return new bn_js_1.default(br,"le")}readU256(){const br=this.readBuffer(32);return new bn_js_1.default(br,"le")}readU512(){const br=this.readBuffer(64);return new bn_js_1.default(br,"le")}readBuffer(br){if(this.offset+br>this.buf.length)throw new BorshError(`Expected buffer length ${br} isn't within bounds`);const wr=this.buf.slice(this.offset,this.offset+br);return this.offset+=br,wr}readString(){const br=this.readU32(),wr=this.readBuffer(br);try{return textDecoder.decode(wr)}catch(Er){throw new BorshError(`Error decoding UTF-8 string: ${Er}`)}}readFixedArray(br){return new Uint8Array(this.readBuffer(br))}readArray(br){const wr=this.readU32(),Er=Array();for(let kr=0;kr{serializeField(fr,br,jr,Er[0],kr)});else if(Er.kind!==void 0)switch(Er.kind){case"option":{wr==null?kr.writeU8(0):(kr.writeU8(1),serializeField(fr,br,wr,Er.type,kr));break}case"map":{kr.writeU32(wr.size),wr.forEach((jr,Br)=>{serializeField(fr,br,Br,Er.key,kr),serializeField(fr,br,jr,Er.value,kr)});break}default:throw new BorshError(`FieldType ${Er} unrecognized`)}else serializeStruct(fr,wr,kr)}catch(jr){throw jr instanceof BorshError&&jr.addToFieldPath(br),jr}}function serializeStruct(fr,br,wr){if(typeof br.borshSerialize=="function"){br.borshSerialize(wr);return}const Er=fr.get(br.constructor);if(!Er)throw new BorshError(`Class ${br.constructor.name} is missing in schema`);if(Er.kind==="struct")Er.fields.map(([kr,jr])=>{serializeField(fr,kr,br[kr],jr,wr)});else if(Er.kind==="enum"){const kr=br[Er.field];for(let jr=0;jrdeserializeField(fr,br,wr[0],Er))}if(wr.kind==="option")return Er.readU8()?deserializeField(fr,br,wr.type,Er):void 0;if(wr.kind==="map"){let kr=new Map;const jr=Er.readU32();for(let Br=0;Br=Er.values.length)throw new BorshError(`Enum index: ${kr} is out of range`);const[jr,Br]=Er.values[kr],qr=deserializeField(fr,jr,Br,wr);return new br({[jr]:qr})}throw new BorshError(`Unexpected schema kind: ${Er.kind} for ${br.constructor.name}`)}function deserialize(fr,br,wr,Er=BinaryReader){const kr=new Er(wr),jr=deserializeStruct(fr,br,kr);if(kr.offsetthis.span)throw new RangeError("indeterminate span");return this.span}replicate(br){const wr=Object.create(this.constructor.prototype);return Object.assign(wr,this),wr.property=br,wr}fromArray(br){}}Layout$1.Layout=Layout;function nameWithProperty(fr,br){return br.property?fr+"["+br.property+"]":fr}Layout$1.nameWithProperty=nameWithProperty;function bindConstructorLayout(fr,br){if(typeof fr!="function")throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(fr,"layout_"))throw new Error("Class is already bound to a layout");if(!(br&&br instanceof Layout))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(br,"boundConstructor_"))throw new Error("layout is already bound to a constructor");fr.layout_=br,br.boundConstructor_=fr,br.makeDestinationObject=()=>new fr,Object.defineProperty(fr.prototype,"encode",{value(wr,Er){return br.encode(this,wr,Er)},writable:!0}),Object.defineProperty(fr,"decode",{value(wr,Er){return br.decode(wr,Er)},writable:!0})}Layout$1.bindConstructorLayout=bindConstructorLayout;class ExternalLayout extends Layout{isCount(){throw new Error("ExternalLayout is abstract")}}Layout$1.ExternalLayout=ExternalLayout;class GreedyCount extends ExternalLayout{constructor(br=1,wr){if(!Number.isInteger(br)||0>=br)throw new TypeError("elementSpan must be a (positive) integer");super(-1,wr),this.elementSpan=br}isCount(){return!0}decode(br,wr=0){checkUint8Array(br);const Er=br.length-wr;return Math.floor(Er/this.elementSpan)}encode(br,wr,Er){return 0}}Layout$1.GreedyCount=GreedyCount;class OffsetLayout extends ExternalLayout{constructor(br,wr=0,Er){if(!(br instanceof Layout))throw new TypeError("layout must be a Layout");if(!Number.isInteger(wr))throw new TypeError("offset must be integer or undefined");super(br.span,Er||br.property),this.layout=br,this.offset=wr}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(br,wr=0){return this.layout.decode(br,wr+this.offset)}encode(br,wr,Er=0){return this.layout.encode(br,wr,Er+this.offset)}}Layout$1.OffsetLayout=OffsetLayout;class UInt extends Layout{constructor(br,wr){if(super(br,wr),6Br+kr.encode(qr,wr,Er+Br),0);return this.count instanceof ExternalLayout&&this.count.encode(br.length,wr,Er),jr}}Layout$1.Sequence=Sequence;class Structure extends Layout{constructor(br,wr,Er){if(!(Array.isArray(br)&&br.reduce((jr,Br)=>jr&&Br instanceof Layout,!0)))throw new TypeError("fields must be array of Layout instances");typeof wr=="boolean"&&Er===void 0&&(Er=wr,wr=void 0);for(const jr of br)if(0>jr.span&&jr.property===void 0)throw new Error("fields cannot contain unnamed variable-length layout");let kr=-1;try{kr=br.reduce((jr,Br)=>jr+Br.getSpan(),0)}catch{}super(kr,wr),this.fields=br,this.decodePrefixes=!!Er}getSpan(br,wr=0){if(0<=this.span)return this.span;let Er=0;try{Er=this.fields.reduce((kr,jr)=>{const Br=jr.getSpan(br,wr);return wr+=Br,kr+Br},0)}catch{throw new RangeError("indeterminate span")}return Er}decode(br,wr=0){checkUint8Array(br);const Er=this.makeDestinationObject();for(const kr of this.fields)if(kr.property!==void 0&&(Er[kr.property]=kr.decode(br,wr)),wr+=kr.getSpan(br,wr),this.decodePrefixes&&br.length===wr)break;return Er}encode(br,wr,Er=0){const kr=Er;let jr=0,Br=0;for(const qr of this.fields){let Wr=qr.span;if(Br=0Wr&&(Wr=qr.getSpan(wr,Er)))}jr=Er,Er+=Wr}return jr+Br-kr}fromArray(br){const wr=this.makeDestinationObject();for(const Er of this.fields)Er.property!==void 0&&0Er.span?wr=-1:0<=wr&&(wr+=Er.span)}}}Layout$1.Structure=Structure;class UnionDiscriminator{constructor(br){this.property=br}decode(br,wr){throw new Error("UnionDiscriminator is abstract")}encode(br,wr,Er){throw new Error("UnionDiscriminator is abstract")}}Layout$1.UnionDiscriminator=UnionDiscriminator;class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(br,wr){if(!(br instanceof ExternalLayout&&br.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(wr||br.property||"variant"),this.layout=br}decode(br,wr){return this.layout.decode(br,wr)}encode(br,wr,Er){return this.layout.encode(br,wr,Er)}}Layout$1.UnionLayoutDiscriminator=UnionLayoutDiscriminator;class Union extends Layout{constructor(br,wr,Er){let kr;if(br instanceof UInt||br instanceof UIntBE)kr=new UnionLayoutDiscriminator(new OffsetLayout(br));else if(br instanceof ExternalLayout&&br.isCount())kr=new UnionLayoutDiscriminator(br);else if(br instanceof UnionDiscriminator)kr=br;else throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");if(wr===void 0&&(wr=null),!(wr===null||wr instanceof Layout))throw new TypeError("defaultLayout must be null or a Layout");if(wr!==null){if(0>wr.span)throw new Error("defaultLayout must have constant span");wr.property===void 0&&(wr=wr.replicate("content"))}let jr=-1;wr&&(jr=wr.span,0<=jr&&(br instanceof UInt||br instanceof UIntBE)&&(jr+=kr.layout.span)),super(jr,Er),this.discriminator=kr,this.usesPrefixDiscriminator=br instanceof UInt||br instanceof UIntBE,this.defaultLayout=wr,this.registry={};let Br=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(qr){return Br(qr)},this.configGetSourceVariant=function(qr){Br=qr.bind(this)}}getSpan(br,wr=0){if(0<=this.span)return this.span;const Er=this.getVariant(br,wr);if(!Er)throw new Error("unable to determine span for unrecognized variant");return Er.getSpan(br,wr)}defaultGetSourceVariant(br){if(Object.prototype.hasOwnProperty.call(br,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(br,this.defaultLayout.property))return;const wr=this.registry[br[this.discriminator.property]];if(wr&&(!wr.layout||wr.property&&Object.prototype.hasOwnProperty.call(br,wr.property)))return wr}else for(const wr in this.registry){const Er=this.registry[wr];if(Er.property&&Object.prototype.hasOwnProperty.call(br,Er.property))return Er}throw new Error("unable to infer src variant")}decode(br,wr=0){let Er;const kr=this.discriminator,jr=kr.decode(br,wr),Br=this.registry[jr];if(Br===void 0){const qr=this.defaultLayout;let Wr=0;this.usesPrefixDiscriminator&&(Wr=kr.layout.span),Er=this.makeDestinationObject(),Er[kr.property]=jr,Er[qr.property]=qr.decode(br,wr+Wr)}else Er=Br.decode(br,wr);return Er}encode(br,wr,Er=0){const kr=this.getSourceVariant(br);if(kr===void 0){const jr=this.discriminator,Br=this.defaultLayout;let qr=0;return this.usesPrefixDiscriminator&&(qr=jr.layout.span),jr.encode(br[jr.property],wr,Er),qr+Br.encode(br[Br.property],wr,Er+qr)}return kr.encode(br,wr,Er)}addVariant(br,wr,Er){const kr=new VariantLayout(this,br,wr,Er);return this.registry[br]=kr,kr}getVariant(br,wr=0){let Er;return br instanceof Uint8Array?Er=this.discriminator.decode(br,wr):Er=br,this.registry[Er]}}Layout$1.Union=Union;class VariantLayout extends Layout{constructor(br,wr,Er,kr){if(!(br instanceof Union))throw new TypeError("union must be a Union");if(!Number.isInteger(wr)||0>wr)throw new TypeError("variant must be a (non-negative) integer");if(typeof Er=="string"&&kr===void 0&&(kr=Er,Er=null),Er){if(!(Er instanceof Layout))throw new TypeError("layout must be a Layout");if(br.defaultLayout!==null&&0<=Er.span&&Er.span>br.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if(typeof kr!="string")throw new TypeError("variant must have a String property")}let jr=br.span;0>br.span&&(jr=Er?Er.span:0,0<=jr&&br.usesPrefixDiscriminator&&(jr+=br.discriminator.layout.span)),super(jr,kr),this.union=br,this.variant=wr,this.layout=Er||null}getSpan(br,wr=0){if(0<=this.span)return this.span;let Er=0;this.union.usesPrefixDiscriminator&&(Er=this.union.discriminator.layout.span);let kr=0;return this.layout&&(kr=this.layout.getSpan(br,wr+Er)),Er+kr}decode(br,wr=0){const Er=this.makeDestinationObject();if(this!==this.union.getVariant(br,wr))throw new Error("variant mismatch");let kr=0;return this.union.usesPrefixDiscriminator&&(kr=this.union.discriminator.layout.span),this.layout?Er[this.property]=this.layout.decode(br,wr+kr):this.property?Er[this.property]=!0:this.union.usesPrefixDiscriminator&&(Er[this.union.discriminator.property]=this.variant),Er}encode(br,wr,Er=0){let kr=0;if(this.union.usesPrefixDiscriminator&&(kr=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(br,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,wr,Er);let jr=kr;if(this.layout&&(this.layout.encode(br[this.property],wr,Er+kr),jr+=this.layout.getSpan(wr,Er+kr),0<=this.union.span&&jr>this.union.span))throw new Error("encoded variant overruns containing union");return jr}fromArray(br){if(this.layout)return this.layout.fromArray(br)}}Layout$1.VariantLayout=VariantLayout;function fixBitwiseResult(fr){return 0>fr&&(fr+=4294967296),fr}class BitStructure extends Layout{constructor(br,wr,Er){if(!(br instanceof UInt||br instanceof UIntBE))throw new TypeError("word must be a UInt or UIntBE layout");if(typeof wr=="string"&&Er===void 0&&(Er=wr,wr=!1),4=wr)throw new TypeError("bits must be positive integer");const kr=8*br.span,jr=br.fields.reduce((Br,qr)=>Br+qr.bits,0);if(wr+jr>kr)throw new Error("bits too long for span remainder ("+(kr-jr)+" of "+kr+" remain)");this.container=br,this.bits=wr,this.valueMask=(1<>>this.start}encode(br){if(typeof br!="number"||!Number.isInteger(br)||br!==fixBitwiseResult(br&this.valueMask))throw new TypeError(nameWithProperty("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const wr=this.container._packedGetValue(),Er=fixBitwiseResult(br<Er&&(Er=this.length.decode(br,wr)),Er}decode(br,wr=0){let Er=this.span;return 0>Er&&(Er=this.length.decode(br,wr)),uint8ArrayToBuffer(br).slice(wr,wr+Er)}encode(br,wr,Er){let kr=this.length;if(this.length instanceof ExternalLayout&&(kr=br.length),!(br instanceof Uint8Array&&kr===br.length))throw new TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+kr+") Uint8Array as src");if(Er+kr>wr.length)throw new RangeError("encoding overruns Uint8Array");const jr=uint8ArrayToBuffer(br);return uint8ArrayToBuffer(wr).write(jr.toString("hex"),Er,kr,"hex"),this.length instanceof ExternalLayout&&this.length.encode(kr,wr,Er),kr}};Layout$1.Blob=Blob$1;class CString extends Layout{constructor(br){super(-1,br)}getSpan(br,wr=0){checkUint8Array(br);let Er=wr;for(;Erwr.length)throw new RangeError("encoding overruns Buffer");const Br=uint8ArrayToBuffer(wr);return kr.copy(Br,Er),Br[Er+jr]=0,jr+1}}Layout$1.CString=CString;class UTF8 extends Layout{constructor(br,wr){if(typeof br=="string"&&wr===void 0&&(wr=br,br=void 0),br===void 0)br=-1;else if(!Number.isInteger(br))throw new TypeError("maxSpan must be an integer");super(-1,wr),this.maxSpan=br}getSpan(br,wr=0){return checkUint8Array(br),br.length-wr}decode(br,wr=0){const Er=this.getSpan(br,wr);if(0<=this.maxSpan&&this.maxSpanwr.length)throw new RangeError("encoding overruns Buffer");return kr.copy(uint8ArrayToBuffer(wr),Er),jr}}Layout$1.UTF8=UTF8;class Constant extends Layout{constructor(br,wr){super(0,wr),this.value=br}decode(br,wr){return this.value}encode(br,wr,Er){return 0}}Layout$1.Constant=Constant;Layout$1.greedy=(fr,br)=>new GreedyCount(fr,br);var offset=Layout$1.offset=(fr,br,wr)=>new OffsetLayout(fr,br,wr),u8=Layout$1.u8=fr=>new UInt(1,fr),u16=Layout$1.u16=fr=>new UInt(2,fr);Layout$1.u24=fr=>new UInt(3,fr);var u32=Layout$1.u32=fr=>new UInt(4,fr);Layout$1.u40=fr=>new UInt(5,fr);Layout$1.u48=fr=>new UInt(6,fr);var nu64=Layout$1.nu64=fr=>new NearUInt64(fr);Layout$1.u16be=fr=>new UIntBE(2,fr);Layout$1.u24be=fr=>new UIntBE(3,fr);Layout$1.u32be=fr=>new UIntBE(4,fr);Layout$1.u40be=fr=>new UIntBE(5,fr);Layout$1.u48be=fr=>new UIntBE(6,fr);Layout$1.nu64be=fr=>new NearUInt64BE(fr);Layout$1.s8=fr=>new Int(1,fr);Layout$1.s16=fr=>new Int(2,fr);Layout$1.s24=fr=>new Int(3,fr);Layout$1.s32=fr=>new Int(4,fr);Layout$1.s40=fr=>new Int(5,fr);Layout$1.s48=fr=>new Int(6,fr);var ns64=Layout$1.ns64=fr=>new NearInt64(fr);Layout$1.s16be=fr=>new IntBE(2,fr);Layout$1.s24be=fr=>new IntBE(3,fr);Layout$1.s32be=fr=>new IntBE(4,fr);Layout$1.s40be=fr=>new IntBE(5,fr);Layout$1.s48be=fr=>new IntBE(6,fr);Layout$1.ns64be=fr=>new NearInt64BE(fr);Layout$1.f32=fr=>new Float(fr);Layout$1.f32be=fr=>new FloatBE(fr);Layout$1.f64=fr=>new Double(fr);Layout$1.f64be=fr=>new DoubleBE(fr);var struct=Layout$1.struct=(fr,br,wr)=>new Structure(fr,br,wr);Layout$1.bits=(fr,br,wr)=>new BitStructure(fr,br,wr);var seq=Layout$1.seq=(fr,br,wr)=>new Sequence(fr,br,wr);Layout$1.union=(fr,br,wr)=>new Union(fr,br,wr);Layout$1.unionLayoutDiscriminator=(fr,br)=>new UnionLayoutDiscriminator(fr,br);var blob=Layout$1.blob=(fr,br)=>new Blob$1(fr,br);Layout$1.cstr=fr=>new CString(fr);Layout$1.utf8=(fr,br)=>new UTF8(fr,br);Layout$1.constant=(fr,br)=>new Constant(fr,br);var browser$1={};Object.defineProperty(browser$1,"__esModule",{value:!0});function toBigIntLE(fr){{const br=Buffer$2.from(fr);br.reverse();const wr=br.toString("hex");return wr.length===0?BigInt(0):BigInt(`0x${wr}`)}}var toBigIntLE_1=browser$1.toBigIntLE=toBigIntLE;function toBigIntBE(fr){{const br=fr.toString("hex");return br.length===0?BigInt(0):BigInt(`0x${br}`)}}browser$1.toBigIntBE=toBigIntBE;function toBufferLE(fr,br){{const wr=fr.toString(16),Er=Buffer$2.from(wr.padStart(br*2,"0").slice(0,br*2),"hex");return Er.reverse(),Er}}var toBufferLE_1=browser$1.toBufferLE=toBufferLE;function toBufferBE(fr,br){{const wr=fr.toString(16);return Buffer$2.from(wr.padStart(br*2,"0").slice(0,br*2),"hex")}}browser$1.toBufferBE=toBufferBE;let StructError$2=class extends TypeError{constructor(br,wr){let Er;const{message:kr,explanation:jr,...Br}=br,{path:qr}=br,Wr=qr.length===0?kr:`At path: ${qr.join(".")} -- ${kr}`;super(jr??Wr),jr!=null&&(this.cause=Wr),Object.assign(this,Br),this.name=this.constructor.name,this.failures=()=>Er??(Er=[br,...wr()])}};function isIterable$2(fr){return isObject$2(fr)&&typeof fr[Symbol.iterator]=="function"}function isObject$2(fr){return typeof fr=="object"&&fr!=null}function print$2(fr){return typeof fr=="symbol"?fr.toString():typeof fr=="string"?JSON.stringify(fr):`${fr}`}function shiftIterator$2(fr){const{done:br,value:wr}=fr.next();return br?void 0:wr}function toFailure$2(fr,br,wr,Er){if(fr===!0)return;fr===!1?fr={}:typeof fr=="string"&&(fr={message:fr});const{path:kr,branch:jr}=br,{type:Br}=wr,{refinement:qr,message:Wr=`Expected a value of type \`${Br}\`${qr?` with refinement \`${qr}\``:""}, but received: \`${print$2(Er)}\``}=fr;return{value:Er,type:Br,refinement:qr,key:kr[kr.length-1],path:kr,branch:jr,...fr,message:Wr}}function*toFailures$2(fr,br,wr,Er){isIterable$2(fr)||(fr=[fr]);for(const kr of fr){const jr=toFailure$2(kr,br,wr,Er);jr&&(yield jr)}}function*run$2(fr,br,wr={}){const{path:Er=[],branch:kr=[fr],coerce:jr=!1,mask:Br=!1}=wr,qr={path:Er,branch:kr};if(jr&&(fr=br.coercer(fr,qr),Br&&br.type!=="type"&&isObject$2(br.schema)&&isObject$2(fr)&&!Array.isArray(fr)))for(const Vr in fr)br.schema[Vr]===void 0&&delete fr[Vr];let Wr="valid";for(const Vr of br.validator(fr,qr))Vr.explanation=wr.message,Wr="not_valid",yield[Vr,void 0];for(let[Vr,Hr,Zr]of br.entries(fr,qr)){const Jr=run$2(Hr,Zr,{path:Vr===void 0?Er:[...Er,Vr],branch:Vr===void 0?kr:[...kr,Hr],coerce:jr,mask:Br,message:wr.message});for(const Xr of Jr)Xr[0]?(Wr=Xr[0].refinement!=null?"not_refined":"not_valid",yield[Xr[0],void 0]):jr&&(Hr=Xr[1],Vr===void 0?fr=Hr:fr instanceof Map?fr.set(Vr,Hr):fr instanceof Set?fr.add(Hr):isObject$2(fr)&&(Hr!==void 0||Vr in fr)&&(fr[Vr]=Hr))}if(Wr!=="not_valid")for(const Vr of br.refiner(fr,qr))Vr.explanation=wr.message,Wr="not_refined",yield[Vr,void 0];Wr==="valid"&&(yield[void 0,fr])}let Struct$5=class{constructor(br){const{type:wr,schema:Er,validator:kr,refiner:jr,coercer:Br=Wr=>Wr,entries:qr=function*(){}}=br;this.type=wr,this.schema=Er,this.entries=qr,this.coercer=Br,kr?this.validator=(Wr,Vr)=>{const Hr=kr(Wr,Vr);return toFailures$2(Hr,Vr,this,Wr)}:this.validator=()=>[],jr?this.refiner=(Wr,Vr)=>{const Hr=jr(Wr,Vr);return toFailures$2(Hr,Vr,this,Wr)}:this.refiner=()=>[]}assert(br,wr){return assert$3(br,this,wr)}create(br,wr){return create$2(br,this,wr)}is(br){return is$2(br,this)}mask(br,wr){return mask$2(br,this,wr)}validate(br,wr={}){return validate$3(br,this,wr)}};function assert$3(fr,br,wr){const Er=validate$3(fr,br,{message:wr});if(Er[0])throw Er[0]}function create$2(fr,br,wr){const Er=validate$3(fr,br,{coerce:!0,message:wr});if(Er[0])throw Er[0];return Er[1]}function mask$2(fr,br,wr){const Er=validate$3(fr,br,{coerce:!0,mask:!0,message:wr});if(Er[0])throw Er[0];return Er[1]}function is$2(fr,br){return!validate$3(fr,br)[0]}function validate$3(fr,br,wr={}){const Er=run$2(fr,br,wr),kr=shiftIterator$2(Er);return kr[0]?[new StructError$2(kr[0],function*(){for(const Br of Er)Br[0]&&(yield Br[0])}),void 0]:[void 0,kr[1]]}function define$2(fr,br){return new Struct$5({type:fr,schema:null,validator:br})}function any$2(){return define$2("any",()=>!0)}function array$2(fr){return new Struct$5({type:"array",schema:fr,*entries(br){if(fr&&Array.isArray(br))for(const[wr,Er]of br.entries())yield[wr,Er,fr]},coercer(br){return Array.isArray(br)?br.slice():br},validator(br){return Array.isArray(br)||`Expected an array value, but received: ${print$2(br)}`}})}function boolean$2(){return define$2("boolean",fr=>typeof fr=="boolean")}function instance$2(fr){return define$2("instance",br=>br instanceof fr||`Expected a \`${fr.name}\` instance, but received: ${print$2(br)}`)}function literal$2(fr){const br=print$2(fr),wr=typeof fr;return new Struct$5({type:"literal",schema:wr==="string"||wr==="number"||wr==="boolean"?fr:null,validator(Er){return Er===fr||`Expected the literal \`${br}\`, but received: ${print$2(Er)}`}})}function never$2(){return define$2("never",()=>!1)}function nullable$2(fr){return new Struct$5({...fr,validator:(br,wr)=>br===null||fr.validator(br,wr),refiner:(br,wr)=>br===null||fr.refiner(br,wr)})}function number$2(){return define$2("number",fr=>typeof fr=="number"&&!isNaN(fr)||`Expected a number, but received: ${print$2(fr)}`)}function optional$2(fr){return new Struct$5({...fr,validator:(br,wr)=>br===void 0||fr.validator(br,wr),refiner:(br,wr)=>br===void 0||fr.refiner(br,wr)})}function record$2(fr,br){return new Struct$5({type:"record",schema:null,*entries(wr){if(isObject$2(wr))for(const Er in wr){const kr=wr[Er];yield[Er,Er,fr],yield[Er,kr,br]}},validator(wr){return isObject$2(wr)||`Expected an object, but received: ${print$2(wr)}`}})}function string$2(){return define$2("string",fr=>typeof fr=="string"||`Expected a string, but received: ${print$2(fr)}`)}function tuple$2(fr){const br=never$2();return new Struct$5({type:"tuple",schema:null,*entries(wr){if(Array.isArray(wr)){const Er=Math.max(fr.length,wr.length);for(let kr=0;krwr.type).join(" | ");return new Struct$5({type:"union",schema:null,coercer(wr){for(const Er of fr){const[kr,jr]=Er.validate(wr,{coerce:!0});if(!kr)return jr}return wr},validator(wr,Er){const kr=[];for(const jr of fr){const[...Br]=run$2(wr,jr,Er),[qr]=Br;if(qr[0])for(const[Wr]of Br)Wr&&kr.push(Wr);else return[]}return[`Expected the value to satisfy a union of \`${br}\`, but received: ${print$2(wr)}`,...kr]}})}function unknown$2(){return define$2("unknown",()=>!0)}function coerce$2(fr,br,wr){return new Struct$5({...fr,coercer:(Er,kr)=>is$2(Er,br)?fr.coercer(wr(Er,kr),kr):fr.coercer(Er,kr)})}var getRandomValues,rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate$2(fr){return typeof fr=="string"&®EX.test(fr)}var byteToHex=[];for(var i=0;i<256;++i)byteToHex.push((i+256).toString(16).substr(1));function stringify$1(fr){var br=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,wr=(byteToHex[fr[br+0]]+byteToHex[fr[br+1]]+byteToHex[fr[br+2]]+byteToHex[fr[br+3]]+"-"+byteToHex[fr[br+4]]+byteToHex[fr[br+5]]+"-"+byteToHex[fr[br+6]]+byteToHex[fr[br+7]]+"-"+byteToHex[fr[br+8]]+byteToHex[fr[br+9]]+"-"+byteToHex[fr[br+10]]+byteToHex[fr[br+11]]+byteToHex[fr[br+12]]+byteToHex[fr[br+13]]+byteToHex[fr[br+14]]+byteToHex[fr[br+15]]).toLowerCase();if(!validate$2(wr))throw TypeError("Stringified UUID is invalid");return wr}var _nodeId,_clockseq,_lastMSecs=0,_lastNSecs=0;function v1(fr,br,wr){var Er=br&&wr||0,kr=br||new Array(16);fr=fr||{};var jr=fr.node||_nodeId,Br=fr.clockseq!==void 0?fr.clockseq:_clockseq;if(jr==null||Br==null){var qr=fr.random||(fr.rng||rng)();jr==null&&(jr=_nodeId=[qr[0]|1,qr[1],qr[2],qr[3],qr[4],qr[5]]),Br==null&&(Br=_clockseq=(qr[6]<<8|qr[7])&16383)}var Wr=fr.msecs!==void 0?fr.msecs:Date.now(),Vr=fr.nsecs!==void 0?fr.nsecs:_lastNSecs+1,Hr=Wr-_lastMSecs+(Vr-_lastNSecs)/1e4;if(Hr<0&&fr.clockseq===void 0&&(Br=Br+1&16383),(Hr<0||Wr>_lastMSecs)&&fr.nsecs===void 0&&(Vr=0),Vr>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=Wr,_lastNSecs=Vr,_clockseq=Br,Wr+=122192928e5;var Zr=((Wr&268435455)*1e4+Vr)%4294967296;kr[Er++]=Zr>>>24&255,kr[Er++]=Zr>>>16&255,kr[Er++]=Zr>>>8&255,kr[Er++]=Zr&255;var Jr=Wr/4294967296*1e4&268435455;kr[Er++]=Jr>>>8&255,kr[Er++]=Jr&255,kr[Er++]=Jr>>>24&15|16,kr[Er++]=Jr>>>16&255,kr[Er++]=Br>>>8|128,kr[Er++]=Br&255;for(var Xr=0;Xr<6;++Xr)kr[Er+Xr]=jr[Xr];return br||stringify$1(kr)}function parse(fr){if(!validate$2(fr))throw TypeError("Invalid UUID");var br,wr=new Uint8Array(16);return wr[0]=(br=parseInt(fr.slice(0,8),16))>>>24,wr[1]=br>>>16&255,wr[2]=br>>>8&255,wr[3]=br&255,wr[4]=(br=parseInt(fr.slice(9,13),16))>>>8,wr[5]=br&255,wr[6]=(br=parseInt(fr.slice(14,18),16))>>>8,wr[7]=br&255,wr[8]=(br=parseInt(fr.slice(19,23),16))>>>8,wr[9]=br&255,wr[10]=(br=parseInt(fr.slice(24,36),16))/1099511627776&255,wr[11]=br/4294967296&255,wr[12]=br>>>24&255,wr[13]=br>>>16&255,wr[14]=br>>>8&255,wr[15]=br&255,wr}function stringToBytes(fr){fr=unescape(encodeURIComponent(fr));for(var br=[],wr=0;wr>5]>>>kr%32&255,Br=parseInt(Er.charAt(jr>>>4&15)+Er.charAt(jr&15),16);br.push(Br)}return br}function getOutputLength(fr){return(fr+64>>>9<<4)+14+1}function wordsToMd5(fr,br){fr[br>>5]|=128<>5]|=(fr[Er/8]&255)<>16)+(br>>16)+(wr>>16);return Er<<16|wr&65535}function bitRotateLeft(fr,br){return fr<>>32-br}function md5cmn(fr,br,wr,Er,kr,jr){return safeAdd(bitRotateLeft(safeAdd(safeAdd(br,fr),safeAdd(Er,jr)),kr),wr)}function md5ff(fr,br,wr,Er,kr,jr,Br){return md5cmn(br&wr|~br&Er,fr,br,kr,jr,Br)}function md5gg(fr,br,wr,Er,kr,jr,Br){return md5cmn(br&Er|wr&~Er,fr,br,kr,jr,Br)}function md5hh(fr,br,wr,Er,kr,jr,Br){return md5cmn(br^wr^Er,fr,br,kr,jr,Br)}function md5ii(fr,br,wr,Er,kr,jr,Br){return md5cmn(wr^(br|~Er),fr,br,kr,jr,Br)}var v3=v35("v3",48,md5);function v4(fr,br,wr){fr=fr||{};var Er=fr.random||(fr.rng||rng)();if(Er[6]=Er[6]&15|64,Er[8]=Er[8]&63|128,br){wr=wr||0;for(var kr=0;kr<16;++kr)br[wr+kr]=Er[kr];return br}return stringify$1(Er)}function f(fr,br,wr,Er){switch(fr){case 0:return br&wr^~br&Er;case 1:return br^wr^Er;case 2:return br&wr^br&Er^wr&Er;case 3:return br^wr^Er}}function ROTL(fr,br){return fr<>>32-br}function sha1(fr){var br=[1518500249,1859775393,2400959708,3395469782],wr=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof fr=="string"){var Er=unescape(encodeURIComponent(fr));fr=[];for(var kr=0;kr>>0;jn=In,In=Tn,Tn=ROTL($n,30)>>>0,$n=wn,wn=na}wr[0]=wr[0]+wn>>>0,wr[1]=wr[1]+$n>>>0,wr[2]=wr[2]+Tn>>>0,wr[3]=wr[3]+In>>>0,wr[4]=wr[4]+jn>>>0}return[wr[0]>>24&255,wr[0]>>16&255,wr[0]>>8&255,wr[0]&255,wr[1]>>24&255,wr[1]>>16&255,wr[1]>>8&255,wr[1]&255,wr[2]>>24&255,wr[2]>>16&255,wr[2]>>8&255,wr[2]&255,wr[3]>>24&255,wr[3]>>16&255,wr[3]>>8&255,wr[3]&255,wr[4]>>24&255,wr[4]>>16&255,wr[4]>>8&255,wr[4]&255]}var v5=v35("v5",80,sha1);const nil="00000000-0000-0000-0000-000000000000";function version$5(fr){if(!validate$2(fr))throw TypeError("Invalid UUID");return parseInt(fr.substr(14,1),16)}const esmBrowser=Object.freeze(Object.defineProperty({__proto__:null,NIL:nil,parse,stringify:stringify$1,v1,v3,v4,v5,validate:validate$2,version:version$5},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(esmBrowser),uuid$1=require$$0.v4,generateRequest$1=function(fr,br,wr,Er){if(typeof fr!="string")throw new TypeError(fr+" must be a string");Er=Er||{};const kr=typeof Er.version=="number"?Er.version:2;if(kr!==1&&kr!==2)throw new TypeError(kr+" must be 1 or 2");const jr={method:fr};if(kr===2&&(jr.jsonrpc="2.0"),br){if(typeof br!="object"&&!Array.isArray(br))throw new TypeError(br+" must be an object, array or omitted");jr.params=br}if(typeof wr>"u"){const Br=typeof Er.generator=="function"?Er.generator:function(){return uuid$1()};jr.id=Br(jr,Er)}else kr===2&&wr===null?Er.notificationIdNull&&(jr.id=null):jr.id=wr;return jr};var generateRequest_1=generateRequest$1;const uuid=require$$0.v4,generateRequest=generateRequest_1,ClientBrowser=function(fr,br){if(!(this instanceof ClientBrowser))return new ClientBrowser(fr,br);br||(br={}),this.options={reviver:typeof br.reviver<"u"?br.reviver:null,replacer:typeof br.replacer<"u"?br.replacer:null,generator:typeof br.generator<"u"?br.generator:function(){return uuid()},version:typeof br.version<"u"?br.version:2,notificationIdNull:typeof br.notificationIdNull=="boolean"?br.notificationIdNull:!1},this.callServer=fr};var browser=ClientBrowser;ClientBrowser.prototype.request=function(fr,br,wr,Er){const kr=this;let jr=null;const Br=Array.isArray(fr)&&typeof br=="function";if(this.options.version===1&&Br)throw new TypeError("JSON-RPC 1.0 does not support batching");if(Br||!Br&&fr&&typeof fr=="object"&&typeof br=="function")Er=br,jr=fr;else{typeof wr=="function"&&(Er=wr,wr=void 0);const Vr=typeof Er=="function";try{jr=generateRequest(fr,br,wr,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(Hr){if(Vr)return Er(Hr);throw Hr}if(!Vr)return jr}let Wr;try{Wr=JSON.stringify(jr,this.options.replacer)}catch(Vr){return Er(Vr)}return this.callServer(Wr,function(Vr,Hr){kr._parseResponse(Vr,Hr,Er)}),jr};ClientBrowser.prototype._parseResponse=function(fr,br,wr){if(fr){wr(fr);return}if(!br)return wr();let Er;try{Er=JSON.parse(br,this.options.reviver)}catch(kr){return wr(kr)}if(wr.length===3)if(Array.isArray(Er)){const kr=function(Br){return typeof Br.error<"u"},jr=function(Br){return!kr(Br)};return wr(null,Er.filter(kr),Er.filter(jr))}else return wr(null,Er.error,Er.result);wr(null,Er)};const RpcClient=getDefaultExportFromCjs$2(browser);var client={},eventemitter3={exports:{}};(function(fr){var br=Object.prototype.hasOwnProperty,wr="~";function Er(){}Object.create&&(Er.prototype=Object.create(null),new Er().__proto__||(wr=!1));function kr(Wr,Vr,Hr){this.fn=Wr,this.context=Vr,this.once=Hr||!1}function jr(Wr,Vr,Hr,Zr,Jr){if(typeof Hr!="function")throw new TypeError("The listener must be a function");var Xr=new kr(Hr,Zr||Wr,Jr),En=wr?wr+Vr:Vr;return Wr._events[En]?Wr._events[En].fn?Wr._events[En]=[Wr._events[En],Xr]:Wr._events[En].push(Xr):(Wr._events[En]=Xr,Wr._eventsCount++),Wr}function Br(Wr,Vr){--Wr._eventsCount===0?Wr._events=new Er:delete Wr._events[Vr]}function qr(){this._events=new Er,this._eventsCount=0}qr.prototype.eventNames=function(){var Vr=[],Hr,Zr;if(this._eventsCount===0)return Vr;for(Zr in Hr=this._events)br.call(Hr,Zr)&&Vr.push(wr?Zr.slice(1):Zr);return Object.getOwnPropertySymbols?Vr.concat(Object.getOwnPropertySymbols(Hr)):Vr},qr.prototype.listeners=function(Vr){var Hr=wr?wr+Vr:Vr,Zr=this._events[Hr];if(!Zr)return[];if(Zr.fn)return[Zr.fn];for(var Jr=0,Xr=Zr.length,En=new Array(Xr);Jr++this.rpc_id),Hr?this.dataPack=Hr:this.dataPack=new utils_cjs_1.DefaultDataPack,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(wr,Er,kr,jr){return!jr&&typeof kr=="object"&&(jr=kr,kr=null),new Promise((Br,qr)=>{if(!this.ready)return qr(new Error("socket not ready"));const Wr=this.generate_request_id(wr,Er),Vr={jsonrpc:"2.0",method:wr,params:Er||void 0,id:Wr};this.socket.send(this.dataPack.encode(Vr),jr,Hr=>{if(Hr)return qr(Hr);this.queue[Wr]={promise:[Br,qr]},kr&&(this.queue[Wr].timeout=setTimeout(()=>{delete this.queue[Wr],qr(new Error("reply timeout"))},kr))})})}async login(wr){const Er=await this.call("rpc.login",wr);if(!Er)throw new Error("authentication failed");return Er}async listMethods(){return await this.call("__listMethods")}notify(wr,Er){return new Promise((kr,jr)=>{if(!this.ready)return jr(new Error("socket not ready"));const Br={jsonrpc:"2.0",method:wr,params:Er};this.socket.send(this.dataPack.encode(Br),qr=>{if(qr)return jr(qr);kr()})})}async subscribe(wr){typeof wr=="string"&&(wr=[wr]);const Er=await this.call("rpc.on",wr);if(typeof wr=="string"&&Er[wr]!=="ok")throw new Error("Failed subscribing to an event '"+wr+"' with: "+Er[wr]);return Er}async unsubscribe(wr){typeof wr=="string"&&(wr=[wr]);const Er=await this.call("rpc.off",wr);if(typeof wr=="string"&&Er[wr]!=="ok")throw new Error("Failed unsubscribing from an event with: "+Er);return Er}close(wr,Er){this.socket.close(wr||1e3,Er)}setAutoReconnect(wr){this.reconnect=wr}setReconnectInterval(wr){this.reconnect_interval=wr}setMaxReconnects(wr){this.max_reconnects=wr}_connect(wr,Er){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(wr,Er),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:kr})=>{kr instanceof ArrayBuffer&&(kr=Buffer$2.from(kr).toString());try{kr=this.dataPack.decode(kr)}catch{return}if(kr.notification&&this.listeners(kr.notification).length){if(!Object.keys(kr.params).length)return this.emit(kr.notification);const jr=[kr.notification];if(kr.params.constructor===Object)jr.push(kr.params);else for(let Br=0;Br{this.emit.apply(this,jr)})}if(!this.queue[kr.id])return kr.method?Promise.resolve().then(()=>{this.emit(kr.method,kr==null?void 0:kr.params)}):void 0;"error"in kr=="result"in kr&&this.queue[kr.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[kr.id].timeout&&clearTimeout(this.queue[kr.id].timeout),kr.error?this.queue[kr.id].promise[1](kr.error):this.queue[kr.id].promise[0](kr.result),delete this.queue[kr.id]}),this.socket.addEventListener("error",kr=>this.emit("error",kr)),this.socket.addEventListener("close",({code:kr,reason:jr})=>{this.ready&&setTimeout(()=>this.emit("close",kr,jr),0),this.ready=!1,this.socket=void 0,kr!==1e3&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||this.max_reconnects===0)&&(this.reconnect_timer_id=setTimeout(()=>this._connect(wr,Er),this.reconnect_interval)))})}}var _default$1=client.default=CommonClient,websocket_browser={};Object.defineProperty(websocket_browser,"__esModule",{value:!0});const eventemitter3_1=eventemitter3Exports;class WebSocketBrowserImpl extends eventemitter3_1.EventEmitter{constructor(wr,Er,kr){super();_f(this,"socket");this.socket=new window.WebSocket(wr,kr),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=jr=>this.emit("message",jr.data),this.socket.onerror=jr=>this.emit("error",jr),this.socket.onclose=jr=>{this.emit("close",jr.code,jr.reason)}}send(wr,Er,kr){const jr=kr||Er;try{this.socket.send(wr),jr()}catch(Br){jr(Br)}}close(wr,Er){this.socket.close(wr,Er)}addEventListener(wr,Er,kr){this.socket.addEventListener(wr,Er,kr)}}function default_1(fr,br){return new WebSocketBrowserImpl(fr,br)}var _default=websocket_browser.default=default_1;function isOnCurve$2(fr){try{return ed25519.ExtendedPoint.fromHex(fr),!0}catch{return!1}}const sign=(fr,br)=>ed25519.sign(fr,br.slice(0,32)),verify=ed25519.verify,toBuffer$2=fr=>Buffer$1$1.isBuffer(fr)?fr:fr instanceof Uint8Array?Buffer$1$1.from(fr.buffer,fr.byteOffset,fr.byteLength):Buffer$1$1.from(fr);let Struct$4=class{constructor(br){Object.assign(this,br)}encode(){return Buffer$1$1.from(serialize_1(SOLANA_SCHEMA$2,this))}static decode(br){return deserialize_1(SOLANA_SCHEMA$2,this,br)}static decodeUnchecked(br){return deserializeUnchecked_1(SOLANA_SCHEMA$2,this,br)}};const SOLANA_SCHEMA$2=new Map;var _PublicKey$2;const MAX_SEED_LENGTH$2=32,PUBLIC_KEY_LENGTH$2=32;function isPublicKeyData$2(fr){return fr._bn!==void 0}let uniquePublicKeyCounter$2=1,PublicKey$2=class Cv extends Struct$4{constructor(br){if(super({}),this._bn=void 0,isPublicKeyData$2(br))this._bn=br._bn;else{if(typeof br=="string"){const wr=bs58$6.decode(br);if(wr.length!=PUBLIC_KEY_LENGTH$2)throw new Error("Invalid public key input");this._bn=new BN$2(wr)}else this._bn=new BN$2(br);if(this._bn.byteLength()>PUBLIC_KEY_LENGTH$2)throw new Error("Invalid public key input")}}static unique(){const br=new Cv(uniquePublicKeyCounter$2);return uniquePublicKeyCounter$2+=1,new Cv(br.toBuffer())}equals(br){return this._bn.eq(br._bn)}toBase58(){return bs58$6.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const br=this.toBuffer();return new Uint8Array(br.buffer,br.byteOffset,br.byteLength)}toBuffer(){const br=this._bn.toArrayLike(Buffer$1$1);if(br.length===PUBLIC_KEY_LENGTH$2)return br;const wr=Buffer$1$1.alloc(32);return br.copy(wr,32-br.length),wr}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(br,wr,Er){const kr=Buffer$1$1.concat([br.toBuffer(),Buffer$1$1.from(wr),Er.toBuffer()]),jr=sha256$4(kr);return new Cv(jr)}static createProgramAddressSync(br,wr){let Er=Buffer$1$1.alloc(0);br.forEach(function(jr){if(jr.length>MAX_SEED_LENGTH$2)throw new TypeError("Max seed length exceeded");Er=Buffer$1$1.concat([Er,toBuffer$2(jr)])}),Er=Buffer$1$1.concat([Er,wr.toBuffer(),Buffer$1$1.from("ProgramDerivedAddress")]);const kr=sha256$4(Er);if(isOnCurve$2(kr))throw new Error("Invalid seeds, address must fall off the curve");return new Cv(kr)}static async createProgramAddress(br,wr){return this.createProgramAddressSync(br,wr)}static findProgramAddressSync(br,wr){let Er=255,kr;for(;Er!=0;){try{const jr=br.concat(Buffer$1$1.from([Er]));kr=this.createProgramAddressSync(jr,wr)}catch(jr){if(jr instanceof TypeError)throw jr;Er--;continue}return[kr,Er]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(br,wr){return this.findProgramAddressSync(br,wr)}static isOnCurve(br){const wr=new Cv(br);return isOnCurve$2(wr.toBytes())}};_PublicKey$2=PublicKey$2;PublicKey$2.default=new _PublicKey$2("11111111111111111111111111111111");SOLANA_SCHEMA$2.set(PublicKey$2,{kind:"struct",fields:[["_bn","u256"]]});new PublicKey$2("BPFLoader1111111111111111111111111111111111");const PACKET_DATA_SIZE=1232,VERSION_PREFIX_MASK=127,SIGNATURE_LENGTH_IN_BYTES$2=64;class TransactionExpiredBlockheightExceededError extends Error{constructor(br){super(`Signature ${br} has expired: block height exceeded.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(br,wr){super(`Transaction was not confirmed in ${wr.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${br} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});class TransactionExpiredNonceInvalidError extends Error{constructor(br){super(`Signature ${br} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=br}}Object.defineProperty(TransactionExpiredNonceInvalidError.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MessageAccountKeys{constructor(br,wr){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=br,this.accountKeysFromLookups=wr}keySegments(){const br=[this.staticAccountKeys];return this.accountKeysFromLookups&&(br.push(this.accountKeysFromLookups.writable),br.push(this.accountKeysFromLookups.readonly)),br}get(br){for(const wr of this.keySegments()){if(br256)throw new Error("Account index overflow encountered during compilation");const Er=new Map;this.keySegments().flat().forEach((jr,Br)=>{Er.set(jr.toBase58(),Br)});const kr=jr=>{const Br=Er.get(jr.toBase58());if(Br===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return Br};return br.map(jr=>({programIdIndex:kr(jr.programId),accountKeyIndexes:jr.keys.map(Br=>kr(Br.pubkey)),data:jr.data}))}}const publicKey$3=(fr="publicKey")=>blob(32,fr),signature=(fr="signature")=>blob(64,fr),rustString$2=(fr="string")=>{const br=struct([u32("length"),u32("lengthPadding"),blob(offset(u32(),-8),"chars")],fr),wr=br.decode.bind(br),Er=br.encode.bind(br),kr=br;return kr.decode=(jr,Br)=>wr(jr,Br).chars.toString(),kr.encode=(jr,Br,qr)=>{const Wr={chars:Buffer$1$1.from(jr,"utf8")};return Er(Wr,Br,qr)},kr.alloc=jr=>u32().span+u32().span+Buffer$1$1.from(jr,"utf8").length,kr},authorized$2=(fr="authorized")=>struct([publicKey$3("staker"),publicKey$3("withdrawer")],fr),lockup$2=(fr="lockup")=>struct([ns64("unixTimestamp"),ns64("epoch"),publicKey$3("custodian")],fr),voteInit$2=(fr="voteInit")=>struct([publicKey$3("nodePubkey"),publicKey$3("authorizedVoter"),publicKey$3("authorizedWithdrawer"),u8("commission")],fr),voteAuthorizeWithSeedArgs$2=(fr="voteAuthorizeWithSeedArgs")=>struct([u32("voteAuthorizationType"),publicKey$3("currentAuthorityDerivedKeyOwnerPubkey"),rustString$2("currentAuthorityDerivedKeySeed"),publicKey$3("newAuthorized")],fr);function getAlloc(fr,br){const wr=kr=>{if(kr.span>=0)return kr.span;if(typeof kr.alloc=="function")return kr.alloc(br[kr.property]);if("count"in kr&&"elementLayout"in kr){const jr=br[kr.property];if(Array.isArray(jr))return jr.length*wr(kr.elementLayout)}else if("fields"in kr)return getAlloc({layout:kr},br[kr.property]);return 0};let Er=0;return fr.layout.fields.forEach(kr=>{Er+=wr(kr)}),Er}function decodeLength(fr){let br=0,wr=0;for(;;){let Er=fr.shift();if(br|=(Er&127)<>=7,wr==0){fr.push(Er);break}else Er|=128,fr.push(Er)}}function assert$2(fr,br){if(!fr)throw new Error(br||"Assertion failed")}class CompiledKeys{constructor(br,wr){this.payer=void 0,this.keyMetaMap=void 0,this.payer=br,this.keyMetaMap=wr}static compile(br,wr){const Er=new Map,kr=Br=>{const qr=Br.toBase58();let Wr=Er.get(qr);return Wr===void 0&&(Wr={isSigner:!1,isWritable:!1,isInvoked:!1},Er.set(qr,Wr)),Wr},jr=kr(wr);jr.isSigner=!0,jr.isWritable=!0;for(const Br of br){kr(Br.programId).isInvoked=!0;for(const qr of Br.keys){const Wr=kr(qr.pubkey);Wr.isSigner||(Wr.isSigner=qr.isSigner),Wr.isWritable||(Wr.isWritable=qr.isWritable)}}return new CompiledKeys(wr,Er)}getMessageComponents(){const br=[...this.keyMetaMap.entries()];assert$2(br.length<=256,"Max static account keys length exceeded");const wr=br.filter(([,Wr])=>Wr.isSigner&&Wr.isWritable),Er=br.filter(([,Wr])=>Wr.isSigner&&!Wr.isWritable),kr=br.filter(([,Wr])=>!Wr.isSigner&&Wr.isWritable),jr=br.filter(([,Wr])=>!Wr.isSigner&&!Wr.isWritable),Br={numRequiredSignatures:wr.length+Er.length,numReadonlySignedAccounts:Er.length,numReadonlyUnsignedAccounts:jr.length};{assert$2(wr.length>0,"Expected at least one writable signer key");const[Wr]=wr[0];assert$2(Wr===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const qr=[...wr.map(([Wr])=>new PublicKey$2(Wr)),...Er.map(([Wr])=>new PublicKey$2(Wr)),...kr.map(([Wr])=>new PublicKey$2(Wr)),...jr.map(([Wr])=>new PublicKey$2(Wr))];return[Br,qr]}extractTableLookup(br){const[wr,Er]=this.drainKeysFoundInLookupTable(br.state.addresses,Br=>!Br.isSigner&&!Br.isInvoked&&Br.isWritable),[kr,jr]=this.drainKeysFoundInLookupTable(br.state.addresses,Br=>!Br.isSigner&&!Br.isInvoked&&!Br.isWritable);if(!(wr.length===0&&kr.length===0))return[{accountKey:br.key,writableIndexes:wr,readonlyIndexes:kr},{writable:Er,readonly:jr}]}drainKeysFoundInLookupTable(br,wr){const Er=new Array,kr=new Array;for(const[jr,Br]of this.keyMetaMap.entries())if(wr(Br)){const qr=new PublicKey$2(jr),Wr=br.findIndex(Vr=>Vr.equals(qr));Wr>=0&&(assert$2(Wr<256,"Max lookup table index exceeded"),Er.push(Wr),kr.push(qr),this.keyMetaMap.delete(jr))}return[Er,kr]}}const END_OF_BUFFER_ERROR_MESSAGE="Reached end of buffer unexpectedly";function guardedShift(fr){if(fr.length===0)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return fr.shift()}function guardedSplice(fr,...br){const[wr]=br;if(br.length===2?wr+(br[1]??0)>fr.length:wr>=fr.length)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return fr.splice(...br)}class Message{constructor(br){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=br.header,this.accountKeys=br.accountKeys.map(wr=>new PublicKey$2(wr)),this.recentBlockhash=br.recentBlockhash,this.instructions=br.instructions,this.instructions.forEach(wr=>this.indexToProgramIds.set(wr.programIdIndex,this.accountKeys[wr.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(br=>({programIdIndex:br.programIdIndex,accountKeyIndexes:br.accounts,data:bs58$6.decode(br.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new MessageAccountKeys(this.staticAccountKeys)}static compile(br){const wr=CompiledKeys.compile(br.instructions,br.payerKey),[Er,kr]=wr.getMessageComponents(),Br=new MessageAccountKeys(kr).compileInstructions(br.instructions).map(qr=>({programIdIndex:qr.programIdIndex,accounts:qr.accountKeyIndexes,data:bs58$6.encode(qr.data)}));return new Message({header:Er,accountKeys:kr,recentBlockhash:br.recentBlockhash,instructions:Br})}isAccountSigner(br){return br=this.header.numRequiredSignatures){const Er=br-wr,jr=this.accountKeys.length-wr-this.header.numReadonlyUnsignedAccounts;return Er!this.isProgramId(wr))}serialize(){const br=this.accountKeys.length;let wr=[];encodeLength(wr,br);const Er=this.instructions.map(Zr=>{const{accounts:Jr,programIdIndex:Xr}=Zr,En=Array.from(bs58$6.decode(Zr.data));let wn=[];encodeLength(wn,Jr.length);let $n=[];return encodeLength($n,En.length),{programIdIndex:Xr,keyIndicesCount:Buffer$1$1.from(wn),keyIndices:Jr,dataLength:Buffer$1$1.from($n),data:En}});let kr=[];encodeLength(kr,Er.length);let jr=Buffer$1$1.alloc(PACKET_DATA_SIZE);Buffer$1$1.from(kr).copy(jr);let Br=kr.length;Er.forEach(Zr=>{const Xr=struct([u8("programIdIndex"),blob(Zr.keyIndicesCount.length,"keyIndicesCount"),seq(u8("keyIndex"),Zr.keyIndices.length,"keyIndices"),blob(Zr.dataLength.length,"dataLength"),seq(u8("userdatum"),Zr.data.length,"data")]).encode(Zr,jr,Br);Br+=Xr}),jr=jr.slice(0,Br);const qr=struct([blob(1,"numRequiredSignatures"),blob(1,"numReadonlySignedAccounts"),blob(1,"numReadonlyUnsignedAccounts"),blob(wr.length,"keyCount"),seq(publicKey$3("key"),br,"keys"),publicKey$3("recentBlockhash")]),Wr={numRequiredSignatures:Buffer$1$1.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Buffer$1$1.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Buffer$1$1.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Buffer$1$1.from(wr),keys:this.accountKeys.map(Zr=>toBuffer$2(Zr.toBytes())),recentBlockhash:bs58$6.decode(this.recentBlockhash)};let Vr=Buffer$1$1.alloc(2048);const Hr=qr.encode(Wr,Vr);return jr.copy(Vr,Hr),Vr.slice(0,Hr+jr.length)}static from(br){let wr=[...br];const Er=guardedShift(wr);if(Er!==(Er&VERSION_PREFIX_MASK))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const kr=guardedShift(wr),jr=guardedShift(wr),Br=decodeLength(wr);let qr=[];for(let Jr=0;Jr0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new MessageAccountKeys(this.staticAccountKeys,wr)}isAccountSigner(br){return br=Er){const kr=br-Er,jr=this.addressTableLookups.reduce((Br,qr)=>Br+qr.writableIndexes.length,0);return kr=this.header.numRequiredSignatures){const kr=br-wr,Br=Er-wr-this.header.numReadonlyUnsignedAccounts;return krjr.key.equals(Er.accountKey));if(!kr)throw new Error(`Failed to find address lookup table account for table key ${Er.accountKey.toBase58()}`);for(const jr of Er.writableIndexes)if(jrHr.toBytes()),recentBlockhash:bs58$6.decode(this.recentBlockhash),instructionsLength:new Uint8Array(Er),serializedInstructions:wr,addressTableLookupsLength:new Uint8Array(jr),serializedAddressTableLookups:kr},qr);return qr.slice(0,Vr)}serializeInstructions(){let br=0;const wr=new Uint8Array(PACKET_DATA_SIZE);for(const Er of this.compiledInstructions){const kr=Array();encodeLength(kr,Er.accountKeyIndexes.length);const jr=Array();encodeLength(jr,Er.data.length);const Br=struct([u8("programIdIndex"),blob(kr.length,"encodedAccountKeyIndexesLength"),seq(u8(),Er.accountKeyIndexes.length,"accountKeyIndexes"),blob(jr.length,"encodedDataLength"),blob(Er.data.length,"data")]);br+=Br.encode({programIdIndex:Er.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(kr),accountKeyIndexes:Er.accountKeyIndexes,encodedDataLength:new Uint8Array(jr),data:Er.data},wr,br)}return wr.slice(0,br)}serializeAddressTableLookups(){let br=0;const wr=new Uint8Array(PACKET_DATA_SIZE);for(const Er of this.addressTableLookups){const kr=Array();encodeLength(kr,Er.writableIndexes.length);const jr=Array();encodeLength(jr,Er.readonlyIndexes.length);const Br=struct([publicKey$3("accountKey"),blob(kr.length,"encodedWritableIndexesLength"),seq(u8(),Er.writableIndexes.length,"writableIndexes"),blob(jr.length,"encodedReadonlyIndexesLength"),seq(u8(),Er.readonlyIndexes.length,"readonlyIndexes")]);br+=Br.encode({accountKey:Er.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(kr),writableIndexes:Er.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(jr),readonlyIndexes:Er.readonlyIndexes},wr,br)}return wr.slice(0,br)}static deserialize(br){let wr=[...br];const Er=guardedShift(wr),kr=Er&VERSION_PREFIX_MASK;assert$2(Er!==kr,"Expected versioned message but received legacy message");const jr=kr;assert$2(jr===0,`Expected versioned message with version 0 but found version ${jr}`);const Br={numRequiredSignatures:guardedShift(wr),numReadonlySignedAccounts:guardedShift(wr),numReadonlyUnsignedAccounts:guardedShift(wr)},qr=[],Wr=decodeLength(wr);for(let En=0;En{const br=VersionedMessage.deserializeMessageVersion(fr);if(br==="legacy")return Message.from(fr);if(br===0)return MessageV0.deserialize(fr);throw new Error(`Transaction message version ${br} deserialization is not supported`)}};let TransactionStatus=function(fr){return fr[fr.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",fr[fr.PROCESSED=1]="PROCESSED",fr[fr.TIMED_OUT=2]="TIMED_OUT",fr[fr.NONCE_INVALID=3]="NONCE_INVALID",fr}({});const DEFAULT_SIGNATURE=Buffer$1$1.alloc(SIGNATURE_LENGTH_IN_BYTES$2).fill(0);class TransactionInstruction{constructor(br){this.keys=void 0,this.programId=void 0,this.data=Buffer$1$1.alloc(0),this.programId=br.programId,this.keys=br.keys,br.data&&(this.data=br.data)}toJSON(){return{keys:this.keys.map(({pubkey:br,isSigner:wr,isWritable:Er})=>({pubkey:br.toJSON(),isSigner:wr,isWritable:Er})),programId:this.programId.toJSON(),data:[...this.data]}}}class Transaction{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(br){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!!br)if(br.feePayer&&(this.feePayer=br.feePayer),br.signatures&&(this.signatures=br.signatures),Object.prototype.hasOwnProperty.call(br,"nonceInfo")){const{minContextSlot:wr,nonceInfo:Er}=br;this.minNonceContextSlot=wr,this.nonceInfo=Er}else if(Object.prototype.hasOwnProperty.call(br,"lastValidBlockHeight")){const{blockhash:wr,lastValidBlockHeight:Er}=br;this.recentBlockhash=wr,this.lastValidBlockHeight=Er}else{const{recentBlockhash:wr,nonceInfo:Er}=br;Er&&(this.nonceInfo=Er),this.recentBlockhash=wr}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(br=>br.toJSON()),signers:this.signatures.map(({publicKey:br})=>br.toJSON())}}add(...br){if(br.length===0)throw new Error("No instructions");return br.forEach(wr=>{"instructions"in wr?this.instructions=this.instructions.concat(wr.instructions):"data"in wr&&"programId"in wr&&"keys"in wr?this.instructions.push(wr):this.instructions.push(new TransactionInstruction(wr))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let br,wr;if(this.nonceInfo?(br=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?wr=[this.nonceInfo.nonceInstruction,...this.instructions]:wr=this.instructions):(br=this.recentBlockhash,wr=this.instructions),!br)throw new Error("Transaction recentBlockhash required");wr.length<1&&console.warn("No instructions provided");let Er;if(this.feePayer)Er=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)Er=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let wn=0;wn{wn.keys.forEach(Tn=>{jr.push({...Tn})});const $n=wn.programId.toString();kr.includes($n)||kr.push($n)}),kr.forEach(wn=>{jr.push({pubkey:new PublicKey$2(wn),isSigner:!1,isWritable:!1})});const Br=[];jr.forEach(wn=>{const $n=wn.pubkey.toString(),Tn=Br.findIndex(In=>In.pubkey.toString()===$n);Tn>-1?(Br[Tn].isWritable=Br[Tn].isWritable||wn.isWritable,Br[Tn].isSigner=Br[Tn].isSigner||wn.isSigner):Br.push(wn)}),Br.sort(function(wn,$n){if(wn.isSigner!==$n.isSigner)return wn.isSigner?-1:1;if(wn.isWritable!==$n.isWritable)return wn.isWritable?-1:1;const Tn={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return wn.pubkey.toBase58().localeCompare($n.pubkey.toBase58(),"en",Tn)});const qr=Br.findIndex(wn=>wn.pubkey.equals(Er));if(qr>-1){const[wn]=Br.splice(qr,1);wn.isSigner=!0,wn.isWritable=!0,Br.unshift(wn)}else Br.unshift({pubkey:Er,isSigner:!0,isWritable:!0});for(const wn of this.signatures){const $n=Br.findIndex(Tn=>Tn.pubkey.equals(wn.publicKey));if($n>-1)Br[$n].isSigner||(Br[$n].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw new Error(`unknown signer: ${wn.publicKey.toString()}`)}let Wr=0,Vr=0,Hr=0;const Zr=[],Jr=[];Br.forEach(({pubkey:wn,isSigner:$n,isWritable:Tn})=>{$n?(Zr.push(wn.toString()),Wr+=1,Tn||(Vr+=1)):(Jr.push(wn.toString()),Tn||(Hr+=1))});const Xr=Zr.concat(Jr),En=wr.map(wn=>{const{data:$n,programId:Tn}=wn;return{programIdIndex:Xr.indexOf(Tn.toString()),accounts:wn.keys.map(In=>Xr.indexOf(In.pubkey.toString())),data:bs58$6.encode($n)}});return En.forEach(wn=>{assert$2(wn.programIdIndex>=0),wn.accounts.forEach($n=>assert$2($n>=0))}),new Message({header:{numRequiredSignatures:Wr,numReadonlySignedAccounts:Vr,numReadonlyUnsignedAccounts:Hr},accountKeys:Xr,recentBlockhash:br,instructions:En})}_compile(){const br=this.compileMessage(),wr=br.accountKeys.slice(0,br.header.numRequiredSignatures);return this.signatures.length===wr.length&&this.signatures.every((kr,jr)=>wr[jr].equals(kr.publicKey))||(this.signatures=wr.map(Er=>({signature:null,publicKey:Er}))),br}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(br){return(await br.getFeeForMessage(this.compileMessage())).value}setSigners(...br){if(br.length===0)throw new Error("No signers");const wr=new Set;this.signatures=br.filter(Er=>{const kr=Er.toString();return wr.has(kr)?!1:(wr.add(kr),!0)}).map(Er=>({signature:null,publicKey:Er}))}sign(...br){if(br.length===0)throw new Error("No signers");const wr=new Set,Er=[];for(const jr of br){const Br=jr.publicKey.toString();wr.has(Br)||(wr.add(Br),Er.push(jr))}this.signatures=Er.map(jr=>({signature:null,publicKey:jr.publicKey}));const kr=this._compile();this._partialSign(kr,...Er)}partialSign(...br){if(br.length===0)throw new Error("No signers");const wr=new Set,Er=[];for(const jr of br){const Br=jr.publicKey.toString();wr.has(Br)||(wr.add(Br),Er.push(jr))}const kr=this._compile();this._partialSign(kr,...Er)}_partialSign(br,...wr){const Er=br.serialize();wr.forEach(kr=>{const jr=sign(Er,kr.secretKey);this._addSignature(kr.publicKey,toBuffer$2(jr))})}addSignature(br,wr){this._compile(),this._addSignature(br,wr)}_addSignature(br,wr){assert$2(wr.length===64);const Er=this.signatures.findIndex(kr=>br.equals(kr.publicKey));if(Er<0)throw new Error(`unknown signer: ${br.toString()}`);this.signatures[Er].signature=Buffer$1$1.from(wr)}verifySignatures(br=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),br)}_getMessageSignednessErrors(br,wr){const Er={};for(const{signature:kr,publicKey:jr}of this.signatures)kr===null?wr&&(Er.missing||(Er.missing=[])).push(jr):verify(kr,br,jr.toBytes())||(Er.invalid||(Er.invalid=[])).push(jr);return Er.invalid||Er.missing?Er:void 0}serialize(br){const{requireAllSignatures:wr,verifySignatures:Er}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},br),kr=this.serializeMessage();if(Er){const jr=this._getMessageSignednessErrors(kr,wr);if(jr){let Br="Signature verification failed.";throw jr.invalid&&(Br+=` Invalid signature for public key${jr.invalid.length===1?"":"(s)"} [\`${jr.invalid.map(qr=>qr.toBase58()).join("`, `")}\`].`),jr.missing&&(Br+=` Missing signature for public key${jr.missing.length===1?"":"(s)"} [\`${jr.missing.map(qr=>qr.toBase58()).join("`, `")}\`].`),new Error(Br)}}return this._serialize(kr)}_serialize(br){const{signatures:wr}=this,Er=[];encodeLength(Er,wr.length);const kr=Er.length+wr.length*64+br.length,jr=Buffer$1$1.alloc(kr);return assert$2(wr.length<256),Buffer$1$1.from(Er).copy(jr,0),wr.forEach(({signature:Br},qr)=>{Br!==null&&(assert$2(Br.length===64,"signature has invalid length"),Buffer$1$1.from(Br).copy(jr,Er.length+qr*64))}),br.copy(jr,Er.length+wr.length*64),assert$2(jr.length<=PACKET_DATA_SIZE,`Transaction too large: ${jr.length} > ${PACKET_DATA_SIZE}`),jr}get keys(){return assert$2(this.instructions.length===1),this.instructions[0].keys.map(br=>br.pubkey)}get programId(){return assert$2(this.instructions.length===1),this.instructions[0].programId}get data(){return assert$2(this.instructions.length===1),this.instructions[0].data}static from(br){let wr=[...br];const Er=decodeLength(wr);let kr=[];for(let jr=0;jr0&&(Er.feePayer=br.accountKeys[0]),wr.forEach((kr,jr)=>{const Br={signature:kr==bs58$6.encode(DEFAULT_SIGNATURE)?null:bs58$6.decode(kr),publicKey:br.accountKeys[jr]};Er.signatures.push(Br)}),br.instructions.forEach(kr=>{const jr=kr.accounts.map(Br=>{const qr=br.accountKeys[Br];return{pubkey:qr,isSigner:Er.signatures.some(Wr=>Wr.publicKey.toString()===qr.toString())||br.isAccountSigner(Br),isWritable:br.isAccountWritable(Br)}});Er.instructions.push(new TransactionInstruction({keys:jr,programId:br.accountKeys[kr.programIdIndex],data:bs58$6.decode(kr.data)}))}),Er._message=br,Er._json=Er.toJSON(),Er}}class VersionedTransaction{get version(){return this.message.version}constructor(br,wr){if(this.signatures=void 0,this.message=void 0,wr!==void 0)assert$2(wr.length===br.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures"),this.signatures=wr;else{const Er=[];for(let kr=0;krBr.equals(kr.publicKey));assert$2(jr>=0,`Cannot sign with non signer key ${kr.publicKey.toBase58()}`),this.signatures[jr]=sign(wr,kr.secretKey)}}addSignature(br,wr){assert$2(wr.byteLength===64,"Signature must be 64 bytes long");const kr=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(jr=>jr.equals(br));assert$2(kr>=0,`Can not add signature; \`${br.toBase58()}\` is not required to sign this transaction`),this.signatures[kr]=wr}}const NUM_TICKS_PER_SECOND=160,DEFAULT_TICKS_PER_SLOT=64,NUM_SLOTS_PER_SECOND=NUM_TICKS_PER_SECOND/DEFAULT_TICKS_PER_SLOT,MS_PER_SLOT=1e3/NUM_SLOTS_PER_SECOND;new PublicKey$2("SysvarC1ock11111111111111111111111111111111");new PublicKey$2("SysvarEpochSchedu1e111111111111111111111111");new PublicKey$2("Sysvar1nstructions1111111111111111111111111");const SYSVAR_RECENT_BLOCKHASHES_PUBKEY=new PublicKey$2("SysvarRecentB1ockHashes11111111111111111111"),SYSVAR_RENT_PUBKEY=new PublicKey$2("SysvarRent111111111111111111111111111111111");new PublicKey$2("SysvarRewards111111111111111111111111111111");new PublicKey$2("SysvarS1otHashes111111111111111111111111111");new PublicKey$2("SysvarS1otHistory11111111111111111111111111");new PublicKey$2("SysvarStakeHistory1111111111111111111111111");class SendTransactionError extends Error{constructor({action:br,signature:wr,transactionMessage:Er,logs:kr}){let jr;switch(br){case"send":jr=`Transaction ${wr} resulted in an error. ${Er}. `+(kr?`Logs: diff --git a/assets/index-BbrMFua0.js b/assets/index-D0Cq9I1E.js similarity index 98% rename from assets/index-BbrMFua0.js rename to assets/index-D0Cq9I1E.js index a1afa86..c97984a 100644 --- a/assets/index-BbrMFua0.js +++ b/assets/index-D0Cq9I1E.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BD01_B0B.js","assets/index-jkWzPUAB.js","assets/index-BqexNBF0.css"])))=>i.map(i=>d[i]); -import{B as pe,_ as me}from"./index-jkWzPUAB.js";const he=Symbol(),ee=Object.getPrototypeOf,Y=new WeakMap,ge=e=>e&&(Y.has(e)?Y.get(e):ee(e)===Object.prototype||ee(e)===Array.prototype),ye=e=>ge(e)&&e[he]||null,te=(e,t=!0)=>{Y.set(e,t)},z={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_BACKEND_URL:"https://push-auth.push.org",VITE_APP_DYNAMIC_ENV_ID:"82e8732d-11b8-428d-a553-7087d0c44171",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"},F=e=>typeof e=="object"&&e!==null,L=new WeakMap,x=new WeakSet,ve=(e=Object.is,t=(o,g)=>new Proxy(o,g),s=o=>F(o)&&!x.has(o)&&(Array.isArray(o)||!(Symbol.iterator in o))&&!(o instanceof WeakMap)&&!(o instanceof WeakSet)&&!(o instanceof Error)&&!(o instanceof Number)&&!(o instanceof Date)&&!(o instanceof String)&&!(o instanceof RegExp)&&!(o instanceof ArrayBuffer),n=o=>{switch(o.status){case"fulfilled":return o.value;case"rejected":throw o.reason;default:throw o}},l=new WeakMap,c=(o,g,I=n)=>{const v=l.get(o);if((v==null?void 0:v[0])===g)return v[1];const w=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o));return te(w,!0),l.set(o,[g,w]),Reflect.ownKeys(o).forEach(j=>{if(Object.getOwnPropertyDescriptor(w,j))return;const O=Reflect.get(o,j),A={value:O,enumerable:!0,configurable:!0};if(x.has(O))te(O,!1);else if(O instanceof Promise)delete A.value,A.get=()=>I(O);else if(L.has(O)){const[y,H]=L.get(O);A.value=c(y,H(),I)}Object.defineProperty(w,j,A)}),Object.preventExtensions(w)},d=new WeakMap,f=[1,1],W=o=>{if(!F(o))throw new Error("object required");const g=d.get(o);if(g)return g;let I=f[0];const v=new Set,w=(i,a=++f[0])=>{I!==a&&(I=a,v.forEach(r=>r(i,a)))};let j=f[1];const O=(i=++f[1])=>(j!==i&&!v.size&&(j=i,y.forEach(([a])=>{const r=a[1](i);r>I&&(I=r)})),I),A=i=>(a,r)=>{const h=[...a];h[1]=[i,...h[1]],w(h,r)},y=new Map,H=(i,a)=>{if((z?"production":void 0)!=="production"&&y.has(i))throw new Error("prop listener already exists");if(v.size){const r=a[3](A(i));y.set(i,[a,r])}else y.set(i,[a])},Z=i=>{var a;const r=y.get(i);r&&(y.delete(i),(a=r[1])==null||a.call(r))},ue=i=>(v.add(i),v.size===1&&y.forEach(([r,h],U)=>{if((z?"production":void 0)!=="production"&&h)throw new Error("remove already exists");const $=r[3](A(U));y.set(U,[r,$])}),()=>{v.delete(i),v.size===0&&y.forEach(([r,h],U)=>{h&&(h(),y.set(U,[r]))})}),q=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o)),R=t(q,{deleteProperty(i,a){const r=Reflect.get(i,a);Z(a);const h=Reflect.deleteProperty(i,a);return h&&w(["delete",[a],r]),h},set(i,a,r,h){const U=Reflect.has(i,a),$=Reflect.get(i,a,h);if(U&&(e($,r)||d.has(r)&&e($,d.get(r))))return!0;Z(a),F(r)&&(r=ye(r)||r);let V=r;if(r instanceof Promise)r.then(C=>{r.status="fulfilled",r.value=C,w(["resolve",[a],C])}).catch(C=>{r.status="rejected",r.reason=C,w(["reject",[a],C])});else{!L.has(r)&&s(r)&&(V=W(r));const C=!x.has(V)&&L.get(V);C&&H(a,C)}return Reflect.set(i,a,V,h),w(["set",[a],r,$]),!0}});d.set(o,R);const fe=[q,O,c,ue];return L.set(R,fe),Reflect.ownKeys(o).forEach(i=>{const a=Object.getOwnPropertyDescriptor(o,i);"value"in a&&(R[i]=o[i],delete a.value,delete a.writable),Object.defineProperty(q,i,a)}),R})=>[W,L,x,e,t,s,n,l,c,d,f],[we]=ve();function P(e={}){return we(e)}function S(e,t,s){const n=L.get(e);(z?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let l;const c=[],d=n[3];let f=!1;const o=d(g=>{c.push(g),l||(l=Promise.resolve().then(()=>{l=void 0,f&&t(c.splice(0))}))});return f=!0,()=>{f=!1,o()}}function be(e,t){const s=L.get(e);(z?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[n,l,c]=s;return c(n,l(),t)}const u=P({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),de={state:u,subscribe(e){return S(u,()=>e(u))},push(e,t){e!==u.view&&(u.view=e,t&&(u.data=t),u.history.push(e))},reset(e){u.view=e,u.history=[e]},replace(e){u.history.length>1&&(u.history[u.history.length-1]=e,u.view=e)},goBack(){if(u.history.length>1){u.history.pop();const[e]=u.history.slice(-1);u.view=e}},setData(e){u.data=e}},m={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 m.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const e=navigator.userAgent.toLowerCase();return m.isMobile()&&(e.includes("iphone")||e.includes("ipad"))},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},isArray(e){return Array.isArray(e)&&e.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(e,t,s){if(m.isHttpUrl(e))return this.formatUniversalUrl(e,t,s);let n=e;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},formatUniversalUrl(e,t,s){if(!m.isHttpUrl(e))return this.formatNativeUrl(e,t,s);let n=e;if(n.startsWith("https://t.me")){const c=pe.from(t).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,s);const d=new URL(n);return d.searchParams.set("startapp",c),d.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},async wait(e){return new Promise(t=>{setTimeout(t,e)})},openHref(e,t){const s=this.isTelegram()?"_blank":t;window.open(e,s,"noreferrer noopener")},setWalletConnectDeepLink(e,t){try{localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(e){try{const[t]=e.split("?");localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(m.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(m.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var e;const t=(e=de.state.data)==null?void 0:e.Wallet;if(!t)throw new Error('Missing "Wallet" view data');return t}},Ie=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),p=P({enabled:Ie,userSessionId:"",events:[],connectedWalletId:void 0}),_e={state:p,subscribe(e){return S(p.events,()=>e(be(p.events[p.events.length-1])))},initialize(){p.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(p.userSessionId=crypto.randomUUID())},setConnectedWalletId(e){p.connectedWalletId=e},click(e){if(p.enabled){const t={type:"CLICK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},track(e){if(p.enabled){const t={type:"TRACK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},view(e){if(p.enabled){const t={type:"VIEW",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}}},_=P({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),b={state:_,subscribe(e){return S(_,()=>e(_))},setChains(e){_.chains=e},setWalletConnectUri(e){_.walletConnectUri=e},setIsCustomDesktop(e){_.isCustomDesktop=e},setIsCustomMobile(e){_.isCustomMobile=e},setIsDataLoaded(e){_.isDataLoaded=e},setIsUiLoaded(e){_.isUiLoaded=e},setIsAuth(e){_.isAuth=e}},B=P({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}),N={state:B,subscribe(e){return S(B,()=>e(B))},setConfig(e){var t,s;_e.initialize(),b.setChains(e.chains),b.setIsAuth(!!e.enableAuthMode),b.setIsCustomMobile(!!((t=e.mobileWallets)!=null&&t.length)),b.setIsCustomDesktop(!!((s=e.desktopWallets)!=null&&s.length)),m.setModalVersionInStorage(),Object.assign(B,e)}};var Ee=Object.defineProperty,se=Object.getOwnPropertySymbols,Oe=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable,ne=(e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ce=(e,t)=>{for(var s in t||(t={}))Oe.call(t,s)&&ne(e,s,t[s]);if(se)for(var s of se(t))We.call(t,s)&&ne(e,s,t[s]);return e};const G="https://explorer-api.walletconnect.com",Q="wcm",X="js-2.7.0";async function K(e,t){const s=Ce({sdkType:Q,sdkVersion:X},t),n=new URL(e,G);return n.searchParams.append("projectId",N.state.projectId),Object.entries(s).forEach(([c,d])=>{d&&n.searchParams.append(c,String(d))}),(await fetch(n)).json()}const M={async getDesktopListings(e){return K("/w3m/v1/getDesktopListings",e)},async getMobileListings(e){return K("/w3m/v1/getMobileListings",e)},async getInjectedListings(e){return K("/w3m/v1/getInjectedListings",e)},async getAllListings(e){return K("/w3m/v1/getAllListings",e)},getWalletImageUrl(e){return`${G}/w3m/v1/getWalletImage/${e}?projectId=${N.state.projectId}&sdkType=${Q}&sdkVersion=${X}`},getAssetImageUrl(e){return`${G}/w3m/v1/getAssetImage/${e}?projectId=${N.state.projectId}&sdkType=${Q}&sdkVersion=${X}`}};var Le=Object.defineProperty,oe=Object.getOwnPropertySymbols,Pe=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,re=(e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Me=(e,t)=>{for(var s in t||(t={}))Pe.call(t,s)&&re(e,s,t[s]);if(oe)for(var s of oe(t))Ae.call(t,s)&&re(e,s,t[s]);return e};const ae=m.isMobile(),E=P({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Re={state:E,async getRecomendedWallets(){const{explorerRecommendedWalletIds:e,explorerExcludedWalletIds:t}=N.state;if(e==="NONE"||t==="ALL"&&!e)return E.recomendedWallets;if(m.isArray(e)){const n={recommendedIds:e.join(",")},{listings:l}=await M.getAllListings(n),c=Object.values(l);c.sort((d,f)=>{const W=e.indexOf(d.id),o=e.indexOf(f.id);return W-o}),E.recomendedWallets=c}else{const{chains:s,isAuth:n}=b.state,l=s==null?void 0:s.join(","),c=m.isArray(t),d={page:1,sdks:n?"auth_v1":void 0,entries:m.RECOMMENDED_WALLET_AMOUNT,chains:l,version:2,excludedIds:c?t.join(","):void 0},{listings:f}=ae?await M.getMobileListings(d):await M.getDesktopListings(d);E.recomendedWallets=Object.values(f)}return E.recomendedWallets},async getWallets(e){const t=Me({},e),{explorerRecommendedWalletIds:s,explorerExcludedWalletIds:n}=N.state,{recomendedWallets:l}=E;if(n==="ALL")return E.wallets;l.length?t.excludedIds=l.map(I=>I.id).join(","):m.isArray(s)&&(t.excludedIds=s.join(",")),m.isArray(n)&&(t.excludedIds=[t.excludedIds,n].filter(Boolean).join(",")),b.state.isAuth&&(t.sdks="auth_v1");const{page:c,search:d}=e,{listings:f,total:W}=ae?await M.getMobileListings(t):await M.getDesktopListings(t),o=Object.values(f),g=d?"search":"wallets";return E[g]={listings:[...E[g].listings,...o],total:W,page:c??1},{listings:o,total:W}},getWalletImageUrl(e){return M.getWalletImageUrl(e)},getAssetImageUrl(e){return M.getAssetImageUrl(e)},resetSearch(){E.search={listings:[],total:0,page:1}}},T=P({open:!1}),J={state:T,subscribe(e){return S(T,()=>e(T))},async open(e){return new Promise(t=>{const{isUiLoaded:s,isDataLoaded:n}=b.state;if(m.removeWalletConnectDeepLink(),b.setWalletConnectUri(e==null?void 0:e.uri),b.setChains(e==null?void 0:e.chains),de.reset("ConnectWallet"),s&&n)T.open=!0,t();else{const l=setInterval(()=>{const c=b.state;c.isUiLoaded&&c.isDataLoaded&&(clearInterval(l),T.open=!0,t())},200)}})},close(){T.open=!1}};var De=Object.defineProperty,ie=Object.getOwnPropertySymbols,Se=Object.prototype.hasOwnProperty,je=Object.prototype.propertyIsEnumerable,le=(e,t,s)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ue=(e,t)=>{for(var s in t||(t={}))Se.call(t,s)&&le(e,s,t[s]);if(ie)for(var s of ie(t))je.call(t,s)&&le(e,s,t[s]);return e};function Te(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const k=P({themeMode:Te()?"dark":"light"}),ce={state:k,subscribe(e){return S(k,()=>e(k))},setThemeConfig(e){const{themeMode:t,themeVariables:s}=e;t&&(k.themeMode=t),s&&(k.themeVariables=Ue({},s))}},D=P({open:!1,message:"",variant:"success"}),Ve={state:D,subscribe(e){return S(D,()=>e(D))},openToast(e,t){D.open=!0,D.message=e,D.variant=t},closeToast(){D.open=!1}};class Ne{constructor(t){this.openModal=J.open,this.closeModal=J.close,this.subscribeModal=J.subscribe,this.setTheme=ce.setThemeConfig,ce.setThemeConfig(t),N.setConfig(t),this.initUi()}async initUi(){if(typeof window<"u"){await me(()=>import("./index-BD01_B0B.js"),__vite__mapDeps([0,1,2]));const t=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",t),b.setIsUiLoaded(!0)}}}const xe=Object.freeze(Object.defineProperty({__proto__:null,WalletConnectModal:Ne},Symbol.toStringTag,{value:"Module"}));export{m as C,Re as E,J as M,b as O,de as R,ce as T,Ve as a,_e as b,N as c,xe as i}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BQN9T08X.js","assets/index-CkcpbNxk.js","assets/index-BqexNBF0.css"])))=>i.map(i=>d[i]); +import{B as pe,_ as me}from"./index-CkcpbNxk.js";const he=Symbol(),ee=Object.getPrototypeOf,Y=new WeakMap,ge=e=>e&&(Y.has(e)?Y.get(e):ee(e)===Object.prototype||ee(e)===Array.prototype),ye=e=>ge(e)&&e[he]||null,te=(e,t=!0)=>{Y.set(e,t)},z={BASE_URL:"/push-wallet/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_BACKEND_URL:"https://push-auth.push.org",VITE_APP_DYNAMIC_ENV_ID:"82e8732d-11b8-428d-a553-7087d0c44171",VITE_APP_ENV:"dev",VITE_DEV_MODE:"testing"},F=e=>typeof e=="object"&&e!==null,L=new WeakMap,x=new WeakSet,ve=(e=Object.is,t=(o,g)=>new Proxy(o,g),s=o=>F(o)&&!x.has(o)&&(Array.isArray(o)||!(Symbol.iterator in o))&&!(o instanceof WeakMap)&&!(o instanceof WeakSet)&&!(o instanceof Error)&&!(o instanceof Number)&&!(o instanceof Date)&&!(o instanceof String)&&!(o instanceof RegExp)&&!(o instanceof ArrayBuffer),n=o=>{switch(o.status){case"fulfilled":return o.value;case"rejected":throw o.reason;default:throw o}},l=new WeakMap,c=(o,g,I=n)=>{const v=l.get(o);if((v==null?void 0:v[0])===g)return v[1];const w=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o));return te(w,!0),l.set(o,[g,w]),Reflect.ownKeys(o).forEach(j=>{if(Object.getOwnPropertyDescriptor(w,j))return;const O=Reflect.get(o,j),A={value:O,enumerable:!0,configurable:!0};if(x.has(O))te(O,!1);else if(O instanceof Promise)delete A.value,A.get=()=>I(O);else if(L.has(O)){const[y,H]=L.get(O);A.value=c(y,H(),I)}Object.defineProperty(w,j,A)}),Object.preventExtensions(w)},d=new WeakMap,f=[1,1],W=o=>{if(!F(o))throw new Error("object required");const g=d.get(o);if(g)return g;let I=f[0];const v=new Set,w=(i,a=++f[0])=>{I!==a&&(I=a,v.forEach(r=>r(i,a)))};let j=f[1];const O=(i=++f[1])=>(j!==i&&!v.size&&(j=i,y.forEach(([a])=>{const r=a[1](i);r>I&&(I=r)})),I),A=i=>(a,r)=>{const h=[...a];h[1]=[i,...h[1]],w(h,r)},y=new Map,H=(i,a)=>{if((z?"production":void 0)!=="production"&&y.has(i))throw new Error("prop listener already exists");if(v.size){const r=a[3](A(i));y.set(i,[a,r])}else y.set(i,[a])},Z=i=>{var a;const r=y.get(i);r&&(y.delete(i),(a=r[1])==null||a.call(r))},ue=i=>(v.add(i),v.size===1&&y.forEach(([r,h],U)=>{if((z?"production":void 0)!=="production"&&h)throw new Error("remove already exists");const $=r[3](A(U));y.set(U,[r,$])}),()=>{v.delete(i),v.size===0&&y.forEach(([r,h],U)=>{h&&(h(),y.set(U,[r]))})}),q=Array.isArray(o)?[]:Object.create(Object.getPrototypeOf(o)),R=t(q,{deleteProperty(i,a){const r=Reflect.get(i,a);Z(a);const h=Reflect.deleteProperty(i,a);return h&&w(["delete",[a],r]),h},set(i,a,r,h){const U=Reflect.has(i,a),$=Reflect.get(i,a,h);if(U&&(e($,r)||d.has(r)&&e($,d.get(r))))return!0;Z(a),F(r)&&(r=ye(r)||r);let V=r;if(r instanceof Promise)r.then(C=>{r.status="fulfilled",r.value=C,w(["resolve",[a],C])}).catch(C=>{r.status="rejected",r.reason=C,w(["reject",[a],C])});else{!L.has(r)&&s(r)&&(V=W(r));const C=!x.has(V)&&L.get(V);C&&H(a,C)}return Reflect.set(i,a,V,h),w(["set",[a],r,$]),!0}});d.set(o,R);const fe=[q,O,c,ue];return L.set(R,fe),Reflect.ownKeys(o).forEach(i=>{const a=Object.getOwnPropertyDescriptor(o,i);"value"in a&&(R[i]=o[i],delete a.value,delete a.writable),Object.defineProperty(q,i,a)}),R})=>[W,L,x,e,t,s,n,l,c,d,f],[we]=ve();function P(e={}){return we(e)}function S(e,t,s){const n=L.get(e);(z?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let l;const c=[],d=n[3];let f=!1;const o=d(g=>{c.push(g),l||(l=Promise.resolve().then(()=>{l=void 0,f&&t(c.splice(0))}))});return f=!0,()=>{f=!1,o()}}function be(e,t){const s=L.get(e);(z?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[n,l,c]=s;return c(n,l(),t)}const u=P({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),de={state:u,subscribe(e){return S(u,()=>e(u))},push(e,t){e!==u.view&&(u.view=e,t&&(u.data=t),u.history.push(e))},reset(e){u.view=e,u.history=[e]},replace(e){u.history.length>1&&(u.history[u.history.length-1]=e,u.view=e)},goBack(){if(u.history.length>1){u.history.pop();const[e]=u.history.slice(-1);u.view=e}},setData(e){u.data=e}},m={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 m.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const e=navigator.userAgent.toLowerCase();return m.isMobile()&&(e.includes("iphone")||e.includes("ipad"))},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},isArray(e){return Array.isArray(e)&&e.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(e,t,s){if(m.isHttpUrl(e))return this.formatUniversalUrl(e,t,s);let n=e;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},formatUniversalUrl(e,t,s){if(!m.isHttpUrl(e))return this.formatNativeUrl(e,t,s);let n=e;if(n.startsWith("https://t.me")){const c=pe.from(t).toString("base64").replace(/[=]/g,"");n.endsWith("/")&&(n=n.slice(0,-1)),this.setWalletConnectDeepLink(n,s);const d=new URL(n);return d.searchParams.set("startapp",c),d.toString()}n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,s);const l=encodeURIComponent(t);return`${n}wc?uri=${l}`},async wait(e){return new Promise(t=>{setTimeout(t,e)})},openHref(e,t){const s=this.isTelegram()?"_blank":t;window.open(e,s,"noreferrer noopener")},setWalletConnectDeepLink(e,t){try{localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(e){try{const[t]=e.split("?");localStorage.setItem(m.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(m.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(m.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var e;const t=(e=de.state.data)==null?void 0:e.Wallet;if(!t)throw new Error('Missing "Wallet" view data');return t}},Ie=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),p=P({enabled:Ie,userSessionId:"",events:[],connectedWalletId:void 0}),_e={state:p,subscribe(e){return S(p.events,()=>e(be(p.events[p.events.length-1])))},initialize(){p.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(p.userSessionId=crypto.randomUUID())},setConnectedWalletId(e){p.connectedWalletId=e},click(e){if(p.enabled){const t={type:"CLICK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},track(e){if(p.enabled){const t={type:"TRACK",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}},view(e){if(p.enabled){const t={type:"VIEW",name:e.name,userSessionId:p.userSessionId,timestamp:Date.now(),data:e};p.events.push(t)}}},_=P({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),b={state:_,subscribe(e){return S(_,()=>e(_))},setChains(e){_.chains=e},setWalletConnectUri(e){_.walletConnectUri=e},setIsCustomDesktop(e){_.isCustomDesktop=e},setIsCustomMobile(e){_.isCustomMobile=e},setIsDataLoaded(e){_.isDataLoaded=e},setIsUiLoaded(e){_.isUiLoaded=e},setIsAuth(e){_.isAuth=e}},B=P({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}),N={state:B,subscribe(e){return S(B,()=>e(B))},setConfig(e){var t,s;_e.initialize(),b.setChains(e.chains),b.setIsAuth(!!e.enableAuthMode),b.setIsCustomMobile(!!((t=e.mobileWallets)!=null&&t.length)),b.setIsCustomDesktop(!!((s=e.desktopWallets)!=null&&s.length)),m.setModalVersionInStorage(),Object.assign(B,e)}};var Ee=Object.defineProperty,se=Object.getOwnPropertySymbols,Oe=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable,ne=(e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ce=(e,t)=>{for(var s in t||(t={}))Oe.call(t,s)&&ne(e,s,t[s]);if(se)for(var s of se(t))We.call(t,s)&&ne(e,s,t[s]);return e};const G="https://explorer-api.walletconnect.com",Q="wcm",X="js-2.7.0";async function K(e,t){const s=Ce({sdkType:Q,sdkVersion:X},t),n=new URL(e,G);return n.searchParams.append("projectId",N.state.projectId),Object.entries(s).forEach(([c,d])=>{d&&n.searchParams.append(c,String(d))}),(await fetch(n)).json()}const M={async getDesktopListings(e){return K("/w3m/v1/getDesktopListings",e)},async getMobileListings(e){return K("/w3m/v1/getMobileListings",e)},async getInjectedListings(e){return K("/w3m/v1/getInjectedListings",e)},async getAllListings(e){return K("/w3m/v1/getAllListings",e)},getWalletImageUrl(e){return`${G}/w3m/v1/getWalletImage/${e}?projectId=${N.state.projectId}&sdkType=${Q}&sdkVersion=${X}`},getAssetImageUrl(e){return`${G}/w3m/v1/getAssetImage/${e}?projectId=${N.state.projectId}&sdkType=${Q}&sdkVersion=${X}`}};var Le=Object.defineProperty,oe=Object.getOwnPropertySymbols,Pe=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,re=(e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Me=(e,t)=>{for(var s in t||(t={}))Pe.call(t,s)&&re(e,s,t[s]);if(oe)for(var s of oe(t))Ae.call(t,s)&&re(e,s,t[s]);return e};const ae=m.isMobile(),E=P({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Re={state:E,async getRecomendedWallets(){const{explorerRecommendedWalletIds:e,explorerExcludedWalletIds:t}=N.state;if(e==="NONE"||t==="ALL"&&!e)return E.recomendedWallets;if(m.isArray(e)){const n={recommendedIds:e.join(",")},{listings:l}=await M.getAllListings(n),c=Object.values(l);c.sort((d,f)=>{const W=e.indexOf(d.id),o=e.indexOf(f.id);return W-o}),E.recomendedWallets=c}else{const{chains:s,isAuth:n}=b.state,l=s==null?void 0:s.join(","),c=m.isArray(t),d={page:1,sdks:n?"auth_v1":void 0,entries:m.RECOMMENDED_WALLET_AMOUNT,chains:l,version:2,excludedIds:c?t.join(","):void 0},{listings:f}=ae?await M.getMobileListings(d):await M.getDesktopListings(d);E.recomendedWallets=Object.values(f)}return E.recomendedWallets},async getWallets(e){const t=Me({},e),{explorerRecommendedWalletIds:s,explorerExcludedWalletIds:n}=N.state,{recomendedWallets:l}=E;if(n==="ALL")return E.wallets;l.length?t.excludedIds=l.map(I=>I.id).join(","):m.isArray(s)&&(t.excludedIds=s.join(",")),m.isArray(n)&&(t.excludedIds=[t.excludedIds,n].filter(Boolean).join(",")),b.state.isAuth&&(t.sdks="auth_v1");const{page:c,search:d}=e,{listings:f,total:W}=ae?await M.getMobileListings(t):await M.getDesktopListings(t),o=Object.values(f),g=d?"search":"wallets";return E[g]={listings:[...E[g].listings,...o],total:W,page:c??1},{listings:o,total:W}},getWalletImageUrl(e){return M.getWalletImageUrl(e)},getAssetImageUrl(e){return M.getAssetImageUrl(e)},resetSearch(){E.search={listings:[],total:0,page:1}}},T=P({open:!1}),J={state:T,subscribe(e){return S(T,()=>e(T))},async open(e){return new Promise(t=>{const{isUiLoaded:s,isDataLoaded:n}=b.state;if(m.removeWalletConnectDeepLink(),b.setWalletConnectUri(e==null?void 0:e.uri),b.setChains(e==null?void 0:e.chains),de.reset("ConnectWallet"),s&&n)T.open=!0,t();else{const l=setInterval(()=>{const c=b.state;c.isUiLoaded&&c.isDataLoaded&&(clearInterval(l),T.open=!0,t())},200)}})},close(){T.open=!1}};var De=Object.defineProperty,ie=Object.getOwnPropertySymbols,Se=Object.prototype.hasOwnProperty,je=Object.prototype.propertyIsEnumerable,le=(e,t,s)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ue=(e,t)=>{for(var s in t||(t={}))Se.call(t,s)&&le(e,s,t[s]);if(ie)for(var s of ie(t))je.call(t,s)&&le(e,s,t[s]);return e};function Te(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const k=P({themeMode:Te()?"dark":"light"}),ce={state:k,subscribe(e){return S(k,()=>e(k))},setThemeConfig(e){const{themeMode:t,themeVariables:s}=e;t&&(k.themeMode=t),s&&(k.themeVariables=Ue({},s))}},D=P({open:!1,message:"",variant:"success"}),Ve={state:D,subscribe(e){return S(D,()=>e(D))},openToast(e,t){D.open=!0,D.message=e,D.variant=t},closeToast(){D.open=!1}};class Ne{constructor(t){this.openModal=J.open,this.closeModal=J.close,this.subscribeModal=J.subscribe,this.setTheme=ce.setThemeConfig,ce.setThemeConfig(t),N.setConfig(t),this.initUi()}async initUi(){if(typeof window<"u"){await me(()=>import("./index-BQN9T08X.js"),__vite__mapDeps([0,1,2]));const t=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",t),b.setIsUiLoaded(!0)}}}const xe=Object.freeze(Object.defineProperty({__proto__:null,WalletConnectModal:Ne},Symbol.toStringTag,{value:"Module"}));export{m as C,Re as E,J as M,b as O,de as R,ce as T,Ve as a,_e as b,N as c,xe as i}; diff --git a/assets/nodecrypto-B3VJzu49.js b/assets/nodecrypto-pMA0JG-7.js similarity index 64% rename from assets/nodecrypto-B3VJzu49.js rename to assets/nodecrypto-pMA0JG-7.js index c2775a2..46e6ee4 100644 --- a/assets/nodecrypto-B3VJzu49.js +++ b/assets/nodecrypto-pMA0JG-7.js @@ -1 +1 @@ -import{r as n,B as y}from"./index-jkWzPUAB.js";import{c as p}from"./utils-C6R2Lbau.js";var r=n();const m=async t=>{const{content:o,publicKey:i,privateKey:s}=t,c=r.createPrivateKey({key:p({uncompressedPrivateKeyHex:s,compressedPublicKeyHex:i}),format:"jwk"}),e=r.createSign("SHA256");return e.write(y.from(o)),e.end(),e.sign(c,"hex")};export{m as signWithApiKey}; +import{r as n,B as y}from"./index-CkcpbNxk.js";import{c as p}from"./utils-B7bt9iXy.js";var r=n();const m=async t=>{const{content:o,publicKey:i,privateKey:s}=t,c=r.createPrivateKey({key:p({uncompressedPrivateKeyHex:s,compressedPublicKeyHex:i}),format:"jwk"}),e=r.createSign("SHA256");return e.write(y.from(o)),e.end(),e.sign(c,"hex")};export{m as signWithApiKey}; diff --git a/assets/purejs-CR9yUBx8.js b/assets/purejs-B-VHXJWQ.js similarity index 92% rename from assets/purejs-CR9yUBx8.js rename to assets/purejs-B-VHXJWQ.js index 5e5444d..5565e69 100644 --- a/assets/purejs-CR9yUBx8.js +++ b/assets/purejs-B-VHXJWQ.js @@ -1 +1 @@ -import{F as n,c as s,s as i,u as r,b as o}from"./index-jkWzPUAB.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=n(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),g=t.create(BigInt("-3")),d=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),c=s({a:g,b:d,Fp:t,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},i),u=async f=>{const a=c.getPublicKey(f.privateKey,!0),e=r(a);if(e!=f.publicKey)throw new Error(`Bad API key. Expected to get public key ${f.publicKey}, got ${e}`);const b=o().update(f.content).digest();return c.sign(b,f.privateKey).toDERHex()};export{u as signWithApiKey}; +import{F as n,c as s,s as i,u as r,b as o}from"./index-CkcpbNxk.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=n(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),g=t.create(BigInt("-3")),d=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),c=s({a:g,b:d,Fp:t,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},i),u=async f=>{const a=c.getPublicKey(f.privateKey,!0),e=r(a);if(e!=f.publicKey)throw new Error(`Bad API key. Expected to get public key ${f.publicKey}, got ${e}`);const b=o().update(f.content).digest();return c.sign(b,f.privateKey).toDERHex()};export{u as signWithApiKey}; diff --git a/assets/utils-C6R2Lbau.js b/assets/utils-B7bt9iXy.js similarity index 98% rename from assets/utils-C6R2Lbau.js rename to assets/utils-B7bt9iXy.js index 61b9709..63ab6f9 100644 --- a/assets/utils-C6R2Lbau.js +++ b/assets/utils-B7bt9iXy.js @@ -1,4 +1,4 @@ -import{a as d,h as B,D as w}from"./index-jkWzPUAB.js";/** +import{a as d,h as B,D as w}from"./index-CkcpbNxk.js";/** * Code modified from https://github.com/google/tink/blob/6f74b99a2bfe6677e3670799116a57268fd067fa/javascript/subtle/bytes.ts * * @license diff --git a/assets/webcrypto-DQKOHd8b.js b/assets/webcrypto-CJZUMDsH.js similarity index 90% rename from assets/webcrypto-DQKOHd8b.js rename to assets/webcrypto-CJZUMDsH.js index 97b8281..00b7483 100644 --- a/assets/webcrypto-DQKOHd8b.js +++ b/assets/webcrypto-CJZUMDsH.js @@ -1 +1 @@ -import{c}from"./utils-C6R2Lbau.js";import{u as i}from"./index-jkWzPUAB.js";const p=async n=>{const{content:e,publicKey:s,privateKey:t}=n,o=await g({uncompressedPrivateKeyHex:t,compressedPublicKeyHex:s});return await l({key:o,content:e})};async function g(n){const{uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s}=n,t=c({uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s});return await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}async function l(n){const{key:e,content:s}=n,t=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(s)),o=u(new Uint8Array(t));return i(o)}function u(n){if(n.length%2!=0||n.length==0||n.length>132)throw new Error("Invalid IEEE P1363 signature encoding. Length: "+n.length);const e=a(n.subarray(0,n.length/2)),s=a(n.subarray(n.length/2,n.length));let t=0;const o=2+e.length+1+1+s.length;let r;return o>=128?(r=new Uint8Array(o+3),r[t++]=48,r[t++]=129,r[t++]=o):(r=new Uint8Array(o+2),r[t++]=48,r[t++]=o),r[t++]=2,r[t++]=e.length,r.set(e,t),t+=e.length,r[t++]=2,r[t++]=s.length,r.set(s,t),r}function a(n){let e=0;for(;e{const{content:e,publicKey:s,privateKey:t}=n,o=await g({uncompressedPrivateKeyHex:t,compressedPublicKeyHex:s});return await l({key:o,content:e})};async function g(n){const{uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s}=n,t=c({uncompressedPrivateKeyHex:e,compressedPublicKeyHex:s});return await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}async function l(n){const{key:e,content:s}=n,t=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(s)),o=u(new Uint8Array(t));return i(o)}function u(n){if(n.length%2!=0||n.length==0||n.length>132)throw new Error("Invalid IEEE P1363 signature encoding. Length: "+n.length);const e=a(n.subarray(0,n.length/2)),s=a(n.subarray(n.length/2,n.length));let t=0;const o=2+e.length+1+1+s.length;let r;return o>=128?(r=new Uint8Array(o+3),r[t++]=48,r[t++]=129,r[t++]=o):(r=new Uint8Array(o+2),r[t++]=48,r[t++]=o),r[t++]=2,r[t++]=e.length,r.set(e,t),t+=e.length,r[t++]=2,r[t++]=s.length,r.set(s,t),r}function a(n){let e=0;for(;e - +