gun-eth 1.4.23 → 1.4.24
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/gun-eth.bundle.min.js +2 -0
- package/dist/gun-eth.bundle.min.js.map +1 -0
- package/dist/gun-eth.node.cjs +1351 -0
- package/dist/gun-eth.node.cjs.map +1 -0
- package/dist/gun-eth.node.mjs +1340 -0
- package/dist/gun-eth.node.mjs.map +1 -0
- package/package.json +18 -15
- package/dist/gun-eth.cjs.js +0 -2846
- package/dist/gun-eth.cjs.js.map +0 -1
- package/dist/gun-eth.esm.js +0 -2835
- package/dist/gun-eth.esm.js.map +0 -1
- package/dist/gun-eth.min.js +0 -2
- package/dist/gun-eth.min.js.map +0 -1
@@ -0,0 +1,2 @@
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("gun"),require("gun/sea.js"),require("@noble/hashes/sha3"),require("@noble/curves/secp256k1"),require("../node_modules/ethers/lib.esm/crypto/crypto.js"),require("@noble/hashes/ripemd160"),require("aes-js"),require("@noble/hashes/scrypt"),require("@adraffy/ens-normalize"),require("../node_modules/ethers/lib.esm/utils/base64.js"),require("../node_modules/ethers/lib.esm/utils/geturl.js")):"function"==typeof define&&define.amd?define(["exports","gun","gun/sea.js","@noble/hashes/sha3","@noble/curves/secp256k1","../node_modules/ethers/lib.esm/crypto/crypto","@noble/hashes/ripemd160","aes-js","@noble/hashes/scrypt","@adraffy/ens-normalize","../node_modules/ethers/lib.esm/utils/base64","../node_modules/ethers/lib.esm/utils/geturl"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).GunEth={},t.Gun,t.SEA,t.sha3,t.secp256k1,t.crypto_js,t.ripemd160$1,t.aesJs,t.scrypt$1,t.ensNormalize$1,t.base64_js,t.geturl_js)}(this,(function(t,e,n,r,s,i,a,o,c,l,u,h){"use strict";var d="undefined"!=typeof document?document.currentScript:null;const p="6.13.4";function f(t,e,n){const r=e.split("|").map((t=>t.trim()));for(let n=0;n<r.length;n++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof t===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=t,s}async function g(t){const e=Object.keys(t);return(await Promise.all(e.map((e=>Promise.resolve(t[e]))))).reduce(((t,n,r)=>(t[e[r]]=n,t)),{})}function y(t,e,n){for(let r in e){let s=e[r];const i=n?n[r]:null;i&&f(s,i,r),Object.defineProperty(t,r,{enumerable:!0,value:s,writable:!1})}}function m(t){if(null==t)return"null";if(Array.isArray(t))return"[ "+t.map(m).join(", ")+" ]";if(t instanceof Uint8Array){const e="0123456789abcdef";let n="0x";for(let r=0;r<t.length;r++)n+=e[t[r]>>4],n+=e[15&t[r]];return n}if("object"==typeof t&&"function"==typeof t.toJSON)return m(t.toJSON());switch(typeof t){case"boolean":case"symbol":case"number":return t.toString();case"bigint":return BigInt(t).toString();case"string":return JSON.stringify(t);case"object":{const e=Object.keys(t);return e.sort(),"{ "+e.map((e=>`${m(e)}: ${m(t[e])}`)).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function b(t,e){return t&&t.code===e}function w(t){return b(t,"CALL_EXCEPTION")}function v(t,e,n){let r,s=t;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${m(n)}`);for(const t in n){if("shortMessage"===t)continue;const e=n[t];r.push(t+"="+m(e))}}r.push(`code=${e}`),r.push(`version=${p}`),r.length&&(t+=" ("+r.join(", ")+")")}switch(e){case"INVALID_ARGUMENT":r=new TypeError(t);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(t);break;default:r=new Error(t)}return y(r,{code:e}),n&&Object.assign(r,n),null==r.shortMessage&&y(r,{shortMessage:s}),r}function E(t,e,n,r){if(!t)throw v(e,n,r)}function N(t,e,n,r){E(t,e,"INVALID_ARGUMENT",{argument:n,value:r})}function P(t,e,n){null==n&&(n=""),n&&(n=": "+n),E(t>=e,"missing arguemnt"+n,"MISSING_ARGUMENT",{count:t,expectedCount:e}),E(t<=e,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:t,expectedCount:e})}const k=["NFD","NFC","NFKD","NFKC"].reduce(((t,e)=>{try{if("test"!=="test".normalize(e))throw new Error("bad");if("NFD"===e){const t=String.fromCharCode(233).normalize("NFD");if(t!==String.fromCharCode(101,769))throw new Error("broken")}t.push(e)}catch(t){}return t}),[]);function T(t){E(k.indexOf(t)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:t}})}function R(t,e,n){if(null==n&&(n=""),t!==e){let t=n,e="new";n&&(t+=".",e+=" "+n),E(!1,`private constructor; use ${t}from* methods`,"UNSUPPORTED_OPERATION",{operation:e})}}function A(t,e,n){if(t instanceof Uint8Array)return n?new Uint8Array(t):t;if("string"==typeof t&&t.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)){const e=new Uint8Array((t.length-2)/2);let n=2;for(let r=0;r<e.length;r++)e[r]=parseInt(t.substring(n,n+2),16),n+=2;return e}N(!1,"invalid BytesLike value",e||"value",t)}function O(t,e){return A(t,e,!1)}function I(t,e){return A(t,e,!0)}function S(t,e){return!("string"!=typeof t||!t.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof e||t.length===2+2*e)&&(!0!==e||t.length%2==0))}function x(t){return S(t,!0)||t instanceof Uint8Array}const C="0123456789abcdef";function _(t){const e=O(t);let n="0x";for(let t=0;t<e.length;t++){const r=e[t];n+=C[(240&r)>>4]+C[15&r]}return n}function U(t){return"0x"+t.map((t=>_(t).substring(2))).join("")}function F(t){return S(t,!0)?(t.length-2)/2:O(t).length}function L(t,e,n){const r=O(t);return null!=n&&n>r.length&&E(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),_(r.slice(null==e?0:e,null==n?r.length:n))}function D(t,e,n){const r=O(t);E(e>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),n?s.set(r,e-r.length):s.set(r,0),_(s)}function B(t,e){return D(t,e,!0)}const G=BigInt(0),$=BigInt(1),M=9007199254740991;function j(t,e){let n=H(t,"value");const r=BigInt(q(e,"width")),s=$<<r-$;if(n<G){n=-n,E(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t});return(~n&($<<r)-$)+$}return E(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:t}),n}function K(t,e){const n=V(t,"value"),r=BigInt(q(e,"bits"));return n&($<<r)-$}function H(t,e){switch(typeof t){case"bigint":return t;case"number":return N(Number.isInteger(t),"underflow",e||"value",t),N(t>=-M&&t<=M,"overflow",e||"value",t),BigInt(t);case"string":try{if(""===t)throw new Error("empty string");return"-"===t[0]&&"-"!==t[1]?-BigInt(t.substring(1)):BigInt(t)}catch(n){N(!1,`invalid BigNumberish string: ${n.message}`,e||"value",t)}}N(!1,"invalid BigNumberish value",e||"value",t)}function V(t,e){const n=H(t,e);return E(n>=G,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:t}),n}const z="0123456789abcdef";function J(t){if(t instanceof Uint8Array){let e="0x0";for(const n of t)e+=z[n>>4],e+=z[15&n];return BigInt(e)}return H(t)}function q(t,e){switch(typeof t){case"bigint":return N(t>=-M&&t<=M,"overflow",e||"value",t),Number(t);case"number":return N(Number.isInteger(t),"underflow",e||"value",t),N(t>=-M&&t<=M,"overflow",e||"value",t),t;case"string":try{if(""===t)throw new Error("empty string");return q(BigInt(t),e)}catch(n){N(!1,`invalid numeric string: ${n.message}`,e||"value",t)}}N(!1,"invalid numeric value",e||"value",t)}function W(t,e){let n=V(t,"value").toString(16);if(null==e)n.length%2&&(n="0"+n);else{const r=q(e,"width");for(E(2*r>=n.length,`value exceeds width (${r} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:t});n.length<2*r;)n="0"+n}return"0x"+n}function Y(t){const e=V(t,"value");if(e===G)return new Uint8Array([]);let n=e.toString(16);n.length%2&&(n="0"+n);const r=new Uint8Array(n.length/2);for(let t=0;t<r.length;t++){const e=2*t;r[t]=parseInt(n.substring(e,e+2),16)}return r}function X(t){let e=_(x(t)?t:Y(t)).substring(2);for(;e.startsWith("0");)e=e.substring(1);return""===e&&(e="0"),"0x"+e}const Z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Q=null;function tt(t){if(null==Q){Q={};for(let t=0;t<58;t++)Q[Z[t]]=BigInt(t)}const e=Q[t];return N(null!=e,"invalid base58 value","letter",t),e}const et=BigInt(0),nt=BigInt(58);function rt(t){const e=O(t);let n=J(e),r="";for(;n;)r=Z[Number(n%nt)]+r,n/=nt;for(let t=0;t<e.length&&!e[t];t++)r=Z[0]+r;return r}class st{filter;emitter;#t;constructor(t,e,n){this.#t=e,y(this,{emitter:t,filter:n})}async removeListener(){null!=this.#t&&await this.emitter.off(this.filter,this.#t)}}function it(t,e,n,r,s){if("BAD_PREFIX"===t||"UNEXPECTED_CONTINUE"===t){let t=0;for(let r=e+1;r<n.length&&n[r]>>6==2;r++)t++;return t}return"OVERRUN"===t?n.length-e-1:0}const at=Object.freeze({error:function(t,e,n,r,s){N(!1,`invalid codepoint at offset ${e}; ${t}`,"bytes",n)},ignore:it,replace:function(t,e,n,r,s){return"OVERLONG"===t?(N("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),it(t,e,n))}});function ot(t,e){N("string"==typeof t,"invalid string value","str",t),null!=e&&(T(e),t=t.normalize(e));let n=[];for(let e=0;e<t.length;e++){const r=t.charCodeAt(e);if(r<128)n.push(r);else if(r<2048)n.push(r>>6|192),n.push(63&r|128);else if(55296==(64512&r)){e++;const s=t.charCodeAt(e);N(e<t.length&&56320==(64512&s),"invalid surrogate pair","str",t);const i=65536+((1023&r)<<10)+(1023&s);n.push(i>>18|240),n.push(i>>12&63|128),n.push(i>>6&63|128),n.push(63&i|128)}else n.push(r>>12|224),n.push(r>>6&63|128),n.push(63&r|128)}return new Uint8Array(n)}function ct(t,e){return n=function(t,e){null==e&&(e=at.error);const n=O(t,"bytes"),r=[];let s=0;for(;s<n.length;){const t=n[s++];if(!(t>>7)){r.push(t);continue}let i=null,a=null;if(192==(224&t))i=1,a=127;else if(224==(240&t))i=2,a=2047;else{if(240!=(248&t)){s+=e(128==(192&t)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}i=3,a=65535}if(s-1+i>=n.length){s+=e("OVERRUN",s-1,n,r);continue}let o=t&(1<<8-i-1)-1;for(let t=0;t<i;t++){let t=n[s];if(128!=(192&t)){s+=e("MISSING_CONTINUE",s,n,r),o=null;break}o=o<<6|63&t,s++}null!==o&&(o>1114111?s+=e("OUT_OF_RANGE",s-1-i,n,r,o):o>=55296&&o<=57343?s+=e("UTF16_SURROGATE",s-1-i,n,r,o):o<=a?s+=e("OVERLONG",s-1-i,n,r,o):r.push(o))}return r}(t,e),n.map((t=>t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10&1023),56320+(1023&t))))).join("");var n}let lt=h.createGetUrl();const ut=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),ht=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let dt=!1;async function pt(t,e){try{const e=t.match(ut);if(!e)throw new Error("invalid data");return new vt(200,"OK",{"content-type":e[1]||"text/plain"},e[2]?u.decodeBase64(e[3]):ot(e[3].replace(/%([0-9a-f][0-9a-f])/gi,((t,e)=>String.fromCharCode(parseInt(e,16))))))}catch(e){return new vt(599,"BAD REQUEST (invalid data: URI)",{},null,new wt(t))}}function ft(t){return async function(e,n){try{const n=e.match(ht);if(!n)throw new Error("invalid link");return new wt(`${t}${n[2]}`)}catch(t){return new vt(599,"BAD REQUEST (invalid IPFS URI)",{},null,new wt(e))}}}const gt={data:pt,ipfs:ft("https://gateway.ipfs.io/ipfs/")},yt=new WeakMap;class mt{#e;#n;constructor(t){this.#e=[],this.#n=!1,yt.set(t,(()=>{if(!this.#n){this.#n=!0;for(const t of this.#e)setTimeout((()=>{t()}),0);this.#e=[]}}))}addListener(t){E(!this.#n,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),this.#e.push(t)}get cancelled(){return this.#n}checkSignal(){E(!this.cancelled,"cancelled","CANCELLED",{})}}function bt(t){if(null==t)throw new Error("missing signal; should not happen");return t.checkSignal(),t}class wt{#r;#s;#i;#a;#o;#c;#l;#u;#h;#d;#p;#f;#g;#y;#m;get url(){return this.#c}set url(t){this.#c=String(t)}get body(){return null==this.#l?null:new Uint8Array(this.#l)}set body(t){if(null==t)this.#l=void 0,this.#u=void 0;else if("string"==typeof t)this.#l=ot(t),this.#u="text/plain";else if(t instanceof Uint8Array)this.#l=t,this.#u="application/octet-stream";else{if("object"!=typeof t)throw new Error("invalid body");this.#l=ot(JSON.stringify(t)),this.#u="application/json"}}hasBody(){return null!=this.#l}get method(){return this.#a?this.#a:this.hasBody()?"POST":"GET"}set method(t){null==t&&(t=""),this.#a=String(t).toUpperCase()}get headers(){const t=Object.assign({},this.#i);return this.#h&&(t.authorization=`Basic ${u.encodeBase64(ot(this.#h))}`),this.allowGzip&&(t["accept-encoding"]="gzip"),null==t["content-type"]&&this.#u&&(t["content-type"]=this.#u),this.body&&(t["content-length"]=String(this.body.length)),t}getHeader(t){return this.headers[t.toLowerCase()]}setHeader(t,e){this.#i[String(t).toLowerCase()]=String(e)}clearHeaders(){this.#i={}}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#h||null}setCredentials(t,e){N(!t.match(/:/),"invalid basic authentication username","username","[REDACTED]"),this.#h=`${t}:${e}`}get allowGzip(){return this.#s}set allowGzip(t){this.#s=!!t}get allowInsecureAuthentication(){return!!this.#r}set allowInsecureAuthentication(t){this.#r=!!t}get timeout(){return this.#o}set timeout(t){N(t>=0,"timeout must be non-zero","timeout",t),this.#o=t}get preflightFunc(){return this.#d||null}set preflightFunc(t){this.#d=t}get processFunc(){return this.#p||null}set processFunc(t){this.#p=t}get retryFunc(){return this.#f||null}set retryFunc(t){this.#f=t}get getUrlFunc(){return this.#m||lt}set getUrlFunc(t){this.#m=t}constructor(t){this.#c=String(t),this.#r=!1,this.#s=!0,this.#i={},this.#a="",this.#o=3e5,this.#y={slotInterval:250,maxAttempts:12},this.#m=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#l?_(this.#l):"null"}>`}setThrottleParams(t){null!=t.slotInterval&&(this.#y.slotInterval=t.slotInterval),null!=t.maxAttempts&&(this.#y.maxAttempts=t.maxAttempts)}async#b(t,e,n,r,s){if(t>=this.#y.maxAttempts)return s.makeServerError("exceeded maximum retry limit");E(Et()<=e,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:r}),n>0&&await function(t){return new Promise((e=>setTimeout(e,t)))}(n);let i=this.clone();const a=(i.url.split(":")[0]||"").toLowerCase();if(a in gt){const t=await gt[a](i.url,bt(r.#g));if(t instanceof vt){let e=t;if(this.processFunc){bt(r.#g);try{e=await this.processFunc(i,e)}catch(t){null!=t.throttle&&"number"==typeof t.stall||e.makeServerError("error in post-processing function",t).assertOk()}}return e}i=t}this.preflightFunc&&(i=await this.preflightFunc(i));const o=await this.getUrlFunc(i,bt(r.#g));let c=new vt(o.statusCode,o.statusMessage,o.headers,o.body,r);if(301===c.statusCode||302===c.statusCode){try{const n=c.headers.location||"";return i.redirect(n).#b(t+1,e,0,r,c)}catch(t){}return c}if(429===c.statusCode&&(null==this.retryFunc||await this.retryFunc(i,c,t))){const n=c.headers["retry-after"];let s=this.#y.slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return"string"==typeof n&&n.match(/^[1-9][0-9]*$/)&&(s=parseInt(n)),i.clone().#b(t+1,e,s,r,c)}if(this.processFunc){bt(r.#g);try{c=await this.processFunc(i,c)}catch(n){null!=n.throttle&&"number"==typeof n.stall||c.makeServerError("error in post-processing function",n).assertOk();let s=this.#y.slotInterval*Math.trunc(Math.random()*Math.pow(2,t));return n.stall>=0&&(s=n.stall),i.clone().#b(t+1,e,s,r,c)}}return c}send(){return E(null==this.#g,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),this.#g=new mt(this),this.#b(0,Et()+this.timeout,0,this,new vt(0,"",{},null,this))}cancel(){E(null!=this.#g,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const t=yt.get(this);if(!t)throw new Error("missing signal; should not happen");t()}redirect(t){const e=this.url.split(":")[0].toLowerCase(),n=t.split(":")[0].toLowerCase();E("GET"===this.method&&("https"!==e||"http"!==n)&&t.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(t)})`});const r=new wt(t);return r.method="GET",r.allowGzip=this.allowGzip,r.timeout=this.timeout,r.#i=Object.assign({},this.#i),this.#l&&(r.#l=new Uint8Array(this.#l)),r.#u=this.#u,r}clone(){const t=new wt(this.url);return t.#a=this.#a,this.#l&&(t.#l=this.#l),t.#u=this.#u,t.#i=Object.assign({},this.#i),t.#h=this.#h,this.allowGzip&&(t.allowGzip=!0),t.timeout=this.timeout,this.allowInsecureAuthentication&&(t.allowInsecureAuthentication=!0),t.#d=this.#d,t.#p=this.#p,t.#f=this.#f,t.#y=Object.assign({},this.#y),t.#m=this.#m,t}static lockConfig(){dt=!0}static getGateway(t){return gt[t.toLowerCase()]||null}static registerGateway(t,e){if("http"===(t=t.toLowerCase())||"https"===t)throw new Error(`cannot intercept ${t}; use registerGetUrl`);if(dt)throw new Error("gateways locked");gt[t]=e}static registerGetUrl(t){if(dt)throw new Error("gateways locked");lt=t}static createGetUrlFunc(t){return h.createGetUrl(t)}static createDataGateway(){return pt}static createIpfsGatewayFunc(t){return ft(t)}}class vt{#w;#v;#i;#l;#E;#N;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#l?_(this.#l):"null"}>`}get statusCode(){return this.#w}get statusMessage(){return this.#v}get headers(){return Object.assign({},this.#i)}get body(){return null==this.#l?null:new Uint8Array(this.#l)}get bodyText(){try{return null==this.#l?"":ct(this.#l)}catch(t){E(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(t){E(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const t=this.headers,e=Object.keys(t);let n=0;return{next:()=>{if(n<e.length){const r=e[n++];return{value:[r,t[r]],done:!1}}return{value:void 0,done:!0}}}}constructor(t,e,n,r,s){this.#w=t,this.#v=e,this.#i=Object.keys(n).reduce(((t,e)=>(t[e.toLowerCase()]=String(n[e]),t)),{}),this.#l=null==r?null:new Uint8Array(r),this.#E=s||null,this.#N={message:""}}makeServerError(t,e){let n;n=t?`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${t})`:`CLIENT ESCALATED SERVER ERROR (${t=`${this.statusCode} ${this.statusMessage}`})`;const r=new vt(599,n,this.headers,this.body,this.#E||void 0);return r.#N={message:t,error:e},r}throwThrottleError(t,e){null==e?e=-1:N(Number.isInteger(e)&&e>=0,"invalid stall timeout","stall",e);const n=new Error(t||"throttling requests");throw y(n,{stall:e,throttle:!0}),n}getHeader(t){return this.headers[t.toLowerCase()]}hasBody(){return null!=this.#l}get request(){return this.#E}ok(){return""===this.#N.message&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:t,error:e}=this.#N;""===t&&(t=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{this.#l&&(r=ct(this.#l))}catch(t){}E(!1,t,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:e,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}function Et(){return(new Date).getTime()}function Nt(t){let e=t.toString(16);for(;e.length<2;)e="0"+e;return"0x"+e}function Pt(t,e,n){let r=0;for(let s=0;s<n;s++)r=256*r+t[e+s];return r}function kt(t,e,n,r){const s=[];for(;n<e+1+r;){const i=Tt(t,n);s.push(i.result),E((n+=i.consumed)<=e+1+r,"child data too short","BUFFER_OVERRUN",{buffer:t,length:r,offset:e})}return{consumed:1+r,result:s}}function Tt(t,e){E(0!==t.length,"data too short","BUFFER_OVERRUN",{buffer:t,length:0,offset:1});const n=e=>{E(e<=t.length,"data short segment too short","BUFFER_OVERRUN",{buffer:t,length:t.length,offset:e})};if(t[e]>=248){const r=t[e]-247;n(e+1+r);const s=Pt(t,e+1,r);return n(e+1+r+s),kt(t,e,e+1+r,r+s)}if(t[e]>=192){const r=t[e]-192;return n(e+1+r),kt(t,e,e+1,r)}if(t[e]>=184){const r=t[e]-183;n(e+1+r);const s=Pt(t,e+1,r);n(e+1+r+s);return{consumed:1+r+s,result:_(t.slice(e+1+r,e+1+r+s))}}if(t[e]>=128){const r=t[e]-128;n(e+1+r);return{consumed:1+r,result:_(t.slice(e+1,e+1+r))}}return{consumed:1,result:Nt(t[e])}}function Rt(t){const e=O(t,"data"),n=Tt(e,0);return N(n.consumed===e.length,"unexpected junk after rlp payload","data",t),n.result}function At(t){const e=[];for(;t;)e.unshift(255&t),t>>=8;return e}function Ot(t){if(Array.isArray(t)){let e=[];if(t.forEach((function(t){e=e.concat(Ot(t))})),e.length<=55)return e.unshift(192+e.length),e;const n=At(e.length);return n.unshift(247+n.length),n.concat(e)}const e=Array.prototype.slice.call(O(t,"object"));if(1===e.length&&e[0]<=127)return e;if(e.length<=55)return e.unshift(128+e.length),e;const n=At(e.length);return n.unshift(183+n.length),n.concat(e)}const It="0123456789abcdef";function St(t){let e="0x";for(const n of Ot(t))e+=It[n>>4],e+=It[15&n];return e}function xt(t){const e=O(t,"randomBytes");e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=_(e);return[n.substring(2,10),n.substring(10,14),n.substring(14,18),n.substring(18,22),n.substring(22,34)].join("-")}const Ct=32,_t=new Uint8Array(Ct),Ut=["then"],Ft={},Lt=new WeakMap;function Dt(t){return Lt.get(t)}function Bt(t,e){Lt.set(t,e)}function Gt(t,e){const n=new Error(`deferred error during ABI decoding triggered accessing ${t}`);throw n.error=e,n}function $t(t,e,n){return t.indexOf(null)>=0?e.map(((t,e)=>t instanceof Mt?$t(Dt(t),t,n):t)):t.reduce(((t,r,s)=>{let i=e.getValue(r);return r in t||(n&&i instanceof Mt&&(i=$t(Dt(i),i,n)),t[r]=i),t}),{})}class Mt extends Array{#P;constructor(...t){const e=t[0];let n=t[1],r=(t[2]||[]).slice(),s=!0;e!==Ft&&(n=t,r=[],s=!1),super(n.length),n.forEach(((t,e)=>{this[e]=t}));const i=r.reduce(((t,e)=>("string"==typeof e&&t.set(e,(t.get(e)||0)+1),t)),new Map);if(Bt(this,Object.freeze(n.map(((t,e)=>{const n=r[e];return null!=n&&1===i.get(n)?n:null})))),this.#P=[],null==this.#P&&this.#P,!s)return;Object.freeze(this);const a=new Proxy(this,{get:(t,e,n)=>{if("string"==typeof e){if(e.match(/^[0-9]+$/)){const n=q(e,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=t[n];return r instanceof Error&&Gt(`index ${n}`,r),r}if(Ut.indexOf(e)>=0)return Reflect.get(t,e,n);const r=t[e];if(r instanceof Function)return function(...e){return r.apply(this===n?t:this,e)};if(!(e in t))return t.getValue.apply(this===n?t:this,[e])}return Reflect.get(t,e,n)}});return Bt(a,Dt(this)),a}toArray(t){const e=[];return this.forEach(((n,r)=>{n instanceof Error&&Gt(`index ${r}`,n),t&&n instanceof Mt&&(n=n.toArray(t)),e.push(n)})),e}toObject(t){const e=Dt(this);return e.reduce(((n,r,s)=>(E(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),$t(e,this,t))),{})}slice(t,e){null==t&&(t=0),t<0&&(t+=this.length)<0&&(t=0),null==e&&(e=this.length),e<0&&(e+=this.length)<0&&(e=0),e>this.length&&(e=this.length);const n=Dt(this),r=[],s=[];for(let i=t;i<e;i++)r.push(this[i]),s.push(n[i]);return new Mt(Ft,r,s)}filter(t,e){const n=Dt(this),r=[],s=[];for(let i=0;i<this.length;i++){const a=this[i];a instanceof Error&&Gt(`index ${i}`,a),t.call(e,a,i,this)&&(r.push(a),s.push(n[i]))}return new Mt(Ft,r,s)}map(t,e){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&Gt(`index ${r}`,s),n.push(t.call(e,s,r,this))}return n}getValue(t){const e=Dt(this).indexOf(t);if(-1===e)return;const n=this[e];return n instanceof Error&&Gt(`property ${JSON.stringify(t)}`,n.error),n}static fromItems(t,e){return new Mt(Ft,t,e)}}function jt(t){let e=Y(t);return E(e.length<=Ct,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:Ct,offset:e.length}),e.length!==Ct&&(e=I(U([_t.slice(e.length%Ct),e]))),e}class Kt{name;type;localName;dynamic;constructor(t,e,n,r){y(this,{name:t,type:e,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(t,e){N(!1,t,this.localName,e)}}class Ht{#k;#T;constructor(){this.#k=[],this.#T=0}get data(){return U(this.#k)}get length(){return this.#T}#R(t){return this.#k.push(t),this.#T+=t.length,t.length}appendWriter(t){return this.#R(I(t.data))}writeBytes(t){let e=I(t);const n=e.length%Ct;return n&&(e=I(U([e,_t.slice(n)]))),this.#R(e)}writeValue(t){return this.#R(jt(t))}writeUpdatableValue(){const t=this.#k.length;return this.#k.push(_t),this.#T+=Ct,e=>{this.#k[t]=jt(e)}}}class Vt{allowLoose;#k;#A;#O;#I;#S;constructor(t,e,n){y(this,{allowLoose:!!e}),this.#k=I(t),this.#O=0,this.#I=null,this.#S=null!=n?n:1024,this.#A=0}get data(){return _(this.#k)}get dataLength(){return this.#k.length}get consumed(){return this.#A}get bytes(){return new Uint8Array(this.#k)}#x(t){if(this.#I)return this.#I.#x(t);this.#O+=t,E(this.#S<1||this.#O<=this.#S*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#S} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:I(this.#k),offset:this.#A,length:t,info:{bytesRead:this.#O,dataLength:this.dataLength}})}#C(t,e,n){let r=Math.ceil(e/Ct)*Ct;return this.#A+r>this.#k.length&&(this.allowLoose&&n&&this.#A+e<=this.#k.length?r=e:E(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:I(this.#k),length:this.#k.length,offset:this.#A+r})),this.#k.slice(this.#A,this.#A+r)}subReader(t){const e=new Vt(this.#k.slice(this.#A+t),this.allowLoose,this.#S);return e.#I=this,e}readBytes(t,e){let n=this.#C(0,t,!!e);return this.#x(t),this.#A+=n.length,n.slice(0,t)}readValue(){return J(this.readBytes(Ct))}readIndex(){return q(J(this.readBytes(Ct)))}}let zt=!1;const Jt=function(t,e,n){return i.createHmac(t,e).update(n).digest()};let qt=Jt;function Wt(t,e,n){const r=O(e,"key"),s=O(n,"data");return _(qt(t,r,s))}Wt._=Jt,Wt.lock=function(){zt=!0},Wt.register=function(t){if(zt)throw new Error("computeHmac is locked");qt=t},Object.freeze(Wt);let Yt=!1;const Xt=function(t){return r.keccak_256(t)};let Zt=Xt;function Qt(t){const e=O(t,"data");return _(Zt(e))}Qt._=Xt,Qt.lock=function(){Yt=!0},Qt.register=function(t){if(Yt)throw new TypeError("keccak256 is locked");Zt=t},Object.freeze(Qt);let te=!1;const ee=function(t){return a.ripemd160(t)};let ne=ee;function re(t){const e=O(t,"data");return _(ne(e))}re._=ee,re.lock=function(){te=!0},re.register=function(t){if(te)throw new TypeError("ripemd160 is locked");ne=t},Object.freeze(re);let se=!1;const ie=function(t,e,n,r,s){return i.pbkdf2Sync(t,e,n,r,s)};let ae=ie;function oe(t,e,n,r,s){const i=O(t,"password"),a=O(e,"salt");return _(ae(i,a,n,r,s))}oe._=ie,oe.lock=function(){se=!0},oe.register=function(t){if(se)throw new Error("pbkdf2 is locked");ae=t},Object.freeze(oe);let ce=!1;const le=function(t){return new Uint8Array(i.randomBytes(t))};let ue=le;function he(t){return ue(t)}he._=le,he.lock=function(){ce=!0},he.register=function(t){if(ce)throw new Error("randomBytes is locked");ue=t},Object.freeze(he);let de=!1,pe=!1;const fe=async function(t,e,n,r,s,i,a){return await c.scryptAsync(t,e,{N:n,r:r,p:s,dkLen:i,onProgress:a})},ge=function(t,e,n,r,s,i){return c.scrypt(t,e,{N:n,r:r,p:s,dkLen:i})};let ye=fe,me=ge;async function be(t,e,n,r,s,i,a){const o=O(t,"passwd"),c=O(e,"salt");return _(await ye(o,c,n,r,s,i,a))}function we(t,e,n,r,s,i){const a=O(t,"passwd"),o=O(e,"salt");return _(me(a,o,n,r,s,i))}be._=fe,be.lock=function(){pe=!0},be.register=function(t){if(pe)throw new Error("scrypt is locked");ye=t},Object.freeze(be),we._=ge,we.lock=function(){de=!0},we.register=function(t){if(de)throw new Error("scryptSync is locked");me=t},Object.freeze(we);const ve=function(t){return i.createHash("sha256").update(t).digest()};let Ee=ve,Ne=!1;function Pe(t){const e=O(t,"data");return _(Ee(e))}Pe._=ve,Pe.lock=function(){Ne=!0},Pe.register=function(t){if(Ne)throw new Error("sha256 is locked");Ee=t},Object.freeze(Pe),Object.freeze(Pe);const ke="0x0000000000000000000000000000000000000000",Te="0x0000000000000000000000000000000000000000000000000000000000000000",Re=BigInt(0),Ae=BigInt(1),Oe=BigInt(2),Ie=BigInt(27),Se=BigInt(28),xe=BigInt(35),Ce={};function _e(t){return B(Y(t),32)}class Ue{#_;#U;#F;#L;get r(){return this.#_}set r(t){N(32===F(t),"invalid r","value",t),this.#_=_(t)}get s(){return this.#U}set s(t){N(32===F(t),"invalid s","value",t);const e=_(t);N(parseInt(e.substring(0,3))<8,"non-canonical s","value",e),this.#U=e}get v(){return this.#F}set v(t){const e=q(t,"value");N(27===e||28===e,"invalid v","v",t),this.#F=e}get networkV(){return this.#L}get legacyChainId(){const t=this.networkV;return null==t?null:Ue.getChainId(t)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const t=O(this.s);return this.yParity&&(t[0]|=128),_(t)}get compactSerialized(){return U([this.r,this.yParityAndS])}get serialized(){return U([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(t,e,n,r){R(t,Ce,"Signature"),this.#_=e,this.#U=n,this.#F=r,this.#L=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const t=new Ue(Ce,this.r,this.s,this.v);return this.networkV&&(t.#L=this.networkV),t}toJSON(){const t=this.networkV;return{_type:"signature",networkV:null!=t?t.toString():null,r:this.r,s:this.s,v:this.v}}static getChainId(t){const e=H(t,"v");return e==Ie||e==Se?Re:(N(e>=xe,"invalid EIP-155 v","v",t),(e-xe)/Oe)}static getChainIdV(t,e){return H(t)*Oe+BigInt(35+e-27)}static getNormalizedV(t){const e=H(t);return e===Re||e===Ie?27:e===Ae||e===Se?28:(N(e>=xe,"invalid v","v",t),e&Ae?27:28)}static from(t){function e(e,n){N(e,n,"signature",t)}if(null==t)return new Ue(Ce,Te,Te,27);if("string"==typeof t){const n=O(t,"signature");if(64===n.length){const t=_(n.slice(0,32)),e=n.slice(32,64),r=128&e[0]?28:27;return e[0]&=127,new Ue(Ce,t,_(e),r)}if(65===n.length){const t=_(n.slice(0,32)),r=n.slice(32,64);e(!(128&r[0]),"non-canonical s");const s=Ue.getNormalizedV(n[64]);return new Ue(Ce,t,_(r),s)}e(!1,"invalid raw signature length")}if(t instanceof Ue)return t.clone();const n=t.r;e(null!=n,"missing r");const r=_e(n),s=function(t,n){if(null!=t)return _e(t);if(null!=n){e(S(n,32),"invalid yParityAndS");const t=O(n);return t[0]&=127,_(t)}e(!1,"missing s")}(t.s,t.yParityAndS);e(!(128&O(s)[0]),"non-canonical s");const{networkV:i,v:a}=function(t,n,r){if(null!=t){const e=H(t);return{networkV:e>=xe?e:void 0,v:Ue.getNormalizedV(e)}}if(null!=n)return e(S(n,32),"invalid yParityAndS"),{v:128&O(n)[0]?28:27};if(null!=r){switch(q(r,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}e(!1,"invalid yParity")}e(!1,"missing v")}(t.v,t.yParityAndS,t.yParity),o=new Ue(Ce,r,s,a);return i&&(o.#L=i),e(null==t.yParity||q(t.yParity,"sig.yParity")===o.yParity,"yParity mismatch"),e(null==t.yParityAndS||t.yParityAndS===o.yParityAndS,"yParityAndS mismatch"),o}}class Fe{#D;constructor(t){N(32===F(t),"invalid private key","privateKey","[REDACTED]"),this.#D=_(t)}get privateKey(){return this.#D}get publicKey(){return Fe.computePublicKey(this.#D)}get compressedPublicKey(){return Fe.computePublicKey(this.#D,!0)}sign(t){N(32===F(t),"invalid digest length","digest",t);const e=s.secp256k1.sign(I(t),I(this.#D),{lowS:!0});return Ue.from({r:W(e.r,32),s:W(e.s,32),v:e.recovery?28:27})}computeSharedSecret(t){const e=Fe.computePublicKey(t);return _(s.secp256k1.getSharedSecret(I(this.#D),O(e),!1))}static computePublicKey(t,e){let n=O(t,"key");if(32===n.length){return _(s.secp256k1.getPublicKey(n,!!e))}if(64===n.length){const t=new Uint8Array(65);t[0]=4,t.set(n,1),n=t}return _(s.secp256k1.ProjectivePoint.fromHex(n).toRawBytes(e))}static recoverPublicKey(t,e){N(32===F(t),"invalid digest length","digest",t);const n=Ue.from(e);let r=s.secp256k1.Signature.fromCompact(I(U([n.r,n.s])));r=r.addRecoveryBit(n.yParity);const i=r.recoverPublicKey(I(t));return N(null!=i,"invalid signautre for digest","signature",e),"0x"+i.toHex(!1)}static addPoints(t,e,n){const r=s.secp256k1.ProjectivePoint.fromHex(Fe.computePublicKey(t).substring(2)),i=s.secp256k1.ProjectivePoint.fromHex(Fe.computePublicKey(e).substring(2));return"0x"+r.add(i).toHex(!!n)}}const Le=BigInt(0),De=BigInt(36);function Be(t){const e=(t=t.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let t=0;t<40;t++)n[t]=e[t].charCodeAt(0);const r=O(Qt(n));for(let t=0;t<40;t+=2)r[t>>1]>>4>=8&&(e[t]=e[t].toUpperCase()),(15&r[t>>1])>=8&&(e[t+1]=e[t+1].toUpperCase());return"0x"+e.join("")}const Ge={};for(let t=0;t<10;t++)Ge[String(t)]=String(t);for(let t=0;t<26;t++)Ge[String.fromCharCode(65+t)]=String(10+t);const $e=function(){const t={};for(let e=0;e<36;e++){t["0123456789abcdefghijklmnopqrstuvwxyz"[e]]=BigInt(e)}return t}();function Me(t){if(N("string"==typeof t,"invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/)){t.startsWith("0x")||(t="0x"+t);const e=Be(t);return N(!t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===t,"bad address checksum","address",t),e}if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){N(t.substring(2,4)===function(t){let e=(t=(t=t.toUpperCase()).substring(4)+t.substring(0,2)+"00").split("").map((t=>Ge[t])).join("");for(;e.length>=15;){let t=e.substring(0,15);e=parseInt(t,10)%97+e.substring(t.length)}let n=String(98-parseInt(e,10)%97);for(;n.length<2;)n="0"+n;return n}(t),"bad icap checksum","address",t);let e=function(t){t=t.toLowerCase();let e=Le;for(let n=0;n<t.length;n++)e=e*De+$e[t[n]];return e}(t.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return Be("0x"+e)}N(!1,"invalid address","address",t)}function je(t){return t&&"function"==typeof t.getAddress}async function Ke(t,e){const n=await e;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(E("string"!=typeof t,"unconfigured name","UNCONFIGURED_NAME",{value:t}),N(!1,"invalid AddressLike value; did not resolve to a value address","target",t)),Me(n)}function He(t,e){return"string"==typeof t?t.match(/^0x[0-9a-f]{40}$/i)?Me(t):(E(null!=e,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Ke(t,e.resolveName(t))):je(t)?Ke(t,t.getAddress()):t&&"function"==typeof t.then?Ke(t,t):void N(!1,"unsupported addressable value","target",t)}const Ve={};function ze(t,e){let n=!1;return e<0&&(n=!0,e*=-1),new We(Ve,`${n?"":"u"}int${e}`,t,{signed:n,width:e})}function Je(t,e){return new We(Ve,`bytes${e||""}`,t,{size:e})}const qe=Symbol.for("_ethers_typed");class We{type;value;#B;_typedSymbol;constructor(t,e,n,r){null==r&&(r=null),R(Ve,t,"Typed"),y(this,{_typedSymbol:qe,type:e,value:n}),this.#B=r,this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map((t=>t.format())).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return this.#B}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===this.#B?-1:!1===this.#B?this.value.length:null}static from(t,e){return new We(Ve,t,e)}static uint8(t){return ze(t,8)}static uint16(t){return ze(t,16)}static uint24(t){return ze(t,24)}static uint32(t){return ze(t,32)}static uint40(t){return ze(t,40)}static uint48(t){return ze(t,48)}static uint56(t){return ze(t,56)}static uint64(t){return ze(t,64)}static uint72(t){return ze(t,72)}static uint80(t){return ze(t,80)}static uint88(t){return ze(t,88)}static uint96(t){return ze(t,96)}static uint104(t){return ze(t,104)}static uint112(t){return ze(t,112)}static uint120(t){return ze(t,120)}static uint128(t){return ze(t,128)}static uint136(t){return ze(t,136)}static uint144(t){return ze(t,144)}static uint152(t){return ze(t,152)}static uint160(t){return ze(t,160)}static uint168(t){return ze(t,168)}static uint176(t){return ze(t,176)}static uint184(t){return ze(t,184)}static uint192(t){return ze(t,192)}static uint200(t){return ze(t,200)}static uint208(t){return ze(t,208)}static uint216(t){return ze(t,216)}static uint224(t){return ze(t,224)}static uint232(t){return ze(t,232)}static uint240(t){return ze(t,240)}static uint248(t){return ze(t,248)}static uint256(t){return ze(t,256)}static uint(t){return ze(t,256)}static int8(t){return ze(t,-8)}static int16(t){return ze(t,-16)}static int24(t){return ze(t,-24)}static int32(t){return ze(t,-32)}static int40(t){return ze(t,-40)}static int48(t){return ze(t,-48)}static int56(t){return ze(t,-56)}static int64(t){return ze(t,-64)}static int72(t){return ze(t,-72)}static int80(t){return ze(t,-80)}static int88(t){return ze(t,-88)}static int96(t){return ze(t,-96)}static int104(t){return ze(t,-104)}static int112(t){return ze(t,-112)}static int120(t){return ze(t,-120)}static int128(t){return ze(t,-128)}static int136(t){return ze(t,-136)}static int144(t){return ze(t,-144)}static int152(t){return ze(t,-152)}static int160(t){return ze(t,-160)}static int168(t){return ze(t,-168)}static int176(t){return ze(t,-176)}static int184(t){return ze(t,-184)}static int192(t){return ze(t,-192)}static int200(t){return ze(t,-200)}static int208(t){return ze(t,-208)}static int216(t){return ze(t,-216)}static int224(t){return ze(t,-224)}static int232(t){return ze(t,-232)}static int240(t){return ze(t,-240)}static int248(t){return ze(t,-248)}static int256(t){return ze(t,-256)}static int(t){return ze(t,-256)}static bytes1(t){return Je(t,1)}static bytes2(t){return Je(t,2)}static bytes3(t){return Je(t,3)}static bytes4(t){return Je(t,4)}static bytes5(t){return Je(t,5)}static bytes6(t){return Je(t,6)}static bytes7(t){return Je(t,7)}static bytes8(t){return Je(t,8)}static bytes9(t){return Je(t,9)}static bytes10(t){return Je(t,10)}static bytes11(t){return Je(t,11)}static bytes12(t){return Je(t,12)}static bytes13(t){return Je(t,13)}static bytes14(t){return Je(t,14)}static bytes15(t){return Je(t,15)}static bytes16(t){return Je(t,16)}static bytes17(t){return Je(t,17)}static bytes18(t){return Je(t,18)}static bytes19(t){return Je(t,19)}static bytes20(t){return Je(t,20)}static bytes21(t){return Je(t,21)}static bytes22(t){return Je(t,22)}static bytes23(t){return Je(t,23)}static bytes24(t){return Je(t,24)}static bytes25(t){return Je(t,25)}static bytes26(t){return Je(t,26)}static bytes27(t){return Je(t,27)}static bytes28(t){return Je(t,28)}static bytes29(t){return Je(t,29)}static bytes30(t){return Je(t,30)}static bytes31(t){return Je(t,31)}static bytes32(t){return Je(t,32)}static address(t){return new We(Ve,"address",t)}static bool(t){return new We(Ve,"bool",!!t)}static bytes(t){return new We(Ve,"bytes",t)}static string(t){return new We(Ve,"string",t)}static array(t,e){throw new Error("not implemented yet")}static tuple(t,e){throw new Error("not implemented yet")}static overrides(t){return new We(Ve,"overrides",Object.assign({},t))}static isTyped(t){return t&&"object"==typeof t&&"_typedSymbol"in t&&t._typedSymbol===qe}static dereference(t,e){if(We.isTyped(t)){if(t.type!==e)throw new Error(`invalid type: expecetd ${e}, got ${t.type}`);return t.value}return t}}class Ye extends Kt{constructor(t){super("address","address",t,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(t,e){let n=We.dereference(e,"string");try{n=Me(n)}catch(t){return this._throwError(t.message,e)}return t.writeValue(n)}decode(t){return Me(W(t.readValue(),20))}}class Xe extends Kt{coder;constructor(t){super(t.name,t.type,"_",t.dynamic),this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,e){return this.coder.encode(t,e)}decode(t){return this.coder.decode(t)}}function Ze(t,e,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let t={};r=e.map((e=>{const r=e.localName;return E(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),E(!t[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:e},value:n}),t[r]=!0,n[r]}))}else N(!1,"invalid tuple value","tuple",n);N(e.length===r.length,"types/value length mismatch","tuple",n);let s=new Ht,i=new Ht,a=[];e.forEach(((t,e)=>{let n=r[e];if(t.dynamic){let e=i.length;t.encode(i,n);let r=s.writeUpdatableValue();a.push((t=>{r(t+e)}))}else t.encode(s,n)})),a.forEach((t=>{t(s.length)}));let o=t.appendWriter(s);return o+=t.appendWriter(i),o}function Qe(t,e){let n=[],r=[],s=t.subReader(0);return e.forEach((e=>{let i=null;if(e.dynamic){let n=t.readIndex(),r=s.subReader(n);try{i=e.decode(r)}catch(t){if(b(t,"BUFFER_OVERRUN"))throw t;i=t,i.baseType=e.name,i.name=e.localName,i.type=e.type}}else try{i=e.decode(t)}catch(t){if(b(t,"BUFFER_OVERRUN"))throw t;i=t,i.baseType=e.name,i.name=e.localName,i.type=e.type}if(null==i)throw new Error("investigate");n.push(i),r.push(e.localName||null)})),Mt.fromItems(n,r)}class tn extends Kt{coder;length;constructor(t,e,n){super("array",t.type+"["+(e>=0?e:"")+"]",n,-1===e||t.dynamic),y(this,{coder:t,length:e})}defaultValue(){const t=this.coder.defaultValue(),e=[];for(let n=0;n<this.length;n++)e.push(t);return e}encode(t,e){const n=We.dereference(e,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,t.writeValue(n.length)),P(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let t=0;t<n.length;t++)s.push(this.coder);return Ze(t,s,n)}decode(t){let e=this.length;-1===e&&(e=t.readIndex(),E(e*Ct<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:e*Ct,length:t.dataLength}));let n=[];for(let t=0;t<e;t++)n.push(new Xe(this.coder));return Qe(t,n)}}class en extends Kt{constructor(t){super("bool","bool",t,!1)}defaultValue(){return!1}encode(t,e){const n=We.dereference(e,"bool");return t.writeValue(n?1:0)}decode(t){return!!t.readValue()}}class nn extends Kt{constructor(t,e){super(t,t,e,!0)}defaultValue(){return"0x"}encode(t,e){e=I(e);let n=t.writeValue(e.length);return n+=t.writeBytes(e),n}decode(t){return t.readBytes(t.readIndex(),!0)}}class rn extends nn{constructor(t){super("bytes",t)}decode(t){return _(super.decode(t))}}class sn extends Kt{size;constructor(t,e){let n="bytes"+String(t);super(n,n,e,!1),y(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(t,e){let n=I(We.dereference(e,this.type));return n.length!==this.size&&this._throwError("incorrect data length",e),t.writeBytes(n)}decode(t){return _(t.readBytes(this.size))}}const an=new Uint8Array([]);class on extends Kt{constructor(t){super("null","",t,!1)}defaultValue(){return null}encode(t,e){return null!=e&&this._throwError("not null",e),t.writeBytes(an)}decode(t){return t.readBytes(0),null}}const cn=BigInt(0),ln=BigInt(1),un=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class hn extends Kt{size;signed;constructor(t,e,n){const r=(e?"int":"uint")+8*t;super(r,r,n,!1),y(this,{size:t,signed:e},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,e){let n=H(We.dereference(e,this.type)),r=K(un,256);if(this.signed){let t=K(r,8*this.size-1);(n>t||n<-(t+ln))&&this._throwError("value out-of-bounds",e),n=j(n,256)}else(n<cn||n>K(r,8*this.size))&&this._throwError("value out-of-bounds",e);return t.writeValue(n)}decode(t){let e=K(t.readValue(),8*this.size);return this.signed&&(e=function(t,e){const n=V(t,"value"),r=BigInt(q(e,"width"));if(E(n>>r===G,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:t}),n>>r-$)return-((~n&($<<r)-$)+$);return n}(e,8*this.size)),e}}class dn extends nn{constructor(t){super("string",t)}defaultValue(){return""}encode(t,e){return super.encode(t,ot(We.dereference(e,"string")))}decode(t){return ct(super.decode(t))}}class pn extends Kt{coders;constructor(t,e){let n=!1;const r=[];t.forEach((t=>{t.dynamic&&(n=!0),r.push(t.type)}));super("tuple","tuple("+r.join(",")+")",e,n),y(this,{coders:Object.freeze(t.slice())})}defaultValue(){const t=[];this.coders.forEach((e=>{t.push(e.defaultValue())}));const e=this.coders.reduce(((t,e)=>{const n=e.localName;return n&&(t[n]||(t[n]=0),t[n]++),t}),{});return this.coders.forEach(((n,r)=>{let s=n.localName;s&&1===e[s]&&("length"===s&&(s="_length"),null==t[s]&&(t[s]=t[r]))})),Object.freeze(t)}encode(t,e){const n=We.dereference(e,"tuple");return Ze(t,this.coders,n)}decode(t){return Qe(t,this.coders)}}function fn(t){return Qt(ot(t))}const gn=new Uint8Array(32);function yn(t){return N(0!==t.length,"invalid ENS name; empty component","comp",t),t}function mn(t){const e=ot(function(t){try{if(0===t.length)throw new Error("empty label");return l.ens_normalize(t)}catch(e){N(!1,`invalid ENS name (${e.message})`,"name",t)}}(t)),n=[];if(0===t.length)return n;let r=0;for(let t=0;t<e.length;t++){46===e[t]&&(n.push(yn(e.slice(r,t))),r=t+1)}return N(r<e.length,"invalid ENS name; empty component","name",t),n.push(yn(e.slice(r))),n}function bn(t){N("string"==typeof t,"invalid ENS name; not a string","name",t),N(t.length,"invalid ENS name (empty label)","name",t);let e=gn;const n=mn(t);for(;n.length;)e=Qt(U([e,Qt(n.pop())]));return _(e)}function wn(t,e){const n=null!=e?e:63;return N(n<=255,"DNS encoded label cannot exceed 255","length",n),_(U(mn(t).map((e=>{N(e.length<=n,`label ${JSON.stringify(t)} exceeds ${n} bytes`,"name",t);const r=new Uint8Array(e.length+1);return r.set(e,1),r[0]=r.length-1,r}))))+"00"}function vn(t,e){return{address:Me(t),storageKeys:e.map(((t,e)=>(N(S(t,32),"invalid slot",`storageKeys[${e}]`,t),t.toLowerCase())))}}function En(t){if(Array.isArray(t))return t.map(((e,n)=>Array.isArray(e)?(N(2===e.length,"invalid slot set",`value[${n}]`,e),vn(e[0],e[1])):(N(null!=e&&"object"==typeof e,"invalid address-slot set","value",t),vn(e.address,e.storageKeys))));N(null!=t&&"object"==typeof t,"invalid access list","value",t);const e=Object.keys(t).map((e=>{const n=t[e].reduce(((t,e)=>(t[e]=!0,t)),{});return vn(e,Object.keys(n).sort())}));return e.sort(((t,e)=>t.address.localeCompare(e.address))),e}function Nn(t){let e;return e="string"==typeof t?Fe.computePublicKey(t,!1):t.publicKey,Me(Qt("0x"+e.substring(4)).substring(26))}function Pn(t,e){return Nn(Fe.recoverPublicKey(t,e))}gn.fill(0);const kn=BigInt(0),Tn=BigInt(2),Rn=BigInt(27),An=BigInt(28),On=BigInt(35),In=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Sn=131072;function xn(t,e){let n=t.toString(16);for(;n.length<2;)n="0"+n;return n+=Pe(e).substring(4),"0x"+n}function Cn(t){return"0x"===t?null:Me(t)}function _n(t,e){try{return En(t)}catch(n){N(!1,n.message,e,t)}}function Un(t,e){return"0x"===t?0:q(t,e)}function Fn(t,e){if("0x"===t)return kn;const n=H(t,e);return N(n<=In,"value exceeds uint size",e,n),n}function Ln(t,e){const n=H(t,"value"),r=Y(n);return N(r.length<=32,"value too large",`tx.${e}`,n),r}function Dn(t){return En(t).map((t=>[t.address,t.storageKeys]))}function Bn(t,e){N(Array.isArray(t),`invalid ${e}`,"value",t);for(let e=0;e<t.length;e++)N(S(t[e],32),"invalid ${ param } hash",`value[${e}]`,t[e]);return t}function Gn(t,e){let n;try{if(n=Un(e[0],"yParity"),0!==n&&1!==n)throw new Error("bad yParity")}catch(t){N(!1,"invalid yParity","yParity",e[0])}const r=B(e[1],32),s=B(e[2],32),i=Ue.from({r:r,s:s,yParity:n});t.signature=i}class $n{#G;#$;#k;#M;#j;#K;#H;#V;#z;#J;#q;#W;#Y;#X;#Z;#Q;get type(){return this.#G}set type(t){switch(t){case null:this.#G=null;break;case 0:case"legacy":this.#G=0;break;case 1:case"berlin":case"eip-2930":this.#G=1;break;case 2:case"london":case"eip-1559":this.#G=2;break;case 3:case"cancun":case"eip-4844":this.#G=3;break;default:N(!1,"unsupported transaction type","type",t)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844"}return null}get to(){const t=this.#$;return null==t&&3===this.type?ke:t}set to(t){this.#$=null==t?null:Me(t)}get nonce(){return this.#M}set nonce(t){this.#M=q(t,"value")}get gasLimit(){return this.#j}set gasLimit(t){this.#j=H(t)}get gasPrice(){const t=this.#K;return null!=t||0!==this.type&&1!==this.type?t:kn}set gasPrice(t){this.#K=null==t?null:H(t,"gasPrice")}get maxPriorityFeePerGas(){const t=this.#H;return null==t?2===this.type||3===this.type?kn:null:t}set maxPriorityFeePerGas(t){this.#H=null==t?null:H(t,"maxPriorityFeePerGas")}get maxFeePerGas(){const t=this.#V;return null==t?2===this.type||3===this.type?kn:null:t}set maxFeePerGas(t){this.#V=null==t?null:H(t,"maxFeePerGas")}get data(){return this.#k}set data(t){this.#k=_(t)}get value(){return this.#z}set value(t){this.#z=H(t,"value")}get chainId(){return this.#J}set chainId(t){this.#J=H(t)}get signature(){return this.#q||null}set signature(t){this.#q=null==t?null:Ue.from(t)}get accessList(){const t=this.#W||null;return null==t?1===this.type||2===this.type||3===this.type?[]:null:t}set accessList(t){this.#W=null==t?null:En(t)}get maxFeePerBlobGas(){const t=this.#Y;return null==t&&3===this.type?kn:t}set maxFeePerBlobGas(t){this.#Y=null==t?null:H(t,"maxFeePerBlobGas")}get blobVersionedHashes(){let t=this.#X;return null==t&&3===this.type?[]:t}set blobVersionedHashes(t){if(null!=t){N(Array.isArray(t),"blobVersionedHashes must be an Array","value",t),t=t.slice();for(let e=0;e<t.length;e++)N(S(t[e],32),"invalid blobVersionedHash",`value[${e}]`,t[e])}this.#X=t}get blobs(){return null==this.#Q?null:this.#Q.map((t=>Object.assign({},t)))}set blobs(t){if(null==t)return void(this.#Q=null);const e=[],n=[];for(let r=0;r<t.length;r++){const s=t[r];if(x(s)){E(this.#Z,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let t=O(s);if(N(t.length<=Sn,"blob is too large",`blobs[${r}]`,s),t.length!==Sn){const e=new Uint8Array(Sn);e.set(t),t=e}const i=this.#Z.blobToKzgCommitment(t),a=_(this.#Z.computeBlobKzgProof(t,i));e.push({data:_(t),commitment:_(i),proof:a}),n.push(xn(1,i))}else{const t=_(s.commitment);e.push({data:_(s.data),commitment:t,proof:_(s.proof)}),n.push(xn(1,t))}}this.#Q=e,this.#X=n}get kzg(){return this.#Z}set kzg(t){this.#Z=t}constructor(){this.#G=null,this.#$=null,this.#M=0,this.#j=kn,this.#K=null,this.#H=null,this.#V=null,this.#k="0x",this.#z=kn,this.#J=kn,this.#q=null,this.#W=null,this.#Y=null,this.#X=null,this.#Q=null,this.#Z=null}get hash(){return null==this.signature?null:Qt(this.#tt(!0,!1))}get unsignedHash(){return Qt(this.unsignedSerialized)}get from(){return null==this.signature?null:Pn(this.unsignedHash,this.signature)}get fromPublicKey(){return null==this.signature?null:Fe.recoverPublicKey(this.unsignedHash,this.signature)}isSigned(){return null!=this.signature}#tt(t,e){E(!t||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=t?this.signature:null;switch(this.inferType()){case 0:return function(t,e){const n=[Ln(t.nonce,"nonce"),Ln(t.gasPrice||0,"gasPrice"),Ln(t.gasLimit,"gasLimit"),t.to||"0x",Ln(t.value,"value"),t.data];let r=kn;if(t.chainId!=kn)r=H(t.chainId,"tx.chainId"),N(!e||null==e.networkV||e.legacyChainId===r,"tx.chainId/sig.v mismatch","sig",e);else if(t.signature){const e=t.signature.legacyChainId;null!=e&&(r=e)}if(!e)return r!==kn&&(n.push(Y(r)),n.push("0x"),n.push("0x")),St(n);let s=BigInt(27+e.yParity);return r!==kn?s=Ue.getChainIdV(r,e.v):BigInt(e.v)!==s&&N(!1,"tx.chainId/sig.v mismatch","sig",e),n.push(Y(s)),n.push(Y(e.r)),n.push(Y(e.s)),St(n)}(this,n);case 1:return function(t,e){const n=[Ln(t.chainId,"chainId"),Ln(t.nonce,"nonce"),Ln(t.gasPrice||0,"gasPrice"),Ln(t.gasLimit,"gasLimit"),t.to||"0x",Ln(t.value,"value"),t.data,Dn(t.accessList||[])];return e&&(n.push(Ln(e.yParity,"recoveryParam")),n.push(Y(e.r)),n.push(Y(e.s))),U(["0x01",St(n)])}(this,n);case 2:return function(t,e){const n=[Ln(t.chainId,"chainId"),Ln(t.nonce,"nonce"),Ln(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Ln(t.maxFeePerGas||0,"maxFeePerGas"),Ln(t.gasLimit,"gasLimit"),t.to||"0x",Ln(t.value,"value"),t.data,Dn(t.accessList||[])];return e&&(n.push(Ln(e.yParity,"yParity")),n.push(Y(e.r)),n.push(Y(e.s))),U(["0x02",St(n)])}(this,n);case 3:return function(t,e,n){const r=[Ln(t.chainId,"chainId"),Ln(t.nonce,"nonce"),Ln(t.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),Ln(t.maxFeePerGas||0,"maxFeePerGas"),Ln(t.gasLimit,"gasLimit"),t.to||ke,Ln(t.value,"value"),t.data,Dn(t.accessList||[]),Ln(t.maxFeePerBlobGas||0,"maxFeePerBlobGas"),Bn(t.blobVersionedHashes||[],"blobVersionedHashes")];return e&&(r.push(Ln(e.yParity,"yParity")),r.push(Y(e.r)),r.push(Y(e.s)),n)?U(["0x03",St([r,n.map((t=>t.data)),n.map((t=>t.commitment)),n.map((t=>t.proof))])]):U(["0x03",St(r)])}(this,n,e?this.blobs:null)}E(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#tt(!0,!0)}get unsignedSerialized(){return this.#tt(!1,!1)}inferType(){const t=this.inferTypes();return t.indexOf(2)>=0?2:t.pop()}inferTypes(){const t=null!=this.gasPrice,e=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,n=null!=this.accessList,r=null!=this.#Y||this.#X;null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&E(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),E(!e||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),E(0!==this.type||!n,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const s=[];return null!=this.type?s.push(this.type):e?s.push(2):t?(s.push(1),n||s.push(0)):n?(s.push(1),s.push(2)):(r&&this.to||(s.push(0),s.push(1),s.push(2)),s.push(3)),s.sort(),s}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}clone(){return $n.from(this)}toJSON(){const t=t=>null==t?null:t.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:t(this.gasLimit),gasPrice:t(this.gasPrice),maxPriorityFeePerGas:t(this.maxPriorityFeePerGas),maxFeePerGas:t(this.maxFeePerGas),value:t(this.value),chainId:t(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}static from(t){if(null==t)return new $n;if("string"==typeof t){const e=O(t);if(e[0]>=127)return $n.from(function(t){const e=Rt(t);N(Array.isArray(e)&&(9===e.length||6===e.length),"invalid field count for legacy transaction","data",t);const n={type:0,nonce:Un(e[0],"nonce"),gasPrice:Fn(e[1],"gasPrice"),gasLimit:Fn(e[2],"gasLimit"),to:Cn(e[3]),value:Fn(e[4],"value"),data:_(e[5]),chainId:kn};if(6===e.length)return n;const r=Fn(e[6],"v"),s=Fn(e[7],"r"),i=Fn(e[8],"s");if(s===kn&&i===kn)n.chainId=r;else{let t=(r-On)/Tn;t<kn&&(t=kn),n.chainId=t,N(t!==kn||r===Rn||r===An,"non-canonical legacy v","v",e[6]),n.signature=Ue.from({r:B(e[7],32),s:B(e[8],32),v:r})}return n}(e));switch(e[0]){case 1:return $n.from(function(t){const e=Rt(O(t).slice(1));N(Array.isArray(e)&&(8===e.length||11===e.length),"invalid field count for transaction type: 1","data",_(t));const n={type:1,chainId:Fn(e[0],"chainId"),nonce:Un(e[1],"nonce"),gasPrice:Fn(e[2],"gasPrice"),gasLimit:Fn(e[3],"gasLimit"),to:Cn(e[4]),value:Fn(e[5],"value"),data:_(e[6]),accessList:_n(e[7],"accessList")};return 8===e.length||Gn(n,e.slice(8)),n}(e));case 2:return $n.from(function(t){const e=Rt(O(t).slice(1));N(Array.isArray(e)&&(9===e.length||12===e.length),"invalid field count for transaction type: 2","data",_(t));const n={type:2,chainId:Fn(e[0],"chainId"),nonce:Un(e[1],"nonce"),maxPriorityFeePerGas:Fn(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Fn(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Fn(e[4],"gasLimit"),to:Cn(e[5]),value:Fn(e[6],"value"),data:_(e[7]),accessList:_n(e[8],"accessList")};return 9===e.length||Gn(n,e.slice(9)),n}(e));case 3:return $n.from(function(t){let e=Rt(O(t).slice(1)),n="3",r=null;if(4===e.length&&Array.isArray(e[0])){n="3 (network format)";const t=e[1],s=e[2],i=e[3];N(Array.isArray(t),"invalid network format: blobs not an array","fields[1]",t),N(Array.isArray(s),"invalid network format: commitments not an array","fields[2]",s),N(Array.isArray(i),"invalid network format: proofs not an array","fields[3]",i),N(t.length===s.length,"invalid network format: blobs/commitments length mismatch","fields",e),N(t.length===i.length,"invalid network format: blobs/proofs length mismatch","fields",e),r=[];for(let n=0;n<e[1].length;n++)r.push({data:t[n],commitment:s[n],proof:i[n]});e=e[0]}N(Array.isArray(e)&&(11===e.length||14===e.length),`invalid field count for transaction type: ${n}`,"data",_(t));const s={type:3,chainId:Fn(e[0],"chainId"),nonce:Un(e[1],"nonce"),maxPriorityFeePerGas:Fn(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Fn(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Fn(e[4],"gasLimit"),to:Cn(e[5]),value:Fn(e[6],"value"),data:_(e[7]),accessList:_n(e[8],"accessList"),maxFeePerBlobGas:Fn(e[9],"maxFeePerBlobGas"),blobVersionedHashes:e[10]};r&&(s.blobs=r),N(null!=s.to,`invalid address for transaction type: ${n}`,"data",t),N(Array.isArray(s.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",t);for(let e=0;e<s.blobVersionedHashes.length;e++)N(S(s.blobVersionedHashes[e],32),`invalid blobVersionedHash at index ${e}: must be length 32`,"data",t);return 11===e.length||Gn(s,e.slice(11)),s}(e))}E(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const e=new $n;return null!=t.type&&(e.type=t.type),null!=t.to&&(e.to=t.to),null!=t.nonce&&(e.nonce=t.nonce),null!=t.gasLimit&&(e.gasLimit=t.gasLimit),null!=t.gasPrice&&(e.gasPrice=t.gasPrice),null!=t.maxPriorityFeePerGas&&(e.maxPriorityFeePerGas=t.maxPriorityFeePerGas),null!=t.maxFeePerGas&&(e.maxFeePerGas=t.maxFeePerGas),null!=t.maxFeePerBlobGas&&(e.maxFeePerBlobGas=t.maxFeePerBlobGas),null!=t.data&&(e.data=t.data),null!=t.value&&(e.value=t.value),null!=t.chainId&&(e.chainId=t.chainId),null!=t.signature&&(e.signature=Ue.from(t.signature)),null!=t.accessList&&(e.accessList=t.accessList),null!=t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes),null!=t.kzg&&(e.kzg=t.kzg),null!=t.blobs&&(e.blobs=t.blobs),null!=t.hash&&(N(e.isSigned(),"unsigned transaction cannot define '.hash'","tx",t),N(e.hash===t.hash,"hash mismatch","tx",t)),null!=t.from&&(N(e.isSigned(),"unsigned transaction cannot define '.from'","tx",t),N(e.from.toLowerCase()===(t.from||"").toLowerCase(),"from mismatch","tx",t)),e}}function Mn(t){return"string"==typeof t&&(t=ot(t)),Qt(U([ot("Ethereum Signed Message:\n"),ot(String(t.length)),t]))}const jn=new Uint8Array(32);jn.fill(0);const Kn=BigInt(-1),Hn=BigInt(0),Vn=BigInt(1),zn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const Jn=W(Vn,32),qn=W(Hn,32),Wn={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},Yn=["name","version","chainId","verifyingContract","salt"];function Xn(t){return function(e){return N("string"==typeof e,`invalid domain value for ${JSON.stringify(t)}`,`domain.${t}`,e),e}}const Zn={name:Xn("name"),version:Xn("version"),chainId:function(t){const e=H(t,"domain.chainId");return N(e>=0,"invalid chain ID","domain.chainId",t),Number.isSafeInteger(e)?Number(e):X(e)},verifyingContract:function(t){try{return Me(t).toLowerCase()}catch(t){}N(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",t)},salt:function(t){const e=O(t,"domain.salt");return N(32===e.length,'invalid domain value "salt"',"domain.salt",t),_(e)}};function Qn(t){{const e=t.match(/^(u?)int(\d+)$/);if(e){const n=""===e[1],r=parseInt(e[2]);N(r%8==0&&0!==r&&r<=256&&e[2]===String(r),"invalid numeric width","type",t);const s=K(zn,n?r-1:r),i=n?(s+Vn)*Kn:Hn;return function(e){const r=H(e,"value");return N(r>=i&&r<=s,`value out-of-bounds for ${t}`,"value",r),W(n?j(r,256):r,32)}}}{const e=t.match(/^bytes(\d+)$/);if(e){const n=parseInt(e[1]);return N(0!==n&&n<=32&&e[1]===String(n),"invalid bytes width","type",t),function(e){return N(O(e).length===n,`invalid length for ${t}`,"value",e),function(t){const e=O(t),n=e.length%32;return n?U([e,jn.slice(n)]):_(e)}(e)}}}switch(t){case"address":return function(t){return B(Me(t),32)};case"bool":return function(t){return t?Jn:qn};case"bytes":return function(t){return Qt(t)};case"string":return function(t){return fn(t)}}return null}function tr(t,e){return`${t}(${e.map((({name:t,type:e})=>e+" "+t)).join(",")})`}function er(t){const e=t.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return e?{base:e[1],index:e[2]+e[4],array:{base:e[1],prefix:e[1]+e[2],count:e[5]?parseInt(e[5]):-1}}:{base:t}}class nr{primaryType;#et;get types(){return JSON.parse(this.#et)}#nt;#rt;constructor(t){this.#nt=new Map,this.#rt=new Map;const e=new Map,n=new Map,r=new Map,s={};Object.keys(t).forEach((i=>{s[i]=t[i].map((({name:e,type:n})=>{let{base:r,index:s}=er(n);return"int"!==r||t.int||(r="int256"),"uint"!==r||t.uint||(r="uint256"),{name:e,type:r+(s||"")}})),e.set(i,new Set),n.set(i,[]),r.set(i,new Set)})),this.#et=JSON.stringify(s);for(const r in s){const i=new Set;for(const a of s[r]){N(!i.has(a.name),`duplicate variable name ${JSON.stringify(a.name)} in ${JSON.stringify(r)}`,"types",t),i.add(a.name);const s=er(a.type).base;N(s!==r,`circular type reference to ${JSON.stringify(s)}`,"types",t);Qn(s)||(N(n.has(s),`unknown type ${JSON.stringify(s)}`,"types",t),n.get(s).push(r),e.get(r).add(s))}}const i=Array.from(n.keys()).filter((t=>0===n.get(t).length));N(0!==i.length,"missing primary type","types",t),N(1===i.length,`ambiguous primary types or unused types: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"types",t),y(this,{primaryType:i[0]}),function s(i,a){N(!a.has(i),`circular type reference to ${JSON.stringify(i)}`,"types",t),a.add(i);for(const t of e.get(i))if(n.has(t)){s(t,a);for(const e of a)r.get(e).add(t)}a.delete(i)}(this.primaryType,new Set);for(const[t,e]of r){const n=Array.from(e);n.sort(),this.#nt.set(t,tr(t,s[t])+n.map((t=>tr(t,s[t]))).join(""))}}getEncoder(t){let e=this.#rt.get(t);return e||(e=this.#st(t),this.#rt.set(t,e)),e}#st(t){{const e=Qn(t);if(e)return e}const e=er(t).array;if(e){const t=e.prefix,n=this.getEncoder(t);return r=>{N(-1===e.count||e.count===r.length,`array length mismatch; expected length ${e.count}`,"value",r);let s=r.map(n);return this.#nt.has(t)&&(s=s.map(Qt)),Qt(U(s))}}const n=this.types[t];if(n){const e=fn(this.#nt.get(t));return t=>{const r=n.map((({name:e,type:n})=>{const r=this.getEncoder(n)(t[e]);return this.#nt.has(n)?Qt(r):r}));return r.unshift(e),U(r)}}N(!1,`unknown type: ${t}`,"type",t)}encodeType(t){const e=this.#nt.get(t);return N(e,`unknown type: ${JSON.stringify(t)}`,"name",t),e}encodeData(t,e){return this.getEncoder(t)(e)}hashStruct(t,e){return Qt(this.encodeData(t,e))}encode(t){return this.encodeData(this.primaryType,t)}hash(t){return this.hashStruct(this.primaryType,t)}_visit(t,e,n){if(Qn(t))return n(t,e);const r=er(t).array;if(r)return N(-1===r.count||r.count===e.length,`array length mismatch; expected length ${r.count}`,"value",e),e.map((t=>this._visit(r.prefix,t,n)));const s=this.types[t];if(s)return s.reduce(((t,{name:r,type:s})=>(t[r]=this._visit(s,e[r],n),t)),{});N(!1,`unknown type: ${t}`,"type",t)}visit(t,e){return this._visit(this.primaryType,t,e)}static from(t){return new nr(t)}static getPrimaryType(t){return nr.from(t).primaryType}static hashStruct(t,e,n){return nr.from(e).hashStruct(t,n)}static hashDomain(t){const e=[];for(const n in t){if(null==t[n])continue;const r=Wn[n];N(r,`invalid typed-data domain key: ${JSON.stringify(n)}`,"domain",t),e.push({name:n,type:r})}return e.sort(((t,e)=>Yn.indexOf(t.name)-Yn.indexOf(e.name))),nr.hashStruct("EIP712Domain",{EIP712Domain:e},t)}static encode(t,e,n){return U(["0x1901",nr.hashDomain(t),nr.from(e).hash(n)])}static hash(t,e,n){return Qt(nr.encode(t,e,n))}static async resolveNames(t,e,n,r){t=Object.assign({},t);for(const e in t)null==t[e]&&delete t[e];const s={};t.verifyingContract&&!S(t.verifyingContract,20)&&(s[t.verifyingContract]="0x");const i=nr.from(e);i.visit(n,((t,e)=>("address"!==t||S(e,20)||(s[e]="0x"),e)));for(const t in s)s[t]=await r(t);return t.verifyingContract&&s[t.verifyingContract]&&(t.verifyingContract=s[t.verifyingContract]),{domain:t,value:n=i.visit(n,((t,e)=>"address"===t&&s[e]?s[e]:e))}}static getPayload(t,e,n){nr.hashDomain(t);const r={},s=[];Yn.forEach((e=>{const n=t[e];null!=n&&(r[e]=Zn[e](n),s.push({name:e,type:Wn[e]}))}));const i=nr.from(e);e=i.types;const a=Object.assign({},e);return N(null==a.EIP712Domain,"types must not contain EIP712Domain type","types.EIP712Domain",e),a.EIP712Domain=s,i.encode(n),{types:a,domain:r,primaryType:i.primaryType,message:i.visit(n,((t,e)=>{if(t.match(/^bytes(\d*)/))return _(O(e));if(t.match(/^u?int/))return H(e).toString();switch(t){case"address":return e.toLowerCase();case"bool":return!!e;case"string":return N("string"==typeof e,"invalid string","value",e),e}N(!1,"unsupported type","type",t)}))}}}function rr(t){const e=new Set;return t.forEach((t=>e.add(t))),Object.freeze(e)}const sr=rr("external public payable override".split(" ")),ir="constant external internal payable private public pure view override",ar=rr(ir.split(" ")),or="constructor error event fallback function receive struct",cr=rr(or.split(" ")),lr="calldata memory storage payable indexed",ur=rr(lr.split(" ")),hr=rr([or,lr,"tuple returns",ir].join(" ").split(" ")),dr={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},pr=new RegExp("^(\\s*)"),fr=new RegExp("^([0-9]+)"),gr=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),yr=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),mr=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class br{#A;#it;get offset(){return this.#A}get length(){return this.#it.length-this.#A}constructor(t){this.#A=0,this.#it=t.slice()}clone(){return new br(this.#it)}reset(){this.#A=0}#at(t=0,e=0){return new br(this.#it.slice(t,e).map((e=>Object.freeze(Object.assign({},e,{match:e.match-t,linkBack:e.linkBack-t,linkNext:e.linkNext-t})))))}popKeyword(t){const e=this.peek();if("KEYWORD"!==e.type||!t.has(e.text))throw new Error(`expected keyword ${e.text}`);return this.pop().text}popType(t){if(this.peek().type!==t){const e=this.peek();throw new Error(`expected ${t}; got ${e.type} ${JSON.stringify(e.text)}`)}return this.pop().text}popParen(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=this.#at(this.#A+1,t.match+1);return this.#A=t.match+1,e}popParams(){const t=this.peek();if("OPEN_PAREN"!==t.type)throw new Error("bad start");const e=[];for(;this.#A<t.match-1;){const t=this.peek().linkNext;e.push(this.#at(this.#A+1,t)),this.#A=t}return this.#A=t.match+1,e}peek(){if(this.#A>=this.#it.length)throw new Error("out-of-bounds");return this.#it[this.#A]}peekKeyword(t){const e=this.peekType("KEYWORD");return null!=e&&t.has(e)?e:null}peekType(t){if(0===this.length)return null;const e=this.peek();return e.type===t?e.text:null}pop(){const t=this.peek();return this.#A++,t}toString(){const t=[];for(let e=this.#A;e<this.#it.length;e++){const n=this.#it[e];t.push(`${n.type}:${n.text}`)}return`<TokenString ${t.join(" ")}>`}}function wr(t){const e=[],n=e=>{const n=i<t.length?JSON.stringify(t[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${e}`)};let r=[],s=[],i=0;for(;i<t.length;){let a=t.substring(i),o=a.match(pr);o&&(i+=o[1].length,a=t.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};e.push(c);let l=dr[a[0]]||"";if(l){if(c.type=l,c.text=a[0],i++,"OPEN_PAREN"===l)r.push(e.length-1),s.push(e.length-1);else if("CLOSE_PAREN"==l)0===r.length&&n("no matching open bracket"),c.match=r.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if("COMMA"===l)c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if("OPEN_BRACKET"===l)c.type="BRACKET";else if("CLOSE_BRACKET"===l){let t=e.pop().text;if(e.length>0&&"NUMBER"===e[e.length-1].type){const n=e.pop().text;t=n+t,e[e.length-1].value=q(n)}if(0===e.length||"BRACKET"!==e[e.length-1].type)throw new Error("missing opening bracket");e[e.length-1].text+=t}}else if(o=a.match(gr),o){if(c.text=o[1],i+=c.text.length,hr.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(mr)){c.type="TYPE";continue}c.type="ID"}else{if(o=a.match(fr),!o)throw new Error(`unexpected token ${JSON.stringify(a[0])} at position ${i}`);c.text=o[1],c.type="NUMBER",i+=c.text.length}}return new br(e.map((t=>Object.freeze(t))))}function vr(t,e){let n=[];for(const r in e.keys())t.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Er(t,e){if(e.peekKeyword(cr)){const n=e.pop().text;if(n!==t)throw new Error(`expected ${t}, got ${n}`)}return e.popType("ID")}function Nr(t,e){const n=new Set;for(;;){const r=t.peekType("KEYWORD");if(null==r||e&&!e.has(r))break;if(t.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function Pr(t){let e=Nr(t,ar);return vr(e,rr("constant payable nonpayable".split(" "))),vr(e,rr("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function kr(t,e){return t.popParams().map((t=>Br.from(t,e)))}function Tr(t){if(t.peekType("AT")){if(t.pop(),t.peekType("NUMBER"))return H(t.pop().text);throw new Error("invalid gas")}return null}function Rr(t){if(t.length)throw new Error(`unexpected tokens at offset ${t.offset}: ${t.toString()}`)}const Ar=new RegExp(/^(.*)\[([0-9]*)\]$/);function Or(t){const e=t.match(mr);if(N(e,"invalid type","type",t),"uint"===t)return"uint256";if("int"===t)return"int256";if(e[2]){const n=parseInt(e[2]);N(0!==n&&n<=32,"invalid bytes length","type",t)}else if(e[3]){const n=parseInt(e[3]);N(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",t)}return t}const Ir={},Sr=Symbol.for("_ethers_internal"),xr="_ParamTypeInternal",Cr="_ErrorInternal",_r="_EventInternal",Ur="_ConstructorInternal",Fr="_FallbackInternal",Lr="_FunctionInternal",Dr="_StructInternal";class Br{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(t,e,n,r,s,i,a,o){if(R(t,Ir,"ParamType"),Object.defineProperty(this,Sr,{value:xr}),i&&(i=Object.freeze(i.slice())),"array"===r){if(null==a||null==o)throw new Error("")}else if(null!=a||null!=o)throw new Error("");if("tuple"===r){if(null==i)throw new Error("")}else if(null!=i)throw new Error("");y(this,{name:e,type:n,baseType:r,indexed:s,components:i,arrayLength:a,arrayChildren:o})}format(t){if(null==t&&(t="sighash"),"json"===t){const e=this.name||"";if(this.isArray()){const t=JSON.parse(this.arrayChildren.format("json"));return t.name=e,t.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(t)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:e};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map((e=>JSON.parse(e.format(t))))),JSON.stringify(n)}let e="";return this.isArray()?(e+=this.arrayChildren.format(t),e+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?e+="("+this.components.map((e=>e.format(t))).join("full"===t?", ":",")+")":e+=this.type,"sighash"!==t&&(!0===this.indexed&&(e+=" indexed"),"full"===t&&this.name&&(e+=" "+this.name)),e}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(t,e){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return t.map((t=>n.arrayChildren.walk(t,e)))}if(this.isTuple()){if(!Array.isArray(t))throw new Error("invalid tuple value");if(t.length!==this.components.length)throw new Error("array is wrong length");const n=this;return t.map(((t,r)=>n.components[r].walk(t,e)))}return e(this.type,t)}#ot(t,e,n,r){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const s=this.arrayChildren,i=e.slice();return i.forEach(((e,r)=>{s.#ot(t,e,n,(t=>{i[r]=t}))})),void r(i)}if(this.isTuple()){const s=this.components;let i;if(Array.isArray(e))i=e.slice();else{if(null==e||"object"!=typeof e)throw new Error("invalid tuple value");i=s.map((t=>{if(!t.name)throw new Error("cannot use object value with unnamed components");if(!(t.name in e))throw new Error(`missing value for component ${t.name}`);return e[t.name]}))}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach(((e,r)=>{s[r].#ot(t,e,n,(t=>{i[r]=t}))})),void r(i)}const s=n(this.type,e);s.then?t.push(async function(){r(await s)}()):r(s)}async walkAsync(t,e){const n=[],r=[t];return this.#ot(n,t,e,(t=>{r[0]=t})),n.length&&await Promise.all(n),r[0]}static from(t,e){if(Br.isParamType(t))return t;if("string"==typeof t)try{return Br.from(wr(t),e)}catch(e){N(!1,"invalid param type","obj",t)}else if(t instanceof br){let n="",r="",s=null;Nr(t,rr(["tuple"])).has("tuple")||t.peekType("OPEN_PAREN")?(r="tuple",s=t.popParams().map((t=>Br.from(t))),n=`tuple(${s.map((t=>t.format())).join(",")})`):(n=Or(t.popType("TYPE")),r=n);let i=null,a=null;for(;t.length&&t.peekType("BRACKET");){const e=t.pop();i=new Br(Ir,"",n,r,null,s,a,i),a=e.value,n+=e.text,r="array",s=null}let o=null;if(Nr(t,ur).has("indexed")){if(!e)throw new Error("");o=!0}const c=t.peekType("ID")?t.pop().text:"";if(t.length)throw new Error("leftover tokens");return new Br(Ir,c,n,r,o,s,a,i)}const n=t.name;N(!n||"string"==typeof n&&n.match(yr),"invalid name","obj.name",n);let r=t.indexed;null!=r&&(N(e,"parameter cannot be indexed","obj.indexed",t.indexed),r=!!r);let s=t.type,i=s.match(Ar);if(i){const e=parseInt(i[2]||"-1"),a=Br.from({type:i[1],components:t.components});return new Br(Ir,n||"",s,"array",r,null,e,a)}if("tuple"===s||s.startsWith("tuple(")||s.startsWith("(")){const e=null!=t.components?t.components.map((t=>Br.from(t))):null;return new Br(Ir,n||"",s,"tuple",r,e,null,null)}return s=Or(t.type),new Br(Ir,n||"",s,s,r,null,null,null)}static isParamType(t){return t&&t[Sr]===xr}}class Gr{type;inputs;constructor(t,e,n){R(t,Ir,"Fragment"),y(this,{type:e,inputs:n=Object.freeze(n.slice())})}static from(t){if("string"==typeof t){try{Gr.from(JSON.parse(t))}catch(t){}return Gr.from(wr(t))}if(t instanceof br){switch(t.peekKeyword(cr)){case"constructor":return Hr.from(t);case"error":return jr.from(t);case"event":return Kr.from(t);case"fallback":case"receive":return Vr.from(t);case"function":return zr.from(t);case"struct":return Jr.from(t)}}else if("object"==typeof t){switch(t.type){case"constructor":return Hr.from(t);case"error":return jr.from(t);case"event":return Kr.from(t);case"fallback":case"receive":return Vr.from(t);case"function":return zr.from(t);case"struct":return Jr.from(t)}E(!1,`unsupported type: ${t.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}N(!1,"unsupported frgament object","obj",t)}static isConstructor(t){return Hr.isFragment(t)}static isError(t){return jr.isFragment(t)}static isEvent(t){return Kr.isFragment(t)}static isFunction(t){return zr.isFragment(t)}static isStruct(t){return Jr.isFragment(t)}}class $r extends Gr{name;constructor(t,e,n,r){super(t,e,r),N("string"==typeof n&&n.match(yr),"invalid identifier","name",n),r=Object.freeze(r.slice()),y(this,{name:n})}}function Mr(t,e){return"("+e.map((e=>e.format(t))).join("full"===t?", ":",")+")"}class jr extends $r{constructor(t,e,n){super(t,"error",e,n),Object.defineProperty(this,Sr,{value:Cr})}get selector(){return fn(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("error"),e.push(this.name+Mr(t,this.inputs)),e.join(" ")}static from(t){if(jr.isFragment(t))return t;if("string"==typeof t)return jr.from(wr(t));if(t instanceof br){const e=Er("error",t),n=kr(t);return Rr(t),new jr(Ir,e,n)}return new jr(Ir,t.name,t.inputs?t.inputs.map(Br.from):[])}static isFragment(t){return t&&t[Sr]===Cr}}class Kr extends $r{anonymous;constructor(t,e,n,r){super(t,"event",e,n),Object.defineProperty(this,Sr,{value:_r}),y(this,{anonymous:r})}get topicHash(){return fn(this.format("sighash"))}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("event"),e.push(this.name+Mr(t,this.inputs)),"sighash"!==t&&this.anonymous&&e.push("anonymous"),e.join(" ")}static getTopicHash(t,e){e=(e||[]).map((t=>Br.from(t)));return new Kr(Ir,t,e,!1).topicHash}static from(t){if(Kr.isFragment(t))return t;if("string"==typeof t)try{return Kr.from(wr(t))}catch(e){N(!1,"invalid event fragment","obj",t)}else if(t instanceof br){const e=Er("event",t),n=kr(t,!0),r=!!Nr(t,rr(["anonymous"])).has("anonymous");return Rr(t),new Kr(Ir,e,n,r)}return new Kr(Ir,t.name,t.inputs?t.inputs.map((t=>Br.from(t,!0))):[],!!t.anonymous)}static isFragment(t){return t&&t[Sr]===_r}}class Hr extends Gr{payable;gas;constructor(t,e,n,r,s){super(t,e,n),Object.defineProperty(this,Sr,{value:Ur}),y(this,{payable:r,gas:s})}format(t){if(E(null!=t&&"sighash"!==t,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===t)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t))))});const e=[`constructor${Mr(t,this.inputs)}`];return this.payable&&e.push("payable"),null!=this.gas&&e.push(`@${this.gas.toString()}`),e.join(" ")}static from(t){if(Hr.isFragment(t))return t;if("string"==typeof t)try{return Hr.from(wr(t))}catch(e){N(!1,"invalid constuctor fragment","obj",t)}else if(t instanceof br){Nr(t,rr(["constructor"]));const e=kr(t),n=!!Nr(t,sr).has("payable"),r=Tr(t);return Rr(t),new Hr(Ir,"constructor",e,n,r)}return new Hr(Ir,"constructor",t.inputs?t.inputs.map(Br.from):[],!!t.payable,null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Sr]===Ur}}class Vr extends Gr{payable;constructor(t,e,n){super(t,"fallback",e),Object.defineProperty(this,Sr,{value:Fr}),y(this,{payable:n})}format(t){const e=0===this.inputs.length?"receive":"fallback";if("json"===t){const t=this.payable?"payable":"nonpayable";return JSON.stringify({type:e,stateMutability:t})}return`${e}()${this.payable?" payable":""}`}static from(t){if(Vr.isFragment(t))return t;if("string"==typeof t)try{return Vr.from(wr(t))}catch(e){N(!1,"invalid fallback fragment","obj",t)}else if(t instanceof br){const e=t.toString();N(t.peekKeyword(rr(["fallback","receive"])),"type must be fallback or receive","obj",e);if("receive"===t.popKeyword(rr(["fallback","receive"]))){const e=kr(t);return N(0===e.length,"receive cannot have arguments","obj.inputs",e),Nr(t,rr(["payable"])),Rr(t),new Vr(Ir,[],!0)}let n=kr(t);n.length?N(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map((t=>t.format("minimal"))).join(", ")):n=[Br.from("bytes")];const r=Pr(t);if(N("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),Nr(t,rr(["returns"])).has("returns")){const e=kr(t);N(1===e.length&&"bytes"===e[0].type,"invalid fallback outputs","obj.outputs",e.map((t=>t.format("minimal"))).join(", "))}return Rr(t),new Vr(Ir,n,"payable"===r)}if("receive"===t.type)return new Vr(Ir,[],!0);if("fallback"===t.type){const e=[Br.from("bytes")],n="payable"===t.stateMutability;return new Vr(Ir,e,n)}N(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[Sr]===Fr}}class zr extends $r{constant;outputs;stateMutability;payable;gas;constructor(t,e,n,r,s,i){super(t,"function",e,r),Object.defineProperty(this,Sr,{value:Lr});y(this,{constant:"view"===n||"pure"===n,gas:i,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return fn(this.format("sighash")).substring(0,10)}format(t){if(null==t&&(t="sighash"),"json"===t)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((e=>JSON.parse(e.format(t)))),outputs:this.outputs.map((e=>JSON.parse(e.format(t))))});const e=[];return"sighash"!==t&&e.push("function"),e.push(this.name+Mr(t,this.inputs)),"sighash"!==t&&("nonpayable"!==this.stateMutability&&e.push(this.stateMutability),this.outputs&&this.outputs.length&&(e.push("returns"),e.push(Mr(t,this.outputs))),null!=this.gas&&e.push(`@${this.gas.toString()}`)),e.join(" ")}static getSelector(t,e){e=(e||[]).map((t=>Br.from(t)));return new zr(Ir,t,"view",e,[],null).selector}static from(t){if(zr.isFragment(t))return t;if("string"==typeof t)try{return zr.from(wr(t))}catch(e){N(!1,"invalid function fragment","obj",t)}else if(t instanceof br){const e=Er("function",t),n=kr(t),r=Pr(t);let s=[];Nr(t,rr(["returns"])).has("returns")&&(s=kr(t));const i=Tr(t);return Rr(t),new zr(Ir,e,r,n,s,i)}let e=t.stateMutability;return null==e&&(e="payable","boolean"==typeof t.constant?(e="view",t.constant||(e="payable","boolean"!=typeof t.payable||t.payable||(e="nonpayable"))):"boolean"!=typeof t.payable||t.payable||(e="nonpayable")),new zr(Ir,t.name,e,t.inputs?t.inputs.map(Br.from):[],t.outputs?t.outputs.map(Br.from):[],null!=t.gas?t.gas:null)}static isFragment(t){return t&&t[Sr]===Lr}}class Jr extends $r{constructor(t,e,n){super(t,"struct",e,n),Object.defineProperty(this,Sr,{value:Dr})}format(){throw new Error("@TODO")}static from(t){if("string"==typeof t)try{return Jr.from(wr(t))}catch(e){N(!1,"invalid struct fragment","obj",t)}else if(t instanceof br){const e=Er("struct",t),n=kr(t);return Rr(t),new Jr(Ir,e,n)}return new Jr(Ir,t.name,t.inputs?t.inputs.map(Br.from):[])}static isFragment(t){return t&&t[Sr]===Dr}}const qr=new Map;qr.set(0,"GENERIC_PANIC"),qr.set(1,"ASSERT_FALSE"),qr.set(17,"OVERFLOW"),qr.set(18,"DIVIDE_BY_ZERO"),qr.set(33,"ENUM_RANGE_ERROR"),qr.set(34,"BAD_STORAGE_DATA"),qr.set(49,"STACK_UNDERFLOW"),qr.set(50,"ARRAY_RANGE_ERROR"),qr.set(65,"OUT_OF_MEMORY"),qr.set(81,"UNINITIALIZED_FUNCTION_CALL");const Wr=new RegExp(/^bytes([0-9]*)$/),Yr=new RegExp(/^(u?int)([0-9]*)$/);let Xr=null,Zr=1024;class Qr{#ct(t){if(t.isArray())return new tn(this.#ct(t.arrayChildren),t.arrayLength,t.name);if(t.isTuple())return new pn(t.components.map((t=>this.#ct(t))),t.name);switch(t.baseType){case"address":return new Ye(t.name);case"bool":return new en(t.name);case"string":return new dn(t.name);case"bytes":return new rn(t.name);case"":return new on(t.name)}let e=t.type.match(Yr);if(e){let n=parseInt(e[2]||"256");return N(0!==n&&n<=256&&n%8==0,"invalid "+e[1]+" bit length","param",t),new hn(n/8,"int"===e[1],t.name)}if(e=t.type.match(Wr),e){let n=parseInt(e[1]);return N(0!==n&&n<=32,"invalid bytes length","param",t),new sn(n,t.name)}N(!1,"invalid type","type",t.type)}getDefaultValue(t){const e=t.map((t=>this.#ct(Br.from(t))));return new pn(e,"_").defaultValue()}encode(t,e){P(e.length,t.length,"types/values length mismatch");const n=t.map((t=>this.#ct(Br.from(t)))),r=new pn(n,"_"),s=new Ht;return r.encode(s,e),s.data}decode(t,e,n){const r=t.map((t=>this.#ct(Br.from(t))));return new pn(r,"_").decode(new Vt(e,n,Zr))}static _setDefaultMaxInflation(t){N("number"==typeof t&&Number.isInteger(t),"invalid defaultMaxInflation factor","value",t),Zr=t}static defaultAbiCoder(){return null==Xr&&(Xr=new Qr),Xr}static getBuiltinCallException(t,e,n){return function(t,e,n,r){let s="missing revert data",i=null,a=null;if(n){s="execution reverted";const t=O(n);if(n=_(n),0===t.length)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(t.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===_(t.slice(0,4)))try{i=r.decode(["string"],t.slice(4))[0],a={signature:"Error(string)",name:"Error",args:[i]},s+=`: ${JSON.stringify(i)}`}catch(t){s+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===_(t.slice(0,4)))try{const e=Number(r.decode(["uint256"],t.slice(4))[0]);a={signature:"Panic(uint256)",name:"Panic",args:[e]},i=`Panic due to ${qr.get(e)||"UNKNOWN"}(${e})`,s+=`: ${i}`}catch(t){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const o={to:e.to?Me(e.to):null,data:e.data||"0x"};return e.from&&(o.from=Me(e.from)),v(s,"CALL_EXCEPTION",{action:t,data:n,reason:i,transaction:o,invocation:null,revert:a})}(t,e,n,Qr.defaultAbiCoder())}}class ts{fragment;name;signature;topic;args;constructor(t,e,n){const r=t.name,s=t.format();y(this,{fragment:t,name:r,signature:s,topic:e,args:n})}}class es{fragment;name;args;signature;selector;value;constructor(t,e,n,r){const s=t.name,i=t.format();y(this,{fragment:t,name:s,args:n,signature:i,selector:e,value:r})}}class ns{fragment;name;args;signature;selector;constructor(t,e,n){const r=t.name,s=t.format();y(this,{fragment:t,name:r,args:n,signature:s,selector:e})}}class rs{hash;_isIndexed;static isIndexed(t){return!(!t||!t._isIndexed)}constructor(t){y(this,{hash:t,_isIndexed:!0})}}const ss={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"},is={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:t=>`reverted with reason string ${JSON.stringify(t)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:t=>{let e="unknown panic code";return t>=0&&t<=255&&ss[t.toString()]&&(e=ss[t.toString()]),`reverted with panic code 0x${t.toString(16)} (${e})`}}};class as{fragments;deploy;fallback;receive;#lt;#ut;#ht;#dt;constructor(t){let e=[];e="string"==typeof t?JSON.parse(t):t,this.#ht=new Map,this.#lt=new Map,this.#ut=new Map;const n=[];for(const t of e)try{n.push(Gr.from(t))}catch(e){console.log(`[Warning] Invalid Fragment ${JSON.stringify(t)}:`,e.message)}y(this,{fragments:Object.freeze(n)});let r=null,s=!1;this.#dt=this.getAbiCoder(),this.fragments.forEach(((t,e)=>{let n;switch(t.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void y(this,{deploy:t});case"fallback":return void(0===t.inputs.length?s=!0:(N(!r||t.payable!==r.payable,"conflicting fallback fragments",`fragments[${e}]`,t),r=t,s=r.payable));case"function":n=this.#ht;break;case"event":n=this.#ut;break;case"error":n=this.#lt;break;default:return}const i=t.format();n.has(i)||n.set(i,t)})),this.deploy||y(this,{deploy:Hr.from("constructor()")}),y(this,{fallback:r,receive:s})}format(t){const e=t?"minimal":"full";return this.fragments.map((t=>t.format(e)))}formatJson(){const t=this.fragments.map((t=>t.format("json")));return JSON.stringify(t.map((t=>JSON.parse(t))))}getAbiCoder(){return Qr.defaultAbiCoder()}#pt(t,e,n){if(S(t)){const e=t.toLowerCase();for(const t of this.#ht.values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of this.#ht)e.split("(")[0]===t&&r.push(n);if(e){const t=e.length>0?e[e.length-1]:null;let n=e.length,s=!0;We.isTyped(t)&&"overrides"===t.type&&(s=!1,n--);for(let t=r.length-1;t>=0;t--){const e=r[t].inputs.length;e===n||s&&e===n-1||r.splice(t,1)}for(let t=r.length-1;t>=0;t--){const n=r[t].inputs;for(let s=0;s<e.length;s++)if(We.isTyped(e[s])){if(s>=n.length){if("overrides"===e[s].type)continue;r.splice(t,1);break}if(e[s].type!==n[s].baseType){r.splice(t,1);break}}}}if(1===r.length&&e&&e.length!==r[0].inputs.length){const t=e[e.length-1];(null==t||Array.isArray(t)||"object"!=typeof t)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){N(!1,`ambiguous function description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=this.#ht.get(zr.from(t).format());return r||null}getFunctionName(t){const e=this.#pt(t,null,!1);return N(e,"no matching function","key",t),e.name}hasFunction(t){return!!this.#pt(t,null,!1)}getFunction(t,e){return this.#pt(t,e||null,!0)}forEachFunction(t){const e=Array.from(this.#ht.keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(this.#ht.get(r),n)}}#ft(t,e,n){if(S(t)){const e=t.toLowerCase();for(const t of this.#ut.values())if(e===t.topicHash)return t;return null}if(-1===t.indexOf("(")){const r=[];for(const[e,n]of this.#ut)e.split("(")[0]===t&&r.push(n);if(e){for(let t=r.length-1;t>=0;t--)r[t].inputs.length<e.length&&r.splice(t,1);for(let t=r.length-1;t>=0;t--){const n=r[t].inputs;for(let s=0;s<e.length;s++)if(We.isTyped(e[s])&&e[s].type!==n[s].baseType){r.splice(t,1);break}}}if(0===r.length)return null;if(r.length>1&&n){N(!1,`ambiguous event description (i.e. matches ${r.map((t=>JSON.stringify(t.format()))).join(", ")})`,"key",t)}return r[0]}const r=this.#ut.get(Kr.from(t).format());return r||null}getEventName(t){const e=this.#ft(t,null,!1);return N(e,"no matching event","key",t),e.name}hasEvent(t){return!!this.#ft(t,null,!1)}getEvent(t,e){return this.#ft(t,e||null,!0)}forEachEvent(t){const e=Array.from(this.#ut.keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(this.#ut.get(r),n)}}getError(t,e){if(S(t)){const e=t.toLowerCase();if(is[e])return jr.from(is[e].signature);for(const t of this.#lt.values())if(e===t.selector)return t;return null}if(-1===t.indexOf("(")){const e=[];for(const[n,r]of this.#lt)n.split("(")[0]===t&&e.push(r);if(0===e.length)return"Error"===t?jr.from("error Error(string)"):"Panic"===t?jr.from("error Panic(uint256)"):null;if(e.length>1){N(!1,`ambiguous error description (i.e. ${e.map((t=>JSON.stringify(t.format()))).join(", ")})`,"name",t)}return e[0]}if("Error(string)"===(t=jr.from(t).format()))return jr.from("error Error(string)");if("Panic(uint256)"===t)return jr.from("error Panic(uint256)");const n=this.#lt.get(t);return n||null}forEachError(t){const e=Array.from(this.#lt.keys());e.sort(((t,e)=>t.localeCompare(e)));for(let n=0;n<e.length;n++){const r=e[n];t(this.#lt.get(r),n)}}_decodeParams(t,e){return this.#dt.decode(t,e)}_encodeParams(t,e){return this.#dt.encode(t,e)}encodeDeploy(t){return this._encodeParams(this.deploy.inputs,t||[])}decodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);N(e,"unknown error","fragment",t),t=e}return N(L(e,0,4)===t.selector,`data signature does not match error ${t.name}.`,"data",e),this._decodeParams(t.inputs,L(e,4))}encodeErrorResult(t,e){if("string"==typeof t){const e=this.getError(t);N(e,"unknown error","fragment",t),t=e}return U([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);N(e,"unknown function","fragment",t),t=e}return N(L(e,0,4)===t.selector,`data signature does not match function ${t.name}.`,"data",e),this._decodeParams(t.inputs,L(e,4))}encodeFunctionData(t,e){if("string"==typeof t){const e=this.getFunction(t);N(e,"unknown function","fragment",t),t=e}return U([t.selector,this._encodeParams(t.inputs,e||[])])}decodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);N(e,"unknown function","fragment",t),t=e}let n="invalid length for result data";const r=I(e);if(r.length%32==0)try{return this.#dt.decode(t.outputs,r)}catch(t){n="could not decode result data"}E(!1,n,"BAD_DATA",{value:_(r),info:{method:t.name,signature:t.format()}})}makeError(t,e){const n=O(t,"data"),r=Qr.getBuiltinCallException("call",e,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const t=_(n.slice(0,4)),e=this.getError(t);if(e)try{const t=this.#dt.decode(e.inputs,n.slice(4));r.revert={name:e.name,signature:e.format(),args:t},r.reason=r.revert.signature,r.message=`execution reverted: ${r.reason}`}catch(t){r.message="execution reverted (coult not decode custom error)"}}const s=this.parseTransaction(e);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(t,e){if("string"==typeof t){const e=this.getFunction(t);N(e,"unknown function","fragment",t),t=e}return _(this.#dt.encode(t.outputs,e||[]))}encodeFilterTopics(t,e){if("string"==typeof t){const e=this.getEvent(t);N(e,"unknown event","eventFragment",t),t=e}E(e.length<=t.inputs.length,`too many arguments for ${t.format()}`,"UNEXPECTED_ARGUMENT",{count:e.length,expectedCount:t.inputs.length});const n=[];t.anonymous||n.push(t.topicHash);const r=(t,e)=>"string"===t.type?fn(e):"bytes"===t.type?Qt(_(e)):("bool"===t.type&&"boolean"==typeof e?e=e?"0x01":"0x00":t.type.match(/^u?int/)?e=W(e):t.type.match(/^bytes/)?e=D(e,32,!1):"address"===t.type&&this.#dt.encode(["address"],[e]),B(_(e),32));for(e.forEach(((e,s)=>{const i=t.inputs[s];i.indexed?null==e?n.push(null):"array"===i.baseType||"tuple"===i.baseType?N(!1,"filtering with tuples or arrays not supported","contract."+i.name,e):Array.isArray(e)?n.push(e.map((t=>r(i,t)))):n.push(r(i,e)):N(null==e,"cannot filter non-indexed parameters; must be null","contract."+i.name,e)}));n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(t,e){if("string"==typeof t){const e=this.getEvent(t);N(e,"unknown event","eventFragment",t),t=e}const n=[],r=[],s=[];return t.anonymous||n.push(t.topicHash),N(e.length===t.inputs.length,"event arguments/values mismatch","values",e),t.inputs.forEach(((t,i)=>{const a=e[i];if(t.indexed)if("string"===t.type)n.push(fn(a));else if("bytes"===t.type)n.push(Qt(a));else{if("tuple"===t.baseType||"array"===t.baseType)throw new Error("not implemented");n.push(this.#dt.encode([t.type],[a]))}else r.push(t),s.push(a)})),{data:this.#dt.encode(r,s),topics:n}}decodeEventLog(t,e,n){if("string"==typeof t){const e=this.getEvent(t);N(e,"unknown event","eventFragment",t),t=e}if(null!=n&&!t.anonymous){const e=t.topicHash;N(S(n[0],32)&&n[0].toLowerCase()===e,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],i=[];t.inputs.forEach(((t,e)=>{t.indexed?"string"===t.type||"bytes"===t.type||"tuple"===t.baseType||"array"===t.baseType?(r.push(Br.from({type:"bytes32",name:t.name})),i.push(!0)):(r.push(t),i.push(!1)):(s.push(t),i.push(!1))}));const a=null!=n?this.#dt.decode(r,U(n)):null,o=this.#dt.decode(s,e,!0),c=[],l=[];let u=0,h=0;return t.inputs.forEach(((t,e)=>{let n=null;if(t.indexed)if(null==a)n=new rs(null);else if(i[e])n=new rs(a[h++]);else try{n=a[h++]}catch(t){n=t}else try{n=o[u++]}catch(t){n=t}c.push(n),l.push(t.name||null)})),Mt.fromItems(c,l)}parseTransaction(t){const e=O(t.data,"tx.data"),n=H(null!=t.value?t.value:0,"tx.value"),r=this.getFunction(_(e.slice(0,4)));if(!r)return null;const s=this.#dt.decode(r.inputs,e.slice(4));return new es(r,r.selector,s,n)}parseCallResult(t){throw new Error("@TODO")}parseLog(t){const e=this.getEvent(t.topics[0]);return!e||e.anonymous?null:new ts(e,e.topicHash,this.decodeEventLog(e,t.data,t.topics))}parseError(t){const e=_(t),n=this.getError(L(e,0,4));if(!n)return null;const r=this.#dt.decode(n.inputs,L(e,4));return new ns(n,n.selector,r)}static from(t){return t instanceof as?t:"string"==typeof t?new as(JSON.parse(t)):"function"==typeof t.formatJson?new as(t.formatJson()):"function"==typeof t.format?new as(t.format("json")):new as(t)}}const os=BigInt(0);function cs(t){return null==t?null:t}function ls(t){return null==t?null:t.toString()}class us{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(t,e,n){y(this,{gasPrice:cs(t),maxFeePerGas:cs(e),maxPriorityFeePerGas:cs(n)})}toJSON(){const{gasPrice:t,maxFeePerGas:e,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:ls(t),maxFeePerGas:ls(e),maxPriorityFeePerGas:ls(n)}}}function hs(t){const e={};t.to&&(e.to=t.to),t.from&&(e.from=t.from),t.data&&(e.data=_(t.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const r of n)r in t&&null!=t[r]&&(e[r]=H(t[r],`request.${r}`));const r="type,nonce".split(/,/);for(const n of r)n in t&&null!=t[n]&&(e[n]=q(t[n],`request.${n}`));return t.accessList&&(e.accessList=En(t.accessList)),"blockTag"in t&&(e.blockTag=t.blockTag),"enableCcipRead"in t&&(e.enableCcipRead=!!t.enableCcipRead),"customData"in t&&(e.customData=t.customData),"blobVersionedHashes"in t&&t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.slice()),"kzg"in t&&(e.kzg=t.kzg),"blobs"in t&&t.blobs&&(e.blobs=t.blobs.map((t=>x(t)?_(t):Object.assign({},t)))),e}class ds{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#gt;constructor(t,e){this.#gt=t.transactions.map((t=>"string"!=typeof t?new gs(t,e):t)),y(this,{provider:e,hash:cs(t.hash),number:t.number,timestamp:t.timestamp,parentHash:t.parentHash,parentBeaconBlockRoot:t.parentBeaconBlockRoot,nonce:t.nonce,difficulty:t.difficulty,gasLimit:t.gasLimit,gasUsed:t.gasUsed,blobGasUsed:t.blobGasUsed,excessBlobGas:t.excessBlobGas,miner:t.miner,prevRandao:cs(t.prevRandao),extraData:t.extraData,baseFeePerGas:cs(t.baseFeePerGas),stateRoot:t.stateRoot,receiptsRoot:t.receiptsRoot})}get transactions(){return this.#gt.map((t=>"string"==typeof t?t:t.hash))}get prefetchedTransactions(){const t=this.#gt.slice();return 0===t.length?[]:(E("object"==typeof t[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),t)}toJSON(){const{baseFeePerGas:t,difficulty:e,extraData:n,gasLimit:r,gasUsed:s,hash:i,miner:a,prevRandao:o,nonce:c,number:l,parentHash:u,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:p,timestamp:f,transactions:g}=this;return{_type:"Block",baseFeePerGas:ls(t),difficulty:ls(e),extraData:n,gasLimit:ls(r),gasUsed:ls(s),blobGasUsed:ls(this.blobGasUsed),excessBlobGas:ls(this.excessBlobGas),hash:i,miner:a,prevRandao:o,nonce:c,number:l,parentHash:u,timestamp:f,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:p,transactions:g}}[Symbol.iterator](){let t=0;const e=this.transactions;return{next:()=>t<this.length?{value:e[t++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#gt.length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(t){let e;if("number"==typeof t)e=this.#gt[t];else{const n=t.toLowerCase();for(const t of this.#gt){if("string"==typeof t){if(t!==n)continue;e=t;break}if(t.hash!==n){e=t;break}}}if(null==e)throw new Error("no such tx");return"string"==typeof e?await this.provider.getTransaction(e):e}getPrefetchedTransaction(t){const e=this.prefetchedTransactions;if("number"==typeof t)return e[t];t=t.toLowerCase();for(const n of e)if(n.hash===t)return n;N(!1,"no matching transaction","indexOrHash",t)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(t=this).hash,number:t.number};var t}}class ps{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(t,e){this.provider=e;const n=Object.freeze(t.topics.slice());y(this,{transactionHash:t.transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,removed:t.removed,address:t.address,data:t.data,topics:n,index:t.index,transactionIndex:t.transactionIndex})}toJSON(){const{address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:a,transactionHash:o,transactionIndex:c}=this;return{_type:"log",address:t,blockHash:e,blockNumber:n,data:r,index:s,removed:i,topics:a,transactionHash:o,transactionIndex:c}}async getBlock(){const t=await this.provider.getBlock(this.blockHash);return E(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransaction(){const t=await this.provider.getTransaction(this.transactionHash);return E(!!t,"failed to find transaction","UNKNOWN_ERROR",{}),t}async getTransactionReceipt(){const t=await this.provider.getTransactionReceipt(this.transactionHash);return E(!!t,"failed to find transaction receipt","UNKNOWN_ERROR",{}),t}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(t=this).transactionHash,blockHash:t.blockHash,blockNumber:t.blockNumber,address:t.address,data:t.data,topics:Object.freeze(t.topics.slice()),index:t.index}};var t}}class fs{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#yt;constructor(t,e){this.#yt=Object.freeze(t.logs.map((t=>new ps(t,e))));let n=os;null!=t.effectiveGasPrice?n=t.effectiveGasPrice:null!=t.gasPrice&&(n=t.gasPrice),y(this,{provider:e,to:t.to,from:t.from,contractAddress:t.contractAddress,hash:t.hash,index:t.index,blockHash:t.blockHash,blockNumber:t.blockNumber,logsBloom:t.logsBloom,gasUsed:t.gasUsed,cumulativeGasUsed:t.cumulativeGasUsed,blobGasUsed:t.blobGasUsed,gasPrice:n,blobGasPrice:t.blobGasPrice,type:t.type,status:t.status,root:t.root})}get logs(){return this.#yt}toJSON(){const{to:t,from:e,contractAddress:n,hash:r,index:s,blockHash:i,blockNumber:a,logsBloom:o,logs:c,status:l,root:u}=this;return{_type:"TransactionReceipt",blockHash:i,blockNumber:a,contractAddress:n,cumulativeGasUsed:ls(this.cumulativeGasUsed),from:e,gasPrice:ls(this.gasPrice),blobGasUsed:ls(this.blobGasUsed),blobGasPrice:ls(this.blobGasPrice),gasUsed:ls(this.gasUsed),hash:r,index:s,logs:c,logsBloom:o,root:u,status:l,to:t}}get length(){return this.logs.length}[Symbol.iterator](){let t=0;return{next:()=>t<this.length?{value:this.logs[t++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const t=await this.provider.getBlock(this.blockHash);if(null==t)throw new Error("TODO");return t}async getTransaction(){const t=await this.provider.getTransaction(this.hash);if(null==t)throw new Error("TODO");return t}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return ms(this)}reorderedEvent(t){return E(!t||t.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),ys(this,t)}}class gs{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;#mt;constructor(t,e){this.provider=e,this.blockNumber=null!=t.blockNumber?t.blockNumber:null,this.blockHash=null!=t.blockHash?t.blockHash:null,this.hash=t.hash,this.index=t.index,this.type=t.type,this.from=t.from,this.to=t.to||null,this.gasLimit=t.gasLimit,this.nonce=t.nonce,this.data=t.data,this.value=t.value,this.gasPrice=t.gasPrice,this.maxPriorityFeePerGas=null!=t.maxPriorityFeePerGas?t.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=t.maxFeePerGas?t.maxFeePerGas:null,this.maxFeePerBlobGas=null!=t.maxFeePerBlobGas?t.maxFeePerBlobGas:null,this.chainId=t.chainId,this.signature=t.signature,this.accessList=null!=t.accessList?t.accessList:null,this.blobVersionedHashes=null!=t.blobVersionedHashes?t.blobVersionedHashes:null,this.#mt=-1}toJSON(){const{blockNumber:t,blockHash:e,index:n,hash:r,type:s,to:i,from:a,nonce:o,data:c,signature:l,accessList:u,blobVersionedHashes:h}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:t,blockHash:e,blobVersionedHashes:h,chainId:ls(this.chainId),data:c,from:a,gasLimit:ls(this.gasLimit),gasPrice:ls(this.gasPrice),hash:r,maxFeePerGas:ls(this.maxFeePerGas),maxPriorityFeePerGas:ls(this.maxPriorityFeePerGas),maxFeePerBlobGas:ls(this.maxFeePerBlobGas),nonce:o,signature:l,to:i,index:n,type:s,value:ls(this.value)}}async getBlock(){let t=this.blockNumber;if(null==t){const e=await this.getTransaction();e&&(t=e.blockNumber)}if(null==t)return null;const e=this.provider.getBlock(t);if(null==e)throw new Error("TODO");return e}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:t,blockNumber:e}=await g({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==t||null==t.blockNumber?0:e-t.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(t,e){const n=null==t?1:t,r=null==e?0:e;let s=this.#mt,i=-1,a=-1===s;const o=async()=>{if(a)return null;const{blockNumber:t,nonce:e}=await g({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(e<this.nonce)return void(s=t);if(a)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===i&&(i=s-3,i<this.#mt&&(i=this.#mt));i<=t;){if(a)return null;const e=await this.provider.getBlock(i,!0);if(null==e)return;for(const t of e)if(t===this.hash)return;for(let r=0;r<e.length;r++){const i=await e.getTransaction(r);if(i.from===this.from&&i.nonce===this.nonce){if(a)return null;const e=await this.provider.getTransactionReceipt(i.hash);if(null==e)return;if(t-e.blockNumber+1<n)return;let r="replaced";i.data===this.data&&i.to===this.to&&i.value===this.value?r="repriced":"0x"===i.data&&i.from===i.to&&i.value===os&&(r="cancelled"),E(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:i.replaceableTransaction(s),hash:i.hash,receipt:e})}}i++}},c=t=>{if(null==t||0!==t.status)return t;E(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:t.to,from:t.from,data:""},receipt:t})},l=await this.provider.getTransactionReceipt(this.hash);if(0===n)return c(l);if(l){if(await l.confirmations()>=n)return c(l)}else if(await o(),0===n)return null;const u=new Promise(((t,e)=>{const i=[],l=()=>{i.forEach((t=>t()))};if(i.push((()=>{a=!0})),r>0){const t=setTimeout((()=>{l(),e(v("wait for transaction timeout","TIMEOUT"))}),r);i.push((()=>{clearTimeout(t)}))}const u=async r=>{if(await r.confirmations()>=n){l();try{t(c(r))}catch(t){e(t)}}};if(i.push((()=>{this.provider.off(this.hash,u)})),this.provider.on(this.hash,u),s>=0){const t=async()=>{try{await o()}catch(t){if(b(t,"TRANSACTION_REPLACED"))return l(),void e(t)}a||this.provider.once("block",t)};i.push((()=>{this.provider.off("block",t)})),this.provider.once("block",t)}}));return await u}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return E(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),ms(this)}reorderedEvent(t){return E(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),E(!t||t.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),ys(this,t)}replaceableTransaction(t){N(Number.isInteger(t)&&t>=0,"invalid startBlock","startBlock",t);const e=new gs(this,this.provider);return e.#mt=t,e}}function ys(t,e){return{orphan:"reorder-transaction",tx:t,other:e}}function ms(t){return{orphan:"drop-transaction",tx:t}}class bs extends ps{interface;fragment;args;constructor(t,e,n){super(t,t.provider);y(this,{args:e.decodeEventLog(n,t.data,t.topics),fragment:n,interface:e})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class ws extends ps{error;constructor(t,e){super(t,t.provider),y(this,{error:e})}}class vs extends fs{#bt;constructor(t,e,n){super(n,e),this.#bt=t}get logs(){return super.logs.map((t=>{const e=t.topics.length?this.#bt.getEvent(t.topics[0]):null;if(e)try{return new bs(t,this.#bt,e)}catch(e){return new ws(t,e)}return t}))}}class Es extends gs{#bt;constructor(t,e,n){super(n,e),this.#bt=t}async wait(t,e){const n=await super.wait(t,e);return null==n?null:new vs(this.#bt,this.provider,n)}}class Ns extends st{log;constructor(t,e,n,r){super(t,e,n),y(this,{log:r})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class Ps extends Ns{constructor(t,e,n,r,s){super(t,e,n,new bs(s,t.interface,r));y(this,{args:t.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const ks=BigInt(0);function Ts(t){return t&&"function"==typeof t.call}function Rs(t){return t&&"function"==typeof t.estimateGas}function As(t){return t&&"function"==typeof t.resolveName}function Os(t){return t&&"function"==typeof t.sendTransaction}function Is(t){if(null!=t){if(As(t))return t;if(t.provider)return t.provider}}class Ss{#wt;fragment;constructor(t,e,n){if(y(this,{fragment:e}),e.inputs.length<n.length)throw new Error("too many arguments");const r=xs(t.runner,"resolveName"),s=As(r)?r:null;this.#wt=async function(){const r=await Promise.all(e.inputs.map(((t,e)=>null==n[e]?null:t.walkAsync(n[e],((t,e)=>"address"===t?Array.isArray(e)?Promise.all(e.map((t=>He(t,s)))):He(e,s):e)))));return t.interface.encodeFilterTopics(e,r)}()}getTopicFilter(){return this.#wt}}function xs(t,e){return null==t?null:"function"==typeof t[e]?t:t.provider&&"function"==typeof t.provider[e]?t.provider:null}function Cs(t){return null==t?null:t.provider||null}async function _s(t,e){const n=We.dereference(t,"overrides");N("object"==typeof n,"invalid overrides parameter","overrides",t);const r=hs(n);return N(null==r.to||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),N(null==r.data||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}function Us(t){const e=async function(e){const n=await _s(e,["data"]);n.to=await t.getAddress(),n.from&&(n.from=await He(n.from,Is(t.runner)));const r=t.interface,s=H(n.value||ks,"overrides.value")===ks,i="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||i||s||N(!1,"cannot send data to receive or send value to non-payable fallback","overrides",e),N(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return N(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),N(r.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=t.runner;E(Os(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await e(n)),i=Cs(t.runner);return new Es(t.interface,i,s)},r=async t=>await n(t);return y(r,{_contract:t,estimateGas:async function(n){const r=xs(t.runner,"estimateGas");return E(Rs(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await e(n))},populateTransaction:e,send:n,staticCall:async function(n){const r=xs(t.runner,"call");E(Ts(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await e(n);try{return await r.call(s)}catch(e){if(w(e)&&e.data)throw t.interface.makeError(e.data,s);throw e}}}),r}function Fs(t,e){const n=function(...n){const r=t.interface.getFunction(e,n);return E(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=async function(...e){const r=n(...e);let s={};if(r.inputs.length+1===e.length&&(s=await _s(e.pop()),s.from&&(s.from=await He(s.from,Is(t.runner)))),r.inputs.length!==e.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await async function(t,e,n){const r=xs(t,"resolveName"),s=As(r)?r:null;return await Promise.all(e.map(((t,e)=>t.walkAsync(n[e],((t,e)=>(e=We.dereference(e,t),"address"===t?He(e,s):e))))))}(t.runner,r.inputs,e);return Object.assign({},s,await g({to:t.getAddress(),data:t.interface.encodeFunctionData(r,i)}))},s=async function(...t){const e=await a(...t);return 1===e.length?e[0]:e},i=async function(...e){const n=t.runner;E(Os(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...e)),i=Cs(t.runner);return new Es(t.interface,i,s)},a=async function(...e){const s=xs(t.runner,"call");E(Ts(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await r(...e);let a="0x";try{a=await s.call(i)}catch(e){if(w(e)&&e.data)throw t.interface.makeError(e.data,i);throw e}const o=n(...e);return t.interface.decodeFunctionResult(o,a)},o=async(...t)=>n(...t).constant?await s(...t):await i(...t);return y(o,{name:t.interface.getFunctionName(e),_contract:t,_key:e,getFragment:n,estimateGas:async function(...e){const n=xs(t.runner,"estimateGas");return E(Rs(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...e))},populateTransaction:r,send:i,staticCall:s,staticCallResult:a}),Object.defineProperty(o,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getFunction(e);return E(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),o}const Ls=Symbol.for("_ethersInternal_contract"),Ds=new WeakMap;function Bs(t){return Ds.get(t[Ls])}async function Gs(t,e){let n,r=null;if(Array.isArray(e)){const r=function(e){if(S(e,32))return e;const n=t.interface.getEvent(e);return N(n,"unknown fragment","name",e),n.topicHash};n=e.map((t=>null==t?null:Array.isArray(t)?t.map(r):r(t)))}else"*"===e?n=[null]:"string"==typeof e?S(e,32)?n=[e]:(r=t.interface.getEvent(e),N(r,"unknown fragment","event",e),n=[r.topicHash]):(s=e)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await e.getTopicFilter():"fragment"in e?(r=e.fragment,n=[r.topicHash]):N(!1,"unknown event name","event",e);var s;n=n.map((t=>{if(null==t)return null;if(Array.isArray(t)){const e=Array.from(new Set(t.map((t=>t.toLowerCase()))).values());return 1===e.length?e[0]:(e.sort(),e)}return t.toLowerCase()}));return{fragment:r,tag:n.map((t=>null==t?"null":Array.isArray(t)?t.join("|"):t)).join("&"),topics:n}}async function $s(t,e){const{subs:n}=Bs(t);return n.get((await Gs(t,e)).tag)||null}async function Ms(t,e,n){const r=Cs(t.runner);E(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:i,topics:a}=await Gs(t,n),{addr:o,subs:c}=Bs(t);let l=c.get(i);if(!l){const e={address:o||t,topics:a},u=e=>{let r=s;if(null==r)try{r=t.interface.getEvent(e.topics[0])}catch(t){}if(r){const i=r,a=s?t.interface.decodeEventLog(s,e.data,e.topics):[];Ks(t,n,a,(r=>new Ps(t,r,n,i,e)))}else Ks(t,n,[],(r=>new Ns(t,r,n,e)))};let h=[];l={tag:i,listeners:[],start:()=>{h.length||h.push(r.on(e,u))},stop:async()=>{if(0==h.length)return;let t=h;h=[],await Promise.all(t),r.off(e,u)}},c.set(i,l)}return l}let js=Promise.resolve();async function Ks(t,e,n,r){try{await js}catch(t){}const s=async function(t,e,n,r){await js;const s=await $s(t,e);if(!s)return!1;const i=s.listeners.length;return s.listeners=s.listeners.filter((({listener:e,once:s})=>{const i=Array.from(n);r&&i.push(r(s?null:e));try{e.call(t,...i)}catch(t){}return!s})),0===s.listeners.length&&(s.stop(),Bs(t).subs.delete(s.tag)),i>0}(t,e,n,r);return js=s,await s}const Hs=["then"];class Vs{target;interface;runner;filters;[Ls];fallback;constructor(t,e,n,r){N("string"==typeof t||je(t),"invalid value for Contract target","target",t),null==n&&(n=null);const s=as.from(e);let i;y(this,{target:t,runner:n,interface:s}),Object.defineProperty(this,Ls,{value:{}});let a=null,o=null;if(r){const t=Cs(n);o=new Es(this.interface,t,r)}let c=new Map;if("string"==typeof t)if(S(t))a=t,i=Promise.resolve(t);else{const e=xs(n,"resolveName");if(!As(e))throw v("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=e.resolveName(t).then((e=>{if(null==e)throw v("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:t});return Bs(this).addr=e,e}))}else i=t.getAddress().then((t=>{if(null==t)throw new Error("TODO");return Bs(this).addr=t,t}));var l,u;l=this,u={addrPromise:i,addr:a,deployTx:o,subs:c},Ds.set(l[Ls],u);const h=new Proxy({},{get:(t,e,n)=>{if("symbol"==typeof e||Hs.indexOf(e)>=0)return Reflect.get(t,e,n);try{return this.getEvent(e)}catch(t){if(!b(t,"INVALID_ARGUMENT")||"key"!==t.argument)throw t}},has:(t,e)=>Hs.indexOf(e)>=0?Reflect.has(t,e):Reflect.has(t,e)||this.interface.hasEvent(String(e))});return y(this,{filters:h}),y(this,{fallback:s.receive||s.fallback?Us(this):null}),new Proxy(this,{get:(t,e,n)=>{if("symbol"==typeof e||e in t||Hs.indexOf(e)>=0)return Reflect.get(t,e,n);try{return t.getFunction(e)}catch(t){if(!b(t,"INVALID_ARGUMENT")||"key"!==t.argument)throw t}},has:(t,e)=>"symbol"==typeof e||e in t||Hs.indexOf(e)>=0?Reflect.has(t,e):t.interface.hasFunction(e)})}connect(t){return new Vs(this.target,this.interface,t)}attach(t){return new Vs(t,this.interface,this.runner)}async getAddress(){return await Bs(this).addrPromise}async getDeployedCode(){const t=Cs(this.runner);E(t,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const e=await t.getCode(await this.getAddress());return"0x"===e?null:e}async waitForDeployment(){const t=this.deploymentTransaction();if(t)return await t.wait(),this;if(null!=await this.getDeployedCode())return this;const e=Cs(this.runner);return E(null!=e,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((t,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return t(this);e.once("block",r)}catch(t){n(t)}};r()}))}deploymentTransaction(){return Bs(this).deployTx}getFunction(t){"string"!=typeof t&&(t=t.format());return Fs(this,t)}getEvent(t){return"string"!=typeof t&&(t=t.format()),function(t,e){const n=function(...n){const r=t.interface.getEvent(e,n);return E(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:n}}),r},r=function(...e){return new Ss(t,n(...e),e)};return y(r,{name:t.interface.getEventName(e),_contract:t,_key:e,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=t.interface.getEvent(e);return E(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),n}}),r}(this,t)}async queryTransaction(t){throw new Error("@TODO")}async queryFilter(t,e,n){null==e&&(e=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=Bs(this),i=r||await s,{fragment:a,topics:o}=await Gs(this,t),c={address:i,topics:o,fromBlock:e,toBlock:n},l=Cs(this.runner);return E(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(c)).map((t=>{let e=a;if(null==e)try{e=this.interface.getEvent(t.topics[0])}catch(t){}if(e)try{return new bs(t,this.interface,e)}catch(e){return new ws(t,e)}return new ps(t,l)}))}async on(t,e){const n=await Ms(this,"on",t);return n.listeners.push({listener:e,once:!1}),n.start(),this}async once(t,e){const n=await Ms(this,"once",t);return n.listeners.push({listener:e,once:!0}),n.start(),this}async emit(t,...e){return await Ks(this,t,e,null)}async listenerCount(t){if(t){const e=await $s(this,t);return e?e.listeners.length:0}const{subs:e}=Bs(this);let n=0;for(const{listeners:t}of e.values())n+=t.length;return n}async listeners(t){if(t){const e=await $s(this,t);return e?e.listeners.map((({listener:t})=>t)):[]}const{subs:e}=Bs(this);let n=[];for(const{listeners:t}of e.values())n=n.concat(t.map((({listener:t})=>t)));return n}async off(t,e){const n=await $s(this,t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return null!=e&&0!==n.listeners.length||(n.stop(),Bs(this).subs.delete(n.tag)),this}async removeAllListeners(t){if(t){const e=await $s(this,t);if(!e)return this;e.stop(),Bs(this).subs.delete(e.tag)}else{const{subs:t}=Bs(this);for(const{tag:e,stop:n}of t.values())n(),t.delete(e)}return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return await this.off(t,e)}static buildClass(t){return class extends Vs{constructor(e,n=null){super(e,t,n)}}}static from(t,e,n){null==n&&(n=null);return new this(t,e,n)}}class zs extends(function(){return Vs}()){}function Js(t){return t.match(/^ipfs:\/\/ipfs\//i)?t=t.substring(12):t.match(/^ipfs:\/\//i)?t=t.substring(7):N(!1,"unsupported IPFS format","link",t),`https://gateway.ipfs.io/ipfs/${t}`}class qs{name;constructor(t){y(this,{name:t})}connect(t){return this}supportsCoinType(t){return!1}async encodeAddress(t,e){throw new Error("unsupported coin")}async decodeAddress(t,e){throw new Error("unsupported coin")}}const Ws=new RegExp("^(ipfs)://(.*)$","i"),Ys=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),Ws,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class Xs{provider;address;name;#vt;#Et;constructor(t,e,n){y(this,{provider:t,address:e,name:n}),this.#vt=null,this.#Et=new zs(e,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],t)}async supportsWildcard(){return null==this.#vt&&(this.#vt=(async()=>{try{return await this.#Et.supportsInterface("0x9061b923")}catch(t){if(b(t,"CALL_EXCEPTION"))return!1;throw this.#vt=null,t}})()),await this.#vt}async#Nt(t,e){e=(e||[]).slice();const n=this.#Et.interface;e.unshift(bn(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(t),E(r,"missing fragment","UNKNOWN_ERROR",{info:{funcName:t}}),e=[wn(this.name,255),n.encodeFunctionData(r,e)],t="resolve(bytes,bytes)"),e.push({enableCcipRead:!0});try{const s=await this.#Et[t](...e);return r?n.decodeFunctionResult(r,s)[0]:s}catch(t){if(!b(t,"CALL_EXCEPTION"))throw t}return null}async getAddress(t){if(null==t&&(t=60),60===t)try{const t=await this.#Nt("addr(bytes32)");return null==t||t===ke?null:t}catch(t){if(b(t,"CALL_EXCEPTION"))return null;throw t}if(t>=0&&t<2147483648){let e=t+2147483648;const n=await this.#Nt("addr(bytes32,uint)",[e]);if(S(n,20))return Me(n)}let e=null;for(const n of this.provider.plugins)if(n instanceof qs&&n.supportsCoinType(t)){e=n;break}if(null==e)return null;const n=await this.#Nt("addr(bytes32,uint)",[t]);if(null==n||"0x"===n)return null;const r=await e.decodeAddress(t,n);if(null!=r)return r;E(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${t})`,info:{coinType:t,data:n}})}async getText(t){const e=await this.#Nt("text(bytes32,string)",[t]);return null==e||"0x"===e?null:e}async getContentHash(){const t=await this.#Nt("contenthash(bytes32)");if(null==t||"0x"===t)return null;const e=t.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(e){const t="e3010170"===e[1]?"ipfs":"ipns",n=parseInt(e[4],16);if(e[5].length===2*n)return`${t}://${rt("0x"+e[2])}`}const n=t.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return`bzz://${n[1]}`;E(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:t}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const t=[{type:"name",value:this.name}];try{const e=await this.getText("avatar");if(null==e)return t.push({type:"!avatar",value:""}),{url:null,linkage:t};t.push({type:"avatar",value:e});for(let n=0;n<Ys.length;n++){const r=e.match(Ys[n]);if(null==r)continue;const s=r[1].toLowerCase();switch(s){case"https":case"data":return t.push({type:"url",value:e}),{linkage:t,url:e};case"ipfs":{const n=Js(e);return t.push({type:"ipfs",value:e}),t.push({type:"url",value:n}),{linkage:t,url:n}}case"erc721":case"erc1155":{const n="erc721"===s?"tokenURI(uint256)":"uri(uint256)";t.push({type:s,value:e});const i=await this.getAddress();if(null==i)return t.push({type:"!owner",value:""}),{url:null,linkage:t};const a=(r[2]||"").split("/");if(2!==a.length)return t.push({type:`!${s}caip`,value:r[2]||""}),{url:null,linkage:t};const o=a[1],c=new zs(a[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if("erc721"===s){const e=await c.ownerOf(o);if(i!==e)return t.push({type:"!owner",value:e}),{url:null,linkage:t};t.push({type:"owner",value:e})}else if("erc1155"===s){const e=await c.balanceOf(i,o);if(!e)return t.push({type:"!balance",value:"0"}),{url:null,linkage:t};t.push({type:"balance",value:e.toString()})}let l=await c[n](o);if(null==l||"0x"===l)return t.push({type:"!metadata-url",value:""}),{url:null,linkage:t};t.push({type:"metadata-url-base",value:l}),"erc1155"===s&&(l=l.replace("{id}",W(o,32).substring(2)),t.push({type:"metadata-url-expanded",value:l})),l.match(/^ipfs:/i)&&(l=Js(l)),t.push({type:"metadata-url",value:l});let u={};const h=await new wt(l).send();h.assertOk();try{u=h.bodyJson}catch(e){try{t.push({type:"!metadata",value:h.bodyText})}catch(e){const n=h.body;return n&&t.push({type:"!metadata",value:_(n)}),{url:null,linkage:t}}return{url:null,linkage:t}}if(!u)return t.push({type:"!metadata",value:""}),{url:null,linkage:t};t.push({type:"metadata",value:JSON.stringify(u)});let d=u.image;if("string"!=typeof d)return t.push({type:"!imageUrl",value:""}),{url:null,linkage:t};if(d.match(/^(https:\/\/|data:)/i));else{if(null==d.match(Ws))return t.push({type:"!imageUrl-ipfs",value:d}),{url:null,linkage:t};t.push({type:"imageUrl-ipfs",value:d}),d=Js(d)}return t.push({type:"url",value:d}),{linkage:t,url:d}}}}}catch(t){}return{linkage:t,url:null}}static async getEnsAddress(t){const e=await t.getNetwork(),n=e.getPlugin("org.ethers.plugins.network.Ens");return E(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:e}}),n.address}static async#Pt(t,e){const n=await Xs.getEnsAddress(t);try{const r=new zs(n,["function resolver(bytes32) view returns (address)"],t),s=await r.resolver(bn(e),{enableCcipRead:!0});return s===ke?null:s}catch(t){throw t}return null}static async fromName(t,e){let n=e;for(;;){if(""===n||"."===n)return null;if("eth"!==e&&"eth"===n)return null;const r=await Xs.#Pt(t,n);if(null!=r){const s=new Xs(t,r,e);return n===e||await s.supportsWildcard()?s:null}n=n.split(".").slice(1).join(".")}}}const Zs=BigInt(0);function Qs(t,e){return function(n){return null==n?e:t(n)}}function ti(t,e){return n=>{if(e&&null==n)return null;if(!Array.isArray(n))throw new Error("not an array");return n.map((e=>t(e)))}}function ei(t,e){return n=>{const r={};for(const s in t){let i=s;if(e&&s in e&&!(i in n))for(const t of e[s])if(t in n){i=t;break}try{const e=t[s](n[i]);void 0!==e&&(r[s]=e)}catch(t){E(!1,`invalid value for value.${s} (${t instanceof Error?t.message:"not-an-error"})`,"BAD_DATA",{value:n})}}return r}}function ni(t){return N(S(t,!0),"invalid data","value",t),t}function ri(t){return N(S(t,32),"invalid hash","value",t),t}const si=ei({address:Me,blockHash:ri,blockNumber:q,data:ni,index:q,removed:Qs((function(t){switch(t){case!0:case"true":return!0;case!1:case"false":return!1}N(!1,`invalid boolean; ${JSON.stringify(t)}`,"value",t)}),!1),topics:ti(ri),transactionHash:ri,transactionIndex:q},{index:["logIndex"]});const ii=ei({hash:Qs(ri),parentHash:ri,parentBeaconBlockRoot:Qs(ri,null),number:q,timestamp:q,nonce:Qs(ni),difficulty:H,gasLimit:H,gasUsed:H,stateRoot:Qs(ri,null),receiptsRoot:Qs(ri,null),blobGasUsed:Qs(H,null),excessBlobGas:Qs(H,null),miner:Qs(Me),prevRandao:Qs(ri,null),extraData:ni,baseFeePerGas:Qs(H)},{prevRandao:["mixHash"]});const ai=ei({transactionIndex:q,blockNumber:q,transactionHash:ri,address:Me,topics:ti(ri),data:ni,index:q,blockHash:ri},{index:["logIndex"]});const oi=ei({to:Qs(Me,null),from:Qs(Me,null),contractAddress:Qs(Me,null),index:q,root:Qs(_),gasUsed:H,blobGasUsed:Qs(H,null),logsBloom:Qs(ni),blockHash:ri,hash:ri,logs:ti((function(t){return ai(t)})),blockNumber:q,cumulativeGasUsed:H,effectiveGasPrice:Qs(H),blobGasPrice:Qs(H,null),status:Qs(q),type:Qs(q,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function ci(t){t.to&&H(t.to)===Zs&&(t.to="0x0000000000000000000000000000000000000000");const e=ei({hash:ri,index:Qs(q,void 0),type:t=>"0x"===t||null==t?0:q(t),accessList:Qs(En,null),blobVersionedHashes:Qs(ti(ri,!0),null),blockHash:Qs(ri,null),blockNumber:Qs(q,null),transactionIndex:Qs(q,null),from:Me,gasPrice:Qs(H),maxPriorityFeePerGas:Qs(H),maxFeePerGas:Qs(H),maxFeePerBlobGas:Qs(H,null),gasLimit:H,to:Qs(Me,null),value:H,nonce:q,data:ni,creates:Qs(Me,null),chainId:Qs(H,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(t);if(null==e.to&&null==e.creates&&(e.creates=function(t){const e=Me(t.from);let n=H(t.nonce,"tx.nonce").toString(16);return n="0"===n?"0x":n.length%2?"0x0"+n:"0x"+n,Me(L(Qt(St([e,n])),12))}(e)),1!==t.type&&2!==t.type||null!=t.accessList||(e.accessList=[]),t.signature?e.signature=Ue.from(t.signature):e.signature=Ue.from(t),null==e.chainId){const t=e.signature.legacyChainId;null!=t&&(e.chainId=t)}return e.blockHash&&H(e.blockHash)===Zs&&(e.blockHash=null),e}class li{name;constructor(t){y(this,{name:t})}clone(){return new li(this.name)}}class ui extends li{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(t,e){null==t&&(t=0),super(`org.ethers.network.plugins.GasCost#${t||0}`);const n={effectiveBlock:t};function r(t,r){let s=(e||{})[t];null==s&&(s=r),N("number"==typeof s,`invalud value for ${t}`,"costs",e),n[t]=s}r("txBase",21e3),r("txCreate",32e3),r("txDataZero",4),r("txDataNonzero",16),r("txAccessListStorageKey",1900),r("txAccessListAddress",2400),y(this,n)}clone(){return new ui(this.effectiveBlock,this)}}class hi extends li{address;targetNetwork;constructor(t,e){super("org.ethers.plugins.network.Ens"),y(this,{address:t||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==e?1:e})}clone(){return new hi(this.address,this.targetNetwork)}}class di extends li{#c;#kt;get url(){return this.#c}get processFunc(){return this.#kt}constructor(t,e){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#c=t,this.#kt=e}clone(){return this}}const pi=new Map;class fi{#Tt;#J;#Rt;constructor(t,e){this.#Tt=t,this.#J=H(e),this.#Rt=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#Tt}set name(t){this.#Tt=t}get chainId(){return this.#J}set chainId(t){this.#J=H(t,"chainId")}matches(t){if(null==t)return!1;if("string"==typeof t){try{return this.chainId===H(t)}catch(t){}return this.name===t}if("number"==typeof t||"bigint"==typeof t){try{return this.chainId===H(t)}catch(t){}return!1}if("object"==typeof t){if(null!=t.chainId){try{return this.chainId===H(t.chainId)}catch(t){}return!1}return null!=t.name&&this.name===t.name}return!1}get plugins(){return Array.from(this.#Rt.values())}attachPlugin(t){if(this.#Rt.get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return this.#Rt.set(t.name,t.clone()),this}getPlugin(t){return this.#Rt.get(t)||null}getPlugins(t){return this.plugins.filter((e=>e.name.split("#")[0]===t))}clone(){const t=new fi(this.name,this.chainId);return this.plugins.forEach((e=>{t.attachPlugin(e.clone())})),t}computeIntrinsicGas(t){const e=this.getPlugin("org.ethers.plugins.network.GasCost")||new ui;let n=e.txBase;if(null==t.to&&(n+=e.txCreate),t.data)for(let r=2;r<t.data.length;r+=2)"00"===t.data.substring(r,r+2)?n+=e.txDataZero:n+=e.txDataNonzero;if(t.accessList){const r=En(t.accessList);for(const t in r)n+=e.txAccessListAddress+e.txAccessListStorageKey*r[t].storageKeys.length}return n}static from(t){if(function(){if(mi)return;function t(t,e,n){const r=function(){const r=new fi(t,e);return null!=n.ensNetwork&&r.attachPlugin(new hi(null,n.ensNetwork)),r.attachPlugin(new ui),(n.plugins||[]).forEach((t=>{r.attachPlugin(t)})),r};fi.register(t,r),fi.register(e,r),n.altNames&&n.altNames.forEach((t=>{fi.register(t,r)}))}mi=!0,t("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),t("ropsten",3,{ensNetwork:3}),t("rinkeby",4,{ensNetwork:4}),t("goerli",5,{ensNetwork:5}),t("kovan",42,{ensNetwork:42}),t("sepolia",11155111,{ensNetwork:11155111}),t("holesky",17e3,{ensNetwork:17e3}),t("classic",61,{}),t("classicKotti",6,{}),t("arbitrum",42161,{ensNetwork:1}),t("arbitrum-goerli",421613,{}),t("arbitrum-sepolia",421614,{}),t("base",8453,{ensNetwork:1}),t("base-goerli",84531,{}),t("base-sepolia",84532,{}),t("bnb",56,{ensNetwork:1}),t("bnbt",97,{}),t("linea",59144,{ensNetwork:1}),t("linea-goerli",59140,{}),t("linea-sepolia",59141,{}),t("matic",137,{ensNetwork:1,plugins:[yi("https://gasstation.polygon.technology/v2")]}),t("matic-amoy",80002,{}),t("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[yi("https://gasstation-testnet.polygon.technology/v2")]}),t("optimism",10,{ensNetwork:1,plugins:[]}),t("optimism-goerli",420,{}),t("optimism-sepolia",11155420,{}),t("xdai",100,{ensNetwork:1})}(),null==t)return fi.from("mainnet");if("number"==typeof t&&(t=BigInt(t)),"string"==typeof t||"bigint"==typeof t){const e=pi.get(t);if(e)return e();if("bigint"==typeof t)return new fi("unknown",t);N(!1,"unknown network","network",t)}if("function"==typeof t.clone){return t.clone()}if("object"==typeof t){N("string"==typeof t.name&&"number"==typeof t.chainId,"invalid network object name or chainId","network",t);const e=new fi(t.name,t.chainId);return(t.ensAddress||null!=t.ensNetwork)&&e.attachPlugin(new hi(t.ensAddress,t.ensNetwork)),e}N(!1,"invalid network","network",t)}static register(t,e){"number"==typeof t&&(t=BigInt(t));const n=pi.get(t);n&&N(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",t),pi.set(t,e)}}function gi(t,e){const n=String(t);if(!n.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${t}`);const r=n.split(".");if(1===r.length&&r.push(""),2!==r.length)throw new Error(`invalid gwei value: ${t}`);for(;r[1].length<e;)r[1]+="0";if(r[1].length>9){let t=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||t++,r[1]=t.toString()}return BigInt(r[0]+r[1])}function yi(t){return new di(t,(async(t,e,n)=>{let r;n.setHeader("User-Agent","ethers");try{const[e,s]=await Promise.all([n.send(),t()]);r=e;const i=r.bodyJson.standard;return{gasPrice:s.gasPrice,maxFeePerGas:gi(i.maxFee,9),maxPriorityFeePerGas:gi(i.maxPriorityFee,9)}}catch(t){E(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:r,error:t})}}))}let mi=!1;function bi(t){return JSON.parse(JSON.stringify(t))}class wi{#At;#Ot;#It;#St;constructor(t){this.#At=t,this.#Ot=null,this.#It=4e3,this.#St=-2}get pollingInterval(){return this.#It}set pollingInterval(t){this.#It=t}async#xt(){try{const t=await this.#At.getBlockNumber();if(-2===this.#St)return void(this.#St=t);if(t!==this.#St){for(let e=this.#St+1;e<=t;e++){if(null==this.#Ot)return;await this.#At.emit("block",e)}this.#St=t}}catch(t){}null!=this.#Ot&&(this.#Ot=this.#At._setTimeout(this.#xt.bind(this),this.#It))}start(){this.#Ot||(this.#Ot=this.#At._setTimeout(this.#xt.bind(this),this.#It),this.#xt())}stop(){this.#Ot&&(this.#At._clearTimeout(this.#Ot),this.#Ot=null)}pause(t){this.stop(),t&&(this.#St=-2)}resume(){this.start()}}class vi{#At;#xt;#Ct;constructor(t){this.#At=t,this.#Ct=!1,this.#xt=t=>{this._poll(t,this.#At)}}async _poll(t,e){throw new Error("sub-classes must override this")}start(){this.#Ct||(this.#Ct=!0,this.#xt(-2),this.#At.on("block",this.#xt))}stop(){this.#Ct&&(this.#Ct=!1,this.#At.off("block",this.#xt))}pause(t){this.stop()}resume(){this.start()}}class Ei extends vi{#_t;#Ut;constructor(t,e){super(t),this.#_t=e,this.#Ut=-2}pause(t){t&&(this.#Ut=-2),super.pause(t)}async _poll(t,e){const n=await e.getBlock(this.#_t);null!=n&&(-2===this.#Ut?this.#Ut=n.number:n.number>this.#Ut&&(e.emit(this.#_t,n.number),this.#Ut=n.number))}}class Ni extends vi{#wt;constructor(t,e){super(t),this.#wt=bi(e)}async _poll(t,e){throw new Error("@TODO")}}class Pi extends vi{#Ft;constructor(t,e){super(t),this.#Ft=e}async _poll(t,e){const n=await e.getTransactionReceipt(this.#Ft);n&&e.emit(this.#Ft,n)}}class ki{#At;#wt;#Ot;#Ct;#St;constructor(t,e){this.#At=t,this.#wt=bi(e),this.#Ot=this.#xt.bind(this),this.#Ct=!1,this.#St=-2}async#xt(t){if(-2===this.#St)return;const e=bi(this.#wt);e.fromBlock=this.#St+1,e.toBlock=t;const n=await this.#At.getLogs(e);if(0!==n.length)for(const t of n)this.#At.emit(this.#wt,t),this.#St=t.blockNumber;else this.#St<t-60&&(this.#St=t-60)}start(){this.#Ct||(this.#Ct=!0,-2===this.#St&&this.#At.getBlockNumber().then((t=>{this.#St=t})),this.#At.on("block",this.#Ot))}stop(){this.#Ct&&(this.#Ct=!1,this.#At.off("block",this.#Ot))}pause(t){this.stop(),t&&(this.#St=-2)}resume(){this.start()}}const Ti=BigInt(2);function Ri(t){return t&&"function"==typeof t.then}function Ai(t,e){return t+":"+JSON.stringify(e,((t,e)=>{if(null==e)return"null";if("bigint"==typeof e)return`bigint:${e.toString()}`;if("string"==typeof e)return e.toLowerCase();if("object"==typeof e&&!Array.isArray(e)){const t=Object.keys(e);return t.sort(),t.reduce(((t,n)=>(t[n]=e[n],t)),{})}return e}))}class Oi{name;constructor(t){y(this,{name:t})}start(){}stop(){}pause(t){}resume(){}}function Ii(t){return(t=Array.from(new Set(t).values())).sort(),t}async function Si(t,e){if(null==t)throw new Error("invalid event");if(Array.isArray(t)&&(t={topics:t}),"string"==typeof t)switch(t){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:t,tag:t}}if(S(t,32)){const e=t.toLowerCase();return{type:"transaction",tag:Ai("tx",{hash:e}),hash:e}}if(t.orphan){const e=t;return{type:"orphan",tag:Ai("orphan",e),filter:(n=e,JSON.parse(JSON.stringify(n)))}}var n;if(t.address||t.topics){const n=t,r={topics:(n.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ii(t.map((t=>t.toLowerCase()))):t.toLowerCase()))};if(n.address){const t=[],s=[],i=n=>{S(n)?t.push(n):s.push((async()=>{t.push(await He(n,e))})())};Array.isArray(n.address)?n.address.forEach(i):i(n.address),s.length&&await Promise.all(s),r.address=Ii(t.map((t=>t.toLowerCase())))}return{filter:r,tag:Ai("event",r),type:"event"}}N(!1,"unknown ProviderEvent","event",t)}function xi(){return(new Date).getTime()}const Ci={cacheTimeout:250,pollingInterval:4e3};class _i{#Lt;#Rt;#Dt;#Bt;#Gt;#$t;#Mt;#jt;#Kt;#Ht;#Vt;#B;constructor(t,e){if(this.#B=Object.assign({},Ci,e||{}),"any"===t)this.#$t=!0,this.#Gt=null;else if(t){const e=fi.from(t);this.#$t=!1,this.#Gt=Promise.resolve(e),setTimeout((()=>{this.emit("network",e,null)}),0)}else this.#$t=!1,this.#Gt=null;this.#jt=-1,this.#Mt=new Map,this.#Lt=new Map,this.#Rt=new Map,this.#Dt=null,this.#Bt=!1,this.#Kt=1,this.#Ht=new Map,this.#Vt=!1}get pollingInterval(){return this.#B.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#Rt.values())}attachPlugin(t){if(this.#Rt.get(t.name))throw new Error(`cannot replace existing plugin: ${t.name} `);return this.#Rt.set(t.name,t.connect(this)),this}getPlugin(t){return this.#Rt.get(t)||null}get disableCcipRead(){return this.#Vt}set disableCcipRead(t){this.#Vt=!!t}async#zt(t){const e=this.#B.cacheTimeout;if(e<0)return await this._perform(t);const n=Ai(t.method,t);let r=this.#Mt.get(n);return r||(r=this._perform(t),this.#Mt.set(n,r),setTimeout((()=>{this.#Mt.get(n)===r&&this.#Mt.delete(n)}),e)),await r}async ccipReadFetch(t,e,n){if(this.disableCcipRead||0===n.length||null==t.to)return null;const r=t.to.toLowerCase(),s=e.toLowerCase(),i=[];for(let e=0;e<n.length;e++){const a=n[e],o=a.replace("{sender}",r).replace("{data}",s),c=new wt(o);-1===a.indexOf("{data}")&&(c.body={data:s,sender:r}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:c,index:e,urls:n});let l,u="unknown error";try{l=await c.send()}catch(t){i.push(t.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:c,result:{error:t}});continue}try{const t=l.bodyJson;if(t.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:c,result:t}),t.data;t.message&&(u=t.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:c,result:t})}catch(t){}E(l.statusCode<400||l.statusCode>=500,`response not found during CCIP fetch: ${u}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:t,info:{url:a,errorMessage:u}}),i.push(u)}E(!1,`error encountered during CCIP fetch: ${i.map((t=>JSON.stringify(t))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:t,info:{urls:n,errorMessages:i}})}_wrapBlock(t,e){return new ds(function(t){const e=ii(t);return e.transactions=t.transactions.map((t=>"string"==typeof t?t:ci(t))),e}(t),this)}_wrapLog(t,e){return new ps(function(t){return si(t)}(t),this)}_wrapTransactionReceipt(t,e){return new fs(function(t){return oi(t)}(t),this)}_wrapTransactionResponse(t,e){return new gs(ci(t),this)}_detectNetwork(){E(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(t){E(!1,`unsupported method: ${t.method}`,"UNSUPPORTED_OPERATION",{operation:t.method,info:t})}async getBlockNumber(){const t=q(await this.#zt({method:"getBlockNumber"}),"%response");return this.#jt>=0&&(this.#jt=t),t}_getAddress(t){return He(t,this)}_getBlockTag(t){if(null==t)return"latest";switch(t){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return t}return S(t)?S(t,32)?t:X(t):("bigint"==typeof t&&(t=q(t,"blockTag")),"number"==typeof t?t>=0?X(t):this.#jt>=0?X(this.#jt+t):this.getBlockNumber().then((e=>X(e+t))):void N(!1,"invalid blockTag","blockTag",t))}_getFilter(t){const e=(t.topics||[]).map((t=>null==t?null:Array.isArray(t)?Ii(t.map((t=>t.toLowerCase()))):t.toLowerCase())),n="blockHash"in t?t.blockHash:void 0,r=(t,r,s)=>{let i;switch(t.length){case 0:break;case 1:i=t[0];break;default:t.sort(),i=t}if(n&&(null!=r||null!=s))throw new Error("invalid filter");const a={};return i&&(a.address=i),e.length&&(a.topics=e),r&&(a.fromBlock=r),s&&(a.toBlock=s),n&&(a.blockHash=n),a};let s,i,a=[];if(t.address)if(Array.isArray(t.address))for(const e of t.address)a.push(this._getAddress(e));else a.push(this._getAddress(t.address));return"fromBlock"in t&&(s=this._getBlockTag(t.fromBlock)),"toBlock"in t&&(i=this._getBlockTag(t.toBlock)),a.filter((t=>"string"!=typeof t)).length||null!=s&&"string"!=typeof s||null!=i&&"string"!=typeof i?Promise.all([Promise.all(a),s,i]).then((t=>r(t[0],t[1],t[2]))):r(a,s,i)}_getTransactionRequest(t){const e=hs(t),n=[];if(["to","from"].forEach((t=>{if(null==e[t])return;const r=He(e[t],this);Ri(r)?n.push(async function(){e[t]=await r}()):e[t]=r})),null!=e.blockTag){const t=this._getBlockTag(e.blockTag);Ri(t)?n.push(async function(){e.blockTag=await t}()):e.blockTag=t}return n.length?async function(){return await Promise.all(n),e}():e}async getNetwork(){if(null==this.#Gt){const t=(async()=>{try{const t=await this._detectNetwork();return this.emit("network",t,null),t}catch(e){throw this.#Gt===t&&(this.#Gt=null),e}})();return this.#Gt=t,(await t).clone()}const t=this.#Gt,[e,n]=await Promise.all([t,this._detectNetwork()]);return e.chainId!==n.chainId&&(this.#$t?(this.emit("network",n,e),this.#Gt===t&&(this.#Gt=Promise.resolve(n))):E(!1,`network changed: ${e.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),e.clone()}async getFeeData(){const t=await this.getNetwork(),e=async()=>{const{_block:e,gasPrice:n,priorityFee:r}=await g({_block:this.#Jt("latest",!1),gasPrice:(async()=>{try{return H(await this.#zt({method:"getGasPrice"}),"%response")}catch(t){}return null})(),priorityFee:(async()=>{try{return H(await this.#zt({method:"getPriorityFee"}),"%response")}catch(t){}return null})()});let s=null,i=null;const a=this._wrapBlock(e,t);return a&&a.baseFeePerGas&&(i=null!=r?r:BigInt("1000000000"),s=a.baseFeePerGas*Ti+i),new us(n,s,i)},n=t.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const t=new wt(n.url),r=await n.processFunc(e,this,t);return new us(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await e()}async estimateGas(t){let e=this._getTransactionRequest(t);return Ri(e)&&(e=await e),H(await this.#zt({method:"estimateGas",transaction:e}),"%response")}async#qt(t,e,n){E(n<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},t,{blockTag:e,enableCcipRead:!0})});const r=hs(t);try{return _(await this._perform({method:"call",transaction:r,blockTag:e}))}catch(t){if(!this.disableCcipRead&&w(t)&&t.data&&n>=0&&"latest"===e&&null!=r.to&&"0x556f1830"===L(t.data,0,4)){const s=t.data,i=await He(r.to,this);let a;try{a=function(t){const e={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};E(F(t)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const n=L(t,0,32);E(L(n,0,12)===L($i,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),e.sender=L(n,12);try{const n=[],r=q(L(t,32,64)),s=q(L(t,r,r+32)),i=L(t,r+32);for(let t=0;t<s;t++){const e=Ui(i,32*t);if(null==e)throw new Error("abort");n.push(e)}e.urls=n}catch(t){E(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=Fi(t,64);if(null==n)throw new Error("abort");e.calldata=n}catch(t){E(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}E(L(t,100,128)===L($i,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),e.selector=L(t,96,100);try{const n=Fi(t,128);if(null==n)throw new Error("abort");e.extraData=n}catch(t){E(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return e.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((t=>e[t])),e}(L(t.data,4))}catch(t){E(!1,t.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:r,info:{data:s}})}E(a.sender.toLowerCase()===i.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:s,reason:"OffchainLookup",transaction:r,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:a.errorArgs}});const o=await this.ccipReadFetch(r,a.calldata,a.urls);E(null!=o,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:r,info:{data:t.data,errorArgs:a.errorArgs}});const c={to:i,data:U([a.selector,Gi([o,a.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:c});try{const t=await this.#qt(c,e,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},c),result:t}),t}catch(t){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},c),error:t}),t}}throw t}}async#Wt(t){const{value:e}=await g({network:this.getNetwork(),value:t});return e}async call(t){const{tx:e,blockTag:n}=await g({tx:this._getTransactionRequest(t),blockTag:this._getBlockTag(t.blockTag)});return await this.#Wt(this.#qt(e,n,t.enableCcipRead?0:-1))}async#Yt(t,e,n){let r=this._getAddress(e),s=this._getBlockTag(n);return"string"==typeof r&&"string"==typeof s||([r,s]=await Promise.all([r,s])),await this.#Wt(this.#zt(Object.assign(t,{address:r,blockTag:s})))}async getBalance(t,e){return H(await this.#Yt({method:"getBalance"},t,e),"%response")}async getTransactionCount(t,e){return q(await this.#Yt({method:"getTransactionCount"},t,e),"%response")}async getCode(t,e){return _(await this.#Yt({method:"getCode"},t,e))}async getStorage(t,e,n){const r=H(e,"position");return _(await this.#Yt({method:"getStorage",position:r},t,n))}async broadcastTransaction(t){const{blockNumber:e,hash:n,network:r}=await g({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:t}),network:this.getNetwork()}),s=$n.from(t);if(s.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(s,r).replaceableTransaction(e)}async#Jt(t,e){if(S(t,32))return await this.#zt({method:"getBlock",blockHash:t,includeTransactions:e});let n=this._getBlockTag(t);return"string"!=typeof n&&(n=await n),await this.#zt({method:"getBlock",blockTag:n,includeTransactions:e})}async getBlock(t,e){const{network:n,params:r}=await g({network:this.getNetwork(),params:this.#Jt(t,!!e)});return null==r?null:this._wrapBlock(r,n)}async getTransaction(t){const{network:e,params:n}=await g({network:this.getNetwork(),params:this.#zt({method:"getTransaction",hash:t})});return null==n?null:this._wrapTransactionResponse(n,e)}async getTransactionReceipt(t){const{network:e,params:n}=await g({network:this.getNetwork(),params:this.#zt({method:"getTransactionReceipt",hash:t})});if(null==n)return null;if(null==n.gasPrice&&null==n.effectiveGasPrice){const e=await this.#zt({method:"getTransaction",hash:t});if(null==e)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=e.gasPrice}return this._wrapTransactionReceipt(n,e)}async getTransactionResult(t){const{result:e}=await g({network:this.getNetwork(),result:this.#zt({method:"getTransactionResult",hash:t})});return null==e?null:_(e)}async getLogs(t){let e=this._getFilter(t);Ri(e)&&(e=await e);const{network:n,params:r}=await g({network:this.getNetwork(),params:this.#zt({method:"getLogs",filter:e})});return r.map((t=>this._wrapLog(t,n)))}_getProvider(t){E(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(t){return await Xs.fromName(this,t)}async getAvatar(t){const e=await this.getResolver(t);return e?await e.getAvatar():null}async resolveName(t){const e=await this.getResolver(t);return e?await e.getAddress():null}async lookupAddress(t){const e=bn((t=Me(t)).substring(2).toLowerCase()+".addr.reverse");try{const n=await Xs.getEnsAddress(this),r=new zs(n,["function resolver(bytes32) view returns (address)"],this),s=await r.resolver(e);if(null==s||s===ke)return null;const i=new zs(s,["function name(bytes32) view returns (string)"],this),a=await i.name(e);return await this.resolveName(a)!==t?null:a}catch(t){if(b(t,"BAD_DATA")&&"0x"===t.value)return null;if(b(t,"CALL_EXCEPTION"))return null;throw t}return null}async waitForTransaction(t,e,n){const r=null!=e?e:1;return 0===r?this.getTransactionReceipt(t):new Promise((async(e,s)=>{let i=null;const a=async n=>{try{const s=await this.getTransactionReceipt(t);if(null!=s&&n-s.blockNumber+1>=r)return e(s),void(i&&(clearTimeout(i),i=null))}catch(t){console.log("EEE",t)}this.once("block",a)};null!=n&&(i=setTimeout((()=>{null!=i&&(i=null,this.off("block",a),s(v("timeout","TIMEOUT",{reason:"timeout"})))}),n)),a(await this.getBlockNumber())}))}async waitForBlock(t){E(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(t){const e=this.#Ht.get(t);e&&(e.timer&&clearTimeout(e.timer),this.#Ht.delete(t))}_setTimeout(t,e){null==e&&(e=0);const n=this.#Kt++,r=()=>{this.#Ht.delete(n),t()};if(this.paused)this.#Ht.set(n,{timer:null,func:r,time:e});else{const t=setTimeout(r,e);this.#Ht.set(n,{timer:t,func:r,time:xi()})}return n}_forEachSubscriber(t){for(const e of this.#Lt.values())t(e.subscriber)}_getSubscriber(t){switch(t.type){case"debug":case"error":case"network":return new Oi(t.type);case"block":{const t=new wi(this);return t.pollingInterval=this.pollingInterval,t}case"safe":case"finalized":return new Ei(this,t.type);case"event":return new ki(this,t.filter);case"transaction":return new Pi(this,t.hash);case"orphan":return new Ni(this,t.filter)}throw new Error(`unsupported event: ${t.type}`)}_recoverSubscriber(t,e){for(const n of this.#Lt.values())if(n.subscriber===t){n.started&&n.subscriber.stop(),n.subscriber=e,n.started&&e.start(),null!=this.#Dt&&e.pause(this.#Dt);break}}async#Xt(t,e){let n=await Si(t,this);return"event"===n.type&&e&&e.length>0&&!0===e[0].removed&&(n=await Si({orphan:"drop-log",log:e[0]},this)),this.#Lt.get(n.tag)||null}async#Zt(t){const e=await Si(t,this),n=e.tag;let r=this.#Lt.get(n);if(!r){r={subscriber:this._getSubscriber(e),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#Lt.set(n,r)}return r}async on(t,e){const n=await this.#Zt(t);return n.listeners.push({listener:e,once:!1}),n.started||(n.subscriber.start(),n.started=!0,null!=this.#Dt&&n.subscriber.pause(this.#Dt)),this}async once(t,e){const n=await this.#Zt(t);return n.listeners.push({listener:e,once:!0}),n.started||(n.subscriber.start(),n.started=!0,null!=this.#Dt&&n.subscriber.pause(this.#Dt)),this}async emit(t,...e){const n=await this.#Xt(t,e);if(!n||0===n.listeners.length)return!1;const r=n.listeners.length;return n.listeners=n.listeners.filter((({listener:n,once:r})=>{const s=new st(this,r?null:n,t);try{n.call(this,...e,s)}catch(t){}return!r})),0===n.listeners.length&&(n.started&&n.subscriber.stop(),this.#Lt.delete(n.tag)),r>0}async listenerCount(t){if(t){const e=await this.#Xt(t);return e?e.listeners.length:0}let e=0;for(const{listeners:t}of this.#Lt.values())e+=t.length;return e}async listeners(t){if(t){const e=await this.#Xt(t);return e?e.listeners.map((({listener:t})=>t)):[]}let e=[];for(const{listeners:t}of this.#Lt.values())e=e.concat(t.map((({listener:t})=>t)));return e}async off(t,e){const n=await this.#Xt(t);if(!n)return this;if(e){const t=n.listeners.map((({listener:t})=>t)).indexOf(e);t>=0&&n.listeners.splice(t,1)}return e&&0!==n.listeners.length||(n.started&&n.subscriber.stop(),this.#Lt.delete(n.tag)),this}async removeAllListeners(t){if(t){const{tag:e,started:n,subscriber:r}=await this.#Zt(t);n&&r.stop(),this.#Lt.delete(e)}else for(const[t,{started:e,subscriber:n}]of this.#Lt)e&&n.stop(),this.#Lt.delete(t);return this}async addListener(t,e){return await this.on(t,e)}async removeListener(t,e){return this.off(t,e)}get destroyed(){return this.#Bt}destroy(){this.removeAllListeners();for(const t of this.#Ht.keys())this._clearTimeout(t);this.#Bt=!0}get paused(){return null!=this.#Dt}set paused(t){!!t!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(t){if(this.#jt=-1,null!=this.#Dt){if(this.#Dt==!!t)return;E(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((e=>e.pause(t))),this.#Dt=!!t;for(const t of this.#Ht.values())t.timer&&clearTimeout(t.timer),t.time=xi()-t.time}resume(){if(null!=this.#Dt){this._forEachSubscriber((t=>t.resume())),this.#Dt=null;for(const t of this.#Ht.values()){let e=t.time;e<0&&(e=0),t.time=xi(),setTimeout(t.func,e)}}}}function Ui(t,e){try{const n=Fi(t,e);if(n)return ct(n)}catch(t){}return null}function Fi(t,e){if("0x"===t)return null;try{const n=q(L(t,e,e+32)),r=q(L(t,n,n+32));return L(t,n+32,n+32+r)}catch(t){}return null}function Li(t){const e=Y(t);if(e.length>32)throw new Error("internal; should not happen");const n=new Uint8Array(32);return n.set(e,32-e.length),n}function Di(t){if(t.length%32==0)return t;const e=new Uint8Array(32*Math.ceil(t.length/32));return e.set(t),e}const Bi=new Uint8Array([]);function Gi(t){const e=[];let n=0;for(let r=0;r<t.length;r++)e.push(Bi),n+=32;for(let r=0;r<t.length;r++){const s=O(t[r]);e[r]=Li(n),e.push(Li(s.length)),e.push(Di(s)),n+=32+32*Math.ceil(s.length/32)}return U(e)}const $i="0x0000000000000000000000000000000000000000000000000000000000000000";function Mi(t,e){if(t.provider)return t.provider;E(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:e})}async function ji(t,e){let n=hs(e);if(null!=n.to&&(n.to=He(n.to,t)),null!=n.from){const e=n.from;n.from=Promise.all([t.getAddress(),He(e,t)]).then((([t,e])=>(N(t.toLowerCase()===e.toLowerCase(),"transaction from mismatch","tx.from",e),t)))}else n.from=t.getAddress();return await g(n)}class Ki{provider;constructor(t){y(this,{provider:t||null})}async getNonce(t){return Mi(this,"getTransactionCount").getTransactionCount(await this.getAddress(),t)}async populateCall(t){return await ji(this,t)}async populateTransaction(t){const e=Mi(this,"populateTransaction"),n=await ji(this,t);null==n.nonce&&(n.nonce=await this.getNonce("pending")),null==n.gasLimit&&(n.gasLimit=await this.estimateGas(n));const r=await this.provider.getNetwork();if(null!=n.chainId){N(H(n.chainId)===r.chainId,"transaction chainId mismatch","tx.chainId",t.chainId)}else n.chainId=r.chainId;const s=null!=n.maxFeePerGas||null!=n.maxPriorityFeePerGas;if(null==n.gasPrice||2!==n.type&&!s?0!==n.type&&1!==n.type||!s||N(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",t):N(!1,"eip-1559 transaction do not support gasPrice","tx",t),2!==n.type&&null!=n.type||null==n.maxFeePerGas||null==n.maxPriorityFeePerGas)if(0===n.type||1===n.type){const t=await e.getFeeData();E(null!=t.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice)}else{const t=await e.getFeeData();if(null==n.type)if(null!=t.maxFeePerGas&&null!=t.maxPriorityFeePerGas)if(n.type=2,null!=n.gasPrice){const t=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=t,n.maxPriorityFeePerGas=t}else null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas);else null!=t.gasPrice?(E(!s,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==n.gasPrice&&(n.gasPrice=t.gasPrice),n.type=0):E(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else 2!==n.type&&3!==n.type||(null==n.maxFeePerGas&&(n.maxFeePerGas=t.maxFeePerGas),null==n.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas))}else n.type=2;return await g(n)}async estimateGas(t){return Mi(this,"estimateGas").estimateGas(await this.populateCall(t))}async call(t){return Mi(this,"call").call(await this.populateCall(t))}async resolveName(t){const e=Mi(this,"resolveName");return await e.resolveName(t)}async sendTransaction(t){const e=Mi(this,"sendTransaction"),n=await this.populateTransaction(t);delete n.from;const r=$n.from(n);return await e.broadcastTransaction(await this.signTransaction(r))}}class Hi extends Ki{address;constructor(t,e){super(e),y(this,{address:t})}async getAddress(){return this.address}connect(t){return new Hi(this.address,t)}#Qt(t,e){E(!1,`VoidSigner cannot sign ${t}`,"UNSUPPORTED_OPERATION",{operation:e})}async signTransaction(t){this.#Qt("transactions","signTransaction")}async signMessage(t){this.#Qt("messages","signMessage")}async signTypedData(t,e,n){this.#Qt("typed-data","signTypedData")}}class Vi{#At;#te;#Ot;#Ct;#ee;#ne;constructor(t){this.#At=t,this.#te=null,this.#Ot=this.#xt.bind(this),this.#Ct=!1,this.#ee=null,this.#ne=!1}_subscribe(t){throw new Error("subclasses must override this")}_emitResults(t,e){throw new Error("subclasses must override this")}_recover(t){throw new Error("subclasses must override this")}async#xt(t){try{null==this.#te&&(this.#te=this._subscribe(this.#At));let t=null;try{t=await this.#te}catch(t){if(!b(t,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==t.operation)throw t}if(null==t)return this.#te=null,void this.#At._recoverSubscriber(this,this._recover(this.#At));const e=await this.#At.getNetwork();if(this.#ee||(this.#ee=e),this.#ee.chainId!==e.chainId)throw new Error("chaid changed");if(this.#ne)return;const n=await this.#At.send("eth_getFilterChanges",[t]);await this._emitResults(this.#At,n)}catch(t){console.log("@TODO",t)}this.#At.once("block",this.#Ot)}#re(){const t=this.#te;t&&(this.#te=null,t.then((t=>{this.#At.destroyed||this.#At.send("eth_uninstallFilter",[t])})))}start(){this.#Ct||(this.#Ct=!0,this.#xt(-2))}stop(){this.#Ct&&(this.#Ct=!1,this.#ne=!0,this.#re(),this.#At.off("block",this.#Ot))}pause(t){t&&this.#re(),this.#At.off("block",this.#Ot)}resume(){this.start()}}class zi extends Vi{#se;constructor(t,e){var n;super(t),this.#se=(n=e,JSON.parse(JSON.stringify(n)))}_recover(t){return new ki(t,this.#se)}async _subscribe(t){return await t.send("eth_newFilter",[this.#se])}async _emitResults(t,e){for(const n of e)t.emit(this.#se,t._wrapLog(n,t._network))}}class Ji extends Vi{async _subscribe(t){return await t.send("eth_newPendingTransactionFilter",[])}async _emitResults(t,e){for(const n of e)t.emit("pending",n)}}const qi="bigint,boolean,function,number,string,symbol".split(/,/g);function Wi(t){if(null==t||qi.indexOf(typeof t)>=0)return t;if("function"==typeof t.getAddress)return t;if(Array.isArray(t))return t.map(Wi);if("object"==typeof t)return Object.keys(t).reduce(((e,n)=>(e[n]=t[n],e)),{});throw new Error(`should not happen: ${t} (${typeof t})`)}function Yi(t){return new Promise((e=>{setTimeout(e,t)}))}function Xi(t){return t?t.toLowerCase():t}function Zi(t){return t&&"number"==typeof t.pollingInterval}const Qi={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class ta extends Ki{address;constructor(t,e){super(t),y(this,{address:e=Me(e)})}connect(t){E(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(t){return await this.populateCall(t)}async sendUncheckedTransaction(t){const e=Wi(t),n=[];if(e.from){const r=e.from;n.push((async()=>{const n=await He(r,this.provider);N(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n})())}else e.from=this.address;if(null==e.gasLimit&&n.push((async()=>{e.gasLimit=await this.provider.estimateGas({...e,from:this.address})})()),null!=e.to){const t=e.to;n.push((async()=>{e.to=await He(t,this.provider)})())}n.length&&await Promise.all(n);const r=this.provider.getRpcTransaction(e);return this.provider.send("eth_sendTransaction",[r])}async sendTransaction(t){const e=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(t);return await new Promise(((t,r)=>{const s=[1e3,100];let i=0;const a=async()=>{try{const r=await this.provider.getTransaction(n);if(null!=r)return void t(r.replaceableTransaction(e))}catch(t){if(b(t,"CANCELLED")||b(t,"BAD_DATA")||b(t,"NETWORK_ERROR")||b(t,"UNSUPPORTED_OPERATION"))return null==t.info&&(t.info={}),t.info.sendTransactionHash=n,void r(t);if(b(t,"INVALID_ARGUMENT")&&(i++,null==t.info&&(t.info={}),t.info.sendTransactionHash=n,i>10))return void r(t);this.provider.emit("error",v("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:t}))}this.provider._setTimeout((()=>{a()}),s.pop()||4e3)};a()}))}async signTransaction(t){const e=Wi(t);if(e.from){const n=await He(e.from,this.provider);N(null!=n&&n.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",t),e.from=n}else e.from=this.address;const n=this.provider.getRpcTransaction(e);return await this.provider.send("eth_signTransaction",[n])}async signMessage(t){const e="string"==typeof t?ot(t):t;return await this.provider.send("personal_sign",[_(e),this.address.toLowerCase()])}async signTypedData(t,e,n){const r=Wi(n),s=await nr.resolveNames(t,e,r,(async t=>{const e=await He(t);return N(null!=e,"TypedData does not support null address","value",t),e}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(nr.getPayload(s.domain,e,s.value))])}async unlock(t){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),t,null])}async _legacySignMessage(t){const e="string"==typeof t?ot(t):t;return await this.provider.send("eth_sign",[this.address.toLowerCase(),_(e)])}}class ea extends _i{#B;#ie;#ae;#oe;#ce;#ee;#le;#ue(){if(this.#oe)return;const t=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");this.#oe=setTimeout((()=>{this.#oe=null;const t=this.#ae;for(this.#ae=[];t.length;){const e=[t.shift()];for(;t.length&&e.length!==this.#B.batchMaxCount;){e.push(t.shift());if(JSON.stringify(e.map((t=>t.payload))).length>this.#B.batchMaxSize){t.unshift(e.pop());break}}(async()=>{const t=1===e.length?e[0].payload:e.map((t=>t.payload));this.emit("debug",{action:"sendRpcPayload",payload:t});try{const n=await this._send(t);this.emit("debug",{action:"receiveRpcResult",result:n});for(const{resolve:t,reject:r,payload:s}of e){if(this.destroyed){r(v("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:s.method}));continue}const e=n.filter((t=>t.id===s.id))[0];if(null!=e)"error"in e?r(this.getRpcError(s,e)):t(e.result);else{const t=v("missing response for request","BAD_DATA",{value:n,info:{payload:s}});this.emit("error",t),r(t)}}}catch(t){this.emit("debug",{action:"receiveRpcError",error:t});for(const{reject:n}of e)n(t)}})()}}),t)}constructor(t,e){super(t,e),this.#ie=1,this.#B=Object.assign({},Qi,e||{}),this.#ae=[],this.#oe=null,this.#ee=null,this.#le=null;{let t=null;const e=new Promise((e=>{t=e}));this.#ce={promise:e,resolve:t}}const n=this._getOption("staticNetwork");"boolean"==typeof n?(N(!n||"any"!==t,"staticNetwork cannot be used on special network 'any'","options",e),n&&null!=t&&(this.#ee=fi.from(t))):n&&(N(null==t||n.matches(t),"staticNetwork MUST match network object","options",e),this.#ee=n)}_getOption(t){return this.#B[t]}get _network(){return E(this.#ee,"network is not available yet","NETWORK_ERROR"),this.#ee}async _perform(t){if("call"===t.method||"estimateGas"===t.method){let e=t.transaction;if(e&&null!=e.type&&H(e.type)&&null==e.maxFeePerGas&&null==e.maxPriorityFeePerGas){const n=await this.getFeeData();null==n.maxFeePerGas&&null==n.maxPriorityFeePerGas&&(t=Object.assign({},t,{transaction:Object.assign({},e,{type:void 0})}))}}const e=this.getRpcRequest(t);return null!=e?await this.send(e.method,e.args):super._perform(t)}async _detectNetwork(){const t=this._getOption("staticNetwork");if(t){if(!0!==t)return t;if(this.#ee)return this.#ee}return this.#le?await this.#le:this.ready?(this.#le=(async()=>{try{const t=fi.from(H(await this.send("eth_chainId",[])));return this.#le=null,t}catch(t){throw this.#le=null,t}})(),await this.#le):(this.#le=(async()=>{const t={id:this.#ie++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let e;this.emit("debug",{action:"sendRpcPayload",payload:t});try{e=(await this._send(t))[0],this.#le=null}catch(t){throw this.#le=null,this.emit("debug",{action:"receiveRpcError",error:t}),t}if(this.emit("debug",{action:"receiveRpcResult",result:e}),"result"in e)return fi.from(H(e.result));throw this.getRpcError(t,e)})(),await this.#le)}_start(){null!=this.#ce&&null!=this.#ce.resolve&&(this.#ce.resolve(),this.#ce=null,(async()=>{for(;null==this.#ee&&!this.destroyed;)try{this.#ee=await this._detectNetwork()}catch(t){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",v("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:t}})),await Yi(1e3)}this.#ue()})())}async _waitUntilReady(){if(null!=this.#ce)return await this.#ce.promise}_getSubscriber(t){return"pending"===t.type?new Ji(this):"event"===t.type?this._getOption("polling")?new ki(this,t.filter):new zi(this,t.filter):"orphan"===t.type&&"drop-log"===t.filter.orphan?new Oi("orphan"):super._getSubscriber(t)}get ready(){return null==this.#ce}getRpcTransaction(t){const e={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((n=>{if(null==t[n])return;let r=n;"gasLimit"===n&&(r="gas"),e[r]=X(H(t[n],`tx.${n}`))})),["from","to","data"].forEach((n=>{null!=t[n]&&(e[n]=_(t[n]))})),t.accessList&&(e.accessList=En(t.accessList)),t.blobVersionedHashes&&(e.blobVersionedHashes=t.blobVersionedHashes.map((t=>t.toLowerCase()))),e}getRpcRequest(t){switch(t.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[Xi(t.address),t.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[Xi(t.address),t.blockTag]};case"getCode":return{method:"eth_getCode",args:[Xi(t.address),t.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[Xi(t.address),"0x"+t.position.toString(16),t.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[t.signedTransaction]};case"getBlock":if("blockTag"in t)return{method:"eth_getBlockByNumber",args:[t.blockTag,!!t.includeTransactions]};if("blockHash"in t)return{method:"eth_getBlockByHash",args:[t.blockHash,!!t.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[t.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[t.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(t.transaction),t.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(t.transaction)]};case"getLogs":return t.filter&&null!=t.filter.address&&(Array.isArray(t.filter.address)?t.filter.address=t.filter.address.map(Xi):t.filter.address=Xi(t.filter.address)),{method:"eth_getLogs",args:[t.filter]}}return null}getRpcError(t,e){const{method:n}=t,{error:r}=e;if("eth_estimateGas"===n&&r.message){const e=r.message;if(!e.match(/revert/i)&&e.match(/insufficient funds/i))return v("insufficient funds","INSUFFICIENT_FUNDS",{transaction:t.params[0],info:{payload:t,error:r}})}if("eth_call"===n||"eth_estimateGas"===n){const e=sa(r),s=Qr.getBuiltinCallException("eth_call"===n?"call":"estimateGas",t.params[0],e?e.data:null);return s.info={error:r,payload:t},s}const s=JSON.stringify(function(t){const e=[];return ia(t,e),e}(r));if("string"==typeof r.message&&r.message.match(/user denied|ethers-user-denied/i)){return v("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[n]||"unknown",reason:"rejected",info:{payload:t,error:r}})}if("eth_sendRawTransaction"===n||"eth_sendTransaction"===n){const e=t.params[0];if(s.match(/insufficient funds|base fee exceeds gas limit/i))return v("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:e,info:{error:r}});if(s.match(/nonce/i)&&s.match(/too low/i))return v("nonce has already been used","NONCE_EXPIRED",{transaction:e,info:{error:r}});if(s.match(/replacement transaction/i)&&s.match(/underpriced/i))return v("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:e,info:{error:r}});if(s.match(/only replay-protected/i))return v("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:e,info:{error:r}}})}let i=!!s.match(/the method .* does not exist/i);return i||r&&r.details&&r.details.startsWith("Unauthorized method:")&&(i=!0),i?v("unsupported operation","UNSUPPORTED_OPERATION",{operation:t.method,info:{error:r,payload:t}}):v("could not coalesce error","UNKNOWN_ERROR",{error:r,payload:t})}send(t,e){if(this.destroyed)return Promise.reject(v("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t}));const n=this.#ie++,r=new Promise(((r,s)=>{this.#ae.push({resolve:r,reject:s,payload:{method:t,params:e,id:n,jsonrpc:"2.0"}})}));return this.#ue(),r}async getSigner(t){null==t&&(t=0);const e=this.send("eth_accounts",[]);if("number"==typeof t){const n=await e;if(t>=n.length)throw new Error("no such account");return new ta(this,n[t])}const{accounts:n}=await g({network:this.getNetwork(),accounts:e});t=Me(t);for(const e of n)if(Me(e)===t)return new ta(this,t);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((t=>new ta(this,t)))}destroy(){this.#oe&&(clearTimeout(this.#oe),this.#oe=null);for(const{payload:t,reject:e}of this.#ae)e(v("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:t.method}));this.#ae=[],super.destroy()}}class na extends ea{#he;constructor(t,e){super(t,e);let n=this._getOption("pollingInterval");null==n&&(n=Qi.pollingInterval),this.#he=n}_getSubscriber(t){const e=super._getSubscriber(t);return Zi(e)&&(e.pollingInterval=this.#he),e}get pollingInterval(){return this.#he}set pollingInterval(t){if(!Number.isInteger(t)||t<0)throw new Error("invalid interval");this.#he=t,this._forEachSubscriber((t=>{Zi(t)&&(t.pollingInterval=this.#he)}))}}class ra extends na{#de;constructor(t,e,n){null==t&&(t="http://localhost:8545"),super(e,n),this.#de="string"==typeof t?new wt(t):t.clone()}_getConnection(){return this.#de.clone()}async send(t,e){return await this._start(),await super.send(t,e)}async _send(t){const e=this._getConnection();e.body=JSON.stringify(t),e.setHeader("content-type","application/json");const n=await e.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}}function sa(t){if(null==t)return null;if("string"==typeof t.message&&t.message.match(/revert/i)&&S(t.data))return{message:t.message,data:t.data};if("object"==typeof t){for(const e in t){const n=sa(t[e]);if(n)return n}return null}if("string"==typeof t)try{return sa(JSON.parse(t))}catch(t){}return null}function ia(t,e){if(null!=t){if("string"==typeof t.message&&e.push(t.message),"object"==typeof t)for(const n in t)ia(t[n],e);if("string"==typeof t)try{return ia(JSON.parse(t),e)}catch(t){}}}class aa extends na{#E;constructor(t,e,n){const r=Object.assign({},null!=n?n:{},{batchMaxCount:1});N(t&&t.request,"invalid EIP-1193 provider","ethereum",t),super(e,r),this.#E=async(e,n)=>{const r={method:e,params:n};this.emit("debug",{action:"sendEip1193Request",payload:r});try{const e=await t.request(r);return this.emit("debug",{action:"receiveEip1193Result",result:e}),e}catch(t){const e=new Error(t.message);throw e.code=t.code,e.data=t.data,e.payload=r,this.emit("debug",{action:"receiveEip1193Error",error:e}),e}}}async send(t,e){return await this._start(),await super.send(t,e)}async _send(t){N(!Array.isArray(t),"EIP-1193 does not support batch request","payload",t);try{const e=await this.#E(t.method,t.params||[]);return[{id:t.id,result:e}]}catch(e){return[{id:t.id,error:{code:e.code,data:e.data,message:e.message}}]}}getRpcError(t,e){switch((e=JSON.parse(JSON.stringify(e))).error.code||-1){case 4001:e.error.message=`ethers-user-denied: ${e.error.message}`;break;case 4200:e.error.message=`ethers-unsupported: ${e.error.message}`}return super.getRpcError(t,e)}async hasSigner(t){null==t&&(t=0);const e=await this.send("eth_accounts",[]);return"number"==typeof t?e.length>t:(t=t.toLowerCase(),0!==e.filter((e=>e.toLowerCase()===t)).length)}async getSigner(t){if(null==t&&(t=0),!await this.hasSigner(t))try{await this.#E("eth_requestAccounts",[])}catch(t){const e=t.payload;throw this.getRpcError(e,{id:e.id,error:t})}return await super.getSigner(t)}}class oa extends Ki{address;#pe;constructor(t,e){super(e),N(t&&"function"==typeof t.sign,"invalid private key","privateKey","[ REDACTED ]"),this.#pe=t;y(this,{address:Nn(this.signingKey.publicKey)})}get signingKey(){return this.#pe}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(t){return new oa(this.#pe,t)}async signTransaction(t){t=hs(t);const{to:e,from:n}=await g({to:t.to?He(t.to,this.provider):void 0,from:t.from?He(t.from,this.provider):void 0});null!=e&&(t.to=e),null!=n&&(t.from=n),null!=t.from&&(N(Me(t.from)===this.address,"transaction from address mismatch","tx.from",t.from),delete t.from);const r=$n.from(t);return r.signature=this.signingKey.sign(r.unsignedHash),r.serialized}async signMessage(t){return this.signMessageSync(t)}signMessageSync(t){return this.signingKey.sign(Mn(t)).serialized}async signTypedData(t,e,n){const r=await nr.resolveNames(t,e,n,(async t=>{E(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:t}});const e=await this.provider.resolveName(t);return E(null!=e,"unconfigured ENS name","UNCONFIGURED_NAME",{value:t}),e}));return this.signingKey.sign(nr.hash(r.domain,e,r.value)).serialized}}const ca=" !#$%&'()*+,-./<=>?@[]^_`{|}~",la=/^[a-z]*$/i;function ua(t,e){let n=97;return t.reduce(((t,r)=>(r===e?n++:r.match(la)?t.push(String.fromCharCode(n)+r):(n=97,t.push(r)),t)),[])}function ha(t){return N("0"===t[0],"unsupported auwl data","data",t),function(t,e){for(let n=28;n>=0;n--)t=t.split(ca[n]).join(e.substring(2*n,2*n+2));const n=[],r=t.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((t,e,r,s)=>{if(r)for(let t=parseInt(r);t>=0;t--)n.push(";");else n.push(e.toLowerCase());return""}));if(r)throw new Error(`leftovers: ${JSON.stringify(r)}`);return ua(ua(n,";"),":")}(t.substring(59),t.substring(1,59))}class da{locale;constructor(t){y(this,{locale:t})}split(t){return t.toLowerCase().split(/\s+/g)}join(t){return t.join(" ")}}class pa extends da{#k;#fe;constructor(t,e,n){super(t),this.#k=e,this.#fe=n,this.#ge=null}get _data(){return this.#k}_decodeWords(){return ha(this.#k)}#ge;#ye(){if(null==this.#ge){const t=this._decodeWords();if(fn(t.join("\n")+"\n")!==this.#fe)throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);this.#ge=t}return this.#ge}getWord(t){const e=this.#ye();return N(t>=0&&t<e.length,`invalid word index: ${t}`,"index",t),e[t]}getWordIndex(t){return this.#ye().indexOf(t)}}let fa=null;class ga extends pa{constructor(){super("en","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","0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60")}static wordlist(){return null==fa&&(fa=new ga),fa}}function ya(t){return(1<<t)-1<<8-t&255}function ma(t,e){T("NFKD"),null==e&&(e=ga.wordlist());const n=e.split(t);N(n.length%3==0&&n.length>=12&&n.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const r=new Uint8Array(Math.ceil(11*n.length/8));let s=0;for(let t=0;t<n.length;t++){let i=e.getWordIndex(n[t].normalize("NFKD"));N(i>=0,`invalid mnemonic word at index ${t}`,"mnemonic","[ REDACTED ]");for(let t=0;t<11;t++)i&1<<10-t&&(r[s>>3]|=1<<7-s%8),s++}const i=32*n.length/3,a=ya(n.length/3);return N((O(Pe(r.slice(0,i/8)))[0]&a)===(r[r.length-1]&a),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),_(r.slice(0,i/8))}function ba(t,e){N(t.length%4==0&&t.length>=16&&t.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==e&&(e=ga.wordlist());const n=[0];let r=11;for(let e=0;e<t.length;e++)r>8?(n[n.length-1]<<=8,n[n.length-1]|=t[e],r-=8):(n[n.length-1]<<=r,n[n.length-1]|=t[e]>>8-r,n.push(t[e]&((1<<8-r)-1&255)),r+=3);const s=t.length/4,i=parseInt(Pe(t).substring(2,4),16)&ya(s);return n[n.length-1]<<=s,n[n.length-1]|=i>>8-s,e.join(n.map((t=>e.getWord(t))))}const wa={};class va{phrase;password;wordlist;entropy;constructor(t,e,n,r,s){null==r&&(r=""),null==s&&(s=ga.wordlist()),R(t,wa,"Mnemonic"),y(this,{phrase:n,password:r,wordlist:s,entropy:e})}computeSeed(){const t=ot("mnemonic"+this.password,"NFKD");return oe(ot(this.phrase,"NFKD"),t,2048,64,"sha512")}static fromPhrase(t,e,n){const r=ma(t,n);return t=ba(O(r),n),new va(wa,r,t,e,n)}static fromEntropy(t,e,n){const r=O(t,"entropy"),s=ba(r,n);return new va(wa,_(r),s,e,n)}static entropyToPhrase(t,e){return ba(O(t,"entropy"),e)}static phraseToEntropy(t,e){return ma(t,e)}static isValidMnemonic(t,e){try{return ma(t,e),!0}catch(t){}return!1}}function Ea(t){return"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),I(t)}function Na(t,e){for(t=String(t);t.length<e;)t="0"+t;return t}function Pa(t){return"string"==typeof t?ot(t,"NFKC"):I(t)}function ka(t,e){const n=e.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);N(null!=n,"invalid path","path",e);const r=n[1],s=n[3],i="!"===n[4];let a=t;for(const t of r.toLowerCase().split(".")){if(Array.isArray(a)){if(!t.match(/^[0-9]+$/))break;a=a[parseInt(t)]}else if("object"==typeof a){let e=null;for(const n in a)if(n.toLowerCase()===t){e=a[n];break}a=e}else a=null;if(null==a)break}if(N(!i||null!=a,"missing required value","path",r),s&&null!=a){if("int"===s){if("string"==typeof a&&a.match(/^-?[0-9]+$/))return parseInt(a);if(Number.isSafeInteger(a))return a}if("number"===s&&"string"==typeof a&&a.match(/^-?[0-9.]*$/))return parseFloat(a);if("data"===s&&"string"==typeof a)return Ea(a);if("array"===s&&Array.isArray(a))return a;if(s===typeof a)return a;N(!1,`wrong type found for ${s} `,"path",r)}return a}const Ta="m/44'/60'/0'/0/0";function Ra(t){try{const e=JSON.parse(t);if(3===(null!=e.version?parseInt(e.version):0))return!0}catch(t){}return!1}function Aa(t,e){const n=O(e),r=ka(t,"crypto.ciphertext:data!");N(_(Qt(U([n.slice(16,32),r]))).substring(2)===ka(t,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const s=function(t,e,n){if("aes-128-ctr"===ka(t,"crypto.cipher:string")){const r=ka(t,"crypto.cipherparams.iv:data!");return _(new o.CTR(e,r).decrypt(n))}E(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(t,n.slice(0,16),r),i=Nn(s);if(t.address){let e=t.address.toLowerCase();e.startsWith("0x")||(e="0x"+e),N(Me(e)===i,"keystore address/privateKey mismatch","address",t.address)}const a={address:i,privateKey:s};if("0.1"===ka(t,"x-ethers.version:string")){const e=n.slice(32,64),r=ka(t,"x-ethers.mnemonicCiphertext:data!"),s=ka(t,"x-ethers.mnemonicCounter:data!"),i=new o.CTR(e,s);a.mnemonic={path:ka(t,"x-ethers.path:string")||Ta,locale:ka(t,"x-ethers.locale:string")||"en",entropy:_(O(i.decrypt(r)))}}return a}function Oa(t){const e=ka(t,"crypto.kdf:string");if(e&&"string"==typeof e){if("scrypt"===e.toLowerCase()){const n=ka(t,"crypto.kdfparams.salt:data!"),r=ka(t,"crypto.kdfparams.n:int!"),s=ka(t,"crypto.kdfparams.r:int!"),i=ka(t,"crypto.kdfparams.p:int!");N(r>0&&!(r&r-1),"invalid kdf.N","kdf.N",r),N(s>0&&i>0,"invalid kdf","kdf",e);const a=ka(t,"crypto.kdfparams.dklen:int!");return N(32===a,"invalid kdf.dklen","kdf.dflen",a),{name:"scrypt",salt:n,N:r,r:s,p:i,dkLen:64}}if("pbkdf2"===e.toLowerCase()){const e=ka(t,"crypto.kdfparams.salt:data!"),n=ka(t,"crypto.kdfparams.prf:string!"),r=n.split("-").pop();N("sha256"===r||"sha512"===r,"invalid kdf.pdf","kdf.pdf",n);const s=ka(t,"crypto.kdfparams.c:int!"),i=ka(t,"crypto.kdfparams.dklen:int!");return N(32===i,"invalid kdf.dklen","kdf.dklen",i),{name:"pbkdf2",salt:e,count:s,dkLen:i,algorithm:r}}}N(!1,"unsupported key-derivation function","kdf",e)}function Ia(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}function Sa(t){const e=null!=t.salt?O(t.salt,"options.salt"):he(32);let n=1<<17,r=8,s=1;return t.scrypt&&(t.scrypt.N&&(n=t.scrypt.N),t.scrypt.r&&(r=t.scrypt.r),t.scrypt.p&&(s=t.scrypt.p)),N("number"==typeof n&&n>0&&Number.isSafeInteger(n)&&(BigInt(n)&BigInt(n-1))===BigInt(0),"invalid scrypt N parameter","options.N",n),N("number"==typeof r&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r),N("number"==typeof s&&s>0&&Number.isSafeInteger(s),"invalid scrypt p parameter","options.p",s),{name:"scrypt",dkLen:32,salt:e,N:n,r:r,p:s}}function xa(t,e,n,r){const s=O(n.privateKey,"privateKey"),i=null!=r.iv?O(r.iv,"options.iv"):he(16);N(16===i.length,"invalid options.iv length","options.iv",r.iv);const a=null!=r.uuid?O(r.uuid,"options.uuid"):he(16);N(16===a.length,"invalid options.uuid length","options.uuid",r.iv);const c=t.slice(0,16),l=t.slice(16,32),u=O(new o.CTR(c,i).encrypt(s)),h=Qt(U([l,u])),d={address:n.address.substring(2).toLowerCase(),id:xt(a),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:_(i).substring(2)},ciphertext:_(u).substring(2),kdf:"scrypt",kdfparams:{salt:_(e.salt).substring(2),n:e.N,dklen:32,p:e.p,r:e.r},mac:h.substring(2)}};if(n.mnemonic){const e=null!=r.client?r.client:`ethers/${p}`,s=n.mnemonic.path||Ta,i=n.mnemonic.locale||"en",a=t.slice(32,64),c=O(n.mnemonic.entropy,"account.mnemonic.entropy"),l=he(16),u=O(new o.CTR(a,l).encrypt(c)),h=new Date,f="UTC--"+(h.getUTCFullYear()+"-"+Na(h.getUTCMonth()+1,2)+"-"+Na(h.getUTCDate(),2)+"T"+Na(h.getUTCHours(),2)+"-"+Na(h.getUTCMinutes(),2)+"-"+Na(h.getUTCSeconds(),2)+".0Z")+"--"+d.address;d["x-ethers"]={client:e,gethFilename:f,path:s,locale:i,mnemonicCounter:_(l).substring(2),mnemonicCiphertext:_(u).substring(2),version:"0.1"}}return JSON.stringify(d)}function Ca(t,e,n){null==n&&(n={});const r=Pa(e),s=Sa(n);return xa(O(we(r,s.salt,s.N,s.r,s.p,64)),s,t,n)}async function _a(t,e,n){null==n&&(n={});const r=Pa(e),s=Sa(n);return xa(O(await be(r,s.salt,s.N,s.r,s.p,64,n.progressCallback)),s,t,n)}const Ua="m/44'/60'/0'/0/0",Fa=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),La=2147483648,Da=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function Ba(t,e){let n="";for(;t;)n="0123456789abcdef"[t%16]+n,t=Math.trunc(t/16);for(;n.length<2*e;)n="0"+n;return"0x"+n}function Ga(t){const e=O(t);return rt(U([e,L(Pe(Pe(e)),0,4)]))}const $a={};function Ma(t,e,n,r){const s=new Uint8Array(37);t&La?(E(null!=r,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),s.set(O(r),1)):s.set(O(n));for(let e=24;e>=0;e-=8)s[33+(e>>3)]=t>>24-e&255;const i=O(Wt("sha512",e,s));return{IL:i.slice(0,32),IR:i.slice(32)}}function ja(t,e){const n=e.split("/");N(n.length>0,"invalid path","path",e),"m"===n[0]&&(N(0===t.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${t.depth}`,"path",e),n.shift());let r=t;for(let t=0;t<n.length;t++){const e=n[t];if(e.match(/^[0-9]+'$/)){const n=parseInt(e.substring(0,e.length-1));N(n<La,"invalid path index",`path[${t}]`,e),r=r.deriveChild(La+n)}else if(e.match(/^[0-9]+$/)){const n=parseInt(e);N(n<La,"invalid path index",`path[${t}]`,e),r=r.deriveChild(n)}else N(!1,"invalid path component",`path[${t}]`,e)}return r}class Ka extends oa{publicKey;fingerprint;parentFingerprint;mnemonic;chainCode;path;index;depth;constructor(t,e,n,r,s,i,a,o,c){super(e,c),R(t,$a,"HDNodeWallet"),y(this,{publicKey:e.compressedPublicKey});y(this,{parentFingerprint:n,fingerprint:L(re(Pe(this.publicKey)),0,4),chainCode:r,path:s,index:i,depth:a}),y(this,{mnemonic:o})}connect(t){return new Ka($a,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,t)}#me(){const t={address:this.address,privateKey:this.privateKey},e=this.mnemonic;return this.path&&e&&"en"===e.wordlist.locale&&""===e.password&&(t.mnemonic={path:this.path,locale:"en",entropy:e.entropy}),t}async encrypt(t,e){return await _a(this.#me(),t,{progressCallback:e})}encryptSync(t){return Ca(this.#me(),t)}get extendedKey(){return E(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Ga(U(["0x0488ADE4",Ba(this.depth,1),this.parentFingerprint,Ba(this.index,4),this.chainCode,U(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new Ha($a,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(t){const e=q(t,"index");N(e<=4294967295,"invalid index","index",e);let n=this.path;n&&(n+="/"+(2147483647&e),e&La&&(n+="'"));const{IR:r,IL:s}=Ma(e,this.chainCode,this.publicKey,this.privateKey),i=new Fe(W((J(s)+BigInt(this.privateKey))%Da,32));return new Ka($a,i,this.fingerprint,_(r),n,e,this.depth+1,this.mnemonic,this.provider)}derivePath(t){return ja(this,t)}static#be(t,e){N(x(t),"invalid seed","seed","[REDACTED]");const n=O(t,"seed");N(n.length>=16&&n.length<=64,"invalid seed","seed","[REDACTED]");const r=O(Wt("sha512",Fa,n)),s=new Fe(_(r.slice(0,32)));return new Ka($a,s,"0x00000000",_(r.slice(32)),"m",0,0,e,null)}static fromExtendedKey(t){const e=Y(function(t){let e=et;for(let n=0;n<t.length;n++)e*=nt,e+=tt(t[n]);return e}(t));N(82===e.length||Ga(e.slice(0,78))===t,"invalid extended key","extendedKey","[ REDACTED ]");const n=e[4],r=_(e.slice(5,9)),s=parseInt(_(e.slice(9,13)).substring(2),16),i=_(e.slice(13,45)),a=e.slice(45,78);switch(_(e.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const t=_(a);return new Ha($a,Nn(t),t,r,i,null,s,n,null)}case"0x0488ade4":case"0x04358394 ":if(0!==a[0])break;return new Ka($a,new Fe(a.slice(1)),r,i,null,s,n,null,null)}N(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(t,e,n){null==t&&(t=""),null==e&&(e=Ua),null==n&&(n=ga.wordlist());const r=va.fromEntropy(he(16),t,n);return Ka.#be(r.computeSeed(),r).derivePath(e)}static fromMnemonic(t,e){return e||(e=Ua),Ka.#be(t.computeSeed(),t).derivePath(e)}static fromPhrase(t,e,n,r){null==e&&(e=""),null==n&&(n=Ua),null==r&&(r=ga.wordlist());const s=va.fromPhrase(t,e,r);return Ka.#be(s.computeSeed(),s).derivePath(n)}static fromSeed(t){return Ka.#be(t,null)}}class Ha extends Hi{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(t,e,n,r,s,i,a,o,c){super(e,c),R(t,$a,"HDNodeVoidWallet"),y(this,{publicKey:n});y(this,{publicKey:n,fingerprint:L(re(Pe(n)),0,4),parentFingerprint:r,chainCode:s,path:i,index:a,depth:o})}connect(t){return new Ha($a,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,t)}get extendedKey(){return E(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),Ga(U(["0x0488B21E",Ba(this.depth,1),this.parentFingerprint,Ba(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(t){const e=q(t,"index");N(e<=4294967295,"invalid index","index",e);let n=this.path;n&&(n+="/"+(2147483647&e),e&La&&(n+="'"));const{IR:r,IL:s}=Ma(e,this.chainCode,this.publicKey,null),i=Fe.addPoints(s,this.publicKey,!0),a=Nn(i);return new Ha($a,a,i,this.fingerprint,_(r),n,e,this.depth+1,this.provider)}derivePath(t){return ja(this,t)}}function Va(t){try{if(JSON.parse(t).encseed)return!0}catch(t){}return!1}function za(t,e){const n=JSON.parse(t),r=Pa(e),s=Me(ka(n,"ethaddr:string!")),i=Ea(ka(n,"encseed:string!"));N(i&&i.length%16==0,"invalid encseed","json",t);const a=O(oe(r,r,2e3,32,"sha256")).slice(0,16),c=i.slice(0,16),l=i.slice(16),u=new o.CBC(a,c),h=o.pkcs7Strip(O(u.decrypt(l)));let d="";for(let t=0;t<h.length;t++)d+=String.fromCharCode(h[t]);return{address:s,privateKey:fn(d)}}function Ja(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}class qa extends oa{constructor(t,e){"string"!=typeof t||t.startsWith("0x")||(t="0x"+t),super("string"==typeof t?new Fe(t):t,e)}connect(t){return new qa(this.signingKey,t)}async encrypt(t,e){const n={address:this.address,privateKey:this.privateKey};return await _a(n,t,{progressCallback:e})}encryptSync(t){return Ca({address:this.address,privateKey:this.privateKey},t)}static#we(t){if(N(t,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in t&&t.mnemonic&&"en"===t.mnemonic.locale){const e=va.fromEntropy(t.mnemonic.entropy),n=Ka.fromMnemonic(e,t.mnemonic.path);if(n.address===t.address&&n.privateKey===t.privateKey)return n;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const e=new qa(t.privateKey);return N(e.address===t.address,"address/privateKey mismatch","json","[ REDACTED ]"),e}static async fromEncryptedJson(t,e,n){let r=null;return Ra(t)?r=await async function(t,e,n){const r=JSON.parse(t),s=Pa(e),i=Oa(r);if("pbkdf2"===i.name){n&&(n(0),await Ia(0));const{salt:t,count:e,dkLen:a,algorithm:o}=i,c=oe(s,t,e,a,o);return n&&(n(1),await Ia(0)),Aa(r,c)}E("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:a,N:o,r:c,p:l,dkLen:u}=i;return Aa(r,await be(s,a,o,c,l,u,n))}(t,e,n):Va(t)&&(n&&(n(0),await Ja(0)),r=za(t,e),n&&(n(1),await Ja(0))),qa.#we(r)}static fromEncryptedJsonSync(t,e){let n=null;return Ra(t)?n=function(t,e){const n=JSON.parse(t),r=Pa(e),s=Oa(n);if("pbkdf2"===s.name){const{salt:t,count:e,dkLen:i,algorithm:a}=s;return Aa(n,oe(r,t,e,i,a))}E("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:i,N:a,r:o,p:c,dkLen:l}=s;return Aa(n,we(r,i,a,o,c,l))}(t,e):Va(t)?n=za(t,e):N(!1,"invalid JSON wallet","json","[ REDACTED ]"),qa.#we(n)}static createRandom(t){const e=Ka.createRandom();return t?e.connect(t):e}static fromPhrase(t,e){const n=Ka.fromPhrase(t);return e?n.connect(e):n}}var Wa={STEALTH_ANNOUNCER_ADDRESS:"",PROOF_OF_INTEGRITY_ADDRESS:""};let Ya={PROOF_OF_INTEGRITY_ADDRESS:"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",STEALTH_ANNOUNCER_ADDRESS:"0x5FbDB2315678afecb367f032d93F642f64180aa3"};if("undefined"==typeof window){const{fileURLToPath:t}=require("url"),{dirname:e}=require("path"),{readFileSync:n}=require("fs"),{join:r}=require("path");try{const s=t("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(s).href:"undefined"==typeof document?location.href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("gun-eth.bundle.min.js",document.baseURI).href),i=n(r(e(s),"contract-address.json"),"utf8");Ya=JSON.parse(i),console.log("Loaded contract addresses:",Ya)}catch(t){console.warn("Warning: contract-address.json not found or invalid")}}const Xa={CHAIN_ID:1337,PROOF_OF_INTEGRITY_ADDRESS:Ya.PROOF_OF_INTEGRITY_ADDRESS,STEALTH_ANNOUNCER_ADDRESS:Ya.STEALTH_ANNOUNCER_ADDRESS,RPC_URL:"http://127.0.0.1:8545",GUN_PEER:"http://localhost:8765/gun"},Za={optimismSepolia:{STEALTH_ANNOUNCER_ADDRESS:"0xD0F2e9DA59d2DFECFdE67CcF17300BB6093A72f8",PROOF_OF_INTEGRITY_ADDRESS:"0x...",RPC_URL:"https://sepolia.optimism.io",CHAIN_ID:11155420},arbitrumSepolia:{STEALTH_ANNOUNCER_ADDRESS:"0x...",PROOF_OF_INTEGRITY_ADDRESS:"0x...",RPC_URL:"https://sepolia-rollup.arbitrum.io/rpc",CHAIN_ID:421614},localhost:{RPC_URL:"http://127.0.0.1:8545",CHAIN_ID:1337}};function Qa(t){let e;if("localhost"===t)try{return e={...Za.localhost,...Wa},console.log("Using local addresses:",e),e}catch(t){throw console.warn("No local addresses found"),new Error("No local addresses found. Did you run local deployment?")}if(e=Za[t],!e)throw new Error(`Chain ${t} not supported. Supported chains: ${Object.keys(Za).join(", ")}`);return e}const to=[{inputs:[{internalType:"address",name:"_devAddress",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],name:"StealthPaymentAnnounced",type:"event"},{anonymous:!1,inputs:[{internalType:"address",name:"newAddress",type:"address"}],name:"DevAddressUpdated",type:"event"},{anonymous:!1,inputs:[{internalType:"uint256",name:"newFee",type:"uint256"}],name:"DevFeeUpdated",type:"event"},{inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"}],name:"announcePayment",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"devAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"devFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getAnnouncementsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"fromIndex",type:"uint256"},{internalType:"uint256",name:"toIndex",type:"uint256"}],name:"getAnnouncementsInRange",outputs:[{components:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct StealthAnnouncer.StealthAnnouncement[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newFee",type:"uint256"}],name:"updateDevFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newAddress",type:"address"}],name:"updateDevAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawStuckETH",outputs:[],stateMutability:"nonpayable",type:"function"}],eo=[{inputs:[{internalType:"bytes[]",name:"nodeIds",type:"bytes[]"},{internalType:"bytes32[]",name:"contentHashes",type:"bytes32[]"}],name:"batchUpdateData",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes",name:"nodeId",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"},{indexed:!1,internalType:"address",name:"updater",type:"address"}],name:"DataUpdated",type:"event"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"}],name:"getLatestRecord",outputs:[{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"updateData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"verifyData",outputs:[{internalType:"bool",name:"",type:"bool"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];let no="",ro="";const so="Access GunDB with Ethereum";function io(){return _(he(32)).slice(2)}function ao(t){try{const e=Qt(_(t));return console.log("Generated password:",e),e}catch(t){return console.error("Error generating password:",t),null}}function oo(t){const e="0x"+(t=>{const e="=".repeat((4-t.length%4)%4),n=t.replace(/-/g,"+").replace(/_/g,"/")+e,r=atob(n);return Array.from(r,(t=>t.charCodeAt(0).toString(16).padStart(2,"0"))).join("")})(t),n=new qa(e);return{account:n,publicKey:n.address,privateKey:e}}const co=async()=>{if(no&&ro){const t=new ra(no,{chainId:Xa.CHAIN_ID,name:"localhost"});return new qa(ro,t)}if("undefined"!=typeof window&&void 0!==window.ethereum){await window.ethereum.request({method:"eth_requestAccounts"});return new aa(window.ethereum).getSigner()}throw new Error("No valid Ethereum provider found")};function lo(t,e){try{const n=Buffer.from(t,"base64"),r=Qt(U([n,O(e)])),s=new qa(r);return console.log("Debug deriveStealthAddress:",{sharedSecretHex:_(n),spendingPublicKey:e,stealthPrivateKey:r,stealthAddress:s.address}),{stealthPrivateKey:r,stealthAddress:s.address,wallet:s}}catch(t){throw console.error("Error in deriveStealthAddress:",t),t}}e.chain.MESSAGE_TO_SIGN=so,e.chain.setSigner=function(t,e){return no=t,ro=e,console.log("Standalone configuration set"),this},e.chain.getSigner=co(),e.chain.verifySignature=async function(t,e){try{const n=function(t,e){return Pn(Mn(t),e)}(t,e);return n}catch(t){return console.error("Error verifying signature:",t),null}},e.chain.generatePassword=function(t){return ao(t)},e.chain.createSignature=async function(t){try{if(t!==so)throw new Error("Invalid message, valid message is: "+so);const e=await co(),n=await e.signMessage(t);return console.log("Signature created:",n),n}catch(t){return console.error("Error creating signature:",t),null}},e.chain.createAndStoreEncryptedPair=async function(t,e){try{const r=this,s=await n.pair(),i=await n.pair(),a=await n.pair(),o=ao(e),c=await n.encrypt(JSON.stringify(s),o),l=await n.encrypt(JSON.stringify(i),o),u=await n.encrypt(JSON.stringify(a),o),h=oo(i.priv),d=oo(a.priv);r.get("gun-eth").get("users").get(t).put({pair:c,v_pair:l,s_pair:u,publicKeys:{viewingPublicKey:i.epub,viewingPublicKey:i.epub,spendingPublicKey:d.publicKey,ethViewingAddress:h.publicKey}}),console.log("Encrypted pairs and public keys stored for:",t)}catch(t){throw console.error("Error creating and storing encrypted pair:",t),t}},e.chain.getAndDecryptPair=async function(t,e){try{const r=this,s=await r.get("gun-eth").get("users").get(t).get("pair").then();if(!s)throw new Error("No encrypted data found for this address");const i=ao(e),a=await n.decrypt(s,i);return console.log(a),a}catch(t){return console.error("Error retrieving and decrypting pair:",t),null}},e.chain.proof=function(t,e,n,r){if(console.log("Proof plugin called with:",{chain:t,nodeId:e,data:n}),"function"!=typeof r)return console.error("Callback must be a function"),this;try{const s=Qa(t);console.log(`Using ${t} configuration:`,s);new zs(s.PROOF_OF_INTEGRITY_ADDRESS,eo,signer);const i=async(t,e)=>{console.log("Verifying on chain:",{nodeId:t,contentHash:e});const n=await co(),r=new zs(PROOF_CONTRACT_ADDRESS,eo,n),[s,i,a]=await r.verifyData(ot(t),e);return console.log("Verification result:",{isValid:s,timestamp:i,updater:a}),{isValid:s,timestamp:i,updater:a}},a=async(t,e)=>{console.log("Writing on chain:",{nodeId:t,contentHash:e});const n=await co(),r=new zs(PROOF_CONTRACT_ADDRESS,eo,n),s=await r.updateData(ot(t),e);console.log("Transaction sent:",s.hash);const i=await s.wait();return console.log("Transaction confirmed:",i),s},o=async t=>{const e=await co(),n=new zs(PROOF_CONTRACT_ADDRESS,eo,e),[r,s,i]=await n.getLatestRecord(ot(t));return console.log("Latest record from blockchain:",{nodeId:t,contentHash:r,timestamp:s,updater:i}),{contentHash:r,timestamp:s,updater:i}};if(e&&!n)gun.get(e).once((async t=>{if(!t)return void(r&&r({err:"Node not found in GunDB"}));console.log("existingData",t);const n=t._contentHash;if(console.log("contentHash",n),n)try{const{isValid:t,timestamp:s,updater:a}=await i(e,n),c=await o(e);t?r&&r({ok:!0,message:"Data verified on blockchain",timestamp:s,updater:a,latestRecord:c}):r&&r({ok:!1,message:"Data not verified on blockchain",latestRecord:c})}catch(t){r&&r({err:t.message})}else r&&r({err:"No content hash found for this node"})}));else if(n&&!e){const t=io(),e=Qt(ot(JSON.stringify(n)));gun.get(t).put({...n,_contentHash:e},(async n=>{if(console.log("ack",n),n.err)r&&r({err:"Error saving data to GunDB"});else try{const n=await a(t,e);r&&r({ok:!0,message:"Data written to GunDB and blockchain",nodeId:t,txHash:n.hash})}catch(t){r&&r({err:t.message})}}))}else r&&r({err:"Invalid input. Provide either nodeId or data, not both."});return gun}catch(t){return r({err:t.message}),this}},e.chain.gunToEthAccount=function(t){return oo(t)},e.chain.generateStealthAddress=async function(t,e){try{const r=this,s=await r.get("gun-eth").get("users").get(t).get("publicKeys").then();if(!s||!s.viewingPublicKey||!s.spendingPublicKey)throw new Error("Recipient's public keys not found");const i=await this.verifySignature(so,e),a=ao(e),o=await r.get("gun-eth").get("users").get(i).then();if(!o||!o.s_pair)throw new Error("Sender's keys not found");let c;try{const t=await n.decrypt(o.s_pair,a);c="string"==typeof t?JSON.parse(t):t}catch(t){throw console.error("Error decrypting spending pair:",t),new Error("Unable to decrypt spending pair")}const l=await n.secret(s.viewingPublicKey,c);if(!l)throw new Error("Unable to generate shared secret");console.log("Generate shared secret:",l);const{stealthAddress:u}=lo(l,s.spendingPublicKey);return{stealthAddress:u,senderPublicKey:c.epub,spendingPublicKey:s.spendingPublicKey}}catch(t){throw console.error("Error generating stealth address:",t),t}},e.chain.publishStealthKeys=async function(t){try{const e=this,r=await this.verifySignature(so,t),s=ao(t),i=await e.get("gun-eth").get("users").get(r).then();if(!i||!i.v_pair||!i.s_pair)throw new Error("Keys not found");const a=JSON.parse(await n.decrypt(i.v_pair,s)),o=JSON.parse(await n.decrypt(i.s_pair,s)),c=oo(a.priv),l=oo(o.priv);e.get("gun-eth").get("users").get(r).get("publicKeys").put({viewingPublicKey:c.publicKey,spendingPublicKey:l.publicKey}),console.log("Stealth public keys published successfully")}catch(t){throw console.error("Error publishing stealth keys:",t),t}},e.chain.recoverStealthFunds=async function(t,e,r,s){try{const i=this,a=ao(r),o=await this.verifySignature(so,r),c=await i.get("gun-eth").get("users").get(o).then();if(!c||!c.v_pair||!c.s_pair)throw new Error("Keys not found");let l;try{const t=await n.decrypt(c.v_pair,a);l="string"==typeof t?JSON.parse(t):t}catch(t){throw console.error("Error decrypting keys:",t),new Error("Unable to decrypt keys")}const u=await n.secret(e,l);if(!u)throw new Error("Unable to generate shared secret");console.log("Recover shared secret:",u);const{wallet:h,stealthAddress:d}=lo(u,s);if(d.toLowerCase()!==t.toLowerCase())throw console.error("Mismatch:",{recovered:d,expected:t,sharedSecret:u}),new Error("Recovered stealth address does not match");return{wallet:h,address:d}}catch(t){throw console.error("Error recovering stealth funds:",t),t}},e.chain.announceStealthPayment=async function(t,e,n,r,s={onChain:!1,chain:"optimismSepolia"}){try{const i=this,a=await this.verifySignature(so,r);if(s.onChain){const r=await co(),i=Qa(s.chain),a=new zs(i.STEALTH_ANNOUNCER_ADDRESS,to,r),o=await a.devFee();console.log("Dev fee:",o.toString());const c=await a.announcePayment(e,n,t,{value:o});console.log("Transaction sent:",c.hash);const l=await c.wait();console.log("Transaction confirmed:",l.hash),console.log("Stealth payment announced on-chain (dev fee paid)")}else i.get("gun-eth").get("stealth-payments").set({stealthAddress:t,senderAddress:a,senderPublicKey:e,spendingPublicKey:n,timestamp:Date.now()}),console.log("Stealth payment announced off-chain")}catch(t){throw console.error("Error announcing stealth payment:",t),console.error("Error details:",t.stack),t}},e.chain.getStealthPayments=async function(t,e={source:"both"}){try{const n=[];if("onChain"===e.source||"both"===e.source){const e=await co(),r="development"===process.env.NODE_ENV?Xa.STEALTH_ANNOUNCER_ADDRESS:STEALTH_ANNOUNCER_ADDRESS,s=new zs(r,to,e);try{const e=await s.getAnnouncementsCount(),r=Number(e.toString());if(console.log("Total on-chain announcements:",r),r>0){const e=100,i=r-1;for(let r=0;r<=i;r+=e){const a=Math.min(r+e-1,i),o=await s.getAnnouncementsInRange(r,a);for(const e of o)try{if(!(e&&e.stealthAddress&&e.senderPublicKey&&e.spendingPublicKey)){console.log("Invalid announcement:",e);continue}const r=await this.recoverStealthFunds(e.stealthAddress,e.senderPublicKey,t,e.spendingPublicKey);n.push({stealthAddress:e.stealthAddress,senderPublicKey:e.senderPublicKey,spendingPublicKey:e.spendingPublicKey,timestamp:Number(e.timestamp),source:"onChain",wallet:r})}catch(t){console.log(`Announcement not for us: ${e.stealthAddress}`);continue}}}}catch(t){console.error("Error retrieving on-chain announcements:",t)}}if("offChain"===e.source||"both"===e.source){const t=this,e=await new Promise((e=>{const n=[];t.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once(((t,e)=>{t?.stealthAddress&&n.push({...t,id:e,source:"offChain"})})),setTimeout((()=>e(n)),2e3)}));n.push(...e)}return console.log(`Found ${n.length} stealth payments`),n}catch(t){throw console.error("Error retrieving stealth payments:",t),t}},e.chain.cleanStealthPayments=async function(t){try{const e=this,n=await e.get("gun-eth").get("stealth-payments").get(t).map().once().then();n&&Object.keys(n).forEach((async r=>{const s=n[r];s&&s.stealthAddress&&s.senderPublicKey&&s.spendingPublicKey||await e.get("gun-eth").get("stealth-payments").get(t).get(r).put(null)}))}catch(t){console.error("Error cleaning stealth payments:",t)}};class uo{static generateRandomId=io;static generatePassword=ao;static gunToEthAccount=oo;static getSigner=co;static deriveStealthAddress=lo;static chainMethods={setSigner:e.chain.setSigner,getSigner:e.chain.getSigner,verifySignature:e.chain.verifySignature,generatePassword:e.chain.generatePassword,createSignature:e.chain.createSignature,createAndStoreEncryptedPair:e.chain.createAndStoreEncryptedPair,getAndDecryptPair:e.chain.getAndDecryptPair,proof:e.chain.proof,gunToEthAccount:e.chain.gunToEthAccount,generateStealthAddress:e.chain.generateStealthAddress,publishStealthKeys:e.chain.publishStealthKeys,recoverStealthFunds:e.chain.recoverStealthFunds,announceStealthPayment:e.chain.announceStealthPayment,getStealthPayments:e.chain.getStealthPayments,cleanStealthPayments:e.chain.cleanStealthPayments};static MESSAGE_TO_SIGN=so;static PROOF_CONTRACT_ADDRESS=PROOF_CONTRACT_ADDRESS;static LOCAL_CONFIG=Xa}t.default=e,t.GunEth=uo,t.MESSAGE_TO_SIGN=so,t.deriveStealthAddress=lo,t.generatePassword=ao,t.generateRandomId=io,t.getSigner=co,t.gunToEthAccount=oo,Object.defineProperty(t,"__esModule",{value:!0})}));
|
2
|
+
//# sourceMappingURL=gun-eth.bundle.min.js.map
|