ethers.js/dist/ethers.min.js
2022-09-15 23:02:59 -04:00

1 line
394 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const version="6.0.0-beta-exports.1";async function resolveProperties(value){const keys=Object.keys(value);const results=await Promise.all(keys.map(k=>Promise.resolve(value[k])));return results.reduce((accum,v,index)=>{accum[keys[index]]=v;return accum},{})}function defineReadOnly(object,name,value){Object.defineProperty(object,name,{enumerable:true,value:value,writable:false})}function checkType(value,type){const types=type.split("|").map(t=>t.trim());for(let i=0;i<types.length;i++){switch(type){case"any":return;case"boolean":case"number":case"string":if(typeof value===type){return}}}throw new Error("invalid value for type")}function defineProperties(target,values,types,defaults){for(let key in values){let value=values[key];const fallback=defaults?defaults[key]:undefined;if(fallback!==undefined){value=fallback}else{const type=types?types[key]:null;if(type){checkType(value,type)}}Object.defineProperty(target,key,{enumerable:true,value:value,writable:false})}}const ErrorConstructors={};ErrorConstructors.INVALID_ARGUMENT=TypeError;ErrorConstructors.NUMERIC_FAULT=RangeError;ErrorConstructors.BUFFER_OVERRUN=RangeError;function isError(error,code){return error&&error.code===code}function isCallException(error){return isError(error,"CALL_EXCEPTION")}function makeError(message,code,info){{const details=[];if(info){if("message"in info||"code"in info||"name"in info){throw new Error(`value will overwrite populated values: ${JSON.stringify(info)}`)}for(const key in info){const value=info[key];try{details.push(key+"="+JSON.stringify(value))}catch(error){details.push(key+"=[could not serialize object]")}}}details.push(`code=${code}`);details.push(`version=${version}`);if(details.length){message+=" ("+details.join(", ")+")"}}const create=ErrorConstructors[code]||Error;const error=new create(message);defineReadOnly(error,"code",code);if(info){for(const key in info){defineReadOnly(error,key,info[key])}}return error}function throwError(message,code,info){throw makeError(message,code,info)}function throwArgumentError(message,name,value){return throwError(message,"INVALID_ARGUMENT",{argument:name,value:value})}function assertArgument(check,message,name,value){if(!check){throwArgumentError(message,name,value)}}function assertArgumentCount(count,expectedCount,message=""){if(message){message=": "+message}if(count<expectedCount){throwError("missing arguemnt"+message,"MISSING_ARGUMENT",{count:count,expectedCount:expectedCount})}if(count>expectedCount){throwError("too many arguemnts"+message,"UNEXPECTED_ARGUMENT",{count:count,expectedCount:expectedCount})}}const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function assertNormalize(form){if(_normalizeForms.indexOf(form)===-1){throwError("platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}}function assertPrivate(givenGuard,guard,className=""){if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}throwError(`private constructor; use ${method}from* methods`,"UNSUPPORTED_OPERATION",{operation:operation})}}function _getBytes(value,name,copy){if(value instanceof Uint8Array){if(copy){return new Uint8Array(value)}return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;i<result.length;i++){result[i]=parseInt(value.substring(offset,offset+2),16);offset+=2}return result}return throwArgumentError("invalid BytesLike value",name||"value",value)}function getBytes(value,name){return _getBytes(value,name,false)}function getBytesCopy(value,name){return _getBytes(value,name,true)}function isHexString(value,length){if(typeof value!=="string"||!value.match(/^0x[0-9A-Fa-f]*$/)){return false}if(typeof length==="number"&&value.length!==2+2*length){return false}if(length===true&&value.length%2!==0){return false}return true}function isBytesLike(value){return isHexString(value,true)||value instanceof Uint8Array}const HexCharacters="0123456789abcdef";function hexlify(data){const bytes=getBytes(data);let result="0x";for(let i=0;i<bytes.length;i++){const v=bytes[i];result+=HexCharacters[(v&240)>>4]+HexCharacters[v&15]}return result}function concat(datas){return"0x"+datas.map(d=>hexlify(d).substring(2)).join("")}function dataLength(data){if(isHexString(data,true)){return(data.length-2)/2}return getBytes(data).length}function dataSlice(data,start,end){const bytes=getBytes(data);if(end!=null&&end>bytes.length){throwError("cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:bytes,length:bytes.length,offset:end})}return hexlify(bytes.slice(start==null?0:start,end==null?bytes.length:end))}function stripZerosLeft(data){let bytes=hexlify(data).substring(2);while(bytes.substring(0,2)=="00"){bytes=bytes.substring(2)}return"0x"+bytes}function zeroPad(data,length,left){const bytes=getBytes(data);if(length<bytes.length){throwError("padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(bytes),length:length,offset:length+1})}const result=new Uint8Array(length);result.fill(0);if(left){result.set(bytes,length-bytes.length)}else{result.set(bytes,0)}return hexlify(result)}function zeroPadValue(data,length){return zeroPad(data,length,true)}function zeroPadBytes(data,length){return zeroPad(data,length,false)}const BN_0$6=BigInt(0);const BN_1$5=BigInt(1);const maxValue=9007199254740991;function fromTwos(_value,_width){const value=getBigInt(_value,"value");const width=BigInt(getNumber(_width,"width"));if(value>>width-BN_1$5){const mask=(BN_1$5<<width)-BN_1$5;return-((~value&mask)+BN_1$5)}return value}function toTwos(_value,_width){const value=getBigInt(_value,"value");const width=BigInt(getNumber(_width,"width"));if(value<BN_0$6){const mask=(BN_1$5<<width)-BN_1$5;return(~-value&mask)+BN_1$5}return value}function mask(_value,_bits){const value=getBigInt(_value,"value");const bits=BigInt(getNumber(_bits,"bits"));return value&(BN_1$5<<bits)-BN_1$5}function getBigInt(value,name){switch(typeof value){case"bigint":return value;case"number":if(!Number.isInteger(value)){throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){throwArgumentError("overflow",name||"value",value)}return BigInt(value);case"string":try{return BigInt(value)}catch(e){throwArgumentError(`invalid BigNumberish string: ${e.message}`,name||"value",value)}}return throwArgumentError("invalid BigNumberish value",name||"value",value)}const Nibbles$1="0123456789abcdef";function toBigInt(value){if(value instanceof Uint8Array){let result="0x0";for(const v of value){result+=Nibbles$1[v>>4];result+=Nibbles$1[v&15]}return BigInt(result)}return getBigInt(value)}function getNumber(value,name){switch(typeof value){case"bigint":if(value<-maxValue||value>maxValue){throwArgumentError("overflow",name||"value",value)}return Number(value);case"number":if(!Number.isInteger(value)){throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){throwArgumentError("overflow",name||"value",value)}return value;case"string":try{return getNumber(BigInt(value),name)}catch(e){throwArgumentError(`invalid numeric string: ${e.message}`,name||"value",value)}}return throwArgumentError("invalid numeric value",name||"value",value)}function toNumber(value){return getNumber(toBigInt(value))}function toHex(_value,_width){const value=getBigInt(_value,"value");if(value<0){throw new Error("cannot convert negative value to hex")}let result=value.toString(16);if(_width==null){if(result.length%2){result="0"+result}}else{const width=getNumber(_width,"width");if(width*2<result.length){throw new Error(`value ${value} exceeds width ${width}`)}while(result.length<width*2){result="0"+result}}return"0x"+result}function toArray(_value){const value=getBigInt(_value,"value");if(value<0){throw new Error("cannot convert negative value to hex")}if(value===BN_0$6){return new Uint8Array([])}let hex=value.toString(16);if(hex.length%2){hex="0"+hex}const result=new Uint8Array(hex.length/2);for(let i=0;i<result.length;i++){const offset=i*2;result[i]=parseInt(hex.substring(offset,offset+2),16)}return result}function toQuantity(value){let result=hexlify(isBytesLike(value)?value:toArray(value)).substring(2);while(result.substring(0,1)==="0"){result=result.substring(1)}if(result===""){result="0"}return"0x"+result}const Alphabet="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Lookup=null;function getAlpha(letter){if(Lookup==null){Lookup={};for(let i=0;i<Alphabet.length;i++){Lookup[Alphabet[i]]=BigInt(i)}}const result=Lookup[letter];if(result==null){throwArgumentError(`invalid base58 value`,"letter",letter)}return result}const BN_0$5=BigInt(0);const BN_58=BigInt(58);function encodeBase58(_value){let value=toBigInt(getBytes(_value));let result="";while(value){result=Alphabet[Number(value%BN_58)]+result;value/=BN_58}return result}function decodeBase58(value){let result=BN_0$5;for(let i=0;i<value.length;i++){result*=BN_58;result+=getAlpha(value[i])}return getBytes(toHex(result))}function decodeBase64(textData){textData=atob(textData);const data=new Uint8Array(textData.length);for(let i=0;i<textData.length;i++){data[i]=textData.charCodeAt(i)}return getBytes(data)}function encodeBase64(_data){const data=getBytes(_data);let textData="";for(let i=0;i<data.length;i++){textData+=String.fromCharCode(data[i])}return btoa(textData)}class EventPayload{filter;emitter;#listener;constructor(emitter,listener,filter){this.#listener=listener;defineProperties(this,{emitter:emitter,filter:filter})}async removeListener(){if(this.#listener==null){return}await this.emitter.off(this.filter,this.#listener)}}function errorFunc(reason,offset,bytes,output,badCodepoint){return throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`,"bytes",bytes)}function ignoreFunc(reason,offset,bytes,output,badCodepoint){if(reason==="BAD_PREFIX"||reason==="UNEXPECTED_CONTINUE"){let i=0;for(let o=offset+1;o<bytes.length;o++){if(bytes[o]>>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){output.push(badCodepoint!=null?badCodepoint:-1);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes,output,badCodepoint)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=getBytes(_bytes,"bytes");const result=[];let i=0;while(i<bytes.length){const c=bytes[i++];if(c>>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j<extraLength;j++){let nextChar=bytes[i];if((nextChar&192)!=128){i+=onError("MISSING_CONTINUE",i,bytes,result);res=null;break}res=res<<6|nextChar&63;i++}if(res===null){continue}if(res>1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){if(form!=null){assertNormalize(form);str=str.normalize(form)}let result=[];for(let i=0;i<str.length;i++){const c=str.charCodeAt(i);if(c<128){result.push(c)}else if(c<2048){result.push(c>>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);if(i>=str.length||(c2&64512)!==56320){throw new Error("invalid utf-8 string")}const pair=65536+((c&1023)<<10)+(c2&1023);result.push(pair>>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function escapeChar(value){const hex="0000"+value.toString(16);return"\\u"+hex.substring(hex.length-4)}function _toEscapedUtf8String(bytes,onError){return'"'+getUtf8CodePoints(bytes,onError).map(codePoint=>{if(codePoint<256){switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 13:return"\\r";case 34:return'\\"';case 92:return"\\\\"}if(codePoint>=32&&codePoint<127){return String.fromCharCode(codePoint)}}if(codePoint<=65535){return escapeChar(codePoint)}codePoint-=65536;return escapeChar((codePoint>>10&1023)+55296)+escapeChar((codePoint&1023)+56320)}).join("")+'"'}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}function toUtf8CodePoints(str,form){return getUtf8CodePoints(toUtf8Bytes(str,form))}async function getUrl(req,_signal){const protocol=req.url.split(":")[0].toLowerCase();if(protocol!=="http"&&protocol!=="https"){throwError(`unsupported protocol ${protocol}`,"UNSUPPORTED_OPERATION",{info:{protocol:protocol},operation:"request"})}if(req.credentials&&!req.allowInsecureAuthentication){throwError("insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"})}let signal=undefined;if(_signal){const controller=new AbortController;signal=controller.signal;_signal.addListener(()=>{controller.abort()})}const init={method:req.method,headers:new Headers(Array.from(req)),body:req.body||undefined,signal:signal};const resp=await fetch(req.url,init);const headers={};resp.headers.forEach((value,key)=>{headers[key.toLowerCase()]=value});const respBody=await resp.arrayBuffer();const body=respBody==null?null:new Uint8Array(respBody);return{statusCode:resp.status,statusMessage:resp.statusText,headers:headers,body:body}}const MAX_ATTEMPTS=12;const SLOT_INTERVAL=250;let getUrlFunc=getUrl;const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i");const reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$5=false;async function gatewayData(url,signal){try{const match=url.match(reData);if(!match){throw new Error("invalid data")}return new FetchResponse(200,"OK",{"content-type":match[1]||"text/plain"},match[2]?decodeBase64(match[3]):unpercent(match[3]))}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(url))}}function getIpfsGatewayFunc(baseUrl){async function gatewayIpfs(url,signal){try{const match=url.match(reIpfs);if(!match){throw new Error("invalid link")}return new FetchRequest(`${baseUrl}${match[2]}`)}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(url))}}return gatewayIpfs}const Gateways={data:gatewayData,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")};const fetchSignals=new WeakMap;class FetchCancelSignal{#listeners;#cancelled;constructor(request){this.#listeners=[];this.#cancelled=false;fetchSignals.set(request,()=>{if(this.#cancelled){return}this.#cancelled=true;for(const listener of this.#listeners){setTimeout(()=>{listener()},0)}this.#listeners=[]})}addListener(listener){if(this.#cancelled){throwError("singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"})}this.#listeners.push(listener)}get cancelled(){return this.#cancelled}checkSignal(){if(!this.cancelled){return}throwError("cancelled","CANCELLED",{})}}function checkSignal(signal){if(signal==null){throw new Error("missing signal; should not happen")}signal.checkSignal();return signal}class FetchRequest{#allowInsecure;#gzip;#headers;#method;#timeout;#url;#body;#bodyType;#creds;#preflight;#process;#retry;#signal;get url(){return this.#url}set url(url){this.#url=String(url)}get body(){if(this.#body==null){return null}return new Uint8Array(this.#body)}set body(body){if(body==null){this.#body=undefined;this.#bodyType=undefined}else if(typeof body==="string"){this.#body=toUtf8Bytes(body);this.#bodyType="text/plain"}else if(body instanceof Uint8Array){this.#body=body;this.#bodyType="application/octet-stream"}else if(typeof body==="object"){this.#body=toUtf8Bytes(JSON.stringify(body));this.#bodyType="application/json"}else{throw new Error("invalid body")}}hasBody(){return this.#body!=null}get method(){if(this.#method){return this.#method}if(this.hasBody()){return"POST"}return"GET"}set method(method){if(method==null){method=""}this.#method=String(method).toUpperCase()}get headers(){const headers=Object.assign({},this.#headers);if(this.#creds){headers["authorization"]=`Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`}if(this.allowGzip){headers["accept-encoding"]="gzip"}if(headers["content-type"]==null&&this.#bodyType){headers["content-type"]=this.#bodyType}if(this.body){headers["content-length"]=String(this.body.length)}return Object.freeze(headers)}getHeader(key){return this.headers[key.toLowerCase()]}setHeader(key,value){this.#headers[String(key).toLowerCase()]=String(value)}clearHeaders(){this.#headers={}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index<keys.length){const key=keys[index++];return{value:[key,headers[key]],done:false}}return{value:undefined,done:true}}}}get credentials(){return this.#creds||null}setCredentials(username,password){if(username.match(/:/)){throwArgumentError("invalid basic authentication username","username","[REDACTED]")}this.#creds=`${username}:${password}`}get allowGzip(){return this.#gzip}set allowGzip(value){this.#gzip=!!value}get allowInsecureAuthentication(){return!!this.#allowInsecure}set allowInsecureAuthentication(value){this.#allowInsecure=!!value}get timeout(){return this.#timeout}set timeout(timeout){assertArgument(timeout>=0,"timeout must be non-zero","timeout",timeout);this.#timeout=timeout}get preflightFunc(){return this.#preflight||null}set preflightFunc(preflight){this.#preflight=preflight}get processFunc(){return this.#process||null}set processFunc(process){this.#process=process}get retryFunc(){return this.#retry||null}set retryFunc(retry){this.#retry=retry}constructor(url){this.#url=String(url);this.#allowInsecure=false;this.#gzip=false;this.#headers={};this.#method="";this.#timeout=300}async#send(attempt,expires,delay,_request,_response){if(attempt>=MAX_ATTEMPTS){return _response.makeServerError("exceeded maximum retry limit")}if(getTime$2()>expires){return throwError("timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:_request})}if(delay>0){await wait(delay)}let req=this.clone();const scheme=(req.url.split(":")[0]||"").toLowerCase();if(scheme in Gateways){const result=await Gateways[scheme](req.url,checkSignal(_request.#signal));if(result instanceof FetchResponse){let response=result;if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}}}return response}req=result}if(this.preflightFunc){req=await this.preflightFunc(req)}const resp=await getUrlFunc(req,checkSignal(_request.#signal));let response=new FetchResponse(resp.statusCode,resp.statusMessage,resp.headers,resp.body,_request);if(response.statusCode===301||response.statusCode===302){try{const location=response.headers.location||"";return req.redirect(location).#send(attempt+1,expires,0,_request,response)}catch(error){}return response}else if(response.statusCode===429){if(this.retryFunc==null||await this.retryFunc(req,response,attempt)){const retryAfter=response.headers["retry-after"];let delay=SLOT_INTERVAL*Math.trunc(Math.random()*Math.pow(2,attempt));if(typeof retryAfter==="string"&&retryAfter.match(/^[1-9][0-9]*$/)){delay=parseInt(retryAfter)}return req.clone().#send(attempt+1,expires,delay,_request,response)}}if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}let delay=SLOT_INTERVAL*Math.trunc(Math.random()*Math.pow(2,attempt));if(error.stall>=0){delay=error.stall}return req.clone().#send(attempt+1,expires,delay,_request,response)}}return response}send(){if(this.#signal!=null){return throwError("request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"})}this.#signal=new FetchCancelSignal(this);return this.#send(0,getTime$2()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){if(this.#signal==null){return throwError("request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"})}const signal=fetchSignals.get(this);if(!signal){throw new Error("missing signal; should not happen")}signal()}redirect(location){const current=this.url.split(":")[0].toLowerCase();const target=location.split(":")[0].toLowerCase();if(this.method!=="GET"||current==="https"&&target==="http"||!location.match(/^https?:/)){return throwError(`unsupported redirect`,"UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`})}const req=new FetchRequest(location);req.method="GET";req.allowGzip=this.allowGzip;req.timeout=this.timeout;req.#headers=Object.assign({},this.#headers);if(this.#body){req.#body=new Uint8Array(this.#body)}req.#bodyType=this.#bodyType;return req}clone(){const clone=new FetchRequest(this.url);clone.#method=this.#method;if(this.#body){clone.#body=this.#body}clone.#bodyType=this.#bodyType;clone.#headers=Object.assign({},this.#headers);clone.#creds=this.#creds;if(this.allowGzip){clone.allowGzip=true}clone.timeout=this.timeout;if(this.allowInsecureAuthentication){clone.allowInsecureAuthentication=true}clone.#preflight=this.#preflight;clone.#process=this.#process;clone.#retry=this.#retry;return clone}static lockConfig(){locked$5=true}static getGateway(scheme){return Gateways[scheme.toLowerCase()]||null}static registerGateway(scheme,func){scheme=scheme.toLowerCase();if(scheme==="http"||scheme==="https"){throw new Error(`cannot intercept ${scheme}; use registerGetUrl`)}if(locked$5){throw new Error("gateways locked")}Gateways[scheme]=func}static registerGetUrl(getUrl){if(locked$5){throw new Error("gateways locked")}getUrlFunc=getUrl}}class FetchResponse{#statusCode;#statusMessage;#headers;#body;#request;#error;toString(){return`<Response status=${this.statusCode} body=${this.#body?hexlify(this.#body):"null"}>`}get statusCode(){return this.#statusCode}get statusMessage(){return this.#statusMessage}get headers(){return this.#headers}get body(){return this.#body==null?null:new Uint8Array(this.#body)}get bodyText(){try{return this.#body==null?"":toUtf8String(this.#body)}catch(error){return throwError("response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(error){return throwError("response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index<keys.length){const key=keys[index++];return{value:[key,headers[key]],done:false}}return{value:undefined,done:true}}}}constructor(statusCode,statusMessage,headers,body,request){this.#statusCode=statusCode;this.#statusMessage=statusMessage;this.#headers=Object.freeze(Object.assign({},Object.keys(headers).reduce((accum,k)=>{accum[k.toLowerCase()]=String(headers[k]);return accum},{})));this.#body=body==null?null:new Uint8Array(body);this.#request=request||null;this.#error={message:""}}makeServerError(message,error){let statusMessage;if(!message){message=`${this.statusCode} ${this.statusMessage}`;statusMessage=`CLIENT ESCALATED SERVER ERROR (${message})`}else{statusMessage=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`}const response=new FetchResponse(599,statusMessage,this.headers,this.body,this.#request||undefined);response.#error={message:message,error:error};return response}throwThrottleError(message,stall){if(stall==null){stall=-1}else if(typeof stall!=="number"||!Number.isInteger(stall)||stall<0){return throwArgumentError("invalid stall timeout","stall",stall)}const error=new Error(message||"throttling requests");defineProperties(error,{stall:stall,throttle:true});throw error}getHeader(key){return this.headers[key.toLowerCase()]}hasBody(){return this.#body!=null}get request(){return this.#request}ok(){return this.#error.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok()){return}let{message,error}=this.#error;if(message===""){message=`server response ${this.statusCode} ${this.statusMessage}`}throwError(message,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:error})}}function getTime$2(){return(new Date).getTime()}function unpercent(value){return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi,(all,code)=>{return String.fromCharCode(parseInt(code,16))}))}function wait(delay){return new Promise(resolve=>setTimeout(resolve,delay))}const _constructorGuard={};const NegativeOne$1=BigInt(-1);function throwFault(message,fault,operation,value){const params={fault:fault,operation:operation};if(value!==undefined){params.value=value}return throwError(message,"NUMERIC_FAULT",params)}let zeros$1="0";while(zeros$1.length<256){zeros$1+=zeros$1}function getMultiplier(decimals){if(typeof decimals!=="number"||decimals<0||decimals>256||decimals%1){throwArgumentError("invalid decimal length","decimals",decimals)}return BigInt("1"+zeros$1.substring(0,decimals))}function formatFixed(_value,_decimals){if(_decimals==null){_decimals=18}let value=getBigInt(_value,"value");const decimals=getNumber(_decimals,"decimals");const multiplier=getMultiplier(decimals);const multiplierStr=String(multiplier);const negative=value<0;if(negative){value*=NegativeOne$1}let fraction=String(value%multiplier);while(fraction.length<multiplierStr.length-1){fraction="0"+fraction}while(fraction.length>1&&fraction.substring(fraction.length-1)==="0"){fraction=fraction.substring(0,fraction.length-1)}let result=String(value/multiplier);if(multiplierStr.length!==1){result+="."+fraction}if(negative){result="-"+result}return result}function parseFixed(value,_decimals){if(_decimals==null){_decimals=18}const decimals=getNumber(_decimals,"decimals");const multiplier=getMultiplier(decimals);if(typeof value!=="string"||!value.match(/^-?[0-9.]+$/)){throwArgumentError("invalid decimal value","value",value)}const negative=value.substring(0,1)==="-";if(negative){value=value.substring(1)}if(value==="."){throwArgumentError("missing value","value",value)}const comps=value.split(".");if(comps.length>2){throwArgumentError("too many decimal points","value",value)}let whole=comps[0]||"0",fraction=comps[1]||"0";while(fraction[fraction.length-1]==="0"){fraction=fraction.substring(0,fraction.length-1)}if(fraction.length>String(multiplier).length-1){throwFault("fractional component exceeds decimals","underflow","parseFixed")}if(fraction===""){fraction="0"}while(fraction.length<String(multiplier).length-1){fraction+="0"}const wholeValue=BigInt(whole);const fractionValue=BigInt(fraction);let wei=wholeValue*multiplier+fractionValue;if(negative){wei*=NegativeOne$1}return wei}class FixedFormat{signed;width;decimals;name;_multiplier;constructor(constructorGuard,signed,width,decimals){if(constructorGuard!==_constructorGuard){throwError("cannot use FixedFormat constructor; use FixedFormat.from","UNSUPPORTED_OPERATION",{operation:"new FixedFormat"})}this.signed=signed;this.width=width;this.decimals=decimals;this.name=(signed?"":"u")+"fixed"+String(width)+"x"+String(decimals);this._multiplier=getMultiplier(decimals);Object.freeze(this)}static from(value){if(value instanceof FixedFormat){return value}if(typeof value==="number"){value=`fixed128x${value}`}let signed=true;let width=128;let decimals=18;if(typeof value==="string"){if(value==="fixed"){}else if(value==="ufixed"){signed=false}else{const match=value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);if(!match){return throwArgumentError("invalid fixed format","format",value)}signed=match[1]!=="u";width=parseInt(match[2]);decimals=parseInt(match[3])}}else if(value){const check=(key,type,defaultValue)=>{if(value[key]==null){return defaultValue}if(typeof value[key]!==type){throwArgumentError("invalid fixed format ("+key+" not "+type+")","format."+key,value[key])}return value[key]};signed=check("signed","boolean",signed);width=check("width","number",width);decimals=check("decimals","number",decimals)}if(width%8){throwArgumentError("invalid fixed format width (not byte aligned)","format.width",width)}if(decimals>80){throwArgumentError("invalid fixed format (decimals too large)","format.decimals",decimals)}return new FixedFormat(_constructorGuard,signed,width,decimals)}}class FixedNumber{format;_isFixedNumber;#value;constructor(constructorGuard,hex,value,format){if(constructorGuard!==_constructorGuard){throwError("cannot use FixedNumber constructor; use FixedNumber.from","UNSUPPORTED_OPERATION",{operation:"new FixedFormat"})}this.format=FixedFormat.from(format);this.#value=value;this._isFixedNumber=true;Object.freeze(this)}#checkFormat(other){if(this.format.name!==other.format.name){throwArgumentError("incompatible format; use fixedNumber.toFormat","other",other)}}addUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a+b,this.format.decimals,this.format)}subUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a-b,this.format.decimals,this.format)}mulUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a*b/this.format._multiplier,this.format.decimals,this.format)}divUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a*this.format._multiplier/b,this.format.decimals,this.format)}floor(){const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);if(this.isNegative()&&hasFraction){result=result.subUnsafe(ONE.toFormat(result.format))}return result}ceiling(){const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);if(!this.isNegative()&&hasFraction){result=result.addUnsafe(ONE.toFormat(result.format))}return result}round(decimals){if(decimals==null){decimals=0}const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}if(decimals<0||decimals>80||decimals%1){throwArgumentError("invalid decimal count","decimals",decimals)}if(comps[1].length<=decimals){return this}const factor=FixedNumber.from("1"+zeros$1.substring(0,decimals),this.format);const bump=BUMP.toFormat(this.format);return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor)}isZero(){return this.#value==="0.0"||this.#value==="0"}isNegative(){return this.#value[0]==="-"}toString(){return this.#value}toHexString(_width){throw new Error("TODO")}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(format){return FixedNumber.fromString(this.#value,format)}static fromValue(value,decimals=0,format="fixed"){return FixedNumber.fromString(formatFixed(value,decimals),FixedFormat.from(format))}static fromString(value,format="fixed"){const fixedFormat=FixedFormat.from(format);const numeric=parseFixed(value,fixedFormat.decimals);if(!fixedFormat.signed&&numeric<0){throwFault("unsigned value cannot be negative","overflow","value",value)}const hex=function(){if(fixedFormat.signed){return toHex(toTwos(numeric,fixedFormat.width))}return toHex(numeric,fixedFormat.width/8)}();const decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(_constructorGuard,hex,decimal,fixedFormat)}static fromBytes(_value,format="fixed"){const value=getBytes(_value,"value");const fixedFormat=FixedFormat.from(format);if(value.length>fixedFormat.width/8){throw new Error("overflow")}let numeric=toBigInt(value);if(fixedFormat.signed){numeric=fromTwos(numeric,fixedFormat.width)}const hex=toHex(toTwos(numeric,(fixedFormat.signed?0:1)+fixedFormat.width));const decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(_constructorGuard,hex,decimal,fixedFormat)}static from(value,format){if(typeof value==="string"){return FixedNumber.fromString(value,format)}if(value instanceof Uint8Array){return FixedNumber.fromBytes(value,format)}try{return FixedNumber.fromValue(value,0,format)}catch(error){if(error.code!=="INVALID_ARGUMENT"){throw error}}return throwArgumentError("invalid FixedNumber value","value",value)}static isFixedNumber(value){return!!(value&&value._isFixedNumber)}}const ONE=FixedNumber.from(1);const BUMP=FixedNumber.from("0.5");function hexlifyByte(value){let result=value.toString(16);while(result.length<2){result="0"+result}return"0x"+result}function unarrayifyInteger(data,offset,length){let result=0;for(let i=0;i<length;i++){result=result*256+data[offset+i]}return result}function _decodeChildren(data,offset,childOffset,length){const result=[];while(childOffset<offset+1+length){const decoded=_decode(data,childOffset);result.push(decoded.result);childOffset+=decoded.consumed;if(childOffset>offset+1+length){throwError("child data too short","BUFFER_OVERRUN",{buffer:data,length:length,offset:offset})}}return{consumed:1+length,result:result}}function _decode(data,offset){if(data.length===0){throwError("data too short","BUFFER_OVERRUN",{buffer:data,length:0,offset:1})}const checkOffset=offset=>{if(offset>data.length){throwError("data short segment too short","BUFFER_OVERRUN",{buffer:data,length:data.length,offset:offset})}};if(data[offset]>=248){const lengthLength=data[offset]-247;checkOffset(offset+1+lengthLength);const length=unarrayifyInteger(data,offset+1,lengthLength);checkOffset(offset+1+lengthLength+length);return _decodeChildren(data,offset,offset+1+lengthLength,lengthLength+length)}else if(data[offset]>=192){const length=data[offset]-192;checkOffset(offset+1+length);return _decodeChildren(data,offset,offset+1,length)}else if(data[offset]>=184){const lengthLength=data[offset]-183;checkOffset(offset+1+lengthLength);const length=unarrayifyInteger(data,offset+1,lengthLength);checkOffset(offset+1+lengthLength+length);const result=hexlify(data.slice(offset+1+lengthLength,offset+1+lengthLength+length));return{consumed:1+lengthLength+length,result:result}}else if(data[offset]>=128){const length=data[offset]-128;checkOffset(offset+1+length);const result=hexlify(data.slice(offset+1,offset+1+length));return{consumed:1+length,result:result}}return{consumed:1,result:hexlifyByte(data[offset])}}function decodeRlp(_data){const data=getBytes(_data,"data");const decoded=_decode(data,0);if(decoded.consumed!==data.length){throwArgumentError("unexpected junk after rlp payload","data",_data)}return decoded.result}function arrayifyInteger(value){const result=[];while(value){result.unshift(value&255);value>>=8}return result}function _encode(object){if(Array.isArray(object)){let payload=[];object.forEach(function(child){payload=payload.concat(_encode(child))});if(payload.length<=55){payload.unshift(192+payload.length);return payload}const length=arrayifyInteger(payload.length);length.unshift(247+length.length);return length.concat(payload)}const data=Array.prototype.slice.call(getBytes(object,"object"));if(data.length===1&&data[0]<=127){return data}else if(data.length<=55){data.unshift(128+data.length);return data}const length=arrayifyInteger(data.length);length.unshift(183+length.length);return length.concat(data)}const nibbles="0123456789abcdef";function encodeRlp(object){let result="0x";for(const v of _encode(object)){result+=nibbles[v>>4];result+=nibbles[v&15]}return result}function getStore(store,key){return store[key]}function setStore(store,key,value){if(Object.isFrozen(store)){throw new Error(`frozen object is immuatable; cannot set ${String(key)}`)}store[key]=value}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(value,unit){if(typeof unit==="string"){const index=names.indexOf(unit);if(index===-1){throwArgumentError("invalid unit","unit",unit)}unit=3*index}return formatFixed(value,unit!=null?unit:18)}function parseUnits(value,unit){if(typeof value!=="string"){throwArgumentError("value must be a string","value",value)}if(typeof unit==="string"){const index=names.indexOf(unit);if(index===-1){throwArgumentError("invalid unit","unit",unit)}unit=3*index}return parseFixed(value,unit!=null?unit:18)}function formatEther(wei){return formatUnits(wei,18)}function parseEther(ether){return parseUnits(ether,18)}const WordSize=32;const Padding=new Uint8Array(WordSize);const passProperties$1=["then"];const _guard$4={};class Result extends Array{#indices;constructor(guard,items,keys){assertPrivate(guard,_guard$4,"Result");super(...items);this.#indices=new Map;if(keys){keys.forEach((key,index)=>{if(key==null){return}if(this.#indices.has(key)){this.#indices.get(key).push(index)}else{this.#indices.set(key,[index])}})}Object.freeze(this);return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="string"){if(prop.match(/^[0-9]+$/)){const index=getNumber(prop,"%index");if(index<0||index>=this.length){throw new RangeError("out of result range")}const item=target[index];if(item instanceof Error){this.#throwError(`index ${index}`,item)}return item}if(prop in target||passProperties$1.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}if(!(prop in target)){return target.getValue(prop)}}return Reflect.get(target,prop,receiver)}})}slice(start,end){if(start==null){start=0}if(end==null){end=this.length}const result=[];for(let i=start;i<end;i++){let value;try{value=this[i]}catch(error){value=error.error}result.push(value)}return result}#throwError(name,error){const wrapped=new Error(`deferred error during ABI decoding triggered accessing ${name}`);wrapped.error=error;throw wrapped}getValue(name){const index=this.#indices.get(name);if(index!=null&&index.length===1){const item=this[index[0]];if(item instanceof Error){this.#throwError(`property ${JSON.stringify(name)}`,item)}return item}throw new Error(`no named parameter: ${JSON.stringify(name)}`)}static fromItems(items,keys){return new Result(_guard$4,items,keys)}}function checkResultErrors(result){const errors=[];const checkErrors=function(path,object){if(!Array.isArray(object)){return}for(let key in object){const childPath=path.slice();childPath.push(key);try{checkErrors(childPath,object[key])}catch(error){errors.push({path:childPath,error:error})}}};checkErrors([],result);return errors}function getValue$1(value){let bytes=toArray(value);if(bytes.length>WordSize){throwError("value out-of-bounds","BUFFER_OVERRUN",{buffer:bytes,length:WordSize,offset:bytes.length})}if(bytes.length!==WordSize){bytes=getBytesCopy(concat([Padding.slice(bytes.length%WordSize),bytes]))}return bytes}class Coder{name;type;localName;dynamic;constructor(name,type,localName,dynamic){defineProperties(this,{name:name,type:type,localName:localName,dynamic:dynamic},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(message,value){return throwArgumentError(message,this.localName,value)}}class Writer{#data;#dataLength;constructor(){this.#data=[];this.#dataLength=0}get data(){return concat(this.#data)}get length(){return this.#dataLength}#writeData(data){this.#data.push(data);this.#dataLength+=data.length;return data.length}appendWriter(writer){return this.#writeData(getBytesCopy(writer.data))}writeBytes(value){let bytes=getBytesCopy(value);const paddingOffset=bytes.length%WordSize;if(paddingOffset){bytes=getBytesCopy(concat([bytes,Padding.slice(paddingOffset)]))}return this.#writeData(bytes)}writeValue(value){return this.#writeData(getValue$1(value))}writeUpdatableValue(){const offset=this.#data.length;this.#data.push(Padding);this.#dataLength+=WordSize;return value=>{this.#data[offset]=getValue$1(value)}}}class Reader{allowLoose;#data;#offset;constructor(data,allowLoose){defineProperties(this,{allowLoose:!!allowLoose});this.#data=getBytesCopy(data);this.#offset=0}get data(){return hexlify(this.#data)}get dataLength(){return this.#data.length}get consumed(){return this.#offset}get bytes(){return new Uint8Array(this.#data)}#peekBytes(offset,length,loose){let alignedLength=Math.ceil(length/WordSize)*WordSize;if(this.#offset+alignedLength>this.#data.length){if(this.allowLoose&&loose&&this.#offset+length<=this.#data.length){alignedLength=length}else{throwError("data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#data),length:this.#data.length,offset:this.#offset+alignedLength})}}return this.#data.slice(this.#offset,this.#offset+alignedLength)}subReader(offset){return new Reader(this.#data.slice(this.#offset+offset),this.allowLoose)}readBytes(length,loose){let bytes=this.#peekBytes(0,length,!!loose);this.#offset+=bytes.length;return bytes.slice(0,length)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool(b){if(typeof b!=="boolean")throw new Error(`Expected boolean, not ${b}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function hash(hash){if(typeof hash!=="function"||typeof hash.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(hash.outputLen);number(hash.blockLen)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.length<min){throw new Error(`digestInto() expects output buffer of length at least ${min}`)}}const assert={number:number,bool:bool,bytes:bytes,hash:hash,exists:exists,output:output};const crypto$2={node:undefined,web:typeof self==="object"&&"crypto"in self?self.crypto:undefined};const u8=arr=>new Uint8Array(arr.buffer,arr.byteOffset,arr.byteLength);const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr=(word,shift)=>word<<32-shift|word>>>shift;const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");const hexes$1=Array.from({length:256},(v,i)=>i.toString(16).padStart(2,"0"));function bytesToHex$1(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Uint8Array expected");let hex="";for(let i=0;i<uint8a.length;i++){hex+=hexes$1[uint8a[i]]}return hex}function hexToBytes$1(hex){if(typeof hex!=="string"){throw new TypeError("hexToBytes: expected string, got "+typeof hex)}if(hex.length%2)throw new Error("hexToBytes: received invalid unpadded hex");const array=new Uint8Array(hex.length/2);for(let i=0;i<array.length;i++){const j=i*2;const hexByte=hex.slice(j,j+2);const byte=Number.parseInt(hexByte,16);if(Number.isNaN(byte)||byte<0)throw new Error("Invalid byte sequence");array[i]=byte}return array}const nextTick=async()=>{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i<iters;i++){cb(i);const diff=Date.now()-ts;if(diff>=0&&diff<tick)continue;await nextTick();ts+=diff}}function utf8ToBytes(str){if(typeof str!=="string"){throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`)}return(new TextEncoder).encode(str)}function toBytes(data){if(typeof data==="string")data=utf8ToBytes(data);if(!(data instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);return data}function concatBytes$1(...arrays){if(!arrays.every(a=>a instanceof Uint8Array))throw new Error("Uint8Array list expected");if(arrays.length===1)return arrays[0];const length=arrays.reduce((a,arr)=>a+arr.length,0);const result=new Uint8Array(length);for(let i=0,pad=0;i<arrays.length;i++){const arr=arrays[i];result.set(arr,pad);pad+=arr.length}return result}class Hash{clone(){return this._cloneInto()}}const isPlainObject=obj=>Object.prototype.toString.call(obj)==="[object Object]"&&obj.constructor===Object;function checkOpts(defaults,opts){if(opts!==undefined&&(typeof opts!=="object"||!isPlainObject(opts)))throw new TypeError("Options should be object or undefined");const merged=Object.assign(defaults,opts);return merged}function wrapConstructor(hashConstructor){const hashC=message=>hashConstructor().update(toBytes(message)).digest();const tmp=hashConstructor();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashConstructor();return hashC}function wrapConstructorWithOpts(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest();const tmp=hashCons({});hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=opts=>hashCons(opts);return hashC}function randomBytes$2(bytesLength=32){if(crypto$2.web){return crypto$2.web.getRandomValues(new Uint8Array(bytesLength))}else if(crypto$2.node){return new Uint8Array(crypto$2.node.randomBytes(bytesLength).buffer)}else{throw new Error("The environment doesn't have randomBytes function")}}class HMAC extends Hash{constructor(hash,_key){super();this.finished=false;this.destroyed=false;assert.hash(hash);const key=toBytes(_key);this.iHash=hash.create();if(!(this.iHash instanceof Hash))throw new TypeError("Expected instance of class which extends utils.Hash");const blockLen=this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const pad=new Uint8Array(blockLen);pad.set(key.length>this.iHash.blockLen?hash.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad);this.oHash=hash.create();for(let i=0;i<pad.length;i++)pad[i]^=54^92;this.oHash.update(pad);pad.fill(0)}update(buf){assert.exists(this);this.iHash.update(buf);return this}digestInto(out){assert.exists(this);assert.bytes(out,this.outputLen);this.finished=true;this.iHash.digestInto(out);this.oHash.update(out);this.oHash.digestInto(out);this.destroy()}digest(){const out=new Uint8Array(this.oHash.outputLen);this.digestInto(out);return out}_cloneInto(to){to||(to=Object.create(Object.getPrototypeOf(this),{}));const{oHash,iHash,finished,destroyed,blockLen,outputLen}=this;to=to;to.finished=finished;to.destroyed=destroyed;to.blockLen=blockLen;to.outputLen=outputLen;to.oHash=oHash._cloneInto(to.oHash);to.iHash=iHash._cloneInto(to.iHash);return to}destroy(){this.destroyed=true;this.oHash.destroy();this.iHash.destroy()}}const hmac=(hash,key,message)=>new HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key);function pbkdf2Init(hash,_password,_salt,_opts){assert.hash(hash);const opts=checkOpts({dkLen:32,asyncTick:10},_opts);const{c,dkLen,asyncTick}=opts;assert.number(c);assert.number(dkLen);assert.number(asyncTick);if(c<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const password=toBytes(_password);const salt=toBytes(_salt);const DK=new Uint8Array(dkLen);const PRF=hmac.create(hash,password);const PRFSalt=PRF._cloneInto().update(salt);return{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}}function pbkdf2Output(PRF,PRFSalt,DK,prfW,u){PRF.destroy();PRFSalt.destroy();if(prfW)prfW.destroy();u.fill(0);return DK}function pbkdf2$1(hash,password,salt,opts){const{c,dkLen,DK,PRF,PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4);const view=createView(arr);const u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos<dkLen;ti++,pos+=PRF.outputLen){const Ti=DK.subarray(pos,pos+PRF.outputLen);view.setInt32(0,ti,false);(prfW=PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);Ti.set(u.subarray(0,Ti.length));for(let ui=1;ui<c;ui++){PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;i<Ti.length;i++)Ti[i]^=u[i]}}return pbkdf2Output(PRF,PRFSalt,DK,prfW,u)}async function pbkdf2Async(hash,password,salt,opts){const{c,dkLen,asyncTick,DK,PRF,PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4);const view=createView(arr);const u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos<dkLen;ti++,pos+=PRF.outputLen){const Ti=DK.subarray(pos,pos+PRF.outputLen);view.setInt32(0,ti,false);(prfW=PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);Ti.set(u.subarray(0,Ti.length));await asyncLoop(c-1,asyncTick,i=>{PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;i<Ti.length;i++)Ti[i]^=u[i]})}return pbkdf2Output(PRF,PRFSalt,DK,prfW,u)}function setBigUint64(view,byteOffset,value,isLE){if(typeof view.setBigUint64==="function")return view.setBigUint64(byteOffset,value,isLE);const _32n=BigInt(32);const _u32_max=BigInt(4294967295);const wh=Number(value>>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}class SHA2 extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){assert.exists(this);const{view,buffer,blockLen}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);continue}buffer.set(data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0}}this.length+=data.length;this.roundClean();return this}digestInto(out){assert.exists(this);assert.output(out,this);this.finished=true;const{buffer,view,blockLen,isLE}=this;let{pos}=this;buffer[pos++]=128;this.buffer.subarray(pos).fill(0);if(this.padOffset>blockLen-pos){this.process(view,0);pos=0}for(let i=pos;i<blockLen;i++)buffer[i]=0;setBigUint64(view,blockLen-8,BigInt(this.length*8),isLE);this.process(view,0);const oview=createView(out);this.get().forEach((v,i)=>oview.setUint32(4*i,v,isLE))}digest(){const{buffer,outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneInto(to){to||(to=new this.constructor);to.set(...this.get());const{blockLen,buffer,length,finished,destroyed,pos}=this;to.length=length;to.pos=pos;to.finished=finished;to.destroyed=destroyed;if(length%blockLen)to.buffer.set(buffer);return to}}const Chi=(a,b,c)=>a&b^~a&c;const Maj=(a,b,c)=>a&b^a&c^b&c;const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25);const T1=H+sigma1+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr(A,2)^rotr(A,13)^rotr(A,22);const T2=sigma0+Maj(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256);const U32_MASK64=BigInt(2**32-1);const _32n=BigInt(32);function fromBig(n,le=false){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;i<lst.length;i++){const{h,l}=fromBig(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}const toBig=(h,l)=>BigInt(h>>>0)<<_32n|BigInt(l>>>0);const shrSH=(h,l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(h,l)=>l;const rotr32L=(h,l)=>h;const rotlSH=(h,l,s)=>h<<s|l>>>32-s;const rotlSL=(h,l,s)=>l<<s|h>>>32-s;const rotlBH=(h,l,s)=>l<<s-32|h>>>64-s;const rotlBL=(h,l,s)=>h<<s-32|l>>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const[SHA512_Kh,SHA512_Kl]=u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n)));const SHA512_W_H=new Uint32Array(80);const SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,false);this.Ah=1779033703|0;this.Al=4089235720|0;this.Bh=3144134277|0;this.Bl=2227873595|0;this.Ch=1013904242|0;this.Cl=4271175723|0;this.Dh=2773480762|0;this.Dl=1595750129|0;this.Eh=1359893119|0;this.El=2917565137|0;this.Fh=2600822924|0;this.Fl=725511199|0;this.Gh=528734635|0;this.Gl=4215389547|0;this.Hh=1541459225|0;this.Hl=327033209|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7);const s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6);const s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6);const SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41);const sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39);const sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=u64.add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=u64.add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=u64.add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=u64.add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=u64.add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=u64.add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=u64.add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=u64.add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=u64.add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0);SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class SHA512_256 extends SHA512{constructor(){super();this.Ah=573645204|0;this.Al=4230739756|0;this.Bh=2673172387|0;this.Bl=3360449730|0;this.Ch=596883563|0;this.Cl=1867755857|0;this.Dh=2520282905|0;this.Dl=1497426621|0;this.Eh=2519219938|0;this.El=2827943907|0;this.Fh=3193839141|0;this.Fl=1401305490|0;this.Gh=721525244|0;this.Gl=746961066|0;this.Hh=246885852|0;this.Hl=2177182882|0;this.outputLen=32}}class SHA384 extends SHA512{constructor(){super();this.Ah=3418070365|0;this.Al=3238371032|0;this.Bh=1654270250|0;this.Bl=914150663|0;this.Ch=2438529370|0;this.Cl=812702999|0;this.Dh=355462360|0;this.Dl=4144912697|0;this.Eh=1731405415|0;this.El=4290775857|0;this.Fh=2394180231|0;this.Fl=1750603025|0;this.Gh=3675008525|0;this.Gl=1694076839|0;this.Hh=1203062813|0;this.Hl=3204075428|0;this.outputLen=48}}const sha512$1=wrapConstructor(()=>new SHA512);const sha512_256=wrapConstructor(()=>new SHA512_256);const sha384=wrapConstructor(()=>new SHA384);function getGlobal$1(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const anyGlobal=getGlobal$1();const crypto$1=anyGlobal.crypto||anyGlobal.msCrypto;function createHash(algo){switch(algo){case"sha256":return sha256$1.create();case"sha512":return sha512$1.create()}return throwArgumentError("invalid hashing algorithm name","algorithm",algo)}function createHmac(_algo,key){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];if(algo==null){return throwArgumentError("invalid hmac algorithm","algorithm",_algo)}return hmac.create(algo,key)}function pbkdf2Sync(password,salt,iterations,keylen,_algo){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];if(algo==null){return throwArgumentError("invalid pbkdf2 algorithm","algorithm",_algo)}return pbkdf2$1(algo,password,salt,{c:iterations,dkLen:keylen})}function randomBytes$1(length){if(crypto$1==null){return throwError("platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"})}if(!Number.isInteger(length)||length<=0||length>1024){throwArgumentError("invalid length","length",length)}const result=new Uint8Array(length);crypto$1.getRandomValues(result);return result}let locked$4=false;const _computeHmac=function(algorithm,key,data){return"0x"+createHmac(algorithm,key).update(data).digest("hex")};let __computeHmac=_computeHmac;function computeHmac(algorithm,_key,_data){const key=getBytes(_key,"key");const data=getBytes(_data,"data");return hexlify(__computeHmac(algorithm,key,data))}computeHmac._=_computeHmac;computeHmac.lock=function(){locked$4=true};computeHmac.register=function(func){if(locked$4){throw new Error("computeHmac is locked")}__computeHmac=func};Object.freeze(computeHmac);const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n$1=BigInt(0);const _1n$1=BigInt(1);const _2n$1=BigInt(2);const _7n=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n$1,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n$1;for(let j=0;j<7;j++){R=(R<<_1n$1^(R>>_7n)*_0x71n)%_256n;if(R&_2n$1)t^=_1n$1<<(_1n$1<<BigInt(j))-_1n$1}_SHA3_IOTA.push(t)}const[SHA3_IOTA_H,SHA3_IOTA_L]=u64.split(_SHA3_IOTA,true);const rotlH=(h,l,s)=>s>32?u64.rotlBH(h,l,s):u64.rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?u64.rotlBL(h,l,s):u64.rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;assert.number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){assert.exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];if(this.pos===blockLen)this.keccak()}return this}finish(){if(this.finished)return;this.finished=true;const{state,suffix,pos,blockLen}=this;state[pos]^=suffix;if((suffix&128)!==0&&pos===blockLen-1)this.keccak();state[blockLen-1]^=128;this.keccak()}writeInto(out){assert.exists(this,false);assert.bytes(out);this.finish();const bufferOut=this.state;const{blockLen}=this;for(let pos=0,len=out.length;pos<len;){if(this.posOut>=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){assert.number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){assert.output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));const sha3_224=gen(6,144,224/8);const sha3_256=gen(6,136,256/8);const sha3_384=gen(6,104,384/8);const sha3_512=gen(6,72,512/8);const keccak_224=gen(1,144,224/8);const keccak_256=gen(1,136,256/8);const keccak_384=gen(1,104,384/8);const keccak_512=gen(1,72,512/8);const genShake=(suffix,blockLen,outputLen)=>wrapConstructorWithOpts((opts={})=>new Keccak(blockLen,suffix,opts.dkLen===undefined?outputLen:opts.dkLen,true));const shake128=genShake(31,168,128/8);const shake256=genShake(31,136,256/8);let locked$3=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked$3=true};keccak256.register=function(func){if(locked$3){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);const Id=Uint8Array.from({length:16},(_,i)=>i);const Pi=Id.map(i=>(9*i+5)%16);let idxL=[Id];let idxR=[Pi];for(let i=0;i<4;i++)for(let j of[idxL,idxR])j.push(j[i].map(k=>Rho[k]));const shifts=[[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(i=>new Uint8Array(i));const shiftsL=idxL.map((idx,i)=>idx.map(j=>shifts[i][j]));const shiftsR=idxR.map((idx,i)=>idx.map(j=>shifts[i][j]));const Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]);const Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);const rotl$1=(word,shift)=>word<<shift|word>>>32-shift;function f(group,x,y,z){if(group===0)return x^y^z;else if(group===1)return x&y|~x&z;else if(group===2)return(x|~y)^z;else if(group===3)return x&z|y&~z;else return x^(y|~z)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,true);this.h0=1732584193|0;this.h1=4023233417|0;this.h2=2562383102|0;this.h3=271733878|0;this.h4=3285377520|0}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF[i]=view.getUint32(offset,true);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl[group],hbr=Kr[group];const rl=idxL[group],rr=idxR[group];const sl=shiftsL[group],sr=shiftsR[group];for(let i=0;i<16;i++){const tl=rotl$1(al+f(group,bl,cl,dl)+BUF[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl$1(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr=rotl$1(ar+f(rGroup,br,cr,dr)+BUF[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl$1(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=true;this.buffer.fill(0);this.set(0,0,0,0,0)}}const ripemd160$1=wrapConstructor(()=>new RIPEMD160);let locked$2=false;const _ripemd160=function(data){return ripemd160$1(data)};let __ripemd160=_ripemd160;function ripemd160(_data){const data=getBytes(_data,"data");return hexlify(__ripemd160(data))}ripemd160._=_ripemd160;ripemd160.lock=function(){locked$2=true};ripemd160.register=function(func){if(locked$2){throw new TypeError("ripemd160 is locked")}__ripemd160=func};Object.freeze(ripemd160);let locked$1=false;const _pbkdf2=function(password,salt,iterations,keylen,algo){return pbkdf2Sync(password,salt,iterations,keylen,algo)};let __pbkdf2=_pbkdf2;function pbkdf2(_password,_salt,iterations,keylen,algo){const password=getBytes(_password,"password");const salt=getBytes(_salt,"salt");return hexlify(__pbkdf2(password,salt,iterations,keylen,algo))}pbkdf2._=_pbkdf2;pbkdf2.lock=function(){locked$1=true};pbkdf2.register=function(func){if(locked$1){throw new Error("pbkdf2 is locked")}__pbkdf2=func};Object.freeze(pbkdf2);let locked=false;const _randomBytes=function(length){return new Uint8Array(randomBytes$1(length))};let __randomBytes=_randomBytes;function randomBytes(length){return __randomBytes(length)}randomBytes._=_randomBytes;randomBytes.lock=function(){locked=true};randomBytes.register=function(func){if(locked){throw new Error("random is locked")}__randomBytes=func};Object.freeze(randomBytes);const rotl=(a,b)=>a<<b|a>>>32-b;function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++];let y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++];let y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++];let y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++];let y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++];let y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++];let y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++];let y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++];let x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2){x04^=rotl(x00+x12|0,7);x08^=rotl(x04+x00|0,9);x12^=rotl(x08+x04|0,13);x00^=rotl(x12+x08|0,18);x09^=rotl(x05+x01|0,7);x13^=rotl(x09+x05|0,9);x01^=rotl(x13+x09|0,13);x05^=rotl(x01+x13|0,18);x14^=rotl(x10+x06|0,7);x02^=rotl(x14+x10|0,9);x06^=rotl(x02+x14|0,13);x10^=rotl(x06+x02|0,18);x03^=rotl(x15+x11|0,7);x07^=rotl(x03+x15|0,9);x11^=rotl(x07+x03|0,13);x15^=rotl(x11+x07|0,18);x01^=rotl(x00+x03|0,7);x02^=rotl(x01+x00|0,9);x03^=rotl(x02+x01|0,13);x00^=rotl(x03+x02|0,18);x06^=rotl(x05+x04|0,7);x07^=rotl(x06+x05|0,9);x04^=rotl(x07+x06|0,13);x05^=rotl(x04+x07|0,18);x11^=rotl(x10+x09|0,7);x08^=rotl(x11+x10|0,9);x09^=rotl(x08+x11|0,13);x10^=rotl(x09+x08|0,18);x12^=rotl(x15+x14|0,7);x13^=rotl(x12+x15|0,9);x14^=rotl(x13+x12|0,13);x15^=rotl(x14+x13|0,18)}out[oi++]=y00+x00|0;out[oi++]=y01+x01|0;out[oi++]=y02+x02|0;out[oi++]=y03+x03|0;out[oi++]=y04+x04|0;out[oi++]=y05+x05|0;out[oi++]=y06+x06|0;out[oi++]=y07+x07|0;out[oi++]=y08+x08|0;out[oi++]=y09+x09|0;out[oi++]=y10+x10|0;out[oi++]=y11+x11|0;out[oi++]=y12+x12|0;out[oi++]=y13+x13|0;out[oi++]=y14+x14|0;out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0;let tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+(2*r-1)*16+i];for(let i=0;i<r;i++,head+=16,ii+=16){XorAndSalsa(out,tail,input,ii,out,head);if(i>0)tail+=16;XorAndSalsa(out,head,input,ii+=16,out,tail)}}function scryptInit(password,salt,_opts){const opts=checkOpts({dkLen:32,asyncTick:10,maxmem:1024**3+1024},_opts);const{N,r,p,dkLen,asyncTick,maxmem,onProgress}=opts;assert.number(N);assert.number(r);assert.number(p);assert.number(dkLen);assert.number(asyncTick);assert.number(maxmem);if(onProgress!==undefined&&typeof onProgress!=="function")throw new Error("progressCb should be function");const blockSize=128*r;const blockSize32=blockSize/4;if(N<=1||(N&N-1)!==0||N>=2**(blockSize/8)||N>2**32){throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32")}if(p<0||p>(2**32-1)*32/blockSize){throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)")}if(dkLen<0||dkLen>(2**32-1)*32){throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32")}const memUsed=blockSize*(N+p);if(memUsed>maxmem){throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`)}const B=pbkdf2$1(sha256$1,password,salt,{c:1,dkLen:blockSize*p});const B32=u32(B);const V=u32(new Uint8Array(blockSize*N));const tmp=u32(new Uint8Array(blockSize));let blockMixCb=()=>{};if(onProgress){const totalBlockMix=2*N*p;const callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1);let blockMixCnt=0;blockMixCb=()=>{blockMixCnt++;if(onProgress&&(!(blockMixCnt%callbackPer)||blockMixCnt===totalBlockMix))onProgress(blockMixCnt/totalBlockMix)}}return{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){const res=pbkdf2$1(sha256$1,password,B,{c:1,dkLen:dkLen});B.fill(0);V.fill(0);tmp.fill(0);return res}function scrypt$1(password,salt,opts){const{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb}=scryptInit(password,salt,opts);for(let pi=0;pi<p;pi++){const Pi=blockSize32*pi;for(let i=0;i<blockSize32;i++)V[i]=B32[Pi+i];for(let i=0,pos=0;i<N-1;i++){BlockMix(V,pos,V,pos+=blockSize32,r);blockMixCb()}BlockMix(V,(N-1)*blockSize32,B32,Pi,r);blockMixCb();for(let i=0;i<N;i++){const j=B32[Pi+blockSize32-16]%N;for(let k=0;k<blockSize32;k++)tmp[k]=B32[Pi+k]^V[j*blockSize32+k];BlockMix(tmp,0,B32,Pi,r);blockMixCb()}}return scryptOutput(password,dkLen,B,V,tmp)}async function scryptAsync(password,salt,opts){const{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb,asyncTick}=scryptInit(password,salt,opts);for(let pi=0;pi<p;pi++){const Pi=blockSize32*pi;for(let i=0;i<blockSize32;i++)V[i]=B32[Pi+i];let pos=0;await asyncLoop(N-1,asyncTick,i=>{BlockMix(V,pos,V,pos+=blockSize32,r);blockMixCb()});BlockMix(V,(N-1)*blockSize32,B32,Pi,r);blockMixCb();await asyncLoop(N,asyncTick,i=>{const j=B32[Pi+blockSize32-16]%N;for(let k=0;k<blockSize32;k++)tmp[k]=B32[Pi+k]^V[j*blockSize32+k];BlockMix(tmp,0,B32,Pi,r);blockMixCb()})}return scryptOutput(password,dkLen,B,V,tmp)}let lockedSync=false,lockedAsync=false;const _scryptAsync=async function(passwd,salt,N,r,p,dkLen,onProgress){return await scryptAsync(passwd,salt,{N:N,r:r,p:p,dkLen:dkLen,onProgress:onProgress})};const _scryptSync=function(passwd,salt,N,r,p,dkLen){return scrypt$1(passwd,salt,{N:N,r:r,p:p,dkLen:dkLen})};let __scryptAsync=_scryptAsync;let __scryptSync=_scryptSync;async function scrypt(_passwd,_salt,N,r,p,dkLen,progress){const passwd=getBytes(_passwd,"passwd");const salt=getBytes(_salt,"salt");return hexlify(await __scryptAsync(passwd,salt,N,r,p,dkLen,progress))}scrypt._=_scryptAsync;scrypt.lock=function(){lockedAsync=true};scrypt.register=function(func){if(lockedAsync){throw new Error("scrypt is locked")}__scryptAsync=func};Object.freeze(scrypt);function scryptSync(_passwd,_salt,N,r,p,dkLen){const passwd=getBytes(_passwd,"passwd");const salt=getBytes(_salt,"salt");return hexlify(__scryptSync(passwd,salt,N,r,p,dkLen))}scryptSync._=_scryptSync;scryptSync.lock=function(){lockedSync=true};scryptSync.register=function(func){if(lockedSync){throw new Error("scryptSync is locked")}__scryptSync=func};Object.freeze(scryptSync);const _sha256=function(data){return createHash("sha256").update(data).digest()};const _sha512=function(data){return createHash("sha512").update(data).digest()};let __sha256=_sha256;let __sha512=_sha512;let locked256=false,locked512=false;function sha256(_data){const data=getBytes(_data,"data");return hexlify(__sha256(data))}sha256._=_sha256;sha256.lock=function(){locked256=true};sha256.register=function(func){if(locked256){throw new Error("sha256 is locked")}__sha256=func};Object.freeze(sha256);function sha512(_data){const data=getBytes(_data,"data");return hexlify(__sha512(data))}sha512._=_sha512;sha512.lock=function(){locked512=true};sha512.register=function(func){if(locked512){throw new Error("sha512 is locked")}__sha512=func};Object.freeze(sha256);var _nodeResolve_empty={};var nodeCrypto=Object.freeze({__proto__:null,default:_nodeResolve_empty});const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _3n=BigInt(3);const _8n=BigInt(8);const POW_2_256=_2n**BigInt(256);const CURVE={a:_0n,b:BigInt(7),P:POW_2_256-_2n**BigInt(32)-BigInt(977),n:POW_2_256-BigInt("432420386565659656852420866394968145599"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")};function weistrass(x){const{a,b}=CURVE;const x2=mod(x*x);const x3=mod(x2*x);return mod(x3+a*x+b)}const USE_ENDOMORPHISM=CURVE.a===_0n;class JacobianPoint{constructor(x,y,z){this.x=x;this.y=y;this.z=z}static fromAffine(p){if(!(p instanceof Point)){throw new TypeError("JacobianPoint#fromAffine: expected Point")}return new JacobianPoint(p.x,p.y,_1n)}static toAffineBatch(points){const toInv=invertBatch(points.map(p=>p.z));return points.map((p,i)=>p.toAffine(toInv[i]))}static normalizeZ(points){return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine)}equals(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this;const{x:X2,y:Y2,z:Z2}=other;const Z1Z1=mod(Z1**_2n);const Z2Z2=mod(Z2**_2n);const U1=mod(X1*Z2Z2);const U2=mod(X2*Z1Z1);const S1=mod(mod(Y1*Z2)*Z2Z2);const S2=mod(mod(Y2*Z1)*Z1Z1);return U1===U2&&S1===S2}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:X1,y:Y1,z:Z1}=this;const A=mod(X1**_2n);const B=mod(Y1**_2n);const C=mod(B**_2n);const D=mod(_2n*(mod((X1+B)**_2n)-A-C));const E=mod(_3n*A);const F=mod(E**_2n);const X3=mod(F-_2n*D);const Y3=mod(E*(D-X3)-_8n*C);const Z3=mod(_2n*Y1*Z1);return new JacobianPoint(X3,Y3,Z3)}add(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this;const{x:X2,y:Y2,z:Z2}=other;if(X2===_0n||Y2===_0n)return this;if(X1===_0n||Y1===_0n)return other;const Z1Z1=mod(Z1**_2n);const Z2Z2=mod(Z2**_2n);const U1=mod(X1*Z2Z2);const U2=mod(X2*Z1Z1);const S1=mod(mod(Y1*Z2)*Z2Z2);const S2=mod(mod(Y2*Z1)*Z1Z1);const H=mod(U2-U1);const r=mod(S2-S1);if(H===_0n){if(r===_0n){return this.double()}else{return JacobianPoint.ZERO}}const HH=mod(H**_2n);const HHH=mod(H*HH);const V=mod(U1*HH);const X3=mod(r**_2n-HHH-_2n*V);const Y3=mod(r*(V-X3)-S1*HHH);const Z3=mod(Z1*Z2*H);return new JacobianPoint(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}multiplyUnsafe(scalar){const P0=JacobianPoint.ZERO;if(typeof scalar==="bigint"&&scalar===_0n)return P0;let n=normalizeScalar(scalar);if(n===_1n)return this;if(!USE_ENDOMORPHISM){let p=P0;let d=this;while(n>_0n){if(n&_1n)p=p.add(d);d=d.double();n>>=_1n}return p}let{k1neg,k1,k2neg,k2}=splitScalarEndo(n);let k1p=P0;let k2p=P0;let d=this;while(k1>_0n||k2>_0n){if(k1&_1n)k1p=k1p.add(d);if(k2&_1n)k2p=k2p.add(d);d=d.double();k1>>=_1n;k2>>=_1n}if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z);return k1p.add(k2p)}precomputeWindow(W){const windows=USE_ENDOMORPHISM?128/W+1:256/W+1;const points=[];let p=this;let base=p;for(let window=0;window<windows;window++){base=p;points.push(base);for(let i=1;i<2**(W-1);i++){base=base.add(p);points.push(base)}p=base.double()}return points}wNAF(n,affinePoint){if(!affinePoint&&this.equals(JacobianPoint.BASE))affinePoint=Point.BASE;const W=affinePoint&&affinePoint._WINDOW_SIZE||1;if(256%W){throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2")}let precomputes=affinePoint&&pointPrecomputes.get(affinePoint);if(!precomputes){precomputes=this.precomputeWindow(W);if(affinePoint&&W!==1){precomputes=JacobianPoint.normalizeZ(precomputes);pointPrecomputes.set(affinePoint,precomputes)}}let p=JacobianPoint.ZERO;let f=JacobianPoint.ZERO;const windows=1+(USE_ENDOMORPHISM?128/W:256/W);const windowSize=2**(W-1);const mask=BigInt(2**W-1);const maxNumber=2**W;const shiftBy=BigInt(W);for(let window=0;window<windows;window++){const offset=window*windowSize;let wbits=Number(n&mask);n>>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n}if(wbits===0){let pr=precomputes[offset];if(window%2)pr=pr.negate();f=f.add(pr)}else{let cached=precomputes[offset+Math.abs(wbits)-1];if(wbits<0)cached=cached.negate();p=p.add(cached)}}return{p:p,f:f}}multiply(scalar,affinePoint){let n=normalizeScalar(scalar);let point;let fake;if(USE_ENDOMORPHISM){const{k1neg,k1,k2neg,k2}=splitScalarEndo(n);let{p:k1p,f:f1p}=this.wNAF(k1,affinePoint);let{p:k2p,f:f2p}=this.wNAF(k2,affinePoint);if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p,f}=this.wNAF(n,affinePoint);point=p;fake=f}return JacobianPoint.normalizeZ([point,fake])[0]}toAffine(invZ=invert(this.z)){const{x,y,z}=this;const iz1=invZ;const iz2=mod(iz1*iz1);const iz3=mod(iz2*iz1);const ax=mod(x*iz2);const ay=mod(y*iz3);const zz=mod(z*iz1);if(zz!==_1n)throw new Error("invZ was invalid");return new Point(ax,ay)}}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);const pointPrecomputes=new WeakMap;class Point{constructor(x,y){this.x=x;this.y=y}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize;pointPrecomputes.delete(this)}static fromCompressedHex(bytes){const isShort=bytes.length===32;const x=bytesToNumber(isShort?bytes:bytes.subarray(1));if(!isValidFieldElement(x))throw new Error("Point is not on curve");const y2=weistrass(x);let y=sqrtMod(y2);const isYOdd=(y&_1n)===_1n;if(isShort){if(isYOdd)y=mod(-y)}else{const isFirstByteOdd=(bytes[0]&1)===1;if(isFirstByteOdd!==isYOdd)y=mod(-y)}const point=new Point(x,y);point.assertValidity();return point}static fromUncompressedHex(bytes){const x=bytesToNumber(bytes.subarray(1,33));const y=bytesToNumber(bytes.subarray(33,65));const point=new Point(x,y);point.assertValidity();return point}static fromHex(hex){const bytes=ensureBytes(hex);const len=bytes.length;const header=bytes[0];if(len===32||len===33&&(header===2||header===3)){return this.fromCompressedHex(bytes)}if(len===65&&header===4)return this.fromUncompressedHex(bytes);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`)}static fromPrivateKey(privateKey){return Point.BASE.multiply(normalizePrivateKey(privateKey))}static fromSignature(msgHash,signature,recovery){msgHash=ensureBytes(msgHash);const h=truncateHash(msgHash);const{r,s}=normalizeSignature(signature);if(recovery!==0&&recovery!==1){throw new Error("Cannot recover signature: invalid recovery bit")}const prefix=recovery&1?"03":"02";const R=Point.fromHex(prefix+numTo32bStr(r));const{n}=CURVE;const rinv=invert(r,n);const u1=mod(-h*rinv,n);const u2=mod(s*rinv,n);const Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("Cannot recover signature: point at infinify");Q.assertValidity();return Q}toRawBytes(isCompressed=false){return hexToBytes(this.toHex(isCompressed))}toHex(isCompressed=false){const x=numTo32bStr(this.x);if(isCompressed){const prefix=this.y&_1n?"03":"02";return`${prefix}${x}`}else{return`04${x}${numTo32bStr(this.y)}`}}toHexX(){return this.toHex(true).slice(2)}toRawX(){return this.toRawBytes(true).slice(1)}assertValidity(){const msg="Point is not on elliptic curve";const{x,y}=this;if(!isValidFieldElement(x)||!isValidFieldElement(y))throw new Error(msg);const left=mod(y*y);const right=weistrass(x);if(mod(left-right)!==_0n)throw new Error(msg)}equals(other){return this.x===other.x&&this.y===other.y}negate(){return new Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(other){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine()}subtract(other){return this.add(other.negate())}multiply(scalar){return JacobianPoint.fromAffine(this).multiply(scalar,this).toAffine()}multiplyAndAddUnsafe(Q,a,b){const P=JacobianPoint.fromAffine(this);const aP=a===_0n||a===_1n||this!==Point.BASE?P.multiplyUnsafe(a):P.multiply(a);const bQ=JacobianPoint.fromAffine(Q).multiplyUnsafe(b);const sum=aP.add(bQ);return sum.equals(JacobianPoint.ZERO)?undefined:sum.toAffine()}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy);Point.ZERO=new Point(_0n,_0n);function sliceDER(s){return Number.parseInt(s[0],16)>=8?"00"+s:s}function parseDERInt(data){if(data.length<2||data[0]!==2){throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`)}const len=data[1];const res=data.subarray(2,len+2);if(!len||res.length!==len){throw new Error(`Invalid signature integer: wrong length`)}if(res[0]===0&&res[1]<=127){throw new Error("Invalid signature integer: trailing length")}return{data:bytesToNumber(res),left:data.subarray(len+2)}}function parseDERSignature(data){if(data.length<2||data[0]!=48){throw new Error(`Invalid signature tag: ${bytesToHex(data)}`)}if(data[1]!==data.length-2){throw new Error("Invalid signature: incorrect length")}const{data:r,left:sBytes}=parseDERInt(data.subarray(2));const{data:s,left:rBytesLeft}=parseDERInt(sBytes);if(rBytesLeft.length){throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`)}return{r:r,s:s}}class Signature$1{constructor(r,s){this.r=r;this.s=s;this.assertValidity()}static fromCompact(hex){const arr=isUint8a(hex);const name="Signature.fromCompact";if(typeof hex!=="string"&&!arr)throw new TypeError(`${name}: Expected string or Uint8Array`);const str=arr?bytesToHex(hex):hex;if(str.length!==128)throw new Error(`${name}: Expected 64-byte hex`);return new Signature$1(hexToNumber(str.slice(0,64)),hexToNumber(str.slice(64,128)))}static fromDER(hex){const arr=isUint8a(hex);if(typeof hex!=="string"&&!arr)throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);const{r,s}=parseDERSignature(arr?hex:hexToBytes(hex));return new Signature$1(r,s)}static fromHex(hex){return this.fromDER(hex)}assertValidity(){const{r,s}=this;if(!isWithinCurveOrder(r))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(s))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const HALF=CURVE.n>>_1n;return this.s>HALF}normalizeS(){return this.hasHighS()?new Signature$1(this.r,CURVE.n-this.s):this}toDERRawBytes(isCompressed=false){return hexToBytes(this.toDERHex(isCompressed))}toDERHex(isCompressed=false){const sHex=sliceDER(numberToHexUnpadded(this.s));if(isCompressed)return sHex;const rHex=sliceDER(numberToHexUnpadded(this.r));const rLen=numberToHexUnpadded(rHex.length/2);const sLen=numberToHexUnpadded(sHex.length/2);const length=numberToHexUnpadded(rHex.length/2+sHex.length/2+4);return`30${length}02${rLen}${rHex}02${sLen}${sHex}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function concatBytes(...arrays){if(!arrays.every(isUint8a))throw new Error("Uint8Array list expected");if(arrays.length===1)return arrays[0];const length=arrays.reduce((a,arr)=>a+arr.length,0);const result=new Uint8Array(length);for(let i=0,pad=0;i<arrays.length;i++){const arr=arrays[i];result.set(arr,pad);pad+=arr.length}return result}function isUint8a(bytes){return bytes instanceof Uint8Array}const hexes=Array.from({length:256},(v,i)=>i.toString(16).padStart(2,"0"));function bytesToHex(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Expected Uint8Array");let hex="";for(let i=0;i<uint8a.length;i++){hex+=hexes[uint8a[i]]}return hex}function numTo32bStr(num){if(num>POW_2_256)throw new Error("Expected number < 2^256");return num.toString(16).padStart(64,"0")}function numTo32b(num){return hexToBytes(numTo32bStr(num))}function numberToHexUnpadded(num){const hex=num.toString(16);return hex.length&1?`0${hex}`:hex}function hexToNumber(hex){if(typeof hex!=="string"){throw new TypeError("hexToNumber: expected string, got "+typeof hex)}return BigInt(`0x${hex}`)}function hexToBytes(hex){if(typeof hex!=="string"){throw new TypeError("hexToBytes: expected string, got "+typeof hex)}if(hex.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+hex.length);const array=new Uint8Array(hex.length/2);for(let i=0;i<array.length;i++){const j=i*2;const hexByte=hex.slice(j,j+2);const byte=Number.parseInt(hexByte,16);if(Number.isNaN(byte)||byte<0)throw new Error("Invalid byte sequence");array[i]=byte}return array}function bytesToNumber(bytes){return hexToNumber(bytesToHex(bytes))}function ensureBytes(hex){return hex instanceof Uint8Array?Uint8Array.from(hex):hexToBytes(hex)}function normalizeScalar(num){if(typeof num==="number"&&Number.isSafeInteger(num)&&num>0)return BigInt(num);if(typeof num==="bigint"&&isWithinCurveOrder(num))return num;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(a,b=CURVE.P){const result=a%b;return result>=_0n?result:b+result}function pow2(x,power){const{P}=CURVE;let res=x;while(power-- >_0n){res*=res;res%=P}return res}function sqrtMod(x){const{P}=CURVE;const _6n=BigInt(6);const _11n=BigInt(11);const _22n=BigInt(22);const _23n=BigInt(23);const _44n=BigInt(44);const _88n=BigInt(88);const b2=x*x*x%P;const b3=b2*b2*x%P;const b6=pow2(b3,_3n)*b3%P;const b9=pow2(b6,_3n)*b3%P;const b11=pow2(b9,_2n)*b2%P;const b22=pow2(b11,_11n)*b11%P;const b44=pow2(b22,_22n)*b22%P;const b88=pow2(b44,_44n)*b44%P;const b176=pow2(b88,_88n)*b88%P;const b220=pow2(b176,_44n)*b44%P;const b223=pow2(b220,_3n)*b3%P;const t1=pow2(b223,_23n)*b22%P;const t2=pow2(t1,_6n)*b2%P;return pow2(t2,_2n)}function invert(number,modulo=CURVE.P){if(number===_0n||modulo<=_0n){throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`)}let a=mod(number,modulo);let b=modulo;let x=_0n,y=_1n,u=_1n,v=_0n;while(a!==_0n){const q=b/a;const r=b%a;const m=x-u*q;const n=y-v*q;b=a,a=r,x=u,y=v,u=m,v=n}const gcd=b;if(gcd!==_1n)throw new Error("invert: does not exist");return mod(x,modulo)}function invertBatch(nums,p=CURVE.P){const scratch=new Array(nums.length);const lastMultiplied=nums.reduce((acc,num,i)=>{if(num===_0n)return acc;scratch[i]=acc;return mod(acc*num,p)},_1n);const inverted=invert(lastMultiplied,p);nums.reduceRight((acc,num,i)=>{if(num===_0n)return acc;scratch[i]=mod(acc*scratch[i],p);return mod(acc*num,p)},inverted);return scratch}const divNearest=(a,b)=>(a+b/_2n)/b;const POW_2_128=_2n**BigInt(128);function splitScalarEndo(k){const{n}=CURVE;const a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15");const b1=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3");const a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");const b2=a1;const c1=divNearest(b2*k,n);const c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n);let k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128;const k2neg=k2>POW_2_128;if(k1neg)k1=n-k1;if(k2neg)k2=n-k2;if(k1>POW_2_128||k2>POW_2_128){throw new Error("splitScalarEndo: Endomorphism failed, k="+k)}return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}function truncateHash(hash){const{n}=CURVE;const byteLength=hash.length;const delta=byteLength*8-256;let h=bytesToNumber(hash);if(delta>0)h=h>>BigInt(delta);if(h>=n)h-=n;return h}class HmacDrbg{constructor(){this.v=new Uint8Array(32).fill(1);this.k=new Uint8Array(32).fill(0);this.counter=0}hmac(...values){return utils.hmacSha256(this.k,...values)}hmacSync(...values){if(typeof utils.hmacSha256Sync!=="function")throw new Error("utils.hmacSha256Sync is undefined, you need to set it");const res=utils.hmacSha256Sync(this.k,...values);if(res instanceof Promise)throw new Error("To use sync sign(), ensure utils.hmacSha256 is sync");return res}incr(){if(this.counter>=1e3){throw new Error("Tried 1,000 k values for sign(), all were invalid")}this.counter+=1}async reseed(seed=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),seed);this.v=await this.hmac(this.v);if(seed.length===0)return;this.k=await this.hmac(this.v,Uint8Array.from([1]),seed);this.v=await this.hmac(this.v)}reseedSync(seed=new Uint8Array){this.k=this.hmacSync(this.v,Uint8Array.from([0]),seed);this.v=this.hmacSync(this.v);if(seed.length===0)return;this.k=this.hmacSync(this.v,Uint8Array.from([1]),seed);this.v=this.hmacSync(this.v)}async generate(){this.incr();this.v=await this.hmac(this.v);return this.v}generateSync(){this.incr();this.v=this.hmacSync(this.v);return this.v}}function isWithinCurveOrder(num){return _0n<num&&num<CURVE.n}function isValidFieldElement(num){return _0n<num&&num<CURVE.P}function kmdToSig(kBytes,m,d){const k=bytesToNumber(kBytes);if(!isWithinCurveOrder(k))return;const{n}=CURVE;const q=Point.BASE.multiply(k);const r=mod(q.x,n);if(r===_0n)return;const s=mod(invert(k,n)*mod(m+d*r,n),n);if(s===_0n)return;const sig=new Signature$1(r,s);const recovery=(q.x===sig.r?0:2)|Number(q.y&_1n);return{sig:sig,recovery:recovery}}function normalizePrivateKey(key){let num;if(typeof key==="bigint"){num=key}else if(typeof key==="number"&&Number.isSafeInteger(key)&&key>0){num=BigInt(key)}else if(typeof key==="string"){if(key.length!==64)throw new Error("Expected 32 bytes of private key");num=hexToNumber(key)}else if(isUint8a(key)){if(key.length!==32)throw new Error("Expected 32 bytes of private key");num=bytesToNumber(key)}else{throw new TypeError("Expected valid private key")}if(!isWithinCurveOrder(num))throw new Error("Expected private key: 0 < key < n");return num}function normalizePublicKey(publicKey){if(publicKey instanceof Point){publicKey.assertValidity();return publicKey}else{return Point.fromHex(publicKey)}}function normalizeSignature(signature){if(signature instanceof Signature$1){signature.assertValidity();return signature}try{return Signature$1.fromDER(signature)}catch(error){return Signature$1.fromCompact(signature)}}function getPublicKey(privateKey,isCompressed=false){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)}function recoverPublicKey(msgHash,signature,recovery,isCompressed=false){return Point.fromSignature(msgHash,signature,recovery).toRawBytes(isCompressed)}function isPub(item){const arr=isUint8a(item);const str=typeof item==="string";const len=(arr||str)&&item.length;if(arr)return len===33||len===65;if(str)return len===66||len===130;if(item instanceof Point)return true;return false}function getSharedSecret(privateA,publicB,isCompressed=false){if(isPub(privateA))throw new TypeError("getSharedSecret: first arg must be private key");if(!isPub(publicB))throw new TypeError("getSharedSecret: second arg must be public key");const b=normalizePublicKey(publicB);b.assertValidity();return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed)}function bits2int(bytes){const slice=bytes.length>32?bytes.slice(0,32):bytes;return bytesToNumber(slice)}function bits2octets(bytes){const z1=bits2int(bytes);const z2=mod(z1,CURVE.n);return int2octets(z2<_0n?z1:z2)}function int2octets(num){if(typeof num!=="bigint")throw new Error("Expected bigint");const hex=numTo32bStr(num);return hexToBytes(hex)}function initSigArgs(msgHash,privateKey,extraEntropy){if(msgHash==null)throw new Error(`sign: expected valid message hash, not "${msgHash}"`);const h1=ensureBytes(msgHash);const d=normalizePrivateKey(privateKey);const seedArgs=[int2octets(d),bits2octets(h1)];if(extraEntropy!=null){if(extraEntropy===true)extraEntropy=utils.randomBytes(32);const e=ensureBytes(extraEntropy);if(e.length!==32)throw new Error("sign: Expected 32 bytes of extra data");seedArgs.push(e)}const seed=concatBytes(...seedArgs);const m=bits2int(h1);return{seed:seed,m:m,d:d}}function finalizeSig(recSig,opts){let{sig,recovery}=recSig;const{canonical,der,recovered}=Object.assign({canonical:true,der:true},opts);if(canonical&&sig.hasHighS()){sig=sig.normalizeS();recovery^=1}const hashed=der?sig.toDERRawBytes():sig.toCompactRawBytes();return recovered?[hashed,recovery]:hashed}async function sign(msgHash,privKey,opts={}){const{seed,m,d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;await drbg.reseed(seed);while(!(sig=kmdToSig(await drbg.generate(),m,d)))await drbg.reseed();return finalizeSig(sig,opts)}function signSync(msgHash,privKey,opts={}){const{seed,m,d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;drbg.reseedSync(seed);while(!(sig=kmdToSig(drbg.generateSync(),m,d)))drbg.reseedSync();return finalizeSig(sig,opts)}const vopts={strict:true};function verify(signature,msgHash,publicKey,opts=vopts){let sig;try{sig=normalizeSignature(signature);msgHash=ensureBytes(msgHash)}catch(error){return false}const{r,s}=sig;if(opts.strict&&sig.hasHighS())return false;const h=truncateHash(msgHash);let P;try{P=normalizePublicKey(publicKey)}catch(error){return false}const{n}=CURVE;const sinv=invert(s,n);const u1=mod(h*sinv,n);const u2=mod(r*sinv,n);const R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2);if(!R)return false;const v=mod(R.x,n);return v===r}function finalizeSchnorrChallenge(ch){return mod(bytesToNumber(ch),CURVE.n)}function hasEvenY(point){return(point.y&_1n)===_0n}class SchnorrSignature{constructor(r,s){this.r=r;this.s=s;this.assertValidity()}static fromHex(hex){const bytes=ensureBytes(hex);if(bytes.length!==64)throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);const r=bytesToNumber(bytes.subarray(0,32));const s=bytesToNumber(bytes.subarray(32,64));return new SchnorrSignature(r,s)}assertValidity(){const{r,s}=this;if(!isValidFieldElement(r)||!isWithinCurveOrder(s))throw new Error("Invalid signature")}toHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}toRawBytes(){return hexToBytes(this.toHex())}}function schnorrGetPublicKey(privateKey){return Point.fromPrivateKey(privateKey).toRawX()}function initSchnorrSigArgs(message,privateKey,auxRand){if(message==null)throw new TypeError(`sign: Expected valid message, not "${message}"`);const m=ensureBytes(message);const d0=normalizePrivateKey(privateKey);const rand=ensureBytes(auxRand);if(rand.length!==32)throw new TypeError("sign: Expected 32 bytes of aux randomness");const P=Point.fromPrivateKey(d0);const px=P.toRawX();const d=hasEvenY(P)?d0:CURVE.n-d0;return{m:m,P:P,px:px,d:d,rand:rand}}function initSchnorrNonce(d,t0h){return numTo32b(d^bytesToNumber(t0h))}function finalizeSchnorrNonce(k0h){const k0=mod(bytesToNumber(k0h),CURVE.n);if(k0===_0n)throw new Error("sign: Creation of signature failed. k is zero");const R=Point.fromPrivateKey(k0);const rx=R.toRawX();const k=hasEvenY(R)?k0:CURVE.n-k0;return{R:R,rx:rx,k:k}}function finalizeSchnorrSig(R,k,e,d){return new SchnorrSignature(R.x,mod(k+e*d,CURVE.n)).toRawBytes()}async function schnorrSign(message,privateKey,auxRand=utils.randomBytes()){const{m,px,d,rand}=initSchnorrSigArgs(message,privateKey,auxRand);const t=initSchnorrNonce(d,await utils.taggedHash(TAGS.aux,rand));const{R,rx,k}=finalizeSchnorrNonce(await utils.taggedHash(TAGS.nonce,t,px,m));const e=finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge,rx,px,m));const sig=finalizeSchnorrSig(R,k,e,d);const isValid=await schnorrVerify(sig,m,px);if(!isValid)throw new Error("sign: Invalid signature produced");return sig}function schnorrSignSync(message,privateKey,auxRand=utils.randomBytes()){const{m,px,d,rand}=initSchnorrSigArgs(message,privateKey,auxRand);const t=initSchnorrNonce(d,utils.taggedHashSync(TAGS.aux,rand));const{R,rx,k}=finalizeSchnorrNonce(utils.taggedHashSync(TAGS.nonce,t,px,m));const e=finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge,rx,px,m));const sig=finalizeSchnorrSig(R,k,e,d);const isValid=schnorrVerifySync(sig,m,px);if(!isValid)throw new Error("sign: Invalid signature produced");return sig}function initSchnorrVerify(signature,message,publicKey){const raw=signature instanceof SchnorrSignature;const sig=raw?signature:SchnorrSignature.fromHex(signature);if(raw)sig.assertValidity();return{...sig,m:ensureBytes(message),P:normalizePublicKey(publicKey)}}function finalizeSchnorrVerify(r,P,s,e){const R=Point.BASE.multiplyAndAddUnsafe(P,normalizePrivateKey(s),mod(-e,CURVE.n));if(!R||!hasEvenY(R)||R.x!==r)return false;return true}async function schnorrVerify(signature,message,publicKey){try{const{r,s,m,P}=initSchnorrVerify(signature,message,publicKey);const e=finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){return false}}function schnorrVerifySync(signature,message,publicKey){try{const{r,s,m,P}=initSchnorrVerify(signature,message,publicKey);const e=finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){return false}}const schnorr={Signature:SchnorrSignature,getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,signSync:schnorrSignSync,verifySync:schnorrVerifySync};Point.BASE._setWindowSize(8);const crypto={node:nodeCrypto,web:typeof self==="object"&&"crypto"in self?self.crypto:undefined};const TAGS={challenge:"BIP0340/challenge",aux:"BIP0340/aux",nonce:"BIP0340/nonce"};const TAGGED_HASH_PREFIXES={};const utils={isValidPrivateKey(privateKey){try{normalizePrivateKey(privateKey);return true}catch(error){return false}},privateAdd:(privateKey,tweak)=>{const p=normalizePrivateKey(privateKey);const t=normalizePrivateKey(tweak);return numTo32b(mod(p+t,CURVE.n))},privateNegate:privateKey=>{const p=normalizePrivateKey(privateKey);return numTo32b(CURVE.n-p)},pointAddScalar:(p,tweak,isCompressed)=>{const P=Point.fromHex(p);const t=normalizePrivateKey(tweak);const Q=Point.BASE.multiplyAndAddUnsafe(P,t,_1n);if(!Q)throw new Error("Tweaked point at infinity");return Q.toRawBytes(isCompressed)},pointMultiply:(p,tweak,isCompressed)=>{const P=Point.fromHex(p);const t=bytesToNumber(ensureBytes(tweak));return P.multiply(t).toRawBytes(isCompressed)},hashToPrivateKey:hash=>{hash=ensureBytes(hash);if(hash.length<40||hash.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");const num=mod(bytesToNumber(hash),CURVE.n-_1n)+_1n;return numTo32b(num)},randomBytes:(bytesLength=32)=>{if(crypto.web){return crypto.web.getRandomValues(new Uint8Array(bytesLength))}else if(crypto.node){const{randomBytes}=crypto.node;return Uint8Array.from(randomBytes(bytesLength))}else{throw new Error("The environment doesn't have randomBytes function")}},randomPrivateKey:()=>{return utils.hashToPrivateKey(utils.randomBytes(40))},bytesToHex:bytesToHex,hexToBytes:hexToBytes,concatBytes:concatBytes,mod:mod,invert:invert,sha256:async(...messages)=>{if(crypto.web){const buffer=await crypto.web.subtle.digest("SHA-256",concatBytes(...messages));return new Uint8Array(buffer)}else if(crypto.node){const{createHash}=crypto.node;const hash=createHash("sha256");messages.forEach(m=>hash.update(m));return Uint8Array.from(hash.digest())}else{throw new Error("The environment doesn't have sha256 function")}},hmacSha256:async(key,...messages)=>{if(crypto.web){const ckey=await crypto.web.subtle.importKey("raw",key,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);const message=concatBytes(...messages);const buffer=await crypto.web.subtle.sign("HMAC",ckey,message);return new Uint8Array(buffer)}else if(crypto.node){const{createHmac}=crypto.node;const hash=createHmac("sha256",key);messages.forEach(m=>hash.update(m));return Uint8Array.from(hash.digest())}else{throw new Error("The environment doesn't have hmac-sha256 function")}},sha256Sync:undefined,hmacSha256Sync:undefined,taggedHash:async(tag,...messages)=>{let tagP=TAGGED_HASH_PREFIXES[tag];if(tagP===undefined){const tagH=await utils.sha256(Uint8Array.from(tag,c=>c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return utils.sha256(tagP,...messages)},taggedHashSync:(tag,...messages)=>{if(typeof utils.sha256Sync!=="function")throw new Error("utils.sha256Sync is undefined, you need to set it");let tagP=TAGGED_HASH_PREFIXES[tag];if(tagP===undefined){const tagH=utils.sha256Sync(Uint8Array.from(tag,c=>c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return utils.sha256Sync(tagP,...messages)},precompute(windowSize=8,point=Point.BASE){const cached=point===Point.BASE?point:new Point(point.x,point.y);cached._setWindowSize(windowSize);cached.multiply(_3n);return cached}};const ZeroAddress="0x0000000000000000000000000000000000000000";const ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000";const NegativeOne=BigInt(-1);const Zero=BigInt(0);const One=BigInt(1);const Two=BigInt(2);const N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const WeiPerEther=BigInt("1000000000000000000");const MaxUint256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const MinInt256=BigInt("0x8000000000000000000000000000000000000000000000000000000000000000")*NegativeOne;const MaxInt256=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const EtherSymbol="Ξ";const MessagePrefix="Ethereum Signed Message:\n";const BN_0$4=BigInt(0);const BN_1$4=BigInt(1);const BN_2$3=BigInt(2);const BN_27$1=BigInt(27);const BN_28$1=BigInt(28);const BN_35$1=BigInt(35);const _guard$3={};class Signature{#props;get r(){return getStore(this.#props,"r")}set r(value){if(dataLength(value)!==32){throwArgumentError("invalid r","value",value)}setStore(this.#props,"r",hexlify(value))}get s(){return getStore(this.#props,"s")}set s(value){if(dataLength(value)!==32){throwArgumentError("invalid r","value",value)}else if(getBytes(value)[0]&128){throwArgumentError("non-canonical s","value",value)}setStore(this.#props,"s",hexlify(value))}get v(){return getStore(this.#props,"v")}set v(value){const v=getNumber(value,"value");if(v!==27&&v!==28){throw new Error("@TODO")}setStore(this.#props,"v",v)}get networkV(){return getStore(this.#props,"networkV")}get legacyChainId(){const v=this.networkV;if(v==null){return null}return Signature.getChainId(v)}get yParity(){if(this.v===27){return 0}return 1}get yParityAndS(){const yParityAndS=getBytes(this.s);if(this.yParity){yParityAndS[0]|=128}return hexlify(yParityAndS)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(guard,r,s,v){assertPrivate(guard,_guard$3,"Signature");this.#props={r:r,s:s,v:v,networkV:null}}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const clone=new Signature(_guard$3,this.r,this.s,this.v);if(this.networkV){setStore(clone.#props,"networkV",this.networkV)}return clone}freeze(){Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}toJSON(){const networkV=this.networkV;return{_type:"signature",networkV:networkV!=null?networkV.toString():null,r:this.r,s:this.s,v:this.v}}static create(){return new Signature(_guard$3,ZeroHash,ZeroHash,27)}static getChainId(v){const bv=getBigInt(v,"v");if(bv==BN_27$1||bv==BN_28$1){return BN_0$4}if(bv<BN_35$1){throwArgumentError("invalid EIP-155 v","v",v)}return(bv-BN_35$1)/BN_2$3}static getChainIdV(chainId,v){return getBigInt(chainId)*BN_2$3+BigInt(35+v-27)}static getNormalizedV(v){const bv=getBigInt(v);if(bv==BN_0$4){return 27}if(bv==BN_1$4){return 28}return bv&BN_1$4?27:28}static from(sig){const throwError=message=>{return throwArgumentError(message,"signature",sig)};if(typeof sig==="string"){const bytes=getBytes(sig,"signature");if(bytes.length===64){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);const v=s[0]&128?28:27;s[0]&=127;return new Signature(_guard$3,r,hexlify(s),v)}if(dataLength(sig)!==65){const r=hexlify(sig.slice(0,32));const s=bytes.slice(32,64);if(s[0]&128){throwError("non-canonical s")}const v=Signature.getNormalizedV(bytes[64]);return new Signature(_guard$3,r,hexlify(s),v)}return throwError("invlaid raw signature length")}if(sig instanceof Signature){return sig.clone()}const r=sig.r;if(r==null){throwError("missing r")}if(!isHexString(r,32)){throwError("invalid r")}const s=function(s,yParityAndS){if(s!=null){if(!isHexString(s,32)){throwError("invalid s")}return s}if(yParityAndS!=null){if(!isHexString(yParityAndS,32)){throwError("invalid yParityAndS")}const bytes=getBytes(yParityAndS);bytes[0]&=127;return hexlify(bytes)}return throwError("missing s")}(sig.s,sig.yParityAndS);if(getBytes(s)[0]&128){throwError("non-canonical s")}const{networkV,v}=function(_v,yParityAndS,yParity){if(_v!=null){const v=getBigInt(_v);return{networkV:v>=BN_35$1?v:undefined,v:Signature.getNormalizedV(v)}}if(yParityAndS!=null){if(!isHexString(yParityAndS,32)){throwError("invalid yParityAndS")}return{v:getBytes(yParityAndS)[0]&128?28:27}}if(yParity!=null){switch(yParity){case 0:return{v:27};case 1:return{v:28}}return throwError("invalid yParity")}return throwError("missing v")}(sig.v,sig.yParityAndS,sig.yParity);const result=new Signature(_guard$3,r,s,v);if(networkV){setStore(result.#props,"networkV",networkV)}if("yParity"in sig&&sig.yParity!==result.yParity){throwError("yParity mismatch")}else if("yParityAndS"in sig&&sig.yParityAndS!==result.yParityAndS){throwError("yParityAndS mismatch")}return result}}utils.hmacSha256Sync=function(key,...messages){return getBytes(computeHmac("sha256",key,concat(messages)))};class SigningKey{#privateKey;constructor(privateKey){this.#privateKey=hexlify(privateKey)}get privateKey(){return this.#privateKey}get publicKey(){return SigningKey.computePublicKey(this.#privateKey)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#privateKey,true)}sign(digest){const[sigDer,recid]=signSync(getBytesCopy(digest),getBytesCopy(this.#privateKey),{recovered:true,canonical:true});const sig=Signature$1.fromHex(sigDer);return Signature.from({r:toHex("0x"+sig.r.toString(16),32),s:toHex("0x"+sig.s.toString(16),32),v:recid?28:27}).freeze()}computeShardSecret(other){const pubKey=SigningKey.computePublicKey(other);return hexlify(getSharedSecret(getBytesCopy(this.#privateKey),pubKey))}static computePublicKey(key,compressed){let bytes=getBytes(key,"key");if(bytes.length===32){const pubKey=getPublicKey(bytes,!!compressed);return hexlify(pubKey)}if(bytes.length===64){const pub=new Uint8Array(65);pub[0]=4;pub.set(bytes,1);bytes=pub}const point=Point.fromHex(bytes);return hexlify(point.toRawBytes(compressed))}static recoverPublicKey(digest,signature){const sig=Signature.from(signature);const der=Signature$1.fromCompact(getBytesCopy(concat([sig.r,sig.s]))).toDERRawBytes();const pubKey=recoverPublicKey(getBytesCopy(digest),der,sig.yParity);if(pubKey!=null){return hexlify(pubKey)}return throwArgumentError("invalid signautre for digest","signature",signature)}static _addPoints(p0,p1,compressed){const pub0=Point.fromHex(SigningKey.computePublicKey(p0).substring(2));const pub1=Point.fromHex(SigningKey.computePublicKey(p1).substring(2));return"0x"+pub0.add(pub1).toHex(!!compressed)}}function lock(){computeHmac.lock();keccak256.lock();pbkdf2.lock();randomBytes.lock();ripemd160.lock();scrypt.lock();scryptSync.lock();sha256.lock();sha512.lock()}const BN_0$3=BigInt(0);const BN_36=BigInt(36);function getChecksumAddress(address){address=address.toLowerCase();const chars=address.substring(2).split("");const expanded=new Uint8Array(40);for(let i=0;i<40;i++){expanded[i]=chars[i].charCodeAt(0)}const hashed=getBytes(keccak256(expanded));for(let i=0;i<40;i+=2){if(hashed[i>>1]>>4>=8){chars[i]=chars[i].toUpperCase()}if((hashed[i>>1]&15)>=8){chars[i+1]=chars[i+1].toUpperCase()}}return"0x"+chars.join("")}const ibanLookup={};for(let i=0;i<10;i++){ibanLookup[String(i)]=String(i)}for(let i=0;i<26;i++){ibanLookup[String.fromCharCode(65+i)]=String(10+i)}const safeDigits=15;function ibanChecksum(address){address=address.toUpperCase();address=address.substring(4)+address.substring(0,2)+"00";let expanded=address.split("").map(c=>{return ibanLookup[c]}).join("");while(expanded.length>=safeDigits){let block=expanded.substring(0,safeDigits);expanded=parseInt(block,10)%97+expanded.substring(block.length)}let checksum=String(98-parseInt(expanded,10)%97);while(checksum.length<2){checksum="0"+checksum}return checksum}const Base36=function(){const result={};for(let i=0;i<36;i++){const key="0123456789abcdefghijklmnopqrstuvwxyz"[i];result[key]=BigInt(i)}return result}();function fromBase36(value){value=value.toLowerCase();let result=BN_0$3;for(let i=0;i<value.length;i++){result=result*BN_36+Base36[value[i]]}return result}function getAddress(address){if(typeof address!=="string"){throwArgumentError("invalid address","address",address)}if(address.match(/^(0x)?[0-9a-fA-F]{40}$/)){if(address.substring(0,2)!=="0x"){address="0x"+address}const result=getChecksumAddress(address);if(address.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&result!==address){throwArgumentError("bad address checksum","address",address)}return result}if(address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){if(address.substring(2,4)!==ibanChecksum(address)){throwArgumentError("bad icap checksum","address",address)}let result=fromBase36(address.substring(4)).toString(16);while(result.length<40){result="0"+result}return getChecksumAddress("0x"+result)}return throwArgumentError("invalid address","address",address)}function getIcapAddress(address){let base36=BigInt(getAddress(address)).toString(36).toUpperCase();while(base36.length<30){base36="0"+base36}return"XE"+ibanChecksum("XE00"+base36)+base36}function getCreateAddress(tx){const from=getAddress(tx.from);const nonce=getBigInt(tx.nonce,"tx.nonce");let nonceHex=nonce.toString(16);if(nonceHex==="0"){nonceHex="0x"}else if(nonceHex.length%2){nonceHex="0x0"+nonceHex}else{nonceHex="0x"+nonceHex}return getAddress(dataSlice(keccak256(encodeRlp([from,nonceHex])),12))}function getCreate2Address(_from,_salt,_initCodeHash){const from=getAddress(_from);const salt=getBytes(_salt,"salt");const initCodeHash=getBytes(_initCodeHash,"initCodeHash");if(salt.length!==32){throwArgumentError("salt must be 32 bytes","salt",_salt)}if(initCodeHash.length!==32){throwArgumentError("initCodeHash must be 32 bytes","initCodeHash",_initCodeHash)}return getAddress(dataSlice(keccak256(concat(["0xff",from,salt,initCodeHash])),12))}function isAddressable(value){return value&&typeof value.getAddress==="function"}function isAddress(value){try{getAddress(value);return true}catch(error){}return false}async function checkAddress(target,promise){const result=await promise;if(result==null||result==="0x0000000000000000000000000000000000000000"){if(typeof target==="string"){return throwError("unconfigured name","UNCONFIGURED_NAME",{value:target})}return throwArgumentError("invalid AddressLike value; did not resolve to a value address","target",target)}return getAddress(result)}function resolveAddress(target,resolver){if(typeof target==="string"){if(target.match(/^0x[0-9a-f]{40}$/i)){return getAddress(target)}if(resolver==null){return throwError("ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"})}return checkAddress(target,resolver.resolveName(target))}else if(isAddressable(target)){return checkAddress(target,target.getAddress())}else if(typeof target.then==="function"){return checkAddress(target,target)}return throwArgumentError("unsupported addressable value","target",target)}const _gaurd={};function n(value,width){let signed=false;if(width<0){signed=true;width*=-1}return new Typed(_gaurd,`${signed?"":"u"}int${width}`,value,{signed:signed,width:width})}function b(value,size){return new Typed(_gaurd,`bytes${size?size:""}`,value,{size:size})}const _typedSymbol=Symbol.for("_ethers_typed");class Typed{type;value;#options;_typedSymbol;constructor(gaurd,type,value,options=null){if(gaurd!==_gaurd){throw new Error("private constructor")}defineProperties(this,{_typedSymbol:_typedSymbol,type:type,value:value});this.#options=options;this.format()}format(){if(this.type==="array"){throw new Error("")}else if(this.type==="dynamicArray"){throw new Error("")}else if(this.type==="tuple"){return`tuple(${this.value.map(v=>v.format()).join(",")})`}return this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.substring(0,5)==="bytes"}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple"){throw TypeError("not a tuple")}return this.#options}get arrayLength(){if(this.type!=="array"){throw TypeError("not an array")}if(this.#options===true){return-1}if(this.#options===false){return this.value.length}return null}static from(type,value){return new Typed(_gaurd,type,value)}static uint8(v){return n(v,8)}static uint16(v){return n(v,16)}static uint24(v){return n(v,24)}static uint32(v){return n(v,32)}static uint40(v){return n(v,40)}static uint48(v){return n(v,46)}static uint56(v){return n(v,56)}static uint64(v){return n(v,64)}static uint72(v){return n(v,72)}static uint80(v){return n(v,80)}static uint88(v){return n(v,88)}static uint96(v){return n(v,96)}static uint104(v){return n(v,104)}static uint112(v){return n(v,112)}static uint120(v){return n(v,120)}static uint128(v){return n(v,128)}static uint136(v){return n(v,136)}static uint144(v){return n(v,144)}static uint152(v){return n(v,152)}static uint160(v){return n(v,160)}static uint168(v){return n(v,168)}static uint176(v){return n(v,176)}static uint184(v){return n(v,184)}static uint192(v){return n(v,192)}static uint200(v){return n(v,200)}static uint208(v){return n(v,208)}static uint216(v){return n(v,216)}static uint224(v){return n(v,224)}static uint232(v){return n(v,232)}static uint240(v){return n(v,240)}static uint248(v){return n(v,248)}static uint256(v){return n(v,256)}static uint(v){return n(v,256)}static int8(v){return n(v,-8)}static int16(v){return n(v,-16)}static int24(v){return n(v,-24)}static int32(v){return n(v,-32)}static int40(v){return n(v,-40)}static int48(v){return n(v,-46)}static int56(v){return n(v,-56)}static int64(v){return n(v,-64)}static int72(v){return n(v,-72)}static int80(v){return n(v,-80)}static int88(v){return n(v,-88)}static int96(v){return n(v,-96)}static int104(v){return n(v,-104)}static int112(v){return n(v,-112)}static int120(v){return n(v,-120)}static int128(v){return n(v,-128)}static int136(v){return n(v,-136)}static int144(v){return n(v,-144)}static int152(v){return n(v,-152)}static int160(v){return n(v,-160)}static int168(v){return n(v,-168)}static int176(v){return n(v,-176)}static int184(v){return n(v,-184)}static int192(v){return n(v,-192)}static int200(v){return n(v,-200)}static int208(v){return n(v,-208)}static int216(v){return n(v,-216)}static int224(v){return n(v,-224)}static int232(v){return n(v,-232)}static int240(v){return n(v,-240)}static int248(v){return n(v,-248)}static int256(v){return n(v,-256)}static int(v){return n(v,-256)}static bytes(v){return b(v)}static bytes1(v){return b(v,1)}static bytes2(v){return b(v,2)}static bytes3(v){return b(v,3)}static bytes4(v){return b(v,4)}static bytes5(v){return b(v,5)}static bytes6(v){return b(v,6)}static bytes7(v){return b(v,7)}static bytes8(v){return b(v,8)}static bytes9(v){return b(v,9)}static bytes10(v){return b(v,10)}static bytes11(v){return b(v,11)}static bytes12(v){return b(v,12)}static bytes13(v){return b(v,13)}static bytes14(v){return b(v,14)}static bytes15(v){return b(v,15)}static bytes16(v){return b(v,16)}static bytes17(v){return b(v,17)}static bytes18(v){return b(v,18)}static bytes19(v){return b(v,19)}static bytes20(v){return b(v,20)}static bytes21(v){return b(v,21)}static bytes22(v){return b(v,22)}static bytes23(v){return b(v,23)}static bytes24(v){return b(v,24)}static bytes25(v){return b(v,25)}static bytes26(v){return b(v,26)}static bytes27(v){return b(v,27)}static bytes28(v){return b(v,28)}static bytes29(v){return b(v,29)}static bytes30(v){return b(v,30)}static bytes31(v){return b(v,31)}static bytes32(v){return b(v,32)}static address(v){return new Typed(_gaurd,"address",v)}static bool(v){return new Typed(_gaurd,"bool",!!v)}static string(v){return new Typed(_gaurd,"string",v)}static array(v,dynamic){throw new Error("not implemented yet");return new Typed(_gaurd,"array",v,dynamic)}static tuple(v,name){throw new Error("not implemented yet");return new Typed(_gaurd,"tuple",v,name)}static overrides(v){return new Typed(_gaurd,"overrides",Object.assign({},v))}static isTyped(value){return value&&value._typedSymbol===_typedSymbol}static dereference(value,type){if(Typed.isTyped(value)){if(value.type!==type){throw new Error(`invalid type: expecetd ${type}, got ${value.type}`)}return value.value}return value}}class AddressCoder extends Coder{constructor(localName){super("address","address",localName,false)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(writer,_value){let value=Typed.dereference(_value,"string");try{value=getAddress(value)}catch(error){return this._throwError(error.message,_value)}return writer.writeValue(value)}decode(reader){return getAddress(toHex(reader.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(coder){super(coder.name,coder.type,"_",coder.dynamic);this.coder=coder}defaultValue(){return this.coder.defaultValue()}encode(writer,value){return this.coder.encode(writer,value)}decode(reader){return this.coder.decode(reader)}}function pack(writer,coders,values){let arrayValues=[];if(Array.isArray(values)){arrayValues=values}else if(values&&typeof values==="object"){let unique={};arrayValues=coders.map(coder=>{const name=coder.localName;if(!name){throwError("cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values})}if(unique[name]){throwError("cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values})}unique[name]=true;return values[name]})}else{throwArgumentError("invalid tuple value","tuple",values)}if(coders.length!==arrayValues.length){throwArgumentError("types/value length mismatch","tuple",values)}let staticWriter=new Writer;let dynamicWriter=new Writer;let updateFuncs=[];coders.forEach((coder,index)=>{let value=arrayValues[index];if(coder.dynamic){let dynamicOffset=dynamicWriter.length;coder.encode(dynamicWriter,value);let updateFunc=staticWriter.writeUpdatableValue();updateFuncs.push(baseOffset=>{updateFunc(baseOffset+dynamicOffset)})}else{coder.encode(staticWriter,value)}});updateFuncs.forEach(func=>{func(staticWriter.length)});let length=writer.appendWriter(staticWriter);length+=writer.appendWriter(dynamicWriter);return length}function unpack(reader,coders){let values=[];let keys=[];let baseReader=reader.subReader(0);coders.forEach(coder=>{let value=null;if(coder.dynamic){let offset=reader.readIndex();let offsetReader=baseReader.subReader(offset);try{value=coder.decode(offsetReader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}else{try{value=coder.decode(reader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}if(value==undefined){throw new Error("investigate")}values.push(value);keys.push(coder.localName||null)});return Result.fromItems(values,keys)}class ArrayCoder extends Coder{coder;length;constructor(coder,length,localName){const type=coder.type+"["+(length>=0?length:"")+"]";const dynamic=length===-1||coder.dynamic;super("array",type,localName,dynamic);defineProperties(this,{coder:coder,length:length})}defaultValue(){const defaultChild=this.coder.defaultValue();const result=[];for(let i=0;i<this.length;i++){result.push(defaultChild)}return result}encode(writer,_value){const value=Typed.dereference(_value,"array");if(!Array.isArray(value)){this._throwError("expected array value",value)}let count=this.length;if(count===-1){count=value.length;writer.writeValue(value.length)}assertArgumentCount(value.length,count,"coder array"+(this.localName?" "+this.localName:""));let coders=[];for(let i=0;i<value.length;i++){coders.push(this.coder)}return pack(writer,coders,value)}decode(reader){let count=this.length;if(count===-1){count=reader.readIndex();if(count*WordSize>reader.dataLength){throwError("insufficient data length","BUFFER_OVERRUN",{buffer:reader.bytes,offset:count*WordSize,length:reader.dataLength})}}let coders=[];for(let i=0;i<count;i++){coders.push(new AnonymousCoder(this.coder))}return unpack(reader,coders)}}class BooleanCoder extends Coder{constructor(localName){super("bool","bool",localName,false)}defaultValue(){return false}encode(writer,_value){const value=Typed.dereference(_value,"bool");return writer.writeValue(value?1:0)}decode(reader){return!!reader.readValue()}}class DynamicBytesCoder extends Coder{constructor(type,localName){super(type,type,localName,true)}defaultValue(){return"0x"}encode(writer,value){value=getBytesCopy(value);let length=writer.writeValue(value.length);length+=writer.writeBytes(value);return length}decode(reader){return reader.readBytes(reader.readIndex(),true)}}class BytesCoder extends DynamicBytesCoder{constructor(localName){super("bytes",localName)}decode(reader){return hexlify(super.decode(reader))}}class FixedBytesCoder extends Coder{size;constructor(size,localName){let name="bytes"+String(size);super(name,name,localName,false);defineProperties(this,{size:size},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(writer,_value){let data=getBytesCopy(Typed.dereference(_value,this.type));if(data.length!==this.size){this._throwError("incorrect data length",_value)}return writer.writeBytes(data)}decode(reader){return hexlify(reader.readBytes(this.size))}}const Empty$1=new Uint8Array([]);class NullCoder extends Coder{constructor(localName){super("null","",localName,false)}defaultValue(){return null}encode(writer,value){if(value!=null){this._throwError("not null",value)}return writer.writeBytes(Empty$1)}decode(reader){reader.readBytes(0);return null}}const BN_0$2=BigInt(0);const BN_1$3=BigInt(1);const BN_MAX_UINT256$2=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class NumberCoder extends Coder{size;signed;constructor(size,signed,localName){const name=(signed?"int":"uint")+size*8;super(name,name,localName,false);defineProperties(this,{size:size,signed:signed},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(writer,_value){let value=getBigInt(Typed.dereference(_value,this.type));let maxUintValue=mask(BN_MAX_UINT256$2,WordSize*8);if(this.signed){let bounds=mask(maxUintValue,this.size*8-1);if(value>bounds||value<-(bounds+BN_1$3)){this._throwError("value out-of-bounds",_value)}}else if(value<BN_0$2||value>mask(maxUintValue,this.size*8)){this._throwError("value out-of-bounds",_value)}value=mask(toTwos(value,this.size*8),this.size*8);if(this.signed){value=toTwos(fromTwos(value,this.size*8),8*WordSize)}return writer.writeValue(value)}decode(reader){let value=mask(reader.readValue(),this.size*8);if(this.signed){value=fromTwos(value,this.size*8)}return value}}class StringCoder extends DynamicBytesCoder{constructor(localName){super("string",localName)}defaultValue(){return""}encode(writer,_value){return super.encode(writer,toUtf8Bytes(Typed.dereference(_value,"string")))}decode(reader){return toUtf8String(super.decode(reader))}}class TupleCoder extends Coder{coders;constructor(coders,localName){let dynamic=false;const types=[];coders.forEach(coder=>{if(coder.dynamic){dynamic=true}types.push(coder.type)});const type="tuple("+types.join(",")+")";super("tuple",type,localName,dynamic);defineProperties(this,{coders:Object.freeze(coders.slice())})}defaultValue(){const values=[];this.coders.forEach(coder=>{values.push(coder.defaultValue())});const uniqueNames=this.coders.reduce((accum,coder)=>{const name=coder.localName;if(name){if(!accum[name]){accum[name]=0}accum[name]++}return accum},{});this.coders.forEach((coder,index)=>{let name=coder.localName;if(!name||uniqueNames[name]!==1){return}if(name==="length"){name="_length"}if(values[name]!=null){return}values[name]=values[index]});return Object.freeze(values)}encode(writer,_value){const value=Typed.dereference(_value,"tuple");return pack(writer,this.coders,value)}decode(reader){return unpack(reader,this.coders)}}function id(value){return keccak256(toUtf8Bytes(value))}function ens_normalize(name){return name}const Zeros=new Uint8Array(32);Zeros.fill(0);function checkComponent(comp){if(comp.length===0){throw new Error("invalid ENS name; empty component")}return comp}function ensNameSplit(name){const bytes=toUtf8Bytes(ens_normalize(name));const comps=[];if(name.length===0){return comps}let last=0;for(let i=0;i<bytes.length;i++){const d=bytes[i];if(d===46){comps.push(checkComponent(bytes.slice(last,i)));last=i+1}}if(last>=bytes.length){throw new Error("invalid ENS name; empty component")}comps.push(checkComponent(bytes.slice(last)));return comps}function ensNormalize(name){return ensNameSplit(name).map(comp=>toUtf8String(comp)).join(".")}function isValidName(name){try{return ensNameSplit(name).length!==0}catch(error){}return false}function namehash(name){if(typeof name!=="string"){throwArgumentError("invalid ENS name; not a string","name",name)}let result=Zeros;const comps=ensNameSplit(name);while(comps.length){result=keccak256(concat([result,keccak256(comps.pop())]))}return hexlify(result)}function dnsEncode(name){return hexlify(concat(ensNameSplit(name).map(comp=>{if(comp.length>63){throw new Error("invalid DNS encoded entry; length exceeds 63 bytes")}const bytes=new Uint8Array(comp.length+1);bytes.set(comp,1);bytes[0]=bytes.length-1;return bytes})))+"00"}function hashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(MessagePrefix),toUtf8Bytes(String(message.length)),message]))}const regexBytes=new RegExp("^bytes([0-9]+)$");const regexNumber$1=new RegExp("^(u?int)([0-9]*)$");const regexArray=new RegExp("^(.*)\\[([0-9]*)\\]$");function _pack(type,value,isArray){switch(type){case"address":if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(value);case"string":return toUtf8Bytes(value);case"bytes":return getBytes(value);case"bool":value=!!value?"0x01":"0x00";if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(value)}let match=type.match(regexNumber$1);if(match){let size=parseInt(match[2]||"256");if(match[2]&&String(size)!==match[2]||size%8!==0||size===0||size>256){return throwArgumentError("invalid number type","type",type)}if(isArray){size=256}value=toTwos(value,size);return getBytes(zeroPadValue(toArray(value),size/8))}match=type.match(regexBytes);if(match){const size=parseInt(match[1]);if(String(size)!==match[1]||size===0||size>32){return throwArgumentError("invalid bytes type","type",type)}if(dataLength(value)!==size){return throwArgumentError(`invalid value for ${type}`,"value",value)}if(isArray){return getBytes(zeroPadBytes(value,32))}return value}match=type.match(regexArray);if(match&&Array.isArray(value)){const baseType=match[1];const count=parseInt(match[2]||String(value.length));if(count!=value.length){throwArgumentError(`invalid array length for ${type}`,"value",value)}const result=[];value.forEach(function(value){result.push(_pack(baseType,value,true))});return getBytes(concat(result))}return throwArgumentError("invalid type","type",type)}function solidityPacked(types,values){if(types.length!=values.length){throwArgumentError("wrong number of values; expected ${ types.length }","values",values)}const tight=[];types.forEach(function(type,index){tight.push(_pack(type,values[index]))});return hexlify(concat(tight))}function solidityPackedKeccak256(types,values){return keccak256(solidityPacked(types,values))}function solidityPackedSha256(types,values){return sha256(solidityPacked(types,values))}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1);const BN_0$1=BigInt(0);const BN_1$2=BigInt(1);const BN_MAX_UINT256$1=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(value){const bytes=getBytes(value);const padOffset=bytes.length%32;if(padOffset){return concat([bytes,padding.slice(padOffset)])}return hexlify(bytes)}const hexTrue=toHex(BN_1$2,32);const hexFalse=toHex(BN_0$1,32);const domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"};const domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(key){return function(value){if(typeof value!=="string"){throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`,`domain.${key}`,value)}return value}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(value){return getBigInt(value,"domain.chainId")},verifyingContract:function(value){try{return getAddress(value).toLowerCase()}catch(error){}return throwArgumentError(`invalid domain value "verifyingContract"`,"domain.verifyingContract",value)},salt:function(value){const bytes=getBytes(value,"domain.salt");if(bytes.length!==32){throwArgumentError(`invalid domain value "salt"`,"domain.salt",value)}return hexlify(bytes)}};function getBaseEncoder(type){{const match=type.match(/^(u?)int(\d*)$/);if(match){const signed=match[1]==="";const width=parseInt(match[2]||"256");if(width%8!==0||width>256||match[2]&&match[2]!==String(width)){throwArgumentError("invalid numeric width","type",type)}const boundsUpper=mask(BN_MAX_UINT256$1,signed?width-1:width);const boundsLower=signed?(boundsUpper+BN_1$2)*BN__1:BN_0$1;return function(_value){const value=getBigInt(_value,"value");if(value<boundsLower||value>boundsUpper){throwArgumentError(`value out-of-bounds for ${type}`,"value",value)}return toHex(toTwos(value,256),32)}}}{const match=type.match(/^bytes(\d+)$/);if(match){const width=parseInt(match[1]);if(width===0||width>32||match[1]!==String(width)){throwArgumentError("invalid bytes width","type",type)}return function(value){const bytes=getBytes(value);if(bytes.length!==width){throwArgumentError(`invalid length for ${type}`,"value",value)}return hexPadRight(value)}}}switch(type){case"address":return function(value){return zeroPadValue(getAddress(value),32)};case"bool":return function(value){return!value?hexFalse:hexTrue};case"bytes":return function(value){return keccak256(value)};case"string":return function(value){return id(value)}}return null}function encodeType(name,fields){return`${name}(${fields.map(({name,type})=>type+" "+name).join(",")})`}class TypedDataEncoder{primaryType;#types;get types(){return JSON.parse(this.#types)}#fullTypes;#encoderCache;constructor(types){this.#types=JSON.stringify(types);this.#fullTypes=new Map;this.#encoderCache=new Map;const links=new Map;const parents=new Map;const subtypes=new Map;Object.keys(types).forEach(type=>{links.set(type,new Set);parents.set(type,[]);subtypes.set(type,new Set)});for(const name in types){const uniqueNames=new Set;for(const field of types[name]){if(uniqueNames.has(field.name)){throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`,"types",types)}uniqueNames.add(field.name);const baseType=field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]||null;if(baseType===name){throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`,"types",types)}const encoder=getBaseEncoder(baseType);if(encoder){continue}if(!parents.has(baseType)){throwArgumentError(`unknown type ${JSON.stringify(baseType)}`,"types",types)}parents.get(baseType).push(name);links.get(name).add(baseType)}}const primaryTypes=Array.from(parents.keys()).filter(n=>parents.get(n).length===0);if(primaryTypes.length===0){throwArgumentError("missing primary type","types",types)}else if(primaryTypes.length>1){throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map(t=>JSON.stringify(t)).join(", ")}`,"types",types)}defineProperties(this,{primaryType:primaryTypes[0]});function checkCircular(type,found){if(found.has(type)){throwArgumentError(`circular type reference to ${JSON.stringify(type)}`,"types",types)}found.add(type);for(const child of links.get(type)){if(!parents.has(child)){continue}checkCircular(child,found);for(const subtype of found){subtypes.get(subtype).add(child)}}found.delete(type)}checkCircular(this.primaryType,new Set);for(const[name,set]of subtypes){const st=Array.from(set);st.sort();this.#fullTypes.set(name,encodeType(name,types[name])+st.map(t=>encodeType(t,types[t])).join(""))}}getEncoder(type){let encoder=this.#encoderCache.get(type);if(!encoder){encoder=this.#getEncoder(type);this.#encoderCache.set(type,encoder)}return encoder}#getEncoder(type){{const encoder=getBaseEncoder(type);if(encoder){return encoder}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const subEncoder=this.getEncoder(subtype);const length=parseInt(match[3]);return value=>{if(length>=0&&value.length!==length){throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value)}let result=value.map(subEncoder);if(this.#fullTypes.has(subtype)){result=result.map(keccak256)}return keccak256(concat(result))}}const fields=this.types[type];if(fields){const encodedType=id(this.#fullTypes.get(type));return value=>{const values=fields.map(({name,type})=>{const result=this.getEncoder(type)(value[name]);if(this.#fullTypes.has(type)){return keccak256(result)}return result});values.unshift(encodedType);return concat(values)}}return throwArgumentError(`unknown type: ${type}`,"type",type)}encodeType(name){const result=this.#fullTypes.get(name);if(!result){return throwArgumentError(`unknown type: ${JSON.stringify(name)}`,"name",name)}return result}encodeData(type,value){return this.getEncoder(type)(value)}hashStruct(name,value){return keccak256(this.encodeData(name,value))}encode(value){return this.encodeData(this.primaryType,value)}hash(value){return this.hashStruct(this.primaryType,value)}_visit(type,value,callback){{const encoder=getBaseEncoder(type);if(encoder){return callback(type,value)}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const length=parseInt(match[3]);if(length>=0&&value.length!==length){throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value)}return value.map(v=>this._visit(subtype,v,callback))}const fields=this.types[type];if(fields){return fields.reduce((accum,{name,type})=>{accum[name]=this._visit(type,value[name],callback);return accum},{})}return throwArgumentError(`unknown type: ${type}`,"type",type)}visit(value,callback){return this._visit(this.primaryType,value,callback)}static from(types){return new TypedDataEncoder(types)}static getPrimaryType(types){return TypedDataEncoder.from(types).primaryType}static hashStruct(name,types,value){return TypedDataEncoder.from(types).hashStruct(name,value)}static hashDomain(domain){const domainFields=[];for(const name in domain){const type=domainFieldTypes[name];if(!type){throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`,"domain",domain)}domainFields.push({name:name,type:type})}domainFields.sort((a,b)=>{return domainFieldNames.indexOf(a.name)-domainFieldNames.indexOf(b.name)});return TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:domainFields},domain)}static encode(domain,types,value){return concat(["0x1901",TypedDataEncoder.hashDomain(domain),TypedDataEncoder.from(types).hash(value)])}static hash(domain,types,value){return keccak256(TypedDataEncoder.encode(domain,types,value))}static async resolveNames(domain,types,value,resolveName){domain=Object.assign({},domain);const ensCache={};if(domain.verifyingContract&&!isHexString(domain.verifyingContract,20)){ensCache[domain.verifyingContract]="0x"}const encoder=TypedDataEncoder.from(types);encoder.visit(value,(type,value)=>{if(type==="address"&&!isHexString(value,20)){ensCache[value]="0x"}return value});for(const name in ensCache){ensCache[name]=await resolveName(name)}if(domain.verifyingContract&&ensCache[domain.verifyingContract]){domain.verifyingContract=ensCache[domain.verifyingContract]}value=encoder.visit(value,(type,value)=>{if(type==="address"&&ensCache[value]){return ensCache[value]}return value});return{domain:domain,value:value}}static getPayload(domain,types,value){TypedDataEncoder.hashDomain(domain);const domainValues={};const domainTypes=[];domainFieldNames.forEach(name=>{const value=domain[name];if(value==null){return}domainValues[name]=domainChecks[name](value);domainTypes.push({name:name,type:domainFieldTypes[name]})});const encoder=TypedDataEncoder.from(types);const typesWithDomain=Object.assign({},types);if(typesWithDomain.EIP712Domain){throwArgumentError("types must not contain EIP712Domain type","types.EIP712Domain",types)}else{typesWithDomain.EIP712Domain=domainTypes}encoder.encode(value);return{types:typesWithDomain,domain:domainValues,primaryType:encoder.primaryType,message:encoder.visit(value,(type,value)=>{if(type.match(/^bytes(\d*)/)){return hexlify(getBytes(value))}if(type.match(/^u?int/)){return getBigInt(value).toString()}switch(type){case"address":return value.toLowerCase();case"bool":return!!value;case"string":if(typeof value!=="string"){throwArgumentError(`invalid string`,"value",value)}return value}return throwArgumentError("unsupported type","type",type)})}}}function setify(items){const result=new Set;items.forEach(k=>result.add(k));return Object.freeze(result)}const _kwVisib="constant external internal payable private public pure view";const KwVisib=setify(_kwVisib.split(" "));const _kwTypes="constructor error event function struct";const KwTypes=setify(_kwTypes.split(" "));const _kwModifiers="calldata memory storage payable indexed";const KwModifiers=setify(_kwModifiers.split(" "));const _kwOther="tuple returns";const _keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" ");const Keywords=setify(_keywords.split(" "));const SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"};const regexWhitespace=new RegExp("^(\\s*)");const regexNumber=new RegExp("^([0-9]+)");const regexIdentifier=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");const regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))");class TokenString{#offset;#tokens;get offset(){return this.#offset}get length(){return this.#tokens.length-this.#offset}constructor(tokens){this.#offset=0;this.#tokens=tokens.slice()}clone(){return new TokenString(this.#tokens)}reset(){this.#offset=0}#subTokenString(from=0,to=0){return new TokenString(this.#tokens.slice(from,to).map(t=>{return Object.freeze(Object.assign({},t,{match:t.match-from,linkBack:t.linkBack-from,linkNext:t.linkNext-from}));return t}))}popKeyword(allowed){const top=this.peek();if(top.type!=="KEYWORD"||!allowed.has(top.text)){throw new Error(`expected keyword ${top.text}`)}return this.pop().text}popType(type){if(this.peek().type!==type){throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`)}return this.pop().text}popParen(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=this.#subTokenString(this.#offset+1,top.match+1);this.#offset=top.match+1;return result}popParams(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=[];while(this.#offset<top.match-1){const link=this.peek().linkNext;result.push(this.#subTokenString(this.#offset+1,link));this.#offset=link}this.#offset=top.match+1;return result}peek(){if(this.#offset>=this.#tokens.length){throw new Error("out-of-bounds")}return this.#tokens[this.#offset]}peekKeyword(allowed){const top=this.peekType("KEYWORD");return top!=null&&allowed.has(top)?top:null}peekType(type){if(this.length===0){return null}const top=this.peek();return top.type===type?top.text:null}pop(){const result=this.peek();this.#offset++;return result}toString(){const tokens=[];for(let i=this.#offset;i<this.#tokens.length;i++){const token=this.#tokens[i];tokens.push(`${token.type}:${token.text}`)}return`<TokenString ${tokens.join(" ")}>`}}function lex(text){const tokens=[];const throwError=message=>{const token=offset<text.length?JSON.stringify(text[offset]):"$EOI";throw new Error(`invalid token ${token} at ${offset}: ${message}`)};let brackets=[];let commas=[];let offset=0;while(offset<text.length){let cur=text.substring(offset);let match=cur.match(regexWhitespace);if(match){offset+=match[1].length;cur=text.substring(offset)}const token={depth:brackets.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:offset,value:-1};tokens.push(token);let type=SimpleTokens[cur[0]]||"";if(type){token.type=type;token.text=cur[0];offset++;if(type==="OPEN_PAREN"){brackets.push(tokens.length-1);commas.push(tokens.length-1)}else if(type=="CLOSE_PAREN"){if(brackets.length===0){throwError("no matching open bracket")}token.match=brackets.pop();tokens[token.match].match=tokens.length-1;token.depth--;token.linkBack=commas.pop();tokens[token.linkBack].linkNext=tokens.length-1}else if(type==="COMMA"){token.linkBack=commas.pop();tokens[token.linkBack].linkNext=tokens.length-1;commas.push(tokens.length-1)}else if(type==="OPEN_BRACKET"){token.type="BRACKET"}else if(type==="CLOSE_BRACKET"){let suffix=tokens.pop().text;if(tokens.length>0&&tokens[tokens.length-1].type==="NUMBER"){const value=tokens.pop().text;suffix=value+suffix;tokens[tokens.length-1].value=getNumber(value)}if(tokens.length===0||tokens[tokens.length-1].type!=="BRACKET"){throw new Error("missing opening bracket")}tokens[tokens.length-1].text+=suffix}continue}match=cur.match(regexIdentifier);if(match){token.text=match[1];offset+=token.text.length;if(Keywords.has(token.text)){token.type="KEYWORD";continue}if(token.text.match(regexType)){token.type="TYPE";continue}token.type="ID";continue}match=cur.match(regexNumber);if(match){token.text=match[1];token.type="NUMBER";offset+=token.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`)}return new TokenString(tokens.map(t=>Object.freeze(t)))}function allowSingle(set,allowed){let included=[];for(const key in allowed.keys()){if(set.has(key)){included.push(key)}}if(included.length>1){throw new Error(`conflicting types: ${included.join(", ")}`)}}function consumeName(type,tokens){if(tokens.peekKeyword(KwTypes)){const keyword=tokens.pop().text;if(keyword!==type){throw new Error(`expected ${type}, got ${keyword}`)}}return tokens.popType("ID")}function consumeKeywords(tokens,allowed){const keywords=new Set;while(true){const keyword=tokens.peekType("KEYWORD");if(keyword==null||allowed&&!allowed.has(keyword)){break}tokens.pop();if(keywords.has(keyword)){throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`)}keywords.add(keyword)}return Object.freeze(keywords)}function consumeMutability(tokens){let modifiers=consumeKeywords(tokens,KwVisib);allowSingle(modifiers,setify("constant payable nonpayable".split(" ")));allowSingle(modifiers,setify("pure view payable nonpayable".split(" ")));if(modifiers.has("view")){return"view"}if(modifiers.has("pure")){return"pure"}if(modifiers.has("payable")){return"payable"}if(modifiers.has("nonpayable")){return"nonpayable"}if(modifiers.has("constant")){return"view"}return"nonpayable"}function consumeParams(tokens,allowIndexed){return tokens.popParams().map(t=>ParamType.fromTokens(t,allowIndexed))}function consumeGas(tokens){if(tokens.peekType("AT")){tokens.pop();if(tokens.peekType("NUMBER")){return getBigInt(tokens.pop().text)}throw new Error("invalid gas")}return null}function consumeEoi(tokens){if(tokens.length){throw new Error(`unexpected tokens: ${tokens.toString()}`)}}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(type){const match=type.match(regexType);if(!match){return throwArgumentError("invalid type","type",type)}if(type==="uint"){return"uint256"}if(type==="int"){return"int256"}if(match[2]){const length=parseInt(match[2]);if(length===0||length>32){throwArgumentError("invalid bytes length","type",type)}}else if(match[3]){const size=parseInt(match[3]);if(size===0||size>256||size%8){throwArgumentError("invalid numeric width","type",type)}}return type}const _guard$2={};const internal$1=Symbol.for("_ethers_internal");const ParamTypeInternal="_ParamTypeInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(guard,name,type,baseType,indexed,components,arrayLength,arrayChildren){assertPrivate(guard,_guard$2,"ParamType");Object.defineProperty(this,internal$1,{value:ParamTypeInternal});if(components){components=Object.freeze(components.slice())}if(baseType==="array"){if(arrayLength==null||arrayChildren==null){throw new Error("")}}else if(arrayLength!=null||arrayChildren!=null){throw new Error("")}if(baseType==="tuple"){if(components==null){throw new Error("")}}else if(components!=null){throw new Error("")}defineProperties(this,{name:name,type:type,baseType:baseType,indexed:indexed,components:components,arrayLength:arrayLength,arrayChildren:arrayChildren})}format(format="sighash"){if(format==="json"){let result={type:this.baseType==="tuple"?"tuple":this.type,name:this.name||undefined};if(typeof this.indexed==="boolean"){result.indexed=this.indexed}if(this.isTuple()){result.components=this.components.map(c=>JSON.parse(c.format(format)))}return JSON.stringify(result)}let result="";if(this.isArray()){result+=this.arrayChildren.format(format);result+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`}else{if(this.isTuple()){if(format!=="sighash"){result+=this.type}result+="("+this.components.map(comp=>comp.format(format)).join(format==="full"?", ":",")+")"}else{result+=this.type}}if(format!=="sighash"){if(this.indexed===true){result+=" indexed"}if(format==="full"&&this.name){result+=" "+this.name}}return result}static isArray(value){return value&&value.baseType==="array"}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(value,process){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invlaid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const _this=this;return value.map(v=>_this.arrayChildren.walk(v,process))}if(this.isTuple()){if(!Array.isArray(value)){throw new Error("invlaid tuple value")}if(value.length!==this.components.length){throw new Error("array is wrong length")}const _this=this;return value.map((v,i)=>_this.components[i].walk(v,process))}return process(this.type,value)}#walkAsync(promises,value,process,setValue){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invlaid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const childType=this.arrayChildren;const result=value.slice();result.forEach((value,index)=>{childType.#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}if(this.isTuple()){const components=this.components;let result;if(Array.isArray(value)){result=value.slice()}else{if(value==null||typeof value!=="object"){throw new Error("invlaid tuple value")}result=components.map(param=>{if(!param.name){throw new Error("cannot use object value with unnamed components")}if(!(param.name in value)){throw new Error(`missing value for component ${param.name}`)}return value[param.name]})}if(value.length!==this.components.length){throw new Error("array is wrong length")}result.forEach((value,index)=>{components[index].#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}const result=process(this.type,value);if(result.then){promises.push(async function(){setValue(await result)}())}else{setValue(result)}}async walkAsync(value,process){const promises=[];const result=[value];this.#walkAsync(promises,value,process,value=>{result[0]=value});if(promises.length){await Promise.all(promises)}return result[0]}static from(obj,allowIndexed){if(ParamType.isParamType(obj)){return obj}if(typeof obj==="string"){return ParamType.fromTokens(lex(obj),allowIndexed)}if(obj instanceof TokenString){return ParamType.fromTokens(obj,allowIndexed)}const name=obj.name;if(name&&(typeof name!=="string"||!name.match(regexIdentifier))){throwArgumentError("invalid name","obj.name",name)}let indexed=obj.indexed;if(indexed!=null){if(!allowIndexed){throwArgumentError("parameter cannot be indexed","obj.indexed",obj.indexed)}indexed=!!indexed}let type=obj.type;let arrayMatch=type.match(regexArrayType);if(arrayMatch){const arrayLength=arrayMatch[2];const arrayChildren=ParamType.from({type:arrayMatch[1],components:obj.components});return new ParamType(_guard$2,name,type,"array",indexed,null,arrayLength,arrayChildren)}if(type.substring(0,5)==="tuple("||type[0]==="("){const comps=obj.components!=null?obj.components.map(c=>ParamType.from(c)):null;const tuple=new ParamType(_guard$2,name,type,"tuple",indexed,comps,null,null);return tuple}type=verifyBasicType(obj.type);return new ParamType(_guard$2,name,type,type,indexed,null,null,null)}static fromObject(obj,allowIndexed){throw new Error("@TODO")}static fromTokens(tokens,allowIndexed){let type="",baseType="";let comps=null;if(consumeKeywords(tokens,setify(["tuple"])).has("tuple")||tokens.peekType("OPEN_PAREN")){baseType="tuple";comps=tokens.popParams().map(t=>ParamType.from(t));type=`tuple(${comps.map(c=>c.format()).join(",")})`}else{type=verifyBasicType(tokens.popType("TYPE"));baseType=type}let arrayChildren=null;let arrayLength=null;while(tokens.length&&tokens.peekType("BRACKET")){const bracket=tokens.pop();arrayChildren=new ParamType(_guard$2,"",type,baseType,null,comps,arrayLength,arrayChildren);arrayLength=bracket.value;type+=bracket.text;baseType="array";comps=null}let indexed=null;const keywords=consumeKeywords(tokens,KwModifiers);if(keywords.has("indexed")){if(!allowIndexed){throw new Error("")}indexed=true}const name=tokens.peekType("ID")?tokens.pop().text:"";if(tokens.length){throw new Error("leftover tokens")}return new ParamType(_guard$2,name,type,baseType,indexed,comps,arrayLength,arrayChildren)}static isParamType(value){return value&&value[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(guard,type,inputs){assertPrivate(guard,_guard$2,"Fragment");inputs=Object.freeze(inputs.slice());defineProperties(this,{type:type,inputs:inputs})}static from(obj){if(typeof obj==="string"){return this.fromString(obj)}if(obj instanceof TokenString){return this.fromTokens(obj)}if(typeof obj==="object"){return this.fromObject(obj)}throw new Error(`unsupported type: ${obj}`)}static fromObject(obj){switch(obj.type){case"constructor":return ConstructorFragment.fromObject(obj);case"error":return ErrorFragment.fromObject(obj);case"event":return EventFragment.fromObject(obj);case"function":return FunctionFragment.fromObject(obj);case"struct":return StructFragment.fromObject(obj)}throw new Error("not implemented yet")}static fromString(text){try{Fragment.from(JSON.parse(text))}catch(e){}return Fragment.fromTokens(lex(text))}static fromTokens(tokens){const type=tokens.popKeyword(KwTypes);switch(type){case"constructor":return ConstructorFragment.fromTokens(tokens);case"error":return ErrorFragment.fromTokens(tokens);case"event":return EventFragment.fromTokens(tokens);case"function":return FunctionFragment.fromTokens(tokens);case"struct":return StructFragment.fromTokens(tokens)}throw new Error(`unsupported type: ${type}`)}static isConstructor(value){return value&&value.type==="constructor"}static isError(value){return value&&value.type==="error"}static isEvent(value){return value&&value.type==="event"}static isFunction(value){return value&&value.type==="function"}static isStruct(value){return value&&value.type==="struct"}}class NamedFragment extends Fragment{name;constructor(guard,type,name,inputs){super(guard,type,inputs);inputs=Object.freeze(inputs.slice());defineProperties(this,{name:name})}}function joinParams(format,params){return"("+params.map(p=>p.format(format)).join(format==="full"?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,"error",name,inputs)}get selector(){return id(this.format("sighash")).substring(0,10)}format(format="sighash"){if(format==="json"){return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(input=>JSON.parse(input.format(format)))})}const result=[];if(format!=="sighash"){result.push("error")}result.push(this.name+joinParams(format,this.inputs));return result.join(" ")}static fromString(text){return ErrorFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("error",tokens);const inputs=consumeParams(tokens);consumeEoi(tokens);return new ErrorFragment(_guard$2,name,inputs)}}class EventFragment extends NamedFragment{anonymous;constructor(guard,name,inputs,anonymous){super(guard,"event",name,inputs);defineProperties(this,{anonymous:anonymous})}get topicHash(){return id(this.format("sighash"))}format(format="sighash"){if(format==="json"){return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[];if(format!=="sighash"){result.push("event")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"&&this.anonymous){result.push("anonymous")}return result.join(" ")}static fromString(text){return EventFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("event",tokens);const inputs=consumeParams(tokens,true);const anonymous=!!consumeKeywords(tokens,setify(["anonymous"])).has("anonymous");consumeEoi(tokens);return new EventFragment(_guard$2,name,inputs,anonymous)}}class ConstructorFragment extends Fragment{payable;gas;constructor(guard,type,inputs,payable,gas){super(guard,type,inputs);defineProperties(this,{payable:payable,gas:gas})}format(format="sighash"){if(format==="sighash"){throwError("cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"})}if(format==="json"){return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[`constructor${joinParams(format,this.inputs)}`];result.push(this.payable?"payable":"nonpayable");if(this.gas!=null){result.push(`@${this.gas.toString()}`)}return result.join(" ")}static fromString(text){return ConstructorFragment.fromTokens(lex(text))}static fromObject(obj){throw new Error("TODO")}static fromTokens(tokens){consumeKeywords(tokens,setify(["constructor"]));const inputs=consumeParams(tokens);const payable=!!consumeKeywords(tokens,setify(["payable"])).has("payable");const gas=consumeGas(tokens);consumeEoi(tokens);return new ConstructorFragment(_guard$2,"constructor",inputs,payable,gas)}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(guard,name,stateMutability,inputs,outputs,gas){super(guard,"function",name,inputs);outputs=Object.freeze(outputs.slice());const constant=stateMutability==="view"||stateMutability==="pure";const payable=stateMutability==="payable";defineProperties(this,{constant:constant,gas:gas,outputs:outputs,payable:payable,stateMutability:stateMutability})}get selector(){return id(this.format("sighash")).substring(0,10)}format(format="sighash"){if(format==="json"){return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:undefined,payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format))),outputs:this.outputs.map(o=>JSON.parse(o.format(format)))})}const result=[];if(format!=="sighash"){result.push("function")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"){if(this.stateMutability!=="nonpayable"){result.push(this.stateMutability)}if(this.outputs&&this.outputs.length){result.push("returns");result.push(joinParams(format,this.outputs))}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}}return result.join(" ")}static fromString(text){return FunctionFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("function",tokens);const inputs=consumeParams(tokens);const mutability=consumeMutability(tokens);let outputs=[];if(consumeKeywords(tokens,setify(["returns"])).has("returns")){outputs=consumeParams(tokens)}const gas=consumeGas(tokens);consumeEoi(tokens);return new FunctionFragment(_guard$2,name,mutability,inputs,outputs,gas)}}class StructFragment extends NamedFragment{format(){throw new Error("@TODO")}static fromString(text){return StructFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("struct",tokens);const inputs=consumeParams(tokens);consumeEoi(tokens);return new StructFragment(_guard$2,"struct",name,inputs)}}const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/);const paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);class AbiCoder{#getCoder(param){if(param.isArray()){return new ArrayCoder(this.#getCoder(param.arrayChildren),param.arrayLength,param.name)}if(param.isTuple()){return new TupleCoder(param.components.map(c=>this.#getCoder(c)),param.name)}switch(param.baseType){case"address":return new AddressCoder(param.name);case"bool":return new BooleanCoder(param.name);case"string":return new StringCoder(param.name);case"bytes":return new BytesCoder(param.name);case"":return new NullCoder(param.name)}let match=param.type.match(paramTypeNumber);if(match){let size=parseInt(match[2]||"256");if(size===0||size>256||size%8!==0){throwArgumentError("invalid "+match[1]+" bit length","param",param)}return new NumberCoder(size/8,match[1]==="int",param.name)}match=param.type.match(paramTypeBytes);if(match){let size=parseInt(match[1]);if(size===0||size>32){throwArgumentError("invalid bytes length","param",param)}return new FixedBytesCoder(size,param.name)}return throwArgumentError("invalid type","type",param.type)}getDefaultValue(types){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.defaultValue()}encode(types,values){assertArgumentCount(values.length,types.length,"types/values length mismatch");const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");const writer=new Writer;coder.encode(writer,values);return writer.data}decode(types,data,loose){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.decode(new Reader(data,loose))}}const defaultAbiCoder=new AbiCoder;function formatBytes32String(text){const bytes=toUtf8Bytes(text);if(bytes.length>31){throw new Error("bytes32 string must be less than 32 bytes")}return zeroPadBytes(bytes,32)}function parseBytes32String(_bytes){const data=getBytes(_bytes,"bytes");if(data.length!==32){throw new Error("invalid bytes32 - not 32 bytes long")}if(data[31]!==0){throw new Error("invalid bytes32 string - no null terminator")}let length=31;while(data[length-1]===0){length--}return toUtf8String(data.slice(0,length))}class LogDescription{fragment;name;signature;topic;args;constructor(fragment,topic,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,signature:signature,topic:topic,args:args})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(fragment,selector,args,value){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector,value:value})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(fragment,selector,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector})}}class Indexed{hash;_isIndexed;static isIndexed(value){return!!(value&&value._isIndexed)}constructor(hash){defineProperties(this,{hash:hash,_isIndexed:true})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"};const BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:message=>{return`reverted with reason string ${JSON.stringify(message)}`}},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:code=>{let reason="unknown panic code";if(code>=0&&code<=255&&PanicReasons[code.toString()]){reason=PanicReasons[code.toString()]}return`reverted with panic code 0x${code.toString(16)} (${reason})`}}};class Interface{fragments;deploy;#errors;#events;#functions;#abiCoder;constructor(fragments){let abi=[];if(typeof fragments==="string"){abi=JSON.parse(fragments)}else{abi=fragments}this.#functions=new Map;this.#errors=new Map;this.#events=new Map;defineProperties(this,{fragments:Object.freeze(abi.map(f=>Fragment.from(f)).filter(f=>f!=null))});this.#abiCoder=this.getAbiCoder();this.fragments.forEach(fragment=>{let bucket;switch(fragment.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}defineProperties(this,{deploy:fragment});return;case"function":bucket=this.#functions;break;case"event":bucket=this.#events;break;case"error":bucket=this.#errors;break;default:return}const signature=fragment.format();if(bucket.has(signature)){return}bucket.set(signature,fragment)});if(!this.deploy){defineProperties(this,{deploy:ConstructorFragment.fromString("constructor()")})}}format(minimal){const format=minimal?"minimal":"full";const abi=this.fragments.map(f=>f.format(format));return abi}formatJson(){const abi=this.fragments.map(f=>f.format("json"));return JSON.stringify(abi.map(j=>JSON.parse(j)))}getAbiCoder(){return defaultAbiCoder}#getFunction(key,values,forceUnique){if(isHexString(key)){const selector=key.toLowerCase();for(const fragment of this.#functions.values()){if(selector===fragment.selector){return fragment}}throwArgumentError("no matching function","selector",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#functions){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){const lastValue=values.length>0?values[values.length-1]:null;let valueLength=values.length;let allowOptions=true;if(Typed.isTyped(lastValue)&&lastValue.type==="overrides"){allowOptions=false;valueLength--}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs.length;if(inputs!==valueLength&&(!allowOptions||inputs!==valueLength-1)){matching.splice(i,1)}}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs;for(let j=0;j<values.length;j++){if(!Typed.isTyped(values[j])){continue}if(j>=inputs.length){if(values[j].type==="overrides"){continue}matching.splice(i,1);break}if(values[j].type!==inputs[j].baseType){matching.splice(i,1);break}}}}if(matching.length===1&&values&&values.length!==matching[0].inputs.length){const lastArg=values[values.length-1];if(lastArg==null||Array.isArray(lastArg)||typeof lastArg!=="object"){matching.splice(0,1)}}if(matching.length===0){throwArgumentError("no matching function","name",key)}else if(matching.length>1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");throwArgumentError(`multiple matching functions (i.e. ${matchStr})`,"name",key)}return matching[0]}const result=this.#functions.get(FunctionFragment.fromString(key).format());if(result){return result}return throwArgumentError("no matching function","signature",key)}getFunctionName(key){return this.#getFunction(key,null,false).name}getFunction(key,values){return this.#getFunction(key,values||null,true)}#getEvent(key,values,forceUnique){if(isHexString(key)){const eventTopic=key.toLowerCase();for(const fragment of this.#events.values()){if(eventTopic===fragment.topicHash){return fragment}}throwArgumentError("no matching event","eventTopic",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#events){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){for(let i=matching.length-1;i>=0;i--){if(matching[i].inputs.length<values.length){matching.splice(i,1)}}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs;for(let j=0;j<values.length;j++){if(!Typed.isTyped(values[j])){continue}if(values[j].type!==inputs[j].baseType){matching.splice(i,1);break}}}}if(matching.length===0){throwArgumentError("no matching event","name",key)}else if(matching.length>1&&forceUnique){throwArgumentError("multiple matching events","name",key)}return matching[0]}const result=this.#events.get(EventFragment.fromString(key).format());if(result){return result}return throwArgumentError("no matching event","signature",key)}getEventName(key){return this.#getEvent(key,null,false).name}getEvent(key,values){return this.#getEvent(key,values||null,true)}getError(key,values){if(isHexString(key)){const selector=key.toLowerCase();if(BuiltinErrors[selector]){return ErrorFragment.fromString(BuiltinErrors[selector].signature)}for(const fragment of this.#errors.values()){if(selector===fragment.selector){return fragment}}throwArgumentError("no matching error","selector",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#errors){if(name.split("(")[0]===key){matching.push(fragment)}}if(matching.length===0){if(key==="Error"){return ErrorFragment.fromString("error Error(string)")}if(key==="Panic"){return ErrorFragment.fromString("error Panic(uint256)")}throwArgumentError("no matching error","name",key)}else if(matching.length>1){throwArgumentError("multiple matching errors","name",key)}return matching[0]}key=ErrorFragment.fromString(key).format();if(key==="Error(string)"){return ErrorFragment.fromString("error Error(string)")}if(key==="Panic(uint256)"){return ErrorFragment.fromString("error Panic(uint256)")}const result=this.#errors.get(key);if(result){return result}return throwArgumentError("no matching error","signature",key)}_decodeParams(params,data){return this.#abiCoder.decode(params,data)}_encodeParams(params,values){return this.#abiCoder.encode(params,values)}encodeDeploy(values){return this._encodeParams(this.deploy.inputs,values||[])}decodeErrorResult(fragment,data){if(typeof fragment==="string"){fragment=this.getError(fragment)}if(dataSlice(data,0,4)!==fragment.selector){throwArgumentError(`data signature does not match error ${fragment.name}.`,"data",data)}return this._decodeParams(fragment.inputs,dataSlice(data,4))}encodeErrorResult(key,values){const fragment=typeof key==="string"?this.getError(key):key;return concat([fragment.selector,this._encodeParams(fragment.inputs,values||[])])}decodeFunctionData(key,data){const fragment=typeof key==="string"?this.getFunction(key):key;if(dataSlice(data,0,4)!==fragment.selector){throwArgumentError(`data signature does not match function ${fragment.name}.`,"data",data)}return this._decodeParams(fragment.inputs,dataSlice(data,4))}encodeFunctionData(key,values){const fragment=typeof key==="string"?this.getFunction(key):key;return concat([fragment.selector,this._encodeParams(fragment.inputs,values||[])])}decodeFunctionResult(fragment,data){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}let message="invalid length for result data";const bytes=getBytesCopy(data);if(bytes.length%32===0){try{return this.#abiCoder.decode(fragment.outputs,bytes)}catch(error){message="could not decode result data"}}return throwError(message,"BAD_DATA",{value:hexlify(bytes),info:{method:fragment.name,signature:fragment.format()}})}makeError(fragment,_data,tx){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}const data=getBytes(_data);let args=undefined;if(tx){try{args=this.#abiCoder.decode(fragment.inputs,tx.data||"0x")}catch(error){console.log(error)}}let errorArgs=undefined;let errorName=undefined;let errorSignature=undefined;let reason="unknown reason";if(data.length===0){reason="missing error reason"}else if(data.length%32===4){const selector=hexlify(data.slice(0,4));const builtin=BuiltinErrors[selector];if(builtin){try{errorName=builtin.name;errorSignature=builtin.signature;errorArgs=this.#abiCoder.decode(builtin.inputs,data.slice(4));reason=builtin.reason(...errorArgs)}catch(error){console.log(error)}}else{reason="unknown custom error";try{const error=this.getError(selector);errorName=error.name;errorSignature=error.format();reason=`custom error: ${errorSignature}`;try{errorArgs=this.#abiCoder.decode(error.inputs,data.slice(4))}catch(error){reason=`custom error: ${errorSignature} (coult not decode error data)`}}catch(error){console.log(error)}}}return makeError("call revert exception","CALL_EXCEPTION",{data:hexlify(data),transaction:null,method:fragment.name,signature:fragment.format(),args:args,errorArgs:errorArgs,errorName:errorName,errorSignature:errorSignature,reason:reason})}encodeFunctionResult(key,values){const fragment=typeof key==="string"?this.getFunction(key):key;return hexlify(this.#abiCoder.encode(fragment.outputs,values||[]))}encodeFilterTopics(eventFragment,values){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}if(values.length>eventFragment.inputs.length){throwError("too many arguments for "+eventFragment.format(),"UNEXPECTED_ARGUMENT",{count:values.length,expectedCount:eventFragment.inputs.length})}const topics=[];if(!eventFragment.anonymous){topics.push(eventFragment.topicHash)}const encodeTopic=(param,value)=>{if(param.type==="string"){return id(value)}else if(param.type==="bytes"){return keccak256(hexlify(value))}if(param.type==="bool"&&typeof value==="boolean"){value=value?"0x01":"0x00"}if(param.type.match(/^u?int/)){value=toHex(value)}if(param.type==="address"){this.#abiCoder.encode(["address"],[value])}return zeroPadValue(hexlify(value),32)};values.forEach((value,index)=>{const param=eventFragment.inputs[index];if(!param.indexed){if(value!=null){throwArgumentError("cannot filter non-indexed parameters; must be null","contract."+param.name,value)}return}if(value==null){topics.push(null)}else if(param.baseType==="array"||param.baseType==="tuple"){throwArgumentError("filtering with tuples or arrays not supported","contract."+param.name,value)}else if(Array.isArray(value)){topics.push(value.map(value=>encodeTopic(param,value)))}else{topics.push(encodeTopic(param,value))}});while(topics.length&&topics[topics.length-1]===null){topics.pop()}return topics}encodeEventLog(eventFragment,values){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}const topics=[];const dataTypes=[];const dataValues=[];if(!eventFragment.anonymous){topics.push(eventFragment.topicHash)}if(values.length!==eventFragment.inputs.length){throwArgumentError("event arguments/values mismatch","values",values)}eventFragment.inputs.forEach((param,index)=>{const value=values[index];if(param.indexed){if(param.type==="string"){topics.push(id(value))}else if(param.type==="bytes"){topics.push(keccak256(value))}else if(param.baseType==="tuple"||param.baseType==="array"){throw new Error("not implemented")}else{topics.push(this.#abiCoder.encode([param.type],[value]))}}else{dataTypes.push(param);dataValues.push(value)}});return{data:this.#abiCoder.encode(dataTypes,dataValues),topics:topics}}decodeEventLog(eventFragment,data,topics){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}if(topics!=null&&!eventFragment.anonymous){const eventTopic=eventFragment.topicHash;if(!isHexString(topics[0],32)||topics[0].toLowerCase()!==eventTopic){throwArgumentError("fragment/topic mismatch","topics[0]",topics[0])}topics=topics.slice(1)}const indexed=[];const nonIndexed=[];const dynamic=[];eventFragment.inputs.forEach((param,index)=>{if(param.indexed){if(param.type==="string"||param.type==="bytes"||param.baseType==="tuple"||param.baseType==="array"){indexed.push(ParamType.fromObject({type:"bytes32",name:param.name}));dynamic.push(true)}else{indexed.push(param);dynamic.push(false)}}else{nonIndexed.push(param);dynamic.push(false)}});const resultIndexed=topics!=null?this.#abiCoder.decode(indexed,concat(topics)):null;const resultNonIndexed=this.#abiCoder.decode(nonIndexed,data,true);const values=[];const keys=[];let nonIndexedIndex=0,indexedIndex=0;eventFragment.inputs.forEach((param,index)=>{let value=null;if(param.indexed){if(resultIndexed==null){value=new Indexed(null)}else if(dynamic[index]){value=new Indexed(resultIndexed[indexedIndex++])}else{try{value=resultIndexed[indexedIndex++]}catch(error){value=error}}}else{try{value=resultNonIndexed[nonIndexedIndex++]}catch(error){value=error}}values.push(value);keys.push(param.name||null)});return Result.fromItems(values,keys)}parseTransaction(tx){const data=getBytes(tx.data,"tx.data");const value=getBigInt(tx.value!=null?tx.value:0,"tx.value");const fragment=this.getFunction(hexlify(data.slice(0,4)));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,data.slice(4));return new TransactionDescription(fragment,fragment.selector,args,value)}parseCallResult(data){throw new Error("@TODO")}parseLog(log){const fragment=this.getEvent(log.topics[0]);if(!fragment||fragment.anonymous){return null}return new LogDescription(fragment,fragment.topicHash,this.decodeEventLog(fragment,log.data,log.topics))}parseError(data){const hexData=hexlify(data);const fragment=this.getError(dataSlice(hexData,0,4));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,dataSlice(hexData,4));return new ErrorDescription(fragment,fragment.selector,args)}static from(value){if(value instanceof Interface){return value}if(typeof value==="string"){return new Interface(JSON.parse(value))}if(typeof value.format==="function"){return new Interface(value.format("json"))}return new Interface(value)}}const BN_1$1=BigInt(1);const Empty=new Uint8Array([]);function parseBytes(result,start){if(result==="0x"){return null}const offset=toNumber(dataSlice(result,start,start+32));const length=toNumber(dataSlice(result,offset,offset+32));return dataSlice(result,offset+32,offset+32+length)}function parseString(result,start){try{const bytes=parseBytes(result,start);if(bytes!=null){return toUtf8String(bytes)}}catch(error){}return null}function numPad$1(value){const result=toArray(value);if(result.length>32){throw new Error("internal; should not happen")}const padded=new Uint8Array(32);padded.set(result,32-result.length);return padded}function bytesPad$1(value){if(value.length%32===0){return value}const result=new Uint8Array(Math.ceil(value.length/32)*32);result.set(value);return result}function encodeBytes$1(datas){const result=[];let byteCount=0;for(let i=0;i<datas.length;i++){result.push(Empty);byteCount+=32}for(let i=0;i<datas.length;i++){const data=getBytes(datas[i]);result[i]=numPad$1(byteCount);result.push(numPad$1(data.length));result.push(bytesPad$1(data));byteCount+=32+Math.ceil(data.length/32)*32}return concat(result)}function getIpfsLink(link){if(link.match(/^ipfs:\/\/ipfs\//i)){link=link.substring(12)}else if(link.match(/^ipfs:\/\//i)){link=link.substring(7)}else{throwArgumentError("unsupported IPFS format","link",link)}return`https:/\/gateway.ipfs.io/ipfs/${link}`}class MulticoinProviderPlugin{name;constructor(name){defineProperties(this,{name:name})}validate(proivder){return this}supportsCoinType(coinType){return false}async encodeAddress(coinType,address){throw new Error("unsupported coin")}async decodeAddress(coinType,data){throw new Error("unsupported coin")}}const BasicMulticoinPluginId="org.ethers.provider-prugins.basicmulticoin";class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin{constructor(){super(BasicMulticoinPluginId)}}const matcherIpfs=new RegExp("^(ipfs)://(.*)$","i");const matchers=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),matcherIpfs,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class EnsResolver{provider;address;name;#supports2544;constructor(provider,address,name){defineProperties(this,{provider:provider,address:address,name:name});this.#supports2544=null}async supportsWildcard(){if(!this.#supports2544){this.#supports2544=this.provider.call({to:this.address,data:"0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"}).then(result=>{return getBigInt(result)===BN_1$1}).catch(error=>{if(error.code==="CALL_EXCEPTION"){return false}this.#supports2544=null;throw error})}return await this.#supports2544}async _fetch(selector,parameters="0x"){const addrData=concat([selector,namehash(this.name),parameters]);const tx={to:this.address,enableCcipRead:true,data:addrData};let wrapped=false;if(await this.supportsWildcard()){wrapped=true;tx.data=concat(["0x9061b923",encodeBytes$1([dnsEncode(this.name),addrData])])}try{let data=await this.provider.call(tx);if(getBytes(data).length%32===4){return throwError("resolver threw error","CALL_EXCEPTION",{transaction:tx,data:data})}if(wrapped){return parseBytes(data,0)}return data}catch(error){if(error.code!=="CALL_EXCEPTION"){throw error}}return null}async getAddress(coinType=60){if(coinType===60){try{const result=await this._fetch("0x3b3b57de");if(result==="0x"||result===ZeroHash){return null}const network=await this.provider.getNetwork();return network.formatter.callAddress(result)}catch(error){if(error.code==="CALL_EXCEPTION"){return null}throw error}}let coinPlugin=null;for(const plugin of this.provider.plugins){if(!(plugin instanceof MulticoinProviderPlugin)){continue}if(plugin.supportsCoinType(coinType)){coinPlugin=plugin;break}}if(coinPlugin==null){return null}const data=parseBytes(await this._fetch("0xf1cb7e06",numPad$1(coinType))||"0x",0);if(data==null||data==="0x"){return null}const address=await coinPlugin.encodeAddress(coinType,data);if(address!=null){return address}return throwError(`invalid coin data`,"UNSUPPORTED_OPERATION",{operation:`getAddress(${coinType})`,info:{coinType:coinType,data:data}})}async getText(key){let keyBytes=toUtf8Bytes(key);const calldata=getBytes(concat([numPad$1(64),numPad$1(keyBytes.length),keyBytes]));const hexBytes=parseBytes(await this._fetch("0x59d1d43c",bytesPad$1(calldata))||"0x",0);if(hexBytes==null||hexBytes==="0x"){return null}return toUtf8String(hexBytes)}async getContentHash(){const hexBytes=parseBytes(await this._fetch("0xbc1c58d1")||"0x",0);if(hexBytes==null||hexBytes==="0x"){return null}const ipfs=hexBytes.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(ipfs){const scheme=ipfs[1]==="e3010170"?"ipfs":"ipns";const length=parseInt(ipfs[4],16);if(ipfs[5].length===length*2){return`${scheme}:/\/${encodeBase58("0x"+ipfs[2])}`}}const swarm=hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(swarm&&swarm[1].length===64){return`bzz:/\/${swarm[1]}`}return throwError(`invalid or unsupported content hash data`,"UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:hexBytes}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const linkage=[{type:"name",value:this.name}];try{const avatar=await this.getText("avatar");if(avatar==null){linkage.push({type:"!avatar",value:""});throw new Error("!avatar")}linkage.push({type:"avatar",value:avatar});for(let i=0;i<matchers.length;i++){const match=avatar.match(matchers[i]);if(match==null){continue}const scheme=match[1].toLowerCase();switch(scheme){case"https":case"data":linkage.push({type:"url",value:avatar});return{linkage:linkage,url:avatar};case"ipfs":{const url=getIpfsLink(avatar);linkage.push({type:"ipfs",value:avatar});linkage.push({type:"url",value:url});return{linkage:linkage,url:url}}case"erc721":case"erc1155":{const selector=scheme==="erc721"?"0xc87b56dd":"0x0e89341c";linkage.push({type:scheme,value:avatar});const owner=await this.getAddress();if(owner==null){linkage.push({type:"!owner",value:""});throw new Error("!owner")}const comps=(match[2]||"").split("/");if(comps.length!==2){linkage.push({type:`!${scheme}caip`,value:match[2]||""});throw new Error("!caip")}const formatter=(await this.provider.getNetwork()).formatter;const addr=formatter.address(comps[0]);const tokenId=numPad$1(comps[1]);if(scheme==="erc721"){const tokenOwner=formatter.callAddress(await this.provider.call({to:addr,data:concat(["0x6352211e",tokenId])}));if(owner!==tokenOwner){linkage.push({type:"!owner",value:tokenOwner});throw new Error("!owner")}linkage.push({type:"owner",value:tokenOwner})}else if(scheme==="erc1155"){const balance=getBigInt(await this.provider.call({to:addr,data:concat(["0x00fdd58e",zeroPadValue(owner,32),tokenId])}));if(!balance){linkage.push({type:"!balance",value:"0"});throw new Error("!balance")}linkage.push({type:"balance",value:balance.toString()})}const tx={to:comps[0],data:concat([selector,tokenId])};let metadataUrl=parseString(await this.provider.call(tx),0);if(metadataUrl==null){linkage.push({type:"!metadata-url",value:""});throw new Error("!metadata-url")}linkage.push({type:"metadata-url-base",value:metadataUrl});if(scheme==="erc1155"){metadataUrl=metadataUrl.replace("{id}",hexlify(tokenId).substring(2));linkage.push({type:"metadata-url-expanded",value:metadataUrl})}if(metadataUrl.match(/^ipfs:/i)){metadataUrl=getIpfsLink(metadataUrl)}linkage.push({type:"metadata-url",value:metadataUrl});let metadata={};const response=await new FetchRequest(metadataUrl).send();response.assertOk();try{metadata=response.bodyJson}catch(error){try{linkage.push({type:"!metadata",value:response.bodyText})}catch(error){const bytes=response.body;if(bytes){linkage.push({type:"!metadata",value:hexlify(bytes)})}throw error}throw error}if(!metadata){linkage.push({type:"!metadata",value:""});throw new Error("!metadata")}linkage.push({type:"metadata",value:JSON.stringify(metadata)});let imageUrl=metadata.image;if(typeof imageUrl!=="string"){linkage.push({type:"!imageUrl",value:""});throw new Error("!imageUrl")}if(imageUrl.match(/^(https:\/\/|data:)/i)){}else{const ipfs=imageUrl.match(matcherIpfs);if(ipfs==null){linkage.push({type:"!imageUrl-ipfs",value:imageUrl});throw new Error("!imageUrl-ipfs")}linkage.push({type:"imageUrl-ipfs",value:imageUrl});imageUrl=getIpfsLink(imageUrl)}linkage.push({type:"url",value:imageUrl});return{linkage:linkage,url:imageUrl}}}}}catch(error){console.log("EE",error)}return{linkage:linkage,url:null}}static async#getResolver(provider,name){const network=await provider.getNetwork();const ensPlugin=network.getPlugin("org.ethers.network-plugins.ens");if(!ensPlugin){return throwError("network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getResolver",info:{network:network.name}})}try{const addrData=await provider.call({to:ensPlugin.address,data:concat(["0x0178b8bf",namehash(name)]),enableCcipRead:true});const addr=network.formatter.callAddress(addrData);if(addr===dataSlice(ZeroHash,0,20)){return null}return addr}catch(error){throw error}return null}static async fromName(provider,name){let currentName=name;while(true){if(currentName===""||currentName==="."){return null}if(name!=="eth"&&currentName==="eth"){return null}const addr=await EnsResolver.#getResolver(provider,currentName);if(addr!=null){const resolver=new EnsResolver(provider,addr,name);if(currentName!==name&&!await resolver.supportsWildcard()){return null}return resolver}currentName=currentName.split(".").slice(1).join(".")}}}function accessSetify(addr,storageKeys){return{address:getAddress(addr),storageKeys:(storageKeys||[]).map((storageKey,index)=>{if(dataLength(storageKey)!==32){throw new Error("")}return storageKey.toLowerCase()})}}function accessListify(value){if(Array.isArray(value)){return value.map((set,index)=>{if(Array.isArray(set)){if(set.length>2){throw new Error("")}return accessSetify(set[0],set[1])}return accessSetify(set.address,set.storageKeys)})}const result=Object.keys(value).map(addr=>{const storageKeys=value[addr].reduce((accum,storageKey)=>{accum[storageKey]=true;return accum},{});return accessSetify(addr,Object.keys(storageKeys).sort())});result.sort((a,b)=>a.address.localeCompare(b.address));return result}function computeAddress(key){const publicKey=SigningKey.computePublicKey(key,false);return getAddress(keccak256("0x"+publicKey.substring(4)).substring(26))}function recoverAddress(digest,signature){return computeAddress(SigningKey.recoverPublicKey(digest,signature))}const BN_0=BigInt(0);const BN_2$2=BigInt(2);const BN_27=BigInt(27);const BN_28=BigInt(28);const BN_35=BigInt(35);const BN_MAX_UINT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function handleAddress(value){if(value==="0x"){return null}return getAddress(value)}function handleData(value,param){try{return hexlify(value)}catch(error){return throwArgumentError("invalid data",param,value)}}function handleAccessList(value,param){try{return accessListify(value)}catch(error){return throwArgumentError("invalid accessList",param,value)}}function handleNumber(_value,param){if(_value==="0x"){return 0}return getNumber(_value,param)}function handleUint(_value,param){if(_value==="0x"){return BN_0}const value=getBigInt(_value,param);if(value>BN_MAX_UINT){throwArgumentError("value exceeds uint size",param,value)}return value}function formatNumber(_value,name){const value=getBigInt(_value,"value");const result=toArray(value);if(result.length>32){throwArgumentError(`value too large`,`tx.${name}`,value)}return result}function formatAccessList(value){return accessListify(value).map(set=>[set.address,set.storageKeys])}function _parseLegacy(data){const fields=decodeRlp(data);if(!Array.isArray(fields)||fields.length!==9&&fields.length!==6){return throwArgumentError("invalid field count for legacy transaction","data",data)}const tx={type:0,nonce:handleNumber(fields[0],"nonce"),gasPrice:handleUint(fields[1],"gasPrice"),gasLimit:handleUint(fields[2],"gasLimit"),to:handleAddress(fields[3]),value:handleUint(fields[4],"value"),data:handleData(fields[5],"dta"),chainId:BN_0};if(fields.length===6){return tx}const v=handleUint(fields[6],"v");const r=handleUint(fields[7],"r");const s=handleUint(fields[8],"s");if(r===BN_0&&s===BN_0){tx.chainId=v}else{let chainId=(v-BN_35)/BN_2$2;if(chainId<BN_0){chainId=BN_0}tx.chainId=chainId;if(chainId===BN_0&&(v<BN_27||v>BN_28)){throwArgumentError("non-canonical legacy v","v",fields[6])}tx.signature=Signature.from({r:zeroPadValue(fields[7],32),s:zeroPadValue(fields[8],32),v:v});tx.hash=keccak256(data)}return tx}function _serializeLegacy(tx,sig){const fields=[formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.gasPrice||0,"gasPrice"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x"];let chainId=BN_0;if(tx.chainId!=null){chainId=getBigInt(tx.chainId,"tx.chainId");if(sig&&sig.networkV!=null&&sig.legacyChainId!==chainId){throwArgumentError("tx.chainId/sig.v mismatch","sig",sig)}}else if(sig){const legacy=sig.legacyChainId;if(legacy!=null){chainId=legacy}}if(!sig){if(chainId!==BN_0){fields.push(toArray(chainId));fields.push("0x");fields.push("0x")}return encodeRlp(fields)}let v=BigInt(27+sig.yParity);if(chainId!==BN_0){v=Signature.getChainIdV(chainId,sig.v)}else if(BigInt(sig.v)!==v){throwArgumentError("tx.chainId/sig.v mismatch","sig",sig)}fields.push(toArray(v));fields.push(toArray(sig.r));fields.push(toArray(sig.s));return encodeRlp(fields)}function _parseEipSignature(tx,fields,serialize){let yParity;try{yParity=handleNumber(fields[0],"yParity");if(yParity!==0&&yParity!==1){throw new Error("bad yParity")}}catch(error){return throwArgumentError("invalid yParity","yParity",fields[0])}const r=zeroPadValue(fields[1],32);const s=zeroPadValue(fields[2],32);const signature=Signature.from({r:r,s:s,yParity:yParity});tx.signature=signature}function _parseEip1559(data){const fields=decodeRlp(getBytes(data).slice(1));if(!Array.isArray(fields)||fields.length!==9&&fields.length!==12){throwArgumentError("invalid field count for transaction type: 2","data",hexlify(data))}const maxPriorityFeePerGas=handleUint(fields[2],"maxPriorityFeePerGas");const maxFeePerGas=handleUint(fields[3],"maxFeePerGas");const tx={type:2,chainId:handleUint(fields[0],"chainId"),nonce:handleNumber(fields[1],"nonce"),maxPriorityFeePerGas:maxPriorityFeePerGas,maxFeePerGas:maxFeePerGas,gasPrice:null,gasLimit:handleUint(fields[4],"gasLimit"),to:handleAddress(fields[5]),value:handleUint(fields[6],"value"),data:handleData(fields[7],"data"),accessList:handleAccessList(fields[8],"accessList")};if(fields.length===9){return tx}tx.hash=keccak256(data);_parseEipSignature(tx,fields.slice(9),_serializeEip1559);return tx}function _serializeEip1559(tx,sig){const fields=[formatNumber(tx.chainId||0,"chainId"),formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(tx.maxFeePerGas||0,"maxFeePerGas"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x",formatAccessList(tx.accessList||[])];if(sig){fields.push(formatNumber(sig.yParity,"yParity"));fields.push(toArray(sig.r));fields.push(toArray(sig.s))}return concat(["0x02",encodeRlp(fields)])}function _parseEip2930(data){const fields=decodeRlp(getBytes(data).slice(1));if(!Array.isArray(fields)||fields.length!==8&&fields.length!==11){throwArgumentError("invalid field count for transaction type: 1","data",hexlify(data))}const tx={type:1,chainId:handleUint(fields[0],"chainId"),nonce:handleNumber(fields[1],"nonce"),gasPrice:handleUint(fields[2],"gasPrice"),gasLimit:handleUint(fields[3],"gasLimit"),to:handleAddress(fields[4]),value:handleUint(fields[5],"value"),data:handleData(fields[6],"data"),accessList:handleAccessList(fields[7],"accessList")};if(fields.length===8){return tx}tx.hash=keccak256(data);_parseEipSignature(tx,fields.slice(8),_serializeEip2930);return tx}function _serializeEip2930(tx,sig){const fields=[formatNumber(tx.chainId||0,"chainId"),formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.gasPrice||0,"gasPrice"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x",formatAccessList(tx.accessList||[])];if(sig){fields.push(formatNumber(sig.yParity,"recoveryParam"));fields.push(toArray(sig.r));fields.push(toArray(sig.s))}return concat(["0x01",encodeRlp(fields)])}class Transaction{#props;get type(){return getStore(this.#props,"type")}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559"}return null}set type(value){switch(value){case null:setStore(this.#props,"type",null);break;case 0:case"legacy":setStore(this.#props,"type",0);break;case 1:case"berlin":case"eip-2930":setStore(this.#props,"type",1);break;case 2:case"london":case"eip-1559":setStore(this.#props,"type",2);break;default:throw new Error(`unsupported transaction type`)}}get to(){return getStore(this.#props,"to")}set to(value){setStore(this.#props,"to",value==null?null:getAddress(value))}get nonce(){return getStore(this.#props,"nonce")}set nonce(value){setStore(this.#props,"nonce",getNumber(value,"value"))}get gasLimit(){return getStore(this.#props,"gasLimit")}set gasLimit(value){setStore(this.#props,"gasLimit",getBigInt(value))}get gasPrice(){const value=getStore(this.#props,"gasPrice");if(value==null&&(this.type===0||this.type===1)){return BN_0}return value}set gasPrice(value){setStore(this.#props,"gasPrice",value==null?null:getBigInt(value,"gasPrice"))}get maxPriorityFeePerGas(){const value=getStore(this.#props,"maxPriorityFeePerGas");if(value==null&&this.type===2){return BN_0}return value}set maxPriorityFeePerGas(value){setStore(this.#props,"maxPriorityFeePerGas",value==null?null:getBigInt(value,"maxPriorityFeePerGas"))}get maxFeePerGas(){const value=getStore(this.#props,"maxFeePerGas");if(value==null&&this.type===2){return BN_0}return value}set maxFeePerGas(value){setStore(this.#props,"maxFeePerGas",value==null?null:getBigInt(value,"maxFeePerGas"))}get data(){return getStore(this.#props,"data")}set data(value){setStore(this.#props,"data",hexlify(value))}get value(){return getStore(this.#props,"value")}set value(value){setStore(this.#props,"value",getBigInt(value,"value"))}get chainId(){return getStore(this.#props,"chainId")}set chainId(value){setStore(this.#props,"chainId",getBigInt(value))}get signature(){return getStore(this.#props,"sig")||null}set signature(value){setStore(this.#props,"sig",value==null?null:Signature.from(value))}get accessList(){const value=getStore(this.#props,"accessList")||null;if(value==null&&(this.type===1||this.type===2)){return[]}return value}set accessList(value){setStore(this.#props,"accessList",value==null?null:accessListify(value))}constructor(){this.#props={type:null,to:null,nonce:0,gasLimit:BigInt(0),gasPrice:null,maxPriorityFeePerGas:null,maxFeePerGas:null,data:"0x",value:BigInt(0),chainId:BigInt(0),sig:null,accessList:null}}get hash(){if(this.signature==null){throw new Error("cannot hash unsigned transaction; maybe you meant .unsignedHash")}return keccak256(this.serialized)}get unsignedHash(){return keccak256(this.unsignedSerialized)}get from(){if(this.signature==null){return null}return recoverAddress(this.unsignedSerialized,this.signature)}get fromPublicKey(){if(this.signature==null){return null}return""}isSigned(){return this.signature!=null}get serialized(){if(this.signature==null){throw new Error("cannot serialize unsigned transaction; maybe you meant .unsignedSerialized")}const types=this.inferTypes();if(types.length!==1){throw new Error("cannot determine transaction type; specify type manually")}switch(types[0]){case 0:return _serializeLegacy(this,this.signature);case 1:return _serializeEip2930(this,this.signature);case 2:return _serializeEip1559(this,this.signature)}throw new Error("unsupported type")}get unsignedSerialized(){const types=this.inferTypes();if(types.length!==1){throw new Error("cannot determine transaction type; specify type manually")}switch(types[0]){case 0:return _serializeLegacy(this);case 1:return _serializeEip2930(this);case 2:return _serializeEip1559(this)}throw new Error("unsupported type")}inferTypes(){const hasGasPrice=this.gasPrice!=null;const hasFee=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null;const hasAccessList=this.accessList!=null;if(this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null){if(this.maxFeePerGas<this.maxPriorityFeePerGas){throw new Error("priorityFee cannot be more than maxFee")}}if((this.type===0||this.type===1)&&hasFee){throw new Error("transaction type cannot have maxFeePerGas or maxPriorityFeePerGas")}if(this.type===0&&hasAccessList){throw new Error("legacy transaction cannot have accessList")}const types=[];if(this.type!=null){types.push(this.type)}else{if(hasFee){types.push(2)}else if(hasGasPrice){types.push(1);if(!hasAccessList){types.push(0)}}else if(hasAccessList){types.push(1);types.push(2)}else{types.push(0);types.push(1);types.push(2)}}types.sort();return types}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}clone(){return Transaction.from(this)}freeze(){if(this.#props.sig){this.#props.sig=this.#props.sig.clone().freeze()}if(this.#props.accessList){this.#props.accessList=Object.freeze(this.#props.accessList.map(set=>{Object.freeze(set.storageKeys);return Object.freeze(set)}))}Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}static from(tx){if(typeof tx==="string"){const payload=getBytes(tx);if(payload[0]>=127){return Transaction.from(_parseLegacy(payload))}switch(payload[0]){case 1:return Transaction.from(_parseEip2930(payload));case 2:return Transaction.from(_parseEip1559(payload))}throw new Error("unsupported transaction type")}const result=new Transaction;if(tx.type!=null){result.type=tx.type}if(tx.to!=null){result.to=tx.to}if(tx.nonce!=null){result.nonce=tx.nonce}if(tx.gasLimit!=null){result.gasLimit=tx.gasLimit}if(tx.gasPrice!=null){result.gasPrice=tx.gasPrice}if(tx.maxPriorityFeePerGas!=null){result.maxPriorityFeePerGas=tx.maxPriorityFeePerGas}if(tx.maxFeePerGas!=null){result.maxFeePerGas=tx.maxFeePerGas}if(tx.data!=null){result.data=tx.data}if(tx.value!=null){result.value=tx.value}if(tx.chainId!=null){result.chainId=tx.chainId}if(tx.signature!=null){result.signature=Signature.from(tx.signature)}if(tx.accessList!=null){result.accessList=tx.accessList}if(tx.hash!=null){if(result.isSigned()){if(result.hash!==tx.hash){throw new Error("hash mismatch")}}else{throw new Error("unsigned transaction cannot have a hashs")}}if(tx.from!=null){if(result.isSigned()){if(result.from.toLowerCase()!==(tx.from||"").toLowerCase()){throw new Error("from mismatch")}}else{throw new Error("unsigned transaction cannot have a from")}}return result}}function getValue(value){if(value==null){return null}return value}function toJson(value){if(value==null){return null}return value.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(gasPrice,maxFeePerGas,maxPriorityFeePerGas){defineProperties(this,{gasPrice:getValue(gasPrice),maxFeePerGas:getValue(maxFeePerGas),maxPriorityFeePerGas:getValue(maxPriorityFeePerGas)})}toJSON(){const{gasPrice,maxFeePerGas,maxPriorityFeePerGas}=this;return{_type:"FeeData",gasPrice:toJson(gasPrice),maxFeePerGas:toJson(maxFeePerGas),maxPriorityFeePerGas:toJson(maxPriorityFeePerGas)}}}function copyRequest$1(req){const result={};if(req.to){result.to=req.to}if(req.from){result.from=req.from}if(req.data){result.data=hexlify(req.data)}const bigIntKeys="chainId,gasLimit,gasPrice,maxFeePerGas, maxPriorityFeePerGas,value".split(/,/);for(const key in bigIntKeys){if(!(key in req)||req[key]==null){continue}result[key]=getBigInt(req[key],`request.${key}`)}const numberKeys="type,nonce".split(/,/);for(const key in numberKeys){if(!(key in req)||req[key]==null){continue}result[key]=getNumber(req[key],`request.${key}`)}if(req.accessList){result.accessList=accessListify(req.accessList)}if("blockTag"in req){result.blockTag=req.blockTag}if("enableCcipRead"in req){result.enableCcipReadEnabled=!!req.enableCcipRead}if("customData"in req){result.customData=req.customData}return result}class Block{provider;number;hash;timestamp;parentHash;nonce;difficulty;gasLimit;gasUsed;miner;extraData;baseFeePerGas;#transactions;constructor(block,provider){if(provider==null){provider=dummyProvider}this.#transactions=Object.freeze(block.transactions.map(tx=>{if(typeof tx!=="string"&&tx.provider!==provider){throw new Error("provider mismatch")}return tx}));defineProperties(this,{provider:provider,hash:getValue(block.hash),number:block.number,timestamp:block.timestamp,parentHash:block.parentHash,nonce:block.nonce,difficulty:block.difficulty,gasLimit:block.gasLimit,gasUsed:block.gasUsed,miner:block.miner,extraData:block.extraData,baseFeePerGas:getValue(block.baseFeePerGas)})}get transactions(){return this.#transactions}toJSON(){const{baseFeePerGas,difficulty,extraData,gasLimit,gasUsed,hash,miner,nonce,number,parentHash,timestamp,transactions}=this;return{_type:"Block",baseFeePerGas:toJson(baseFeePerGas),difficulty:toJson(difficulty),extraData:extraData,gasLimit:toJson(gasLimit),gasUsed:toJson(gasUsed),hash:hash,miner:miner,nonce:nonce,number:number,parentHash:parentHash,timestamp:timestamp,transactions:transactions}}[Symbol.iterator](){let index=0;return{next:()=>{if(index<this.length){return{value:this.transactions[index++],done:false}}return{value:undefined,done:true}}}}get length(){return this.transactions.length}get date(){if(this.timestamp==null){return null}return new Date(this.timestamp*1e3)}async getTransaction(index){const tx=this.transactions[index];if(tx==null){throw new Error("no such tx")}if(typeof tx==="string"){return await this.provider.getTransaction(tx)}else{return tx}}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined()){throw new Error("")}return createOrphanedBlockFilter(this)}}class Log{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(log,provider){if(provider==null){provider=dummyProvider}this.provider=provider;const topics=Object.freeze(log.topics.slice());defineProperties(this,{transactionHash:log.transactionHash,blockHash:log.blockHash,blockNumber:log.blockNumber,removed:log.removed,address:log.address,data:log.data,topics:topics,index:log.index,transactionIndex:log.transactionIndex})}toJSON(){const{address,blockHash,blockNumber,data,index,removed,topics,transactionHash,transactionIndex}=this;return{_type:"log",address:address,blockHash:blockHash,blockNumber:blockNumber,data:data,index:index,removed:removed,topics:topics,transactionHash:transactionHash,transactionIndex:transactionIndex}}async getBlock(){return await this.provider.getBlock(this.blockHash)}async getTransaction(){return await this.provider.getTransaction(this.transactionHash)}async getTransactionReceipt(){return await this.provider.getTransactionReceipt(this.transactionHash)}removedEvent(){return createRemovedLogFilter(this)}}class TransactionReceipt{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;cumulativeGasUsed;gasPrice;byzantium;status;root;#logs;constructor(tx,provider){if(provider==null){provider=dummyProvider}this.#logs=Object.freeze(tx.logs.map(log=>{if(provider!==log.provider){throw new Error("provider mismatch")}return log}));defineProperties(this,{provider:provider,to:tx.to,from:tx.from,contractAddress:tx.contractAddress,hash:tx.hash,index:tx.index,blockHash:tx.blockHash,blockNumber:tx.blockNumber,logsBloom:tx.logsBloom,gasUsed:tx.gasUsed,cumulativeGasUsed:tx.cumulativeGasUsed,gasPrice:tx.effectiveGasPrice||tx.gasPrice,byzantium:tx.byzantium,status:tx.status,root:tx.root})}get logs(){return this.#logs}toJSON(){const{to,from,contractAddress,hash,index,blockHash,blockNumber,logsBloom,logs,byzantium,status,root}=this;return{_type:"TransactionReceipt",blockHash:blockHash,blockNumber:blockNumber,byzantium:byzantium,contractAddress:contractAddress,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:from,gasPrice:toJson(this.gasPrice),gasUsed:toJson(this.gasUsed),hash:hash,index:index,logs:logs,logsBloom:logsBloom,root:root,status:status,to:to}}get length(){return this.logs.length}[Symbol.iterator](){let index=0;return{next:()=>{if(index<this.length){return{value:this.logs[index++],done:false}}return{value:undefined,done:true}}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const block=await this.provider.getBlock(this.blockHash);if(block==null){throw new Error("TODO")}return block}async getTransaction(){const tx=await this.provider.getTransaction(this.hash);if(tx==null){throw new Error("TODO")}return tx}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return createRemovedTransactionFilter(this)}reorderedEvent(other){if(other&&!other.isMined()){return throwError("unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"})}return createReorderedTransactionFilter(this,other)}}class TransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;data;value;chainId;signature;accessList;constructor(tx,provider){if(provider==null){provider=dummyProvider}this.provider=provider;this.blockNumber=tx.blockNumber!=null?tx.blockNumber:null;this.blockHash=tx.blockHash!=null?tx.blockHash:null;this.hash=tx.hash;this.index=tx.index;this.type=tx.type;this.from=tx.from;this.to=tx.to||null;this.gasLimit=tx.gasLimit;this.nonce=tx.nonce;this.data=tx.data;this.value=tx.value;this.gasPrice=tx.gasPrice;this.maxPriorityFeePerGas=tx.maxPriorityFeePerGas!=null?tx.maxPriorityFeePerGas:null;this.maxFeePerGas=tx.maxFeePerGas!=null?tx.maxFeePerGas:null;this.chainId=tx.chainId;this.signature=tx.signature;this.accessList=tx.accessList!=null?tx.accessList:null}toJSON(){const{blockNumber,blockHash,index,hash,type,to,from,nonce,data,signature,accessList}=this;return{_type:"TransactionReceipt",accessList:accessList,blockNumber:blockNumber,blockHash:blockHash,chainId:toJson(this.chainId),data:data,from:from,gasLimit:toJson(this.gasLimit),gasPrice:toJson(this.gasPrice),hash:hash,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),nonce:nonce,signature:signature,to:to,index:index,type:type,value:toJson(this.value)}}async getBlock(){let blockNumber=this.blockNumber;if(blockNumber==null){const tx=await this.getTransaction();if(tx){blockNumber=tx.blockNumber}}if(blockNumber==null){return null}const block=this.provider.getBlock(blockNumber);if(block==null){throw new Error("TODO")}return block}async getTransaction(){return this.provider.getTransaction(this.hash)}async wait(confirms){return this.provider.waitForTransaction(this.hash,confirms)}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}removedEvent(){if(!this.isMined()){return throwError("unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"})}return createRemovedTransactionFilter(this)}reorderedEvent(other){if(!this.isMined()){return throwError("unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"})}if(other&&!other.isMined()){return throwError("unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"})}return createReorderedTransactionFilter(this,other)}}function createOrphanedBlockFilter(block){return{orphan:"drop-block",hash:block.hash,number:block.number}}function createReorderedTransactionFilter(tx,other){return{orphan:"reorder-transaction",tx:tx,other:other}}function createRemovedTransactionFilter(tx){return{orphan:"drop-transaction",tx:tx}}function createRemovedLogFilter(log){return{orphan:"drop-log",log:{transactionHash:log.transactionHash,blockHash:log.blockHash,blockNumber:log.blockNumber,address:log.address,data:log.data,topics:Object.freeze(log.topics.slice()),index:log.index}}}function fail(){throw new Error("this provider should not be used")}class DummyProvider{get provider(){return this}async getNetwork(){return fail()}async getFeeData(){return fail()}async estimateGas(tx){return fail()}async call(tx){return fail()}async resolveName(name){return fail()}async getBlockNumber(){return fail()}async getBalance(address,blockTag){return fail()}async getTransactionCount(address,blockTag){return fail()}async getCode(address,blockTag){return fail()}async getStorageAt(address,position,blockTag){return fail()}async broadcastTransaction(signedTx){return fail()}async getBlock(blockHashOrBlockTag){return fail()}async getBlockWithTransactions(blockHashOrBlockTag){return fail()}async getTransaction(hash){return fail()}async getTransactionReceipt(hash){return fail()}async getTransactionResult(hash){return fail()}async getLogs(filter){return fail()}async lookupAddress(address){return fail()}async waitForTransaction(hash,confirms,timeout){return fail()}async waitForBlock(blockTag){return fail()}async on(event,listener){return fail()}async once(event,listener){return fail()}async emit(event,...args){return fail()}async listenerCount(event){return fail()}async listeners(event){return fail()}async off(event,listener){return fail()}async removeAllListeners(event){return fail()}async addListener(event,listener){return fail()}async removeListener(event,listener){return fail()}}const dummyProvider=new DummyProvider;const BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function stringify(value){if(typeof value!=="string"){throw new Error("invalid string")}return value}class Formatter{#format;#baseBlock;constructor(){const address=this.address.bind(this);const bigNumber=this.bigNumber.bind(this);const blockTag=this.blockTag.bind(this);const data=this.data.bind(this);const hash=this.hash.bind(this);const number=this.number.bind(this);const uint256=this.uint256.bind(this);const topics=this.arrayOf(hash);this.#format={address:address,bigNumber:bigNumber,blockTag:blockTag,data:data,hash:hash,number:number,uint256:uint256,topics:topics,filter:this.object({fromBlock:this.allowNull(blockTag,undefined),toBlock:this.allowNull(blockTag,undefined),blockHash:this.allowNull(hash,undefined),address:this.allowNull(address,undefined),topics:this.allowNull(topics,undefined)}),transactionRequest:this.object({from:this.allowNull(address),type:this.allowNull(number),to:this.allowNull(address),nonce:this.allowNull(number),gasLimit:this.allowNull(uint256),gasPrice:this.allowNull(uint256),maxFeePerGas:this.allowNull(uint256),maxPriorityFeePerGas:this.allowNull(uint256),data:this.allowNull(data),value:this.allowNull(uint256)}),transactionResponse:this.object({hash:hash,index:number,type:this.allowNull(number,0),blockHash:this.allowNull(hash),blockNumber:this.allowNull(number),chainId:this.allowNull(number),from:address,to:this.address,gasLimit:bigNumber,gasPrice:this.allowNull(bigNumber),maxFeePerGas:this.allowNull(bigNumber),maxPriorityFeePerGas:this.allowNull(bigNumber),value:bigNumber,data:data,nonce:number,r:hash,s:hash,v:number,accessList:this.allowNull(this.accessList)},{index:["transactionIndex"]})};this.#baseBlock=this.object({number:number,hash:this.allowNull(hash,null),timestamp:number,parentHash:hash,nonce:this.allowNull(stringify,"0x0000000000000000"),difficulty:bigNumber,gasLimit:bigNumber,gasUsed:bigNumber,miner:this.allowNull(address,"0x0000000000000000000000000000000000000000"),extraData:stringify,baseFeePerGas:this.allowNull(bigNumber)})}address(value){return getAddress(value)}callAddress(value){if(dataLength(value)!==32||dataSlice(value,0,12)!=="0x000000000000000000000000"){throwArgumentError("invalid call address","value",value)}return this.address(dataSlice(value,12))}contractAddress(value){return getCreateAddress({from:this.address(value.from),nonce:getNumber(value.nonce,"value.nonce")})}blockTag(value){if(value==null){return"latest"}switch(value){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return value}if(typeof value==="number"||isHexString(value)&&dataLength(value)<32){return toQuantity(value)}return throwArgumentError("invalid blockTag","value",value)}block(value,provider){const params=this.#baseBlock(value);params.transactions=value.transactions.map(t=>this.hash(t));return new Block(params,provider)}blockWithTransactions(value,provider){throw new Error}transactionRequest(value,provider){return this.#format.transactionRequest(value)}transactionResponse(value,provider){value=Object.assign({},value);if(value.data==null&&value.input!=null){value.data=value.input}if(value.gasLimit==null&&value.gas){value.gasLimit=value.gas}value=this.#format.transactionResponse(value);const sig=Signature.from({r:value.r,s:value.s,v:value.v});value.signature=sig;if(value.chainId==null){value.chainId=sig.legacyChainId}return new TransactionResponse(value,provider)}log(value,provider){const log=this.object({address:this.address,blockHash:this.hash,blockNumber:this.number,data:this.data,index:this.number,removed:this.boolean,topics:this.topics,transactionHash:this.hash,transactionIndex:this.number},{index:["logIndex"]})(value);return new Log(log,provider)}receipt(value,provider){const receipt=this.object({blockHash:this.hash,blockNumber:this.number,contractAddress:this.allowNull(this.address),cumulativeGasUsed:this.bigNumber,from:this.address,gasUsed:this.bigNumber,logs:this.arrayOf(v=>this.log(v,provider)),logsBloom:this.data,root:this.allowNull(this.data),status:this.allowNull(this.number),to:this.address,gasPrice:this.allowNull(this.bigNumber),hash:this.hash,index:this.number,type:this.allowNull(this.number,0)},{hash:["transactionHash"],gasPrice:["effectiveGasPrice"],index:["transactionIndex"]})(value);if(receipt.root!=null){if(receipt.root.length<=4){const value=parseInt(receipt.root);if(value===0||value===1){if(receipt.status!=null&&receipt.status!==value){return throwError("alt-root-status/status mismatch","BAD_DATA",{value:{root:receipt.root,status:receipt.status}})}receipt.status=value;delete receipt.root}else{return throwError("invalid alt-root-status","BAD_DATA",{value:receipt.root})}}else if(!isHexString(receipt.root,32)){return throwError("invalid receipt root hash","BAD_DATA",{value:receipt.root})}}return new TransactionReceipt(receipt,provider)}topics(value){return this.#format.topics(value)}filter(value){return this.#format.filter(value)}filterLog(value){console.log("ME",value);return null}transaction(value){throw new Error}accessList(value){return accessListify(value)}allowFalsish(format,ifFalse){return value=>{if(!value){return ifFalse}return format.call(this,value)}}allowNull(format,ifNull){return value=>{if(value==null){return ifNull}return format.call(this,value)}}arrayOf(format){return array=>{if(!Array.isArray(array)){throw new Error("not an array")}return array.map(i=>format.call(this,i))}}bigNumber(value){return getBigInt(value,"value")}uint256(value){const result=this.bigNumber(value);if(result<0||result>BN_MAX_UINT256){throwArgumentError("invalid uint256","value",value)}return result}boolean(value){switch(value){case true:case"true":return true;case false:case"false":return false}return throwArgumentError(`invalid boolean; ${JSON.stringify(value)}`,"value",value)}_hexstring(dataOrLength){if(dataOrLength==null){dataOrLength=false}return function(value){if(isHexString(value,dataOrLength)){return value.toLowerCase()}throw new Error("bad hexstring")}}data(value){if(dataLength(value)==null){throwArgumentError("","value",value)}return value}hash(value){if(dataLength(value)!==32){throwArgumentError("","value",value)}return this.#format.data(value)}number(value){return getNumber(value)}object(format,altNames){return value=>{const result={};for(const key in format){let srcKey=key;if(altNames&&key in altNames&&!(srcKey in value)){for(const altKey of altNames[key]){if(altKey in value){srcKey=altKey;break}}}try{const nv=format[key].call(this,value[srcKey]);if(nv!==undefined){result[key]=nv}}catch(error){const message=error instanceof Error?error.message:"not-an-error";throwError(`invalid value for value.${key} (${message})`,"BAD_DATA",{value:value})}}return result}}}const EnsAddress="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class NetworkPlugin{name;constructor(name){defineProperties(this,{name:name})}clone(){return new NetworkPlugin(this.name)}validate(network){return this}}class GasCostPlugin extends NetworkPlugin{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(effectiveBlock=0,costs){super(`org.ethers.network-plugins.gas-cost#${effectiveBlock||0}`);const props={effectiveBlock:effectiveBlock};function set(name,nullish){let value=(costs||{})[name];if(value==null){value=nullish}if(typeof value!=="number"){throwArgumentError(`invalud value for ${name}`,"costs",costs)}props[name]=value}set("txBase",21e3);set("txCreate",32e3);set("txDataZero",4);set("txDataNonzero",16);set("txAccessListStorageKey",1900);set("txAccessListAddress",2400);defineProperties(this,props)}clone(){return new GasCostPlugin(this.effectiveBlock,this)}}class EnsPlugin extends NetworkPlugin{address;targetNetwork;constructor(address,targetNetwork){super("org.ethers.network-plugins.ens");defineProperties(this,{address:address||EnsAddress,targetNetwork:targetNetwork==null?1:targetNetwork})}clone(){return new EnsPlugin(this.address,this.targetNetwork)}validate(network){network.formatter.address(this.address);return this}}class FeeDataNetworkPlugin extends NetworkPlugin{#feeDataFunc;get feeDataFunc(){return this.#feeDataFunc}constructor(feeDataFunc){super("org.ethers.network-plugins.fee-data");this.#feeDataFunc=feeDataFunc}async getFeeData(provider){return await this.#feeDataFunc(provider)}clone(){return new FeeDataNetworkPlugin(this.#feeDataFunc)}}const Networks=new Map;const defaultFormatter=new Formatter;class Network{#props;constructor(name,_chainId,formatter){const chainId=getBigInt(_chainId);if(formatter==null){formatter=defaultFormatter}const plugins=new Map;this.#props={name:name,chainId:chainId,formatter:formatter,plugins:plugins}}toJSON(){return{name:this.name,chainId:this.chainId}}get name(){return getStore(this.#props,"name")}set name(value){setStore(this.#props,"name",value)}get chainId(){return getStore(this.#props,"chainId")}set chainId(value){setStore(this.#props,"chainId",getBigInt(value,"chainId"))}get formatter(){return getStore(this.#props,"formatter")}set formatter(value){setStore(this.#props,"formatter",value)}get plugins(){return Array.from(this.#props.plugins.values())}attachPlugin(plugin){if(this.isFrozen()){throw new Error("frozen")}if(this.#props.plugins.get(plugin.name)){throw new Error(`cannot replace existing plugin: ${plugin.name} `)}this.#props.plugins.set(plugin.name,plugin.validate(this));return this}getPlugin(name){return this.#props.plugins.get(name)||null}getPlugins(basename){return this.plugins.filter(p=>p.name.split("#")[0]===basename)}clone(){const clone=new Network(this.name,this.chainId,this.formatter);this.plugins.forEach(plugin=>{clone.attachPlugin(plugin.clone())});return clone}freeze(){Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}computeIntrinsicGas(tx){const costs=this.getPlugin("org.ethers.gas-cost")||new GasCostPlugin;let gas=costs.txBase;if(tx.to==null){gas+=costs.txCreate}if(tx.data){for(let i=2;i<tx.data.length;i+=2){if(tx.data.substring(i,i+2)==="00"){gas+=costs.txDataZero}else{gas+=costs.txDataNonzero}}}if(tx.accessList){const accessList=this.formatter.accessList(tx.accessList);for(const addr in accessList){gas+=costs.txAccessListAddress+costs.txAccessListStorageKey*accessList[addr].storageKeys.length}}return gas}static from(network){if(network==null){return Network.from("homestead")}if(typeof network==="number"){network=BigInt(network)}if(typeof network==="string"||typeof network==="bigint"){const networkFunc=Networks.get(network);if(networkFunc){return networkFunc()}if(typeof network==="bigint"){return new Network("unknown",network)}throwArgumentError("unknown network","network",network)}if(typeof network.clone==="function"){const clone=network.clone();return clone}if(typeof network==="object"){if(typeof network.name!=="string"||typeof network.chainId!=="number"){throwArgumentError("invalid network object name or chainId","network",network)}const custom=new Network(network.name,network.chainId);if(network.ensAddress||network.ensNetwork!=null){custom.attachPlugin(new EnsPlugin(network.ensAddress,network.ensNetwork))}return custom}return throwArgumentError("invalid network","network",network)}static register(nameOrChainId,networkFunc){if(typeof nameOrChainId==="number"){nameOrChainId=BigInt(nameOrChainId)}const existing=Networks.get(nameOrChainId);if(existing){throwArgumentError(`conflicting network for ${JSON.stringify(existing.name)}`,"nameOrChainId",nameOrChainId)}Networks.set(nameOrChainId,networkFunc)}}function copy$2(obj){return JSON.parse(JSON.stringify(obj))}function getPollingSubscriber(provider,event){if(event==="block"){return new PollingBlockSubscriber(provider)}if(isHexString(event,32)){return new PollingTransactionSubscriber(provider,event)}return throwError("unsupported polling event","UNSUPPORTED_OPERATION",{operation:"getPollingSubscriber",info:{event:event}})}class PollingBlockSubscriber{#provider;#poller;#interval;#blockNumber;constructor(provider){this.#provider=provider;this.#poller=null;this.#interval=4e3;this.#blockNumber=-2}get pollingInterval(){return this.#interval}set pollingInterval(value){this.#interval=value}async#poll(){const blockNumber=await this.#provider.getBlockNumber();if(this.#blockNumber===-2){this.#blockNumber=blockNumber;return}if(blockNumber!==this.#blockNumber){for(let b=this.#blockNumber+1;b<=blockNumber;b++){this.#provider.emit("block",b)}this.#blockNumber=blockNumber}this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval)}start(){if(this.#poller){throw new Error("subscriber already running")}this.#poll();this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval)}stop(){if(!this.#poller){throw new Error("subscriber not running")}this.#provider._clearTimeout(this.#poller);this.#poller=null}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}class OnBlockSubscriber{#provider;#poll;constructor(provider){this.#provider=provider;this.#poll=blockNumber=>{this._poll(blockNumber,this.#provider)}}async _poll(blockNumber,provider){throw new Error("sub-classes must override this")}start(){this.#poll(-2);this.#provider.on("block",this.#poll)}stop(){this.#provider.off("block",this.#poll)}pause(dropWhilePaused){this.stop()}resume(){this.start()}}class PollingOrphanSubscriber extends OnBlockSubscriber{#filter;constructor(provider,filter){super(provider);this.#filter=copy$2(filter)}async _poll(blockNumber,provider){throw new Error("@TODO");console.log(this.#filter)}}class PollingTransactionSubscriber extends OnBlockSubscriber{#hash;constructor(provider,hash){super(provider);this.#hash=hash}async _poll(blockNumber,provider){const tx=await provider.getTransactionReceipt(this.#hash);if(tx){provider.emit(this.#hash,tx)}}}class PollingEventSubscriber{#provider;#filter;#poller;#blockNumber;constructor(provider,filter){this.#provider=provider;this.#filter=copy$2(filter);this.#poller=this.#poll.bind(this);this.#blockNumber=-2}async#poll(blockNumber){if(this.#blockNumber===-2){return}const filter=copy$2(this.#filter);filter.fromBlock=this.#blockNumber+1;filter.toBlock=blockNumber;const logs=await this.#provider.getLogs(filter);if(logs.length===0){if(this.#blockNumber<blockNumber-60){this.#blockNumber=blockNumber-60}return}this.#blockNumber=blockNumber;for(const log of logs){this.#provider.emit(this.#filter,log)}}start(){if(this.#blockNumber===-2){this.#provider.getBlockNumber().then(blockNumber=>{this.#blockNumber=blockNumber})}this.#provider.on("block",this.#poller)}stop(){this.#provider.off("block",this.#poller)}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}const BN_2$1=BigInt(2);const MAX_CCIP_REDIRECTS=10;function getTag(prefix,value){return prefix+":"+JSON.stringify(value,(k,v)=>{if(typeof v==="bigint"){return`bigint:${v.toString()}`}if(typeof v==="string"){return v.toLowerCase()}if(typeof v==="object"&&!Array.isArray(v)){const keys=Object.keys(v);keys.sort();return keys.reduce((accum,key)=>{accum[key]=v[key];return accum},{})}return v})}class UnmanagedSubscriber{name;constructor(name){defineProperties(this,{name:name})}start(){}stop(){}pause(dropWhilePaused){}resume(){}}function copy$1(value){return JSON.parse(JSON.stringify(value))}function concisify$1(items){items=Array.from(new Set(items).values());items.sort();return items}async function getSubscription(_event,provider){if(_event==null){throw new Error("invalid event")}if(Array.isArray(_event)){_event={topics:_event}}if(typeof _event==="string"){switch(_event){case"block":case"pending":case"debug":case"network":{return{type:_event,tag:_event}}}}if(isHexString(_event,32)){const hash=_event.toLowerCase();return{type:"transaction",tag:getTag("tx",{hash:hash}),hash:hash}}if(_event.orphan){const event=_event;return{type:"orphan",tag:getTag("orphan",event),filter:copy$1(event)}}if(_event.address||_event.topics){const event=_event;const filter={topics:(event.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify$1(t.map(t=>t.toLowerCase()))}return t.toLowerCase()})};if(event.address){const addresses=[];const promises=[];const addAddress=addr=>{if(isHexString(addr)){addresses.push(addr)}else{promises.push((async()=>{addresses.push(await resolveAddress(addr,provider))})())}};if(Array.isArray(event.address)){event.address.forEach(addAddress)}else{addAddress(event.address)}if(promises.length){await Promise.all(promises)}filter.address=concisify$1(addresses.map(a=>a.toLowerCase()))}return{filter:filter,tag:getTag("event",filter),type:"event"}}return throwArgumentError("unknown ProviderEvent","event",_event)}function getTime$1(){return(new Date).getTime()}function copyRequest(tx){return tx}class AbstractProvider{#subs;#plugins;#pausedState;#networkPromise;#anyNetwork;#performCache;#nextTimer;#timers;#disableCcipRead;constructor(_network){if(_network==="any"){this.#anyNetwork=true;this.#networkPromise=null}else if(_network){const network=Network.from(_network);this.#anyNetwork=false;this.#networkPromise=Promise.resolve(network);setTimeout(()=>{this.emit("network",network,null)},0)}else{this.#anyNetwork=false;this.#networkPromise=null}this.#performCache=new Map;this.#subs=new Map;this.#plugins=new Map;this.#pausedState=null;this.#nextTimer=0;this.#timers=new Map;this.#disableCcipRead=false}get provider(){return this}get plugins(){return Array.from(this.#plugins.values())}attachPlugin(plugin){if(this.#plugins.get(plugin.name)){throw new Error(`cannot replace existing plugin: ${plugin.name} `)}this.#plugins.set(plugin.name,plugin.validate(this));return this}getPlugin(name){return this.#plugins.get(name)||null}set disableCcipRead(value){this.#disableCcipRead=!!value}get disableCcipRead(){return this.#disableCcipRead}async#perform(req){const tag=getTag(req.method,req);let perform=this.#performCache.get(tag);if(!perform){perform=this._perform(req);this.#performCache.set(tag,perform);setTimeout(()=>{if(this.#performCache.get(tag)===perform){this.#performCache.delete(tag)}},250)}return await perform}async ccipReadFetch(tx,calldata,urls){if(this.disableCcipRead||urls.length===0||tx.to==null){return null}const sender=tx.to.toLowerCase();const data=calldata.toLowerCase();const errorMessages=[];for(let i=0;i<urls.length;i++){const url=urls[i];const href=url.replace("{sender}",sender).replace("{data}",data);const request=new FetchRequest(href);if(url.indexOf("{data}")===-1){request.body={data:data,sender:sender}}let errorMessage="unknown error";const resp=await request.send();try{const result=resp.bodyJson;if(result.data){return result.data}if(result.message){errorMessage=result.message}}catch(error){}if(resp.statusCode>=400&&resp.statusCode<500){return throwError(`response not found during CCIP fetch: ${errorMessage}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:tx,info:{url:url,errorMessage:errorMessage}})}errorMessages.push(errorMessage)}return throwError(`error encountered during CCIP fetch: ${errorMessages.map(m=>JSON.stringify(m)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:tx,info:{urls:urls,errorMessages:errorMessages}})}_wrapTransaction(tx,hash,blockNumber){return tx}_detectNetwork(){return throwError("sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(req){return throwError(`unsupported method: ${req.method}`,"UNSUPPORTED_OPERATION",{operation:req.method,info:req})}async getBlockNumber(){return getNumber(await this.#perform({method:"getBlockNumber"}),"%response")}_getAddress(address){return resolveAddress(address,this)}_getBlockTag(blockTag){if(blockTag==null){return"latest"}switch(blockTag){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return blockTag}if(isHexString(blockTag)){if(dataLength(blockTag)===32){return blockTag}return toQuantity(blockTag)}if(typeof blockTag==="number"){if(blockTag>=0){return toQuantity(blockTag)}return this.getBlockNumber().then(b=>toQuantity(b+blockTag))}return throwArgumentError("invalid blockTag","blockTag",blockTag)}async getNetwork(){if(this.#networkPromise==null){const detectNetwork=this._detectNetwork().then(network=>{this.emit("network",network,null);return network},error=>{if(this.#networkPromise===detectNetwork){this.#networkPromise=null}throw error});this.#networkPromise=detectNetwork;return await detectNetwork}const networkPromise=this.#networkPromise;const[expected,actual]=await Promise.all([networkPromise,this._detectNetwork()]);if(expected.chainId!==actual.chainId){if(this.#anyNetwork){this.emit("network",actual,expected);if(this.#networkPromise===networkPromise){this.#networkPromise=Promise.resolve(actual)}}else{throwError(`network changed: ${expected.chainId} => ${actual.chainId} `,"NETWORK_ERROR",{event:"changed"})}}return expected.clone().freeze()}async getFeeData(){const{block,gasPrice}=await resolveProperties({block:this.getBlock("latest"),gasPrice:(async()=>{try{const gasPrice=await this.#perform({method:"getGasPrice"});return getBigInt(gasPrice,"%response")}catch(error){}return null})()});let maxFeePerGas=null,maxPriorityFeePerGas=null;if(block&&block.baseFeePerGas){maxPriorityFeePerGas=BigInt("1500000000");maxFeePerGas=block.baseFeePerGas*BN_2$1+maxPriorityFeePerGas}return new FeeData(gasPrice,maxFeePerGas,maxPriorityFeePerGas)}async _getTransaction(_request){const network=await this.getNetwork();const request=Object.assign({},_request,await resolveProperties({to:_request.to?resolveAddress(_request.to,this):undefined,from:_request.from?resolveAddress(_request.from,this):undefined}));return network.formatter.transactionRequest(request)}async estimateGas(_tx){const transaction=await this._getTransaction(_tx);return getBigInt(await this.#perform({method:"estimateGas",transaction:transaction}),"%response")}async#call(tx,blockTag,attempt){if(attempt>=MAX_CCIP_REDIRECTS){throwError("CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},tx,{blockTag:blockTag,enableCcipRead:true})})}const transaction=copyRequest(tx);try{return hexlify(await this._perform({method:"call",transaction:transaction,blockTag:blockTag}))}catch(error){if(!this.disableCcipRead&&isCallException(error)&&attempt>=0&&blockTag==="latest"&&transaction.to!=null&&dataSlice(error.data,0,4)==="0x556f1830"){const data=error.data;const txSender=await resolveAddress(transaction.to,this);let ccipArgs;try{ccipArgs=parseOffchainLookup(dataSlice(error.data,4))}catch(error){return throwError(error.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:transaction,info:{data:data}})}if(ccipArgs.sender.toLowerCase()!==txSender.toLowerCase()){return throwError("CCIP Read sender mismatch","CALL_EXCEPTION",{data:data,transaction:transaction,errorSignature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",errorName:"OffchainLookup",errorArgs:ccipArgs.errorArgs})}const ccipResult=await this.ccipReadFetch(transaction,ccipArgs.calldata,ccipArgs.urls);if(ccipResult==null){return throwError("CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:transaction,info:{data:error.data,errorArgs:ccipArgs.errorArgs}})}return this.#call({to:txSender,data:concat([ccipArgs.selector,encodeBytes([ccipResult,ccipArgs.extraData])])},blockTag,attempt+1)}throw error}}async call(_tx){const[tx,blockTag]=await Promise.all([this._getTransaction(_tx),this._getBlockTag(_tx.blockTag)]);return this.#call(tx,blockTag,_tx.enableCcipRead?0:-1)}async#getAccountValue(request,_address,_blockTag){let address=this._getAddress(_address);let blockTag=this._getBlockTag(_blockTag);if(typeof address!=="string"||typeof blockTag!=="string"){[address,blockTag]=await Promise.all([address,blockTag])}return await this.#perform(Object.assign(request,{address:address,blockTag:blockTag}))}async getBalance(address,blockTag){return getBigInt(await this.#getAccountValue({method:"getBalance"},address,blockTag),"%response")}async getTransactionCount(address,blockTag){return getNumber(await this.#getAccountValue({method:"getTransactionCount"},address,blockTag),"%response")}async getCode(address,blockTag){return hexlify(await this.#getAccountValue({method:"getCode"},address,blockTag))}async getStorageAt(address,_position,blockTag){const position=getBigInt(_position,"position");return hexlify(await this.#getAccountValue({method:"getStorageAt",position:position},address,blockTag))}async broadcastTransaction(signedTx){throw new Error;return{}}async#getBlock(block,includeTransactions){if(isHexString(block,32)){return await this.#perform({method:"getBlock",blockHash:block,includeTransactions:includeTransactions})}let blockTag=this._getBlockTag(block);if(typeof blockTag!=="string"){blockTag=await blockTag}return await this.#perform({method:"getBlock",blockTag:blockTag,includeTransactions:includeTransactions})}async getBlock(block){const[network,params]=await Promise.all([this.getNetwork(),this.#getBlock(block,false)]);if(params==null){return null}return network.formatter.block(params,this)}async getBlockWithTransactions(block){const format=(await this.getNetwork()).formatter;const params=this.#getBlock(block,true);if(params==null){return null}return format.blockWithTransactions(params,this)}async getTransaction(hash){const format=(await this.getNetwork()).formatter;const params=await this.#perform({method:"getTransaction",hash:hash});return format.transactionResponse(params,this)}async getTransactionReceipt(hash){const format=(await this.getNetwork()).formatter;const receipt=await this.#perform({method:"getTransactionReceipt",hash:hash});if(receipt==null){return null}if(receipt.gasPrice==null&&receipt.effectiveGasPrice==null){const tx=await this.#perform({method:"getTransaction",hash:hash});receipt.effectiveGasPrice=tx.gasPrice}return format.receipt(receipt,this)}async getTransactionResult(hash){const result=await this.#perform({method:"getTransactionResult",hash:hash});if(result==null){return null}return hexlify(result)}_getFilter(filter){const topics=(filter.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify$1(t.map(t=>t.toLowerCase()))}return t.toLowerCase()});const blockHash="blockHash"in filter?filter.blockHash:undefined;const resolve=(_address,fromBlock,toBlock)=>{let address=undefined;switch(_address.length){case 0:break;case 1:address=_address[0];break;default:_address.sort();address=_address}if(blockHash){if(fromBlock!=null||toBlock!=null){throw new Error("invalid filter")}}const filter={};if(address){filter.address=address}if(topics.length){filter.topics=topics}if(fromBlock){filter.fromBlock=fromBlock}if(toBlock){filter.toBlock=toBlock}if(blockHash){filter.blockHash=blockHash}return filter};let address=[];if(filter.address){if(Array.isArray(filter.address)){for(const addr of filter.address){address.push(this._getAddress(addr))}}else{address.push(this._getAddress(filter.address))}}let fromBlock=undefined;if("fromBlock"in filter){fromBlock=this._getBlockTag(filter.fromBlock)}let toBlock=undefined;if("toBlock"in filter){toBlock=this._getBlockTag(filter.toBlock)}if(address.filter(a=>typeof a!=="string").length||fromBlock!=null&&typeof fromBlock!=="string"||toBlock!=null&&typeof toBlock!=="string"){return Promise.all([Promise.all(address),fromBlock,toBlock]).then(result=>{return resolve(result[0],result[1],result[2])})}return resolve(address,fromBlock,toBlock)}async getLogs(_filter){const{network,filter}=await resolveProperties({network:this.getNetwork(),filter:this._getFilter(_filter)});return(await this.#perform({method:"getLogs",filter:filter})).map(l=>{return network.formatter.log(l,this)})}_getProvider(chainId){return throwError("provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(name){return await EnsResolver.fromName(this,name)}async getAvatar(name){const resolver=await this.getResolver(name);if(resolver){return await resolver.getAvatar()}return null}async resolveName(name){if(isHexString(name,20)){return name}const resolver=await this.getResolver(name);if(resolver){return await resolver.getAddress()}return null}async lookupAddress(address){throw new Error}async waitForTransaction(hash,confirms=1,timeout){if(confirms===0){return this.getTransactionReceipt(hash)}return new Promise(async(resolve,reject)=>{let timer=null;const listener=async blockNumber=>{try{const receipt=await this.getTransactionReceipt(hash);if(receipt!=null){if(blockNumber-receipt.blockNumber+1>=confirms){resolve(receipt);this.off("block",listener);if(timer){clearTimeout(timer);timer=null}return}}}catch(error){console.log("EEE",error)}this.once("block",listener)};if(timeout!=null){timer=setTimeout(()=>{if(timer==null){return}timer=null;this.off("block",listener);reject(makeError("timeout","TIMEOUT",{reason:"timeout"}))},timeout)}listener(await this.getBlockNumber())})}async waitForBlock(blockTag){throw new Error}_clearTimeout(timerId){const timer=this.#timers.get(timerId);if(!timer){return}if(timer.timer){clearTimeout(timer.timer)}this.#timers.delete(timerId)}_setTimeout(_func,timeout=0){const timerId=this.#nextTimer++;const func=()=>{this.#timers.delete(timerId);_func()};if(this.paused){this.#timers.set(timerId,{timer:null,func:func,time:timeout})}else{const timer=setTimeout(func,timeout);this.#timers.set(timerId,{timer:timer,func:func,time:getTime$1()})}return timerId}_forEachSubscriber(func){for(const sub of this.#subs.values()){func(sub.subscriber)}}_getSubscriber(sub){switch(sub.type){case"debug":case"network":return new UnmanagedSubscriber(sub.type);case"block":return new PollingBlockSubscriber(this);case"event":return new PollingEventSubscriber(this,sub.filter);case"transaction":return new PollingTransactionSubscriber(this,sub.hash);case"orphan":return new PollingOrphanSubscriber(this,sub.filter)}throw new Error(`unsupported event: ${sub.type}`)}_recoverSubscriber(oldSub,newSub){for(const sub of this.#subs.values()){if(sub.subscriber===oldSub){if(sub.started){sub.subscriber.stop()}sub.subscriber=newSub;if(sub.started){newSub.start()}if(this.#pausedState!=null){newSub.pause(this.#pausedState)}break}}}async#hasSub(event,emitArgs){let sub=await getSubscription(event,this);if(sub.type==="event"&&emitArgs&&emitArgs.length>0&&emitArgs[0].removed===true){sub=await getSubscription({orphan:"drop-log",log:emitArgs[0]},this)}return this.#subs.get(sub.tag)||null}async#getSub(event){const subscription=await getSubscription(event,this);const tag=subscription.tag;let sub=this.#subs.get(tag);if(!sub){const subscriber=this._getSubscriber(subscription);const addressableMap=new WeakMap;const nameMap=new Map;sub={subscriber:subscriber,tag:tag,addressableMap:addressableMap,nameMap:nameMap,started:false,listeners:[]};this.#subs.set(tag,sub)}return sub}async on(event,listener){const sub=await this.#getSub(event);sub.listeners.push({listener:listener,once:false});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async once(event,listener){const sub=await this.#getSub(event);sub.listeners.push({listener:listener,once:true});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async emit(event,...args){const sub=await this.#hasSub(event,args);if(!sub){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const payload=new EventPayload(this,once?null:listener,event);try{listener.call(this,...args,payload)}catch(error){}return!once});return count>0}async listenerCount(event){if(event){const sub=await this.#hasSub(event);if(!sub){return 0}return sub.listeners.length}let total=0;for(const{listeners}of this.#subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await this.#hasSub(event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}let result=[];for(const{listeners}of this.#subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener){const sub=await this.#hasSub(event);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(!listener||sub.listeners.length===0){if(sub.started){sub.subscriber.stop()}this.#subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const{tag,started,subscriber}=await this.#getSub(event);if(started){subscriber.stop()}this.#subs.delete(tag)}else{for(const[tag,{started,subscriber}]of this.#subs){if(started){subscriber.stop()}this.#subs.delete(tag)}}return this}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return this.off(event,listener)}async shutdown(){this.removeAllListeners();for(const timerId of this.#timers.keys()){this._clearTimeout(timerId)}}get paused(){return this.#pausedState!=null}set paused(pause){if(!!pause===this.paused){return}if(this.paused){this.resume()}else{this.pause(false)}}pause(dropWhilePaused){if(this.#pausedState!=null){if(this.#pausedState==!!dropWhilePaused){return}return throwError("cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(s=>s.pause(dropWhilePaused));this.#pausedState=!!dropWhilePaused;for(const timer of this.#timers.values()){if(timer.timer){clearTimeout(timer.timer)}timer.time=getTime$1()-timer.time}}resume(){if(this.#pausedState==null){return}this._forEachSubscriber(s=>s.resume());this.#pausedState=null;for(const timer of this.#timers.values()){let timeout=timer.time;if(timeout<0){timeout=0}timer.time=getTime$1();setTimeout(timer.func,timeout)}}}function _parseString(result,start){try{const bytes=_parseBytes(result,start);if(bytes){return toUtf8String(bytes)}}catch(error){}return null}function _parseBytes(result,start){if(result==="0x"){return null}try{const offset=getNumber(dataSlice(result,start,start+32));const length=getNumber(dataSlice(result,offset,offset+32));return dataSlice(result,offset+32,offset+32+length)}catch(error){}return null}function numPad(value){const result=toArray(value);if(result.length>32){throw new Error("internal; should not happen")}const padded=new Uint8Array(32);padded.set(result,32-result.length);return padded}function bytesPad(value){if(value.length%32===0){return value}const result=new Uint8Array(Math.ceil(value.length/32)*32);result.set(value);return result}const empty=new Uint8Array([]);function encodeBytes(datas){const result=[];let byteCount=0;for(let i=0;i<datas.length;i++){result.push(empty);byteCount+=32}for(let i=0;i<datas.length;i++){const data=getBytes(datas[i]);result[i]=numPad(byteCount);result.push(numPad(data.length));result.push(bytesPad(data));byteCount+=32+Math.ceil(data.length/32)*32}return concat(result)}const zeros="0x0000000000000000000000000000000000000000000000000000000000000000";function parseOffchainLookup(data){const result={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};if(dataLength(data)<5*32){throw new Error("insufficient OffchainLookup data")}const sender=dataSlice(data,0,32);if(dataSlice(sender,0,12)!==dataSlice(zeros,0,12)){throw new Error("corrupt OffchainLookup sender")}result.sender=dataSlice(sender,12);try{const urls=[];const urlsOffset=getNumber(dataSlice(data,32,64));const urlsLength=getNumber(dataSlice(data,urlsOffset,urlsOffset+32));const urlsData=dataSlice(data,urlsOffset+32);for(let u=0;u<urlsLength;u++){const url=_parseString(urlsData,u*32);if(url==null){throw new Error("abort")}urls.push(url)}result.urls=urls}catch(error){throw new Error("corrupt OffchainLookup urls")}try{const calldata=_parseBytes(data,64);if(calldata==null){throw new Error("abort")}result.calldata=calldata}catch(error){throw new Error("corrupt OffchainLookup calldata")}if(dataSlice(data,100,128)!==dataSlice(zeros,0,28)){throw new Error("corrupt OffchainLookup callbaackSelector")}result.selector=dataSlice(data,96,100);try{const extraData=_parseBytes(data,128);if(extraData==null){throw new Error("abort")}result.extraData=extraData}catch(error){throw new Error("corrupt OffchainLookup extraData")}result.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map(k=>result[k]);return result}class AbstractSigner{provider;constructor(provider){defineProperties(this,{provider:provider||null})}#checkProvider(operation){if(this.provider){return this.provider}return throwError("missing provider","UNSUPPORTED_OPERATION",{operation:operation})}async getNonce(blockTag){return this.#checkProvider("getTransactionCount").getTransactionCount(await this.getAddress(),blockTag)}async#populate(op,tx){const provider=this.#checkProvider(op);let pop=Object.assign({},tx);if(pop.to!=null){pop.to=provider.resolveName(pop.to).then(to=>{if(to==null){return throwArgumentError("transaction to ENS name not configured","tx.to",pop.to)}return to})}if(pop.from!=null){const from=pop.from;pop.from=Promise.all([this.getAddress(),this.resolveName(from)]).then(([address,from])=>{if(!from||address.toLowerCase()!==from.toLowerCase()){return throwArgumentError("transaction from mismatch","tx.from",from)}return address})}return pop}async populateCall(tx){const pop=await this.#populate("populateCall",tx);return pop}async populateTransaction(tx){const pop=await this.#populate("populateTransaction",tx);if(pop.nonce==null){pop.nonce=await this.getNonce("pending")}if(pop.gasLimit==null){pop.gasLimit=await this.estimateGas(pop)}const network=await this.provider.getNetwork();if(pop.chainId!=null){const chainId=getBigInt(pop.chainId);if(chainId!==network.chainId){throwArgumentError("transaction chainId mismatch","tx.chainId",tx.chainId)}}else{pop.chainId=network.chainId}return await resolveProperties(pop)}async estimateGas(tx){return this.#checkProvider("estimateGas").estimateGas(await this.populateCall(tx))}async call(tx){return this.#checkProvider("call").call(await this.populateCall(tx))}async resolveName(name){const provider=this.#checkProvider("resolveName");return await provider.resolveName(name)}async sendTransaction(tx){const provider=this.#checkProvider("sendTransaction");const txObj=Transaction.from(await this.populateTransaction(tx));return await provider.broadcastTransaction(await this.signTransaction(txObj))}}class VoidSigner extends AbstractSigner{address;constructor(address,provider){super(provider);defineProperties(this,{address:address})}async getAddress(){return this.address}connect(provider){return new VoidSigner(this.address,provider)}#throwUnsupported(suffix,operation){return throwError(`VoidSigner cannot sign ${suffix}`,"UNSUPPORTED_OPERATION",{operation:operation})}async signTransaction(tx){this.#throwUnsupported("transactions","signTransaction")}async signMessage(message){this.#throwUnsupported("messages","signMessage")}async signTypedData(domain,types,value){this.#throwUnsupported("typed-data","signTypedData")}}class WrappedSigner extends AbstractSigner{#signer;constructor(signer){super(signer.provider);this.#signer=signer}async getAddress(){return await this.#signer.getAddress()}connect(provider){return new WrappedSigner(this.#signer.connect(provider))}async getNonce(blockTag){return await this.#signer.getNonce(blockTag)}async populateCall(tx){return await this.#signer.populateCall(tx)}async populateTransaction(tx){return await this.#signer.populateTransaction(tx)}async estimateGas(tx){return await this.#signer.estimateGas(tx)}async call(tx){return await this.#signer.call(tx)}async resolveName(name){return this.#signer.resolveName(name)}async signTransaction(tx){return await this.#signer.signTransaction(tx)}async sendTransaction(tx){return await this.#signer.sendTransaction(tx)}async signMessage(message){return await this.#signer.signMessage(message)}async signTypedData(domain,types,value){return await this.#signer.signTypedData(domain,types,value)}}const defaultApiKey$2="9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB";const EtherscanPluginId="org.ethers.plugins.etherscan";class EtherscanPlugin extends NetworkPlugin{baseUrl;communityApiKey;constructor(baseUrl,communityApiKey){super(EtherscanPluginId);defineProperties(this,{baseUrl:baseUrl,communityApiKey:communityApiKey})}clone(){return new EtherscanPlugin(this.baseUrl,this.communityApiKey)}}class EtherscanProvider extends AbstractProvider{network;apiKey;constructor(_network,apiKey){super();const network=Network.from(_network);if(apiKey==null){const plugin=network.getPlugin(EtherscanPluginId);if(plugin){apiKey=plugin.communityApiKey}else{apiKey=defaultApiKey$2}}defineProperties(this,{apiKey:apiKey,network:network});this.getBaseUrl()}getBaseUrl(){const plugin=this.network.getPlugin(EtherscanPluginId);if(plugin){return plugin.baseUrl}switch(this.network.name){case"homestead":return"https://api.etherscan.io";case"ropsten":return"https://api-ropsten.etherscan.io";case"rinkeby":return"https://api-rinkeby.etherscan.io";case"kovan":return"https://api-kovan.etherscan.io";case"goerli":return"https://api-goerli.etherscan.io";default:}return throwArgumentError("unsupported network","network",this.network)}getUrl(module,params){const query=Object.keys(params).reduce((accum,key)=>{const value=params[key];if(value!=null){accum+=`&${key}=${value}`}return accum},"");const apiKey=this.apiKey?`&apikey=${this.apiKey}`:"";return`${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`}getPostUrl(){return`${this.getBaseUrl()}/api`}getPostData(module,params){params.module=module;params.apikey=this.apiKey;return params}async detectNetwork(){return this.network}async fetch(module,params,post){const url=post?this.getPostUrl():this.getUrl(module,params);const payload=post?this.getPostData(module,params):null;const request=new FetchRequest(url);request.processFunc=async(request,response)=>{const result=response.hasBody()?JSON.parse(toUtf8String(response.body)):{};const throttle=(typeof result.result==="string"?result.result:"").toLowerCase().indexOf("rate limit")>=0;if(module==="proxy"){if(result&&result.status==0&&result.message=="NOTOK"&&throttle){response.throwThrottleError(result.result)}}else{if(throttle){response.throwThrottleError(result.result)}}return response};if(payload){request.setHeader("content-type","application/x-www-form-urlencoded; charset=UTF-8");request.body=Object.keys(payload).map(k=>`${k}=${payload[k]}`).join("&")}const response=await request.send();response.assertOk();if(!response.hasBody()){throw new Error}const result=JSON.parse(toUtf8String(response.body));if(module==="proxy"){if(result.jsonrpc!="2.0"){const error=new Error("invalid response");error.result=JSON.stringify(result);throw error}if(result.error){const error=new Error(result.error.message||"unknown error");if(result.error.code){error.code=result.error.code}if(result.error.data){error.data=result.error.data}throw error}return result.result}else{if(result.status==0&&(result.message==="No records found"||result.message==="No transactions found")){return result.result}if(result.status!=1||result.message!="OK"){const error=new Error("invalid response");error.result=JSON.stringify(result);throw error}return result.result}}_getTransactionPostData(transaction){const result={};for(let key in transaction){if(transaction[key]==null){continue}let value=transaction[key];if(key==="type"&&value===0){continue}if({type:true,gasLimit:true,gasPrice:true,maxFeePerGs:true,maxPriorityFeePerGas:true,nonce:true,value:true}[key]){value=toQuantity(hexlify(value))}else if(key==="accessList"){value="["+this.network.formatter.accessList(value).map(set=>{return`{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`}).join(",")+"]"}else{value=hexlify(value)}result[key]=value}return result}_checkError(req,error,transaction){throw error}async _detectNetwork(){return this.network}async _perform(req){switch(req.method){case"chainId":return this.network.chainId;case"getBlockNumber":return this.fetch("proxy",{action:"eth_blockNumber"});case"getGasPrice":return this.fetch("proxy",{action:"eth_gasPrice"});case"getBalance":return this.fetch("account",{action:"balance",address:req.address,tag:req.blockTag});case"getTransactionCount":return this.fetch("proxy",{action:"eth_getTransactionCount",address:req.address,tag:req.blockTag});case"getCode":return this.fetch("proxy",{action:"eth_getCode",address:req.address,tag:req.blockTag});case"getStorageAt":return this.fetch("proxy",{action:"eth_getStorageAt",address:req.address,position:req.position,tag:req.blockTag});case"broadcastTransaction":return this.fetch("proxy",{action:"eth_sendRawTransaction",hex:req.signedTransaction},true).catch(error=>{return this._checkError(req,error,req.signedTransaction)});case"getBlock":if("blockTag"in req){return this.fetch("proxy",{action:"eth_getBlockByNumber",tag:req.blockTag,boolean:req.includeTransactions?"true":"false"})}return throwError("getBlock by blockHash not supported by Etherscan","UNSUPPORTED_OPERATION",{operation:"getBlock(blockHash)"});case"getTransaction":return this.fetch("proxy",{action:"eth_getTransactionByHash",txhash:req.hash});case"getTransactionReceipt":return this.fetch("proxy",{action:"eth_getTransactionReceipt",txhash:req.hash});case"call":{if(req.blockTag!=="latest"){throw new Error("EtherscanProvider does not support blockTag for call")}const postData=this._getTransactionPostData(req.transaction);postData.module="proxy";postData.action="eth_call";try{return await this.fetch("proxy",postData,true)}catch(error){return this._checkError(req,error,req.transaction)}}case"estimateGas":{const postData=this._getTransactionPostData(req.transaction);postData.module="proxy";postData.action="eth_estimateGas";try{return await this.fetch("proxy",postData,true)}catch(error){return this._checkError(req,error,req.transaction)}}default:break}return super._perform(req)}async getNetwork(){return this.network}async getEtherPrice(){if(this.network.name!=="homestead"){return 0}return parseFloat((await this.fetch("stats",{action:"ethprice"})).ethusd)}isCommunityResource(){const plugin=this.network.getPlugin(EtherscanPluginId);if(plugin){return plugin.communityApiKey===this.apiKey}return defaultApiKey$2===this.apiKey}}function injectCommonNetworks(){function registerEth(name,chainId,options){const func=function(){const network=new Network(name,chainId);if(options.ensNetwork!=null){network.attachPlugin(new EnsPlugin(null,options.ensNetwork))}if(options.priorityFee){}if(options.etherscan){const{url,apiKey}=options.etherscan;network.attachPlugin(new EtherscanPlugin(url,apiKey))}network.attachPlugin(new GasCostPlugin);return network};Network.register(name,func);Network.register(chainId,func);if(options.altNames){options.altNames.forEach(name=>{Network.register(name,func)})}}registerEth("homestead",1,{ensNetwork:1,altNames:["mainnet"]});registerEth("ropsten",3,{ensNetwork:3});registerEth("rinkeby",4,{ensNetwork:4});registerEth("goerli",5,{ensNetwork:5});registerEth("kovan",42,{ensNetwork:42});registerEth("classic",61,{});registerEth("classicKotti",6,{});registerEth("xdai",100,{ensNetwork:1});registerEth("matic",137,{ensNetwork:1,etherscan:{apiKey:"W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7",url:"https://api.polygonscan.com/"}});registerEth("maticMumbai",80001,{etherscan:{apiKey:"W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7",url:"https://api-testnet.polygonscan.com/"}});registerEth("bnb",56,{ensNetwork:1,etherscan:{apiKey:"EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9",url:"http://api.bscscan.com"}});registerEth("bnbt",97,{etherscan:{apiKey:"EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9",url:"http://api-testnet.bscscan.com"}})}injectCommonNetworks();const BN_1=BigInt("1");const BN_2=BigInt("2");function shuffle(array){for(let i=array.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));const tmp=array[i];array[i]=array[j];array[j]=tmp}}function stall$2(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}function getTime(){return(new Date).getTime()}const defaultConfig={stallTimeout:400,priority:1,weight:1};const defaultState={blockNumber:-2,requests:0,lateResponses:0,errorResponses:0,outOfSync:-1,unsupportedEvents:0,rollingDuration:0,score:0,_network:null,_updateNumber:null,_totalTime:0};async function waitForSync(config,blockNumber){while(config.blockNumber<0||config.blockNumber<blockNumber){if(!config._updateNumber){config._updateNumber=(async()=>{const blockNumber=await config.provider.getBlockNumber();if(blockNumber>config.blockNumber){config.blockNumber=blockNumber}config._updateNumber=null})()}await config._updateNumber;config.outOfSync++}}function normalize(network,value,req){switch(req.method){case"chainId":return getBigInt(value).toString();case"getBlockNumber":return getNumber(value).toString();case"getGasPrice":return getBigInt(value).toString();case"getBalance":return getBigInt(value).toString();case"getTransactionCount":return getNumber(value).toString();case"getCode":return hexlify(value);case"getStorageAt":return hexlify(value);case"getBlock":if(req.includeTransactions){return JSON.stringify(network.formatter.blockWithTransactions(value))}return JSON.stringify(network.formatter.block(value));case"getTransaction":return JSON.stringify(network.formatter.transactionResponse(value));case"getTransactionReceipt":return JSON.stringify(network.formatter.receipt(value));case"call":return hexlify(value);case"estimateGas":return getBigInt(value).toString();case"getLogs":return JSON.stringify(value.map(v=>network.formatter.log(v)))}return throwError("unsupported method","UNSUPPORTED_OPERATION",{operation:`_perform(${JSON.stringify(req.method)})`})}function checkQuorum(quorum,results){const tally=new Map;for(const{result,normal,weight}of results){const t=tally.get(normal)||{result:result,weight:0};t.weight+=weight;tally.set(normal,t)}let bestWeight=0;let bestResult=undefined;for(const{weight,result}of tally.values()){if(weight>=quorum&&weight>bestWeight){bestWeight=weight;bestResult=result}}return bestResult}function getMedian(results){const values=results.map(r=>BigInt(r.result));values.sort((a,b)=>a<b?-1:b>a?1:0);const mid=values.length/2;if(values.length%2){return values[mid]}return(values[mid-1]+values[mid]+BN_1)/BN_2}function getFuzzyMode(quorum,results){if(quorum===1){return getNumber(getMedian(results),"%internal")}const tally=new Map;const add=(result,weight)=>{const t=tally.get(result)||{result:result,weight:0};t.weight+=weight;tally.set(result,t)};for(const{weight,result}of results){const r=getNumber(result);add(r-1,weight);add(r,weight);add(r+1,weight)}let bestWeight=0;let bestResult=undefined;for(const{weight,result}of tally.values()){if(weight>=quorum&&(weight>bestWeight||bestResult!=null&&weight===bestWeight&&result>bestResult)){bestWeight=weight;bestResult=result}}return bestResult}class FallbackProvider extends AbstractProvider{quorum;eventQuorum;eventWorkers;#configs;#height;#initialSyncPromise;constructor(providers,network){super(network);this.#configs=providers.map(p=>{if(p instanceof AbstractProvider){return Object.assign({provider:p},defaultConfig,defaultState)}else{return Object.assign({},defaultConfig,p,defaultState)}});this.#height=-2;this.#initialSyncPromise=null;this.quorum=2;this.eventQuorum=1;this.eventWorkers=1;if(this.quorum>this.#configs.reduce((a,c)=>a+c.weight,0)){throwArgumentError("quorum exceed provider wieght","quorum",this.quorum)}}get providerConfigs(){return this.#configs.slice()}async _detectNetwork(){return Network.from(getBigInt(await this._perform({method:"chainId"}))).freeze()}#getNextConfig(configs){const allConfigs=this.#configs.slice();shuffle(allConfigs);allConfigs.sort((a,b)=>b.priority-a.priority);for(const config of allConfigs){if(configs.indexOf(config)===-1){return config}}return null}#addRunner(running,req){const config=this.#getNextConfig(Array.from(running).map(r=>r.config));if(config==null){return null}const result={};const runner={config:config,result:result,didBump:false,done:false,perform:null,staller:null};const now=getTime();runner.perform=(async()=>{try{config.requests++;result.result=await config.provider._perform(req)}catch(error){config.errorResponses++;result.error=error}if(runner.done){config.lateResponses++}const dt=getTime()-now;config._totalTime+=dt;config.rollingDuration=.95*config.rollingDuration+.05*dt;runner.perform=null})();runner.staller=(async()=>{await stall$2(config.stallTimeout);runner.staller=null})();running.add(runner);return runner}async#initialSync(){let initialSync=this.#initialSyncPromise;if(!initialSync){const promises=[];this.#configs.forEach(config=>{promises.push(waitForSync(config,0));promises.push((async()=>{config._network=await config.provider.getNetwork()})())});this.#initialSyncPromise=initialSync=(async()=>{await Promise.all(promises);let chainId=null;for(const config of this.#configs){const network=config._network;if(chainId==null){chainId=network.chainId}else if(network.chainId!==chainId){throwError("cannot mix providers on different networks","UNSUPPORTED_OPERATION",{operation:"new FallbackProvider"})}}})()}await initialSync}async#checkQuorum(running,req){const results=[];for(const runner of running){if("result"in runner.result){const result=runner.result.result;results.push({result:result,normal:normalize(runner.config._network,result,req),weight:runner.config.weight})}}if(results.reduce((a,r)=>a+r.weight,0)<this.quorum){return undefined}switch(req.method){case"getBlockNumber":{if(this.#height===-2){const height=Math.ceil(getNumber(getMedian(this.#configs.map(c=>({result:c.blockNumber,normal:getNumber(c.blockNumber).toString(),weight:c.weight}))),"%internal"));this.#height=height}const mode=getFuzzyMode(this.quorum,results);if(mode===undefined){return undefined}if(mode>this.#height){this.#height=mode}return this.#height}case"getGasPrice":case"estimateGas":return getMedian(results);case"getBlock":if("blockTag"in req&&req.blockTag==="pending"){return results[0].result}return checkQuorum(this.quorum,results);case"chainId":case"getBalance":case"getTransactionCount":case"getCode":case"getStorageAt":case"getTransaction":case"getTransactionReceipt":case"getLogs":return checkQuorum(this.quorum,results);case"call":return checkQuorum(this.quorum,results);case"broadcastTransaction":throw new Error("TODO")}return throwError("unsupported method","UNSUPPORTED_OPERATION",{operation:`_perform(${JSON.stringify(req.method)})`})}async#waitForQuorum(running,req){if(running.size===0){throw new Error("no runners?!")}const interesting=[];let newRunners=0;for(const runner of running){if(runner.perform){interesting.push(runner.perform)}if(runner.staller){interesting.push(runner.staller);continue}if(runner.didBump){continue}runner.didBump=true;newRunners++}const value=await this.#checkQuorum(running,req);if(value!==undefined){if(value instanceof Error){throw value}return value}for(let i=0;i<newRunners;i++){this.#addRunner(running,req)}if(interesting.length===0){throw new Error("quorum not met")}await Promise.race(interesting);return await this.#waitForQuorum(running,req)}async _perform(req){await this.#initialSync();const running=new Set;for(let i=0;i<this.quorum;i++){this.#addRunner(running,req)}const result=this.#waitForQuorum(running,req);for(const runner of running){runner.done=true}return result}}function copy(obj){return JSON.parse(JSON.stringify(obj))}class FilterIdSubscriber{#provider;#filterIdPromise;#poller;#network;constructor(provider){this.#provider=provider;this.#filterIdPromise=null;this.#poller=this.#poll.bind(this);this.#network=null}_subscribe(provider){throw new Error("subclasses must override this")}_emitResults(provider,result){throw new Error("subclasses must override this")}_recover(provider){throw new Error("subclasses must override this")}async#poll(blockNumber){try{if(this.#filterIdPromise==null){this.#filterIdPromise=this._subscribe(this.#provider)}const filterId=await this.#filterIdPromise;if(filterId==null){this.#provider._recoverSubscriber(this,this._recover(this.#provider));return}const network=await this.#provider.getNetwork();if(!this.#network){this.#network=network}if(this.#network.chainId!==network.chainId){throw new Error("chaid changed")}const result=await this.#provider.send("eth_getFilterChanges",[filterId]);await this._emitResults(this.#provider,result)}catch(error){console.log("@TODO",error)}this.#provider.once("block",this.#poller)}#teardown(){const filterIdPromise=this.#filterIdPromise;if(filterIdPromise){this.#filterIdPromise=null;filterIdPromise.then(filterId=>{this.#provider.send("eth_uninstallFilter",[filterId])})}}start(){this.#poll(-2)}stop(){this.#teardown();this.#provider.off("block",this.#poller)}pause(dropWhilePaused){if(dropWhilePaused){this.#teardown()}this.#provider.off("block",this.#poller)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#event;constructor(provider,filter){super(provider);this.#event=copy(filter)}_recover(provider){return new PollingEventSubscriber(provider,this.#event)}async _subscribe(provider){const filterId=await provider.send("eth_newFilter",[this.#event]);console.log("____SUB",filterId);return filterId}async _emitResults(provider,results){const network=await provider.getNetwork();for(const result of results){const log=network.formatter.log(result,provider);provider.emit(this.#event,log)}}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(provider){return await provider.send("eth_newPendingTransactionFilter",[])}async _emitResults(provider,results){const network=await provider.getNetwork();for(const result of results){provider.emit("pending",network.formatter.hash(result))}}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(value){if(value==null||Primitive.indexOf(typeof value)>=0){return value}if(typeof value.getAddress==="function"){return value}if(Array.isArray(value)){return value.map(deepCopy)}if(typeof value==="object"){return Object.keys(value).reduce((accum,key)=>{accum[key]=value[key];return accum},{})}throw new Error(`should not happen: ${value} (${typeof value})`)}function getLowerCase(value){if(value){return value.toLowerCase()}return value}function isPollable(value){return value&&typeof value.pollingInterval==="number"}const defaultOptions={polling:false,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100};class JsonRpcSigner extends AbstractSigner{address;constructor(provider,address){super(provider);defineProperties(this,{address:address})}connect(provider){return throwError("cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(tx){return await this.populateCall(tx)}async sendUncheckedTransaction(_tx){const tx=deepCopy(_tx);const promises=[];if(tx.from){const _from=tx.from;promises.push((async()=>{const from=await resolveAddress(_from,this.provider);if(from==null||from.toLowerCase()!==this.address.toLowerCase()){throwArgumentError("from address mismatch","transaction",_tx)}tx.from=from})())}else{tx.from=this.address}if(tx.gasLimit==null){promises.push((async()=>{tx.gasLimit=await this.provider.estimateGas({...tx,from:this.address})})())}if(tx.to!=null){const _to=tx.to;promises.push((async()=>{tx.to=await resolveAddress(_to,this.provider)})())}if(promises.length){await Promise.all(promises)}const hexTx=this.provider.getRpcTransaction(tx);return this.provider.send("eth_sendTransaction",[hexTx])}async sendTransaction(tx){const blockNumber=await this.provider.getBlockNumber();const hash=await this.sendUncheckedTransaction(tx);return await new Promise((resolve,reject)=>{const timeouts=[1e3,100];const checkTx=async()=>{const tx=await this.provider.getTransaction(hash);if(tx!=null){resolve(this.provider._wrapTransaction(tx,hash,blockNumber));return}this.provider._setTimeout(()=>{checkTx()},timeouts.pop()||4e3)};checkTx()})}async signTransaction(_tx){const tx=deepCopy(_tx);if(tx.from){const from=await resolveAddress(tx.from,this.provider);if(from==null||from.toLowerCase()!==this.address.toLowerCase()){return throwArgumentError("from address mismatch","transaction",_tx)}tx.from=from}else{tx.from=this.address}const hexTx=this.provider.getRpcTransaction(tx);return await this.provider.send("eth_sign_Transaction",[hexTx])}async signMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("personal_sign",[hexlify(message),this.address.toLowerCase()])}async signTypedData(domain,types,_value){const value=deepCopy(_value);const populated=await TypedDataEncoder.resolveNames(domain,types,value,async value=>{const address=await resolveAddress(value);if(address==null){return throwArgumentError("TypedData does not support null address","value",value)}return address});return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(populated.domain,types,populated.value))])}async unlock(password){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),password,null])}async _legacySignMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("eth_sign",[this.address.toLowerCase(),hexlify(message)])}}class JsonRpcApiProvider extends AbstractProvider{#options;#nextId;#payloads;#drainTimer;constructor(network,options){super(network);this.#nextId=1;this.#options=Object.assign({},defaultOptions,options||{});this.#payloads=[];this.#drainTimer=null;const staticNetwork=this._getOption("staticNetwork");if(staticNetwork&&staticNetwork!==network){throwArgumentError("staticNetwork MUST match network object","options",options)}}_getOption(key){return this.#options[key]}#scheduleDrain(){if(this.#drainTimer){return}const stallTime=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#drainTimer=setTimeout(()=>{this.#drainTimer=null;const payloads=this.#payloads;this.#payloads=[];while(payloads.length){const batch=[payloads.shift()];while(payloads.length){if(batch.length===this.#options.batchMaxCount){break}batch.push(payloads.shift());const bytes=JSON.stringify(batch.map(p=>p.payload));if(bytes.length>this.#options.batchMaxSize){payloads.unshift(batch.pop());break}}(async()=>{const payload=batch.length===1?batch[0].payload:batch.map(p=>p.payload);this.emit("debug",{action:"sendRpcPayload",payload:payload});try{const result=await this._send(payload);this.emit("debug",{action:"receiveRpcResult",result:result});for(const{resolve,reject,payload}of batch){const resp=result.filter(r=>r.id===payload.id)[0];if(resp==null){return reject(new Error("@TODO: no result"))}if("error"in resp){return reject(this.getRpcError(payload,resp))}resolve(resp.result)}}catch(error){this.emit("debug",{action:"receiveRpcError",error:error});for(const{reject}of batch){reject(error)}}})()}},stallTime)}send(method,params){const id=this.#nextId++;const promise=new Promise((resolve,reject)=>{this.#payloads.push({resolve:resolve,reject:reject,payload:{method:method,params:params,id:id,jsonrpc:"2.0"}})});this.#scheduleDrain();return promise}_send(payload){return throwError("sub-classes must override _send","UNSUPPORTED_OPERATION",{operation:"jsonRpcApiProvider._send"})}async getSigner(address=0){const accountsPromise=this.send("eth_accounts",[]);if(typeof address==="number"){const accounts=await accountsPromise;if(address>accounts.length){throw new Error("no such account")}return new JsonRpcSigner(this,accounts[address])}const[network,accounts]=await Promise.all([this.getNetwork(),accountsPromise]);address=network.formatter.address(address);for(const account of accounts){if(network.formatter.address(account)===account){return new JsonRpcSigner(this,account)}}throw new Error("invalid account")}async _detectNetwork(){const network=this._getOption("staticNetwork");if(network){return network}return Network.from(getBigInt(await this._perform({method:"chainId"})))}_getSubscriber(sub){if(sub.type==="pending"){return new FilterIdPendingSubscriber(this)}if(sub.type==="event"){return new FilterIdEventSubscriber(this,sub.filter)}if(sub.type==="orphan"&&sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("orphan")}return super._getSubscriber(sub)}getRpcTransaction(tx){const result={};["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(key=>{if(tx[key]==null){return}let dstKey=key;if(key==="gasLimit"){dstKey="gas"}result[dstKey]=toQuantity(getBigInt(tx[key],`tx.${key}`))});["from","to","data"].forEach(key=>{if(tx[key]==null){return}result[key]=hexlify(tx[key])});if(tx.accessList){result["accessList"]=accessListify(tx.accessList)}return result}getRpcRequest(req){switch(req.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getBalance":return{method:"eth_getBalance",args:[getLowerCase(req.address),req.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[getLowerCase(req.address),req.blockTag]};case"getCode":return{method:"eth_getCode",args:[getLowerCase(req.address),req.blockTag]};case"getStorageAt":return{method:"eth_getStorageAt",args:[getLowerCase(req.address),"0x"+req.position.toString(16),req.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[req.signedTransaction]};case"getBlock":if("blockTag"in req){return{method:"eth_getBlockByNumber",args:[req.blockTag,!!req.includeTransactions]}}else if("blockHash"in req){return{method:"eth_getBlockByHash",args:[req.blockHash,!!req.includeTransactions]}}break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[req.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[req.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(req.transaction),req.blockTag]};case"estimateGas":{return{method:"eth_estimateGas",args:[this.getRpcTransaction(req.transaction)]}}case"getLogs":if(req.filter&&req.filter.address!=null){if(Array.isArray(req.filter.address)){req.filter.address=req.filter.address.map(getLowerCase)}else{req.filter.address=getLowerCase(req.filter.address)}}return{method:"eth_getLogs",args:[req.filter]}}return null}getRpcError(payload,error){const{method}=payload;if(method==="eth_call"){const transaction=payload.params[0];const result=spelunkData(error);if(result){return makeError("execution reverted during JSON-RPC call","CALL_EXCEPTION",{data:result.data,transaction:transaction})}return makeError("missing revert data during JSON-RPC call","CALL_EXCEPTION",{data:"0x",transaction:transaction,info:{error:error}})}const message=JSON.stringify(spelunkMessage(error));if(method==="eth_estimateGas"){const transaction=payload.params[0];if(message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)){return makeError("cannot estimate gas; transaction may fail or may require manual gas limit","UNPREDICTABLE_GAS_LIMIT",{transaction:transaction})}}if(method==="eth_sendRawTransaction"||method==="eth_sendTransaction"){const transaction=payload.params[0];if(message.match(/insufficient funds|base fee exceeds gas limit/)){return makeError("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:transaction})}if(message.match(/nonce/)&&message.match(/too low/)){return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:transaction})}if(message.match(/replacement transaction/)&&message.match(/underpriced/)){return makeError("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:transaction})}if(message.match(/only replay-protected/)){return makeError("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:method,info:{transaction:transaction}})}}return makeError("could not coalesce error","UNKNOWN_ERROR",{error:error})}async _perform(req){if(req.method==="call"||req.method==="estimateGas"){let tx=req.transaction;if(tx&&tx.type!=null&&getBigInt(tx.type)){if(tx.maxFeePerGas==null&&tx.maxPriorityFeePerGas==null){const feeData=await this.getFeeData();if(feeData.maxFeePerGas==null&&feeData.maxPriorityFeePerGas==null){req=Object.assign({},req,{transaction:Object.assign({},tx,{type:undefined})})}}}}const request=this.getRpcRequest(req);if(request!=null){return await this.send(request.method,request.args)}return super._perform(req)}}class JsonRpcProvider extends JsonRpcApiProvider{#connect;#pollingInterval;constructor(url,network,options){if(url==null){url="http://localhost:8545"}super(network,options);if(typeof url==="string"){this.#connect=new FetchRequest(url)}else{this.#connect=url.clone()}this.#pollingInterval=4e3}async _send(payload){const request=this.#connect.clone();request.body=JSON.stringify(payload);const response=await request.send();response.assertOk();let resp=response.bodyJson;if(!Array.isArray(resp)){resp=[resp]}return resp}get pollingInterval(){return this.#pollingInterval}set pollingInterval(value){if(!Number.isInteger(value)||value<0){throw new Error("invalid interval")}this.#pollingInterval=value;this._forEachSubscriber(sub=>{if(isPollable(sub)){sub.pollingInterval=this.#pollingInterval}})}}function spelunkData(value){if(value==null){return null}if(typeof value.message==="string"&&value.message.match("reverted")&&isHexString(value.data)){return{message:value.message,data:value.data}}if(typeof value==="object"){for(const key in value){const result=spelunkData(value[key]);if(result){return result}}return null}if(typeof value==="string"){try{return spelunkData(JSON.parse(value))}catch(error){}}return null}function _spelunkMessage(value,result){if(value==null){return}if(typeof value.message==="string"){result.push(value.message)}if(typeof value==="object"){for(const key in value){_spelunkMessage(value[key],result)}}if(typeof value==="string"){try{return _spelunkMessage(JSON.parse(value),result)}catch(error){}}}function spelunkMessage(value){const result=[];_spelunkMessage(value,result);return result}const shown=new Set;function showThrottleMessage(service){if(shown.has(service)){return}shown.add(service);console.log("========= NOTICE =========");console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`);console.log("");console.log("The default API keys for each service are provided as a highly-throttled,");console.log("community resource for low-traffic projects and early prototyping.");console.log("");console.log("While your application will continue to function, we highly recommended");console.log("signing up for your own API keys to improve performance, increase your");console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");console.log("");console.log("For more details: https://docs.ethers.io/api-keys/");console.log("==========================")}const defaultApiKey$1="_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";function getHost$2(name){switch(name){case"homestead":return"eth-mainnet.alchemyapi.io";case"ropsten":return"eth-ropsten.alchemyapi.io";case"rinkeby":return"eth-rinkeby.alchemyapi.io";case"goerli":return"eth-goerli.alchemyapi.io";case"kovan":return"eth-kovan.alchemyapi.io";case"matic":return"polygon-mainnet.g.alchemy.com";case"maticmum":return"polygon-mumbai.g.alchemy.com";case"arbitrum":return"arb-mainnet.g.alchemy.com";case"arbitrum-rinkeby":return"arb-rinkeby.g.alchemy.com";case"optimism":return"opt-mainnet.g.alchemy.com";case"optimism-kovan":return"opt-kovan.g.alchemy.com"}return throwArgumentError("unsupported network","network",name)}class AlchemyProvider extends JsonRpcProvider{apiKey;constructor(_network="homestead",apiKey){const network=Network.from(_network);if(apiKey==null){apiKey=defaultApiKey$1}const request=AlchemyProvider.getRequest(network,apiKey);super(request,network,{staticNetwork:network});defineProperties(this,{apiKey:apiKey})}_getProvider(chainId){try{return new AlchemyProvider(chainId,this.apiKey)}catch(error){}return super._getProvider(chainId)}async _perform(req){if(req.method==="getTransactionResult"){const trace=await this.send("trace_transaction",[req.hash]);if(trace==null){return null}let data;let error=false;try{data=trace[0].result.output;error=trace[0].error==="Reverted"}catch(error){}if(data){if(error){throwError("an error occurred during transaction executions","CALL_EXCEPTION",{data:data})}return data}return throwError("could not parse trace result","BAD_DATA",{value:trace})}return await super._perform(req)}isCommunityResource(){return this.apiKey===defaultApiKey$1}static getRequest(network,apiKey){if(apiKey==null){apiKey=defaultApiKey$1}const request=new FetchRequest(`https:/\/${getHost$2(network.name)}/v2/${apiKey}`);request.allowGzip=true;if(apiKey===defaultApiKey$1){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("alchemy");return true}}return request}}const defaultApiKey="9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";function getHost$1(name){switch(name){case"homestead":return"rpc.ankr.com/eth";case"ropsten":return"rpc.ankr.com/eth_ropsten";case"rinkeby":return"rpc.ankr.com/eth_rinkeby";case"goerli":return"rpc.ankr.com/eth_goerli";case"matic":return"rpc.ankr.com/polygon";case"arbitrum":return"rpc.ankr.com/arbitrum"}return throwArgumentError("unsupported network","network",name)}class AnkrProvider extends JsonRpcProvider{apiKey;constructor(_network="homestead",apiKey){const network=Network.from(_network);if(apiKey==null){apiKey=defaultApiKey}const options={polling:true,staticNetwork:network};const request=AnkrProvider.getRequest(network,apiKey);super(request,network,options);defineProperties(this,{apiKey:apiKey})}_getProvider(chainId){try{return new AnkrProvider(chainId,this.apiKey)}catch(error){}return super._getProvider(chainId)}static getRequest(network,apiKey){if(apiKey==null){apiKey=defaultApiKey}const request=new FetchRequest(`https:/\/${getHost$1(network.name)}/${apiKey}`);request.allowGzip=true;if(apiKey===defaultApiKey){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("AnkrProvider");return true}}return request}isCommunityResource(){return this.apiKey===defaultApiKey}}class CloudflareProvider extends JsonRpcProvider{constructor(_network="homestead"){const network=Network.from(_network);if(network.name!=="homestead"){return throwArgumentError("unsupported network","network",_network)}super("https://cloudflare-eth.com/",network,{staticNetwork:network})}}const defaultProjectId="84842078b09946638c03157f83405213";function getHost(name){switch(name){case"homestead":return"mainnet.infura.io";case"ropsten":return"ropsten.infura.io";case"rinkeby":return"rinkeby.infura.io";case"kovan":return"kovan.infura.io";case"goerli":return"goerli.infura.io";case"matic":return"polygon-mainnet.infura.io";case"maticmum":return"polygon-mumbai.infura.io";case"optimism":return"optimism-mainnet.infura.io";case"optimism-kovan":return"optimism-kovan.infura.io";case"arbitrum":return"arbitrum-mainnet.infura.io";case"arbitrum-rinkeby":return"arbitrum-rinkeby.infura.io"}return throwArgumentError("unsupported network","network",name)}class InfuraProvider extends JsonRpcProvider{projectId;projectSecret;constructor(_network="homestead",projectId,projectSecret){const network=Network.from(_network);if(projectId==null){projectId=defaultProjectId}if(projectSecret==null){projectSecret=null}const request=InfuraProvider.getRequest(network,projectId,projectSecret);super(request,network,{staticNetwork:network});defineProperties(this,{projectId:projectId,projectSecret:projectSecret})}_getProvider(chainId){try{return new InfuraProvider(chainId,this.projectId,this.projectSecret)}catch(error){}return super._getProvider(chainId)}static getRequest(network,projectId,projectSecret){if(projectId==null){projectId=defaultProjectId}if(projectSecret==null){projectSecret=null}const request=new FetchRequest(`https:/\/${getHost(network.name)}/v3/${projectId}`);request.allowGzip=true;if(projectSecret){request.setCredentials("",projectSecret)}if(projectId===defaultProjectId){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("InfuraProvider");return true}}return request}isCommunityResource(){return this.projectId===defaultProjectId}}const IpcSocketProvider=undefined;class SocketSubscriber{#provider;#filter;get filter(){return JSON.parse(this.#filter)}#filterId;#paused;#emitPromise;constructor(provider,filter){this.#provider=provider;this.#filter=JSON.stringify(filter);this.#filterId=null;this.#paused=null;this.#emitPromise=null}start(){this.#filterId=this.#provider.send("eth_subscribe",this.filter).then(filterId=>{this.#provider._register(filterId,this);return filterId})}stop(){this.#filterId.then(filterId=>{this.#provider.send("eth_unsubscribe",[filterId])});this.#filterId=null}pause(dropWhilePaused){if(!dropWhilePaused){throwError("preserve logs while paused not supported by SocketSubscriber yet","UNSUPPORTED_OPERATION",{operation:"pause(false)"})}this.#paused=!!dropWhilePaused}resume(){this.#paused=null}_handleMessage(message){if(this.#filterId==null){return}if(this.#paused===null){let emitPromise=this.#emitPromise;if(emitPromise==null){emitPromise=this._emit(this.#provider,message)}else{emitPromise=emitPromise.then(async()=>{await this._emit(this.#provider,message)})}this.#emitPromise=emitPromise.then(()=>{if(this.#emitPromise===emitPromise){this.#emitPromise=null}})}}async _emit(provider,message){throw new Error("sub-classes must implemente this; _emit")}}class SocketBlockSubscriber extends SocketSubscriber{constructor(provider){super(provider,["newHeads"])}async _emit(provider,message){provider.emit("block",parseInt(message.number))}}class SocketPendingSubscriber extends SocketSubscriber{constructor(provider){super(provider,["newPendingTransactions"])}async _emit(provider,message){provider.emit("pending",message)}}class SocketEventSubscriber extends SocketSubscriber{#logFilter;get logFilter(){return JSON.parse(this.#logFilter)}#formatter;constructor(provider,filter){super(provider,["logs",filter]);this.#logFilter=JSON.stringify(filter);this.#formatter=provider.getNetwork().then(network=>network.formatter)}async _emit(provider,message){const formatter=await this.#formatter;provider.emit(this.#logFilter,formatter.log(message,provider))}}class SocketProvider extends JsonRpcApiProvider{#callbacks;#ready;#subs;#pending;constructor(network){super(network,{batchMaxCount:1});this.#callbacks=new Map;this.#ready=false;this.#subs=new Map;this.#pending=new Map}_getSubscriber(sub){switch(sub.type){case"close":return new UnmanagedSubscriber("close");case"block":return new SocketBlockSubscriber(this);case"pending":return new SocketPendingSubscriber(this);case"event":return new SocketEventSubscriber(this,sub.filter);case"orphan":if(sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("drop-log")}}return super._getSubscriber(sub)}_register(filterId,subscriber){this.#subs.set(filterId,subscriber);const pending=this.#pending.get(filterId);if(pending){for(const message of pending){subscriber._handleMessage(message)}this.#pending.delete(filterId)}}async _send(payload){assertArgument(!Array.isArray(payload),"WebSocket does not support batch send","payload",payload);const promise=new Promise((resolve,reject)=>{this.#callbacks.set(payload.id,{payload:payload,resolve:resolve,reject:reject})});if(this.#ready){await this._write(JSON.stringify(payload))}return[await promise]}async _start(){if(this.#ready){return}this.#ready=true;for(const{payload}of this.#callbacks.values()){await this._write(JSON.stringify(payload))}}async _processMessage(message){const result=JSON.parse(message);if("id"in result){const callback=this.#callbacks.get(result.id);if(callback==null){console.log("Weird... Response for not a thing we sent");return}this.#callbacks.delete(result.id);if("error"in result){const{message,code,data}=result.error;const error=makeError(message||"unkonwn error","SERVER_ERROR",{request:`ws:${JSON.stringify(callback.payload)}`,info:{code:code,data:data}});callback.reject(error)}else{callback.resolve(result.result)}}else if(result.method==="eth_subscription"){const filterId=result.params.subscription;const subscriber=this.#subs.get(filterId);if(subscriber){subscriber._handleMessage(result.params.result)}else{let pending=this.#pending.get(filterId);if(pending==null){pending=[];this.#pending.set(filterId,pending)}pending.push(result.params.result)}}}async _write(message){throw new Error("sub-classes must override this")}}function getGlobal(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const _WebSocket=getGlobal().WebSocket;class WebSocketProvider extends SocketProvider{url;#websocket;get websocket(){return this.#websocket}constructor(url,network){super(network);if(typeof url==="string"){this.#websocket=new _WebSocket(url)}else{this.#websocket=url}this.websocket.onopen=()=>{this._start()};this.websocket.onmessage=message=>{this._processMessage(message.data)}}async _write(message){this.websocket.send(message)}}class EventLog extends Log{interface;fragment;args;constructor(log,iface,fragment){super(log,log.provider);const args=iface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,interface:iface})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class ContractTransactionReceipt extends TransactionReceipt{#interface;constructor(iface,provider,tx){super(tx,provider);this.#interface=iface}get logs(){return super.logs.map(log=>{const fragment=log.topics.length?this.#interface.getEvent(log.topics[0]):null;if(fragment){return new EventLog(log,this.#interface,fragment)}else{return log}})}}class ContractTransactionResponse extends TransactionResponse{#interface;constructor(iface,provider,tx){super(tx,provider);this.#interface=iface}async wait(confirms){const receipt=await super.wait();if(receipt==null){return null}return new ContractTransactionReceipt(this.#interface,this.provider,receipt)}}class ContractEventPayload extends EventPayload{fragment;log;args;constructor(contract,listener,filter,fragment,_log){super(contract,listener,filter);const log=new EventLog(_log,contract.interface,fragment);const args=contract.interface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,log:log})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}function canCall(value){return value&&typeof value.call==="function"}function canEstimate(value){return value&&typeof value.estimateGas==="function"}function canResolve(value){return value&&typeof value.resolveName==="function"}function canSend(value){return value&&typeof value.sendTransaction==="function"}function concisify(items){items=Array.from(new Set(items).values());items.sort();return items}class PreparedTopicFilter{#filter;fragment;constructor(contract,fragment,args){defineProperties(this,{fragment:fragment});if(fragment.inputs.length<args.length){throw new Error("too many arguments")}const runner=getRunner(contract.runner,"resolveName");const resolver=canResolve(runner)?runner:null;this.#filter=async function(){const resolvedArgs=await Promise.all(fragment.inputs.map((param,index)=>{return param.walkAsync(args[index],(type,value)=>{if(type==="address"){return resolveAddress(value,resolver)}return value})}));return contract.interface.encodeFilterTopics(fragment,resolvedArgs)}()}getTopicFilter(){return this.#filter}}function _WrappedMethodBase(){return Function}function getRunner(value,feature){if(value==null){return null}if(typeof value[feature]==="function"){return value}if(value.provider&&typeof value.provider[feature]==="function"){return value.provider}return null}function getProvider(value){if(value==null){return null}return value.provider||null}async function copyOverrides(arg){const overrides=copyRequest$1(Typed.dereference(arg,"overrides"));if(overrides.to){throwArgumentError("cannot override to","overrides.to",overrides.to)}else if(overrides.data){throwArgumentError("cannot override data","overrides.data",overrides.data)}if(overrides.from){overrides.from=await resolveAddress(overrides.from)}return overrides}async function resolveArgs(_runner,inputs,args){const runner=getRunner(_runner,"resolveName");const resolver=canResolve(runner)?runner:null;return await Promise.all(inputs.map((param,index)=>{return param.walkAsync(args[index],(type,value)=>{if(type==="address"){return resolveAddress(value,resolver)}return value})}))}class WrappedMethod extends _WrappedMethodBase(){name="";_contract;_key;constructor(contract,key){super();defineProperties(this,{name:contract.interface.getFunctionName(key),_contract:contract,_key:key});const proxy=new Proxy(this,{apply:async(target,thisArg,args)=>{const fragment=target.getFragment(...args);if(fragment.constant){return await target.staticCall(...args)}return await target.send(...args)}});return proxy}get fragment(){return this._contract.interface.getFunction(this._key)}getFragment(...args){return this._contract.interface.getFunction(this._key,args)}async populateTransaction(...args){const fragment=this.getFragment(...args);let overrides={};if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop())}if(fragment.inputs.length!==args.length){throw new Error("internal error: fragment inputs doesn't match arguments; should not happen")}const resolvedArgs=await resolveArgs(this._contract.runner,fragment.inputs,args);return Object.assign({},overrides,await resolveProperties({to:this._contract.getAddress(),data:this._contract.interface.encodeFunctionData(fragment,resolvedArgs)}))}async staticCall(...args){const result=await this.staticCallResult(...args);if(result.length===1){return result[0]}return result}async send(...args){const runner=this._contract.runner;if(!canSend(runner)){return throwError("contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"})}const tx=await runner.sendTransaction(await this.populateTransaction(...args));const provider=getProvider(this._contract.runner);return new ContractTransactionResponse(this._contract.interface,provider,tx)}async estimateGas(...args){const runner=getRunner(this._contract.runner,"estimateGas");if(!canEstimate(runner)){return throwError("contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"})}return await runner.estimateGas(await this.populateTransaction(...args))}async staticCallResult(...args){const runner=getRunner(this._contract.runner,"call");if(!canCall(runner)){return throwError("contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"})}const fragment=this.getFragment(...args);const tx=await this.populateTransaction(...args);let result="0x";try{result=await runner.call(tx)}catch(error){if(isCallException(error)){throw this._contract.interface.makeError(fragment,error.data,tx)}throw error}return this._contract.interface.decodeFunctionResult(fragment,result)}}function _WrappedEventBase(){return Function}class WrappedEvent extends _WrappedEventBase(){name="";_contract;_key;constructor(contract,key){super();defineProperties(this,{name:contract.interface.getEventName(key),_contract:contract,_key:key});return new Proxy(this,{apply:async(target,thisArg,args)=>{return new PreparedTopicFilter(contract,target.getFragment(...args),args)}})}get fragment(){return this._contract.interface.getEvent(this._key)}getFragment(...args){return this._contract.interface.getEvent(this._key,args)}}const internal=Symbol.for("_ethersInternal_contract");const internalValues=new WeakMap;function setInternal(contract,values){internalValues.set(contract[internal],values)}function getInternal(contract){return internalValues.get(contract[internal])}function isDeferred(value){return value&&typeof value==="object"&&"getTopicFilter"in value&&typeof value.getTopicFilter==="function"&&value.fragment}async function getSubTag(contract,event){let fragment;let topics;if(Array.isArray(event)){fragment=contract.interface.getEvent(event[0]);topics=event}else if(typeof event==="string"){fragment=contract.interface.getEvent(event);topics=[fragment.topicHash]}else if(isDeferred(event)){fragment=event.fragment;topics=await event.getTopicFilter()}else if("fragment"in event){fragment=event.fragment;topics=[fragment.topicHash]}else{console.log(event);throw new Error("TODO")}topics=topics.map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}return t.toLowerCase()});const tag=topics.map(t=>{if(t==null){return"null"}if(Array.isArray(t)){return t.join("|")}return t}).join("&");return{fragment:fragment,tag:tag,topics:topics}}async function hasSub(contract,event){const{subs}=getInternal(contract);return subs.get((await getSubTag(contract,event)).tag)||null}async function getSub(contract,event){const provider=getProvider(contract.runner);if(!provider){return throwError("contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:"on"})}const{fragment,tag,topics}=await getSubTag(contract,event);const{addr,subs}=getInternal(contract);let sub=subs.get(tag);if(!sub){const address=addr?addr:contract;const filter={address:address,topics:topics};const listener=log=>{const payload=new ContractEventPayload(contract,null,event,fragment,log);emit(contract,event,payload.args,payload)};let started=false;const start=()=>{if(started){return}provider.on(filter,listener);started=true};const stop=()=>{if(!started){return}provider.off(filter,listener);started=false};sub={tag:tag,listeners:[],start:start,stop:stop};subs.set(tag,sub)}return sub}let lastEmit=Promise.resolve();async function _emit(contract,event,args,payload){await lastEmit;const sub=await hasSub(contract,event);if(!sub){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const passArgs=args.slice();if(payload){passArgs.push(new ContractEventPayload(contract,once?null:listener,event,payload.fragment,payload.log))}try{listener.call(contract,...passArgs)}catch(error){}return!once});return count>0}async function emit(contract,event,args,payload){try{await lastEmit}catch(error){}const resultPromise=_emit(contract,event,args,payload);lastEmit=resultPromise;return await resultPromise}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];constructor(target,abi,runner=null,_deployTx){const iface=Interface.from(abi);defineProperties(this,{target:target,runner:runner,interface:iface});Object.defineProperty(this,internal,{value:{}});let addrPromise;let addr=null;let deployTx=null;if(_deployTx){const provider=getProvider(runner);deployTx=new ContractTransactionResponse(this.interface,provider,_deployTx)}let subs=new Map;if(typeof target==="string"){if(isHexString(target)){addr=target;addrPromise=Promise.resolve(target)}else{const resolver=getRunner(runner,"resolveName");if(!canResolve(resolver)){throw makeError("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"})}addrPromise=resolver.resolveName(target).then(addr=>{if(addr==null){throw new Error("TODO")}getInternal(this).addr=addr;return addr})}}else{addrPromise=target.getAddress().then(addr=>{if(addr==null){throw new Error("TODO")}getInternal(this).addr=addr;return addr})}setInternal(this,{addrPromise:addrPromise,addr:addr,deployTx:deployTx,subs:subs});const filters=new Proxy({},{get:(target,_prop,receiver)=>{if(passProperties.indexOf(_prop)>=0){return Reflect.get(target,_prop,receiver)}const prop=String(_prop);const result=this.getEvent(prop);if(result){return result}throw new Error(`unknown contract event: ${prop}`)}});defineProperties(this,{filters:filters});return new Proxy(this,{get:(target,_prop,receiver)=>{if(_prop in target||passProperties.indexOf(_prop)>=0){return Reflect.get(target,_prop,receiver)}const prop=String(_prop);const result=target.getFunction(prop);if(result){return result}throw new Error(`unknown contract method: ${prop}`)}})}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const provider=getProvider(this.runner);if(!provider){return throwError("runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"})}const code=await provider.getCode(await this.getAddress());if(code==="0x"){return null}return code}async waitForDeployment(){const deployTx=this.deploymentTransaction();if(deployTx){await deployTx.wait();return this}const code=await this.getDeployedCode();if(code!=null){return this}const provider=getProvider(this.runner);if(provider==null){return throwError("contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"})}return new Promise((resolve,reject)=>{const checkCode=async()=>{try{const code=await this.getDeployedCode();if(code!=null){return resolve(this)}provider.once("block",checkCode)}catch(error){reject(error)}};checkCode()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(key){if(typeof key!=="string"){key=key.format()}return new WrappedMethod(this,key)}getEvent(key){if(typeof key!=="string"){key=key.format()}return new WrappedEvent(this,key)}async queryTransaction(hash){throw new Error("@TODO")}async queryFilter(event,fromBlock=0,toBlock="latest"){const{addr,addrPromise}=getInternal(this);const address=addr?addr:await addrPromise;const{fragment,topics}=await getSubTag(this,event);const filter={address:address,topics:topics,fromBlock:fromBlock,toBlock:toBlock};const provider=getProvider(this.runner);if(!provider){return throwError("contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"})}return(await provider.getLogs(filter)).map(log=>{return new EventLog(log,this.interface,fragment)})}async on(event,listener){const sub=await getSub(this,event);sub.listeners.push({listener:listener,once:false});sub.start();return this}async once(event,listener){const sub=await getSub(this,event);sub.listeners.push({listener:listener,once:true});sub.start();return this}async emit(event,...args){return await emit(this,event,args,null)}async listenerCount(event){if(event){const sub=await hasSub(this,event);if(!sub){return 0}return sub.listeners.length}const{subs}=getInternal(this);let total=0;for(const{listeners}of subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}const{subs}=getInternal(this);let result=[];for(const{listeners}of subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener){const sub=await hasSub(this,event);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(listener==null||sub.listeners.length===0){sub.stop();getInternal(this).subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return this}sub.stop();getInternal(this).subs.delete(sub.tag)}else{const{subs}=getInternal(this);for(const{tag,stop}of subs.values()){stop();subs.delete(tag)}}return this}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return await this.off(event,listener)}static buildClass(abi){class CustomContract extends BaseContract{constructor(address,runner=null){super(address,abi,runner)}}return CustomContract}static from(target,abi,runner=null){const contract=new this(target,abi,runner);return contract}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}class ContractFactory{interface;bytecode;runner;constructor(abi,bytecode,runner){const iface=Interface.from(abi);if(bytecode instanceof Uint8Array){bytecode=hexlify(getBytes(bytecode))}else{if(typeof bytecode==="object"){bytecode=bytecode.object}if(bytecode.substring(0,2)!=="0x"){bytecode="0x"+bytecode}bytecode=hexlify(getBytes(bytecode))}defineProperties(this,{bytecode:bytecode,interface:iface,runner:runner||null})}async getDeployTransaction(...args){let overrides={};const fragment=this.interface.deploy;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop())}if(fragment.inputs.length!==args.length){throw new Error("incorrect number of arguments to constructor")}const resolvedArgs=await resolveArgs(this.runner,fragment.inputs,args);const data=concat([this.bytecode,this.interface.encodeDeploy(resolvedArgs)]);return Object.assign({},overrides,{data:data})}async deploy(...args){const tx=await this.getDeployTransaction(...args);if(!this.runner||typeof this.runner.sendTransaction!=="function"){return throwError("factory runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"})}const sentTx=await this.runner.sendTransaction(tx);const address=getCreateAddress(sentTx);return new BaseContract(address,this.interface,this.runner,sentTx)}connect(runner){return new ContractFactory(this.interface,this.bytecode,runner)}static fromSolidity(output,runner){if(output==null){throwArgumentError("bad compiler output","output",output)}if(typeof output==="string"){output=JSON.parse(output)}const abi=output.abi;let bytecode="";if(output.bytecode){bytecode=output.bytecode}else if(output.evm&&output.evm.bytecode){bytecode=output.evm.bytecode}return new this(abi,bytecode,runner)}}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(mnemonic){return mnemonic.toLowerCase().split(/ +/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();if(index<0||index>=words.length){throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return this.#loadWords().indexOf(word)}}const words="0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-Eg<tEm|Eph<tEvat%I>Se0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-P<dPe@Pi*Pla(Po'P*[T&dTra0EEbrow:Br-CeCultyDeIntI`~L'MeMilyMousNNcyNtasyRmSh]TT$Th TigueUltV%.e3Atu*Bru?yD $EEdElMa!N)/iv$T^V W3B Ct]EldGu*LeLmLt N$NdNeNg NishReRmR,Sc$ShTT}[X_gAmeAshAtAv%EeIghtIpOatO{O%Ow UidUshY_mCusGIlLd~owOdOtR)Re,R+tRkRtu}RumRw?dSsil/ UndX_gi!AmeEqu|EshI&dIn+OgOntO,OwnOz&U.2ElNNnyRna)RyTu*:D+tInLaxy~ yMePRa+Rba+Rd&Rl-Rm|SSpTeTh U+Ze3N $NiusN*Nt!Nu(e/u*2O,0AntFtGg!Ng RaffeRlVe_dAn)A*A[IdeImp'ObeOomOryO=OwUe_tDde[LdOdO'RillaSpelSsipV nWn_bA)A(AntApeA[Av.yEatE&IdIefItOc yOupOwUnt_rdE[IdeIltIt?N3M:B.IrLfMm M, NdPpyRb%RdRshR=,TVeWkZ?d3AdAl`ArtAvyD+hogIght~oLmetLpNRo3Dd&Gh~NtPRe/%y5BbyCkeyLdLeLiday~owMeNeyOdPeRnRr%R'Sp.$/TelUrV 5BGeM<Mb!M%Nd*dNgryNtRd!RryRtSb<d3Brid:1EOn0EaEntifyLe2N%e4LLeg$L}[0A+Ita>M&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryF<tFl-tF%mHa!H .Iti$Je@JuryMa>N Noc|PutQuiryS<eSe@SideSpi*/$lTa@T e,ToVe,V.eVol=3On0L<dOla>Sue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurE<Tob 0Or1FF Fi)T&2L1Ay0DI=Ymp-0It0CeEI#L(eLy1EnEraIn]Po'T]1An+B.Ch?dD D(?yG<I|Ig($Ph<0Tr-h0H 0Tdo%T TputTside0AlEnEr0NN 0Yg&0/ 0O}:CtDd!GeIrLa)LmNdaNelN-N` P RadeR|RkRrotRtySsT^ThTi|TrolTt nU'VeYm|3A)AnutArAs<tL-<NN$tyNcilOp!Pp Rfe@Rm.Rs#T2O}OtoRa'Ys-$0AnoCn-Ctu*E)GGe#~LotNkO} Pe/olT^Zza_)A}tA,-A>AyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO";const checksum="0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60";class LangEn extends WordlistOwl{constructor(){super("en",words,checksum)}}const langEn=new LangEn;function getUpperMask(bits){return(1<<bits)-1<<8-bits&255}function getLowerMask(bits){return(1<<bits)-1&255}function mnemonicToEntropy(mnemonic,wordlist=langEn){assertNormalize("NFKD");if(wordlist==null){wordlist=langEn}const words=wordlist.split(mnemonic);if(words.length%3!==0||words.length<12||words.length>24){throwArgumentError("invalid mnemonic length","mnemonic","[ REDACTED ]")}const entropy=new Uint8Array(Math.ceil(11*words.length/8));let offset=0;for(let i=0;i<words.length;i++){let index=wordlist.getWordIndex(words[i].normalize("NFKD"));if(index===-1){throwArgumentError(`invalid mnemonic word at index ${i}`,"mnemonic","[ REDACTED ]")}for(let bit=0;bit<11;bit++){if(index&1<<10-bit){entropy[offset>>3]|=1<<7-offset%8}offset++}}const entropyBits=32*words.length/3;const checksumBits=words.length/3;const checksumMask=getUpperMask(checksumBits);const checksum=getBytes(sha256(entropy.slice(0,entropyBits/8)))[0]&checksumMask;if(checksum!==(entropy[entropy.length-1]&checksumMask)){throwArgumentError("invalid mnemonic checksum","mnemonic","[ REDACTED ]")}return hexlify(entropy.slice(0,entropyBits/8))}function entropyToMnemonic(entropy,wordlist=langEn){if(entropy.length%4||entropy.length<16||entropy.length>32){throwArgumentError("invalid entropy size","entropy","[ REDACTED ]")}if(wordlist==null){wordlist=langEn}const indices=[0];let remainingBits=11;for(let i=0;i<entropy.length;i++){if(remainingBits>8){indices[indices.length-1]<<=8;indices[indices.length-1]|=entropy[i];remainingBits-=8}else{indices[indices.length-1]<<=remainingBits;indices[indices.length-1]|=entropy[i]>>8-remainingBits;indices.push(entropy[i]&getLowerMask(8-remainingBits));remainingBits+=3}}const checksumBits=entropy.length/4;const checksum=parseInt(sha256(entropy).substring(2,4),16)&getUpperMask(checksumBits);indices[indices.length-1]<<=checksumBits;indices[indices.length-1]|=checksum>>8-checksumBits;return wordlist.join(indices.map(index=>wordlist.getWord(index)))}const _guard$1={};class Mnemonic{phrase;password;wordlist;entropy;constructor(guard,entropy,phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=langEn}assertPrivate(guard,_guard$1,"Mnemonic");defineProperties(this,{phrase:phrase,password:password,wordlist:wordlist,entropy:entropy})}computeSeed(){const salt=toUtf8Bytes("mnemonic"+this.password,"NFKD");return pbkdf2(toUtf8Bytes(this.phrase,"NFKD"),salt,2048,64,"sha512")}static fromPhrase(phrase,password,wordlist){const entropy=mnemonicToEntropy(phrase,wordlist);phrase=entropyToMnemonic(getBytes(entropy),wordlist);return new Mnemonic(_guard$1,entropy,phrase,password,wordlist)}static fromEntropy(_entropy,password,wordlist){const entropy=getBytes(_entropy,"entropy");const phrase=entropyToMnemonic(entropy,wordlist);return new Mnemonic(_guard$1,hexlify(entropy),phrase,password,wordlist)}static entropyToPhrase(_entropy,wordlist){const entropy=getBytes(_entropy,"entropy");return entropyToMnemonic(entropy,wordlist)}static phraseToEntropy(phrase,wordlist){return mnemonicToEntropy(phrase,wordlist)}static isValidMnemonic(phrase,wordlist){try{mnemonicToEntropy(phrase,wordlist);return true}catch(error){}return false}}class BaseWallet extends AbstractSigner{address;#signingKey;constructor(privateKey,provider){super(provider);this.#signingKey=privateKey;const address=computeAddress(this.signingKey.publicKey);defineProperties(this,{address:address})}get signingKey(){return this.#signingKey}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(provider){return new BaseWallet(this.#signingKey,provider)}async signTransaction(_tx){const tx=Object.assign({},_tx,await resolveProperties({to:_tx.to?resolveAddress(_tx.to,this.provider):undefined,from:_tx.from?resolveAddress(_tx.from,this.provider):undefined}));if(tx.from!=null){if(getAddress(tx.from)!==this.address){throwArgumentError("transaction from address mismatch","tx.from",_tx.from)}delete tx.from}const btx=Transaction.from(tx);btx.signature=this.signingKey.sign(btx.unsignedHash);return btx.serialized}async signMessage(message){return this.signingKey.sign(hashMessage(message)).serialized}async signTypedData(domain,types,value){const populated=await TypedDataEncoder.resolveNames(domain,types,value,async name=>{if(this.provider==null){return throwError("cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:name}})}const address=await this.provider.resolveName(name);if(address==null){return throwError("unconfigured ENS name","UNCONFIGURED_NAME",{value:name})}return address});return this.signingKey.sign(TypedDataEncoder.hash(populated.domain,types,populated.value)).serialized}}const defaultPath$1="m/44'/60'/0'/0/0";const MasterSecret=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]);const HardenedBit=2147483648;const N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const Nibbles="0123456789abcdef";function zpad$1(value,length){let result="";while(value){result=Nibbles[value%16]+result;value=Math.trunc(value/16)}while(result.length<length*2){result="0"+result}return"0x"+result}function encodeBase58Check(_value){const value=getBytes(_value);const check=dataSlice(sha256(sha256(value)),0,4);const bytes=concat([value,check]);return encodeBase58(bytes)}const _guard={};function ser_I(index,chainCode,publicKey,privateKey){const data=new Uint8Array(37);if(index&HardenedBit){if(privateKey==null){return throwError("cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"})}data.set(getBytes(privateKey),1)}else{data.set(getBytes(publicKey))}for(let i=24;i>=0;i-=8){data[33+(i>>3)]=index>>24-i&255}const I=getBytes(computeHmac("sha512",chainCode,data));return{IL:I.slice(0,32),IR:I.slice(32)}}function derivePath(node,path){const components=path.split("/");if(components.length===0||components[0]==="m"&&node.depth!==0){throw new Error("invalid path - "+path)}if(components[0]==="m"){components.shift()}let result=node;for(let i=0;i<components.length;i++){const component=components[i];if(component.match(/^[0-9]+'$/)){const index=parseInt(component.substring(0,component.length-1));if(index>=HardenedBit){throw new Error("invalid path index - "+component)}result=result.deriveChild(HardenedBit+index)}else if(component.match(/^[0-9]+$/)){const index=parseInt(component);if(index>=HardenedBit){throw new Error("invalid path index - "+component)}result=result.deriveChild(index)}else{throw new Error("invalid path component - "+component)}}return result}class HDNodeWallet extends BaseWallet{publicKey;fingerprint;parentFingerprint;mnemonic;chainCode;path;index;depth;constructor(guard,signingKey,parentFingerprint,chainCode,path,index,depth,mnemonic,provider){super(signingKey,provider);assertPrivate(guard,_guard,"HDNodeWallet");defineProperties(this,{publicKey:signingKey.compressedPublicKey});const fingerprint=dataSlice(ripemd160(sha256(this.publicKey)),0,4);defineProperties(this,{parentFingerprint:parentFingerprint,fingerprint:fingerprint,chainCode:chainCode,path:path,index:index,depth:depth});defineProperties(this,{mnemonic:mnemonic})}connect(provider){return new HDNodeWallet(_guard,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,provider)}get extendedKey(){if(this.depth>=256){throw new Error("Depth too large!")}return encodeBase58Check(concat(["0x0488ADE4",zpad$1(this.depth,1),this.parentFingerprint,zpad$1(this.index,4),this.chainCode,concat(["0x00",this.privateKey])]))}hasPath(){return this.path!=null}neuter(){return new HDNodeVoidWallet(_guard,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(_index){const index=getNumber(_index,"index");if(index>4294967295){throw new Error("invalid index - "+String(index))}let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,this.privateKey);const ki=new SigningKey(toHex((toBigInt(IL)+BigInt(this.privateKey))%N,32));return new HDNodeWallet(_guard,ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.mnemonic,this.provider)}derivePath(path){return derivePath(this,path)}static#fromSeed(_seed,mnemonic){const seed=getBytes(_seed,"seed");if(seed.length<16||seed.length>64){throw new Error("invalid seed")}const I=getBytes(computeHmac("sha512",MasterSecret,seed));const signingKey=new SigningKey(hexlify(I.slice(0,32)));return new HDNodeWallet(_guard,signingKey,"0x00000000",hexlify(I.slice(32)),"m",0,0,mnemonic,null)}static fromSeed(seed){return HDNodeWallet.#fromSeed(seed,null)}static fromPhrase(phrase,password="",path=defaultPath$1,wordlist=langEn){if(!path){path=defaultPath$1}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromMnemonic(mnemonic,path=defaultPath$1){if(!path){path=defaultPath$1}return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromExtendedKey(extendedKey){const bytes=getBytes(decodeBase58(extendedKey));if(bytes.length!==82||encodeBase58Check(bytes.slice(0,78))!==extendedKey){throwArgumentError("invalid extended key","extendedKey","[ REDACTED ]")}const depth=bytes[4];const parentFingerprint=hexlify(bytes.slice(5,9));const index=parseInt(hexlify(bytes.slice(9,13)).substring(2),16);const chainCode=hexlify(bytes.slice(13,45));const key=bytes.slice(45,78);switch(hexlify(bytes.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const publicKey=hexlify(key);return new HDNodeVoidWallet(_guard,computeAddress(publicKey),publicKey,parentFingerprint,chainCode,null,index,depth,null)}case"0x0488ade4":case"0x04358394 ":if(key[0]!==0){break}return new HDNodeWallet(_guard,new SigningKey(key.slice(1)),parentFingerprint,chainCode,null,index,depth,null,null)}return throwArgumentError("invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(password="",path=defaultPath$1,wordlist=langEn){if(!path){path=defaultPath$1}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}}class HDNodeVoidWallet extends VoidSigner{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(guard,address,publicKey,parentFingerprint,chainCode,path,index,depth,provider){super(address,provider);assertPrivate(guard,_guard,"HDNodeVoidWallet");defineProperties(this,{publicKey:publicKey});const fingerprint=dataSlice(ripemd160(sha256(publicKey)),0,4);defineProperties(this,{publicKey:publicKey,fingerprint:fingerprint,parentFingerprint:parentFingerprint,chainCode:chainCode,path:path,index:index,depth:depth})}connect(provider){return new HDNodeVoidWallet(_guard,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,provider)}get extendedKey(){if(this.depth>=256){throw new Error("Depth too large!")}return encodeBase58Check(concat(["0x0488B21E",zpad$1(this.depth,1),this.parentFingerprint,zpad$1(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return this.path!=null}deriveChild(_index){const index=getNumber(_index,"index");if(index>4294967295){throw new Error("invalid index - "+String(index))}let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,null);const Ki=SigningKey._addPoints(IL,this.publicKey,true);const address=computeAddress(Ki);return new HDNodeVoidWallet(_guard,address,Ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.provider)}derivePath(path){return derivePath(this,path)}}class HDNodeWalletManager{#root;constructor(phrase,password="",path="m/44'/60'/0'/0",locale=langEn){this.#root=HDNodeWallet.fromPhrase(phrase,password,path,locale)}getSigner(index){return this.#root.deriveChild(index==null?0:index)}}function getAccountPath(_index){const index=getNumber(_index,"index");if(index<0||index>=HardenedBit){throwArgumentError("invalid account index","index",index)}return`m/44'/60'/${index}'/0/0`}var __classPrivateFieldSet$4=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$4=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _AES_key,_AES_Kd,_AES_Ke;const numberOfRounds={16:10,24:12,32:14};const rcon=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145];const S=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22];const Si=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125];const T1=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986];const T2=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766];const T3=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126];const T4=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436];const T5=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890];const T6=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935];const T7=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600];const T8=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480];const U1=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795];const U2=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855];const U3=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150];const U4=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function convertToInt32(bytes){const result=[];for(let i=0;i<bytes.length;i+=4){result.push(bytes[i]<<24|bytes[i+1]<<16|bytes[i+2]<<8|bytes[i+3])}return result}class AES{constructor(key){_AES_key.set(this,void 0);_AES_Kd.set(this,void 0);_AES_Ke.set(this,void 0);if(!(this instanceof AES)){throw Error("AES must be instanitated with `new`")}__classPrivateFieldSet$4(this,_AES_key,new Uint8Array(key),"f");const rounds=numberOfRounds[this.key.length];if(rounds==null){throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)")}__classPrivateFieldSet$4(this,_AES_Ke,[],"f");__classPrivateFieldSet$4(this,_AES_Kd,[],"f");for(let i=0;i<=rounds;i++){__classPrivateFieldGet$4(this,_AES_Ke,"f").push([0,0,0,0]);__classPrivateFieldGet$4(this,_AES_Kd,"f").push([0,0,0,0])}const roundKeyCount=(rounds+1)*4;const KC=this.key.length/4;const tk=convertToInt32(this.key);let index;for(let i=0;i<KC;i++){index=i>>2;__classPrivateFieldGet$4(this,_AES_Ke,"f")[index][i%4]=tk[i];__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds-index][i%4]=tk[i]}let rconpointer=0;let t=KC,tt;while(t<roundKeyCount){tt=tk[KC-1];tk[0]^=S[tt>>16&255]<<24^S[tt>>8&255]<<16^S[tt&255]<<8^S[tt>>24&255]^rcon[rconpointer]<<24;rconpointer+=1;if(KC!=8){for(let i=1;i<KC;i++){tk[i]^=tk[i-1]}}else{for(let i=1;i<KC/2;i++){tk[i]^=tk[i-1]}tt=tk[KC/2-1];tk[KC/2]^=S[tt&255]^S[tt>>8&255]<<8^S[tt>>16&255]<<16^S[tt>>24&255]<<24;for(let i=KC/2+1;i<KC;i++){tk[i]^=tk[i-1]}}let i=0,r,c;while(i<KC&&t<roundKeyCount){r=t>>2;c=t%4;__classPrivateFieldGet$4(this,_AES_Ke,"f")[r][c]=tk[i];__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds-r][c]=tk[i++];t++}}for(let r=1;r<rounds;r++){for(let c=0;c<4;c++){tt=__classPrivateFieldGet$4(this,_AES_Kd,"f")[r][c];__classPrivateFieldGet$4(this,_AES_Kd,"f")[r][c]=U1[tt>>24&255]^U2[tt>>16&255]^U3[tt>>8&255]^U4[tt&255]}}}get key(){return __classPrivateFieldGet$4(this,_AES_key,"f").slice()}encrypt(plaintext){if(plaintext.length!=16){throw new TypeError("invalid plaintext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$4(this,_AES_Ke,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(plaintext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$4(this,_AES_Ke,"f")[0][i]}for(let r=1;r<rounds;r++){for(let i=0;i<4;i++){a[i]=T1[t[i]>>24&255]^T2[t[(i+1)%4]>>16&255]^T3[t[(i+2)%4]>>8&255]^T4[t[(i+3)%4]&255]^__classPrivateFieldGet$4(this,_AES_Ke,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$4(this,_AES_Ke,"f")[rounds][i];result[4*i]=(S[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(S[t[(i+1)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(S[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(S[t[(i+3)%4]&255]^tt)&255}return result}decrypt(ciphertext){if(ciphertext.length!=16){throw new TypeError("invalid ciphertext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$4(this,_AES_Kd,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(ciphertext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$4(this,_AES_Kd,"f")[0][i]}for(let r=1;r<rounds;r++){for(let i=0;i<4;i++){a[i]=T5[t[i]>>24&255]^T6[t[(i+3)%4]>>16&255]^T7[t[(i+2)%4]>>8&255]^T8[t[(i+1)%4]&255]^__classPrivateFieldGet$4(this,_AES_Kd,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds][i];result[4*i]=(Si[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(Si[t[(i+3)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(Si[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(Si[t[(i+1)%4]&255]^tt)&255}return result}}_AES_key=new WeakMap,_AES_Kd=new WeakMap,_AES_Ke=new WeakMap;class ModeOfOperation{constructor(name,key,cls){if(cls&&!(this instanceof cls)){throw new Error(`${name} must be instantiated with "new"`)}Object.defineProperties(this,{aes:{enumerable:true,value:new AES(key)},name:{enumerable:true,value:name}})}}var __classPrivateFieldSet$3=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$3=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CBC_iv,_CBC_lastBlock;class CBC extends ModeOfOperation{constructor(key,iv){super("ECC",key,CBC);_CBC_iv.set(this,void 0);_CBC_lastBlock.set(this,void 0);if(iv){if(iv.length%16){throw new TypeError("invalid iv size (must be 16 bytes)")}__classPrivateFieldSet$3(this,_CBC_iv,new Uint8Array(iv),"f")}else{__classPrivateFieldSet$3(this,_CBC_iv,new Uint8Array(16),"f")}__classPrivateFieldSet$3(this,_CBC_lastBlock,this.iv,"f")}get iv(){return new Uint8Array(__classPrivateFieldGet$3(this,_CBC_iv,"f"))}encrypt(plaintext){if(plaintext.length%16){throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)")}const ciphertext=new Uint8Array(plaintext.length);for(let i=0;i<plaintext.length;i+=16){for(let j=0;j<16;j++){__classPrivateFieldGet$3(this,_CBC_lastBlock,"f")[j]^=plaintext[i+j]}__classPrivateFieldSet$3(this,_CBC_lastBlock,this.aes.encrypt(__classPrivateFieldGet$3(this,_CBC_lastBlock,"f")),"f");ciphertext.set(__classPrivateFieldGet$3(this,_CBC_lastBlock,"f"),i)}return ciphertext}decrypt(ciphertext){if(ciphertext.length%16){throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)")}const plaintext=new Uint8Array(ciphertext.length);for(let i=0;i<ciphertext.length;i+=16){const block=this.aes.decrypt(ciphertext.subarray(i,i+16));for(let j=0;j<16;j++){plaintext[i+j]=block[j]^__classPrivateFieldGet$3(this,_CBC_lastBlock,"f")[j];__classPrivateFieldGet$3(this,_CBC_lastBlock,"f")[j]=ciphertext[i+j]}}return plaintext}}_CBC_iv=new WeakMap,_CBC_lastBlock=new WeakMap;var __classPrivateFieldSet$2=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$2=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CFB_instances,_CFB_iv,_CFB_shiftRegister,_CFB_shift;class CFB extends ModeOfOperation{constructor(key,iv,segmentSize=8){super("CFB",key,CFB);_CFB_instances.add(this);_CFB_iv.set(this,void 0);_CFB_shiftRegister.set(this,void 0);if(!Number.isInteger(segmentSize)||segmentSize%8){throw new TypeError("invalid segmentSize")}Object.defineProperties(this,{segmentSize:{enumerable:true,value:segmentSize}});if(iv){if(iv.length%16){throw new TypeError("invalid iv size (must be 16 bytes)")}__classPrivateFieldSet$2(this,_CFB_iv,new Uint8Array(iv),"f")}else{__classPrivateFieldSet$2(this,_CFB_iv,new Uint8Array(16),"f")}__classPrivateFieldSet$2(this,_CFB_shiftRegister,this.iv,"f")}get iv(){return new Uint8Array(__classPrivateFieldGet$2(this,_CFB_iv,"f"))}encrypt(plaintext){if(8*plaintext.length%this.segmentSize){throw new TypeError("invalid plaintext size (must be multiple of segmentSize bytes)")}const segmentSize=this.segmentSize/8;const ciphertext=new Uint8Array(plaintext);for(let i=0;i<ciphertext.length;i+=segmentSize){const xorSegment=this.aes.encrypt(__classPrivateFieldGet$2(this,_CFB_shiftRegister,"f"));for(let j=0;j<segmentSize;j++){ciphertext[i+j]^=xorSegment[j]}__classPrivateFieldGet$2(this,_CFB_instances,"m",_CFB_shift).call(this,ciphertext.subarray(i))}return ciphertext}decrypt(ciphertext){if(8*ciphertext.length%this.segmentSize){throw new TypeError("invalid ciphertext size (must be multiple of segmentSize bytes)")}const segmentSize=this.segmentSize/8;const plaintext=new Uint8Array(ciphertext);for(let i=0;i<plaintext.length;i+=segmentSize){const xorSegment=this.aes.encrypt(__classPrivateFieldGet$2(this,_CFB_shiftRegister,"f"));for(let j=0;j<segmentSize;j++){plaintext[i+j]^=xorSegment[j]}__classPrivateFieldGet$2(this,_CFB_instances,"m",_CFB_shift).call(this,ciphertext.subarray(i))}return plaintext}}_CFB_iv=new WeakMap,_CFB_shiftRegister=new WeakMap,_CFB_instances=new WeakSet,_CFB_shift=function _CFB_shift(data){const segmentSize=this.segmentSize/8;__classPrivateFieldGet$2(this,_CFB_shiftRegister,"f").set(__classPrivateFieldGet$2(this,_CFB_shiftRegister,"f").subarray(segmentSize));__classPrivateFieldGet$2(this,_CFB_shiftRegister,"f").set(data.subarray(0,segmentSize),16-segmentSize)};var __classPrivateFieldSet$1=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$1=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CTR_remaining,_CTR_remainingIndex,_CTR_counter;class CTR extends ModeOfOperation{constructor(key,initialValue){super("CTR",key,CTR);_CTR_remaining.set(this,void 0);_CTR_remainingIndex.set(this,void 0);_CTR_counter.set(this,void 0);__classPrivateFieldSet$1(this,_CTR_counter,new Uint8Array(16),"f");__classPrivateFieldGet$1(this,_CTR_counter,"f").fill(0);__classPrivateFieldSet$1(this,_CTR_remaining,__classPrivateFieldGet$1(this,_CTR_counter,"f"),"f");__classPrivateFieldSet$1(this,_CTR_remainingIndex,16,"f");if(initialValue==null){initialValue=1}if(typeof initialValue==="number"){this.setCounterValue(initialValue)}else{this.setCounterBytes(initialValue)}}get counter(){return new Uint8Array(__classPrivateFieldGet$1(this,_CTR_counter,"f"))}setCounterValue(value){if(!Number.isInteger(value)||value<0||value>Number.MAX_SAFE_INTEGER){throw new TypeError("invalid counter initial integer value")}for(let index=15;index>=0;--index){__classPrivateFieldGet$1(this,_CTR_counter,"f")[index]=value%256;value=Math.floor(value/256)}}setCounterBytes(value){if(value.length!==16){throw new TypeError("invalid counter initial Uint8Array value length")}__classPrivateFieldGet$1(this,_CTR_counter,"f").set(value)}increment(){for(let i=15;i>=0;i--){if(__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]===255){__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]=0}else{__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]++;break}}}encrypt(plaintext){var _a,_b;const crypttext=new Uint8Array(plaintext);for(let i=0;i<crypttext.length;i++){if(__classPrivateFieldGet$1(this,_CTR_remainingIndex,"f")===16){__classPrivateFieldSet$1(this,_CTR_remaining,this.aes.encrypt(__classPrivateFieldGet$1(this,_CTR_counter,"f")),"f");__classPrivateFieldSet$1(this,_CTR_remainingIndex,0,"f");this.increment()}crypttext[i]^=__classPrivateFieldGet$1(this,_CTR_remaining,"f")[__classPrivateFieldSet$1(this,_CTR_remainingIndex,(_b=__classPrivateFieldGet$1(this,_CTR_remainingIndex,"f"),_a=_b++,_b),"f"),_a]}return crypttext}decrypt(ciphertext){return this.encrypt(ciphertext)}}_CTR_remaining=new WeakMap,_CTR_remainingIndex=new WeakMap,_CTR_counter=new WeakMap;class ECB extends ModeOfOperation{constructor(key){super("ECB",key,ECB)}encrypt(plaintext){if(plaintext.length%16){throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)")}const crypttext=new Uint8Array(plaintext.length);for(let i=0;i<plaintext.length;i+=16){crypttext.set(this.aes.encrypt(plaintext.subarray(i,i+16)),i)}return crypttext}decrypt(crypttext){if(crypttext.length%16){throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)")}const plaintext=new Uint8Array(crypttext.length);for(let i=0;i<crypttext.length;i+=16){plaintext.set(this.aes.decrypt(crypttext.subarray(i,i+16)),i)}return plaintext}}var __classPrivateFieldSet=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _OFB_iv,_OFB_lastPrecipher,_OFB_lastPrecipherIndex;class OFB extends ModeOfOperation{constructor(key,iv){super("OFB",key,OFB);_OFB_iv.set(this,void 0);_OFB_lastPrecipher.set(this,void 0);_OFB_lastPrecipherIndex.set(this,void 0);if(iv){if(iv.length%16){throw new TypeError("invalid iv size (must be 16 bytes)")}__classPrivateFieldSet(this,_OFB_iv,new Uint8Array(iv),"f")}else{__classPrivateFieldSet(this,_OFB_iv,new Uint8Array(16),"f")}__classPrivateFieldSet(this,_OFB_lastPrecipher,this.iv,"f");__classPrivateFieldSet(this,_OFB_lastPrecipherIndex,16,"f")}get iv(){return new Uint8Array(__classPrivateFieldGet(this,_OFB_iv,"f"))}encrypt(plaintext){var _a,_b;if(plaintext.length%16){throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)")}const ciphertext=new Uint8Array(plaintext);for(let i=0;i<ciphertext.length;i++){if(__classPrivateFieldGet(this,_OFB_lastPrecipherIndex,"f")===16){__classPrivateFieldSet(this,_OFB_lastPrecipher,this.aes.encrypt(__classPrivateFieldGet(this,_OFB_lastPrecipher,"f")),"f");__classPrivateFieldSet(this,_OFB_lastPrecipherIndex,0,"f")}ciphertext[i]^=__classPrivateFieldGet(this,_OFB_lastPrecipher,"f")[__classPrivateFieldSet(this,_OFB_lastPrecipherIndex,(_b=__classPrivateFieldGet(this,_OFB_lastPrecipherIndex,"f"),_a=_b++,_b),"f"),_a]}return ciphertext}decrypt(ciphertext){if(ciphertext.length%16){throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)")}return this.encrypt(ciphertext)}}_OFB_iv=new WeakMap,_OFB_lastPrecipher=new WeakMap,_OFB_lastPrecipherIndex=new WeakMap;function pkcs7Pad(data){const padder=16-data.length%16;const result=new Uint8Array(data.length+padder);result.set(data);for(let i=data.length;i<result.length;i++){result[i]=padder}return result}function pkcs7Strip(data){if(data.length<16){throw new TypeError("PKCS#7 invalid length")}const padder=data[data.length-1];if(padder>16){throw new TypeError("PKCS#7 padding byte out of range")}const length=data.length-padder;for(let i=0;i<padder;i++){if(data[length+i]!==padder){throw new TypeError("PKCS#7 invalid padding byte")}}return new Uint8Array(data.subarray(0,length))}function looseArrayify(hexString){if(typeof hexString==="string"&&hexString.substring(0,2)!=="0x"){hexString="0x"+hexString}return getBytesCopy(hexString)}function zpad(value,length){value=String(value);while(value.length<length){value="0"+value}return value}function getPassword(password){if(typeof password==="string"){return toUtf8Bytes(password,"NFKC")}return getBytesCopy(password)}function spelunk(object,_path){const match=_path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);if(match==null){return throwArgumentError("invalid path","path",_path)}const path=match[1];const type=match[3];const reqd=match[4]==="!";let cur=object;for(const comp of path.toLowerCase().split(".")){if(Array.isArray(cur)){if(!comp.match(/^[0-9]+$/)){break}cur=cur[parseInt(comp)]}else if(typeof cur==="object"){let found=null;for(const key in cur){if(key.toLowerCase()===comp){found=cur[key];break}}cur=found}else{cur=null}if(cur==null){break}}if(reqd&&cur==null){throwArgumentError("missing required value","path",path)}if(type&&cur!=null){if(type==="int"){if(typeof cur==="string"&&cur.match(/^-?[0-9]+$/)){return parseInt(cur)}else if(Number.isSafeInteger(cur)){return cur}}if(type==="number"){if(typeof cur==="string"&&cur.match(/^-?[0-9.]*$/)){return parseFloat(cur)}}if(type==="data"){if(typeof cur==="string"){return looseArrayify(cur)}}if(type==="array"&&Array.isArray(cur)){return cur}if(type===typeof cur){return cur}throwArgumentError(`wrong type found for ${type} `,"path",path)}return cur}function uuidV4(randomBytes){const bytes=getBytes(randomBytes,"randomBytes");bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;const value=hexlify(bytes);return[value.substring(2,10),value.substring(10,14),value.substring(14,18),value.substring(18,22),value.substring(22,34)].join("-")}function isCrowdsaleJson(json){try{const data=JSON.parse(json);if(data.encseed){return true}}catch(error){}return false}function decryptCrowdsaleJson(json,_password){const data=JSON.parse(json);const password=getPassword(_password);const address=getAddress(spelunk(data,"ethaddr:string!"));const encseed=looseArrayify(spelunk(data,"encseed:string!"));if(!encseed||encseed.length%16!==0){throwArgumentError("invalid encseed","json",json)}const key=getBytes(pbkdf2(password,password,2e3,32,"sha256")).slice(0,16);const iv=encseed.slice(0,16);const encryptedSeed=encseed.slice(16);const aesCbc=new CBC(key,iv);const seed=pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed)));let seedHex="";for(let i=0;i<seed.length;i++){seedHex+=String.fromCharCode(seed[i])}return{address:address,privateKey:id(seedHex)}}const defaultPath="m/44'/60'/0'/0/0";function isKeystoreJson(json){try{const data=JSON.parse(json);const version=data.version!=null?parseInt(data.version):0;if(version===3){return true}}catch(error){}return false}function decrypt(data,key,ciphertext){const cipher=spelunk(data,"crypto.cipher:string");if(cipher==="aes-128-ctr"){const iv=spelunk(data,"crypto.cipherparams.iv:data!");const aesCtr=new CTR(key,iv);return hexlify(aesCtr.decrypt(ciphertext))}return throwError("unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}function getAccount(data,_key){const key=getBytes(_key);const ciphertext=spelunk(data,"crypto.ciphertext:data!");const computedMAC=hexlify(keccak256(concat([key.slice(16,32),ciphertext]))).substring(2);if(computedMAC!==spelunk(data,"crypto.mac:string!").toLowerCase()){return throwArgumentError("incorrect password","password","[ REDACTED ]")}const privateKey=decrypt(data,key.slice(0,16),ciphertext);const address=computeAddress(privateKey);if(data.address){let check=data.address.toLowerCase();if(check.substring(0,2)!=="0x"){check="0x"+check}if(getAddress(check)!==address){throwArgumentError("keystore address/privateKey mismatch","address",data.address)}}const account={address:address,privateKey:privateKey};const version=spelunk(data,"x-ethers.version:string");if(version==="0.1"){const mnemonicKey=key.slice(32,64);const mnemonicCiphertext=spelunk(data,"x-ethers.mnemonicCiphertext:data!");const mnemonicIv=spelunk(data,"x-ethers.mnemonicCounter:data!");const mnemonicAesCtr=new CTR(mnemonicKey,mnemonicIv);account.mnemonic={path:spelunk(data,"x-ethers.path:string")||defaultPath,locale:spelunk(data,"x-ethers.locale:string")||"en",entropy:hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext)))}}return account}function getKdfParams(data){const kdf=spelunk(data,"crypto.kdf:string");if(kdf&&typeof kdf==="string"){const throwError=function(name,value){return throwArgumentError("invalid key-derivation function parameters",name,value)};if(kdf.toLowerCase()==="scrypt"){const salt=spelunk(data,"crypto.kdfparams.salt:data!");const N=spelunk(data,"crypto.kdfparams.n:int!");const r=spelunk(data,"crypto.kdfparams.r:int!");const p=spelunk(data,"crypto.kdfparams.p:int!");if(!N||!r||!p){return throwError("kdf",kdf)}if((N&N-1)!==0){return throwError("N",N)}const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");if(dkLen!==32){return throwError("dklen",dkLen)}return{name:"scrypt",salt:salt,N:N,r:r,p:p,dkLen:64}}else if(kdf.toLowerCase()==="pbkdf2"){const salt=spelunk(data,"crypto.kdfparams.salt:data!");const prf=spelunk(data,"crypto.kdfparams.prf:string!");const algorithm=prf.split("-").pop();if(algorithm!=="sha256"&&algorithm!=="sha512"){return throwError("prf",prf)}const count=spelunk(data,"crypto.kdfparams.c:int!");const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");if(dkLen!==32){throwError("dklen",dkLen)}return{name:"pbkdf2",salt:salt,count:count,dkLen:dkLen,algorithm:algorithm}}}return throwArgumentError("unsupported key-derivation function","kdf",kdf)}function decryptKeystoreJsonSync(json,_password){const data=JSON.parse(json);const password=getPassword(_password);const params=getKdfParams(data);if(params.name==="pbkdf2"){const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);return getAccount(data,key)}else if(params.name==="scrypt"){const{salt,N,r,p,dkLen}=params;const key=scryptSync(password,salt,N,r,p,dkLen);return getAccount(data,key)}throw new Error("unreachable")}function stall$1(duration){return new Promise(resolve=>{setTimeout(()=>{resolve()},duration)})}async function decryptKeystoreJson(json,_password,progress){const data=JSON.parse(json);const password=getPassword(_password);const params=getKdfParams(data);if(params.name==="pbkdf2"){if(progress){progress(0);await stall$1(0)}const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);if(progress){progress(1);await stall$1(0)}return getAccount(data,key)}else if(params.name==="scrypt"){const{salt,N,r,p,dkLen}=params;const key=await scrypt(password,salt,N,r,p,dkLen,progress);return getAccount(data,key)}throw new Error("unreachable")}async function encryptKeystoreJson(account,password,options,progressCallback){if(typeof options==="function"&&!progressCallback){progressCallback=options;options={}}if(!options){options={}}const privateKey=getBytes(account.privateKey,"privateKey");const passwordBytes=getPassword(password);const salt=options.salt!=null?getBytes(options.salt,"options.slat"):randomBytes(32);const iv=options.iv!=null?getBytes(options.iv,"options.iv"):randomBytes(16);if(iv.length!==16){throwArgumentError("invalid options.iv","options.iv",options.iv)}const uuidRandom=options.uuid!=null?getBytes(options.uuid,"options.uuid"):randomBytes(16);if(uuidRandom.length!==16){throwArgumentError("invalid options.uuid","options.uuid",options.iv)}if(uuidRandom.length!==16){throw new Error("invalid uuid")}let N=1<<17,r=8,p=1;if(options.scrypt){if(options.scrypt.N){N=options.scrypt.N}if(options.scrypt.r){r=options.scrypt.r}if(options.scrypt.p){p=options.scrypt.p}}const _key=await scrypt(passwordBytes,salt,N,r,p,64,progressCallback);const key=getBytes(_key);const derivedKey=key.slice(0,16);const macPrefix=key.slice(16,32);const aesCtr=new CTR(derivedKey,iv);const ciphertext=getBytes(aesCtr.encrypt(privateKey));const mac=keccak256(concat([macPrefix,ciphertext]));const data={address:account.address.substring(2).toLowerCase(),id:uuidV4(uuidRandom),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:hexlify(iv).substring(2)},ciphertext:hexlify(ciphertext).substring(2),kdf:"scrypt",kdfparams:{salt:hexlify(salt).substring(2),n:N,dklen:32,p:p,r:r},mac:mac.substring(2)}};if(account.mnemonic){const client=options.client!=null?options.client:`ethers/${version}`;const path=account.mnemonic.path||defaultPath;const locale=account.mnemonic.locale||"en";const mnemonicKey=key.slice(32,64);const entropy=getBytes(account.mnemonic.entropy,"account.mnemonic.entropy");const mnemonicIv=randomBytes(16);const mnemonicAesCtr=new CTR(mnemonicKey,mnemonicIv);const mnemonicCiphertext=getBytes(mnemonicAesCtr.encrypt(entropy));const now=new Date;const timestamp=now.getUTCFullYear()+"-"+zpad(now.getUTCMonth()+1,2)+"-"+zpad(now.getUTCDate(),2)+"T"+zpad(now.getUTCHours(),2)+"-"+zpad(now.getUTCMinutes(),2)+"-"+zpad(now.getUTCSeconds(),2)+".0Z";const gethFilename="UTC--"+timestamp+"--"+data.address;data["x-ethers"]={client:client,gethFilename:gethFilename,path:path,locale:locale,mnemonicCounter:hexlify(mnemonicIv).substring(2),mnemonicCiphertext:hexlify(mnemonicCiphertext).substring(2),version:"0.1"}}return JSON.stringify(data)}function tryWallet(value){try{if(!value||!value.signingKey){return null}const key=trySigningKey(value.signingKey);if(key==null||computeAddress(key.publicKey)!==value.address){return null}if(value.mnemonic){const wallet=HDNodeWallet.fromMnemonic(value.mnemonic);if(wallet.privateKey!==key.privateKey){return null}}return value}catch(e){console.log(e)}return null}function tryMnemonic(value){try{if(value==null||typeof value.phrase!=="string"||typeof value.password!=="string"||value.wordlist==null){return null}return HDNodeWallet.fromPhrase(value.phrase,value.password,null,value.wordlist)}catch(error){console.log(error)}return null}function trySigningKey(value){try{if(!value||!isHexString(value.privateKey,32)){return null}const key=value.privateKey;if(SigningKey.computePublicKey(key)!==value.publicKey){return null}return new SigningKey(key)}catch(e){console.log(e)}return null}function stall(duration){return new Promise(resolve=>{setTimeout(()=>{resolve()},duration)})}class Wallet extends BaseWallet{#mnemonic;constructor(key,provider){let signingKey=null;let mnemonic=null;if(typeof key==="string"){signingKey=new SigningKey(key)}if(signingKey==null){const wallet=tryWallet(key);if(wallet){signingKey=wallet.signingKey;mnemonic=wallet.mnemonic||null}}if(signingKey==null){const wallet=tryMnemonic(key);if(wallet){signingKey=wallet.signingKey;mnemonic=wallet.mnemonic||null}}if(signingKey==null){signingKey=trySigningKey(key)}if(signingKey==null){throwArgumentError("invalid key","key","[ REDACTED ]")}super(signingKey,provider);this.#mnemonic=mnemonic}get mnemonic(){return this.#mnemonic}connect(provider){return new Wallet(this,provider)}async encrypt(password,options,progressCallback){throw new Error("TODO")}encryptSync(password,options){throw new Error("TODO")}static async fromEncryptedJson(json,password,progress){let account=null;if(isKeystoreJson(json)){account=await decryptKeystoreJson(json,password,progress)}else if(isCrowdsaleJson(json)){if(progress){progress(0);await stall(0)}account=decryptCrowdsaleJson(json,password);if(progress){progress(1);await stall(0)}}else{return throwArgumentError("invalid JSON wallet","json","[ REDACTED ]")}const wallet=new Wallet(account.privateKey);if(wallet.address!==account.address){throwArgumentError("address/privateKey mismatch","json","[ REDACTED ]")}return wallet}static fromEncryptedJsonSync(json,password){let account=null;if(isKeystoreJson(json)){account=decryptKeystoreJsonSync(json,password)}else if(isCrowdsaleJson(json)){account=decryptCrowdsaleJson(json,password)}else{return throwArgumentError("invalid JSON wallet","json","[ REDACTED ]")}const wallet=new Wallet(account.privateKey);if(wallet.address!==account.address){throwArgumentError("address/privateKey mismatch","json","[ REDACTED ]")}return wallet}static createRandom(provider,password,wordlist){return new Wallet(Mnemonic.fromEntropy(randomBytes(16),password,wordlist),provider)}static fromMnemonic(mnemonic,provider){return new Wallet(mnemonic,provider)}static fromPhrase(phrase,provider,password,wordlist){if(password==null){password=""}return new Wallet(Mnemonic.fromPhrase(phrase,password,wordlist),provider)}}const wordlists=Object.freeze({en:langEn});const Base64=")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";function decodeBits(width,data){const maxValue=(1<<width)-1;const result=[];let accum=0,bits=0,flood=0;for(let i=0;i<data.length;i++){accum=accum<<6|Base64.indexOf(data[i]);bits+=6;while(bits>=width){const value=accum>>bits-width;accum&=(1<<bits-width)-1;bits-=width;if(value===0){flood+=maxValue}else{result.push(value+flood);flood=0}}}return result}function decodeOwlA(data,accents){let words=decodeOwl(data).join(",");accents.split(/,/g).forEach(accent=>{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}var ethers=Object.freeze({__proto__:null,version:version,formatBytes32String:formatBytes32String,parseBytes32String:parseBytes32String,AbiCoder:AbiCoder,defaultAbiCoder:defaultAbiCoder,ConstructorFragment:ConstructorFragment,ErrorFragment:ErrorFragment,EventFragment:EventFragment,Fragment:Fragment,FunctionFragment:FunctionFragment,ParamType:ParamType,checkResultErrors:checkResultErrors,Indexed:Indexed,Interface:Interface,LogDescription:LogDescription,Result:Result,TransactionDescription:TransactionDescription,Typed:Typed,getAddress:getAddress,getIcapAddress:getIcapAddress,getCreateAddress:getCreateAddress,getCreate2Address:getCreate2Address,ZeroAddress:ZeroAddress,NegativeOne:NegativeOne,Zero:Zero,One:One,Two:Two,WeiPerEther:WeiPerEther,MaxUint256:MaxUint256,MinInt256:MinInt256,MaxInt256:MaxInt256,N:N$1,ZeroHash:ZeroHash,EtherSymbol:EtherSymbol,MessagePrefix:MessagePrefix,BaseContract:BaseContract,Contract:Contract,ContractFactory:ContractFactory,ContractEventPayload:ContractEventPayload,ContractTransactionReceipt:ContractTransactionReceipt,ContractTransactionResponse:ContractTransactionResponse,EventLog:EventLog,computeHmac:computeHmac,randomBytes:randomBytes,keccak256:keccak256,ripemd160:ripemd160,sha256:sha256,sha512:sha512,pbkdf2:pbkdf2,scrypt:scrypt,scryptSync:scryptSync,lock:lock,Signature:Signature,SigningKey:SigningKey,id:id,isValidName:isValidName,namehash:namehash,dnsEncode:dnsEncode,hashMessage:hashMessage,solidityPacked:solidityPacked,solidityPackedKeccak256:solidityPackedKeccak256,solidityPackedSha256:solidityPackedSha256,TypedDataEncoder:TypedDataEncoder,accessListify:accessListify,computeAddress:computeAddress,recoverAddress:recoverAddress,Transaction:Transaction,decodeBase58:decodeBase58,encodeBase58:encodeBase58,decodeBase64:decodeBase64,encodeBase64:encodeBase64,concat:concat,dataLength:dataLength,dataSlice:dataSlice,getBytes:getBytes,getBytesCopy:getBytesCopy,hexlify:hexlify,isHexString:isHexString,isBytesLike:isBytesLike,stripZerosLeft:stripZerosLeft,zeroPadBytes:zeroPadBytes,zeroPadValue:zeroPadValue,assertArgument:assertArgument,assertArgumentCount:assertArgumentCount,assertNormalize:assertNormalize,assertPrivate:assertPrivate,makeError:makeError,throwArgumentError:throwArgumentError,throwError:throwError,isCallException:isCallException,isError:isError,getIpfsGatewayFunc:getIpfsGatewayFunc,FetchRequest:FetchRequest,FetchResponse:FetchResponse,FetchCancelSignal:FetchCancelSignal,FixedFormat:FixedFormat,FixedNumber:FixedNumber,formatFixed:formatFixed,parseFixed:parseFixed,getBigInt:getBigInt,getNumber:getNumber,toArray:toArray,toBigInt:toBigInt,toHex:toHex,toNumber:toNumber,toQuantity:toQuantity,fromTwos:fromTwos,toTwos:toTwos,mask:mask,formatEther:formatEther,parseEther:parseEther,formatUnits:formatUnits,parseUnits:parseUnits,_toEscapedUtf8String:_toEscapedUtf8String,toUtf8Bytes:toUtf8Bytes,toUtf8CodePoints:toUtf8CodePoints,toUtf8String:toUtf8String,Utf8ErrorFuncs:Utf8ErrorFuncs,decodeRlp:decodeRlp,encodeRlp:encodeRlp,defaultPath:defaultPath$1,getAccountPath:getAccountPath,HDNodeWallet:HDNodeWallet,HDNodeVoidWallet:HDNodeVoidWallet,HDNodeWalletManager:HDNodeWalletManager,isCrowdsaleJson:isCrowdsaleJson,decryptCrowdsaleJson:decryptCrowdsaleJson,isKeystoreJson:isKeystoreJson,decryptKeystoreJsonSync:decryptKeystoreJsonSync,decryptKeystoreJson:decryptKeystoreJson,encryptKeystoreJson:encryptKeystoreJson,Mnemonic:Mnemonic,Wallet:Wallet,Wordlist:Wordlist,langEn:langEn,LangEn:LangEn,wordlists:wordlists,WordlistOwl:WordlistOwl,WordlistOwlA:WordlistOwlA,AbstractProvider:AbstractProvider,FallbackProvider:FallbackProvider,JsonRpcApiProvider:JsonRpcApiProvider,JsonRpcProvider:JsonRpcProvider,JsonRpcSigner:JsonRpcSigner,AlchemyProvider:AlchemyProvider,AnkrProvider:AnkrProvider,CloudflareProvider:CloudflareProvider,EtherscanProvider:EtherscanProvider,InfuraProvider:InfuraProvider,IpcSocketProvider:IpcSocketProvider,SocketProvider:SocketProvider,WebSocketProvider:WebSocketProvider,Network:Network});export{AbiCoder,AbstractProvider,AlchemyProvider,AnkrProvider,BaseContract,CloudflareProvider,ConstructorFragment,Contract,ContractEventPayload,ContractFactory,ContractTransactionReceipt,ContractTransactionResponse,ErrorFragment,EtherSymbol,EtherscanProvider,EventFragment,EventLog,FallbackProvider,FetchCancelSignal,FetchRequest,FetchResponse,FixedFormat,FixedNumber,Fragment,FunctionFragment,HDNodeVoidWallet,HDNodeWallet,HDNodeWalletManager,Indexed,InfuraProvider,Interface,IpcSocketProvider,JsonRpcApiProvider,JsonRpcProvider,JsonRpcSigner,LangEn,LogDescription,MaxInt256,MaxUint256,MessagePrefix,MinInt256,Mnemonic,N$1 as N,NegativeOne,Network,One,ParamType,Result,Signature,SigningKey,SocketProvider,Transaction,TransactionDescription,Two,Typed,TypedDataEncoder,Utf8ErrorFuncs,Wallet,WebSocketProvider,WeiPerEther,Wordlist,WordlistOwl,WordlistOwlA,Zero,ZeroAddress,ZeroHash,_toEscapedUtf8String,accessListify,assertArgument,assertArgumentCount,assertNormalize,assertPrivate,checkResultErrors,computeAddress,computeHmac,concat,dataLength,dataSlice,decodeBase58,decodeBase64,decodeRlp,decryptCrowdsaleJson,decryptKeystoreJson,decryptKeystoreJsonSync,defaultAbiCoder,defaultPath$1 as defaultPath,dnsEncode,encodeBase58,encodeBase64,encodeRlp,encryptKeystoreJson,ethers,formatBytes32String,formatEther,formatFixed,formatUnits,fromTwos,getAccountPath,getAddress,getBigInt,getBytes,getBytesCopy,getCreate2Address,getCreateAddress,getIcapAddress,getIpfsGatewayFunc,getNumber,hashMessage,hexlify,id,isBytesLike,isCallException,isCrowdsaleJson,isError,isHexString,isKeystoreJson,isValidName,keccak256,langEn,lock,makeError,mask,namehash,parseBytes32String,parseEther,parseFixed,parseUnits,pbkdf2,randomBytes,recoverAddress,ripemd160,scrypt,scryptSync,sha256,sha512,solidityPacked,solidityPackedKeccak256,solidityPackedSha256,stripZerosLeft,throwArgumentError,throwError,toArray,toBigInt,toHex,toNumber,toQuantity,toTwos,toUtf8Bytes,toUtf8CodePoints,toUtf8String,version,wordlists,zeroPadBytes,zeroPadValue};