ethers
Version:
A complete and compact Ethereum library, for dapps, wallets and any other tools.
1 lines • 502 kB
JavaScript
const __$G=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};const version="6.13.7";function checkType(value,type,name){const types=type.split("|").map(t=>t.trim());for(let i=0;i<types.length;i++){switch(type){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof value===type){return}}}const error=new Error(`invalid value for type ${type}`);error.code="INVALID_ARGUMENT";error.argument=`value.${name}`;error.value=value;throw error}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 defineProperties(target,values,types){for(let key in values){let value=values[key];const type=types?types[key]:null;if(type){checkType(value,type,key)}Object.defineProperty(target,key,{enumerable:true,value:value,writable:false})}}function stringify$1(value){if(value==null){return"null"}if(Array.isArray(value)){return"[ "+value.map(stringify$1).join(", ")+" ]"}if(value instanceof Uint8Array){const HEX="0123456789abcdef";let result="0x";for(let i=0;i<value.length;i++){result+=HEX[value[i]>>4];result+=HEX[value[i]&15]}return result}if(typeof value==="object"&&typeof value.toJSON==="function"){return stringify$1(value.toJSON())}switch(typeof value){case"boolean":case"symbol":return value.toString();case"bigint":return BigInt(value).toString();case"number":return value.toString();case"string":return JSON.stringify(value);case"object":{const keys=Object.keys(value);keys.sort();return"{ "+keys.map(k=>`${stringify$1(k)}: ${stringify$1(value[k])}`).join(", ")+" }"}}return`[ COULD NOT SERIALIZE ]`}function isError(error,code){return error&&error.code===code}function isCallException(error){return isError(error,"CALL_EXCEPTION")}function makeError(message,code,info){let shortMessage=message;{const details=[];if(info){if("message"in info||"code"in info||"name"in info){throw new Error(`value will overwrite populated values: ${stringify$1(info)}`)}for(const key in info){if(key==="shortMessage"){continue}const value=info[key];details.push(key+"="+stringify$1(value))}}details.push(`code=${code}`);details.push(`version=${version}`);if(details.length){message+=" ("+details.join(", ")+")"}}let error;switch(code){case"INVALID_ARGUMENT":error=new TypeError(message);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":error=new RangeError(message);break;default:error=new Error(message)}defineProperties(error,{code:code});if(info){Object.assign(error,info)}if(error.shortMessage==null){defineProperties(error,{shortMessage:shortMessage})}return error}function assert(check,message,code,info){if(!check){throw makeError(message,code,info)}}function assertArgument(check,message,name,value){assert(check,message,"INVALID_ARGUMENT",{argument:name,value:value})}function assertArgumentCount(count,expectedCount,message){if(message==null){message=""}if(message){message=": "+message}assert(count>=expectedCount,"missing argument"+message,"MISSING_ARGUMENT",{count:count,expectedCount:expectedCount});assert(count<=expectedCount,"too many arguments"+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){assert(_normalizeForms.indexOf(form)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}function assertPrivate(givenGuard,guard,className){if(className==null){className=""}if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}assert(false,`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}assertArgument(false,"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){assert(false,"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.startsWith("00")){bytes=bytes.substring(2)}return"0x"+bytes}function zeroPad(data,length,left){const bytes=getBytes(data);assert(length>=bytes.length,"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$a=BigInt(0);const BN_1$5=BigInt(1);const maxValue=9007199254740991;function fromTwos(_value,_width){const value=getUint(_value,"value");const width=BigInt(getNumber(_width,"width"));assert(value>>width===BN_0$a,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:_value});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){let value=getBigInt(_value,"value");const width=BigInt(getNumber(_width,"width"));const limit=BN_1$5<<width-BN_1$5;if(value<BN_0$a){value=-value;assert(value<=limit,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:_value});const mask=(BN_1$5<<width)-BN_1$5;return(~value&mask)+BN_1$5}else{assert(value<limit,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:_value})}return value}function mask(_value,_bits){const value=getUint(_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":assertArgument(Number.isInteger(value),"underflow",name||"value",value);assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return BigInt(value);case"string":try{if(value===""){throw new Error("empty string")}if(value[0]==="-"&&value[1]!=="-"){return-BigInt(value.substring(1))}return BigInt(value)}catch(e){assertArgument(false,`invalid BigNumberish string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid BigNumberish value",name||"value",value)}function getUint(value,name){const result=getBigInt(value,name);assert(result>=BN_0$a,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:value});return result}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":assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return Number(value);case"number":assertArgument(Number.isInteger(value),"underflow",name||"value",value);assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return value;case"string":try{if(value===""){throw new Error("empty string")}return getNumber(BigInt(value),name)}catch(e){assertArgument(false,`invalid numeric string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid numeric value",name||"value",value)}function toNumber(value){return getNumber(toBigInt(value))}function toBeHex(_value,_width){const value=getUint(_value,"value");let result=value.toString(16);if(_width==null){if(result.length%2){result="0"+result}}else{const width=getNumber(_width,"width");assert(width*2>=result.length,`value exceeds width (${width} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:_value});while(result.length<width*2){result="0"+result}}return"0x"+result}function toBeArray(_value){const value=getUint(_value,"value");if(value===BN_0$a){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:toBeArray(value)).substring(2);while(result.startsWith("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];assertArgument(result!=null,`invalid base58 value`,"letter",letter);return result}const BN_0$9=BigInt(0);const BN_58=BigInt(58);function encodeBase58(_value){const bytes=getBytes(_value);let value=toBigInt(bytes);let result="";while(value){result=Alphabet[Number(value%BN_58)]+result;value/=BN_58}for(let i=0;i<bytes.length;i++){if(bytes[i]){break}result=Alphabet[0]+result}return result}function decodeBase58(value){let result=BN_0$9;for(let i=0;i<value.length;i++){result*=BN_58;result+=getAlpha(value[i])}return 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){assertArgument(false,`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"){assertArgument(typeof badCodepoint==="number","invalid bad code point for replacement","badCodepoint",badCodepoint);output.push(badCodepoint);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes)}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){assertArgument(typeof str==="string","invalid string value","str",str);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);assertArgument(i<str.length&&(c2&64512)===56320,"invalid surrogate pair","str",str);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 _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))}function createGetUrl(options){async function getUrl(req,_signal){assert(_signal==null||!_signal.cancelled,"request cancelled before sending","CANCELLED");const protocol=req.url.split(":")[0].toLowerCase();assert(protocol==="http"||protocol==="https",`unsupported protocol ${protocol}`,"UNSUPPORTED_OPERATION",{info:{protocol:protocol},operation:"request"});assert(protocol==="https"||!req.credentials||req.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let error=null;const controller=new AbortController;const timer=setTimeout(()=>{error=makeError("request timeout","TIMEOUT");controller.abort()},req.timeout);if(_signal){_signal.addListener(()=>{error=makeError("request cancelled","CANCELLED");controller.abort()})}const init={method:req.method,headers:new Headers(Array.from(req)),body:req.body||undefined,signal:controller.signal};let resp;try{resp=await fetch(req.url,init)}catch(_error){clearTimeout(timer);if(error){throw error}throw _error}clearTimeout(timer);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}}return getUrl}const MAX_ATTEMPTS=12;const SLOT_INTERVAL=250;let defaultGetUrlFunc=createGetUrl();const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i");const reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$5=false;async function dataGatewayFunc(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:dataGatewayFunc,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){assert(!this.#cancelled,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"});this.#listeners.push(listener)}get cancelled(){return this.#cancelled}checkSignal(){assert(!this.cancelled,"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;#throttle;#getUrlFunc;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 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){assertArgument(!username.match(/:/),"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}get getUrlFunc(){return this.#getUrlFunc||defaultGetUrlFunc}set getUrlFunc(value){this.#getUrlFunc=value}constructor(url){this.#url=String(url);this.#allowInsecure=false;this.#gzip=true;this.#headers={};this.#method="";this.#timeout=3e5;this.#throttle={slotInterval:SLOT_INTERVAL,maxAttempts:MAX_ATTEMPTS};this.#getUrlFunc=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#body?hexlify(this.#body):"null"}>`}setThrottleParams(params){if(params.slotInterval!=null){this.#throttle.slotInterval=params.slotInterval}if(params.maxAttempts!=null){this.#throttle.maxAttempts=params.maxAttempts}}async#send(attempt,expires,delay,_request,_response){if(attempt>=this.#throttle.maxAttempts){return _response.makeServerError("exceeded maximum retry limit")}assert(getTime$2()<=expires,"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 this.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=this.#throttle.slotInterval*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=this.#throttle.slotInterval*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(){assert(this.#signal==null,"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(){assert(this.#signal!=null,"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();assert(this.method==="GET"&&(current!=="https"||target!=="http")&&location.match(/^https?:/),`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;clone.#throttle=Object.assign({},this.#throttle);clone.#getUrlFunc=this.#getUrlFunc;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")}defaultGetUrlFunc=getUrl}static createGetUrlFunc(options){return createGetUrl()}static createDataGateway(){return dataGatewayFunc}static createIpfsGatewayFunc(baseUrl){return getIpfsGatewayFunc(baseUrl)}}class FetchResponse{#statusCode;#statusMessage;#headers;#body;#request;#error;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#body?hexlify(this.#body):"null"}>`}get statusCode(){return this.#statusCode}get statusMessage(){return this.#statusMessage}get headers(){return Object.assign({},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){assert(false,"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){assert(false,"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.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{assertArgument(Number.isInteger(stall)&&stall>=0,"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}`}let requestUrl=null;if(this.request){requestUrl=this.request.url}let responseBody=null;try{if(this.#body){responseBody=toUtf8String(this.#body)}}catch(e){}assert(false,message,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:error,info:{requestUrl:requestUrl,responseBody:responseBody,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}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 BN_N1=BigInt(-1);const BN_0$8=BigInt(0);const BN_1$4=BigInt(1);const BN_5=BigInt(5);const _guard$5={};let Zeros$1="0000";while(Zeros$1.length<80){Zeros$1+=Zeros$1}function getTens(decimals){let result=Zeros$1;while(result.length<decimals){result+=result}return BigInt("1"+result.substring(0,decimals))}function checkValue(val,format,safeOp){const width=BigInt(format.width);if(format.signed){const limit=BN_1$4<<width-BN_1$4;assert(safeOp==null||val>=-limit&&val<limit,"overflow","NUMERIC_FAULT",{operation:safeOp,fault:"overflow",value:val});if(val>BN_0$8){val=fromTwos(mask(val,width),width)}else{val=-fromTwos(mask(-val,width),width)}}else{const limit=BN_1$4<<width;assert(safeOp==null||val>=0&&val<limit,"overflow","NUMERIC_FAULT",{operation:safeOp,fault:"overflow",value:val});val=(val%limit+limit)%limit&limit-BN_1$4}return val}function getFormat(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]+)$/);assertArgument(match,"invalid fixed format","format",value);signed=match[1]!=="u";width=parseInt(match[2]);decimals=parseInt(match[3])}}else if(value){const v=value;const check=(key,type,defaultValue)=>{if(v[key]==null){return defaultValue}assertArgument(typeof v[key]===type,"invalid fixed format ("+key+" not "+type+")","format."+key,v[key]);return v[key]};signed=check("signed","boolean",signed);width=check("width","number",width);decimals=check("decimals","number",decimals)}assertArgument(width%8===0,"invalid FixedNumber width (not byte aligned)","format.width",width);assertArgument(decimals<=80,"invalid FixedNumber decimals (too large)","format.decimals",decimals);const name=(signed?"":"u")+"fixed"+String(width)+"x"+String(decimals);return{signed:signed,width:width,decimals:decimals,name:name}}function toString(val,decimals){let negative="";if(val<BN_0$8){negative="-";val*=BN_N1}let str=val.toString();if(decimals===0){return negative+str}while(str.length<=decimals){str=Zeros$1+str}const index=str.length-decimals;str=str.substring(0,index)+"."+str.substring(index);while(str[0]==="0"&&str[1]!=="."){str=str.substring(1)}while(str[str.length-1]==="0"&&str[str.length-2]!=="."){str=str.substring(0,str.length-1)}return negative+str}class FixedNumber{format;#format;#val;#tens;_value;constructor(guard,value,format){assertPrivate(guard,_guard$5,"FixedNumber");this.#val=value;this.#format=format;const _value=toString(value,format.decimals);defineProperties(this,{format:format.name,_value:_value});this.#tens=getTens(format.decimals)}get signed(){return this.#format.signed}get width(){return this.#format.width}get decimals(){return this.#format.decimals}get value(){return this.#val}#checkFormat(other){assertArgument(this.format===other.format,"incompatible format; use fixedNumber.toFormat","other",other)}#checkValue(val,safeOp){val=checkValue(val,this.#format,safeOp);return new FixedNumber(_guard$5,val,this.#format)}#add(o,safeOp){this.#checkFormat(o);return this.#checkValue(this.#val+o.#val,safeOp)}addUnsafe(other){return this.#add(other)}add(other){return this.#add(other,"add")}#sub(o,safeOp){this.#checkFormat(o);return this.#checkValue(this.#val-o.#val,safeOp)}subUnsafe(other){return this.#sub(other)}sub(other){return this.#sub(other,"sub")}#mul(o,safeOp){this.#checkFormat(o);return this.#checkValue(this.#val*o.#val/this.#tens,safeOp)}mulUnsafe(other){return this.#mul(other)}mul(other){return this.#mul(other,"mul")}mulSignal(other){this.#checkFormat(other);const value=this.#val*other.#val;assert(value%this.#tens===BN_0$8,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this});return this.#checkValue(value/this.#tens,"mulSignal")}#div(o,safeOp){assert(o.#val!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this});this.#checkFormat(o);return this.#checkValue(this.#val*this.#tens/o.#val,safeOp)}divUnsafe(other){return this.#div(other)}div(other){return this.#div(other,"div")}divSignal(other){assert(other.#val!==BN_0$8,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this});this.#checkFormat(other);const value=this.#val*this.#tens;assert(value%other.#val===BN_0$8,"precision lost during signalling div","NUMERIC_FAULT",{operation:"divSignal",fault:"underflow",value:this});return this.#checkValue(value/other.#val,"divSignal")}cmp(other){let a=this.value,b=other.value;const delta=this.decimals-other.decimals;if(delta>0){b*=getTens(delta)}else if(delta<0){a*=getTens(-delta)}if(a<b){return-1}if(a>b){return 1}return 0}eq(other){return this.cmp(other)===0}lt(other){return this.cmp(other)<0}lte(other){return this.cmp(other)<=0}gt(other){return this.cmp(other)>0}gte(other){return this.cmp(other)>=0}floor(){let val=this.#val;if(this.#val<BN_0$8){val-=this.#tens-BN_1$4}val=this.#val/this.#tens*this.#tens;return this.#checkValue(val,"floor")}ceiling(){let val=this.#val;if(this.#val>BN_0$8){val+=this.#tens-BN_1$4}val=this.#val/this.#tens*this.#tens;return this.#checkValue(val,"ceiling")}round(decimals){if(decimals==null){decimals=0}if(decimals>=this.decimals){return this}const delta=this.decimals-decimals;const bump=BN_5*getTens(delta-1);let value=this.value+bump;const tens=getTens(delta);value=value/tens*tens;checkValue(value,this.#format,"round");return new FixedNumber(_guard$5,value,this.#format)}isZero(){return this.#val===BN_0$8}isNegative(){return this.#val<BN_0$8}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(format){return FixedNumber.fromString(this.toString(),format)}static fromValue(_value,_decimals,_format){const decimals=_decimals==null?0:getNumber(_decimals);const format=getFormat(_format);let value=getBigInt(_value,"value");const delta=decimals-format.decimals;if(delta>0){const tens=getTens(delta);assert(value%tens===BN_0$8,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:_value});value/=tens}else if(delta<0){value*=getTens(-delta)}checkValue(value,format,"fromValue");return new FixedNumber(_guard$5,value,format)}static fromString(_value,_format){const match=_value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(match&&match[2].length+match[3].length>0,"invalid FixedNumber string value","value",_value);const format=getFormat(_format);let whole=match[2]||"0",decimal=match[3]||"";while(decimal.length<format.decimals){decimal+=Zeros$1}assert(decimal.substring(format.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:_value});decimal=decimal.substring(0,format.decimals);const value=BigInt(match[1]+whole+decimal);checkValue(value,format,"fromString");return new FixedNumber(_guard$5,value,format)}static fromBytes(_value,_format){let value=toBigInt(getBytes(_value,"value"));const format=getFormat(_format);if(format.signed){value=fromTwos(value,format.width)}checkValue(value,format,"fromBytes");return new FixedNumber(_guard$5,value,format)}}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;assert(childOffset<=offset+1+length,"child data too short","BUFFER_OVERRUN",{buffer:data,length:length,offset:offset})}return{consumed:1+length,result:result}}function _decode(data,offset){assert(data.length!==0,"data too short","BUFFER_OVERRUN",{buffer:data,length:0,offset:1});const checkOffset=offset=>{assert(offset<=data.length,"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);assertArgument(decoded.consumed===data.length,"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}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(value,unit){let decimals=18;if(typeof unit==="string"){const index=names.indexOf(unit);assertArgument(index>=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromValue(value,decimals,{decimals:decimals,width:512}).toString()}function parseUnits$1(value,unit){assertArgument(typeof value==="string","value must be a string","value",value);let decimals=18;if(typeof unit==="string"){const index=names.indexOf(unit);assertArgument(index>=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromString(value,{decimals:decimals,width:512}).value}function formatEther(wei){return formatUnits(wei,18)}function parseEther(ether){return parseUnits$1(ether,18)}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("-")}const WordSize=32;const Padding=new Uint8Array(WordSize);const passProperties$1=["then"];const _guard$4={};const resultNames=new WeakMap;function getNames(result){return resultNames.get(result)}function setNames(result,names){resultNames.set(result,names)}function throwError(name,error){const wrapped=new Error(`deferred error during ABI decoding triggered accessing ${name}`);wrapped.error=error;throw wrapped}function toObject(names,items,deep){if(names.indexOf(null)>=0){return items.map((item,index)=>{if(item instanceof Result){return toObject(getNames(item),item,deep)}return item})}return names.reduce((accum,name,index)=>{let item=items.getValue(name);if(!(name in accum)){if(deep&&item instanceof Result){item=toObject(getNames(item),item,deep)}accum[name]=item}return accum},{})}class Result extends Array{#names;constructor(...args){const guard=args[0];let items=args[1];let names=(args[2]||[]).slice();let wrap=true;if(guard!==_guard$4){items=args;names=[];wrap=false}super(items.length);items.forEach((item,index)=>{this[index]=item});const nameCounts=names.reduce((accum,name)=>{if(typeof name==="string"){accum.set(name,(accum.get(name)||0)+1)}return accum},new Map);setNames(this,Object.freeze(items.map((item,index)=>{const name=names[index];if(name!=null&&nameCounts.get(name)===1){return name}return null})));this.#names=[];if(this.#names==null){void this.#names}if(!wrap){return}Object.freeze(this);const proxy=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){throwError(`index ${index}`,item)}return item}if(passProperties$1.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}const value=target[prop];if(value instanceof Function){return function(...args){return value.apply(this===receiver?target:this,args)}}else if(!(prop in target)){return target.getValue.apply(this===receiver?target:this,[prop])}}return Reflect.get(target,prop,receiver)}});setNames(proxy,getNames(this));return proxy}toArray(deep){const result=[];this.forEach((item,index)=>{if(item instanceof Error){throwError(`index ${index}`,item)}if(deep&&item instanceof Result){item=item.toArray(deep)}result.push(item)});return result}toObject(deep){const names=getNames(this);return names.reduce((accum,name,index)=>{assert(name!=null,`value at index ${index} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"});return toObject(names,this,deep)},{})}slice(start,end){if(start==null){start=0}if(start<0){start+=this.length;if(start<0){start=0}}if(end==null){end=this.length}if(end<0){end+=this.length;if(end<0){end=0}}if(end>this.length){end=this.length}const _names=getNames(this);const result=[],names=[];for(let i=start;i<end;i++){result.push(this[i]);names.push(_names[i])}return new Result(_guard$4,result,names)}filter(callback,thisArg){const _names=getNames(this);const result=[],names=[];for(let i=0;i<this.length;i++){const item=this[i];if(item instanceof Error){throwError(`index ${i}`,item)}if(callback.call(thisArg,item,i,this)){result.push(item);names.push(_names[i])}}return new Result(_guard$4,result,names)}map(callback,thisArg){const result=[];for(let i=0;i<this.length;i++){const item=this[i];if(item instanceof Error){throwError(`index ${i}`,item)}result.push(callback.call(thisArg,item,i,this))}return result}getValue(name){const index=getNames(this).indexOf(name);if(index===-1){return undefined}const value=this[index];if(value instanceof Error){throwError(`property ${JSON.stringify(name)}`,value.error)}return value}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=toBeArray(value);assert(bytes.length<=WordSize,"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){assertArgument(false,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;#bytesRead;#parent;#maxInflation;constructor(data,allowLoose,maxInflation){defineProperties(this,{allowLoose:!!allowLoose});this.#data=getBytesCopy(data);this.#bytesRead=0;this.#parent=null;this.#maxInflation=maxInflation!=null?maxInflation:1024;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)}#incrementBytesRead(count){if(this.#parent){return this.#parent.#incrementBytesRead(count)}this.#bytesRead+=count;assert(this.#maxInflation<1||this.#bytesRead<=this.#maxInflation*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:getBytesCopy(this.#data),offset:this.#offset,length:count,info:{bytesRead:this.#bytesRead,dataLength:this.dataLength}})}#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{assert(false,"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){const reader=new Reader(this.#data.slice(this.#offset+offset),this.allowLoose,this.#maxInflation);reader.#parent=this;return reader}readBytes(length,loose){let bytes=this.#peekBytes(0,length,!!loose);this.#incrementBytesRead(length);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 bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new Error("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new Error(`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 crypto$1=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:undefined;const u8a$1=a=>a instanceof Uint8Array;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 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$1(str){if(typeof str!=="string")throw new Error(`utf8ToBytes expected string, got ${typeof str}`);return new Uint8Array((new TextEncoder).encode(str))}function toBytes(data){if(typeof data==="string")data=utf8ToBytes$1(data);if(!u8a$1(data))throw new Error(`expected Uint8Array, got ${typeof data}`);return data}function concatBytes$1(...arrays){const r=new Uint8Array(arrays.reduce((sum,a)=>sum+a.length,0));let pad=0;arrays.forEach(a=>{if(!u8a$1(a))throw new Error("Uint8Array expected");r.set(a,pad);pad+=a.length});return r}class Hash{clone(){return this._cloneInto()}}const toStr={}.toString;function checkOpts(defaults,opts){if(opts!==undefined&&toStr.call(opts)!=="[object Object]")throw new Error("Options should be object or undefined");const merged=Object.assign(defaults,opts);return merged}function wrapConstructor(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}function randomBytes$2(bytesLength=32){if(crypto$1&&typeof crypto$1.getRandomValues==="function"){return crypto$1.getRandomValues(new Uint8Array(bytesLength))}throw new Error("crypto.getRandomValues must be defined")}class HMAC extends Hash{constructor(hash$1,_key){super();this.finished=false;this.destroyed=false;hash(hash$1);const key=toBytes(_key);this.iHash=hash$1.create();if(typeof this.iHash.update!=="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash$1.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad);this.oHash=hash$1.create();for(let i=0;i<pad.length;i++)pad[i]^=54^