-
Notifications
You must be signed in to change notification settings - Fork 31
/
14428.b372bed0.iframe.bundle.js
1 lines (1 loc) · 87.6 KB
/
14428.b372bed0.iframe.bundle.js
1
"use strict";(globalThis.webpackChunkmetamask_crx=globalThis.webpackChunkmetamask_crx||[]).push([[14428],{"./node_modules/@ethersproject/providers/lib.esm/_version.js":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{r:()=>version});let version="providers/5.7.2"},"./node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{F:()=>JsonRpcProvider});var lib_esm=__webpack_require__("./node_modules/@ethersproject/abstract-signer/lib.esm/index.js"),bignumber=__webpack_require__("./node_modules/@ethersproject/bignumber/lib.esm/bignumber.js"),bytes_lib_esm=__webpack_require__("./node_modules/@ethersproject/bytes/lib.esm/index.js"),typed_data=__webpack_require__("./node_modules/@ethersproject/hash/lib.esm/typed-data.js"),properties_lib_esm=__webpack_require__("./node_modules/@ethersproject/properties/lib.esm/index.js"),utf8=__webpack_require__("./node_modules/@ethersproject/strings/lib.esm/utf8.js"),transactions_lib_esm=__webpack_require__("./node_modules/@ethersproject/transactions/lib.esm/index.js"),base64=__webpack_require__("./node_modules/@ethersproject/base64/lib.esm/base64.js"),logger_lib_esm=__webpack_require__("./node_modules/@ethersproject/logger/lib.esm/index.js"),__awaiter=function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};function getUrl(href,options){return __awaiter(this,void 0,void 0,function*(){null==options&&(options={});let request={method:options.method||"GET",headers:options.headers||{},body:options.body||void 0};if(!0!==options.skipFetchSetup&&(request.mode="cors",request.cache="no-cache",request.credentials="same-origin",request.redirect="follow",request.referrer="client"),null!=options.fetchOptions){let opts=options.fetchOptions;opts.mode&&(request.mode=opts.mode),opts.cache&&(request.cache=opts.cache),opts.credentials&&(request.credentials=opts.credentials),opts.redirect&&(request.redirect=opts.redirect),opts.referrer&&(request.referrer=opts.referrer)}let response=yield fetch(href,request),body=yield response.arrayBuffer(),headers={};return response.headers.forEach?response.headers.forEach((value,key)=>{headers[key.toLowerCase()]=value}):response.headers.keys().forEach(key=>{headers[key.toLowerCase()]=response.headers.get(key)}),{headers:headers,statusCode:response.status,statusMessage:response.statusText,body:(0,bytes_lib_esm.arrayify)(new Uint8Array(body))}})}var lib_esm_awaiter=function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};let logger=new logger_lib_esm.Logger("web/5.7.1");function staller(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}function bodyify(value,type){if(null==value)return null;if("string"==typeof value)return value;if((0,bytes_lib_esm.isBytesLike)(value)){if(type&&("text"===type.split("/")[0]||"application/json"===type.split(";")[0].trim()))try{return(0,utf8._v)(value)}catch(error){}return(0,bytes_lib_esm.hexlify)(value)}return value}function unpercent(value){return(0,utf8.YW)(value.replace(/%([0-9a-f][0-9a-f])/gi,(all,code)=>String.fromCharCode(parseInt(code,16))))}function _fetchData(connection,body,processFunc){let timer;let attemptLimit="object"==typeof connection&&null!=connection.throttleLimit?connection.throttleLimit:12;logger.assertArgument(attemptLimit>0&&attemptLimit%1==0,"invalid connection throttle limit","connection.throttleLimit",attemptLimit);let throttleCallback="object"==typeof connection?connection.throttleCallback:null,throttleSlotInterval="object"==typeof connection&&"number"==typeof connection.throttleSlotInterval?connection.throttleSlotInterval:100;logger.assertArgument(throttleSlotInterval>0&&throttleSlotInterval%1==0,"invalid connection throttle slot interval","connection.throttleSlotInterval",throttleSlotInterval);let errorPassThrough="object"==typeof connection&&!!connection.errorPassThrough,headers={},url=null,options={method:"GET"},allow304=!1,timeout=12e4;if("string"==typeof connection)url=connection;else if("object"==typeof connection){if((null==connection||null==connection.url)&&logger.throwArgumentError("missing URL","connection.url",connection),url=connection.url,"number"==typeof connection.timeout&&connection.timeout>0&&(timeout=connection.timeout),connection.headers)for(let key in connection.headers)headers[key.toLowerCase()]={key:key,value:String(connection.headers[key])},["if-none-match","if-modified-since"].indexOf(key.toLowerCase())>=0&&(allow304=!0);if(options.allowGzip=!!connection.allowGzip,null!=connection.user&&null!=connection.password){"https:"!==url.substring(0,6)&&!0!==connection.allowInsecureAuthentication&&logger.throwError("basic authentication requires a secure https url",logger_lib_esm.Logger.errors.INVALID_ARGUMENT,{argument:"url",url:url,user:connection.user,password:"[REDACTED]"});let authorization=connection.user+":"+connection.password;headers.authorization={key:"Authorization",value:"Basic "+(0,base64.l)((0,utf8.YW)(authorization))}}null!=connection.skipFetchSetup&&(options.skipFetchSetup=!!connection.skipFetchSetup),null!=connection.fetchOptions&&(options.fetchOptions=(0,properties_lib_esm.shallowCopy)(connection.fetchOptions))}let reData=RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),dataMatch=url?url.match(reData):null;if(dataMatch)try{let response={statusCode:200,statusMessage:"OK",headers:{"content-type":dataMatch[1]||"text/plain"},body:dataMatch[2]?(0,base64.D)(dataMatch[3]):unpercent(dataMatch[3])},result=response.body;return processFunc&&(result=processFunc(response.body,response)),Promise.resolve(result)}catch(error){logger.throwError("processing response error",logger_lib_esm.Logger.errors.SERVER_ERROR,{body:bodyify(dataMatch[1],dataMatch[2]),error:error,requestBody:null,requestMethod:"GET",url:url})}body&&(options.method="POST",options.body=body,null==headers["content-type"]&&(headers["content-type"]={key:"Content-Type",value:"application/octet-stream"}),null==headers["content-length"]&&(headers["content-length"]={key:"Content-Length",value:String(body.length)}));let flatHeaders={};Object.keys(headers).forEach(key=>{let header=headers[key];flatHeaders[header.key]=header.value}),options.headers=flatHeaders;let runningTimeout=(timer=null,{promise:new Promise(function(resolve,reject){timeout&&(timer=setTimeout(()=>{null!=timer&&(timer=null,reject(logger.makeError("timeout",logger_lib_esm.Logger.errors.TIMEOUT,{requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,timeout:timeout,url:url})))},timeout))}),cancel:function(){null!=timer&&(clearTimeout(timer),timer=null)}}),runningFetch=function(){return lib_esm_awaiter(this,void 0,void 0,function*(){for(let attempt=0;attempt<attemptLimit;attempt++){let response=null;try{if(response=yield getUrl(url,options),attempt<attemptLimit){if(301===response.statusCode||302===response.statusCode){let location=response.headers.location||"";if("GET"===options.method&&location.match(/^https:/)){url=response.headers.location;continue}}else if(429===response.statusCode){let tryAgain=!0;if(throttleCallback&&(tryAgain=yield throttleCallback(attempt,url)),tryAgain){let stall=0,retryAfter=response.headers["retry-after"];stall="string"==typeof retryAfter&&retryAfter.match(/^[1-9][0-9]*$/)?1e3*parseInt(retryAfter):throttleSlotInterval*parseInt(String(Math.random()*Math.pow(2,attempt))),yield staller(stall);continue}}}}catch(error){null==(response=error.response)&&(runningTimeout.cancel(),logger.throwError("missing response",logger_lib_esm.Logger.errors.SERVER_ERROR,{requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,serverError:error,url:url}))}let body=response.body;if(allow304&&304===response.statusCode?body=null:!errorPassThrough&&(response.statusCode<200||response.statusCode>=300)&&(runningTimeout.cancel(),logger.throwError("bad response",logger_lib_esm.Logger.errors.SERVER_ERROR,{status:response.statusCode,headers:response.headers,body:bodyify(body,response.headers?response.headers["content-type"]:null),requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,url:url})),processFunc)try{let result=yield processFunc(body,response);return runningTimeout.cancel(),result}catch(error){if(error.throttleRetry&&attempt<attemptLimit){let tryAgain=!0;if(throttleCallback&&(tryAgain=yield throttleCallback(attempt,url)),tryAgain){let timeout=throttleSlotInterval*parseInt(String(Math.random()*Math.pow(2,attempt)));yield staller(timeout);continue}}runningTimeout.cancel(),logger.throwError("processing response error",logger_lib_esm.Logger.errors.SERVER_ERROR,{body:bodyify(body,response.headers?response.headers["content-type"]:null),error:error,requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,url:url})}return runningTimeout.cancel(),body}return logger.throwError("failed response",logger_lib_esm.Logger.errors.SERVER_ERROR,{requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,url:url})})}();return Promise.race([runningTimeout.promise,runningFetch])}function fetchJson(connection,json,processFunc){let body=null;if(null!=json){body=(0,utf8.YW)(json);let updated="string"==typeof connection?{url:connection}:(0,properties_lib_esm.shallowCopy)(connection);updated.headers?0!==Object.keys(updated.headers).filter(k=>"content-type"===k.toLowerCase()).length||(updated.headers=(0,properties_lib_esm.shallowCopy)(updated.headers),updated.headers["content-type"]="application/json"):updated.headers={"content-type":"application/json"},connection=updated}return _fetchData(connection,body,(value,response)=>{let result=null;if(null!=value)try{result=JSON.parse((0,utf8._v)(value))}catch(error){logger.throwError("invalid JSON",logger_lib_esm.Logger.errors.SERVER_ERROR,{body:value,error:error})}return processFunc&&(result=processFunc(result,response)),result})}function poll(func,options){return options||(options={}),null==(options=(0,properties_lib_esm.shallowCopy)(options)).floor&&(options.floor=0),null==options.ceiling&&(options.ceiling=1e4),null==options.interval&&(options.interval=250),new Promise(function(resolve,reject){let timer=null,done=!1,cancel=()=>!done&&(done=!0,timer&&clearTimeout(timer),!0);options.timeout&&(timer=setTimeout(()=>{cancel()&&reject(Error("timeout"))},options.timeout));let retryLimit=options.retryLimit,attempt=0;function check(){return func().then(function(result){if(void 0!==result)cancel()&&resolve(result);else if(options.oncePoll)options.oncePoll.once("poll",check);else if(options.onceBlock)options.onceBlock.once("block",check);else if(!done){if(++attempt>retryLimit){cancel()&&reject(Error("retry limit reached"));return}let timeout=options.interval*parseInt(String(Math.random()*Math.pow(2,attempt)));timeout<options.floor&&(timeout=options.floor),timeout>options.ceiling&&(timeout=options.ceiling),setTimeout(check,timeout)}return null},function(error){cancel()&&reject(error)})}check()})}var _version=__webpack_require__("./node_modules/@ethersproject/providers/lib.esm/_version.js"),abstract_provider_lib_esm=__webpack_require__("./node_modules/@ethersproject/abstract-provider/lib.esm/index.js"),basex_lib_esm=__webpack_require__("./node_modules/@ethersproject/basex/lib.esm/index.js"),hashes=__webpack_require__("./node_modules/@ethersproject/constants/lib.esm/hashes.js"),namehash=__webpack_require__("./node_modules/@ethersproject/hash/lib.esm/namehash.js");let lib_esm_logger=new logger_lib_esm.Logger("networks/5.7.1");function isRenetworkable(value){return value&&"function"==typeof value.renetwork}function ethDefaultProvider(network){let func=function(providers,options){null==options&&(options={});let providerList=[];if(providers.InfuraProvider&&"-"!==options.infura)try{providerList.push(new providers.InfuraProvider(network,options.infura))}catch(error){}if(providers.EtherscanProvider&&"-"!==options.etherscan)try{providerList.push(new providers.EtherscanProvider(network,options.etherscan))}catch(error){}if(providers.AlchemyProvider&&"-"!==options.alchemy)try{providerList.push(new providers.AlchemyProvider(network,options.alchemy))}catch(error){}if(providers.PocketProvider&&"-"!==options.pocket)try{let provider=new providers.PocketProvider(network,options.pocket);provider.network&&-1===["goerli","ropsten","rinkeby","sepolia"].indexOf(provider.network.name)&&providerList.push(provider)}catch(error){}if(providers.CloudflareProvider&&"-"!==options.cloudflare)try{providerList.push(new providers.CloudflareProvider(network))}catch(error){}if(providers.AnkrProvider&&"-"!==options.ankr)try{let provider=new providers.AnkrProvider(network,options.ankr);provider.network&&-1===["ropsten"].indexOf(provider.network.name)&&providerList.push(provider)}catch(error){}if(0===providerList.length)return null;if(providers.FallbackProvider){let quorum=1;return null!=options.quorum?quorum=options.quorum:"homestead"===network&&(quorum=2),new providers.FallbackProvider(providerList,quorum)}return providerList[0]};return func.renetwork=function(network){return ethDefaultProvider(network)},func}function etcDefaultProvider(url,network){let func=function(providers,options){return providers.JsonRpcProvider?new providers.JsonRpcProvider(url,network):null};return func.renetwork=function(network){return etcDefaultProvider(url,network)},func}let homestead={chainId:1,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"homestead",_defaultProvider:ethDefaultProvider("homestead")},ropsten={chainId:3,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"ropsten",_defaultProvider:ethDefaultProvider("ropsten")},classicMordor={chainId:63,name:"classicMordor",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/mordor","classicMordor")},networks={unspecified:{chainId:0,name:"unspecified"},homestead:homestead,mainnet:homestead,morden:{chainId:2,name:"morden"},ropsten:ropsten,testnet:ropsten,rinkeby:{chainId:4,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"rinkeby",_defaultProvider:ethDefaultProvider("rinkeby")},kovan:{chainId:42,name:"kovan",_defaultProvider:ethDefaultProvider("kovan")},goerli:{chainId:5,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"goerli",_defaultProvider:ethDefaultProvider("goerli")},kintsugi:{chainId:1337702,name:"kintsugi"},sepolia:{chainId:11155111,name:"sepolia",_defaultProvider:ethDefaultProvider("sepolia")},classic:{chainId:61,name:"classic",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/etc","classic")},classicMorden:{chainId:62,name:"classicMorden"},classicMordor:classicMordor,classicTestnet:classicMordor,classicKotti:{chainId:6,name:"classicKotti",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/kotti","classicKotti")},xdai:{chainId:100,name:"xdai"},matic:{chainId:137,name:"matic",_defaultProvider:ethDefaultProvider("matic")},maticmum:{chainId:80001,name:"maticmum"},optimism:{chainId:10,name:"optimism",_defaultProvider:ethDefaultProvider("optimism")},"optimism-kovan":{chainId:69,name:"optimism-kovan"},"optimism-goerli":{chainId:420,name:"optimism-goerli"},arbitrum:{chainId:42161,name:"arbitrum"},"arbitrum-rinkeby":{chainId:421611,name:"arbitrum-rinkeby"},"arbitrum-goerli":{chainId:421613,name:"arbitrum-goerli"},bnb:{chainId:56,name:"bnb"},bnbt:{chainId:97,name:"bnbt"}};function getNetwork(network){if(null==network)return null;if("number"==typeof network){for(let name in networks){let standard=networks[name];if(standard.chainId===network)return{name:standard.name,chainId:standard.chainId,ensAddress:standard.ensAddress||null,_defaultProvider:standard._defaultProvider||null}}return{chainId:network,name:"unknown"}}if("string"==typeof network){let standard=networks[network];return null==standard?null:{name:standard.name,chainId:standard.chainId,ensAddress:standard.ensAddress,_defaultProvider:standard._defaultProvider||null}}let standard=networks[network.name];if(!standard)return"number"!=typeof network.chainId&&lib_esm_logger.throwArgumentError("invalid network chainId","network",network),network;0!==network.chainId&&network.chainId!==standard.chainId&&lib_esm_logger.throwArgumentError("network chainId mismatch","network",network);let defaultProvider=network._defaultProvider||null;return null==defaultProvider&&standard._defaultProvider&&(defaultProvider=isRenetworkable(standard._defaultProvider)?standard._defaultProvider.renetwork(network):standard._defaultProvider),{name:network.name,chainId:standard.chainId,ensAddress:network.ensAddress||standard.ensAddress||null,_defaultProvider:defaultProvider}}var sha2=__webpack_require__("./node_modules/@ethersproject/sha2/lib.esm/sha2.js"),bech32=__webpack_require__("./node_modules/@ethersproject/providers/node_modules/bech32/index.js"),bech32_default=__webpack_require__.n(bech32),address_lib_esm=__webpack_require__("./node_modules/@ethersproject/address/lib.esm/index.js");let formatter_logger=new logger_lib_esm.Logger(_version.r);class Formatter{constructor(){this.formats=this.getDefaultFormats()}getDefaultFormats(){let formats={},address=this.address.bind(this),bigNumber=this.bigNumber.bind(this),blockTag=this.blockTag.bind(this),data=this.data.bind(this),hash=this.hash.bind(this),hex=this.hex.bind(this),number=this.number.bind(this),type=this.type.bind(this);return formats.transaction={hash:hash,type:type,accessList:Formatter.allowNull(this.accessList.bind(this),null),blockHash:Formatter.allowNull(hash,null),blockNumber:Formatter.allowNull(number,null),transactionIndex:Formatter.allowNull(number,null),confirmations:Formatter.allowNull(number,null),from:address,gasPrice:Formatter.allowNull(bigNumber),maxPriorityFeePerGas:Formatter.allowNull(bigNumber),maxFeePerGas:Formatter.allowNull(bigNumber),gasLimit:bigNumber,to:Formatter.allowNull(address,null),value:bigNumber,nonce:number,data:data,r:Formatter.allowNull(this.uint256),s:Formatter.allowNull(this.uint256),v:Formatter.allowNull(number),creates:Formatter.allowNull(address,null),raw:Formatter.allowNull(data)},formats.transactionRequest={from:Formatter.allowNull(address),nonce:Formatter.allowNull(number),gasLimit:Formatter.allowNull(bigNumber),gasPrice:Formatter.allowNull(bigNumber),maxPriorityFeePerGas:Formatter.allowNull(bigNumber),maxFeePerGas:Formatter.allowNull(bigNumber),to:Formatter.allowNull(address),value:Formatter.allowNull(bigNumber),data:Formatter.allowNull(v=>this.data(v,!0)),type:Formatter.allowNull(number),accessList:Formatter.allowNull(this.accessList.bind(this),null)},formats.receiptLog={transactionIndex:number,blockNumber:number,transactionHash:hash,address:address,topics:Formatter.arrayOf(hash),data:data,logIndex:number,blockHash:hash},formats.receipt={to:Formatter.allowNull(this.address,null),from:Formatter.allowNull(this.address,null),contractAddress:Formatter.allowNull(address,null),transactionIndex:number,root:Formatter.allowNull(hex),gasUsed:bigNumber,logsBloom:Formatter.allowNull(data),blockHash:hash,transactionHash:hash,logs:Formatter.arrayOf(this.receiptLog.bind(this)),blockNumber:number,confirmations:Formatter.allowNull(number,null),cumulativeGasUsed:bigNumber,effectiveGasPrice:Formatter.allowNull(bigNumber),status:Formatter.allowNull(number),type:type},formats.block={hash:Formatter.allowNull(hash),parentHash:hash,number:number,timestamp:number,nonce:Formatter.allowNull(hex),difficulty:this.difficulty.bind(this),gasLimit:bigNumber,gasUsed:bigNumber,miner:Formatter.allowNull(address),extraData:data,transactions:Formatter.allowNull(Formatter.arrayOf(hash)),baseFeePerGas:Formatter.allowNull(bigNumber)},formats.blockWithTransactions=(0,properties_lib_esm.shallowCopy)(formats.block),formats.blockWithTransactions.transactions=Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this))),formats.filter={fromBlock:Formatter.allowNull(blockTag,void 0),toBlock:Formatter.allowNull(blockTag,void 0),blockHash:Formatter.allowNull(hash,void 0),address:Formatter.allowNull(address,void 0),topics:Formatter.allowNull(this.topics.bind(this),void 0)},formats.filterLog={blockNumber:Formatter.allowNull(number),blockHash:Formatter.allowNull(hash),transactionIndex:number,removed:Formatter.allowNull(this.boolean.bind(this)),address:address,data:Formatter.allowFalsish(data,"0x"),topics:Formatter.arrayOf(hash),transactionHash:hash,logIndex:number},formats}accessList(accessList){return(0,transactions_lib_esm.accessListify)(accessList||[])}number(number){return"0x"===number?0:bignumber.gH.from(number).toNumber()}type(number){return"0x"===number||null==number?0:bignumber.gH.from(number).toNumber()}bigNumber(value){return bignumber.gH.from(value)}boolean(value){if("boolean"==typeof value)return value;if("string"==typeof value){if("true"===(value=value.toLowerCase()))return!0;if("false"===value)return!1}throw Error("invalid boolean - "+value)}hex(value,strict){return"string"==typeof value&&(strict||"0x"===value.substring(0,2)||(value="0x"+value),(0,bytes_lib_esm.isHexString)(value))?value.toLowerCase():formatter_logger.throwArgumentError("invalid hash","value",value)}data(value,strict){let result=this.hex(value,strict);if(result.length%2!=0)throw Error("invalid data; odd-length - "+value);return result}address(value){return(0,address_lib_esm.getAddress)(value)}callAddress(value){if(!(0,bytes_lib_esm.isHexString)(value,32))return null;let address=(0,address_lib_esm.getAddress)((0,bytes_lib_esm.hexDataSlice)(value,12));return"0x0000000000000000000000000000000000000000"===address?null:address}contractAddress(value){return(0,address_lib_esm.getContractAddress)(value)}blockTag(blockTag){if(null==blockTag)return"latest";if("earliest"===blockTag)return"0x0";switch(blockTag){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return blockTag}if("number"==typeof blockTag||(0,bytes_lib_esm.isHexString)(blockTag))return(0,bytes_lib_esm.hexValue)(blockTag);throw Error("invalid blockTag")}hash(value,strict){let result=this.hex(value,strict);return 32!==(0,bytes_lib_esm.hexDataLength)(result)?formatter_logger.throwArgumentError("invalid hash","value",value):result}difficulty(value){if(null==value)return null;let v=bignumber.gH.from(value);try{return v.toNumber()}catch(error){}return null}uint256(value){if(!(0,bytes_lib_esm.isHexString)(value))throw Error("invalid uint256");return(0,bytes_lib_esm.hexZeroPad)(value,32)}_block(value,format){null!=value.author&&null==value.miner&&(value.miner=value.author);let difficulty=null!=value._difficulty?value._difficulty:value.difficulty,result=Formatter.check(format,value);return result._difficulty=null==difficulty?null:bignumber.gH.from(difficulty),result}block(value){return this._block(value,this.formats.block)}blockWithTransactions(value){return this._block(value,this.formats.blockWithTransactions)}transactionRequest(value){return Formatter.check(this.formats.transactionRequest,value)}transactionResponse(transaction){null!=transaction.gas&&null==transaction.gasLimit&&(transaction.gasLimit=transaction.gas),transaction.to&&bignumber.gH.from(transaction.to).isZero()&&(transaction.to="0x0000000000000000000000000000000000000000"),null!=transaction.input&&null==transaction.data&&(transaction.data=transaction.input),null==transaction.to&&null==transaction.creates&&(transaction.creates=this.contractAddress(transaction)),(1===transaction.type||2===transaction.type)&&null==transaction.accessList&&(transaction.accessList=[]);let result=Formatter.check(this.formats.transaction,transaction);if(null!=transaction.chainId){let chainId=transaction.chainId;(0,bytes_lib_esm.isHexString)(chainId)&&(chainId=bignumber.gH.from(chainId).toNumber()),result.chainId=chainId}else{let chainId=transaction.networkId;null==chainId&&null==result.v&&(chainId=transaction.chainId),(0,bytes_lib_esm.isHexString)(chainId)&&(chainId=bignumber.gH.from(chainId).toNumber()),"number"!=typeof chainId&&null!=result.v&&((chainId=(result.v-35)/2)<0&&(chainId=0),chainId=parseInt(chainId)),"number"!=typeof chainId&&(chainId=0),result.chainId=chainId}return result.blockHash&&"x"===result.blockHash.replace(/0/g,"")&&(result.blockHash=null),result}transaction(value){return(0,transactions_lib_esm.parse)(value)}receiptLog(value){return Formatter.check(this.formats.receiptLog,value)}receipt(value){let result=Formatter.check(this.formats.receipt,value);if(null!=result.root){if(result.root.length<=4){let value=bignumber.gH.from(result.root).toNumber();0===value||1===value?(null!=result.status&&result.status!==value&&formatter_logger.throwArgumentError("alt-root-status/status mismatch","value",{root:result.root,status:result.status}),result.status=value,delete result.root):formatter_logger.throwArgumentError("invalid alt-root-status","value.root",result.root)}else 66!==result.root.length&&formatter_logger.throwArgumentError("invalid root hash","value.root",result.root)}return null!=result.status&&(result.byzantium=!0),result}topics(value){return Array.isArray(value)?value.map(v=>this.topics(v)):null!=value?this.hash(value,!0):null}filter(value){return Formatter.check(this.formats.filter,value)}filterLog(value){return Formatter.check(this.formats.filterLog,value)}static check(format,object){let result={};for(let key in format)try{let value=format[key](object[key]);void 0!==value&&(result[key]=value)}catch(error){throw error.checkKey=key,error.checkValue=object[key],error}return result}static allowNull(format,nullValue){return function(value){return null==value?nullValue:format(value)}}static allowFalsish(format,replaceValue){return function(value){return value?format(value):replaceValue}}static arrayOf(format){return function(array){if(!Array.isArray(array))throw Error("not an array");let result=[];return array.forEach(function(value){result.push(format(value))}),result}}}var base_provider_awaiter=function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};let base_provider_logger=new logger_lib_esm.Logger(_version.r);function checkTopic(topic){return null==topic?"null":(32!==(0,bytes_lib_esm.hexDataLength)(topic)&&base_provider_logger.throwArgumentError("invalid topic","topic",topic),topic.toLowerCase())}function serializeTopics(topics){for(topics=topics.slice();topics.length>0&&null==topics[topics.length-1];)topics.pop();return topics.map(topic=>{if(!Array.isArray(topic))return checkTopic(topic);{let unique={};topic.forEach(topic=>{unique[checkTopic(topic)]=!0});let sorted=Object.keys(unique);return sorted.sort(),sorted.join("|")}}).join("&")}function deserializeTopics(data){return""===data?[]:data.split(/&/g).map(topic=>{if(""===topic)return[];let comps=topic.split("|").map(topic=>"null"===topic?null:topic);return 1===comps.length?comps[0]:comps})}function getEventTag(eventName){if("string"==typeof eventName){if(eventName=eventName.toLowerCase(),32===(0,bytes_lib_esm.hexDataLength)(eventName))return"tx:"+eventName;if(-1===eventName.indexOf(":"))return eventName}else if(Array.isArray(eventName))return"filter:*:"+serializeTopics(eventName);else if(abstract_provider_lib_esm.Rj.isForkEvent(eventName))throw base_provider_logger.warn("not implemented"),Error("not implemented");else if(eventName&&"object"==typeof eventName)return"filter:"+(eventName.address||"*")+":"+serializeTopics(eventName.topics||[]);throw Error("invalid event - "+eventName)}function getTime(){return new Date().getTime()}function stall(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}let PollableEvents=["block","network","pending","poll"];class Event{constructor(tag,listener,once){(0,properties_lib_esm.defineReadOnly)(this,"tag",tag),(0,properties_lib_esm.defineReadOnly)(this,"listener",listener),(0,properties_lib_esm.defineReadOnly)(this,"once",once),this._lastBlockNumber=-2,this._inflight=!1}get event(){switch(this.type){case"tx":return this.hash;case"filter":return this.filter}return this.tag}get type(){return this.tag.split(":")[0]}get hash(){let comps=this.tag.split(":");return"tx"!==comps[0]?null:comps[1]}get filter(){let comps=this.tag.split(":");if("filter"!==comps[0])return null;let address=comps[1],topics=deserializeTopics(comps[2]),filter={};return topics.length>0&&(filter.topics=topics),address&&"*"!==address&&(filter.address=address),filter}pollable(){return this.tag.indexOf(":")>=0||PollableEvents.indexOf(this.tag)>=0}}let coinInfos={0:{symbol:"btc",p2pkh:0,p2sh:5,prefix:"bc"},2:{symbol:"ltc",p2pkh:48,p2sh:50,prefix:"ltc"},3:{symbol:"doge",p2pkh:30,p2sh:22},60:{symbol:"eth",ilk:"eth"},61:{symbol:"etc",ilk:"eth"},700:{symbol:"xdai",ilk:"eth"}};function bytes32ify(value){return(0,bytes_lib_esm.hexZeroPad)(bignumber.gH.from(value).toHexString(),32)}function base58Encode(data){return basex_lib_esm.Base58.encode((0,bytes_lib_esm.concat)([data,(0,bytes_lib_esm.hexDataSlice)((0,sha2.sc)((0,sha2.sc)(data)),0,4)]))}let matcherIpfs=RegExp("^(ipfs)://(.*)$","i"),matchers=[RegExp("^(https)://(.*)$","i"),RegExp("^(data):(.*)$","i"),matcherIpfs,RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function _parseString(result,start){try{return(0,utf8._v)(_parseBytes(result,start))}catch(error){}return null}function _parseBytes(result,start){if("0x"===result)return null;let offset=bignumber.gH.from((0,bytes_lib_esm.hexDataSlice)(result,start,start+32)).toNumber(),length=bignumber.gH.from((0,bytes_lib_esm.hexDataSlice)(result,offset,offset+32)).toNumber();return(0,bytes_lib_esm.hexDataSlice)(result,offset+32,offset+32+length)}function getIpfsLink(link){return link.match(/^ipfs:\/\/ipfs\//i)?link=link.substring(12):link.match(/^ipfs:\/\//i)?link=link.substring(7):base_provider_logger.throwArgumentError("unsupported IPFS format","link",link),`https://gateway.ipfs.io/ipfs/${link}`}function numPad(value){let result=(0,bytes_lib_esm.arrayify)(value);if(result.length>32)throw Error("internal; should not happen");let padded=new Uint8Array(32);return padded.set(result,32-result.length),padded}function bytesPad(value){if(value.length%32==0)return value;let result=new Uint8Array(32*Math.ceil(value.length/32));return result.set(value),result}function encodeBytes(datas){let result=[],byteCount=0;for(let i=0;i<datas.length;i++)result.push(null),byteCount+=32;for(let i=0;i<datas.length;i++){let data=(0,bytes_lib_esm.arrayify)(datas[i]);result[i]=numPad(byteCount),result.push(numPad(data.length)),result.push(bytesPad(data)),byteCount+=32+32*Math.ceil(data.length/32)}return(0,bytes_lib_esm.hexConcat)(result)}class Resolver{constructor(provider,address,name,resolvedAddress){(0,properties_lib_esm.defineReadOnly)(this,"provider",provider),(0,properties_lib_esm.defineReadOnly)(this,"name",name),(0,properties_lib_esm.defineReadOnly)(this,"address",provider.formatter.address(address)),(0,properties_lib_esm.defineReadOnly)(this,"_resolvedAddress",resolvedAddress)}supportsWildcard(){return this._supportsEip2544||(this._supportsEip2544=this.provider.call({to:this.address,data:"0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"}).then(result=>bignumber.gH.from(result).eq(1)).catch(error=>{if(error.code===logger_lib_esm.Logger.errors.CALL_EXCEPTION)return!1;throw this._supportsEip2544=null,error})),this._supportsEip2544}_fetch(selector,parameters){return base_provider_awaiter(this,void 0,void 0,function*(){let tx={to:this.address,ccipReadEnabled:!0,data:(0,bytes_lib_esm.hexConcat)([selector,(0,namehash.kM)(this.name),parameters||"0x"])},parseBytes=!1;(yield this.supportsWildcard())&&(parseBytes=!0,tx.data=(0,bytes_lib_esm.hexConcat)(["0x9061b923",encodeBytes([(0,namehash.Wh)(this.name),tx.data])]));try{let result=yield this.provider.call(tx);return(0,bytes_lib_esm.arrayify)(result).length%32==4&&base_provider_logger.throwError("resolver threw error",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{transaction:tx,data:result}),parseBytes&&(result=_parseBytes(result,0)),result}catch(error){if(error.code===logger_lib_esm.Logger.errors.CALL_EXCEPTION)return null;throw error}})}_fetchBytes(selector,parameters){return base_provider_awaiter(this,void 0,void 0,function*(){let result=yield this._fetch(selector,parameters);return null!=result?_parseBytes(result,0):null})}_getAddress(coinType,hexBytes){let coinInfo=coinInfos[String(coinType)];if(null==coinInfo&&base_provider_logger.throwError(`unsupported coin type: ${coinType}`,logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${coinType})`}),"eth"===coinInfo.ilk)return this.provider.formatter.address(hexBytes);let bytes=(0,bytes_lib_esm.arrayify)(hexBytes);if(null!=coinInfo.p2pkh){let p2pkh=hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);if(p2pkh){let length=parseInt(p2pkh[1],16);if(p2pkh[2].length===2*length&&length>=1&&length<=75)return base58Encode((0,bytes_lib_esm.concat)([[coinInfo.p2pkh],"0x"+p2pkh[2]]))}}if(null!=coinInfo.p2sh){let p2sh=hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);if(p2sh){let length=parseInt(p2sh[1],16);if(p2sh[2].length===2*length&&length>=1&&length<=75)return base58Encode((0,bytes_lib_esm.concat)([[coinInfo.p2sh],"0x"+p2sh[2]]))}}if(null!=coinInfo.prefix){let length=bytes[1],version=bytes[0];if(0===version?20!==length&&32!==length&&(version=-1):version=-1,version>=0&&bytes.length===2+length&&length>=1&&length<=75){let words=bech32_default().toWords(bytes.slice(2));return words.unshift(version),bech32_default().encode(coinInfo.prefix,words)}}return null}getAddress(coinType){return base_provider_awaiter(this,void 0,void 0,function*(){if(null==coinType&&(coinType=60),60===coinType)try{let result=yield this._fetch("0x3b3b57de");if("0x"===result||result===hashes.j)return null;return this.provider.formatter.callAddress(result)}catch(error){if(error.code===logger_lib_esm.Logger.errors.CALL_EXCEPTION)return null;throw error}let hexBytes=yield this._fetchBytes("0xf1cb7e06",bytes32ify(coinType));if(null==hexBytes||"0x"===hexBytes)return null;let address=this._getAddress(coinType,hexBytes);return null==address&&base_provider_logger.throwError("invalid or unsupported coin data",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${coinType})`,coinType:coinType,data:hexBytes}),address})}getAvatar(){return base_provider_awaiter(this,void 0,void 0,function*(){let linkage=[{type:"name",content:this.name}];try{let avatar=yield this.getText("avatar");if(null==avatar)return null;for(let i=0;i<matchers.length;i++){let match=avatar.match(matchers[i]);if(null==match)continue;let scheme=match[1].toLowerCase();switch(scheme){case"https":return linkage.push({type:"url",content:avatar}),{linkage,url:avatar};case"data":return linkage.push({type:"data",content:avatar}),{linkage,url:avatar};case"ipfs":return linkage.push({type:"ipfs",content:avatar}),{linkage,url:getIpfsLink(avatar)};case"erc721":case"erc1155":{let selector="erc721"===scheme?"0xc87b56dd":"0x0e89341c";linkage.push({type:scheme,content:avatar});let owner=this._resolvedAddress||(yield this.getAddress()),comps=(match[2]||"").split("/");if(2!==comps.length)return null;let addr=yield this.provider.formatter.address(comps[0]),tokenId=(0,bytes_lib_esm.hexZeroPad)(bignumber.gH.from(comps[1]).toHexString(),32);if("erc721"===scheme){let tokenOwner=this.provider.formatter.callAddress((yield this.provider.call({to:addr,data:(0,bytes_lib_esm.hexConcat)(["0x6352211e",tokenId])})));if(owner!==tokenOwner)return null;linkage.push({type:"owner",content:tokenOwner})}else if("erc1155"===scheme){let balance=bignumber.gH.from((yield this.provider.call({to:addr,data:(0,bytes_lib_esm.hexConcat)(["0x00fdd58e",(0,bytes_lib_esm.hexZeroPad)(owner,32),tokenId])})));if(balance.isZero())return null;linkage.push({type:"balance",content:balance.toString()})}let tx={to:this.provider.formatter.address(comps[0]),data:(0,bytes_lib_esm.hexConcat)([selector,tokenId])},metadataUrl=_parseString((yield this.provider.call(tx)),0);if(null==metadataUrl)return null;linkage.push({type:"metadata-url-base",content:metadataUrl}),"erc1155"===scheme&&(metadataUrl=metadataUrl.replace("{id}",tokenId.substring(2)),linkage.push({type:"metadata-url-expanded",content:metadataUrl})),metadataUrl.match(/^ipfs:/i)&&(metadataUrl=getIpfsLink(metadataUrl)),linkage.push({type:"metadata-url",content:metadataUrl});let metadata=yield fetchJson(metadataUrl);if(!metadata)return null;linkage.push({type:"metadata",content:JSON.stringify(metadata)});let imageUrl=metadata.image;if("string"!=typeof imageUrl)return null;if(imageUrl.match(/^(https:\/\/|data:)/i));else{let ipfs=imageUrl.match(matcherIpfs);if(null==ipfs)return null;linkage.push({type:"url-ipfs",content:imageUrl}),imageUrl=getIpfsLink(imageUrl)}return linkage.push({type:"url",content:imageUrl}),{linkage,url:imageUrl}}}}}catch(error){}return null})}getContentHash(){return base_provider_awaiter(this,void 0,void 0,function*(){let hexBytes=yield this._fetchBytes("0xbc1c58d1");if(null==hexBytes||"0x"===hexBytes)return null;let ipfs=hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(ipfs){let length=parseInt(ipfs[3],16);if(ipfs[4].length===2*length)return"ipfs://"+basex_lib_esm.Base58.encode("0x"+ipfs[1])}let ipns=hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(ipns){let length=parseInt(ipns[3],16);if(ipns[4].length===2*length)return"ipns://"+basex_lib_esm.Base58.encode("0x"+ipns[1])}let swarm=hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(swarm&&64===swarm[1].length)return"bzz://"+swarm[1];let skynet=hexBytes.match(/^0x90b2c605([0-9a-f]*)$/);if(skynet&&68===skynet[1].length){let urlSafe={"=":"","+":"-","/":"_"};return"sia://"+(0,base64.l)("0x"+skynet[1]).replace(/[=+\/]/g,a=>urlSafe[a])}return base_provider_logger.throwError("invalid or unsupported content hash data",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:"getContentHash()",data:hexBytes})})}getText(key){return base_provider_awaiter(this,void 0,void 0,function*(){let keyBytes=(0,utf8.YW)(key);(keyBytes=(0,bytes_lib_esm.concat)([bytes32ify(64),bytes32ify(keyBytes.length),keyBytes])).length%32!=0&&(keyBytes=(0,bytes_lib_esm.concat)([keyBytes,(0,bytes_lib_esm.hexZeroPad)("0x",32-key.length%32)]));let hexBytes=yield this._fetchBytes("0x59d1d43c",(0,bytes_lib_esm.hexlify)(keyBytes));return null==hexBytes||"0x"===hexBytes?null:(0,utf8._v)(hexBytes)})}}let defaultFormatter=null,nextPollId=1;class BaseProvider extends abstract_provider_lib_esm.Kq{constructor(network){if(super(),this._events=[],this._emitted={block:-2},this.disableCcipRead=!1,this.formatter=new.target.getFormatter(),(0,properties_lib_esm.defineReadOnly)(this,"anyNetwork","any"===network),this.anyNetwork&&(network=this.detectNetwork()),network instanceof Promise)this._networkPromise=network,network.catch(error=>{}),this._ready().catch(error=>{});else{let knownNetwork=(0,properties_lib_esm.getStatic)(new.target,"getNetwork")(network);knownNetwork?((0,properties_lib_esm.defineReadOnly)(this,"_network",knownNetwork),this.emit("network",knownNetwork,null)):base_provider_logger.throwArgumentError("invalid network","network",network)}this._maxInternalBlockNumber=-1024,this._lastBlockNumber=-2,this._maxFilterBlockRange=10,this._pollingInterval=4e3,this._fastQueryDate=0}_ready(){return base_provider_awaiter(this,void 0,void 0,function*(){if(null==this._network){let network=null;if(this._networkPromise)try{network=yield this._networkPromise}catch(error){}null==network&&(network=yield this.detectNetwork()),network||base_provider_logger.throwError("no network detected",logger_lib_esm.Logger.errors.UNKNOWN_ERROR,{}),null==this._network&&(this.anyNetwork?this._network=network:(0,properties_lib_esm.defineReadOnly)(this,"_network",network),this.emit("network",network,null))}return this._network})}get ready(){return poll(()=>this._ready().then(network=>network,error=>{if(error.code!==logger_lib_esm.Logger.errors.NETWORK_ERROR||"noNetwork"!==error.event)throw error}))}static getFormatter(){return null==defaultFormatter&&(defaultFormatter=new Formatter),defaultFormatter}static getNetwork(network){return getNetwork(null==network?"homestead":network)}ccipReadFetch(tx,calldata,urls){return base_provider_awaiter(this,void 0,void 0,function*(){if(this.disableCcipRead||0===urls.length)return null;let sender=tx.to.toLowerCase(),data=calldata.toLowerCase(),errorMessages=[];for(let i=0;i<urls.length;i++){let url=urls[i],href=url.replace("{sender}",sender).replace("{data}",data),json=url.indexOf("{data}")>=0?null:JSON.stringify({data,sender}),result=yield fetchJson({url:href,errorPassThrough:!0},json,(value,response)=>(value.status=response.statusCode,value));if(result.data)return result.data;let errorMessage=result.message||"unknown error";if(result.status>=400&&result.status<500)return base_provider_logger.throwError(`response not found during CCIP fetch: ${errorMessage}`,logger_lib_esm.Logger.errors.SERVER_ERROR,{url,errorMessage});errorMessages.push(errorMessage)}return base_provider_logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map(m=>JSON.stringify(m)).join(", ")}`,logger_lib_esm.Logger.errors.SERVER_ERROR,{urls,errorMessages})})}_getInternalBlockNumber(maxAge){return base_provider_awaiter(this,void 0,void 0,function*(){if(yield this._ready(),maxAge>0)for(;this._internalBlockNumber;){let internalBlockNumber=this._internalBlockNumber;try{let result=yield internalBlockNumber;if(getTime()-result.respTime<=maxAge)return result.blockNumber;break}catch(error){if(this._internalBlockNumber===internalBlockNumber)break}}let reqTime=getTime(),checkInternalBlockNumber=(0,properties_lib_esm.resolveProperties)({blockNumber:this.perform("getBlockNumber",{}),networkError:this.getNetwork().then(network=>null,error=>error)}).then(({blockNumber,networkError})=>{if(networkError)throw this._internalBlockNumber===checkInternalBlockNumber&&(this._internalBlockNumber=null),networkError;let respTime=getTime();return(blockNumber=bignumber.gH.from(blockNumber).toNumber())<this._maxInternalBlockNumber&&(blockNumber=this._maxInternalBlockNumber),this._maxInternalBlockNumber=blockNumber,this._setFastBlockNumber(blockNumber),{blockNumber,reqTime,respTime}});return this._internalBlockNumber=checkInternalBlockNumber,checkInternalBlockNumber.catch(error=>{this._internalBlockNumber===checkInternalBlockNumber&&(this._internalBlockNumber=null)}),(yield checkInternalBlockNumber).blockNumber})}poll(){return base_provider_awaiter(this,void 0,void 0,function*(){let pollId=nextPollId++,runners=[],blockNumber=null;try{blockNumber=yield this._getInternalBlockNumber(100+this.pollingInterval/2)}catch(error){this.emit("error",error);return}if(this._setFastBlockNumber(blockNumber),this.emit("poll",pollId,blockNumber),blockNumber===this._lastBlockNumber){this.emit("didPoll",pollId);return}if(-2===this._emitted.block&&(this._emitted.block=blockNumber-1),Math.abs(this._emitted.block-blockNumber)>1e3)base_provider_logger.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`),this.emit("error",base_provider_logger.makeError("network block skew detected",logger_lib_esm.Logger.errors.NETWORK_ERROR,{blockNumber:blockNumber,event:"blockSkew",previousBlockNumber:this._emitted.block})),this.emit("block",blockNumber);else for(let i=this._emitted.block+1;i<=blockNumber;i++)this.emit("block",i);this._emitted.block!==blockNumber&&(this._emitted.block=blockNumber,Object.keys(this._emitted).forEach(key=>{if("block"===key)return;let eventBlockNumber=this._emitted[key];"pending"!==eventBlockNumber&&blockNumber-eventBlockNumber>12&&delete this._emitted[key]})),-2===this._lastBlockNumber&&(this._lastBlockNumber=blockNumber-1),this._events.forEach(event=>{switch(event.type){case"tx":{let hash=event.hash,runner=this.getTransactionReceipt(hash).then(receipt=>(receipt&&null!=receipt.blockNumber&&(this._emitted["t:"+hash]=receipt.blockNumber,this.emit(hash,receipt)),null)).catch(error=>{this.emit("error",error)});runners.push(runner);break}case"filter":if(!event._inflight){event._inflight=!0,-2===event._lastBlockNumber&&(event._lastBlockNumber=blockNumber-1);let filter=event.filter;filter.fromBlock=event._lastBlockNumber+1,filter.toBlock=blockNumber;let minFromBlock=filter.toBlock-this._maxFilterBlockRange;minFromBlock>filter.fromBlock&&(filter.fromBlock=minFromBlock),filter.fromBlock<0&&(filter.fromBlock=0);let runner=this.getLogs(filter).then(logs=>{event._inflight=!1,0!==logs.length&&logs.forEach(log=>{log.blockNumber>event._lastBlockNumber&&(event._lastBlockNumber=log.blockNumber),this._emitted["b:"+log.blockHash]=log.blockNumber,this._emitted["t:"+log.transactionHash]=log.blockNumber,this.emit(filter,log)})}).catch(error=>{this.emit("error",error),event._inflight=!1});runners.push(runner)}}}),this._lastBlockNumber=blockNumber,Promise.all(runners).then(()=>{this.emit("didPoll",pollId)}).catch(error=>{this.emit("error",error)})})}resetEventsBlock(blockNumber){this._lastBlockNumber=blockNumber-1,this.polling&&this.poll()}get network(){return this._network}detectNetwork(){return base_provider_awaiter(this,void 0,void 0,function*(){return base_provider_logger.throwError("provider does not support network detection",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:"provider.detectNetwork"})})}getNetwork(){return base_provider_awaiter(this,void 0,void 0,function*(){let network=yield this._ready(),currentNetwork=yield this.detectNetwork();if(network.chainId!==currentNetwork.chainId){if(this.anyNetwork)return this._network=currentNetwork,this._lastBlockNumber=-2,this._fastBlockNumber=null,this._fastBlockNumberPromise=null,this._fastQueryDate=0,this._emitted.block=-2,this._maxInternalBlockNumber=-1024,this._internalBlockNumber=null,this.emit("network",currentNetwork,network),yield stall(0),this._network;let error=base_provider_logger.makeError("underlying network changed",logger_lib_esm.Logger.errors.NETWORK_ERROR,{event:"changed",network:network,detectedNetwork:currentNetwork});throw this.emit("error",error),error}return network})}get blockNumber(){return this._getInternalBlockNumber(100+this.pollingInterval/2).then(blockNumber=>{this._setFastBlockNumber(blockNumber)},error=>{}),null!=this._fastBlockNumber?this._fastBlockNumber:-1}get polling(){return null!=this._poller}set polling(value){value&&!this._poller?(this._poller=setInterval(()=>{this.poll()},this.pollingInterval),this._bootstrapPoll||(this._bootstrapPoll=setTimeout(()=>{this.poll(),this._bootstrapPoll=setTimeout(()=>{this._poller||this.poll(),this._bootstrapPoll=null},this.pollingInterval)},0))):!value&&this._poller&&(clearInterval(this._poller),this._poller=null)}get pollingInterval(){return this._pollingInterval}set pollingInterval(value){if("number"!=typeof value||value<=0||parseInt(String(value))!=value)throw Error("invalid polling interval");this._pollingInterval=value,this._poller&&(clearInterval(this._poller),this._poller=setInterval(()=>{this.poll()},this._pollingInterval))}_getFastBlockNumber(){let now=getTime();return now-this._fastQueryDate>2*this._pollingInterval&&(this._fastQueryDate=now,this._fastBlockNumberPromise=this.getBlockNumber().then(blockNumber=>((null==this._fastBlockNumber||blockNumber>this._fastBlockNumber)&&(this._fastBlockNumber=blockNumber),this._fastBlockNumber))),this._fastBlockNumberPromise}_setFastBlockNumber(blockNumber){(null==this._fastBlockNumber||!(blockNumber<this._fastBlockNumber))&&(this._fastQueryDate=getTime(),(null==this._fastBlockNumber||blockNumber>this._fastBlockNumber)&&(this._fastBlockNumber=blockNumber,this._fastBlockNumberPromise=Promise.resolve(blockNumber)))}waitForTransaction(transactionHash,confirmations,timeout){return base_provider_awaiter(this,void 0,void 0,function*(){return this._waitForTransaction(transactionHash,null==confirmations?1:confirmations,timeout||0,null)})}_waitForTransaction(transactionHash,confirmations,timeout,replaceable){return base_provider_awaiter(this,void 0,void 0,function*(){let receipt=yield this.getTransactionReceipt(transactionHash);return(receipt?receipt.confirmations:0)>=confirmations?receipt:new Promise((resolve,reject)=>{let cancelFuncs=[],done=!1,alreadyDone=function(){return!!done||(done=!0,cancelFuncs.forEach(func=>{func()}),!1)},minedHandler=receipt=>{receipt.confirmations<confirmations||alreadyDone()||resolve(receipt)};if(this.on(transactionHash,minedHandler),cancelFuncs.push(()=>{this.removeListener(transactionHash,minedHandler)}),replaceable){let lastBlockNumber=replaceable.startBlock,scannedBlock=null,replaceHandler=blockNumber=>base_provider_awaiter(this,void 0,void 0,function*(){done||(yield stall(1e3),this.getTransactionCount(replaceable.from).then(nonce=>base_provider_awaiter(this,void 0,void 0,function*(){if(!done){if(nonce<=replaceable.nonce)lastBlockNumber=blockNumber;else{{let mined=yield this.getTransaction(transactionHash);if(mined&&null!=mined.blockNumber)return}for(null==scannedBlock&&(scannedBlock=lastBlockNumber-3)<replaceable.startBlock&&(scannedBlock=replaceable.startBlock);scannedBlock<=blockNumber;){if(done)return;let block=yield this.getBlockWithTransactions(scannedBlock);for(let ti=0;ti<block.transactions.length;ti++){let tx=block.transactions[ti];if(tx.hash===transactionHash)return;if(tx.from===replaceable.from&&tx.nonce===replaceable.nonce){if(done)return;let receipt=yield this.waitForTransaction(tx.hash,confirmations);if(alreadyDone())return;let reason="replaced";tx.data===replaceable.data&&tx.to===replaceable.to&&tx.value.eq(replaceable.value)?reason="repriced":"0x"===tx.data&&tx.from===tx.to&&tx.value.isZero()&&(reason="cancelled"),reject(base_provider_logger.makeError("transaction was replaced",logger_lib_esm.Logger.errors.TRANSACTION_REPLACED,{cancelled:"replaced"===reason||"cancelled"===reason,reason,replacement:this._wrapTransaction(tx),hash:transactionHash,receipt}));return}}scannedBlock++}}done||this.once("block",replaceHandler)}}),error=>{done||this.once("block",replaceHandler)}))});if(done)return;this.once("block",replaceHandler),cancelFuncs.push(()=>{this.removeListener("block",replaceHandler)})}if("number"==typeof timeout&&timeout>0){let timer=setTimeout(()=>{alreadyDone()||reject(base_provider_logger.makeError("timeout exceeded",logger_lib_esm.Logger.errors.TIMEOUT,{timeout:timeout}))},timeout);timer.unref&&timer.unref(),cancelFuncs.push(()=>{clearTimeout(timer)})}})})}getBlockNumber(){return base_provider_awaiter(this,void 0,void 0,function*(){return this._getInternalBlockNumber(0)})}getGasPrice(){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let result=yield this.perform("getGasPrice",{});try{return bignumber.gH.from(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"getGasPrice",result,error})}})}getBalance(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getBalance",params);try{return bignumber.gH.from(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"getBalance",params,result,error})}})}getTransactionCount(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getTransactionCount",params);try{return bignumber.gH.from(result).toNumber()}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"getTransactionCount",params,result,error})}})}getCode(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getCode",params);try{return(0,bytes_lib_esm.hexlify)(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"getCode",params,result,error})}})}getStorageAt(addressOrName,position,blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag),position:Promise.resolve(position).then(p=>(0,bytes_lib_esm.hexValue)(p))}),result=yield this.perform("getStorageAt",params);try{return(0,bytes_lib_esm.hexlify)(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"getStorageAt",params,result,error})}})}_wrapTransaction(tx,hash,startBlock){if(null!=hash&&32!==(0,bytes_lib_esm.hexDataLength)(hash))throw Error("invalid response - sendTransaction");return null!=hash&&tx.hash!==hash&&base_provider_logger.throwError("Transaction hash mismatch from Provider.sendTransaction.",logger_lib_esm.Logger.errors.UNKNOWN_ERROR,{expectedHash:tx.hash,returnedHash:hash}),tx.wait=(confirms,timeout)=>base_provider_awaiter(this,void 0,void 0,function*(){let replacement;null==confirms&&(confirms=1),null==timeout&&(timeout=0),0!==confirms&&null!=startBlock&&(replacement={data:tx.data,from:tx.from,nonce:tx.nonce,to:tx.to,value:tx.value,startBlock});let receipt=yield this._waitForTransaction(tx.hash,confirms,timeout,replacement);return null==receipt&&0===confirms?null:(this._emitted["t:"+tx.hash]=receipt.blockNumber,0===receipt.status&&base_provider_logger.throwError("transaction failed",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{transactionHash:tx.hash,transaction:tx,receipt:receipt}),receipt)}),tx}sendTransaction(signedTransaction){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let hexTx=yield Promise.resolve(signedTransaction).then(t=>(0,bytes_lib_esm.hexlify)(t)),tx=this.formatter.transaction(signedTransaction);null==tx.confirmations&&(tx.confirmations=0);let blockNumber=yield this._getInternalBlockNumber(100+2*this.pollingInterval);try{let hash=yield this.perform("sendTransaction",{signedTransaction:hexTx});return this._wrapTransaction(tx,hash,blockNumber)}catch(error){throw error.transaction=tx,error.transactionHash=tx.hash,error}})}_getTransactionRequest(transaction){return base_provider_awaiter(this,void 0,void 0,function*(){let values=yield transaction,tx={};return["from","to"].forEach(key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then(v=>v?this._getAddress(v):null))}),["gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","value"].forEach(key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then(v=>v?bignumber.gH.from(v):null))}),["type"].forEach(key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then(v=>null!=v?v:null))}),values.accessList&&(tx.accessList=this.formatter.accessList(values.accessList)),["data"].forEach(key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then(v=>v?(0,bytes_lib_esm.hexlify)(v):null))}),this.formatter.transactionRequest((yield(0,properties_lib_esm.resolveProperties)(tx)))})}_getFilter(filter){return base_provider_awaiter(this,void 0,void 0,function*(){filter=yield filter;let result={};return null!=filter.address&&(result.address=this._getAddress(filter.address)),["blockHash","topics"].forEach(key=>{null!=filter[key]&&(result[key]=filter[key])}),["fromBlock","toBlock"].forEach(key=>{null!=filter[key]&&(result[key]=this._getBlockTag(filter[key]))}),this.formatter.filter((yield(0,properties_lib_esm.resolveProperties)(result)))})}_call(transaction,blockTag,attempt){return base_provider_awaiter(this,void 0,void 0,function*(){attempt>=10&&base_provider_logger.throwError("CCIP read exceeded maximum redirections",logger_lib_esm.Logger.errors.SERVER_ERROR,{redirects:attempt,transaction});let txSender=transaction.to,result=yield this.perform("call",{transaction,blockTag});if(attempt>=0&&"latest"===blockTag&&null!=txSender&&"0x556f1830"===result.substring(0,10)&&(0,bytes_lib_esm.hexDataLength)(result)%32==4)try{let data=(0,bytes_lib_esm.hexDataSlice)(result,4),sender=(0,bytes_lib_esm.hexDataSlice)(data,0,32);bignumber.gH.from(sender).eq(txSender)||base_provider_logger.throwError("CCIP Read sender did not match",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction,data:result});let urls=[],urlsOffset=bignumber.gH.from((0,bytes_lib_esm.hexDataSlice)(data,32,64)).toNumber(),urlsLength=bignumber.gH.from((0,bytes_lib_esm.hexDataSlice)(data,urlsOffset,urlsOffset+32)).toNumber(),urlsData=(0,bytes_lib_esm.hexDataSlice)(data,urlsOffset+32);for(let u=0;u<urlsLength;u++){let url=_parseString(urlsData,32*u);null==url&&base_provider_logger.throwError("CCIP Read contained corrupt URL string",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction,data:result}),urls.push(url)}let calldata=_parseBytes(data,64);bignumber.gH.from((0,bytes_lib_esm.hexDataSlice)(data,100,128)).isZero()||base_provider_logger.throwError("CCIP Read callback selector included junk",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction,data:result});let callbackSelector=(0,bytes_lib_esm.hexDataSlice)(data,96,100),extraData=_parseBytes(data,128),ccipResult=yield this.ccipReadFetch(transaction,calldata,urls);null==ccipResult&&base_provider_logger.throwError("CCIP Read disabled or provided no URLs",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction,data:result});let tx={to:txSender,data:(0,bytes_lib_esm.hexConcat)([callbackSelector,encodeBytes([ccipResult,extraData])])};return this._call(tx,blockTag,attempt+1)}catch(error){if(error.code===logger_lib_esm.Logger.errors.SERVER_ERROR)throw error}try{return(0,bytes_lib_esm.hexlify)(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"call",params:{transaction,blockTag},result,error})}})}call(transaction,blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let resolved=yield(0,properties_lib_esm.resolveProperties)({transaction:this._getTransactionRequest(transaction),blockTag:this._getBlockTag(blockTag),ccipReadEnabled:Promise.resolve(transaction.ccipReadEnabled)});return this._call(resolved.transaction,resolved.blockTag,resolved.ccipReadEnabled?0:-1)})}estimateGas(transaction){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({transaction:this._getTransactionRequest(transaction)}),result=yield this.perform("estimateGas",params);try{return bignumber.gH.from(result)}catch(error){return base_provider_logger.throwError("bad result from backend",logger_lib_esm.Logger.errors.SERVER_ERROR,{method:"estimateGas",params,result,error})}})}_getAddress(addressOrName){return base_provider_awaiter(this,void 0,void 0,function*(){"string"!=typeof(addressOrName=yield addressOrName)&&base_provider_logger.throwArgumentError("invalid address or ENS name","name",addressOrName);let address=yield this.resolveName(addressOrName);return null==address&&base_provider_logger.throwError("ENS name not configured",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:`resolveName(${JSON.stringify(addressOrName)})`}),address})}_getBlock(blockHashOrBlockTag,includeTransactions){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork(),blockHashOrBlockTag=yield blockHashOrBlockTag;let blockNumber=-128,params={includeTransactions:!!includeTransactions};if((0,bytes_lib_esm.isHexString)(blockHashOrBlockTag,32))params.blockHash=blockHashOrBlockTag;else try{params.blockTag=yield this._getBlockTag(blockHashOrBlockTag),(0,bytes_lib_esm.isHexString)(params.blockTag)&&(blockNumber=parseInt(params.blockTag.substring(2),16))}catch(error){base_provider_logger.throwArgumentError("invalid block hash or block tag","blockHashOrBlockTag",blockHashOrBlockTag)}return poll(()=>base_provider_awaiter(this,void 0,void 0,function*(){let block=yield this.perform("getBlock",params);if(null==block)return null!=params.blockHash&&null==this._emitted["b:"+params.blockHash]||null!=params.blockTag&&blockNumber>this._emitted.block?null:void 0;if(includeTransactions){let blockNumber=null;for(let i=0;i<block.transactions.length;i++){let tx=block.transactions[i];if(null==tx.blockNumber)tx.confirmations=0;else if(null==tx.confirmations){null==blockNumber&&(blockNumber=yield this._getInternalBlockNumber(100+2*this.pollingInterval));let confirmations=blockNumber-tx.blockNumber+1;confirmations<=0&&(confirmations=1),tx.confirmations=confirmations}}let blockWithTxs=this.formatter.blockWithTransactions(block);return blockWithTxs.transactions=blockWithTxs.transactions.map(tx=>this._wrapTransaction(tx)),blockWithTxs}return this.formatter.block(block)}),{oncePoll:this})})}getBlock(blockHashOrBlockTag){return this._getBlock(blockHashOrBlockTag,!1)}getBlockWithTransactions(blockHashOrBlockTag){return this._getBlock(blockHashOrBlockTag,!0)}getTransaction(transactionHash){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork(),transactionHash=yield transactionHash;let params={transactionHash:this.formatter.hash(transactionHash,!0)};return poll(()=>base_provider_awaiter(this,void 0,void 0,function*(){let result=yield this.perform("getTransaction",params);if(null==result)return null==this._emitted["t:"+transactionHash]?null:void 0;let tx=this.formatter.transactionResponse(result);if(null==tx.blockNumber)tx.confirmations=0;else if(null==tx.confirmations){let confirmations=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-tx.blockNumber+1;confirmations<=0&&(confirmations=1),tx.confirmations=confirmations}return this._wrapTransaction(tx)}),{oncePoll:this})})}getTransactionReceipt(transactionHash){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork(),transactionHash=yield transactionHash;let params={transactionHash:this.formatter.hash(transactionHash,!0)};return poll(()=>base_provider_awaiter(this,void 0,void 0,function*(){let result=yield this.perform("getTransactionReceipt",params);if(null==result)return null==this._emitted["t:"+transactionHash]?null:void 0;if(null==result.blockHash)return;let receipt=this.formatter.receipt(result);if(null==receipt.blockNumber)receipt.confirmations=0;else if(null==receipt.confirmations){let confirmations=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-receipt.blockNumber+1;confirmations<=0&&(confirmations=1),receipt.confirmations=confirmations}return receipt}),{oncePoll:this})})}getLogs(filter){return base_provider_awaiter(this,void 0,void 0,function*(){yield this.getNetwork();let params=yield(0,properties_lib_esm.resolveProperties)({filter:this._getFilter(filter)}),logs=yield this.perform("getLogs",params);return logs.forEach(log=>{null==log.removed&&(log.removed=!1)}),Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs)})}getEtherPrice(){return base_provider_awaiter(this,void 0,void 0,function*(){return yield this.getNetwork(),this.perform("getEtherPrice",{})})}_getBlockTag(blockTag){return base_provider_awaiter(this,void 0,void 0,function*(){if("number"==typeof(blockTag=yield blockTag)&&blockTag<0){blockTag%1&&base_provider_logger.throwArgumentError("invalid BlockTag","blockTag",blockTag);let blockNumber=yield this._getInternalBlockNumber(100+2*this.pollingInterval);return(blockNumber+=blockTag)<0&&(blockNumber=0),this.formatter.blockTag(blockNumber)}return this.formatter.blockTag(blockTag)})}getResolver(name){return base_provider_awaiter(this,void 0,void 0,function*(){let currentName=name;for(;;){if(""===currentName||"."===currentName||"eth"!==name&&"eth"===currentName)return null;let addr=yield this._getResolver(currentName,"getResolver");if(null!=addr){let resolver=new Resolver(this,addr,name);if(currentName!==name&&!(yield resolver.supportsWildcard()))return null;return resolver}currentName=currentName.split(".").slice(1).join(".")}})}_getResolver(name,operation){return base_provider_awaiter(this,void 0,void 0,function*(){null==operation&&(operation="ENS");let network=yield this.getNetwork();network.ensAddress||base_provider_logger.throwError("network does not support ENS",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation,network:network.name});try{let addrData=yield this.call({to:network.ensAddress,data:"0x0178b8bf"+(0,namehash.kM)(name).substring(2)});return this.formatter.callAddress(addrData)}catch(error){}return null})}resolveName(name){return base_provider_awaiter(this,void 0,void 0,function*(){name=yield name;try{return Promise.resolve(this.formatter.address(name))}catch(error){if((0,bytes_lib_esm.isHexString)(name))throw error}"string"!=typeof name&&base_provider_logger.throwArgumentError("invalid ENS name","name",name);let resolver=yield this.getResolver(name);return resolver?yield resolver.getAddress():null})}lookupAddress(address){return base_provider_awaiter(this,void 0,void 0,function*(){address=yield address;let node=(address=this.formatter.address(address)).substring(2).toLowerCase()+".addr.reverse",resolverAddr=yield this._getResolver(node,"lookupAddress");if(null==resolverAddr)return null;let name=_parseString((yield this.call({to:resolverAddr,data:"0x691f3431"+(0,namehash.kM)(node).substring(2)})),0);return(yield this.resolveName(name))!=address?null:name})}getAvatar(nameOrAddress){return base_provider_awaiter(this,void 0,void 0,function*(){let resolver=null;if((0,bytes_lib_esm.isHexString)(nameOrAddress)){let node=this.formatter.address(nameOrAddress).substring(2).toLowerCase()+".addr.reverse",resolverAddress=yield this._getResolver(node,"getAvatar");if(!resolverAddress)return null;resolver=new Resolver(this,resolverAddress,node);try{let avatar=yield resolver.getAvatar();if(avatar)return avatar.url}catch(error){if(error.code!==logger_lib_esm.Logger.errors.CALL_EXCEPTION)throw error}try{let name=_parseString((yield this.call({to:resolverAddress,data:"0x691f3431"+(0,namehash.kM)(node).substring(2)})),0);resolver=yield this.getResolver(name)}catch(error){if(error.code!==logger_lib_esm.Logger.errors.CALL_EXCEPTION)throw error;return null}}else if(!(resolver=yield this.getResolver(nameOrAddress)))return null;let avatar=yield resolver.getAvatar();return null==avatar?null:avatar.url})}perform(method,params){return base_provider_logger.throwError(method+" not implemented",logger_lib_esm.Logger.errors.NOT_IMPLEMENTED,{operation:method})}_startEvent(event){this.polling=this._events.filter(e=>e.pollable()).length>0}_stopEvent(event){this.polling=this._events.filter(e=>e.pollable()).length>0}_addEventListener(eventName,listener,once){let event=new Event(getEventTag(eventName),listener,once);return this._events.push(event),this._startEvent(event),this}on(eventName,listener){return this._addEventListener(eventName,listener,!1)}once(eventName,listener){return this._addEventListener(eventName,listener,!0)}emit(eventName,...args){let result=!1,stopped=[],eventTag=getEventTag(eventName);return this._events=this._events.filter(event=>event.tag!==eventTag||(setTimeout(()=>{event.listener.apply(this,args)},0),result=!0,!event.once||(stopped.push(event),!1))),stopped.forEach(event=>{this._stopEvent(event)}),result}listenerCount(eventName){if(!eventName)return this._events.length;let eventTag=getEventTag(eventName);return this._events.filter(event=>event.tag===eventTag).length}listeners(eventName){if(null==eventName)return this._events.map(event=>event.listener);let eventTag=getEventTag(eventName);return this._events.filter(event=>event.tag===eventTag).map(event=>event.listener)}off(eventName,listener){if(null==listener)return this.removeAllListeners(eventName);let stopped=[],found=!1,eventTag=getEventTag(eventName);return this._events=this._events.filter(event=>event.tag!==eventTag||event.listener!=listener||!!found||(found=!0,stopped.push(event),!1)),stopped.forEach(event=>{this._stopEvent(event)}),this}removeAllListeners(eventName){let stopped=[];if(null==eventName)stopped=this._events,this._events=[];else{let eventTag=getEventTag(eventName);this._events=this._events.filter(event=>event.tag!==eventTag||(stopped.push(event),!1))}return stopped.forEach(event=>{this._stopEvent(event)}),this}}var json_rpc_provider_awaiter=function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};let json_rpc_provider_logger=new logger_lib_esm.Logger(_version.r),errorGas=["call","estimateGas"];function spelunk(value,requireData){if(null==value)return null;if("string"==typeof value.message&&value.message.match("reverted")){let data=(0,bytes_lib_esm.isHexString)(value.data)?value.data:null;if(!requireData||data)return{message:value.message,data}}if("object"==typeof value){for(let key in value){let result=spelunk(value[key],requireData);if(result)return result}return null}if("string"==typeof value)try{return spelunk(JSON.parse(value),requireData)}catch(error){}return null}function checkError(method,error,params){let transaction=params.transaction||params.signedTransaction;if("call"===method){let result=spelunk(error,!0);if(result)return result.data;json_rpc_provider_logger.throwError("missing revert data in call exception; Transaction reverted without a reason string",logger_lib_esm.Logger.errors.CALL_EXCEPTION,{data:"0x",transaction,error})}if("estimateGas"===method){let result=spelunk(error.body,!1);null==result&&(result=spelunk(error,!1)),result&&json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",logger_lib_esm.Logger.errors.UNPREDICTABLE_GAS_LIMIT,{reason:result.message,method,transaction,error})}let message=error.message;throw error.code===logger_lib_esm.Logger.errors.SERVER_ERROR&&error.error&&"string"==typeof error.error.message?message=error.error.message:"string"==typeof error.body?message=error.body:"string"==typeof error.responseText&&(message=error.responseText),(message=(message||"").toLowerCase()).match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)&&json_rpc_provider_logger.throwError("insufficient funds for intrinsic transaction cost",logger_lib_esm.Logger.errors.INSUFFICIENT_FUNDS,{error,method,transaction}),message.match(/nonce (is )?too low/i)&&json_rpc_provider_logger.throwError("nonce has already been used",logger_lib_esm.Logger.errors.NONCE_EXPIRED,{error,method,transaction}),message.match(/replacement transaction underpriced|transaction gas price.*too low/i)&&json_rpc_provider_logger.throwError("replacement fee too low",logger_lib_esm.Logger.errors.REPLACEMENT_UNDERPRICED,{error,method,transaction}),message.match(/only replay-protected/i)&&json_rpc_provider_logger.throwError("legacy pre-eip-155 transactions not supported",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{error,method,transaction}),errorGas.indexOf(method)>=0&&message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)&&json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",logger_lib_esm.Logger.errors.UNPREDICTABLE_GAS_LIMIT,{error,method,transaction}),error}function timer(timeout){return new Promise(function(resolve){setTimeout(resolve,timeout)})}function getResult(payload){if(payload.error){let error=Error(payload.error.message);throw error.code=payload.error.code,error.data=payload.error.data,error}return payload.result}function getLowerCase(value){return value?value.toLowerCase():value}let _constructorGuard={};class JsonRpcSigner extends lib_esm.l{constructor(constructorGuard,provider,addressOrIndex){if(super(),constructorGuard!==_constructorGuard)throw Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");(0,properties_lib_esm.defineReadOnly)(this,"provider",provider),null==addressOrIndex&&(addressOrIndex=0),"string"==typeof addressOrIndex?((0,properties_lib_esm.defineReadOnly)(this,"_address",this.provider.formatter.address(addressOrIndex)),(0,properties_lib_esm.defineReadOnly)(this,"_index",null)):"number"==typeof addressOrIndex?((0,properties_lib_esm.defineReadOnly)(this,"_index",addressOrIndex),(0,properties_lib_esm.defineReadOnly)(this,"_address",null)):json_rpc_provider_logger.throwArgumentError("invalid address or index","addressOrIndex",addressOrIndex)}connect(provider){return json_rpc_provider_logger.throwError("cannot alter JSON-RPC Signer connection",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:"connect"})}connectUnchecked(){return new UncheckedJsonRpcSigner(_constructorGuard,this.provider,this._address||this._index)}getAddress(){return this._address?Promise.resolve(this._address):this.provider.send("eth_accounts",[]).then(accounts=>(accounts.length<=this._index&&json_rpc_provider_logger.throwError("unknown account #"+this._index,logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:"getAddress"}),this.provider.formatter.address(accounts[this._index])))}sendUncheckedTransaction(transaction){transaction=(0,properties_lib_esm.shallowCopy)(transaction);let fromAddress=this.getAddress().then(address=>(address&&(address=address.toLowerCase()),address));if(null==transaction.gasLimit){let estimate=(0,properties_lib_esm.shallowCopy)(transaction);estimate.from=fromAddress,transaction.gasLimit=this.provider.estimateGas(estimate)}return null!=transaction.to&&(transaction.to=Promise.resolve(transaction.to).then(to=>json_rpc_provider_awaiter(this,void 0,void 0,function*(){if(null==to)return null;let address=yield this.provider.resolveName(to);return null==address&&json_rpc_provider_logger.throwArgumentError("provided ENS name resolves to null","tx.to",to),address}))),(0,properties_lib_esm.resolveProperties)({tx:(0,properties_lib_esm.resolveProperties)(transaction),sender:fromAddress}).then(({tx,sender})=>{null!=tx.from?tx.from.toLowerCase()!==sender&&json_rpc_provider_logger.throwArgumentError("from address mismatch","transaction",transaction):tx.from=sender;let hexTx=this.provider.constructor.hexlifyTransaction(tx,{from:!0});return this.provider.send("eth_sendTransaction",[hexTx]).then(hash=>hash,error=>("string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected transaction",logger_lib_esm.Logger.errors.ACTION_REJECTED,{action:"sendTransaction",transaction:tx}),checkError("sendTransaction",error,hexTx)))})}signTransaction(transaction){return json_rpc_provider_logger.throwError("signing transactions is unsupported",logger_lib_esm.Logger.errors.UNSUPPORTED_OPERATION,{operation:"signTransaction"})}sendTransaction(transaction){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){let blockNumber=yield this.provider._getInternalBlockNumber(100+2*this.provider.pollingInterval),hash=yield this.sendUncheckedTransaction(transaction);try{return yield poll(()=>json_rpc_provider_awaiter(this,void 0,void 0,function*(){let tx=yield this.provider.getTransaction(hash);if(null!==tx)return this.provider._wrapTransaction(tx,hash,blockNumber)}),{oncePoll:this.provider})}catch(error){throw error.transactionHash=hash,error}})}signMessage(message){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){let data="string"==typeof message?(0,utf8.YW)(message):message,address=yield this.getAddress();try{return yield this.provider.send("personal_sign",[(0,bytes_lib_esm.hexlify)(data),address.toLowerCase()])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",logger_lib_esm.Logger.errors.ACTION_REJECTED,{action:"signMessage",from:address,messageData:message}),error}})}_legacySignMessage(message){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){let data="string"==typeof message?(0,utf8.YW)(message):message,address=yield this.getAddress();try{return yield this.provider.send("eth_sign",[address.toLowerCase(),(0,bytes_lib_esm.hexlify)(data)])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",logger_lib_esm.Logger.errors.ACTION_REJECTED,{action:"_legacySignMessage",from:address,messageData:message}),error}})}_signTypedData(domain,types,value){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){let populated=yield typed_data.z.resolveNames(domain,types,value,name=>this.provider.resolveName(name)),address=yield this.getAddress();try{return yield this.provider.send("eth_signTypedData_v4",[address.toLowerCase(),JSON.stringify(typed_data.z.getPayload(populated.domain,types,populated.value))])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",logger_lib_esm.Logger.errors.ACTION_REJECTED,{action:"_signTypedData",from:address,messageData:{domain:populated.domain,types,value:populated.value}}),error}})}unlock(password){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){let provider=this.provider,address=yield this.getAddress();return provider.send("personal_unlockAccount",[address.toLowerCase(),password,null])})}}class UncheckedJsonRpcSigner extends JsonRpcSigner{sendTransaction(transaction){return this.sendUncheckedTransaction(transaction).then(hash=>({hash:hash,nonce:null,gasLimit:null,gasPrice:null,data:null,value:null,chainId:null,confirmations:0,from:null,wait:confirmations=>this.provider.waitForTransaction(hash,confirmations)}))}}let allowedTransactionKeys={chainId:!0,data:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,value:!0,type:!0,accessList:!0,maxFeePerGas:!0,maxPriorityFeePerGas:!0};class JsonRpcProvider extends BaseProvider{constructor(url,network){let networkOrReady=network;null==networkOrReady&&(networkOrReady=new Promise((resolve,reject)=>{setTimeout(()=>{this.detectNetwork().then(network=>{resolve(network)},error=>{reject(error)})},0)})),super(networkOrReady),url||(url=(0,properties_lib_esm.getStatic)(this.constructor,"defaultUrl")()),"string"==typeof url?(0,properties_lib_esm.defineReadOnly)(this,"connection",Object.freeze({url:url})):(0,properties_lib_esm.defineReadOnly)(this,"connection",Object.freeze((0,properties_lib_esm.shallowCopy)(url))),this._nextId=42}get _cache(){return null==this._eventLoopCache&&(this._eventLoopCache={}),this._eventLoopCache}static defaultUrl(){return"http://localhost:8545"}detectNetwork(){return this._cache.detectNetwork||(this._cache.detectNetwork=this._uncachedDetectNetwork(),setTimeout(()=>{this._cache.detectNetwork=null},0)),this._cache.detectNetwork}_uncachedDetectNetwork(){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){yield timer(0);let chainId=null;try{chainId=yield this.send("eth_chainId",[])}catch(error){try{chainId=yield this.send("net_version",[])}catch(error){}}if(null!=chainId){let getNetwork=(0,properties_lib_esm.getStatic)(this.constructor,"getNetwork");try{return getNetwork(bignumber.gH.from(chainId).toNumber())}catch(error){return json_rpc_provider_logger.throwError("could not detect network",logger_lib_esm.Logger.errors.NETWORK_ERROR,{chainId:chainId,event:"invalidNetwork",serverError:error})}}return json_rpc_provider_logger.throwError("could not detect network",logger_lib_esm.Logger.errors.NETWORK_ERROR,{event:"noNetwork"})})}getSigner(addressOrIndex){return new JsonRpcSigner(_constructorGuard,this,addressOrIndex)}getUncheckedSigner(addressOrIndex){return this.getSigner(addressOrIndex).connectUnchecked()}listAccounts(){return this.send("eth_accounts",[]).then(accounts=>accounts.map(a=>this.formatter.address(a)))}send(method,params){let request={method:method,params:params,id:this._nextId++,jsonrpc:"2.0"};this.emit("debug",{action:"request",request:(0,properties_lib_esm.deepCopy)(request),provider:this});let cache=["eth_chainId","eth_blockNumber"].indexOf(method)>=0;if(cache&&this._cache[method])return this._cache[method];let result=fetchJson(this.connection,JSON.stringify(request),getResult).then(result=>(this.emit("debug",{action:"response",request:request,response:result,provider:this}),result),error=>{throw this.emit("debug",{action:"response",error:error,request:request,provider:this}),error});return cache&&(this._cache[method]=result,setTimeout(()=>{this._cache[method]=null},0)),result}prepareRequest(method,params){switch(method){case"getBlockNumber":return["eth_blockNumber",[]];case"getGasPrice":return["eth_gasPrice",[]];case"getBalance":return["eth_getBalance",[getLowerCase(params.address),params.blockTag]];case"getTransactionCount":return["eth_getTransactionCount",[getLowerCase(params.address),params.blockTag]];case"getCode":return["eth_getCode",[getLowerCase(params.address),params.blockTag]];case"getStorageAt":return["eth_getStorageAt",[getLowerCase(params.address),(0,bytes_lib_esm.hexZeroPad)(params.position,32),params.blockTag]];case"sendTransaction":return["eth_sendRawTransaction",[params.signedTransaction]];case"getBlock":if(params.blockTag)return["eth_getBlockByNumber",[params.blockTag,!!params.includeTransactions]];if(params.blockHash)return["eth_getBlockByHash",[params.blockHash,!!params.includeTransactions]];break;case"getTransaction":return["eth_getTransactionByHash",[params.transactionHash]];case"getTransactionReceipt":return["eth_getTransactionReceipt",[params.transactionHash]];case"call":return["eth_call",[(0,properties_lib_esm.getStatic)(this.constructor,"hexlifyTransaction")(params.transaction,{from:!0}),params.blockTag]];case"estimateGas":return["eth_estimateGas",[(0,properties_lib_esm.getStatic)(this.constructor,"hexlifyTransaction")(params.transaction,{from:!0})]];case"getLogs":return params.filter&&null!=params.filter.address&&(params.filter.address=getLowerCase(params.filter.address)),["eth_getLogs",[params.filter]]}return null}perform(method,params){return json_rpc_provider_awaiter(this,void 0,void 0,function*(){if("call"===method||"estimateGas"===method){let tx=params.transaction;if(tx&&null!=tx.type&&bignumber.gH.from(tx.type).isZero()&&null==tx.maxFeePerGas&&null==tx.maxPriorityFeePerGas){let feeData=yield this.getFeeData();null==feeData.maxFeePerGas&&null==feeData.maxPriorityFeePerGas&&((params=(0,properties_lib_esm.shallowCopy)(params)).transaction=(0,properties_lib_esm.shallowCopy)(tx),delete params.transaction.type)}}let args=this.prepareRequest(method,params);null==args&&json_rpc_provider_logger.throwError(method+" not implemented",logger_lib_esm.Logger.errors.NOT_IMPLEMENTED,{operation:method});try{return yield this.send(args[0],args[1])}catch(error){return checkError(method,error,params)}})}_startEvent(event){"pending"===event.tag&&this._startPending(),super._startEvent(event)}_startPending(){if(null!=this._pendingFilter)return;let self=this,pendingFilter=this.send("eth_newPendingTransactionFilter",[]);this._pendingFilter=pendingFilter,pendingFilter.then(function(filterId){function poll(){self.send("eth_getFilterChanges",[filterId]).then(function(hashes){if(self._pendingFilter!=pendingFilter)return null;let seq=Promise.resolve();return hashes.forEach(function(hash){self._emitted["t:"+hash.toLowerCase()]="pending",seq=seq.then(function(){return self.getTransaction(hash).then(function(tx){return self.emit("pending",tx),null})})}),seq.then(function(){return timer(1e3)})}).then(function(){if(self._pendingFilter!=pendingFilter){self.send("eth_uninstallFilter",[filterId]);return}return setTimeout(function(){poll()},0),null}).catch(error=>{})}return poll(),filterId}).catch(error=>{})}_stopEvent(event){"pending"===event.tag&&0===this.listenerCount("pending")&&(this._pendingFilter=null),super._stopEvent(event)}static hexlifyTransaction(transaction,allowExtra){let allowed=(0,properties_lib_esm.shallowCopy)(allowedTransactionKeys);if(allowExtra)for(let key in allowExtra)allowExtra[key]&&(allowed[key]=!0);(0,properties_lib_esm.checkProperties)(transaction,allowed);let result={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(function(key){if(null==transaction[key])return;let value=(0,bytes_lib_esm.hexValue)(bignumber.gH.from(transaction[key]));"gasLimit"===key&&(key="gas"),result[key]=value}),["from","to","data"].forEach(function(key){null!=transaction[key]&&(result[key]=(0,bytes_lib_esm.hexlify)(transaction[key]))}),transaction.accessList&&(result.accessList=(0,transactions_lib_esm.accessListify)(transaction.accessList)),result}}},"./node_modules/@ethersproject/providers/node_modules/bech32/index.js":module=>{for(var ALPHABET="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ALPHABET_MAP={},z=0;z<ALPHABET.length;z++){var x=ALPHABET.charAt(z);if(void 0!==ALPHABET_MAP[x])throw TypeError(x+" is ambiguous");ALPHABET_MAP[x]=z}function polymodStep(pre){var b=pre>>25;return(33554431&pre)<<5^996825010&-(b>>0&1)^642813549&-(b>>1&1)^513874426&-(b>>2&1)^1027748829&-(b>>3&1)^705979059&-(b>>4&1)}function prefixChk(prefix){for(var chk=1,i=0;i<prefix.length;++i){var c=prefix.charCodeAt(i);if(c<33||c>126)return"Invalid prefix ("+prefix+")";chk=polymodStep(chk)^c>>5}for(i=0,chk=polymodStep(chk);i<prefix.length;++i){var v=prefix.charCodeAt(i);chk=polymodStep(chk)^31&v}return chk}function encode(prefix,words,LIMIT){if(LIMIT=LIMIT||90,prefix.length+7+words.length>LIMIT)throw TypeError("Exceeds length limit");var chk=prefixChk(prefix=prefix.toLowerCase());if("string"==typeof chk)throw Error(chk);for(var result=prefix+"1",i=0;i<words.length;++i){var x=words[i];if(x>>5!=0)throw Error("Non 5-bit word");chk=polymodStep(chk)^x,result+=ALPHABET.charAt(x)}for(i=0;i<6;++i)chk=polymodStep(chk);for(chk^=1,i=0;i<6;++i){var v=chk>>(5-i)*5&31;result+=ALPHABET.charAt(v)}return result}function __decode(str,LIMIT){if(LIMIT=LIMIT||90,str.length<8)return str+" too short";if(str.length>LIMIT)return"Exceeds length limit";var lowered=str.toLowerCase(),uppered=str.toUpperCase();if(str!==lowered&&str!==uppered)return"Mixed-case string "+str;var split=(str=lowered).lastIndexOf("1");if(-1===split)return"No separator character for "+str;if(0===split)return"Missing prefix for "+str;var prefix=str.slice(0,split),wordChars=str.slice(split+1);if(wordChars.length<6)return"Data too short";var chk=prefixChk(prefix);if("string"==typeof chk)return chk;for(var words=[],i=0;i<wordChars.length;++i){var c=wordChars.charAt(i),v=ALPHABET_MAP[c];if(void 0===v)return"Unknown character "+c;chk=polymodStep(chk)^v,i+6>=wordChars.length||words.push(v)}return 1!==chk?"Invalid checksum for "+str:{prefix:prefix,words:words}}function decodeUnsafe(){var res=__decode.apply(null,arguments);if("object"==typeof res)return res}function decode(str){var res=__decode.apply(null,arguments);if("object"==typeof res)return res;throw Error(res)}function convert(data,inBits,outBits,pad){for(var value=0,bits=0,maxV=(1<<outBits)-1,result=[],i=0;i<data.length;++i)for(value=value<<inBits|data[i],bits+=inBits;bits>=outBits;)result.push(value>>(bits-=outBits)&maxV);if(pad)bits>0&&result.push(value<<outBits-bits&maxV);else{if(bits>=inBits)return"Excess padding";if(value<<outBits-bits&maxV)return"Non-zero padding"}return result}function toWordsUnsafe(bytes){var res=convert(bytes,8,5,!0);if(Array.isArray(res))return res}function toWords(bytes){var res=convert(bytes,8,5,!0);if(Array.isArray(res))return res;throw Error(res)}function fromWordsUnsafe(words){var res=convert(words,5,8,!1);if(Array.isArray(res))return res}function fromWords(words){var res=convert(words,5,8,!1);if(Array.isArray(res))return res;throw Error(res)}module.exports={decodeUnsafe:decodeUnsafe,decode:decode,encode:encode,toWordsUnsafe:toWordsUnsafe,toWords:toWords,fromWordsUnsafe:fromWordsUnsafe,fromWords:fromWords}}}]);