@supanovaapp/sdk 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +1307 -0
- package/dist/index.esm.js +2 -2
- package/package.json +5 -4
package/dist/index.cjs.js
CHANGED
|
@@ -416,7 +416,7 @@ Resources:
|
|
|
416
416
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[wJ]=this[wJ]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=bv(o);r[a]||(Wdt(i,o),r[a]=!0)}return Se.isArray(e)?e.forEach(s):s(e),this}};Ta.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Se.reduceDescriptors(Ta.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});Se.freezeMethods(Ta);function aT(t,e){const n=this||x8,r=e||n,i=Ta.from(r.headers);let s=r.data;return Se.forEach(t,function(a){s=a.call(n,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function Sge(t){return!!(t&&t.__CANCEL__)}function Tb(t,e,n){on.call(this,t??"canceled",on.ERR_CANCELED,e,n),this.name="CanceledError"}Se.inherits(Tb,on,{__CANCEL__:!0});function $ge(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new on("Request failed with status code "+n.status,[on.ERR_BAD_REQUEST,on.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Hdt(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Vdt(t,e){t=t||10;const n=new Array(t),r=new Array(t);let i=0,s=0,o;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),d=r[s];o||(o=l),n[i]=c,r[i]=l;let u=s,h=0;for(;u!==i;)h+=n[u++],u=u%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),l-o<e)return;const p=d&&l-d;return p?Math.round(h*1e3/p):void 0}}function qdt(t,e){let n=0,r=1e3/e,i,s;const o=(l,d=Date.now())=>{n=d,i=null,s&&(clearTimeout(s),s=null),t(...l)};return[(...l)=>{const d=Date.now(),u=d-n;u>=r?o(l,d):(i=l,s||(s=setTimeout(()=>{s=null,o(i)},r-u)))},()=>i&&o(i)]}const e7=(t,e,n=3)=>{let r=0;const i=Vdt(50,250);return qdt(s=>{const o=s.loaded,a=s.lengthComputable?s.total:void 0,c=o-r,l=i(c),d=o<=a;r=o;const u={loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&d?(a-o)/l:void 0,event:s,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(u)},n)},bJ=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},vJ=t=>(...e)=>Se.asap(()=>t(...e)),Zdt=go.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,go.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(go.origin),go.navigator&&/(msie|trident)/i.test(go.navigator.userAgent)):()=>!0,Kdt=go.hasStandardBrowserEnv?{write(t,e,n,r,i,s,o){if(typeof document>"u")return;const a=[`${t}=${encodeURIComponent(e)}`];Se.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),Se.isString(r)&&a.push(`path=${r}`),Se.isString(i)&&a.push(`domain=${i}`),s===!0&&a.push("secure"),Se.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Gdt(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Ydt(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function kge(t,e,n){let r=!Gdt(e);return t&&(r||n==!1)?Ydt(t,e):e}const xJ=t=>t instanceof Ta?{...t}:t;function lm(t,e){e=e||{};const n={};function r(l,d,u,h){return Se.isPlainObject(l)&&Se.isPlainObject(d)?Se.merge.call({caseless:h},l,d):Se.isPlainObject(d)?Se.merge({},d):Se.isArray(d)?d.slice():d}function i(l,d,u,h){if(Se.isUndefined(d)){if(!Se.isUndefined(l))return r(void 0,l,u,h)}else return r(l,d,u,h)}function s(l,d){if(!Se.isUndefined(d))return r(void 0,d)}function o(l,d){if(Se.isUndefined(d)){if(!Se.isUndefined(l))return r(void 0,l)}else return r(void 0,d)}function a(l,d,u){if(u in e)return r(l,d);if(u in t)return r(void 0,l)}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(l,d,u)=>i(xJ(l),xJ(d),u,!0)};return Se.forEach(Object.keys({...t,...e}),function(d){const u=c[d]||i,h=u(t[d],e[d],d);Se.isUndefined(h)&&u!==a||(n[d]=h)}),n}const Ige=t=>{const e=lm({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=e;if(e.headers=o=Ta.from(o),e.url=Cge(kge(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),Se.isFormData(n)){if(go.hasStandardBrowserEnv||go.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(Se.isFunction(n.getHeaders)){const c=n.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([d,u])=>{l.includes(d.toLowerCase())&&o.set(d,u)})}}if(go.hasStandardBrowserEnv&&(r&&Se.isFunction(r)&&(r=r(e)),r||r!==!1&&Zdt(e.url))){const c=i&&s&&Kdt.read(s);c&&o.set(i,c)}return e},Jdt=typeof XMLHttpRequest<"u",Xdt=Jdt&&function(t){return new Promise(function(n,r){const i=Ige(t);let s=i.data;const o=Ta.from(i.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,d,u,h,p,g;function m(){p&&p(),g&&g(),i.cancelToken&&i.cancelToken.unsubscribe(d),i.signal&&i.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(i.method.toUpperCase(),i.url,!0),y.timeout=i.timeout;function b(){if(!y)return;const v=Ta.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:v,config:t,request:y};$ge(function(_){n(_),m()},function(_){r(_),m()},C),y=null}"onloadend"in y?y.onloadend=b:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(b)},y.onabort=function(){y&&(r(new on("Request aborted",on.ECONNABORTED,t,y)),y=null)},y.onerror=function(E){const C=E&&E.message?E.message:"Network Error",w=new on(C,on.ERR_NETWORK,t,y);w.event=E||null,r(w),y=null},y.ontimeout=function(){let E=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const C=i.transitional||Age;i.timeoutErrorMessage&&(E=i.timeoutErrorMessage),r(new on(E,C.clarifyTimeoutError?on.ETIMEDOUT:on.ECONNABORTED,t,y)),y=null},s===void 0&&o.setContentType(null),"setRequestHeader"in y&&Se.forEach(o.toJSON(),function(E,C){y.setRequestHeader(C,E)}),Se.isUndefined(i.withCredentials)||(y.withCredentials=!!i.withCredentials),a&&a!=="json"&&(y.responseType=i.responseType),l&&([h,g]=e7(l,!0),y.addEventListener("progress",h)),c&&y.upload&&([u,p]=e7(c),y.upload.addEventListener("progress",u),y.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(d=v=>{y&&(r(!v||v.type?new Tb(null,t,y):v),y.abort(),y=null)},i.cancelToken&&i.cancelToken.subscribe(d),i.signal&&(i.signal.aborted?d():i.signal.addEventListener("abort",d)));const x=Hdt(i.url);if(x&&go.protocols.indexOf(x)===-1){r(new on("Unsupported protocol "+x+":",on.ERR_BAD_REQUEST,t));return}y.send(s||null)})},Qdt=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,i;const s=function(l){if(!i){i=!0,a();const d=l instanceof Error?l:this.reason;r.abort(d instanceof on?d:new Tb(d instanceof Error?d.message:d))}};let o=e&&setTimeout(()=>{o=null,s(new on(`timeout ${e} of ms exceeded`,on.ETIMEDOUT))},e);const a=()=>{t&&(o&&clearTimeout(o),o=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),t=null)};t.forEach(l=>l.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>Se.asap(a),c}},eut=function*(t,e){let n=t.byteLength;if(n<e){yield t;return}let r=0,i;for(;r<n;)i=r+e,yield t.slice(r,i),r=i},tut=async function*(t,e){for await(const n of nut(t))yield*eut(n,e)},nut=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{await e.cancel()}},EJ=(t,e,n,r)=>{const i=tut(t,e);let s=0,o,a=c=>{o||(o=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:l,value:d}=await i.next();if(l){a(),c.close();return}let u=d.byteLength;if(n){let h=s+=u;n(h)}c.enqueue(new Uint8Array(d))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})},CJ=64*1024,{isFunction:Gx}=Se,rut=(({Request:t,Response:e})=>({Request:t,Response:e}))(Se.global),{ReadableStream:AJ,TextEncoder:_J}=Se.global,SJ=(t,...e)=>{try{return!!t(...e)}catch{return!1}},iut=t=>{t=Se.merge.call({skipUndefined:!0},rut,t);const{fetch:e,Request:n,Response:r}=t,i=e?Gx(e):typeof fetch=="function",s=Gx(n),o=Gx(r);if(!i)return!1;const a=i&&Gx(AJ),c=i&&(typeof _J=="function"?(g=>m=>g.encode(m))(new _J):async g=>new Uint8Array(await new n(g).arrayBuffer())),l=s&&a&&SJ(()=>{let g=!1;const m=new n(go.origin,{body:new AJ,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!m}),d=o&&a&&SJ(()=>Se.isReadableStream(new r("").body)),u={stream:d&&(g=>g.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!u[g]&&(u[g]=(m,y)=>{let b=m&&m[g];if(b)return b.call(m);throw new on(`Response type '${g}' is not supported`,on.ERR_NOT_SUPPORT,y)})});const h=async g=>{if(g==null)return 0;if(Se.isBlob(g))return g.size;if(Se.isSpecCompliantForm(g))return(await new n(go.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(Se.isArrayBufferView(g)||Se.isArrayBuffer(g))return g.byteLength;if(Se.isURLSearchParams(g)&&(g=g+""),Se.isString(g))return(await c(g)).byteLength},p=async(g,m)=>{const y=Se.toFiniteNumber(g.getContentLength());return y??h(m)};return async g=>{let{url:m,method:y,data:b,signal:x,cancelToken:v,timeout:E,onDownloadProgress:C,onUploadProgress:w,responseType:_,headers:T,withCredentials:P="same-origin",fetchOptions:I}=Ige(g),M=e||fetch;_=_?(_+"").toLowerCase():"text";let R=Qdt([x,v&&v.toAbortSignal()],E),O=null;const S=R&&R.unsubscribe&&(()=>{R.unsubscribe()});let A;try{if(w&&l&&y!=="get"&&y!=="head"&&(A=await p(T,b))!==0){let F=new n(m,{method:"POST",body:b,duplex:"half"}),z;if(Se.isFormData(b)&&(z=F.headers.get("content-type"))&&T.setContentType(z),F.body){const[Z,V]=bJ(A,e7(vJ(w)));b=EJ(F.body,CJ,Z,V)}}Se.isString(P)||(P=P?"include":"omit");const k=s&&"credentials"in n.prototype,L={...I,signal:R,method:y.toUpperCase(),headers:T.normalize().toJSON(),body:b,duplex:"half",credentials:k?P:void 0};O=s&&new n(m,L);let D=await(s?M(O,I):M(m,L));const N=d&&(_==="stream"||_==="response");if(d&&(C||N&&S)){const F={};["status","statusText","headers"].forEach(q=>{F[q]=D[q]});const z=Se.toFiniteNumber(D.headers.get("content-length")),[Z,V]=C&&bJ(z,e7(vJ(C),!0))||[];D=new r(EJ(D.body,CJ,Z,()=>{V&&V(),S&&S()}),F)}_=_||"text";let j=await u[Se.findKey(u,_)||"text"](D,g);return!N&&S&&S(),await new Promise((F,z)=>{$ge(F,z,{data:j,headers:Ta.from(D.headers),status:D.status,statusText:D.statusText,config:g,request:O})})}catch(k){throw S&&S(),k&&k.name==="TypeError"&&/Load failed|fetch/i.test(k.message)?Object.assign(new on("Network Error",on.ERR_NETWORK,g,O),{cause:k.cause||k}):on.from(k,k&&k.code,g,O)}}},sut=new Map,Tge=t=>{let e=t&&t.env||{};const{fetch:n,Request:r,Response:i}=e,s=[r,i,n];let o=s.length,a=o,c,l,d=sut;for(;a--;)c=s[a],l=d.get(c),l===void 0&&d.set(c,l=a?new Map:iut(e)),d=l;return l};Tge();const hF={http:Edt,xhr:Xdt,fetch:{get:Tge}};Se.forEach(hF,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const $J=t=>`- ${t}`,out=t=>Se.isFunction(t)||t===null||t===!1;function aut(t,e){t=Se.isArray(t)?t:[t];const{length:n}=t;let r,i;const s={};for(let o=0;o<n;o++){r=t[o];let a;if(i=r,!out(r)&&(i=hF[(a=String(r)).toLowerCase()],i===void 0))throw new on(`Unknown adapter '${a}'`);if(i&&(Se.isFunction(i)||(i=i.get(e))))break;s[a||"#"+o]=i}if(!i){const o=Object.entries(s).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=n?o.length>1?`since :
|
|
417
417
|
`+o.map($J).join(`
|
|
418
418
|
`):" "+$J(o[0]):"as no adapter specified";throw new on("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const Pge={getAdapter:aut,adapters:hF};function cT(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Tb(null,t)}function kJ(t){return cT(t),t.headers=Ta.from(t.headers),t.data=aT.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Pge.getAdapter(t.adapter||x8.adapter,t)(t).then(function(r){return cT(t),r.data=aT.call(t,t.transformResponse,r),r.headers=Ta.from(r.headers),r},function(r){return Sge(r)||(cT(t),r&&r.response&&(r.response.data=aT.call(t,t.transformResponse,r.response),r.response.headers=Ta.from(r.response.headers))),Promise.reject(r)})}const Oge="1.13.2",cS={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{cS[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const IJ={};cS.transitional=function(e,n,r){function i(s,o){return"[Axios v"+Oge+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,a)=>{if(e===!1)throw new on(i(o," has been removed"+(n?" in "+n:"")),on.ERR_DEPRECATED);return n&&!IJ[o]&&(IJ[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,o,a):!0}};cS.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function cut(t,e,n){if(typeof t!="object")throw new on("options must be an object",on.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let i=r.length;for(;i-- >0;){const s=r[i],o=e[s];if(o){const a=t[s],c=a===void 0||o(a,s,t);if(c!==!0)throw new on("option "+s+" must be "+c,on.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new on("Unknown option "+s,on.ERR_BAD_OPTION)}}const iC={assertOptions:cut,validators:cS},Td=iC.validators;let Ig=class{constructor(e){this.defaults=e||{},this.interceptors={request:new yJ,response:new yJ}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
419
|
-
`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=lm(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&iC.assertOptions(r,{silentJSONParsing:Td.transitional(Td.boolean),forcedJSONParsing:Td.transitional(Td.boolean),clarifyTimeoutError:Td.transitional(Td.boolean)},!1),i!=null&&(Se.isFunction(i)?n.paramsSerializer={serialize:i}:iC.assertOptions(i,{encode:Td.function,serialize:Td.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),iC.assertOptions(n,{baseUrl:Td.spelling("baseURL"),withXsrfToken:Td.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&Se.merge(s.common,s[n.method]);s&&Se.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ta.concat(o,s);const a=[];let c=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(c=c&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const l=[];this.interceptors.response.forEach(function(m){l.push(m.fulfilled,m.rejected)});let d,u=0,h;if(!c){const g=[kJ.bind(this),void 0];for(g.unshift(...a),g.push(...l),h=g.length,d=Promise.resolve(n);u<h;)d=d.then(g[u++],g[u++]);return d}h=a.length;let p=n;for(;u<h;){const g=a[u++],m=a[u++];try{p=g(p)}catch(y){m.call(this,y);break}}try{d=kJ.call(this,p)}catch(g){return Promise.reject(g)}for(u=0,h=l.length;u<h;)d=d.then(l[u++],l[u++]);return d}getUri(e){e=lm(this.defaults,e);const n=kge(e.baseURL,e.url,e.allowAbsoluteUrls);return Cge(n,e.params,e.paramsSerializer)}};Se.forEach(["delete","get","head","options"],function(e){Ig.prototype[e]=function(n,r){return this.request(lm(r||{},{method:e,url:n,data:(r||{}).data}))}});Se.forEach(["post","put","patch"],function(e){function n(r){return function(s,o,a){return this.request(lm(a||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Ig.prototype[e]=n(),Ig.prototype[e+"Form"]=n(!0)});let lut=class Nge{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{r.subscribe(a),s=a}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},e(function(s,o,a){r.reason||(r.reason=new Tb(s,o,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Nge(function(i){e=i}),cancel:e}}};function dut(t){return function(n){return t.apply(null,n)}}function uut(t){return Se.isObject(t)&&t.isAxiosError===!0}const EM={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(EM).forEach(([t,e])=>{EM[e]=t});function Rge(t){const e=new Ig(t),n=uge(Ig.prototype.request,e);return Se.extend(n,Ig.prototype,e,{allOwnKeys:!0}),Se.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return Rge(lm(t,i))},n}const bi=Rge(x8);bi.Axios=Ig;bi.CanceledError=Tb;bi.CancelToken=lut;bi.isCancel=Sge;bi.VERSION=Oge;bi.toFormData=aS;bi.AxiosError=on;bi.Cancel=bi.CanceledError;bi.all=function(e){return Promise.all(e)};bi.spread=dut;bi.isAxiosError=uut;bi.mergeConfig=lm;bi.AxiosHeaders=Ta;bi.formToJSON=t=>_ge(Se.isHTMLForm(t)?new FormData(t):t);bi.getAdapter=Pge.getAdapter;bi.HttpStatusCode=EM;bi.default=bi;const{Axios:aWt,AxiosError:cWt,CanceledError:lWt,isCancel:dWt,CancelToken:uWt,VERSION:hWt,all:pWt,Cancel:fWt,isAxiosError:gWt,spread:mWt,toFormData:yWt,AxiosHeaders:wWt,HttpStatusCode:bWt,formToJSON:vWt,getAdapter:xWt,mergeConfig:EWt}=bi;class Mge{client;getAccessToken;nodeIdentifier;constructor(e={}){const n=e.baseURL||"https://stage_api.walletino.fyi";this.nodeIdentifier=e.nodeIdentifier||"devnet-0",this.client=bi.create({baseURL:n,headers:{"Content-Type":"application/json"}}),this.getAccessToken=e.getAccessToken,this.client.interceptors.request.use(async r=>{if(this.getAccessToken)try{const i=await this.getAccessToken();i&&(r.headers.Authorization=`Bearer ${i}`)}catch(i){console.error("[Supa SDK] ❌ Failed to get access token:",i)}return r.url?.startsWith("/canton/")&&(r.headers["X-Canton-Node-Id"]=this.nodeIdentifier),console.group(`[Supa SDK] 📤 REQUEST: ${r.method?.toUpperCase()} ${r.url}`),console.log("Headers:",{"Content-Type":r.headers["Content-Type"],Authorization:r.headers.Authorization?`Bearer ***${String(r.headers.Authorization).slice(-20)}`:"none","X-Canton-Node-Id":r.headers["X-Canton-Node-Id"]||"none"}),r.data&&console.log("Request Body:",r.data),console.groupEnd(),r},r=>Promise.reject(r)),this.client.interceptors.response.use(r=>(console.group(`[Supa SDK] 📥 RESPONSE: ${r.status} ${r.config.method?.toUpperCase()} ${r.config.url}`),console.log("Status:",r.status,r.statusText),console.log("Response Data:",r.data),console.groupEnd(),r),r=>{if(r.response){console.group(`[Supa SDK] ❌ ERROR RESPONSE: ${r.response.status} ${r.config?.method?.toUpperCase()} ${r.config?.url}`),console.error("Status:",r.response.status,r.response.statusText),console.error("Request Body:",r.config?.data),console.error("Response Data:",r.response.data),console.groupEnd();const i={statusCode:r.response.status,message:r.response.data?.message||r.message,error:r.response.data?.error};return Promise.reject(i)}return console.error("[Supa SDK] ❌ Network error:",r.message),Promise.reject({statusCode:0,message:r.message||"Network error"})})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}setAccessTokenGetter(e){this.getAccessToken=e}getBaseURL(){return this.client.defaults.baseURL||""}}let t7=null;function jge(t){return t7=new Mge(t),t7}function hut(){if(!t7)throw new Error("ApiClient not initialized. Call createApiClient first.");return t7}const Rw=t=>{const e=t.startsWith("0x")?t.slice(2):t,n=new Uint8Array(e.match(/.{1,2}/g)?.map(r=>parseInt(r,16))||[]);return Dge(n)},Mw=t=>{const e=Lge(t);return"0x"+Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("")},Dge=t=>btoa(String.fromCharCode(...t)),Lge=t=>{const e=atob(t.replace(/\s/g,"")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n},put=t=>{let e=t.startsWith("0x")?t.slice(2):t;return e.startsWith("00")&&(e=e.slice(2)),"0x"+e},Bge=t=>{let e=t.startsWith("0x")?t.slice(2):t;e.startsWith("00")&&(e=e.slice(2));try{const n=new Uint8Array(e.match(/.{1,2}/g).map(r=>parseInt(r,16)));return btoa(String.fromCharCode(...n))}catch{throw new Error("Failed to convert public key to base64")}};class Uge{constructor(e){this.client=e}async registerCanton(e,n=0){if(n>4)throw new Error;const{publicKey:r,signFunction:i}=e;let s;try{s=await this.client.post("/canton/register/prepare",{publicKey:r})}catch(d){return await new Promise(u=>setTimeout(u,1500)),typeof d=="object"&&d!==null&&"message"in d&&d.message==="Canton wallet already exists for the user."?void 0:this.registerCanton(e,n+1)}const o=s.hash,a=Mw(o),c=await i(a),l=Rw(c);await this.client.post("/canton/register/submit",{hash:o,signature:l})}async tapDevnet(e,n){const{amount:r,signFunction:i}=e,o=(await this.client.post("/canton/devnet/tap",{amount:r})).hash,a=Mw(o),c=await i(a),l=Rw(c);return await this.submitPreparedAndWait(o,l,n)}async submitPrepared(e,n){return await this.client.post("/canton/api/submit_prepared",{hash:e,signature:n})}async queryCompletion(e){return await this.client.get(`/canton/api/query_completion?submissionId=${encodeURIComponent(e)}`)}async submitPreparedAndWait(e,n,r={}){const{timeout:i=3e4,pollInterval:s=1e3}=r,o=await this.submitPrepared(e,n),{submissionId:a}=o,c=Date.now();for(;Date.now()-c<i;){const l=await this.queryCompletion(a);if(l.status==="completed")return l;await new Promise(d=>setTimeout(d,s))}throw new Error(`Transaction completion timeout after ${i}ms for submissionId: ${a}`)}async getMe(){return await this.client.get("/canton/api/me")}async getActiveContracts(e){const n=new URLSearchParams;e&&e.forEach(s=>n.append("templateIds",s));const r=n.toString(),i=r?`/canton/api/active_contracts?${r}`:"/canton/api/active_contracts";return await this.client.get(i)}async signMessage(e,n){const i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",i),a="0x"+Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join("");return await n(a)}async prepareTransaction(e,n){return await this.client.post("/canton/api/prepare_transaction",{commandId:e,disclosedContracts:n})}async checkRegistrationStatus(){try{return await this.getMe(),!0}catch{return!1}}}class Fge{constructor(e){this.client=e}async getCurrentUser(){return await this.client.get("/user/me")}async getAllUsers(){return await this.client.get("/user/all")}async getUserByPrivyId(e){return await this.client.get(`/user/${e}`)}async getSmartWalletBalances(e=!1){return await this.client.get("/user/smart_wallet_balances",{params:{force:e}})}async createDialog(e){return await this.client.post("/dialogs",{text:e})}async getAllDialogs(e){return await this.client.get("/dialogs",{params:e})}async getDialog(e){return await this.client.get(`/dialogs/${e}`)}async deleteDialog(e){return await this.client.delete(`/dialogs/${e}`)}async createMessage(e,n){return await this.client.post(`/dialogs/${e}/messages`,{text:n})}async getDialogMessages(e,n){return await this.client.get(`/dialogs/${e}/messages`,{params:n})}async getMessage(e){return await this.client.get(`/messages/${e}`)}async getTokenPricesByAddresses(e){return await this.client.post("/onchain/tokens_prices_by_addresses",{addresses:e})}async getTokenPrices(e){return await this.client.get("/onchain/tokens_prices",{params:{symbols:e.join(",")}})}async getTokenPriceHistory(e){return await this.client.get("/onchain/token_price_history",{params:e})}async getTokens24hrPriceChanges(e){return await this.client.post("/onchain/tokens_24hr_changes",{tokens:e})}async getTokenInfo(e,n){const r=Array.isArray(n)?n.join(","):n;return await this.client.get(`/onchain/token_info/${e}`,{params:{token:r}})}async getAccountTokenBalances(e,n,r=!1){return await this.client.get(`/onchain/account_tokens_balances/${e}`,{params:{account:n,force:r}})}async getTransactions(e){return await this.client.get("/transactions",{params:e})}async forceLoadTransactions(e){return await this.client.post("/transactions/transactions_force",null,{params:e})}async getSupaPointsBalance(){return await this.client.get("/supa_points/balance")}async getSupaPointsHistory(e){return await this.client.get("/supa_points/history",{params:e})}async dailyLogin(){return await this.client.post("/supa_points/daily_login")}async checkPaymasterSponsorship(e){return await this.client.post("/paymaster",e)}async getPrivyBalance(){return await this.client.get("/privy/balance")}}const Is={backdrop:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(4px)"},panelWrapper:{position:"fixed",inset:0,zIndex:9999,overflowY:"auto",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"},panel:{backgroundColor:"var(--privy-color-background-2)",border:"1px solid var(--privy-color-border-default)",borderRadius:"var(--privy-border-radius-mdlg)",maxWidth:"560px",width:"100%",maxHeight:"85vh",overflow:"hidden",display:"flex",flexDirection:"column",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)"},header:{padding:"20px 24px",borderBottom:"1px solid var(--privy-color-border-default)",display:"flex",alignItems:"center",justifyContent:"space-between"},title:{fontSize:"18px",fontWeight:600,color:"var(--privy-color-foreground)",margin:0,display:"flex",alignItems:"center",gap:"12px",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'},closeButton:{background:"transparent",border:"none",padding:"8px",cursor:"pointer",color:"var(--privy-color-icon-muted)",borderRadius:"var(--privy-border-radius-sm)",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 150ms"},body:{padding:"24px",overflowY:"auto",flex:1,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'},messageContainer:{backgroundColor:"var(--privy-color-background)",border:"1px solid var(--privy-color-border-default)",borderRadius:"var(--privy-border-radius-md)",padding:"16px",maxHeight:"400px",overflowY:"auto",marginBottom:"16px"},messageContent:{fontFamily:'"SF Mono", "Fira Code", "JetBrains Mono", monospace',fontSize:"14px",lineHeight:1.6,color:"var(--privy-color-foreground)",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},footer:{padding:"16px 24px",borderTop:"1px solid var(--privy-color-border-default)",display:"flex",gap:"12px",justifyContent:"flex-end",backgroundColor:"var(--privy-color-background)"},button:{padding:"12px 20px",borderRadius:"var(--privy-border-radius-md)",fontSize:"14px",fontWeight:600,cursor:"pointer",transition:"all 150ms",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',border:"none"},rejectButton:{backgroundColor:"transparent",border:"1px solid var(--privy-color-border-default)",color:"var(--privy-color-foreground-2)"},confirmButton:{backgroundColor:"var(--privy-color-accent)",color:"var(--privy-color-background)"},description:{fontSize:"14px",color:"var(--privy-color-foreground-2)",marginBottom:"16px",lineHeight:1.5},infoBox:{backgroundColor:"var(--privy-color-info-bg)",border:"1px solid var(--privy-color-border-info)",borderRadius:"var(--privy-border-radius-md)",padding:"12px 16px",display:"flex",gap:"12px",alignItems:"flex-start",marginTop:"16px"},infoText:{fontSize:"13px",color:"var(--privy-color-foreground-2)",lineHeight:1.5,margin:0}},fut=()=>f.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),f.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),gut=()=>f.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),f.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),f.jsx("path",{d:"M2 2l7.586 7.586"}),f.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),mut=()=>f.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),f.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),yut=()=>f.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-icon-interactive)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),f.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]});function lS({open:t,onClose:e,onConfirm:n,onReject:r,title:i="Confirm Action",message:s,confirmText:o="Confirm",rejectText:a="Cancel",description:c,infoText:l,icon:d,loading:u=!1}){const{theme:h}=lf(),p=()=>{r(),e()},g=()=>{n()},m=h==="dark"?"privy-dark":"privy-light";return f.jsx(nU,{show:t,as:$.Fragment,children:f.jsxs(Ohe,{onClose:e,style:{position:"relative",zIndex:9999},children:[f.jsx(sm,{as:$.Fragment,enter:"ease-out duration-200",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-150",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:f.jsx("div",{style:Is.backdrop})}),f.jsx("div",{style:Is.panelWrapper,children:f.jsx(sm,{as:$.Fragment,enter:"ease-out duration-200",enterFrom:"opacity-0 scale-95",enterTo:"opacity-100 scale-100",leave:"ease-in duration-150",leaveFrom:"opacity-100 scale-100",leaveTo:"opacity-0 scale-95",children:f.jsxs(iU,{className:m,style:Is.panel,children:[f.jsxs("div",{style:Is.header,children:[f.jsxs(Phe,{style:Is.title,children:[d||f.jsx(gut,{}),i]}),f.jsx("button",{onClick:p,style:Is.closeButton,onMouseEnter:y=>{y.currentTarget.style.backgroundColor="var(--privy-color-background-hover)",y.currentTarget.style.color="var(--privy-color-icon-default-hover)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color="var(--privy-color-icon-muted)"},children:f.jsx(fut,{})})]}),f.jsxs("div",{style:Is.body,children:[c&&f.jsx("p",{style:Is.description,children:c}),f.jsx("div",{style:Is.messageContainer,children:f.jsx("pre",{style:Is.messageContent,children:s})}),l&&f.jsxs("div",{style:Is.infoBox,children:[f.jsx(yut,{}),f.jsx("p",{style:Is.infoText,children:l})]})]}),f.jsxs("div",{style:Is.footer,children:[f.jsx("button",{onClick:p,disabled:u,style:{...Is.button,...Is.rejectButton,opacity:u?.5:1},onMouseEnter:y=>{u||(y.currentTarget.style.backgroundColor="var(--privy-color-background-hover)",y.currentTarget.style.color="var(--privy-color-foreground-hover)")},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color="var(--privy-color-foreground-2)"},children:a}),f.jsx("button",{onClick:g,disabled:u,style:{...Is.button,...Is.confirmButton,opacity:u?.7:1},onMouseEnter:y=>{u||(y.currentTarget.style.backgroundColor="var(--privy-color-accent-hover)")},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="var(--privy-color-accent)"},children:u?"Processing...":o})]})]})})})]})})}function zge({open:t,onClose:e,onConfirm:n,onReject:r,message:i,loading:s=!1,title:o="Sign Message",description:a="You are about to sign the following message:",confirmText:c="Sign",rejectText:l="Reject"}){return f.jsx(lS,{open:t,onClose:e,onConfirm:n,onReject:r,title:o,message:i,confirmText:c,rejectText:l,description:a,infoText:"Signing a message proves ownership of your wallet without exposing private keys or making any blockchain transactions.",loading:s})}function Wge({open:t,onClose:e,onConfirm:n,onReject:r,transaction:i,loading:s=!1,title:o="Sign Transaction",description:a="Review and sign the following transaction:",confirmText:c="Sign & Send",rejectText:l="Reject",infoText:d="You are submitting a transaction, please be careful"}){return f.jsx(lS,{open:t,onClose:e,onConfirm:n,onReject:r,title:o,message:i,confirmText:c,rejectText:l,description:a,infoText:d,icon:f.jsx(mut,{}),loading:s})}typeof window<"u"&&!window.Buffer&&(window.Buffer=jlt.Buffer,console.log("[Supa SDK] ✅ Buffer polyfill initialized"));const Hge=$.createContext(null);function wut({config:t,children:e}){const[n,r]=$.useState(null),[i,s]=$.useState({type:null,options:null,resolve:null,loading:!1});$.useEffect(()=>{const w=jge({baseURL:t.apiBaseUrl,nodeIdentifier:t.nodeIdentifier}),_=new Uge(w),T=new Fge(w);r({apiClient:w,cantonService:_,apiService:T})},[t]);const o=$.useCallback(w=>_=>new Promise(T=>s({type:w,options:_,resolve:T,loading:!1})),[]),a=$.useCallback(o("confirm"),[o]),c=$.useCallback(o("signMessage"),[o]),l=$.useCallback(o("signTransaction"),[o]),d=$.useCallback(w=>{s(_=>({..._,loading:w}))},[]),u=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!1}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]),h=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!0}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]),p=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!1}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]);if(!n)return null;const g=t.appearance?.theme||"light",m=g==="dark"?"privy-dark":"privy-light",y={embeddedWallets:{showWalletUIs:!0},appearance:{theme:g,accentColor:t.appearance?.accentColor?`#${t.appearance.accentColor.replace("#","")}`:void 0,logo:t.appearance?.logo},loginMethods:t.loginMethods||["email","wallet"]},b={...n,config:t,theme:g,confirm:a,signMessageConfirm:c,signTransactionConfirm:l,setModalLoading:d,closeModal:u},x=i.type!==null,v=i.type==="confirm",E=i.type==="signMessage",C=i.type==="signTransaction";return f.jsx(Olt,{appId:t.privyAppId,clientId:t.privyClientId,config:y,children:f.jsx(Hge.Provider,{value:b,children:f.jsxs("div",{className:m,children:[e,v&&i.options&&f.jsx(lS,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options}),E&&i.options&&f.jsx(zge,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options}),C&&i.options&&f.jsx(Wge,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options})]})})})}function lf(){const t=$.useContext(Hge);if(!t)throw new Error("useSupaContext must be used within SupaProvider");return t}const dS=()=>{const{apiClient:t}=lf(),{login:e}=OOe(),{logout:n}=cde(),{authenticated:r,ready:i,user:s,getAccessToken:o}=Aw();return $.useEffect(()=>{r&&t.setAccessTokenGetter(o)},[r,t,o]),{login:()=>{e()},logout:async()=>{await n()},authenticated:r,loading:!i,user:s,getAccessToken:o,ready:i}},but=()=>{let{refreshSessionAndUser:t,privy:e}=Je();return $.useMemo((()=>({async createWallet(n){let r=await CC(e,{request:{chain_type:n.chainType}}),i=await t();if(!i)throw Error("User must be authenticated before creating a Privy wallet");return{user:i,wallet:r}}})),[t,e])},vut=()=>{let{user:t}=ln(),{privy:e}=Je(),{signWithUserSigner:n}=QU();return $.useMemo((()=>({async signRawHash({address:r,chainType:i,hash:s}){if(!t)throw Error("User must be authenticated before signing");let o=aB(t,i).filter((c=>js(c))).find((c=>c.address===r));if(!o)throw Error("Wallet not found");let a=await pIe(e,n,{wallet_id:o.id,params:{hash:s}});if(a.data&&"signature"in a.data&&a.data.encoding==="hex")return{signature:a.data.signature};throw Error("Failed to sign")}})),[e,n,t])};function uS(){const{signTransactionConfirm:t,setModalLoading:e}=lf(),{signRawHash:n}=vut();return{signRawHashWithModal:$.useCallback(async(i,s)=>{const{skipModal:o=!1,title:a="Sign Hash",description:c="You are about to sign the following hash:",confirmText:l="Sign",rejectText:d="Reject",infoText:u,displayHash:h,showTechnicalDetails:p=!1}=s||{};if(o)return await n(i);const g=h||(p?JSON.stringify({address:i.address,chainType:i.chainType,hash:i.hash},null,2):i.hash);if(!(await t({transaction:g,title:a,description:c,confirmText:l,rejectText:d,infoText:u})).confirmed)return null;e(!0);try{return await n(i)}finally{e(!1)}},[n,t,e])}}const hS=(t,e)=>{const n=[];if(t?.linkedAccounts){const s=t.linkedAccounts.filter(o=>o.type==="wallet"&&o.chainType==="stellar");n.push(...s)}const r=e.filter(s=>s.chainType==="stellar");return n.push(...r),Array.from(new Map(n.map(s=>[s.address,s])).values())},Vge=t=>{if(!t)throw new Error("Wallet is required");let e=t.publicKey;if(!e&&t.linkedAccount&&(e=t.linkedAccount.publicKey),!e)throw new Error("Public key not found in wallet. Make sure you have a Stellar wallet created in Privy.");if(typeof e!="string")throw new Error(`Invalid publicKey type: ${typeof e}`);if(!/^(0x)?[0-9a-fA-F]+$/.test(e))throw new Error(`publicKey is not in hex format: ${e.substring(0,20)}...`);return Bge(e)},xut=t=>t&&t.chainType==="stellar",Eut=(t,e)=>{const n=hS(t,e);if(n.length===0)throw new Error("No Stellar wallet found. Please create one first.");return n[0]};function pS(){const{user:t,authenticated:e}=dS(),{wallets:n}=Sh(),r=e?hS(t,n):[],i=r[0]||null;return{stellarWallets:r,stellarWallet:i}}function qge(){const{cantonService:t}=lf(),{user:e,authenticated:n}=dS(),{wallets:r}=Sh(),{signRawHashWithModal:i}=uS(),{createWallet:s}=but(),{stellarWallet:o,stellarWallets:a}=pS(),[c,l]=$.useState(!1),[d,u]=$.useState(null),[h,p]=$.useState(!1),[g,m]=$.useState(null);$.useEffect(()=>{n&&o&&y()},[n,o]);const y=async()=>{try{const I=await t.checkRegistrationStatus();p(I)}catch{p(!1)}},b=$.useCallback(async()=>{if(!n)throw new Error("User must be authenticated to create wallet");l(!0),u(null);try{const I=await s({chainType:"stellar"});return I||null}catch(I){const M=new Error(`Failed to create Stellar wallet: ${I.message}`);throw u(M),M}finally{l(!1)}},[n,s]),x=$.useCallback(async I=>{if(!o)throw new Error("No Stellar wallet found");try{const M=Mw(I),R=await i({address:o.address,chainType:"stellar",hash:M},{title:"Sign Hash",description:"You are about to sign the following hash.",confirmText:"Sign",rejectText:"Reject",displayHash:`Hash: ${I}`});if(!R)throw new Error("User rejected signature");return Rw(R.signature)}catch(M){throw new Error(`Failed to sign hash: ${M.message}`)}},[o,i]),v=$.useCallback(async()=>{l(!0),u(null);try{let I=o;if(!I){const O=await b();if(O?I=O:(await new Promise(A=>setTimeout(A,1500)),I=hS(e,r)[0]||null),!I)throw new Error("Failed to create Stellar wallet. Please try again.")}const M=Vge(I),R=async O=>{const S=await i({address:I.address,chainType:"stellar",hash:O},{skipModal:!0});if(!S)throw new Error("User rejected signature");return S.signature};await t.registerCanton({publicKey:M,signFunction:R}),p(!0)}catch(I){const M=new Error(`Failed to register Canton wallet: ${I.message}`);throw u(M),M}finally{l(!1)}},[o,b,e,r,i,t]),E=$.useCallback(async(I,M)=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const R=async O=>{const S=await i({address:o.address,chainType:"stellar",hash:O},{title:"Tap Devnet Faucet",description:`You are requesting ${I} tokens from the devnet faucet.`,confirmText:"Confirm & Sign",rejectText:"Cancel",displayHash:`Request ${I} Canton tokens from devnet faucet`});if(!S)throw new Error("User rejected signature");return S.signature};return await t.tapDevnet({amount:I,signFunction:R},M)}catch(R){const O=new Error(`Failed to tap devnet: ${R.message}`);throw u(O),O}finally{l(!1)}},[o,i,t]),C=$.useCallback(()=>{u(null)},[]),w=$.useCallback(async()=>{const I=await t.getMe();return m(I),I},[t]),_=$.useCallback(async I=>await t.getActiveContracts(I),[t]),T=$.useCallback(async I=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const M=async R=>{const O=await i({address:o.address,chainType:"stellar",hash:R},{title:"Sign Message",description:"You are about to sign the following message:",confirmText:"Sign",rejectText:"Reject",displayHash:I});if(!O)throw new Error("User rejected signature");return O.signature};return await t.signMessage(I,M)}catch(M){const R=new Error(`Failed to sign message: ${M.message}`);throw u(R),R}finally{l(!1)}},[o,i,t]),P=$.useCallback(async(I,M,R)=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const O=await t.prepareTransaction(I,M),S=Mw(O.hash),A=await i({address:o.address,chainType:"stellar",hash:S},{title:"Sign Transaction",description:"Review and sign the following transaction.",confirmText:"Sign & Send",rejectText:"Reject",displayHash:`Transaction Hash: ${O.hash}`});if(!A)throw new Error("User rejected transaction");const k=Rw(A.signature);return await t.submitPreparedAndWait(O.hash,k,R)}catch(O){const S=new Error(`Failed to send transaction: ${O.message}`);throw u(S),S}finally{l(!1)}},[o,i,t]);return{stellarWallet:o,stellarWallets:a,createStellarWallet:b,registerCanton:v,isRegistered:h,cantonUser:g,getMe:w,getActiveContracts:_,tapDevnet:E,signHash:x,signMessage:T,sendTransaction:P,loading:c,error:d,clearError:C}}const Cut=()=>{const{apiService:t}=lf();return{user:{getCurrent:()=>t.getCurrentUser(),getAll:()=>t.getAllUsers(),getByPrivyId:e=>t.getUserByPrivyId(e),getBalance:e=>t.getSmartWalletBalances(e)},dialogs:{create:e=>t.createDialog(e),findAll:e=>t.getAllDialogs(e),findOne:e=>t.getDialog(e),delete:e=>t.deleteDialog(e)},messages:{create:(e,n)=>t.createMessage(e,n),findAll:(e,n)=>t.getDialogMessages(e,n),findOne:e=>t.getMessage(e)},onchain:{getPricesByAddresses:e=>t.getTokenPricesByAddresses(e),getTokenPrices:e=>t.getTokenPrices(e),getPriceHistory:e=>t.getTokenPriceHistory(e),get24hrPriceChanges:e=>t.getTokens24hrPriceChanges(e),getTokenInfo:(e,n)=>t.getTokenInfo(e,n),getAccountBalances:(e,n,r)=>t.getAccountTokenBalances(e,n,r)},transactions:{get:e=>t.getTransactions(e),forceLoad:e=>t.forceLoadTransactions(e)},supaPoints:{getBalance:()=>t.getSupaPointsBalance(),getHistory:e=>t.getSupaPointsHistory(e),dailyLogin:()=>t.dailyLogin()},paymaster:{checkSponsorship:e=>t.checkPaymasterSponsorship(e)},privy:{getBalance:()=>t.getPrivyBalance()}}},Zge=()=>{const t=dS(),e=qge(),n=Cut(),r=async()=>{if(!t.authenticated){t.login();return}e.isRegistered||await e.registerCanton()},i=$.useMemo(()=>e.stellarWallet?e.isRegistered?3:2:1,[e.stellarWallet,e.isRegistered]);return $.useEffect(()=>{!e.loading&&t.authenticated&&(i===1&&e.createStellarWallet(),i===2&&e.registerCanton())},[i,t.authenticated,e.loading]),{auth:t,canton:e,api:n,onboard:r}};function Aut(){const{cantonService:t}=lf(),{signRawHashWithModal:e}=uS(),{stellarWallet:n,stellarWallets:r}=pS(),[i,s]=$.useState(!1),[o,a]=$.useState(null),c=$.useCallback(()=>a(null),[]);return{signMessage:$.useCallback(async(d,u)=>{const{onSuccess:h,onRejection:p,onError:g,skipModal:m=!1,title:y="Sign Message",description:b="You are about to sign the following message.",confirmText:x="Sign",rejectText:v="Reject",displayContent:E,showTechnicalDetails:C=!1}=u||{};if(!n){const w=new Error("No Stellar wallet found. Please create one first.");return a(w),g?.(w),null}a(null),s(!0);try{const w=async T=>{const P=await e({address:n.address,chainType:"stellar",hash:T},{skipModal:m,title:y,description:b,confirmText:x,rejectText:v,infoText:"Signing a message proves ownership of your wallet without exposing private keys or making any blockchain transactions.",displayHash:C?void 0:E||d,showTechnicalDetails:C});if(!P)throw new Error("User rejected signature");return P.signature},_=await t.signMessage(d,w);return h?.(_),_}catch(w){if(w.message.includes("rejected"))p?.();else{const T=new Error(`Failed to sign message: ${w.message}`);a(T),g?.(T)}return null}finally{s(!1)}},[n,e,t]),loading:i,error:o,clearError:c,stellarWallets:r,stellarWallet:n}}function _ut(){const{cantonService:t}=lf(),{signRawHashWithModal:e}=uS(),{stellarWallet:n,stellarWallets:r}=pS(),[i,s]=$.useState(!1),[o,a]=$.useState(null),c=$.useCallback(()=>a(null),[]);return{sendTransaction:$.useCallback(async(d,u,h)=>{const{onSuccess:p,onRejection:g,onError:m,skipModal:y=!1,modalTitle:b="Sign Transaction",modalDescription:x="Review and sign the following transaction.",modalConfirmText:v="Sign & Send",modalRejectText:E="Reject",modalDisplayContent:C,showTechnicalDetails:w=!1,submitOptions:_}=h||{};if(!n){const T=new Error("No Stellar wallet found. Please create one first.");return a(T),m?.(T),null}a(null),s(!0);try{const T=await t.prepareTransaction(d,u),P=C||(w?void 0:`Transaction Hash: ${T.hash}`),I=Mw(T.hash),M=await e({address:n.address,chainType:"stellar",hash:I},{skipModal:y,title:b,description:x,confirmText:v,rejectText:E,infoText:"You are submitting a transaction, please be careful",displayHash:P,showTechnicalDetails:w});if(!M)return g?.(),null;const R=Rw(M.signature),O=await t.submitPreparedAndWait(T.hash,R,_);return p?.(O),O}catch(T){if(T.message.includes("rejected"))g?.();else{const I=new Error(`Failed to send transaction: ${T.message}`);a(I),m?.(I)}return null}finally{s(!1)}},[n,e,t]),loading:i,error:o,clearError:c,stellarWallets:r,stellarWallet:n}}function Sut(){const{confirm:t,signMessageConfirm:e,signTransactionConfirm:n,setModalLoading:r,closeModal:i}=lf();return{confirm:t,signMessageConfirm:e,signTransactionConfirm:n,setModalLoading:r,closeModal:i}}const Te={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof process<"u"&&process.env.NODE_ENV==="development"},pF={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(n=>n.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const n=t.find(i=>i.caipNetworkId===e);if(n)return n.name;const[r]=e.split(":");return Te.CHAIN_NAME_MAP?.[r]||void 0}},Kge=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var $ut=20,kut=1,dm=1e6,TJ=1e6,Iut=-7,Tut=21,Put=!1,E8="[big.js] ",qm=E8+"Invalid ",fS=qm+"decimal places",Out=qm+"rounding mode",Gge=E8+"Division by zero",Qn={},uu=void 0,Nut=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Yge(){function t(e){var n=this;if(!(n instanceof t))return e===uu?Yge():new t(e);if(e instanceof t)n.s=e.s,n.e=e.e,n.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(qm+"value");e=e===0&&1/e<0?"-0":String(e)}Rut(n,e)}n.constructor=t}return t.prototype=Qn,t.DP=$ut,t.RM=kut,t.NE=Iut,t.PE=Tut,t.strict=Put,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Rut(t,e){var n,r,i;if(!Nut.test(e))throw Error(qm+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),i=e.length,r=0;r<i&&e.charAt(r)=="0";)++r;if(r==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=n-r-1,t.c=[],n=0;r<=i;)t.c[n++]=+e.charAt(r++)}return t}function Zm(t,e,n,r){var i=t.c;if(n===uu&&(n=t.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(Out);if(e<1)r=n===3&&(r||!!i[0])||e===0&&(n===1&&i[0]>=5||n===2&&(i[0]>5||i[0]===5&&(r||i[1]!==uu))),i.length=1,r?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(r=n===1&&i[e]>=5||n===2&&(i[e]>5||i[e]===5&&(r||i[e+1]!==uu||i[e-1]&1))||n===3&&(r||!!i[0]),i.length=e,r){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function Km(t,e,n){var r=t.e,i=t.c.join(""),s=i.length;if(e)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&n?"-"+i:i}Qn.abs=function(){var t=new this.constructor(this);return t.s=1,t};Qn.cmp=function(t){var e,n=this,r=n.c,i=(t=new n.constructor(t)).c,s=n.s,o=t.s,a=n.e,c=t.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(e=s<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^e?1:-1;return a==c?0:a>c^e?1:-1};Qn.div=function(t){var e=this,n=e.constructor,r=e.c,i=(t=new n(t)).c,s=e.s==t.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>dm)throw Error(fS);if(!i[0])throw Error(Gge);if(!r[0])return t.s=s,t.c=[t.e=0],t;var a,c,l,d,u,h=i.slice(),p=a=i.length,g=r.length,m=r.slice(0,a),y=m.length,b=t,x=b.c=[],v=0,E=o+(b.e=e.e-t.e)+1;for(b.s=s,s=E<0?0:E,h.unshift(0);y++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(y=m.length))d=a>y?1:-1;else for(u=-1,d=0;++u<a;)if(i[u]!=m[u]){d=i[u]>m[u]?1:-1;break}if(d<0){for(c=y==a?i:h;y;){if(m[--y]<c[y]){for(u=y;u&&!m[--u];)m[u]=9;--m[u],m[y]+=10}m[y]-=c[y]}for(;!m[0];)m.shift()}else break}x[v++]=d?l:++l,m[0]&&d?m[y]=r[p]||0:m=[r[p]]}while((p++<g||m[0]!==uu)&&s--);return!x[0]&&v!=1&&(x.shift(),b.e--,E--),v>E&&Zm(b,E,n.RM,m[0]!==uu),b};Qn.eq=function(t){return this.cmp(t)===0};Qn.gt=function(t){return this.cmp(t)>0};Qn.gte=function(t){return this.cmp(t)>-1};Qn.lt=function(t){return this.cmp(t)<0};Qn.lte=function(t){return this.cmp(t)<1};Qn.minus=Qn.sub=function(t){var e,n,r,i,s=this,o=s.constructor,a=s.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,s.plus(t);var l=s.c.slice(),d=s.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(s):t.s=1,t;if(a=d-h){for((i=a<0)?(a=-a,r=l):(h=d,r=u),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<u.length)?l:u).length,a=c=0;c<n;c++)if(l[c]!=u[c]){i=l[c]<u[c];break}if(i&&(r=l,l=u,u=r,t.s=-t.s),(c=(n=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;n>a;){if(l[--n]<u[n]){for(e=n;e&&!l[--e];)l[e]=9;--l[e],l[n]+=10}l[n]-=u[n]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Qn.mod=function(t){var e,n=this,r=n.constructor,i=n.s,s=(t=new r(t)).s;if(!t.c[0])throw Error(Gge);return n.s=t.s=1,e=t.cmp(n)==1,n.s=i,t.s=s,e?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(t),r.DP=i,r.RM=s,this.minus(n.times(t)))};Qn.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Qn.plus=Qn.add=function(t){var e,n,r,i=this,s=i.constructor;if(t=new s(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new s(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),e=l.length,n=0;e;a[e]%=10)n=(a[--e]=a[e]+l[e]+n)/10|0;for(n&&(a.unshift(n),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Qn.pow=function(t){var e=this,n=new e.constructor("1"),r=n,i=t<0;if(t!==~~t||t<-TJ||t>TJ)throw Error(qm+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?n.div(r):r};Qn.prec=function(t,e){if(t!==~~t||t<1||t>dm)throw Error(qm+"precision");return Zm(new this.constructor(this),t,e)};Qn.round=function(t,e){if(t===uu)t=0;else if(t!==~~t||t<-dm||t>dm)throw Error(fS);return Zm(new this.constructor(this),t+this.e+1,e)};Qn.sqrt=function(){var t,e,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(E8+"No square root");s=Math.sqrt(+Km(r,!0,!0)),s===0||s===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),s=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):t=new i(s+""),o=t.e+(i.DP+=4);do n=t,t=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Zm(t,(i.DP-=4)+t.e+1,i.RM)};Qn.times=Qn.mul=function(t){var e,n=this,r=n.constructor,i=n.c,s=(t=new r(t)).c,o=i.length,a=s.length,c=n.e,l=t.e;if(t.s=n.s==t.s?1:-1,!i[0]||!s[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=s,s=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+s[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Qn.toExponential=function(t,e){var n=this,r=n.c[0];if(t!==uu){if(t!==~~t||t<0||t>dm)throw Error(fS);for(n=Zm(new n.constructor(n),++t,e);n.c.length<t;)n.c.push(0)}return Km(n,!0,!!r)};Qn.toFixed=function(t,e){var n=this,r=n.c[0];if(t!==uu){if(t!==~~t||t<0||t>dm)throw Error(fS);for(n=Zm(new n.constructor(n),t+n.e+1,e),t=t+n.e+1;n.c.length<t;)n.c.push(0)}return Km(n,!1,!!r)};Qn[Symbol.for("nodejs.util.inspect.custom")]=Qn.toJSON=Qn.toString=function(){var t=this,e=t.constructor;return Km(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Qn.toNumber=function(){var t=+Km(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(E8+"Imprecise conversion");return t};Qn.toPrecision=function(t,e){var n=this,r=n.constructor,i=n.c[0];if(t!==uu){if(t!==~~t||t<1||t>dm)throw Error(qm+"precision");for(n=Zm(new r(n),t,e);n.c.length<t;)n.c.push(0)}return Km(n,t<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)};Qn.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(E8+"valueOf disallowed");return Km(t,t.e<=e.NE||t.e>=e.PE,!0)};var Tf=Yge();const Ti={bigNumber(t){return t?new Tf(t):new Tf(0)},multiply(t,e){if(t===void 0||e===void 0)return new Tf(0);const n=new Tf(t),r=new Tf(e);return n.times(r)},toFixed(t,e=2){return t===void 0||t===""?new Tf(0).toFixed(e):new Tf(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Tf(e).toNumber()}},Mut=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],jut=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Dut=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Lut={getERC20Abi:t=>Te.USDT_CONTRACT_ADDRESSES.includes(t)?Dut:Mut,getSwapAbi:()=>jut},Bs={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[n,r,i]=e;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[n,r]=e;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:n,chainId:r}}},Yd={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,n=typeof e.message=="string",r=typeof e.code=="number";return n&&r}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){return Yd.isRpcProviderError(t)?t.code===Yd.RPC_ERROR_CODE.USER_REJECTED_REQUEST||Yd.isUserRejectedMessage(t.message):t instanceof Error?Yd.isUserRejectedMessage(t.message):!1}};class But extends Error{constructor(e,n){super(n.message,{cause:e}),this.name=Yd.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=n.code}}class Jge extends But{constructor(e){super(e,{code:Yd.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=Yd.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const _t={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function lT(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Et={setItem(t,e){v6()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(v6())return localStorage.getItem(t)||void 0},removeItem(t){v6()&&localStorage.removeItem(t)},clear(){v6()&&localStorage.clear()}};function v6(){return typeof window<"u"&&typeof localStorage<"u"}function n7(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Uut=Symbol(),PJ=Object.getPrototypeOf,CM=new WeakMap,Fut=t=>t&&(CM.has(t)?CM.get(t):PJ(t)===Object.prototype||PJ(t)===Array.prototype),zut=t=>Fut(t)&&t[Uut]||null,OJ=(t,e=!0)=>{CM.set(t,e)},r7={},fF=t=>typeof t=="object"&&t!==null,Wut=t=>fF(t)&&!C8.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Xge=(t,e)=>{const n=AM.get(t);if(n?.[0]===e)return n[1];const r=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return OJ(r,!0),AM.set(t,[e,r]),Reflect.ownKeys(t).forEach(i=>{if(Object.getOwnPropertyDescriptor(r,i))return;const s=Reflect.get(t,i),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,i),a={value:s,enumerable:o,configurable:!0};if(C8.has(s))OJ(s,!1);else if(H0.has(s)){const[c,l]=H0.get(s);a.value=Xge(c,l())}Object.defineProperty(r,i,a)}),Object.preventExtensions(r)},Hut=(t,e,n,r)=>({deleteProperty(i,s){const o=Reflect.get(i,s);n(s);const a=Reflect.deleteProperty(i,s);return a&&r(["delete",[s],o]),a},set(i,s,o,a){const c=!t()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(NJ(l,o)||r4.has(o)&&NJ(l,r4.get(o))))return!0;n(s),fF(o)&&(o=zut(o)||o);const d=!H0.has(o)&&qut(o)?mr(o):o;return e(s,d),Reflect.set(i,s,d,a),r(["set",[s],o,l]),!0}}),H0=new WeakMap,C8=new WeakSet,AM=new WeakMap,sC=[1],r4=new WeakMap;let NJ=Object.is,Vut=(t,e)=>new Proxy(t,e),qut=Wut,Zut=Xge,Kut=Hut;function mr(t={}){if(!fF(t))throw new Error("object required");const e=r4.get(t);if(e)return e;let n=sC[0];const r=new Set,i=(y,b=++sC[0])=>{n!==b&&(s=n=b,r.forEach(x=>x(y,b)))};let s=n;const o=(y=sC[0])=>(s!==y&&(s=y,c.forEach(([b])=>{const x=b[1](y);x>n&&(n=x)})),n),a=y=>(b,x)=>{const v=[...b];v[1]=[y,...v[1]],i(v,x)},c=new Map,l=(y,b)=>{const x=!C8.has(b)&&H0.get(b);if(x){if((r7?"production":void 0)!=="production"&&c.has(y))throw new Error("prop listener already exists");if(r.size){const v=x[2](a(y));c.set(y,[x,v])}else c.set(y,[x])}},d=y=>{var b;const x=c.get(y);x&&(c.delete(y),(b=x[1])==null||b.call(x))},u=y=>(r.add(y),r.size===1&&c.forEach(([x,v],E)=>{if((r7?"production":void 0)!=="production"&&v)throw new Error("remove already exists");const C=x[2](a(E));c.set(E,[x,C])}),()=>{r.delete(y),r.size===0&&c.forEach(([x,v],E)=>{v&&(v(),c.set(E,[x]))})});let h=!0;const p=Kut(()=>h,l,d,i),g=Vut(t,p);r4.set(t,g);const m=[t,o,u];return H0.set(g,m),Reflect.ownKeys(t).forEach(y=>{const b=Object.getOwnPropertyDescriptor(t,y);"value"in b&&b.writable&&(g[y]=t[y])}),h=!1,g}function Xi(t,e,n){const r=H0.get(t);(r7?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let i;const s=[],o=r[2];let a=!1;const l=o(d=>{s.push(d),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function i4(t){const e=H0.get(t);(r7?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[n,r]=e;return Zut(n,r())}function jw(t){return C8.add(t),t}function Gut(){return{proxyStateMap:H0,refSet:C8,snapCache:AM,versionHolder:sC,proxyCache:r4}}function Qi(t,e,n,r){let i=t[e];return Xi(t,()=>{const s=t[e];Object.is(i,s)||n(i=s)})}const{proxyStateMap:Yut,snapCache:Jut}=Gut(),Yx=t=>Yut.has(t);function Xut(t){const e=[];let n=0;const r=new Map,i=new WeakMap,s=()=>{const l=Jut.get(a),d=l?.[1];if(d&&!i.has(d)){const u=new Map(r);i.set(d,u)}},o=l=>i.get(l)||r,a={data:e,index:n,epoch:0,get size(){return Yx(this)||s(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");const u=r.get(l);return u===void 0?(r.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");const d=r.get(l);return d===void 0?!1:(delete this.data[d],r.delete(l),this.epoch++,!0)},clear(){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,r.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=mr(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const dT=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Qge=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Qut="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",gn={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:dT,SECURE_SITE_DASHBOARD:`${dT}/dashboard`,SECURE_SITE_FAVICON:`${dT}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Te.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Te.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},Be={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=Be.getActiveNamespace(),e=Be.getActiveCaipNetworkId(),n=e?e.split(":")[1]:void 0,r=n?isNaN(Number(n))?n:Number(n):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{Et.setItem(_t.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Et.getItem(_t.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Et.removeItem(_t.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Et.setItem(_t.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Et.setItem(_t.ACTIVE_CAIP_NETWORK_ID,t),Be.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Et.getItem(_t.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Et.removeItem(_t.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=lT(t);Et.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=Be.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Et.setItem(_t.RECENT_WALLETS,JSON.stringify(e)),Et.setItem(_t.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Et.getItem(_t.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=Et.getItem(_t.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Et.removeItem(_t.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const n=lT(t);Et.setItem(n,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Et.getItem(_t.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=lT(t);return Et.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Et.setItem(_t.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Et.getItem(_t.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Et.removeItem(_t.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Et.getItem(_t.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Et.getItem(_t.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Et.setItem(_t.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Et.getItem(_t.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Et.getItem(_t.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Et.setItem(_t.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=Be.getConnectedNamespaces();e.includes(t)||(e.push(t),Be.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=Be.getConnectedNamespaces(),n=e.indexOf(t);n>-1&&(e.splice(n,1),Be.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Et.getItem(_t.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Et.setItem(_t.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Et.removeItem(_t.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Et.getItem(_t.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=Be.getBalanceCache();Et.setItem(_t.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const n=Be.getBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;Be.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=Be.getBalanceCache();e[t.caipAddress]=t,Et.setItem(_t.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Et.getItem(_t.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=Be.getBalanceCache();Et.setItem(_t.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const n=Be.getNativeBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",t),Be.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=Be.getNativeBalanceCache();e[t.caipAddress]=t,Et.setItem(_t.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Et.getItem(_t.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const n=Be.getEnsCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;Be.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=Be.getEnsCache();e[t.address]=t,Et.setItem(_t.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=Be.getEnsCache();Et.setItem(_t.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Et.getItem(_t.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const n=Be.getIdentityCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;Be.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=Be.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Et.setItem(_t.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=Be.getIdentityCache();Et.setItem(_t.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Et.removeItem(_t.PORTFOLIO_CACHE),Et.removeItem(_t.NATIVE_BALANCE_CACHE),Et.removeItem(_t.ENS_CACHE),Et.removeItem(_t.IDENTITY_CACHE),Et.removeItem(_t.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Et.setItem(_t.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Et.getItem(_t.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const n=Be.getConnections(),r=n[e]??[],i=new Map;for(const o of r)i.set(o.connectorId,{...o});for(const o of t){const a=i.get(o.connectorId),c=o.connectorId===Te.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else i.set(o.connectorId,{...o})}const s={...n,[e]:Array.from(i.values())};Et.setItem(_t.CONNECTIONS,JSON.stringify(s))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const t=Et.getItem(_t.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:n}){try{const r=Be.getConnections(),i=r[n]??[],s=new Map(i.map(a=>[a.connectorId,a])),o=s.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?s.delete(t):s.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),Et.setItem(_t.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const t=Et.getItem(_t.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const n=Be.getDisconnectedConnectorIds(),r=n[e]??[];r.push(t),Et.setItem(_t.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const n=Be.getDisconnectedConnectorIds();let r=n[e]??[];r=r.filter(i=>i.toLowerCase()!==t.toLowerCase()),Et.setItem(_t.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(Be.getDisconnectedConnectorIds()[e]??[]).some(i=>i.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=Et.getItem(_t.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){try{const r=Be.getTransactionsCache()[t]?.[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;Be.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:n,transactions:r}){try{const i=Be.getTransactionsCache();i[t]={...i[t],[e]:{timestamp:n,transactions:r}},Et.setItem(_t.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:n,transactions:r})}},removeTransactionsCache({address:t,chainId:e}){try{const n=Be.getTransactionsCache(),r=n?.[t]||{},{[e]:i,...s}=r;Et.setItem(_t.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[t]:s}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Et.getItem(_t.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const n=Be.getTokenPriceCache()[t.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;Be.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=Be.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Et.setItem(_t.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=Be.getTokenPriceCache();Et.setItem(_t.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t?.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=Et.getItem(_t.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=Be.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,Et.setItem(_t.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},Le={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return Le.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=gn.TEN_SEC_MS:!0},isAllowedRetry(t,e=gn.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(Le.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const n=new URL(t),r=new URL(e);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+gn.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let n;return(...r)=>{function i(){t(...r)}n&&clearTimeout(n),n=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,n=null){if(Le.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=n;r&&(r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`)),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const s=encodeURIComponent(e);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(t,e){if(!Le.isHttpUrl(t))return this.formatNativeUrl(t,e);let n=t;n.endsWith("/")||(n=`${n}/`);const r=encodeURIComponent(e);return{redirect:`${n}wc?uri=${r}`,href:n}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?Be.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,n){window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},returnOpenHref(t,e,n){return window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((n,r)=>{const i=new Image;i.onload=n,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Le.wait(2e3)])},parseBalance(t,e){let n="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(n=l)}}const[r,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${e?` ${e}`:""}`,value:s,decimals:o,symbol:e}},getApiUrl(){return Te.W3M_API_URL},getBlockchainApiUrl(){return Te.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Te.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const n={};return e&&t&&(t.forEach((r,i)=>{n[r]=i}),e.sort((r,i)=>{const s=n[r.id],o=n[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const n of t)e+=n.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[n,r]=e.split(".");return{dollars:n,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const n=new Set;return t.filter(r=>{const i=r[e];return n.has(i)?!1:(n.add(i),!0)})},generateSdkVersion(t,e,n){const i=t.length===0?gn.ADAPTER_TYPES.UNIVERSAL:t.map(s=>s.adapterType).join(",");return`${e}-${i}-${n}`},createAccount(t,e,n,r,i){return{namespace:t,address:e,type:n,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),n=e[0];return e.filter(Boolean).length===3&&n in Te.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,n="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",s=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),n,e);return t.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(t,n,e)},injectIntoUrl(t,e,n){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),s=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+s),c=t.substring(r+s,o),l=t.substring(i),d=c+n;return a+d+l}};async function vv(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class A8{constructor({baseUrl:e,clientId:n}){this.baseUrl=e,this.clientId=n}async get({headers:e,signal:n,cache:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"GET",headers:e,signal:n,cache:r})).json()}async getBlob({headers:e,signal:n,...r}){const i=this.createUrl(r);return(await vv(i,{method:"GET",headers:e,signal:n})).blob()}async post({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"POST",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"PUT",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"DELETE",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:n}){const r=new URL(e,this.baseUrl);return n&&Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.append(i,s)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}sendBeacon({body:e,...n}){const r=this.createUrl(n);return navigator.sendBeacon(r.toString(),e?JSON.stringify(e):void 0)}}const _M={getFeatureValue(t,e){const n=e?.[t];return n===void 0?gn.DEFAULT_FEATURES[t]:n},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Le.isTelegram()){if(Le.isIos())return t.filter(e=>e!=="google");if(Le.isMac())return t.filter(e=>e!=="x");if(Le.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t},isSocialsEnabled(){return Array.isArray(_e.state.features?.socials)&&_e.state.features?.socials.length>0||Array.isArray(_e.state.remoteFeatures?.socials)&&_e.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(_e.state.features?.email||_e.state.remoteFeatures?.email)}},kt=mr({features:gn.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:gn.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1}),_e={state:kt,subscribeKey(t,e){return Qi(kt,t,e)},setOptions(t){Object.assign(kt,t)},setRemoteFeatures(t){if(!t)return;const e={...kt.remoteFeatures,...t};kt.remoteFeatures=e,kt.remoteFeatures?.socials&&(kt.remoteFeatures.socials=_M.filterSocialsByPlatform(kt.remoteFeatures.socials)),kt.features?.pay&&(kt.remoteFeatures.email=!1,kt.remoteFeatures.socials=!1)},setFeatures(t){if(!t)return;kt.features||(kt.features=gn.DEFAULT_FEATURES);const e={...kt.features,...t};kt.features=e,kt.features?.pay&&kt.remoteFeatures&&(kt.remoteFeatures.email=!1,kt.remoteFeatures.socials=!1)},setProjectId(t){kt.projectId=t},setCustomRpcUrls(t){kt.customRpcUrls=t},setAllWallets(t){kt.allWallets=t},setIncludeWalletIds(t){kt.includeWalletIds=t},setExcludeWalletIds(t){kt.excludeWalletIds=t},setFeaturedWalletIds(t){kt.featuredWalletIds=t},setTokens(t){kt.tokens=t},setTermsConditionsUrl(t){kt.termsConditionsUrl=t},setPrivacyPolicyUrl(t){kt.privacyPolicyUrl=t},setCustomWallets(t){kt.customWallets=t},setIsSiweEnabled(t){kt.isSiweEnabled=t},setIsUniversalProvider(t){kt.isUniversalProvider=t},setSdkVersion(t){kt.sdkVersion=t},setMetadata(t){kt.metadata=t},setDisableAppend(t){kt.disableAppend=t},setEIP6963Enabled(t){kt.enableEIP6963=t},setDebug(t){kt.debug=t},setEnableWalletGuide(t){kt.enableWalletGuide=t},setEnableAuthLogger(t){kt.enableAuthLogger=t},setEnableWallets(t){kt.enableWallets=t},setPreferUniversalLinks(t){kt.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,n]of Object.entries(gn.SIWX_DEFAULTS))t[e]??=n;kt.siwx=t},setConnectMethodsOrder(t){kt.features={...kt.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){kt.features={...kt.features,walletFeaturesOrder:t}},setSocialsOrder(t){kt.remoteFeatures={...kt.remoteFeatures,socials:t}},setCollapseWallets(t){kt.features={...kt.features,collapseWallets:t}},setEnableEmbedded(t){kt.enableEmbedded=t},setAllowUnsupportedChain(t){kt.allowUnsupportedChain=t},setManualWCControl(t){kt.manualWCControl=t},setEnableNetworkSwitch(t){kt.enableNetworkSwitch=t},setEnableMobileFullScreen(t){kt.enableMobileFullScreen=Le.isMobile()&&t},setEnableReconnect(t){kt.enableReconnect=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,n])=>{n&&(kt.defaultAccountTypes[e]=n)})},setUniversalProviderConfigOverride(t){kt.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return kt.universalProviderConfigOverride},getSnapshot(){return i4(kt)}},F1=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),zi=mr({...F1}),eht={state:zi,subscribeKey(t,e){return Qi(zi,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=Le.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){zi.message=F1.message,zi.variant=F1.variant,zi.svg=F1.svg,zi.open=F1.open,zi.autoClose=F1.autoClose},_showMessage({message:t,svg:e,variant:n="success",autoClose:r=F1.autoClose}){zi.open?(zi.open=!1,setTimeout(()=>{zi.message=t,zi.variant=n,zi.svg=e,zi.open=!0,zi.autoClose=r},150)):(zi.message=t,zi.variant=n,zi.svg=e,zi.open=!0,zi.autoClose=r)}},Nn=eht,tht={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},eme=Le.getBlockchainApiUrl(),oa=mr({clientId:null,api:new A8({baseUrl:eme,clientId:null}),supportedChains:{http:[],ws:[]}}),Ot={state:oa,async get(t){const{st:e,sv:n}=Ot.getSdkProperties(),r=_e.state.projectId,i={...t.params||{},st:e,sv:n,projectId:r};return oa.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=_e.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{oa.supportedChains.http.length||await Ot.getSupportedNetworks()}catch{return!1}return oa.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await Ot.get({path:"v1/supported-chains"});return oa.supportedChains=t,t}catch{return oa.supportedChains}},async fetchIdentity({address:t}){const e=Be.getIdentityFromCacheForAddress(t);if(e)return e;const n=await Ot.get({path:`/v1/identity/${t}`,params:{sender:K.state.activeCaipAddress?Le.getPlainAddress(K.state.activeCaipAddress):void 0}});return Be.updateIdentityCache({address:t,identity:n,timestamp:Date.now()}),n},async fetchTransactions({account:t,cursor:e,signal:n,cache:r,chainId:i}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const o=Be.getTransactionsCacheForAddress({address:t,chainId:i});if(o)return o;const a=await Ot.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:i},signal:n,cache:r});return Be.updateTransactionsCache({address:t,chainId:i,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:n,to:r,gasPrice:i}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:n,to:r,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{fungibles:[]};const n=Be.getTokenPriceCacheForAddresses(t);if(n)return n;const r=await oa.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:_e.state.projectId},headers:{"Content-Type":"application/json"}});return Be.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:r}),r},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:n}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return Ot.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:n}})},async generateSwapCalldata({amount:t,from:e,to:n,userAddress:r,disableEstimate:i}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return oa.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:gn.CONVERT_SLIPPAGE_TOLERANCE},projectId:_e.state.projectId,from:e,to:n,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:n}){const{st:r,sv:i}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Ot.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:n,from:t,to:e,st:r,sv:i}})},async getBalance(t,e,n){const{st:r,sv:i}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return Nn.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=Be.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await Ot.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:n,st:r,sv:i}});return Be.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return[];const n=K.getAccountData()?.address;return Ot.get({path:`/v1/profile/reverse/${t}`,params:{sender:n,apiVersion:"2"}})},async getEnsNameSuggestions(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:n,signature:r}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?oa.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:n,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:n,purchaseAmount:r,paymentAmount:i}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?(await oa.api.post({path:"/v1/generators/onrampurl",params:{projectId:_e.state.projectId},body:{destinationWallets:t,defaultNetwork:n,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Ot.get({path:"/v1/onramp/options"})}catch{return tht}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}){try{return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?await oa.api.post({path:"/v1/onramp/quote",params:{projectId:_e.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}}):null}catch{return{networkFee:{amount:n,currency:e.id},paymentSubtotal:{amount:n,currency:e.id},paymentTotal:{amount:n,currency:e.id},purchaseAmount:{amount:n,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,n){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?oa.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:_e.state.projectId},body:{pci:e,signature:n}}):{success:!1}},setClientId(t){oa.clientId=t,oa.api=new A8({baseUrl:eme,clientId:t})}},nht="https://secure.walletconnect.org/sdk";typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const lc={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},Hc={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},rht={handleMobileDeeplinkRedirect(t,e){const n=window.location.href,r=encodeURIComponent(n);if(t===Hc.PHANTOM.id&&!("phantom"in window)){const i=n.startsWith("https")?"https":"http",s=n.split("/")[2],o=encodeURIComponent(`${i}://${s}`);window.location.href=`${Hc.PHANTOM.url}/ul/browse/${r}?ref=${o}`}if(t===Hc.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Hc.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===Te.CHAIN.SOLANA&&t===Hc.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Hc.COINBASE.url}/dapp?cb_url=${r}`),e===Te.CHAIN.BITCOIN&&t===Hc.BINANCE.id&&!("binancew3w"in window)){const i=K.state.activeCaipNetwork,s=window.btoa("/pages/browser/index"),o=window.btoa(`url=${r}&defaultChainId=${i?.id??1}`),a=new URL(Hc.BINANCE.deeplink);a.searchParams.set("appId",Hc.BINANCE.appId),a.searchParams.set("startPagePath",s),a.searchParams.set("startPageQuery",o);const c=new URL(Hc.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},iht=Object.freeze({enabled:!0,events:[]}),sht=new A8({baseUrl:Le.getAnalyticsUrl(),clientId:null}),oht=5,aht=60*1e3,Pf=mr({...iht}),cht={state:Pf,subscribeKey(t,e){return Qi(Pf,t,e)},async sendError(t,e){if(!Pf.enabled)return;const n=Date.now();if(Pf.events.filter(s=>{const o=new Date(s.properties.timestamp||"").getTime();return n-o<aht}).length>=oht)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Pf.events.push(i);try{if(typeof window>"u")return;const{projectId:s,sdkType:o,sdkVersion:a}=_e.state;await sht.post({path:"/e",params:{projectId:s,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Le.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Pf.enabled=!0},disable(){Pf.enabled=!1},clearEvents(){Pf.events=[]}};class Gp extends Error{constructor(e,n,r){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=n,this.originalError=r,r&&r instanceof Error&&(this.originalName=r.name),Object.setPrototypeOf(this,Gp.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const s=r.stack,o=s.indexOf(`
|
|
419
|
+
`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=lm(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&iC.assertOptions(r,{silentJSONParsing:Td.transitional(Td.boolean),forcedJSONParsing:Td.transitional(Td.boolean),clarifyTimeoutError:Td.transitional(Td.boolean)},!1),i!=null&&(Se.isFunction(i)?n.paramsSerializer={serialize:i}:iC.assertOptions(i,{encode:Td.function,serialize:Td.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),iC.assertOptions(n,{baseUrl:Td.spelling("baseURL"),withXsrfToken:Td.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&Se.merge(s.common,s[n.method]);s&&Se.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ta.concat(o,s);const a=[];let c=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(c=c&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const l=[];this.interceptors.response.forEach(function(m){l.push(m.fulfilled,m.rejected)});let d,u=0,h;if(!c){const g=[kJ.bind(this),void 0];for(g.unshift(...a),g.push(...l),h=g.length,d=Promise.resolve(n);u<h;)d=d.then(g[u++],g[u++]);return d}h=a.length;let p=n;for(;u<h;){const g=a[u++],m=a[u++];try{p=g(p)}catch(y){m.call(this,y);break}}try{d=kJ.call(this,p)}catch(g){return Promise.reject(g)}for(u=0,h=l.length;u<h;)d=d.then(l[u++],l[u++]);return d}getUri(e){e=lm(this.defaults,e);const n=kge(e.baseURL,e.url,e.allowAbsoluteUrls);return Cge(n,e.params,e.paramsSerializer)}};Se.forEach(["delete","get","head","options"],function(e){Ig.prototype[e]=function(n,r){return this.request(lm(r||{},{method:e,url:n,data:(r||{}).data}))}});Se.forEach(["post","put","patch"],function(e){function n(r){return function(s,o,a){return this.request(lm(a||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Ig.prototype[e]=n(),Ig.prototype[e+"Form"]=n(!0)});let lut=class Nge{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{r.subscribe(a),s=a}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},e(function(s,o,a){r.reason||(r.reason=new Tb(s,o,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Nge(function(i){e=i}),cancel:e}}};function dut(t){return function(n){return t.apply(null,n)}}function uut(t){return Se.isObject(t)&&t.isAxiosError===!0}const EM={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(EM).forEach(([t,e])=>{EM[e]=t});function Rge(t){const e=new Ig(t),n=uge(Ig.prototype.request,e);return Se.extend(n,Ig.prototype,e,{allOwnKeys:!0}),Se.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return Rge(lm(t,i))},n}const bi=Rge(x8);bi.Axios=Ig;bi.CanceledError=Tb;bi.CancelToken=lut;bi.isCancel=Sge;bi.VERSION=Oge;bi.toFormData=aS;bi.AxiosError=on;bi.Cancel=bi.CanceledError;bi.all=function(e){return Promise.all(e)};bi.spread=dut;bi.isAxiosError=uut;bi.mergeConfig=lm;bi.AxiosHeaders=Ta;bi.formToJSON=t=>_ge(Se.isHTMLForm(t)?new FormData(t):t);bi.getAdapter=Pge.getAdapter;bi.HttpStatusCode=EM;bi.default=bi;const{Axios:aWt,AxiosError:cWt,CanceledError:lWt,isCancel:dWt,CancelToken:uWt,VERSION:hWt,all:pWt,Cancel:fWt,isAxiosError:gWt,spread:mWt,toFormData:yWt,AxiosHeaders:wWt,HttpStatusCode:bWt,formToJSON:vWt,getAdapter:xWt,mergeConfig:EWt}=bi;class Mge{client;getAccessToken;nodeIdentifier;constructor(e={nodeIdentifier:""}){const n=e.baseURL||"https://stage_api.walletino.fyi";this.nodeIdentifier=e.nodeIdentifier,this.client=bi.create({baseURL:n,headers:{"Content-Type":"application/json"}}),this.getAccessToken=e.getAccessToken,this.client.interceptors.request.use(async r=>{if(this.getAccessToken)try{const i=await this.getAccessToken();i&&(r.headers.Authorization=`Bearer ${i}`)}catch(i){console.error("[Supa SDK] ❌ Failed to get access token:",i)}return r.url?.startsWith("/canton/")&&(r.headers["X-Canton-Node-Id"]=this.nodeIdentifier),console.group(`[Supa SDK] 📤 REQUEST: ${r.method?.toUpperCase()} ${r.url}`),console.log("Headers:",{"Content-Type":r.headers["Content-Type"],Authorization:r.headers.Authorization?`Bearer ***${String(r.headers.Authorization).slice(-20)}`:"none","X-Canton-Node-Id":r.headers["X-Canton-Node-Id"]||"none"}),r.data&&console.log("Request Body:",r.data),console.groupEnd(),r},r=>Promise.reject(r)),this.client.interceptors.response.use(r=>(console.group(`[Supa SDK] 📥 RESPONSE: ${r.status} ${r.config.method?.toUpperCase()} ${r.config.url}`),console.log("Status:",r.status,r.statusText),console.log("Response Data:",r.data),console.groupEnd(),r),r=>{if(r.response){console.group(`[Supa SDK] ❌ ERROR RESPONSE: ${r.response.status} ${r.config?.method?.toUpperCase()} ${r.config?.url}`),console.error("Status:",r.response.status,r.response.statusText),console.error("Request Body:",r.config?.data),console.error("Response Data:",r.response.data),console.groupEnd();const i={statusCode:r.response.status,message:r.response.data?.message||r.message,error:r.response.data?.error};return Promise.reject(i)}return console.error("[Supa SDK] ❌ Network error:",r.message),Promise.reject({statusCode:0,message:r.message||"Network error"})})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}setAccessTokenGetter(e){this.getAccessToken=e}getBaseURL(){return this.client.defaults.baseURL||""}}let t7=null;function jge(t){return t7=new Mge(t),t7}function hut(){if(!t7)throw new Error("ApiClient not initialized. Call createApiClient first.");return t7}const Rw=t=>{const e=t.startsWith("0x")?t.slice(2):t,n=new Uint8Array(e.match(/.{1,2}/g)?.map(r=>parseInt(r,16))||[]);return Dge(n)},Mw=t=>{const e=Lge(t);return"0x"+Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("")},Dge=t=>btoa(String.fromCharCode(...t)),Lge=t=>{const e=atob(t.replace(/\s/g,"")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n},put=t=>{let e=t.startsWith("0x")?t.slice(2):t;return e.startsWith("00")&&(e=e.slice(2)),"0x"+e},Bge=t=>{let e=t.startsWith("0x")?t.slice(2):t;e.startsWith("00")&&(e=e.slice(2));try{const n=new Uint8Array(e.match(/.{1,2}/g).map(r=>parseInt(r,16)));return btoa(String.fromCharCode(...n))}catch{throw new Error("Failed to convert public key to base64")}};class Uge{constructor(e){this.client=e}async registerCanton(e,n=0){if(n>4)throw new Error;const{publicKey:r,signFunction:i}=e;let s;try{s=await this.client.post("/canton/register/prepare",{publicKey:r})}catch(d){return await new Promise(u=>setTimeout(u,1500)),typeof d=="object"&&d!==null&&"message"in d&&d.message==="Canton wallet already exists for the user."?void 0:this.registerCanton(e,n+1)}const o=s.hash,a=Mw(o),c=await i(a),l=Rw(c);await this.client.post("/canton/register/submit",{hash:o,signature:l})}async tapDevnet(e,n){const{amount:r,signFunction:i}=e,o=(await this.client.post("/canton/devnet/tap",{amount:r})).hash,a=Mw(o),c=await i(a),l=Rw(c);return await this.submitPreparedAndWait(o,l,n)}async submitPrepared(e,n){return await this.client.post("/canton/api/submit_prepared",{hash:e,signature:n})}async queryCompletion(e){return await this.client.get(`/canton/api/query_completion?submissionId=${encodeURIComponent(e)}`)}async submitPreparedAndWait(e,n,r={}){const{timeout:i=3e4,pollInterval:s=1e3}=r,o=await this.submitPrepared(e,n),{submissionId:a}=o,c=Date.now();for(;Date.now()-c<i;){const l=await this.queryCompletion(a);if(l.status==="completed")return l;await new Promise(d=>setTimeout(d,s))}throw new Error(`Transaction completion timeout after ${i}ms for submissionId: ${a}`)}async getMe(){return await this.client.get("/canton/api/me")}async getActiveContracts(e){const n=new URLSearchParams;e&&e.forEach(s=>n.append("templateIds",s));const r=n.toString(),i=r?`/canton/api/active_contracts?${r}`:"/canton/api/active_contracts";return await this.client.get(i)}async signMessage(e,n){const i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",i),a="0x"+Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join("");return await n(a)}async prepareTransaction(e,n){return await this.client.post("/canton/api/prepare_transaction",{commandId:e,disclosedContracts:n})}async checkRegistrationStatus(){try{return await this.getMe(),!0}catch{return!1}}}class Fge{constructor(e){this.client=e}async getCurrentUser(){return await this.client.get("/user/me")}async getAllUsers(){return await this.client.get("/user/all")}async getUserByPrivyId(e){return await this.client.get(`/user/${e}`)}async getSmartWalletBalances(e=!1){return await this.client.get("/user/smart_wallet_balances",{params:{force:e}})}async createDialog(e){return await this.client.post("/dialogs",{text:e})}async getAllDialogs(e){return await this.client.get("/dialogs",{params:e})}async getDialog(e){return await this.client.get(`/dialogs/${e}`)}async deleteDialog(e){return await this.client.delete(`/dialogs/${e}`)}async createMessage(e,n){return await this.client.post(`/dialogs/${e}/messages`,{text:n})}async getDialogMessages(e,n){return await this.client.get(`/dialogs/${e}/messages`,{params:n})}async getMessage(e){return await this.client.get(`/messages/${e}`)}async getTokenPricesByAddresses(e){return await this.client.post("/onchain/tokens_prices_by_addresses",{addresses:e})}async getTokenPrices(e){return await this.client.get("/onchain/tokens_prices",{params:{symbols:e.join(",")}})}async getTokenPriceHistory(e){return await this.client.get("/onchain/token_price_history",{params:e})}async getTokens24hrPriceChanges(e){return await this.client.post("/onchain/tokens_24hr_changes",{tokens:e})}async getTokenInfo(e,n){const r=Array.isArray(n)?n.join(","):n;return await this.client.get(`/onchain/token_info/${e}`,{params:{token:r}})}async getAccountTokenBalances(e,n,r=!1){return await this.client.get(`/onchain/account_tokens_balances/${e}`,{params:{account:n,force:r}})}async getTransactions(e){return await this.client.get("/transactions",{params:e})}async forceLoadTransactions(e){return await this.client.post("/transactions/transactions_force",null,{params:e})}async getSupaPointsBalance(){return await this.client.get("/supa_points/balance")}async getSupaPointsHistory(e){return await this.client.get("/supa_points/history",{params:e})}async dailyLogin(){return await this.client.post("/supa_points/daily_login")}async checkPaymasterSponsorship(e){return await this.client.post("/paymaster",e)}async getPrivyBalance(){return await this.client.get("/privy/balance")}}const Is={backdrop:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(4px)"},panelWrapper:{position:"fixed",inset:0,zIndex:9999,overflowY:"auto",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"},panel:{backgroundColor:"var(--privy-color-background-2)",border:"1px solid var(--privy-color-border-default)",borderRadius:"var(--privy-border-radius-mdlg)",maxWidth:"560px",width:"100%",maxHeight:"85vh",overflow:"hidden",display:"flex",flexDirection:"column",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)"},header:{padding:"20px 24px",borderBottom:"1px solid var(--privy-color-border-default)",display:"flex",alignItems:"center",justifyContent:"space-between"},title:{fontSize:"18px",fontWeight:600,color:"var(--privy-color-foreground)",margin:0,display:"flex",alignItems:"center",gap:"12px",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'},closeButton:{background:"transparent",border:"none",padding:"8px",cursor:"pointer",color:"var(--privy-color-icon-muted)",borderRadius:"var(--privy-border-radius-sm)",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 150ms"},body:{padding:"24px",overflowY:"auto",flex:1,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'},messageContainer:{backgroundColor:"var(--privy-color-background)",border:"1px solid var(--privy-color-border-default)",borderRadius:"var(--privy-border-radius-md)",padding:"16px",maxHeight:"400px",overflowY:"auto",marginBottom:"16px"},messageContent:{fontFamily:'"SF Mono", "Fira Code", "JetBrains Mono", monospace',fontSize:"14px",lineHeight:1.6,color:"var(--privy-color-foreground)",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},footer:{padding:"16px 24px",borderTop:"1px solid var(--privy-color-border-default)",display:"flex",gap:"12px",justifyContent:"flex-end",backgroundColor:"var(--privy-color-background)"},button:{padding:"12px 20px",borderRadius:"var(--privy-border-radius-md)",fontSize:"14px",fontWeight:600,cursor:"pointer",transition:"all 150ms",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',border:"none"},rejectButton:{backgroundColor:"transparent",border:"1px solid var(--privy-color-border-default)",color:"var(--privy-color-foreground-2)"},confirmButton:{backgroundColor:"var(--privy-color-accent)",color:"var(--privy-color-background)"},description:{fontSize:"14px",color:"var(--privy-color-foreground-2)",marginBottom:"16px",lineHeight:1.5},infoBox:{backgroundColor:"var(--privy-color-info-bg)",border:"1px solid var(--privy-color-border-info)",borderRadius:"var(--privy-border-radius-md)",padding:"12px 16px",display:"flex",gap:"12px",alignItems:"flex-start",marginTop:"16px"},infoText:{fontSize:"13px",color:"var(--privy-color-foreground-2)",lineHeight:1.5,margin:0}},fut=()=>f.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),f.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),gut=()=>f.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),f.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),f.jsx("path",{d:"M2 2l7.586 7.586"}),f.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),mut=()=>f.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),f.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),yut=()=>f.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"var(--privy-color-icon-interactive)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),f.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]});function lS({open:t,onClose:e,onConfirm:n,onReject:r,title:i="Confirm Action",message:s,confirmText:o="Confirm",rejectText:a="Cancel",description:c,infoText:l,icon:d,loading:u=!1}){const{theme:h}=lf(),p=()=>{r(),e()},g=()=>{n()},m=h==="dark"?"privy-dark":"privy-light";return f.jsx(nU,{show:t,as:$.Fragment,children:f.jsxs(Ohe,{onClose:e,style:{position:"relative",zIndex:9999},children:[f.jsx(sm,{as:$.Fragment,enter:"ease-out duration-200",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-150",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:f.jsx("div",{style:Is.backdrop})}),f.jsx("div",{style:Is.panelWrapper,children:f.jsx(sm,{as:$.Fragment,enter:"ease-out duration-200",enterFrom:"opacity-0 scale-95",enterTo:"opacity-100 scale-100",leave:"ease-in duration-150",leaveFrom:"opacity-100 scale-100",leaveTo:"opacity-0 scale-95",children:f.jsxs(iU,{className:m,style:Is.panel,children:[f.jsxs("div",{style:Is.header,children:[f.jsxs(Phe,{style:Is.title,children:[d||f.jsx(gut,{}),i]}),f.jsx("button",{onClick:p,style:Is.closeButton,onMouseEnter:y=>{y.currentTarget.style.backgroundColor="var(--privy-color-background-hover)",y.currentTarget.style.color="var(--privy-color-icon-default-hover)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color="var(--privy-color-icon-muted)"},children:f.jsx(fut,{})})]}),f.jsxs("div",{style:Is.body,children:[c&&f.jsx("p",{style:Is.description,children:c}),f.jsx("div",{style:Is.messageContainer,children:f.jsx("pre",{style:Is.messageContent,children:s})}),l&&f.jsxs("div",{style:Is.infoBox,children:[f.jsx(yut,{}),f.jsx("p",{style:Is.infoText,children:l})]})]}),f.jsxs("div",{style:Is.footer,children:[f.jsx("button",{onClick:p,disabled:u,style:{...Is.button,...Is.rejectButton,opacity:u?.5:1},onMouseEnter:y=>{u||(y.currentTarget.style.backgroundColor="var(--privy-color-background-hover)",y.currentTarget.style.color="var(--privy-color-foreground-hover)")},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.color="var(--privy-color-foreground-2)"},children:a}),f.jsx("button",{onClick:g,disabled:u,style:{...Is.button,...Is.confirmButton,opacity:u?.7:1},onMouseEnter:y=>{u||(y.currentTarget.style.backgroundColor="var(--privy-color-accent-hover)")},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="var(--privy-color-accent)"},children:u?"Processing...":o})]})]})})})]})})}function zge({open:t,onClose:e,onConfirm:n,onReject:r,message:i,loading:s=!1,title:o="Sign Message",description:a="You are about to sign the following message:",confirmText:c="Sign",rejectText:l="Reject"}){return f.jsx(lS,{open:t,onClose:e,onConfirm:n,onReject:r,title:o,message:i,confirmText:c,rejectText:l,description:a,infoText:"Signing a message proves ownership of your wallet without exposing private keys or making any blockchain transactions.",loading:s})}function Wge({open:t,onClose:e,onConfirm:n,onReject:r,transaction:i,loading:s=!1,title:o="Sign Transaction",description:a="Review and sign the following transaction:",confirmText:c="Sign & Send",rejectText:l="Reject",infoText:d="You are submitting a transaction, please be careful"}){return f.jsx(lS,{open:t,onClose:e,onConfirm:n,onReject:r,title:o,message:i,confirmText:c,rejectText:l,description:a,infoText:d,icon:f.jsx(mut,{}),loading:s})}typeof window<"u"&&!window.Buffer&&(window.Buffer=jlt.Buffer,console.log("[Supa SDK] ✅ Buffer polyfill initialized"));const Hge=$.createContext(null);function wut({config:t,children:e}){const[n,r]=$.useState(null),[i,s]=$.useState({type:null,options:null,resolve:null,loading:!1});$.useEffect(()=>{const w=jge({baseURL:t.apiBaseUrl,nodeIdentifier:t.nodeIdentifier}),_=new Uge(w),T=new Fge(w);r({apiClient:w,cantonService:_,apiService:T})},[t]);const o=$.useCallback(w=>_=>new Promise(T=>s({type:w,options:_,resolve:T,loading:!1})),[]),a=$.useCallback(o("confirm"),[o]),c=$.useCallback(o("signMessage"),[o]),l=$.useCallback(o("signTransaction"),[o]),d=$.useCallback(w=>{s(_=>({..._,loading:w}))},[]),u=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!1}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]),h=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!0}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]),p=$.useCallback(()=>{i.resolve&&i.resolve({confirmed:!1}),s({type:null,options:null,resolve:null,loading:!1})},[i.resolve]);if(!n)return null;const g=t.appearance?.theme||"light",m=g==="dark"?"privy-dark":"privy-light",y={embeddedWallets:{showWalletUIs:!0},appearance:{theme:g,accentColor:t.appearance?.accentColor?`#${t.appearance.accentColor.replace("#","")}`:void 0,logo:t.appearance?.logo},loginMethods:t.loginMethods||["email","wallet"]},b={...n,config:t,theme:g,confirm:a,signMessageConfirm:c,signTransactionConfirm:l,setModalLoading:d,closeModal:u},x=i.type!==null,v=i.type==="confirm",E=i.type==="signMessage",C=i.type==="signTransaction";return f.jsx(Olt,{appId:t.privyAppId,clientId:t.privyClientId,config:y,children:f.jsx(Hge.Provider,{value:b,children:f.jsxs("div",{className:m,children:[e,v&&i.options&&f.jsx(lS,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options}),E&&i.options&&f.jsx(zge,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options}),C&&i.options&&f.jsx(Wge,{open:x,onClose:p,onConfirm:h,onReject:p,loading:i.loading,...i.options})]})})})}function lf(){const t=$.useContext(Hge);if(!t)throw new Error("useSupaContext must be used within SupaProvider");return t}const dS=()=>{const{apiClient:t}=lf(),{login:e}=OOe(),{logout:n}=cde(),{authenticated:r,ready:i,user:s,getAccessToken:o}=Aw();return $.useEffect(()=>{r&&t.setAccessTokenGetter(o)},[r,t,o]),{login:()=>{e()},logout:async()=>{await n()},authenticated:r,loading:!i,user:s,getAccessToken:o,ready:i}},but=()=>{let{refreshSessionAndUser:t,privy:e}=Je();return $.useMemo((()=>({async createWallet(n){let r=await CC(e,{request:{chain_type:n.chainType}}),i=await t();if(!i)throw Error("User must be authenticated before creating a Privy wallet");return{user:i,wallet:r}}})),[t,e])},vut=()=>{let{user:t}=ln(),{privy:e}=Je(),{signWithUserSigner:n}=QU();return $.useMemo((()=>({async signRawHash({address:r,chainType:i,hash:s}){if(!t)throw Error("User must be authenticated before signing");let o=aB(t,i).filter((c=>js(c))).find((c=>c.address===r));if(!o)throw Error("Wallet not found");let a=await pIe(e,n,{wallet_id:o.id,params:{hash:s}});if(a.data&&"signature"in a.data&&a.data.encoding==="hex")return{signature:a.data.signature};throw Error("Failed to sign")}})),[e,n,t])};function uS(){const{signTransactionConfirm:t,setModalLoading:e}=lf(),{signRawHash:n}=vut();return{signRawHashWithModal:$.useCallback(async(i,s)=>{const{skipModal:o=!1,title:a="Sign Hash",description:c="You are about to sign the following hash:",confirmText:l="Sign",rejectText:d="Reject",infoText:u,displayHash:h,showTechnicalDetails:p=!1}=s||{};if(o)return await n(i);const g=h||(p?JSON.stringify({address:i.address,chainType:i.chainType,hash:i.hash},null,2):i.hash);if(!(await t({transaction:g,title:a,description:c,confirmText:l,rejectText:d,infoText:u})).confirmed)return null;e(!0);try{return await n(i)}finally{e(!1)}},[n,t,e])}}const hS=(t,e)=>{const n=[];if(t?.linkedAccounts){const s=t.linkedAccounts.filter(o=>o.type==="wallet"&&o.chainType==="stellar");n.push(...s)}const r=e.filter(s=>s.chainType==="stellar");return n.push(...r),Array.from(new Map(n.map(s=>[s.address,s])).values())},Vge=t=>{if(!t)throw new Error("Wallet is required");let e=t.publicKey;if(!e&&t.linkedAccount&&(e=t.linkedAccount.publicKey),!e)throw new Error("Public key not found in wallet. Make sure you have a Stellar wallet created in Privy.");if(typeof e!="string")throw new Error(`Invalid publicKey type: ${typeof e}`);if(!/^(0x)?[0-9a-fA-F]+$/.test(e))throw new Error(`publicKey is not in hex format: ${e.substring(0,20)}...`);return Bge(e)},xut=t=>t&&t.chainType==="stellar",Eut=(t,e)=>{const n=hS(t,e);if(n.length===0)throw new Error("No Stellar wallet found. Please create one first.");return n[0]};function pS(){const{user:t,authenticated:e}=dS(),{wallets:n}=Sh(),r=e?hS(t,n):[],i=r[0]||null;return{stellarWallets:r,stellarWallet:i}}function qge(){const{cantonService:t}=lf(),{user:e,authenticated:n}=dS(),{wallets:r}=Sh(),{signRawHashWithModal:i}=uS(),{createWallet:s}=but(),{stellarWallet:o,stellarWallets:a}=pS(),[c,l]=$.useState(!1),[d,u]=$.useState(null),[h,p]=$.useState(!1),[g,m]=$.useState(null);$.useEffect(()=>{n&&o&&y()},[n,o]);const y=async()=>{try{const I=await t.checkRegistrationStatus();p(I)}catch{p(!1)}},b=$.useCallback(async()=>{if(!n)throw new Error("User must be authenticated to create wallet");l(!0),u(null);try{const I=await s({chainType:"stellar"});return I||null}catch(I){const M=new Error(`Failed to create Stellar wallet: ${I.message}`);throw u(M),M}finally{l(!1)}},[n,s]),x=$.useCallback(async I=>{if(!o)throw new Error("No Stellar wallet found");try{const M=Mw(I),R=await i({address:o.address,chainType:"stellar",hash:M},{title:"Sign Hash",description:"You are about to sign the following hash.",confirmText:"Sign",rejectText:"Reject",displayHash:`Hash: ${I}`});if(!R)throw new Error("User rejected signature");return Rw(R.signature)}catch(M){throw new Error(`Failed to sign hash: ${M.message}`)}},[o,i]),v=$.useCallback(async()=>{l(!0),u(null);try{let I=o;if(!I){const O=await b();if(O?I=O:(await new Promise(A=>setTimeout(A,1500)),I=hS(e,r)[0]||null),!I)throw new Error("Failed to create Stellar wallet. Please try again.")}const M=Vge(I),R=async O=>{const S=await i({address:I.address,chainType:"stellar",hash:O},{skipModal:!0});if(!S)throw new Error("User rejected signature");return S.signature};await t.registerCanton({publicKey:M,signFunction:R}),p(!0)}catch(I){const M=new Error(`Failed to register Canton wallet: ${I.message}`);throw u(M),M}finally{l(!1)}},[o,b,e,r,i,t]),E=$.useCallback(async(I,M)=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const R=async O=>{const S=await i({address:o.address,chainType:"stellar",hash:O},{title:"Tap Devnet Faucet",description:`You are requesting ${I} tokens from the devnet faucet.`,confirmText:"Confirm & Sign",rejectText:"Cancel",displayHash:`Request ${I} Canton tokens from devnet faucet`});if(!S)throw new Error("User rejected signature");return S.signature};return await t.tapDevnet({amount:I,signFunction:R},M)}catch(R){const O=new Error(`Failed to tap devnet: ${R.message}`);throw u(O),O}finally{l(!1)}},[o,i,t]),C=$.useCallback(()=>{u(null)},[]),w=$.useCallback(async()=>{const I=await t.getMe();return m(I),I},[t]),_=$.useCallback(async I=>await t.getActiveContracts(I),[t]),T=$.useCallback(async I=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const M=async R=>{const O=await i({address:o.address,chainType:"stellar",hash:R},{title:"Sign Message",description:"You are about to sign the following message:",confirmText:"Sign",rejectText:"Reject",displayHash:I});if(!O)throw new Error("User rejected signature");return O.signature};return await t.signMessage(I,M)}catch(M){const R=new Error(`Failed to sign message: ${M.message}`);throw u(R),R}finally{l(!1)}},[o,i,t]),P=$.useCallback(async(I,M,R)=>{if(!o)throw new Error("No Stellar wallet found");l(!0),u(null);try{const O=await t.prepareTransaction(I,M),S=Mw(O.hash),A=await i({address:o.address,chainType:"stellar",hash:S},{title:"Sign Transaction",description:"Review and sign the following transaction.",confirmText:"Sign & Send",rejectText:"Reject",displayHash:`Transaction Hash: ${O.hash}`});if(!A)throw new Error("User rejected transaction");const k=Rw(A.signature);return await t.submitPreparedAndWait(O.hash,k,R)}catch(O){const S=new Error(`Failed to send transaction: ${O.message}`);throw u(S),S}finally{l(!1)}},[o,i,t]);return{stellarWallet:o,stellarWallets:a,createStellarWallet:b,registerCanton:v,isRegistered:h,cantonUser:g,getMe:w,getActiveContracts:_,tapDevnet:E,signHash:x,signMessage:T,sendTransaction:P,loading:c,error:d,clearError:C}}const Cut=()=>{const{apiService:t}=lf();return{user:{getCurrent:()=>t.getCurrentUser(),getAll:()=>t.getAllUsers(),getByPrivyId:e=>t.getUserByPrivyId(e),getBalance:e=>t.getSmartWalletBalances(e)},dialogs:{create:e=>t.createDialog(e),findAll:e=>t.getAllDialogs(e),findOne:e=>t.getDialog(e),delete:e=>t.deleteDialog(e)},messages:{create:(e,n)=>t.createMessage(e,n),findAll:(e,n)=>t.getDialogMessages(e,n),findOne:e=>t.getMessage(e)},onchain:{getPricesByAddresses:e=>t.getTokenPricesByAddresses(e),getTokenPrices:e=>t.getTokenPrices(e),getPriceHistory:e=>t.getTokenPriceHistory(e),get24hrPriceChanges:e=>t.getTokens24hrPriceChanges(e),getTokenInfo:(e,n)=>t.getTokenInfo(e,n),getAccountBalances:(e,n,r)=>t.getAccountTokenBalances(e,n,r)},transactions:{get:e=>t.getTransactions(e),forceLoad:e=>t.forceLoadTransactions(e)},supaPoints:{getBalance:()=>t.getSupaPointsBalance(),getHistory:e=>t.getSupaPointsHistory(e),dailyLogin:()=>t.dailyLogin()},paymaster:{checkSponsorship:e=>t.checkPaymasterSponsorship(e)},privy:{getBalance:()=>t.getPrivyBalance()}}},Zge=()=>{const t=dS(),e=qge(),n=Cut(),r=async()=>{if(!t.authenticated){t.login();return}e.isRegistered||await e.registerCanton()},i=$.useMemo(()=>e.stellarWallet?e.isRegistered?3:2:1,[e.stellarWallet,e.isRegistered]);return $.useEffect(()=>{!e.loading&&t.authenticated&&(i===1&&e.createStellarWallet(),i===2&&e.registerCanton())},[i,t.authenticated,e.loading]),{auth:t,canton:e,api:n,onboard:r}};function Aut(){const{cantonService:t}=lf(),{signRawHashWithModal:e}=uS(),{stellarWallet:n,stellarWallets:r}=pS(),[i,s]=$.useState(!1),[o,a]=$.useState(null),c=$.useCallback(()=>a(null),[]);return{signMessage:$.useCallback(async(d,u)=>{const{onSuccess:h,onRejection:p,onError:g,skipModal:m=!1,title:y="Sign Message",description:b="You are about to sign the following message.",confirmText:x="Sign",rejectText:v="Reject",displayContent:E,showTechnicalDetails:C=!1}=u||{};if(!n){const w=new Error("No Stellar wallet found. Please create one first.");return a(w),g?.(w),null}a(null),s(!0);try{const w=async T=>{const P=await e({address:n.address,chainType:"stellar",hash:T},{skipModal:m,title:y,description:b,confirmText:x,rejectText:v,infoText:"Signing a message proves ownership of your wallet without exposing private keys or making any blockchain transactions.",displayHash:C?void 0:E||d,showTechnicalDetails:C});if(!P)throw new Error("User rejected signature");return P.signature},_=await t.signMessage(d,w);return h?.(_),_}catch(w){if(w.message.includes("rejected"))p?.();else{const T=new Error(`Failed to sign message: ${w.message}`);a(T),g?.(T)}return null}finally{s(!1)}},[n,e,t]),loading:i,error:o,clearError:c,stellarWallets:r,stellarWallet:n}}function _ut(){const{cantonService:t}=lf(),{signRawHashWithModal:e}=uS(),{stellarWallet:n,stellarWallets:r}=pS(),[i,s]=$.useState(!1),[o,a]=$.useState(null),c=$.useCallback(()=>a(null),[]);return{sendTransaction:$.useCallback(async(d,u,h)=>{const{onSuccess:p,onRejection:g,onError:m,skipModal:y=!1,modalTitle:b="Sign Transaction",modalDescription:x="Review and sign the following transaction.",modalConfirmText:v="Sign & Send",modalRejectText:E="Reject",modalDisplayContent:C,showTechnicalDetails:w=!1,submitOptions:_}=h||{};if(!n){const T=new Error("No Stellar wallet found. Please create one first.");return a(T),m?.(T),null}a(null),s(!0);try{const T=await t.prepareTransaction(d,u),P=C||(w?void 0:`Transaction Hash: ${T.hash}`),I=Mw(T.hash),M=await e({address:n.address,chainType:"stellar",hash:I},{skipModal:y,title:b,description:x,confirmText:v,rejectText:E,infoText:"You are submitting a transaction, please be careful",displayHash:P,showTechnicalDetails:w});if(!M)return g?.(),null;const R=Rw(M.signature),O=await t.submitPreparedAndWait(T.hash,R,_);return p?.(O),O}catch(T){if(T.message.includes("rejected"))g?.();else{const I=new Error(`Failed to send transaction: ${T.message}`);a(I),m?.(I)}return null}finally{s(!1)}},[n,e,t]),loading:i,error:o,clearError:c,stellarWallets:r,stellarWallet:n}}function Sut(){const{confirm:t,signMessageConfirm:e,signTransactionConfirm:n,setModalLoading:r,closeModal:i}=lf();return{confirm:t,signMessageConfirm:e,signTransactionConfirm:n,setModalLoading:r,closeModal:i}}const Te={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof process<"u"&&process.env.NODE_ENV==="development"},pF={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(n=>n.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const n=t.find(i=>i.caipNetworkId===e);if(n)return n.name;const[r]=e.split(":");return Te.CHAIN_NAME_MAP?.[r]||void 0}},Kge=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var $ut=20,kut=1,dm=1e6,TJ=1e6,Iut=-7,Tut=21,Put=!1,E8="[big.js] ",qm=E8+"Invalid ",fS=qm+"decimal places",Out=qm+"rounding mode",Gge=E8+"Division by zero",Qn={},uu=void 0,Nut=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Yge(){function t(e){var n=this;if(!(n instanceof t))return e===uu?Yge():new t(e);if(e instanceof t)n.s=e.s,n.e=e.e,n.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(qm+"value");e=e===0&&1/e<0?"-0":String(e)}Rut(n,e)}n.constructor=t}return t.prototype=Qn,t.DP=$ut,t.RM=kut,t.NE=Iut,t.PE=Tut,t.strict=Put,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Rut(t,e){var n,r,i;if(!Nut.test(e))throw Error(qm+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),i=e.length,r=0;r<i&&e.charAt(r)=="0";)++r;if(r==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=n-r-1,t.c=[],n=0;r<=i;)t.c[n++]=+e.charAt(r++)}return t}function Zm(t,e,n,r){var i=t.c;if(n===uu&&(n=t.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(Out);if(e<1)r=n===3&&(r||!!i[0])||e===0&&(n===1&&i[0]>=5||n===2&&(i[0]>5||i[0]===5&&(r||i[1]!==uu))),i.length=1,r?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(r=n===1&&i[e]>=5||n===2&&(i[e]>5||i[e]===5&&(r||i[e+1]!==uu||i[e-1]&1))||n===3&&(r||!!i[0]),i.length=e,r){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function Km(t,e,n){var r=t.e,i=t.c.join(""),s=i.length;if(e)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&n?"-"+i:i}Qn.abs=function(){var t=new this.constructor(this);return t.s=1,t};Qn.cmp=function(t){var e,n=this,r=n.c,i=(t=new n.constructor(t)).c,s=n.s,o=t.s,a=n.e,c=t.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(e=s<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^e?1:-1;return a==c?0:a>c^e?1:-1};Qn.div=function(t){var e=this,n=e.constructor,r=e.c,i=(t=new n(t)).c,s=e.s==t.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>dm)throw Error(fS);if(!i[0])throw Error(Gge);if(!r[0])return t.s=s,t.c=[t.e=0],t;var a,c,l,d,u,h=i.slice(),p=a=i.length,g=r.length,m=r.slice(0,a),y=m.length,b=t,x=b.c=[],v=0,E=o+(b.e=e.e-t.e)+1;for(b.s=s,s=E<0?0:E,h.unshift(0);y++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(y=m.length))d=a>y?1:-1;else for(u=-1,d=0;++u<a;)if(i[u]!=m[u]){d=i[u]>m[u]?1:-1;break}if(d<0){for(c=y==a?i:h;y;){if(m[--y]<c[y]){for(u=y;u&&!m[--u];)m[u]=9;--m[u],m[y]+=10}m[y]-=c[y]}for(;!m[0];)m.shift()}else break}x[v++]=d?l:++l,m[0]&&d?m[y]=r[p]||0:m=[r[p]]}while((p++<g||m[0]!==uu)&&s--);return!x[0]&&v!=1&&(x.shift(),b.e--,E--),v>E&&Zm(b,E,n.RM,m[0]!==uu),b};Qn.eq=function(t){return this.cmp(t)===0};Qn.gt=function(t){return this.cmp(t)>0};Qn.gte=function(t){return this.cmp(t)>-1};Qn.lt=function(t){return this.cmp(t)<0};Qn.lte=function(t){return this.cmp(t)<1};Qn.minus=Qn.sub=function(t){var e,n,r,i,s=this,o=s.constructor,a=s.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,s.plus(t);var l=s.c.slice(),d=s.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(s):t.s=1,t;if(a=d-h){for((i=a<0)?(a=-a,r=l):(h=d,r=u),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<u.length)?l:u).length,a=c=0;c<n;c++)if(l[c]!=u[c]){i=l[c]<u[c];break}if(i&&(r=l,l=u,u=r,t.s=-t.s),(c=(n=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;n>a;){if(l[--n]<u[n]){for(e=n;e&&!l[--e];)l[e]=9;--l[e],l[n]+=10}l[n]-=u[n]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Qn.mod=function(t){var e,n=this,r=n.constructor,i=n.s,s=(t=new r(t)).s;if(!t.c[0])throw Error(Gge);return n.s=t.s=1,e=t.cmp(n)==1,n.s=i,t.s=s,e?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(t),r.DP=i,r.RM=s,this.minus(n.times(t)))};Qn.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Qn.plus=Qn.add=function(t){var e,n,r,i=this,s=i.constructor;if(t=new s(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new s(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),e=l.length,n=0;e;a[e]%=10)n=(a[--e]=a[e]+l[e]+n)/10|0;for(n&&(a.unshift(n),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Qn.pow=function(t){var e=this,n=new e.constructor("1"),r=n,i=t<0;if(t!==~~t||t<-TJ||t>TJ)throw Error(qm+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?n.div(r):r};Qn.prec=function(t,e){if(t!==~~t||t<1||t>dm)throw Error(qm+"precision");return Zm(new this.constructor(this),t,e)};Qn.round=function(t,e){if(t===uu)t=0;else if(t!==~~t||t<-dm||t>dm)throw Error(fS);return Zm(new this.constructor(this),t+this.e+1,e)};Qn.sqrt=function(){var t,e,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(E8+"No square root");s=Math.sqrt(+Km(r,!0,!0)),s===0||s===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),s=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):t=new i(s+""),o=t.e+(i.DP+=4);do n=t,t=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Zm(t,(i.DP-=4)+t.e+1,i.RM)};Qn.times=Qn.mul=function(t){var e,n=this,r=n.constructor,i=n.c,s=(t=new r(t)).c,o=i.length,a=s.length,c=n.e,l=t.e;if(t.s=n.s==t.s?1:-1,!i[0]||!s[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=s,s=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+s[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Qn.toExponential=function(t,e){var n=this,r=n.c[0];if(t!==uu){if(t!==~~t||t<0||t>dm)throw Error(fS);for(n=Zm(new n.constructor(n),++t,e);n.c.length<t;)n.c.push(0)}return Km(n,!0,!!r)};Qn.toFixed=function(t,e){var n=this,r=n.c[0];if(t!==uu){if(t!==~~t||t<0||t>dm)throw Error(fS);for(n=Zm(new n.constructor(n),t+n.e+1,e),t=t+n.e+1;n.c.length<t;)n.c.push(0)}return Km(n,!1,!!r)};Qn[Symbol.for("nodejs.util.inspect.custom")]=Qn.toJSON=Qn.toString=function(){var t=this,e=t.constructor;return Km(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Qn.toNumber=function(){var t=+Km(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(E8+"Imprecise conversion");return t};Qn.toPrecision=function(t,e){var n=this,r=n.constructor,i=n.c[0];if(t!==uu){if(t!==~~t||t<1||t>dm)throw Error(qm+"precision");for(n=Zm(new r(n),t,e);n.c.length<t;)n.c.push(0)}return Km(n,t<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)};Qn.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(E8+"valueOf disallowed");return Km(t,t.e<=e.NE||t.e>=e.PE,!0)};var Tf=Yge();const Ti={bigNumber(t){return t?new Tf(t):new Tf(0)},multiply(t,e){if(t===void 0||e===void 0)return new Tf(0);const n=new Tf(t),r=new Tf(e);return n.times(r)},toFixed(t,e=2){return t===void 0||t===""?new Tf(0).toFixed(e):new Tf(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Tf(e).toNumber()}},Mut=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],jut=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Dut=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Lut={getERC20Abi:t=>Te.USDT_CONTRACT_ADDRESSES.includes(t)?Dut:Mut,getSwapAbi:()=>jut},Bs={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[n,r,i]=e;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[n,r]=e;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:n,chainId:r}}},Yd={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,n=typeof e.message=="string",r=typeof e.code=="number";return n&&r}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){return Yd.isRpcProviderError(t)?t.code===Yd.RPC_ERROR_CODE.USER_REJECTED_REQUEST||Yd.isUserRejectedMessage(t.message):t instanceof Error?Yd.isUserRejectedMessage(t.message):!1}};class But extends Error{constructor(e,n){super(n.message,{cause:e}),this.name=Yd.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=n.code}}class Jge extends But{constructor(e){super(e,{code:Yd.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=Yd.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const _t={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function lT(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Et={setItem(t,e){v6()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(v6())return localStorage.getItem(t)||void 0},removeItem(t){v6()&&localStorage.removeItem(t)},clear(){v6()&&localStorage.clear()}};function v6(){return typeof window<"u"&&typeof localStorage<"u"}function n7(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Uut=Symbol(),PJ=Object.getPrototypeOf,CM=new WeakMap,Fut=t=>t&&(CM.has(t)?CM.get(t):PJ(t)===Object.prototype||PJ(t)===Array.prototype),zut=t=>Fut(t)&&t[Uut]||null,OJ=(t,e=!0)=>{CM.set(t,e)},r7={},fF=t=>typeof t=="object"&&t!==null,Wut=t=>fF(t)&&!C8.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Xge=(t,e)=>{const n=AM.get(t);if(n?.[0]===e)return n[1];const r=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return OJ(r,!0),AM.set(t,[e,r]),Reflect.ownKeys(t).forEach(i=>{if(Object.getOwnPropertyDescriptor(r,i))return;const s=Reflect.get(t,i),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,i),a={value:s,enumerable:o,configurable:!0};if(C8.has(s))OJ(s,!1);else if(H0.has(s)){const[c,l]=H0.get(s);a.value=Xge(c,l())}Object.defineProperty(r,i,a)}),Object.preventExtensions(r)},Hut=(t,e,n,r)=>({deleteProperty(i,s){const o=Reflect.get(i,s);n(s);const a=Reflect.deleteProperty(i,s);return a&&r(["delete",[s],o]),a},set(i,s,o,a){const c=!t()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(NJ(l,o)||r4.has(o)&&NJ(l,r4.get(o))))return!0;n(s),fF(o)&&(o=zut(o)||o);const d=!H0.has(o)&&qut(o)?mr(o):o;return e(s,d),Reflect.set(i,s,d,a),r(["set",[s],o,l]),!0}}),H0=new WeakMap,C8=new WeakSet,AM=new WeakMap,sC=[1],r4=new WeakMap;let NJ=Object.is,Vut=(t,e)=>new Proxy(t,e),qut=Wut,Zut=Xge,Kut=Hut;function mr(t={}){if(!fF(t))throw new Error("object required");const e=r4.get(t);if(e)return e;let n=sC[0];const r=new Set,i=(y,b=++sC[0])=>{n!==b&&(s=n=b,r.forEach(x=>x(y,b)))};let s=n;const o=(y=sC[0])=>(s!==y&&(s=y,c.forEach(([b])=>{const x=b[1](y);x>n&&(n=x)})),n),a=y=>(b,x)=>{const v=[...b];v[1]=[y,...v[1]],i(v,x)},c=new Map,l=(y,b)=>{const x=!C8.has(b)&&H0.get(b);if(x){if((r7?"production":void 0)!=="production"&&c.has(y))throw new Error("prop listener already exists");if(r.size){const v=x[2](a(y));c.set(y,[x,v])}else c.set(y,[x])}},d=y=>{var b;const x=c.get(y);x&&(c.delete(y),(b=x[1])==null||b.call(x))},u=y=>(r.add(y),r.size===1&&c.forEach(([x,v],E)=>{if((r7?"production":void 0)!=="production"&&v)throw new Error("remove already exists");const C=x[2](a(E));c.set(E,[x,C])}),()=>{r.delete(y),r.size===0&&c.forEach(([x,v],E)=>{v&&(v(),c.set(E,[x]))})});let h=!0;const p=Kut(()=>h,l,d,i),g=Vut(t,p);r4.set(t,g);const m=[t,o,u];return H0.set(g,m),Reflect.ownKeys(t).forEach(y=>{const b=Object.getOwnPropertyDescriptor(t,y);"value"in b&&b.writable&&(g[y]=t[y])}),h=!1,g}function Xi(t,e,n){const r=H0.get(t);(r7?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let i;const s=[],o=r[2];let a=!1;const l=o(d=>{s.push(d),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function i4(t){const e=H0.get(t);(r7?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[n,r]=e;return Zut(n,r())}function jw(t){return C8.add(t),t}function Gut(){return{proxyStateMap:H0,refSet:C8,snapCache:AM,versionHolder:sC,proxyCache:r4}}function Qi(t,e,n,r){let i=t[e];return Xi(t,()=>{const s=t[e];Object.is(i,s)||n(i=s)})}const{proxyStateMap:Yut,snapCache:Jut}=Gut(),Yx=t=>Yut.has(t);function Xut(t){const e=[];let n=0;const r=new Map,i=new WeakMap,s=()=>{const l=Jut.get(a),d=l?.[1];if(d&&!i.has(d)){const u=new Map(r);i.set(d,u)}},o=l=>i.get(l)||r,a={data:e,index:n,epoch:0,get size(){return Yx(this)||s(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");const u=r.get(l);return u===void 0?(r.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");const d=r.get(l);return d===void 0?!1:(delete this.data[d],r.delete(l),this.epoch++,!0)},clear(){if(!Yx(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,r.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=mr(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const dT=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Qge=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Qut="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",gn={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:dT,SECURE_SITE_DASHBOARD:`${dT}/dashboard`,SECURE_SITE_FAVICON:`${dT}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Te.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Te.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Te.CHAIN.EVM,Te.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},Be={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=Be.getActiveNamespace(),e=Be.getActiveCaipNetworkId(),n=e?e.split(":")[1]:void 0,r=n?isNaN(Number(n))?n:Number(n):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{Et.setItem(_t.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Et.getItem(_t.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Et.removeItem(_t.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Et.setItem(_t.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Et.setItem(_t.ACTIVE_CAIP_NETWORK_ID,t),Be.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Et.getItem(_t.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Et.removeItem(_t.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=lT(t);Et.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=Be.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Et.setItem(_t.RECENT_WALLETS,JSON.stringify(e)),Et.setItem(_t.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Et.getItem(_t.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=Et.getItem(_t.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Et.removeItem(_t.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const n=lT(t);Et.setItem(n,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Et.getItem(_t.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=lT(t);return Et.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Et.setItem(_t.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Et.getItem(_t.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Et.removeItem(_t.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Et.getItem(_t.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Et.getItem(_t.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Et.setItem(_t.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Et.getItem(_t.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Et.getItem(_t.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Et.setItem(_t.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=Be.getConnectedNamespaces();e.includes(t)||(e.push(t),Be.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=Be.getConnectedNamespaces(),n=e.indexOf(t);n>-1&&(e.splice(n,1),Be.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Et.getItem(_t.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Et.setItem(_t.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Et.removeItem(_t.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Et.getItem(_t.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=Be.getBalanceCache();Et.setItem(_t.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const n=Be.getBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;Be.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=Be.getBalanceCache();e[t.caipAddress]=t,Et.setItem(_t.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Et.getItem(_t.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=Be.getBalanceCache();Et.setItem(_t.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const n=Be.getNativeBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",t),Be.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=Be.getNativeBalanceCache();e[t.caipAddress]=t,Et.setItem(_t.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Et.getItem(_t.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const n=Be.getEnsCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;Be.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=Be.getEnsCache();e[t.address]=t,Et.setItem(_t.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=Be.getEnsCache();Et.setItem(_t.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Et.getItem(_t.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const n=Be.getIdentityCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;Be.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=Be.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Et.setItem(_t.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=Be.getIdentityCache();Et.setItem(_t.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Et.removeItem(_t.PORTFOLIO_CACHE),Et.removeItem(_t.NATIVE_BALANCE_CACHE),Et.removeItem(_t.ENS_CACHE),Et.removeItem(_t.IDENTITY_CACHE),Et.removeItem(_t.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Et.setItem(_t.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Et.getItem(_t.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const n=Be.getConnections(),r=n[e]??[],i=new Map;for(const o of r)i.set(o.connectorId,{...o});for(const o of t){const a=i.get(o.connectorId),c=o.connectorId===Te.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else i.set(o.connectorId,{...o})}const s={...n,[e]:Array.from(i.values())};Et.setItem(_t.CONNECTIONS,JSON.stringify(s))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const t=Et.getItem(_t.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:n}){try{const r=Be.getConnections(),i=r[n]??[],s=new Map(i.map(a=>[a.connectorId,a])),o=s.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?s.delete(t):s.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),Et.setItem(_t.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const t=Et.getItem(_t.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const n=Be.getDisconnectedConnectorIds(),r=n[e]??[];r.push(t),Et.setItem(_t.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const n=Be.getDisconnectedConnectorIds();let r=n[e]??[];r=r.filter(i=>i.toLowerCase()!==t.toLowerCase()),Et.setItem(_t.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(Be.getDisconnectedConnectorIds()[e]??[]).some(i=>i.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=Et.getItem(_t.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){try{const r=Be.getTransactionsCache()[t]?.[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;Be.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:n,transactions:r}){try{const i=Be.getTransactionsCache();i[t]={...i[t],[e]:{timestamp:n,transactions:r}},Et.setItem(_t.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:n,transactions:r})}},removeTransactionsCache({address:t,chainId:e}){try{const n=Be.getTransactionsCache(),r=n?.[t]||{},{[e]:i,...s}=r;Et.setItem(_t.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[t]:s}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Et.getItem(_t.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const n=Be.getTokenPriceCache()[t.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;Be.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=Be.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Et.setItem(_t.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=Be.getTokenPriceCache();Et.setItem(_t.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t?.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=Et.getItem(_t.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=Be.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,Et.setItem(_t.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},Le={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return Le.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=gn.TEN_SEC_MS:!0},isAllowedRetry(t,e=gn.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(Le.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const n=new URL(t),r=new URL(e);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+gn.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let n;return(...r)=>{function i(){t(...r)}n&&clearTimeout(n),n=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,n=null){if(Le.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=n;r&&(r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`)),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const s=encodeURIComponent(e);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(t,e){if(!Le.isHttpUrl(t))return this.formatNativeUrl(t,e);let n=t;n.endsWith("/")||(n=`${n}/`);const r=encodeURIComponent(e);return{redirect:`${n}wc?uri=${r}`,href:n}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?Be.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,n){window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},returnOpenHref(t,e,n){return window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((n,r)=>{const i=new Image;i.onload=n,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Le.wait(2e3)])},parseBalance(t,e){let n="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(n=l)}}const[r,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${e?` ${e}`:""}`,value:s,decimals:o,symbol:e}},getApiUrl(){return Te.W3M_API_URL},getBlockchainApiUrl(){return Te.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Te.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const n={};return e&&t&&(t.forEach((r,i)=>{n[r]=i}),e.sort((r,i)=>{const s=n[r.id],o=n[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const n of t)e+=n.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[n,r]=e.split(".");return{dollars:n,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const n=new Set;return t.filter(r=>{const i=r[e];return n.has(i)?!1:(n.add(i),!0)})},generateSdkVersion(t,e,n){const i=t.length===0?gn.ADAPTER_TYPES.UNIVERSAL:t.map(s=>s.adapterType).join(",");return`${e}-${i}-${n}`},createAccount(t,e,n,r,i){return{namespace:t,address:e,type:n,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),n=e[0];return e.filter(Boolean).length===3&&n in Te.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,n="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",s=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),n,e);return t.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(t,n,e)},injectIntoUrl(t,e,n){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),s=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+s),c=t.substring(r+s,o),l=t.substring(i),d=c+n;return a+d+l}};async function vv(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class A8{constructor({baseUrl:e,clientId:n}){this.baseUrl=e,this.clientId=n}async get({headers:e,signal:n,cache:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"GET",headers:e,signal:n,cache:r})).json()}async getBlob({headers:e,signal:n,...r}){const i=this.createUrl(r);return(await vv(i,{method:"GET",headers:e,signal:n})).blob()}async post({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"POST",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"PUT",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:n,signal:r,...i}){const s=this.createUrl(i);return(await vv(s,{method:"DELETE",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:n}){const r=new URL(e,this.baseUrl);return n&&Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.append(i,s)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}sendBeacon({body:e,...n}){const r=this.createUrl(n);return navigator.sendBeacon(r.toString(),e?JSON.stringify(e):void 0)}}const _M={getFeatureValue(t,e){const n=e?.[t];return n===void 0?gn.DEFAULT_FEATURES[t]:n},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Le.isTelegram()){if(Le.isIos())return t.filter(e=>e!=="google");if(Le.isMac())return t.filter(e=>e!=="x");if(Le.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t},isSocialsEnabled(){return Array.isArray(_e.state.features?.socials)&&_e.state.features?.socials.length>0||Array.isArray(_e.state.remoteFeatures?.socials)&&_e.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(_e.state.features?.email||_e.state.remoteFeatures?.email)}},kt=mr({features:gn.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:gn.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1}),_e={state:kt,subscribeKey(t,e){return Qi(kt,t,e)},setOptions(t){Object.assign(kt,t)},setRemoteFeatures(t){if(!t)return;const e={...kt.remoteFeatures,...t};kt.remoteFeatures=e,kt.remoteFeatures?.socials&&(kt.remoteFeatures.socials=_M.filterSocialsByPlatform(kt.remoteFeatures.socials)),kt.features?.pay&&(kt.remoteFeatures.email=!1,kt.remoteFeatures.socials=!1)},setFeatures(t){if(!t)return;kt.features||(kt.features=gn.DEFAULT_FEATURES);const e={...kt.features,...t};kt.features=e,kt.features?.pay&&kt.remoteFeatures&&(kt.remoteFeatures.email=!1,kt.remoteFeatures.socials=!1)},setProjectId(t){kt.projectId=t},setCustomRpcUrls(t){kt.customRpcUrls=t},setAllWallets(t){kt.allWallets=t},setIncludeWalletIds(t){kt.includeWalletIds=t},setExcludeWalletIds(t){kt.excludeWalletIds=t},setFeaturedWalletIds(t){kt.featuredWalletIds=t},setTokens(t){kt.tokens=t},setTermsConditionsUrl(t){kt.termsConditionsUrl=t},setPrivacyPolicyUrl(t){kt.privacyPolicyUrl=t},setCustomWallets(t){kt.customWallets=t},setIsSiweEnabled(t){kt.isSiweEnabled=t},setIsUniversalProvider(t){kt.isUniversalProvider=t},setSdkVersion(t){kt.sdkVersion=t},setMetadata(t){kt.metadata=t},setDisableAppend(t){kt.disableAppend=t},setEIP6963Enabled(t){kt.enableEIP6963=t},setDebug(t){kt.debug=t},setEnableWalletGuide(t){kt.enableWalletGuide=t},setEnableAuthLogger(t){kt.enableAuthLogger=t},setEnableWallets(t){kt.enableWallets=t},setPreferUniversalLinks(t){kt.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,n]of Object.entries(gn.SIWX_DEFAULTS))t[e]??=n;kt.siwx=t},setConnectMethodsOrder(t){kt.features={...kt.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){kt.features={...kt.features,walletFeaturesOrder:t}},setSocialsOrder(t){kt.remoteFeatures={...kt.remoteFeatures,socials:t}},setCollapseWallets(t){kt.features={...kt.features,collapseWallets:t}},setEnableEmbedded(t){kt.enableEmbedded=t},setAllowUnsupportedChain(t){kt.allowUnsupportedChain=t},setManualWCControl(t){kt.manualWCControl=t},setEnableNetworkSwitch(t){kt.enableNetworkSwitch=t},setEnableMobileFullScreen(t){kt.enableMobileFullScreen=Le.isMobile()&&t},setEnableReconnect(t){kt.enableReconnect=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,n])=>{n&&(kt.defaultAccountTypes[e]=n)})},setUniversalProviderConfigOverride(t){kt.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return kt.universalProviderConfigOverride},getSnapshot(){return i4(kt)}},F1=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),zi=mr({...F1}),eht={state:zi,subscribeKey(t,e){return Qi(zi,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=Le.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){zi.message=F1.message,zi.variant=F1.variant,zi.svg=F1.svg,zi.open=F1.open,zi.autoClose=F1.autoClose},_showMessage({message:t,svg:e,variant:n="success",autoClose:r=F1.autoClose}){zi.open?(zi.open=!1,setTimeout(()=>{zi.message=t,zi.variant=n,zi.svg=e,zi.open=!0,zi.autoClose=r},150)):(zi.message=t,zi.variant=n,zi.svg=e,zi.open=!0,zi.autoClose=r)}},Nn=eht,tht={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},eme=Le.getBlockchainApiUrl(),oa=mr({clientId:null,api:new A8({baseUrl:eme,clientId:null}),supportedChains:{http:[],ws:[]}}),Ot={state:oa,async get(t){const{st:e,sv:n}=Ot.getSdkProperties(),r=_e.state.projectId,i={...t.params||{},st:e,sv:n,projectId:r};return oa.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=_e.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{oa.supportedChains.http.length||await Ot.getSupportedNetworks()}catch{return!1}return oa.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await Ot.get({path:"v1/supported-chains"});return oa.supportedChains=t,t}catch{return oa.supportedChains}},async fetchIdentity({address:t}){const e=Be.getIdentityFromCacheForAddress(t);if(e)return e;const n=await Ot.get({path:`/v1/identity/${t}`,params:{sender:K.state.activeCaipAddress?Le.getPlainAddress(K.state.activeCaipAddress):void 0}});return Be.updateIdentityCache({address:t,identity:n,timestamp:Date.now()}),n},async fetchTransactions({account:t,cursor:e,signal:n,cache:r,chainId:i}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const o=Be.getTransactionsCacheForAddress({address:t,chainId:i});if(o)return o;const a=await Ot.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:i},signal:n,cache:r});return Be.updateTransactionsCache({address:t,chainId:i,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:n,to:r,gasPrice:i}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:n,to:r,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{fungibles:[]};const n=Be.getTokenPriceCacheForAddresses(t);if(n)return n;const r=await oa.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:_e.state.projectId},headers:{"Content-Type":"application/json"}});return Be.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:r}),r},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:n}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return Ot.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:n}})},async generateSwapCalldata({amount:t,from:e,to:n,userAddress:r,disableEstimate:i}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return oa.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:gn.CONVERT_SLIPPAGE_TOLERANCE},projectId:_e.state.projectId,from:e,to:n,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:n}){const{st:r,sv:i}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Ot.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:n,from:t,to:e,st:r,sv:i}})},async getBalance(t,e,n){const{st:r,sv:i}=Ot.getSdkProperties();if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return Nn.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=Be.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await Ot.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:n,st:r,sv:i}});return Be.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return[];const n=K.getAccountData()?.address;return Ot.get({path:`/v1/profile/reverse/${t}`,params:{sender:n,apiVersion:"2"}})},async getEnsNameSuggestions(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:n,signature:r}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?oa.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:n,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:n,purchaseAmount:r,paymentAmount:i}){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?(await oa.api.post({path:"/v1/generators/onrampurl",params:{projectId:_e.state.projectId},body:{destinationWallets:t,defaultNetwork:n,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){if(!await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Ot.get({path:"/v1/onramp/options"})}catch{return tht}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}){try{return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?await oa.api.post({path:"/v1/onramp/quote",params:{projectId:_e.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}}):null}catch{return{networkFee:{amount:n,currency:e.id},paymentSubtotal:{amount:n,currency:e.id},paymentTotal:{amount:n,currency:e.id},purchaseAmount:{amount:n,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?Ot.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,n){return await Ot.isNetworkSupported(K.state.activeCaipNetwork?.caipNetworkId)?oa.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:_e.state.projectId},body:{pci:e,signature:n}}):{success:!1}},setClientId(t){oa.clientId=t,oa.api=new A8({baseUrl:eme,clientId:t})}},nht="https://secure.walletconnect.org/sdk";typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const lc={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},Hc={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},rht={handleMobileDeeplinkRedirect(t,e){const n=window.location.href,r=encodeURIComponent(n);if(t===Hc.PHANTOM.id&&!("phantom"in window)){const i=n.startsWith("https")?"https":"http",s=n.split("/")[2],o=encodeURIComponent(`${i}://${s}`);window.location.href=`${Hc.PHANTOM.url}/ul/browse/${r}?ref=${o}`}if(t===Hc.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Hc.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===Te.CHAIN.SOLANA&&t===Hc.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Hc.COINBASE.url}/dapp?cb_url=${r}`),e===Te.CHAIN.BITCOIN&&t===Hc.BINANCE.id&&!("binancew3w"in window)){const i=K.state.activeCaipNetwork,s=window.btoa("/pages/browser/index"),o=window.btoa(`url=${r}&defaultChainId=${i?.id??1}`),a=new URL(Hc.BINANCE.deeplink);a.searchParams.set("appId",Hc.BINANCE.appId),a.searchParams.set("startPagePath",s),a.searchParams.set("startPageQuery",o);const c=new URL(Hc.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},iht=Object.freeze({enabled:!0,events:[]}),sht=new A8({baseUrl:Le.getAnalyticsUrl(),clientId:null}),oht=5,aht=60*1e3,Pf=mr({...iht}),cht={state:Pf,subscribeKey(t,e){return Qi(Pf,t,e)},async sendError(t,e){if(!Pf.enabled)return;const n=Date.now();if(Pf.events.filter(s=>{const o=new Date(s.properties.timestamp||"").getTime();return n-o<aht}).length>=oht)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Pf.events.push(i);try{if(typeof window>"u")return;const{projectId:s,sdkType:o,sdkVersion:a}=_e.state;await sht.post({path:"/e",params:{projectId:s,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Le.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Pf.enabled=!0},disable(){Pf.enabled=!1},clearEvents(){Pf.events=[]}};class Gp extends Error{constructor(e,n,r){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=n,this.originalError=r,r&&r instanceof Error&&(this.originalName=r.name),Object.setPrototypeOf(this,Gp.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const s=r.stack,o=s.indexOf(`
|
|
420
420
|
`);if(o>-1){const a=s.substring(o+1);this.stack=`${this.name}: ${this.message}
|
|
421
421
|
${a}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,Gp):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function RJ(t,e){let n="";try{t instanceof Error?n=t.message:typeof t=="string"?n=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?n="Unknown error":n=t?.message||JSON.stringify(t):n=String(t)}catch(i){n="Unknown error",console.error("Error parsing error message",i)}const r=t instanceof Gp?t:new Gp(n,e,t);throw cht.sendError(r,r.category),r}function Fa(t,e="INTERNAL_SDK_ERROR"){const n={};return Object.keys(t).forEach(r=>{const i=t[r];if(typeof i=="function"){let s=i;i.constructor.name==="AsyncFunction"?s=async(...o)=>{try{return await i(...o)}catch(a){return RJ(a,e)}}:s=(...o)=>{try{return i(...o)}catch(a){return RJ(a,e)}},n[r]=s}else n[r]=i}),n}const Ka=mr({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),lht={state:Ka,subscribeNetworkImages(t){return Xi(Ka.networkImages,()=>t(Ka.networkImages))},subscribeKey(t,e){return Qi(Ka,t,e)},subscribe(t){return Xi(Ka,()=>t(Ka))},setWalletImage(t,e){Ka.walletImages[t]=e},setNetworkImage(t,e){Ka.networkImages[t]=e},setChainImage(t,e){Ka.chainImages[t]=e},setConnectorImage(t,e){Ka.connectorImages={...Ka.connectorImages,[t]:e}},setTokenImage(t,e){Ka.tokenImages[t]=e},setCurrencyImage(t,e){Ka.currencyImages[t]=e}},To=Fa(lht),dht={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},uT=mr({networkImagePromises:{}}),pc={async fetchWalletImage(t){if(t)return await Ze._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(uT.networkImagePromises[t]||(uT.networkImagePromises[t]=Ze._fetchNetworkImage(t)),await uT.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return To.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return To.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return To.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return To.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.info?.icon)return t.info.icon;if(t?.imageId)return To.state.connectorImages[t.imageId]},getChainImage(t){return To.state.networkImages[dht[t]]},getTokenImage(t){if(t)return To.state.tokenImages[t]}},uht=Le.getAnalyticsUrl(),hht=new A8({baseUrl:uht,clientId:null}),pht=["MODAL_CREATED"],fht=45,MJ=1e3*10,Jr=mr({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),At={state:Jr,subscribe(t){return Xi(Jr,()=>t(Jr))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:n}=_e.state;return{projectId:t,st:e,sv:n||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify(Jr.pendingEvents).length/1024>fht,e=Jr.lastFlush+MJ<Date.now();return t||e},_setPendingEvent(t){try{let e=K.getAccountData()?.address;if("address"in t.data&&t.data.address&&(e=t.data.address),pht.includes(t.data.event)||typeof window>"u")return;const n=K.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:Le.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:n}}}),Jr.reportedErrors.FORBIDDEN=!1,At.shouldFlushEvents()&&At._submitPendingEvents()}catch(e){console.warn("_setPendingEvent",e)}},sendEvent(t){Jr.timestamp=Date.now(),Jr.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(_e.state.features?.analytics||e.includes(t.event))&&At._setPendingEvent(Jr),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){Jr.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION")}catch{return t}},_submitPendingEvents(){if(Jr.lastFlush=Date.now(),!(Jr.pendingEvents.length===0&&Jr.walletImpressions.length===0))try{const t=At._transformPendingEventsForBatch(Jr.pendingEvents);Jr.walletImpressions.length&&t.push({eventId:Le.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION",items:[...Jr.walletImpressions]}}),hht.sendBeacon({path:"/batch",params:At.getSdkProperties(),body:t}),Jr.reportedErrors.FORBIDDEN=!1,Jr.pendingEvents=[],Jr.walletImpressions=[]}catch{Jr.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){Jr.subscribedToVisibilityChange||typeof document>"u"||(Jr.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&At._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{At._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{At._submitPendingEvents()}),setInterval(()=>{At._submitPendingEvents()},MJ))}},ght=Le.getApiUrl(),aa=new A8({baseUrl:ght,clientId:null}),mht=40,jJ=4,yht=20,Jt=mr({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[]}),Ze={state:Jt,subscribeKey(t,e){return Qi(Jt,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:n}=_e.state;return{projectId:t,st:e||"appkit",sv:n||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return _e.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${aa.baseUrl}/getWalletImage/${t}`,n=await aa.getBlob({path:e,params:Ze._getSdkProperties()});To.setWalletImage(t,URL.createObjectURL(n))},async _fetchNetworkImage(t){const e=`${aa.baseUrl}/public/getAssetImage/${t}`,n=await aa.getBlob({path:e,params:Ze._getSdkProperties()});To.setNetworkImage(t,URL.createObjectURL(n))},async _fetchConnectorImage(t){const e=`${aa.baseUrl}/public/getAssetImage/${t}`,n=await aa.getBlob({path:e,params:Ze._getSdkProperties()});To.setConnectorImage(t,URL.createObjectURL(n))},async _fetchCurrencyImage(t){const e=`${aa.baseUrl}/public/getCurrencyImage/${t}`,n=await aa.getBlob({path:e,params:Ze._getSdkProperties()});To.setCurrencyImage(t,URL.createObjectURL(n))},async _fetchTokenImage(t){const e=`${aa.baseUrl}/public/getTokenImage/${t}`,n=await aa.getBlob({path:e,params:Ze._getSdkProperties()});To.setTokenImage(t,URL.createObjectURL(n))},_filterWalletsByPlatform(t){const e=t.length,n=Le.isMobile()?t?.filter(i=>i.mobile_link||i.webapp_link?!0:Object.values(Hc).map(o=>o.id).includes(i.id)):t,r=e-n.length;return{filteredWallets:n,mobileFilteredOutWalletsLength:r}},async fetchProjectConfig(){return(await aa.get({path:"/appkit/v1/config",params:Ze._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await aa.get({path:"/projects/v1/origins",params:Ze._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===Te.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=Te.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const e=K.getAllRequestedCaipNetworks()?.map(({assets:n})=>n?.imageId).filter(Boolean).filter(n=>!pc.getNetworkImageById(n));e&&await Promise.allSettled(e.map(n=>Ze._fetchNetworkImage(n)))},async fetchConnectorImages(){const{connectors:t}=De.state,e=t.map(({imageId:n})=>n).filter(Boolean);await Promise.allSettled(e.map(n=>Ze._fetchConnectorImage(n)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>Ze._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>Ze._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];Ze._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Hc).map(o=>o.id));const r=await aa.get({path:"/getWallets",params:{...Ze._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}}),{filteredWallets:i,mobileFilteredOutWalletsLength:s}=Ze._filterWalletsByPlatform(r?.data);return{data:i||[],count:r?.count,mobileFilteredOutWalletsLength:s}},async prefetchWalletRanks(){const t=De.state.connectors;if(!t?.length)return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(i=>i.name).join(","),K.state.activeChain===Te.CHAIN.EVM){const i=[...t.flatMap(s=>s.connectors?.map(o=>o.info?.rdns)||[]),...t.map(s=>s.info?.rdns)].filter(s=>typeof s=="string"&&s.length>0);i.length&&(e.rdns=i.join(","))}const{data:n}=await Ze.fetchWallets(e);Jt.explorerWallets=n;const r=K.getRequestedCaipNetworkIds().join(",");Jt.explorerFilteredWallets=n.filter(i=>i.chains?.some(s=>r.includes(s)))},async fetchFeaturedWallets(){const{featuredWalletIds:t}=_e.state;if(t?.length){const e={...Ze._getSdkProperties(),page:1,entries:t?.length??jJ,include:t},{data:n}=await Ze.fetchWallets(e),r=[...n].sort((s,o)=>t.indexOf(s.id)-t.indexOf(o.id)),i=r.map(s=>s.image_id).filter(Boolean);await Promise.allSettled(i.map(s=>Ze._fetchWalletImage(s))),Jt.featured=r,Jt.allFeatured=r}},async fetchRecommendedWallets(){try{Jt.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:n}=_e.state,r=[...e??[],...n??[]].filter(Boolean),i=K.getRequestedCaipNetworkIds().join(","),s={page:1,entries:jJ,include:t,exclude:r,chains:i},{data:o,count:a}=await Ze.fetchWallets(s),c=Be.getRecentWallets(),l=o.map(u=>u.image_id).filter(Boolean),d=c.map(u=>u.image_id).filter(Boolean);await Promise.allSettled([...l,...d].map(u=>Ze._fetchWalletImage(u))),Jt.recommended=o,Jt.allRecommended=o,Jt.count=a??0}catch{}finally{Jt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:n,featuredWalletIds:r}=_e.state,i=K.getRequestedCaipNetworkIds().join(","),s=[...Jt.recommended.map(({id:u})=>u),...n??[],...r??[]].filter(Boolean),o={page:t,entries:mht,include:e,exclude:s,chains:i},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await Ze.fetchWallets(o);Jt.mobileFilteredOutWalletsLength=l+(Jt.mobileFilteredOutWalletsLength??0);const d=a.slice(0,yht).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>Ze._fetchWalletImage(u))),Jt.wallets=Le.uniqueBy([...Jt.wallets,...Ze._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(h=>i.includes(h))),Jt.count=c>Jt.count?c:Jt.count,Jt.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:n}=await Ze.fetchWallets(e);n&&n.forEach(r=>{Jt.excludedWallets.push({rdns:r.rdns,name:r.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:n,excludeWalletIds:r}=_e.state,i=K.getRequestedCaipNetworkIds().join(",");Jt.search=[];const s={page:1,entries:100,search:t?.trim(),badge_type:e,include:n,exclude:r,chains:i},{data:o}=await Ze.fetchWallets(s);At.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>Ze._fetchWalletImage(c)),Le.wait(300)]),Jt.search=Ze._filterOutExtensions(o)},initPromise(t,e){const n=Jt.promises[t];return n||(Jt.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:n=!0,fetchNetworkImages:r=!0,fetchWalletRanks:i=!0}={}){const s=[t&&Ze.initPromise("connectorImages",Ze.fetchConnectorImages),e&&Ze.initPromise("featuredWallets",Ze.fetchFeaturedWallets),n&&Ze.initPromise("recommendedWallets",Ze.fetchRecommendedWallets),r&&Ze.initPromise("networkImages",Ze.fetchNetworkImages),i&&Ze.initPromise("walletRanks",Ze.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(s)},prefetchAnalyticsConfig(){_e.state.features?.analytics&&Ze.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await aa.get({path:"/getAnalyticsConfig",params:Ze._getSdkProperties()});_e.setFeatures({analytics:t})}catch{_e.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){Jt.featured=Jt.allFeatured,Jt.recommended=Jt.allRecommended;return}const e=K.getRequestedCaipNetworkIds().join(",");Jt.featured=Jt.allFeatured.filter(n=>n.chains?.some(r=>e.includes(r))),Jt.recommended=Jt.allRecommended.filter(n=>n.chains?.some(r=>e.includes(r))),Jt.filteredWallets=Jt.wallets.filter(n=>n.chains?.some(r=>e.includes(r)))},clearFilterByNamespaces(){Jt.filteredWallets=[]},setFilterByNamespace(t){if(!t){Jt.featured=Jt.allFeatured,Jt.recommended=Jt.allRecommended;return}const e=K.getRequestedCaipNetworkIds().join(",");Jt.featured=Jt.allFeatured.filter(n=>n.chains?.some(r=>e.includes(r))),Jt.recommended=Jt.allRecommended.filter(n=>n.chains?.some(r=>e.includes(r))),Jt.filteredWallets=Jt.wallets.filter(n=>n.chains?.some(r=>e.includes(r)))}},Hn=mr({view:"Connect",history:["Connect"],transactionStack:[]}),wht={state:Hn,subscribeKey(t,e){return Qi(Hn,t,e)},pushTransactionStack(t){Hn.transactionStack.push(t)},popTransactionStack(t){const e=Hn.transactionStack.pop();if(!e)return;const{onSuccess:n,onError:r,onCancel:i}=e;switch(t){case"success":n?.();break;case"error":r?.(),$e.goBack();break;case"cancel":i?.(),$e.goBack();break}},push(t,e){t!==Hn.view&&(Hn.view=t,Hn.history.push(t),Hn.data=e)},reset(t,e){Hn.view=t,Hn.history=[t],Hn.data=e},replace(t,e){Hn.history.at(-1)===t||(Hn.view=t,Hn.history[Hn.history.length-1]=t,Hn.data=e)},goBack(){const t=K.state.activeCaipAddress,e=$e.state.view==="ConnectingFarcaster",n=!t&&e;if(Hn.history.length>1){Hn.history.pop();const[r]=Hn.history.slice(-1);r&&(t&&r==="Connect"?Hn.view="Account":Hn.view=r)}else Ht.close();Hn.data?.wallet&&(Hn.data.wallet=void 0),Hn.data?.redirectView&&(Hn.data.redirectView=void 0),setTimeout(()=>{if(n){K.setAccountProp("farcasterUrl",void 0,K.state.activeChain);const r=De.getAuthConnector();r?.provider?.reload();const i=i4(_e.state);r?.provider?.syncDappData?.({metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType})}},100)},goBackToIndex(t){if(Hn.history.length>1){Hn.history=Hn.history.slice(0,t+1);const[e]=Hn.history.slice(-1);e&&(Hn.view=e)}},goBackOrCloseModal(){$e.state.history.length>1?$e.goBack():Ht.close()}},$e=Fa(wht),qh=mr({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),SM={state:qh,subscribe(t){return Xi(qh,()=>t(qh))},setThemeMode(t){qh.themeMode=t;try{const e=De.getAuthConnector();if(e){const n=SM.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:n,w3mThemeVariables:n7(n,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){qh.themeVariables={...qh.themeVariables,...t};try{const e=De.getAuthConnector();if(e){const n=SM.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:n,w3mThemeVariables:n7(qh.themeVariables,qh.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return i4(qh)}},Ls=Fa(SM),tme=Object.fromEntries(Kge.map(t=>[t,void 0])),bht=Object.fromEntries(Kge.map(t=>[t,!0])),Ln=mr({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:tme,filterByNamespaceMap:bht}),vht={state:Ln,subscribe(t){return Xi(Ln,()=>{t(Ln)})},subscribeKey(t,e){return Qi(Ln,t,e)},initialize(t){t.forEach(e=>{const n=Be.getConnectedConnectorId(e);n&&De.setConnectorId(n,e)})},setActiveConnector(t){t&&(Ln.activeConnector=jw(t))},setConnectors(t){t.filter(i=>!Ln.allConnectors.some(s=>s.id===i.id&&De.getConnectorName(s.name)===De.getConnectorName(i.name)&&s.chain===i.chain)).forEach(i=>{i.type!=="MULTI_CHAIN"&&Ln.allConnectors.push(jw(i))});const n=De.getEnabledNamespaces(),r=De.getEnabledConnectors(n);Ln.connectors=De.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(Ln.filterByNamespaceMap).forEach(e=>{Ln.filterByNamespaceMap[e]=!1}),t.forEach(e=>{Ln.filterByNamespaceMap[e]=!0}),De.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){Ln.filterByNamespaceMap[t]=e,De.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=De.getEnabledNamespaces(),e=De.getEnabledConnectors(t),n=De.areAllNamespacesEnabled();Ln.connectors=De.mergeMultiChainConnectors(e),n?Ze.clearFilterByNamespaces():Ze.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(Ln.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return Ln.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(Ln.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=De.generateConnectorMapByName(t),n=[];return e.forEach(r=>{const i=r[0],s=i?.id===Te.CONNECTOR_ID.AUTH;r.length>1&&i?n.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...r],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:i?.id||""}):i&&n.push(i)}),n},generateConnectorMapByName(t){const e=new Map;return t.forEach(n=>{const{name:r}=n,i=De.getConnectorName(r);if(!i)return;const s=e.get(i)||[];s.find(a=>a.chain===n.chain)||s.push(n),e.set(i,s)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(n=>{e.find(r=>r.chain===n.chain)||e.push(n)}),e},addConnector(t){if(t.id===Te.CONNECTOR_ID.AUTH){const e=t,n=i4(_e.state),r=Ls.getSnapshot().themeMode,i=Ls.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),e?.provider?.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:n7(i,r)}),De.setConnectors([t])}else De.setConnectors([t])},getAuthConnector(t){const e=t||K.state.activeChain,n=Ln.connectors.find(r=>r.id===Te.CONNECTOR_ID.AUTH);if(n)return n?.connectors?.length?n.connectors.find(i=>i.chain===e):n},getAnnouncedConnectorRdns(){return Ln.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return Ln.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:n}){const r=n||K.state.activeChain;return Ln.allConnectors.filter(s=>s.chain===r).find(s=>s.explorerId===t||s.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,n=i4(_e.state),r=Ls.getSnapshot().themeMode,i=Ls.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:n.metadata,sdkVersion:n.sdkVersion,sdkType:n.sdkType,projectId:n.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:n7(i,r)})},getConnectorsByNamespace(t){const e=Ln.allConnectors.filter(n=>n.chain===t);return De.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return K.checkIfSmartAccountEnabled()&&wo(t)===lc.ACCOUNT_TYPES.EOA},selectWalletConnector(t){const e=$e.state.data?.redirectView,n=De.getConnector({id:t.id,rdns:t.rdns});rht.handleMobileDeeplinkRedirect(n?.explorerId||t.id,K.state.activeChain),n?$e.push("ConnectingExternal",{connector:n,wallet:t,redirectView:e}):$e.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?De.getConnectorsByNamespace(t):De.mergeMultiChainConnectors(Ln.allConnectors)},setFilterByNamespace(t){Ln.filterByNamespace=t,Ln.connectors=De.getConnectors(t),Ze.setFilterByNamespace(t)},setConnectorId(t,e){t&&(Ln.activeConnectorIds={...Ln.activeConnectorIds,[e]:t},Be.setConnectedConnectorId(e,t))},removeConnectorId(t){Ln.activeConnectorIds={...Ln.activeConnectorIds,[t]:void 0},Be.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return Ln.activeConnectorIds[t]},isConnected(t){return t?!!Ln.activeConnectorIds[t]:Object.values(Ln.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Ln.activeConnectorIds={...tme}}},De=Fa(vht),xht=1e3,xv={checkNamespaceConnectorId(t,e){return De.getConnectorId(t)===e},isSocialProvider(t){return gn.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:n=!0,redirectViewOnModalClose:r="Connect",onOpen:i,onConnect:s}){return new Promise((o,a)=>{if(t&&De.setActiveConnector(e),i?.(Le.isMobile()&&t),r){const l=Ht.subscribeKey("open",d=>{d||($e.state.view!==r&&$e.replace(r),l(),a(new Error("Modal closed")))})}const c=K.subscribeKey("activeCaipAddress",l=>{l&&(s?.(),n&&Ht.close(),c(),o(Bs.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,n)=>{const r=K.subscribeKey("activeCaipAddress",i=>{i&&(Ht.close(),r(),e(Bs.parseCaipAddress(i)))});Ne.connectExternal(t,t.chain).catch(()=>{r(),n(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:n=!0,onOpenFarcaster:r,onConnect:i}){const s=K.getAccountData(e);let o=s?.socialWindow,a=s?.socialProvider,c=!1,l=null;const d=e||K.state.activeChain,u=K.subscribeKey("activeCaipAddress",h=>{h&&(n&&Ht.close(),u())});return new Promise((h,p)=>{async function g(y){if(y.data?.resultUri)if(y.origin===Te.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",g,!1);try{const b=De.getAuthConnector(d);if(b&&!c){const x=K.getAccountData(d);o&&(o.close(),K.setAccountProp("socialWindow",void 0,d),o=x?.socialWindow),c=!0;const v=y.data.resultUri;if(a&&At.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:a}}),a){Be.setConnectedSocialProvider(a),await Ne.connectExternal({id:b.id,type:b.type,socialUri:v},b.chain);const E=K.state.activeCaipAddress;if(!E){p(new Error("Failed to connect"));return}h(Bs.parseCaipAddress(E)),At.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:a}})}}}catch(b){a&&At.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:a,message:Le.parseError(b)}}),p(new Error("Failed to connect"))}}else a&&At.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:a,message:"Untrusted Origin"}})}async function m(){if(t){const y=K.getAccountData(d);K.setAccountProp("socialProvider",t,d),a=y?.socialProvider,At.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:a}})}if(a==="farcaster"){r?.();const y=Ht.subscribeKey("open",x=>{!x&&t==="farcaster"&&(p(new Error("Popup closed")),i?.(),y())}),b=De.getAuthConnector();if(b&&!K.getAccountData(d)?.farcasterUrl)try{const{url:v}=await b.provider.getFarcasterUri();K.setAccountProp("farcasterUrl",v,d)}catch{p(new Error("Failed to connect to farcaster"))}}else{const y=De.getAuthConnector();l=Le.returnOpenHref(`${Te.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(y&&a){const{uri:b}=await y.provider.getSocialRedirectUri({provider:a});if(l&&b){K.setAccountProp("socialWindow",jw(l),d),o=s?.socialWindow,l.location.href=b;const x=setInterval(()=>{o?.closed&&!c&&(p(new Error("Popup closed")),clearInterval(x))},1e3);window.addEventListener("message",g,!1)}else l?.close(),p(new Error("Failed to initiate social connection"))}}catch{p(new Error("Failed to initiate social connection")),l?.close()}}}m()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:n,onConnect:r}){return new Promise((i,s)=>{if(n?.(),e){const a=Ht.subscribeKey("open",c=>{c||($e.state.view!==e&&$e.replace(e),a(),s(new Error("Modal closed")))})}const o=K.subscribeKey("activeCaipAddress",a=>{a&&(r?.(),t&&Ht.close(),o(),i(Bs.parseCaipAddress(a)))})})},async updateEmail(){const t=Be.getConnectedConnectorId(K.state.activeChain),e=De.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==Te.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const n=e.provider.getEmail()??"";return await Ht.open({view:"UpdateEmailWallet",data:{email:n,redirectView:void 0}}),new Promise((r,i)=>{const s=setInterval(()=>{const a=e.provider.getEmail()??"";a!==n&&(Ht.close(),clearInterval(s),o(),r({email:a}))},xht),o=Ht.subscribeKey("open",a=>{a||($e.state.view!=="Connect"&&$e.push("Connect"),clearInterval(s),o(),i(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return K.checkIfSmartAccountEnabled()&&wo(t)===lc.ACCOUNT_TYPES.EOA}};function gF(){const t=K.state.activeCaipNetwork?.chainNamespace||"eip155",e=K.state.activeCaipNetwork?.id||1,n=gn.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${n}`}function wo(t){return K.getAccountData(t)?.preferredAccountType}function x6(t){return K.state.activeCaipNetwork}const i7={getConnectionStatus(t,e){const n=De.state.activeConnectorIds[e],r=Ne.getConnections(e);return!!n&&t.connectorId===n?"connected":r.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:n}){return t.map(r=>{if((e?r.connectorId.toLowerCase()===e.toLowerCase():!1)&&n){const s=r.accounts.filter(o=>!n.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...r,accounts:s}}return r})},excludeExistingConnections(t,e){const n=new Set(t);return e.filter(r=>!n.has(r.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(n=>n.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){const e=!!_e.state.remoteFeatures?.multiWallet,n=De.state.activeConnectorIds[t],r=Ne.getConnections(t),s=(Ne.state.recentConnections.get(t)??[]).filter(a=>De.getConnectorById(a.connectorId)),o=i7.excludeExistingConnections([...r.map(a=>a.connectorId),...n?[n]:[]],s);return e?{connections:r,recentConnections:o}:{connections:r.filter(a=>a.connectorId.toLowerCase()===n?.toLowerCase()),recentConnections:[]}}},Lr=mr({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Eht={state:Lr,subscribe(t){return Xi(Lr,()=>t(Lr))},setLastNetworkInView(t){Lr.lastNetworkInView=t},async fetchTransactions(t){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Lr.loading=!0;try{const e=await Ot.fetchTransactions({account:t,cursor:Lr.next,chainId:K.state.activeCaipNetwork?.caipNetworkId}),n=oC.filterSpamTransactions(e.data),r=oC.filterByConnectedChain(n),i=[...Lr.transactions,...r];Lr.loading=!1,Lr.transactions=i,Lr.transactionsByYear=oC.groupTransactionsByYearAndMonth(Lr.transactionsByYear,r),Lr.empty=i.length===0,Lr.next=e.next?e.next:void 0}catch{const n=K.state.activeChain;At.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:_e.state.projectId,cursor:Lr.next,isSmartAccount:wo(n)===lc.ACCOUNT_TYPES.SMART_ACCOUNT}}),Nn.showError("Failed to fetch transactions"),Lr.loading=!1,Lr.empty=!0,Lr.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const n=t;return e.forEach(r=>{const i=new Date(r.metadata.minedAt).getFullYear(),s=new Date(r.metadata.minedAt).getMonth(),o=n[i]??{},c=(o[s]??[]).filter(l=>l.id!==r.id);n[i]={...o,[s]:[...c,r].sort((l,d)=>new Date(d.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),n},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(r=>r.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=K.state.activeCaipNetwork?.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){Lr.next=void 0},resetTransactions(){Lr.transactions=[],Lr.transactionsByYear={},Lr.lastNetworkInView=void 0,Lr.loading=!1,Lr.empty=!1,Lr.next=void 0}},oC=Fa(Eht,"API_ERROR"),Bn=mr({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let k1;const Cht={state:Bn,subscribe(t){return Xi(Bn,()=>t(Bn))},subscribeKey(t,e){return Qi(Bn,t,e)},_getClient(){return Bn._client},setClient(t){Bn._client=jw(t)},initialize(t){const e=t.filter(n=>!!n.namespace).map(n=>n.namespace);Ne.syncStorageConnections(e)},syncStorageConnections(t){const e=Be.getConnections(),n=t??Array.from(K.state.chains.keys());for(const r of n){const i=e[r]??[],s=new Map(Bn.recentConnections);s.set(r,i),Bn.recentConnections=s}},getConnections(t){return t?Bn.connections.get(t)??[]:[]},hasAnyConnection(t){const e=Ne.state.connections;return Array.from(e.values()).flatMap(n=>n).some(({connectorId:n})=>n===t)},async connectWalletConnect({cache:t="auto"}={}){const e=Le.isTelegram()||Le.isSafari()&&Le.isIos();if(t==="always"||t==="auto"&&e){if(k1){await k1,k1=void 0;return}if(!Le.isPairingExpired(Bn?.wcPairingExpiry)){const n=Bn.wcUri;Bn.wcUri=n;return}k1=Ne._getClient()?.connectWalletConnect?.().catch(()=>{}),Ne.state.status="connecting",await k1,k1=void 0,Bn.wcPairingExpiry=void 0,Ne.state.status="connected"}else await Ne._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,n=!0){const r=await Ne._getClient()?.connectExternal?.(t);return n&&K.setActiveNamespace(e),r},async reconnectExternal(t){await Ne._getClient()?.reconnectExternal?.(t);const e=t.chain||K.state.activeChain;e&&De.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){if(!e)return;Ht.setLoading(!0,K.state.activeChain);const n=De.getAuthConnector();n&&(K.setAccountProp("preferredAccountType",t,e),await n.provider.setPreferredAccount(t),Be.setPreferredAccountTypes(Object.entries(K.state.chains).reduce((r,[i,s])=>{const o=i,a=wo(o);return a!==void 0&&(r[o]=a),r},{})),await Ne.reconnectExternal(n),Ht.setLoading(!1,K.state.activeChain),At.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:K.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return Ne._getClient()?.signMessage(t)},parseUnits(t,e){return Ne._getClient()?.parseUnits(t,e)},formatUnits(t,e){return Ne._getClient()?.formatUnits(t,e)},updateBalance(t){return Ne._getClient()?.updateBalance(t)},async sendTransaction(t){return Ne._getClient()?.sendTransaction(t)},async getCapabilities(t){return Ne._getClient()?.getCapabilities(t)},async grantPermissions(t){return Ne._getClient()?.grantPermissions(t)},async walletGetAssets(t){return Ne._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return Ne._getClient()?.estimateGas(t)},async writeContract(t){return Ne._getClient()?.writeContract(t)},async getEnsAddress(t){return Ne._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return Ne._getClient()?.getEnsAvatar(t)},checkInstalled(t){return Ne._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){Bn.wcUri=void 0,Bn.wcPairingExpiry=void 0,Bn.wcLinking=void 0,Bn.recentWallet=void 0,Bn.status="disconnected",oC.resetTransactions(),Be.deleteWalletConnectDeepLink(),Be.deleteRecentWallet()},resetUri(){Bn.wcUri=void 0,Bn.wcPairingExpiry=void 0,k1=void 0},finalizeWcConnection(t){const{wcLinking:e,recentWallet:n}=Ne.state;e&&Be.setWalletConnectDeepLink(e),n&&Be.setAppKitRecent(n),t&&At.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:$e.state.data?.wallet?.name||"Unknown",view:$e.state.view,walletRank:n?.order}})},setWcBasic(t){Bn.wcBasic=t},setUri(t){Bn.wcUri=t,Bn.wcPairingExpiry=Le.getPairingExpiry()},setWcLinking(t){Bn.wcLinking=t},setWcError(t){Bn.wcError=t,Bn.buffering=!1},setRecentWallet(t){Bn.recentWallet=t},setBuffering(t){Bn.buffering=t},setStatus(t){Bn.status=t},setIsSwitchingConnection(t){Bn.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:n}={}){try{await Ne._getClient()?.disconnect({id:t,chainNamespace:e,initialDisconnect:n})}catch(r){throw new Gp("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},async disconnectConnector({id:t,namespace:e}){try{await Ne._getClient()?.disconnectConnector({id:t,namespace:e})}catch(n){throw new Gp("Failed to disconnect connector","INTERNAL_SDK_ERROR",n)}},setConnections(t,e){const n=new Map(Bn.connections);n.set(e,t),Bn.connections=n},async handleAuthAccountSwitch({address:t,namespace:e}){const r=K.getAccountData(e)?.user?.accounts?.find(s=>s.type==="smartAccount"),i=r&&r.address.toLowerCase()===t.toLowerCase()&&xv.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await Ne.setPreferredAccountType(i,e)},async handleActiveConnection({connection:t,namespace:e,address:n}){const r=De.getConnectorById(t.connectorId),i=t.connectorId===Te.CONNECTOR_ID.AUTH;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);if(i)i&&n&&await Ne.handleAuthAccountSwitch({address:n,namespace:e});else return(await Ne.connectExternal({id:r.id,type:r.type,provider:r.provider,address:n,chain:e},e))?.address;return n},async handleDisconnectedConnection({connection:t,namespace:e,address:n,closeModalOnConnect:r}){const i=De.getConnectorById(t.connectorId),s=t.auth?.name?.toLowerCase(),o=t.connectorId===Te.CONNECTOR_ID.AUTH,a=t.connectorId===Te.CONNECTOR_ID.WALLET_CONNECT;if(!i)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(s&&xv.isSocialProvider(s)){const{address:l}=await xv.connectSocial({social:s,closeModalOnConnect:r,onOpenFarcaster(){Ht.open({view:"ConnectingFarcaster"})},onConnect(){$e.replace("ProfileWallets")}});c=l}else{const{address:l}=await xv.connectEmail({closeModalOnConnect:r,onOpen(){Ht.open({view:"EmailLogin"})},onConnect(){$e.replace("ProfileWallets")}});c=l}else if(a){const{address:l}=await xv.connectWalletConnect({walletConnect:!0,connector:i,closeModalOnConnect:r,onOpen(d){const u=d?"AllWallets":"ConnectingWalletConnect";Ht.state.open?$e.push(u):Ht.open({view:u})},onConnect(){$e.replace("ProfileWallets")}});c=l}else{const l=await Ne.connectExternal({id:i.id,type:i.type,provider:i.provider,chain:e},e);l&&(c=l.address)}return o&&n&&await Ne.handleAuthAccountSwitch({address:n,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:n,closeModalOnConnect:r,onChange:i}){let s;const o=K.getAccountData(n)?.caipAddress;if(o){const{address:c}=Bs.parseCaipAddress(o);s=c}const a=i7.getConnectionStatus(t,n);switch(a){case"connected":case"active":{const c=await Ne.handleActiveConnection({connection:t,namespace:n,address:e});if(s&&c){const l=c.toLowerCase()!==s.toLowerCase();i?.({address:c,namespace:n,hasSwitchedAccount:l,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const c=await Ne.handleDisconnectedConnection({connection:t,namespace:n,address:e,closeModalOnConnect:r});c&&i?.({address:c,namespace:n,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},Ne=Fa(Cht),hT={createBalance(t,e){const n={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:n.name,symbol:n.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:n.value,price:n.price,quantity:{decimals:n.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:n.decimals})},iconUrl:n.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return xs(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const n=e[1],r=parseInt(n,10);return isNaN(r)?"0x0":`0x${r.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>this.isValidAsset(n)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}};let pT;async function DJ(){if(!pT){const{createPublicClient:t,http:e,defineChain:n}=await Promise.resolve().then(()=>U7e);pT={createPublicClient:t,http:e,defineChain:n}}return pT}const $M={getBlockchainApiRpcUrl(t,e){const n=new URL("https://rpc.walletconnect.org/v1/");return n.searchParams.set("chainId",t),n.searchParams.set("projectId",e),n.toString()},async getViemChain(t){const{defineChain:e}=await DJ(),{chainId:n}=Bs.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(n)})},async createViemPublicClient(t){const{createPublicClient:e,http:n}=await DJ(),r=_e.state.projectId,i=await $M.getViemChain(t);if(!i)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:i,transport:n($M.getBlockchainApiRpcUrl(t.caipNetworkId,r))})}},gS={async getMyTokensWithBalance(t){const e=K.getAccountData()?.address,n=K.state.activeCaipNetwork,r=De.getConnectorId("eip155")===Te.CONNECTOR_ID.AUTH;if(!e||!n)return[];const i=`${n.caipNetworkId}:${e}`,s=Be.getBalanceCacheForCaipAddress(i);if(s)return s.balances;if(n.chainNamespace===Te.CHAIN.EVM&&r){const a=await this.getEIP155Balances(e,n);if(a)return this.filterLowQualityTokens(a)}const o=await Ot.getBalance(e,n.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){try{const n=hT.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await Ne.getCapabilities(t))?.[n]?.assetDiscovery?.supported)return null;const i=await Ne.walletGetAssets({account:t,chainFilter:[n]});if(!hT.isWalletGetAssetsResponse(i))return null;const o=(i[n]||[]).map(a=>hT.createBalance(a,e.caipNetworkId));return Be.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:o},timestamp:Date.now()}),o}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:n}){const r=await $M.createViemPublicClient(n),{address:i}=Bs.parseCaipAddress(t),[{result:s},{result:o},{result:a},{result:c}]=await r.multicall({contracts:[{address:e,functionName:"name",args:[],abi:t2},{address:e,functionName:"symbol",args:[],abi:t2},{address:e,functionName:"balanceOf",args:[i],abi:t2},{address:e,functionName:"decimals",args:[],abi:t2}]});return{name:s,symbol:o,decimals:c,balance:a&&c?xs(a,c):"0"}}},ky=mr({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),$p={state:ky,subscribe(t){return Xi(ky,()=>t(ky))},subscribeOpen(t){return Qi(ky,"open",t)},set(t){Object.assign(ky,{...ky,...t})}},Gy={async getTokenList(t){return(await Ot.fetchSwapTokens({chainId:t}))?.tokens?.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){const t=K.state.activeCaipNetwork;if(!t)return null;try{if(t.chainNamespace==="solana"){const e=(await Ne?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:e,fast:e,instant:e}}else return await Ot.fetchGasPrice({chainId:t.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:n,sourceTokenDecimals:r}){const i=await Ot.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(i?.allowance&&n&&r){const s=Ne.parseUnits(n,r)||0;return BigInt(i.allowance)>=s}return!1},async getMyTokensWithBalance(t){const e=await gS.getMyTokensWithBalance(t);return K.setAccountProp("tokenBalance",e,K.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:gF(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]},async handleSwapError(t){try{const e=t?.cause;return e?.json&&(await e.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},In=mr({tokenBalances:[],loading:!1}),Aht={state:In,subscribe(t){return Xi(In,()=>t(In))},subscribeKey(t,e){return Qi(In,t,e)},setToken(t){t&&(In.token=jw(t))},setTokenAmount(t){In.sendTokenAmount=t},setReceiverAddress(t){In.receiverAddress=t},setReceiverProfileImageUrl(t){In.receiverProfileImageUrl=t},setReceiverProfileName(t){In.receiverProfileName=t},setNetworkBalanceInUsd(t){In.networkBalanceInUSD=t},setLoading(t){In.loading=t},getSdkEventProperties(t){return{message:Le.parseError(t),isSmartAccount:wo(K.state.activeChain)===lc.ACCOUNT_TYPES.SMART_ACCOUNT,token:In.token?.symbol||"",amount:In.sendTokenAmount??0,network:K.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(fn.setLoading(!0),K.state.activeCaipNetwork?.chainNamespace){case"eip155":await fn.sendEvmToken();return;case"solana":await fn.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(t){throw Yd.isUserRejectedRequestError(t)?new Jge(t):t}finally{fn.setLoading(!1)}},async sendEvmToken(){const t=K.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=wo(t);if(!fn.state.sendTokenAmount||!fn.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!fn.state.token)throw new Error("A token is required");if(fn.state.token?.address){At.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===lc.ACCOUNT_TYPES.SMART_ACCOUNT,token:fn.state.token.address,amount:fn.state.sendTokenAmount,network:K.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:n}=await fn.sendERC20Token({receiverAddress:fn.state.receiverAddress,tokenAddress:fn.state.token.address,sendTokenAmount:fn.state.sendTokenAmount,decimals:fn.state.token.quantity.decimals});n&&(In.hash=n)}else{At.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===lc.ACCOUNT_TYPES.SMART_ACCOUNT,token:fn.state.token.symbol||"",amount:fn.state.sendTokenAmount,network:K.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:n}=await fn.sendNativeToken({receiverAddress:fn.state.receiverAddress,sendTokenAmount:fn.state.sendTokenAmount,decimals:fn.state.token.quantity.decimals});n&&(In.hash=n)}},async fetchTokenBalance(t){In.loading=!0;const e=K.state.activeChain,n=K.state.activeCaipNetwork?.caipNetworkId,r=K.state.activeCaipNetwork?.chainNamespace,i=K.getAccountData(e)?.caipAddress??K.state.activeCaipAddress,s=i?Le.getPlainAddress(i):void 0;if(In.lastRetry&&!Le.isAllowedRetry(In.lastRetry,30*gn.ONE_SEC_MS))return In.loading=!1,[];try{if(s&&n&&r){const o=await gS.getMyTokensWithBalance();return In.tokenBalances=o,In.lastRetry=void 0,o}}catch(o){In.lastRetry=Date.now(),t?.(o),Nn.showError("Token Balance Unavailable")}finally{In.loading=!1}return[]},fetchNetworkBalance(){if(In.tokenBalances.length===0)return;const t=Gy.mapBalancesToSwapTokens(In.tokenBalances);if(!t)return;const e=t.find(n=>n.address===gF());e&&(In.networkBalanceInUSD=e?Ti.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){$e.pushTransactionStack({});const e=t.receiverAddress,n=K.getAccountData()?.address,r=Ne.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=await Ne.sendTransaction({chainNamespace:Te.CHAIN.EVM,to:e,address:n,data:"0x",value:r??BigInt(0)});return At.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:wo("eip155")===lc.ACCOUNT_TYPES.SMART_ACCOUNT,token:fn.state.token?.symbol||"",amount:t.sendTokenAmount,network:K.state.activeCaipNetwork?.caipNetworkId||"",hash:s||""}}),Ne._getClient()?.updateBalance("eip155"),fn.resetSend(),{hash:s}},async sendERC20Token(t){$e.pushTransactionStack({onSuccess(){$e.replace("Account")}});const e=Ne.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),n=K.getAccountData()?.address;if(n&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const r=Le.getPlainAddress(t.tokenAddress);if(!r)throw new Error("SendController:sendERC20Token - tokenAddress is required");const i=await Ne.writeContract({fromAddress:n,tokenAddress:r,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Lut.getERC20Abi(r),chainNamespace:Te.CHAIN.EVM});return At.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:wo("eip155")===lc.ACCOUNT_TYPES.SMART_ACCOUNT,token:fn.state.token?.symbol||"",amount:t.sendTokenAmount,network:K.state.activeCaipNetwork?.caipNetworkId||"",hash:i||""}}),fn.resetSend(),{hash:i}}return{hash:void 0}},async sendSolanaToken(){if(!fn.state.sendTokenAmount||!fn.state.receiverAddress)throw new Error("An amount and receiver address are required");$e.pushTransactionStack({onSuccess(){$e.replace("Account")}});let t;fn.state.token&&fn.state.token.address!==gn.SOLANA_NATIVE_TOKEN_ADDRESS&&(Le.isCaipAddress(fn.state.token.address)?t=Le.getPlainAddress(fn.state.token.address):t=fn.state.token.address);const e=await Ne.sendTransaction({chainNamespace:"solana",tokenMint:t,to:fn.state.receiverAddress,value:fn.state.sendTokenAmount});e&&(In.hash=e),Ne._getClient()?.updateBalance("solana"),fn.resetSend()},resetSend(){In.token=void 0,In.sendTokenAmount=void 0,In.receiverAddress=void 0,In.receiverProfileImageUrl=void 0,In.receiverProfileName=void 0,In.loading=!1,In.tokenBalances=[]}},fn=Fa(Aht),fT={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},Jx={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},it=mr({chains:Xut(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),nme={state:it,subscribe(t){return Xi(it,()=>{t(it)})},subscribeKey(t,e){return Qi(it,t,e)},subscribeAccountStateProp(t,e,n){const r=n||it.activeChain;return r?Qi(it.chains.get(r)?.accountState||{},t,e):()=>{}},subscribeChainProp(t,e,n){let r;return Xi(it.chains,()=>{const i=n||it.activeChain;if(i){const s=it.chains.get(i)?.[t];r!==s&&(r=s,e(s))}})},initialize(t,e,n){const{chainId:r,namespace:i}=Be.getActiveNetworkProps(),s=e?.find(d=>d.id.toString()===r?.toString()),a=t.find(d=>d?.namespace===i)||t?.[0],c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=_e.state.enableEmbedded?new Set([...c]):new Set([...e?.map(d=>d.chainNamespace)??[]]);(t?.length===0||!a)&&(it.noAdapters=!0),it.noAdapters||(it.activeChain=a?.namespace,it.activeCaipNetwork=s,K.setChainNetworkData(a?.namespace,{caipNetwork:s}),it.activeChain&&$p.set({activeChain:a?.namespace})),l.forEach(d=>{const u=e?.filter(g=>g.chainNamespace===d),h=Be.getPreferredAccountTypes()||{},p={..._e.state.defaultAccountTypes,...h};K.state.chains.set(d,{namespace:d,networkState:mr({...Jx,caipNetwork:u?.[0]}),accountState:mr({...fT,preferredAccountType:p[d]}),caipNetworks:u??[],...n}),K.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){if(it.activeChain===t){const e=Array.from(it.chains.entries()).find(([n])=>n!==t);if(e){const n=e[1]?.caipNetworks?.[0];n&&K.setActiveCaipNetwork(n)}}it.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:n},r){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");it.chains.set(t.namespace,{namespace:t.namespace,networkState:{...Jx,caipNetwork:r[0]},accountState:{...fT},caipNetworks:r,connectionControllerClient:n,networkControllerClient:e}),K.setRequestedCaipNetworks(r?.filter(i=>i.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=it.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];e.caipNetworks?.find(r=>r.id===t.id)||n.push(t),it.chains.set(t.chainNamespace,{...e,caipNetworks:n}),K.setRequestedCaipNetworks(n,t.chainNamespace),De.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const n=it.chains.get(t);if(n){const r=it.activeCaipNetwork?.id===e,i=[...n.caipNetworks?.filter(s=>s.id!==e)||[]];r&&n?.caipNetworks?.[0]&&K.setActiveCaipNetwork(n.caipNetworks[0]),it.chains.set(t,{...n,caipNetworks:i}),K.setRequestedCaipNetworks(i||[],t),i.length===0&&De.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const n=it.chains.get(t);n&&(n.networkState={...n.networkState||Jx,...e},it.chains.set(t,n))},setChainAccountData(t,e,n=!0){if(!t)throw new Error("Chain is required to update chain account data");const r=it.chains.get(t);if(r){const i={...r.accountState||fT,...e};it.chains.set(t,{...r,accountState:i}),(it.chains.size===1||it.activeChain===t)&&e.caipAddress&&(it.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const n=it.chains.get(t);if(n){const r={...n.networkState||Jx,...e};it.chains.set(t,{...n,networkState:r})}},setAccountProp(t,e,n,r=!0){K.setChainAccountData(n,{[t]:e},r)},setActiveNamespace(t){it.activeChain=t;const e=t?it.chains.get(t):void 0,n=e?.networkState?.caipNetwork;n?.id&&t&&(it.activeCaipAddress=e?.accountState?.caipAddress,it.activeCaipNetwork=n,K.setChainNetworkData(t,{caipNetwork:n}),Be.setActiveCaipNetworkId(n?.caipNetworkId),$p.set({activeChain:t,selectedNetworkId:n?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;const e=it.activeChain===t.chainNamespace;e||K.setIsSwitchingNamespace(!0);const n=it.chains.get(t.chainNamespace);it.activeChain=t.chainNamespace,it.activeCaipNetwork=t,K.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let r=n?.accountState?.address;if(r)it.activeCaipAddress=`${t.chainNamespace}:${t.id}:${r}`;else if(e&&it.activeCaipAddress){const{address:s}=Bs.parseCaipAddress(it.activeCaipAddress);r=s,it.activeCaipAddress=`${t.caipNetworkId}:${r}`}else it.activeCaipAddress=void 0;K.setChainAccountData(t.chainNamespace,{address:r,caipAddress:it.activeCaipAddress}),fn.resetSend(),$p.set({activeChain:it.activeChain,selectedNetworkId:it.activeCaipNetwork?.caipNetworkId}),Be.setActiveCaipNetworkId(t.caipNetworkId),!K.checkIfSupportedNetwork(t.chainNamespace)&&_e.state.enableNetworkSwitch&&!_e.state.allowUnsupportedChain&&!Ne.state.wcBasic&&K.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=it.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==K.state.activeChain,n=K.getNetworkData(t)?.caipNetwork,r=K.getCaipNetworkByNamespace(t,n?.id);e&&r&&await K.switchActiveNetwork(r)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){const n=K.state.activeChain;if(!n)throw new Error("ChainController:switchActiveNetwork - namespace is required");const i=!K.state.chains.get(n)?.caipNetworks?.some(o=>o.id===it.activeCaipNetwork?.id),s=K.getNetworkControllerClient(t.chainNamespace);if(s){try{await s.switchCaipNetwork(t),i&&Ht.close()}catch(o){if(e)throw o;$e.goBack()}At.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||it.activeChain;if(!e)throw new Error("ChainController:getNetworkControllerClient - chain is required");const n=it.chains.get(e);if(!n)throw new Error("Chain adapter not found");if(!n.networkControllerClient)throw new Error("NetworkController client not set");return n.networkControllerClient},getConnectionControllerClient(t){const e=t||it.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const n=it.chains.get(e);if(!n?.connectionControllerClient)throw new Error("ConnectionController client not set");return n.connectionControllerClient},getNetworkProp(t,e){const n=it.chains.get(e)?.networkState;if(n)return n[t]},getRequestedCaipNetworks(t){const e=it.chains.get(t),{approvedCaipNetworkIds:n=[],requestedCaipNetworks:r=[]}=e?.networkState||{};return Le.sortRequestedNetworks(n,r).filter(o=>o?.id)},getAllRequestedCaipNetworks(){const t=[];return it.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const n=K.getRequestedCaipNetworks(e.namespace);t.push(...n)}),t},setRequestedCaipNetworks(t,e){K.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=K.getAllRequestedCaipNetworks().map(s=>s.chainNamespace),i=Array.from(new Set(r));De.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return it.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const n=K.getApprovedCaipNetworkIds(e.namespace);t.push(...n)}),t},getActiveCaipNetwork(t){return t?it.chains.get(t)?.networkState?.caipNetwork:it.activeCaipNetwork},getActiveCaipAddress(){return it.activeCaipAddress},getApprovedCaipNetworkIds(t){return it.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const n=await K.getNetworkControllerClient()?.getApprovedCaipNetworksData();K.setAdapterNetworkState(t,{approvedCaipNetworkIds:n?.approvedCaipNetworkIds,supportsAllNetworks:n?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const n=e||it.activeCaipNetwork?.caipNetworkId,r=K.getRequestedCaipNetworks(t);return r.length?r?.some(i=>i.caipNetworkId===n):!0},checkIfSupportedChainId(t){return it.activeChain?K.getRequestedCaipNetworks(it.activeChain)?.some(n=>n.id===t):!0},setSmartAccountEnabledNetworks(t,e){K.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=pF.caipNetworkIdToNumber(it.activeCaipNetwork?.caipNetworkId),e=it.activeChain;return!e||!t?!1:!!K.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},showUnsupportedChainUI(){Ht.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=it.activeCaipNetwork;return!!(t?.chainNamespace&&gn.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){K.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");const n=K.state.chains.get(e)?.accountState?.preferredAccountType,r=_e.state.defaultAccountTypes[e];it.activeCaipAddress=void 0,K.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:r||n,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),De.removeConnectorId(e)},setIsSwitchingNamespace(t){it.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(it.chains.forEach(n=>{Te.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===n.namespace)&&n.namespace&&t.push(n.namespace)}),t.length>0){const n=t[0];return e=n?it.chains.get(n)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){const e=t||it.activeChain;if(e)return K.state.chains.get(e)?.accountState},getNetworkData(t){const e=t||it.activeChain;if(e)return K.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const n=K.state.chains.get(t),r=n?.caipNetworks?.find(i=>i.id===e);return r||n?.networkState?.caipNetwork||n?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=De.state.filterByNamespace;return(t?[it.chains.get(t)]:Array.from(it.chains.values())).flatMap(n=>n?.caipNetworks||[]).map(n=>n.caipNetworkId)},getCaipNetworks(t){return t?K.getRequestedCaipNetworks(t):K.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return nme.getCaipNetworks(e).find(n=>n.id.toString()===t.toString()||n.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){it.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return it.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){const e=K.getAccountData();if(!e)return[];const n=K.state.activeCaipNetwork?.caipNetworkId,r=K.state.activeCaipNetwork?.chainNamespace,i=K.state.activeCaipAddress,s=i?Le.getPlainAddress(i):void 0;if(K.setAccountProp("balanceLoading",!0,r),e.lastRetry&&!Le.isAllowedRetry(e.lastRetry,30*gn.ONE_SEC_MS))return K.setAccountProp("balanceLoading",!1,r),[];try{if(s&&n&&r){const o=await gS.getMyTokensWithBalance();return K.setAccountProp("tokenBalance",o,r),K.setAccountProp("lastRetry",void 0,r),K.setAccountProp("balanceLoading",!1,r),o}}catch(o){K.setAccountProp("lastRetry",Date.now(),r),t?.(o),Nn.showError("Token Balance Unavailable")}finally{K.setAccountProp("balanceLoading",!1,r)}return[]},isCaipNetworkDisabled(t){const e=t.chainNamespace,n=!!K.getAccountData(e)?.caipAddress,r=K.getAllApprovedCaipNetworkIds(),i=K.getNetworkProp("supportsAllNetworks",e)!==!1,s=De.getConnectorId(e),o=De.getAuthConnector(),a=s===Te.CONNECTOR_ID.AUTH&&o;return!n||i||a?!1:!r?.includes(t.caipNetworkId)}},K=Fa(nme),_ht={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const n=K.state.activeCaipNetwork,r=K.state.activeChain,i=$e.state.data;if(t.id===n?.id)return;const o=!!K.getAccountData(r)?.address,a=!!K.getAccountData(t.chainNamespace)?.address,c=t.chainNamespace!==r,d=De.getConnectorId(r)===Te.CONNECTOR_ID.AUTH,u=Te.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(h=>h===t.chainNamespace);e||d&&u?$e.push("SwitchNetwork",{...i,network:t}):o&&c&&!a?$e.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):$e.push("SwitchNetwork",{...i,network:t})}},ca=mr({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Sht={state:ca,subscribe(t){return Xi(ca,()=>t(ca))},subscribeKey(t,e){return Qi(ca,t,e)},async open(t){const e=t?.namespace,n=K.state.activeChain,r=e&&e!==n,i=K.getAccountData(t?.namespace)?.caipAddress,s=K.state.noAdapters;if(Ne.state.wcBasic?Ze.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await Ze.prefetch(),De.setFilterByNamespace(t?.namespace),Ht.setLoading(!0,e),e&&r){const o=K.getNetworkData(e)?.caipNetwork||K.getRequestedCaipNetworks(e)[0];o&&(s?(await K.switchActiveNetwork(o),$e.push("ConnectingWalletConnectBasic")):_ht.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0}))}else _e.state.manualWCControl||s&&!i?Le.isMobile()?$e.reset("AllWallets"):$e.reset("ConnectingWalletConnectBasic"):t?.view?$e.reset(t.view,t.data):i?$e.reset("Account"):$e.reset("Connect");ca.open=!0,$p.set({open:!0}),At.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!i}})},close(){const t=_e.state.enableEmbedded,e=!!K.state.activeCaipAddress;ca.open&&At.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ca.open=!1,$e.reset("Connect"),Ht.clearLoading(),t?e?$e.replace("Account"):$e.push("Connect"):$p.set({open:!1}),Ne.resetUri()},setLoading(t,e){e&&ca.loadingNamespaceMap.set(e,t),ca.loading=t,$p.set({loading:t})},clearLoading(){ca.loadingNamespaceMap.clear(),ca.loading=!1,$p.set({loading:!1})},shake(){ca.shake||(ca.shake=!0,setTimeout(()=>{ca.shake=!1},500))}},Ht=Fa(Sht),s7={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},la=mr({providers:{...s7},providerIds:{...s7}}),Zr={state:la,subscribeKey(t,e){return Qi(la,t,e)},subscribe(t){return Xi(la,()=>{t(la)})},subscribeProviders(t){return Xi(la.providers,()=>t(la.providers))},setProvider(t,e){t&&e&&(la.providers[t]=jw(e))},getProvider(t){if(t)return la.providers[t]},setProviderId(t,e){e&&(la.providerIds[t]=e)},getProviderId(t){if(t)return la.providerIds[t]},reset(){la.providers={...s7},la.providerIds={...s7}},resetChain(t){la.providers[t]=void 0,la.providerIds[t]=void 0}},H6={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},kM={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},$ht={providers:Qge,selectedProvider:null,error:null,purchaseCurrency:H6,paymentCurrency:kM,purchaseCurrencies:[H6],paymentCurrencies:[],quotesLoading:!1},Pn=mr($ht),kht={state:Pn,subscribe(t){return Xi(Pn,()=>t(Pn))},subscribeKey(t,e){return Qi(Pn,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=K.state.activeChain,n=e===Te.CHAIN.SOLANA?"SOL":"USDC",r=e?K.state.chains.get(e)?.accountState?.address??"":"",i=new URL(t.url);i.searchParams.append("publicKey",Qut),i.searchParams.append("destinationCurrencyCode",n),i.searchParams.append("walletAddress",r),i.searchParams.append("externalCustomerId",_e.state.projectId),Pn.selectedProvider={...t,url:i.toString()}}else Pn.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,n=Qge.filter(r=>e.includes(r.name));Pn.providers=n}else Pn.providers=[]},setPurchaseCurrency(t){Pn.purchaseCurrency=t},setPaymentCurrency(t){Pn.paymentCurrency=t},setPurchaseAmount(t){IM.state.purchaseAmount=t},setPaymentAmount(t){IM.state.paymentAmount=t},async getAvailableCurrencies(){const t=await Ot.getOnrampOptions();Pn.purchaseCurrencies=t.purchaseCurrencies,Pn.paymentCurrencies=t.paymentCurrencies,Pn.paymentCurrency=t.paymentCurrencies[0]||kM,Pn.purchaseCurrency=t.purchaseCurrencies[0]||H6,await Ze.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await Ze.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){Pn.quotesLoading=!0;try{const t=await Ot.getOnrampQuote({purchaseCurrency:Pn.purchaseCurrency,paymentCurrency:Pn.paymentCurrency,amount:Pn.paymentAmount?.toString()||"0",network:Pn.purchaseCurrency?.symbol});return Pn.quotesLoading=!1,Pn.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return Pn.error=t.message,Pn.quotesLoading=!1,null}finally{Pn.quotesLoading=!1}},resetState(){Pn.selectedProvider=null,Pn.error=null,Pn.purchaseCurrency=H6,Pn.paymentCurrency=kM,Pn.purchaseCurrencies=[H6],Pn.paymentCurrencies=[],Pn.paymentAmount=void 0,Pn.purchaseAmount=void 0,Pn.quotesLoading=!1}},IM=Fa(kht),Gf={getGasPriceInEther(t,e){const n=e*t;return Number(n)/1e18},getGasPriceInUSD(t,e,n){const r=Gf.getGasPriceInEther(e,n);return Ti.bigNumber(t).times(r).toNumber()},getPriceImpact({sourceTokenAmount:t,sourceTokenPriceInUSD:e,toTokenPriceInUSD:n,toTokenAmount:r}){const i=Ti.bigNumber(t).times(e),s=Ti.bigNumber(r).times(n);return i.minus(s).div(i).times(100).toNumber()},getMaxSlippage(t,e){const n=Ti.bigNumber(t).div(100);return Ti.multiply(e,n).toNumber()},getProviderFee(t,e=.0085){return Ti.bigNumber(t).times(e).toString()},isInsufficientNetworkTokenForGas(t,e){const n=e||"0";return Ti.bigNumber(t).eq(0)?!0:Ti.bigNumber(Ti.bigNumber(n)).gt(t)},isInsufficientSourceTokenForSwap(t,e,n){const r=n?.find(s=>s.address===e)?.quantity?.numeric;return Ti.bigNumber(r||"0").lt(t)}},Sl=mr({message:"",variant:"info",open:!1}),Iht={state:Sl,subscribeKey(t,e){return Qi(Sl,t,e)},open(t,e){const{debug:n}=_e.state,{code:r,displayMessage:i,debugMessage:s}=t;i&&n&&(Sl.message=i,Sl.variant=e,Sl.open=!0),s&&console.error(typeof s=="function"?s():s,r?{code:r}:void 0)},warn(t,e,n){Sl.open=!0,Sl.message=t,Sl.variant="warning",e&&console.warn(e,n)},close(){Sl.open=!1,Sl.message="",Sl.variant="info"}},ds=Fa(Iht),LJ=15e4,Tht=6,co={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,switchingTokens:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:gn.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},be=mr({...co}),aC={state:be,subscribe(t){return Xi(be,()=>t(be))},subscribeKey(t,e){return Qi(be,t,e)},getParams(){const t=K.state.activeChain,e=K.getAccountData(t)?.caipAddress??K.state.activeCaipAddress,n=Le.getPlainAddress(e),r=gF(),i=De.getConnectorId(K.state.activeChain);if(!n)throw new Error("No address found to swap the tokens from.");const s=!be.toToken?.address||!be.toToken?.decimals,o=!be.sourceToken?.address||!be.sourceToken?.decimals||!Ti.bigNumber(be.sourceTokenAmount).gt(0),a=!be.sourceTokenAmount;return{networkAddress:r,fromAddress:n,fromCaipAddress:e,sourceTokenAddress:be.sourceToken?.address,toTokenAddress:be.toToken?.address,toTokenAmount:be.toTokenAmount,toTokenDecimals:be.toToken?.decimals,sourceTokenAmount:be.sourceTokenAmount,sourceTokenDecimals:be.sourceToken?.decimals,invalidToToken:s,invalidSourceToken:o,invalidSourceTokenAmount:a,availableToSwap:e&&!s&&!o&&!a,isAuthConnector:i===Te.CONNECTOR_ID.AUTH}},async setSourceToken(t){if(!t){be.sourceToken=t,be.sourceTokenAmount="",be.sourceTokenPriceInUSD=0;return}be.sourceToken=t,await Bt.setTokenPrice(t.address,"sourceToken")},setSourceTokenAmount(t){be.sourceTokenAmount=t},async setToToken(t){if(!t){be.toToken=t,be.toTokenAmount="",be.toTokenPriceInUSD=0;return}be.toToken=t,await Bt.setTokenPrice(t.address,"toToken")},setToTokenAmount(t){be.toTokenAmount=t?Ti.toFixed(t,Tht):""},async setTokenPrice(t,e){let n=be.tokensPriceMap[t]||0;n||(be.loadingPrices=!0,n=await Bt.getAddressPrice(t)),e==="sourceToken"?be.sourceTokenPriceInUSD=n:e==="toToken"&&(be.toTokenPriceInUSD=n),be.loadingPrices&&(be.loadingPrices=!1),Bt.getParams().availableToSwap&&!be.switchingTokens&&Bt.swapTokens()},async switchTokens(){if(!(be.initializing||!be.initialized||be.switchingTokens)){be.switchingTokens=!0;try{const t=be.toToken?{...be.toToken}:void 0,e=be.sourceToken?{...be.sourceToken}:void 0,n=t&&be.toTokenAmount===""?"1":be.toTokenAmount;Bt.setSourceTokenAmount(n),Bt.setToTokenAmount(""),await Bt.setSourceToken(t),await Bt.setToToken(e),be.switchingTokens=!1,Bt.swapTokens()}catch(t){throw be.switchingTokens=!1,t}}},resetState(){be.myTokensWithBalance=co.myTokensWithBalance,be.tokensPriceMap=co.tokensPriceMap,be.initialized=co.initialized,be.initializing=co.initializing,be.switchingTokens=co.switchingTokens,be.sourceToken=co.sourceToken,be.sourceTokenAmount=co.sourceTokenAmount,be.sourceTokenPriceInUSD=co.sourceTokenPriceInUSD,be.toToken=co.toToken,be.toTokenAmount=co.toTokenAmount,be.toTokenPriceInUSD=co.toTokenPriceInUSD,be.networkPrice=co.networkPrice,be.networkTokenSymbol=co.networkTokenSymbol,be.networkBalanceInUSD=co.networkBalanceInUSD,be.inputError=co.inputError},resetValues(){const{networkAddress:t}=Bt.getParams(),e=be.tokens?.find(n=>n.address===t);Bt.setSourceToken(e),Bt.setToToken(void 0)},getApprovalLoadingState(){return be.loadingApprovalTransaction},clearError(){be.transactionError=void 0},async initializeState(){if(!be.initializing){if(be.initializing=!0,!be.initialized)try{await Bt.fetchTokens(),be.initialized=!0}catch{be.initialized=!1,Nn.showError("Failed to initialize swap"),$e.goBack()}be.initializing=!1}},async fetchTokens(){const{networkAddress:t}=Bt.getParams();await Bt.getNetworkTokenPrice(),await Bt.getMyTokensWithBalance();const e=be.myTokensWithBalance?.find(n=>n.address===t);e&&(be.networkTokenSymbol=e.symbol,Bt.setSourceToken(e),Bt.setSourceTokenAmount("0"))},async getTokenList(){const t=K.state.activeCaipNetwork?.caipNetworkId;if(!(be.caipNetworkId===t&&be.tokens))try{be.tokensLoading=!0;const e=await Gy.getTokenList(t);be.tokens=e,be.caipNetworkId=t,be.popularTokens=e.sort((n,r)=>n.symbol<r.symbol?-1:n.symbol>r.symbol?1:0),be.suggestedTokens=e.filter(n=>!!gn.SWAP_SUGGESTED_TOKENS.includes(n.symbol))}catch{be.tokens=[],be.popularTokens=[],be.suggestedTokens=[]}finally{be.tokensLoading=!1}},async getAddressPrice(t){const e=be.tokensPriceMap[t];if(e)return e;const r=(await Ot.fetchTokenPrice({addresses:[t]}))?.fungibles||[],s=[...be.tokens||[],...be.myTokensWithBalance||[]]?.find(c=>c.address===t)?.symbol,o=r.find(c=>c.symbol.toLowerCase()===s?.toLowerCase())?.price||0,a=parseFloat(o.toString());return be.tokensPriceMap[t]=a,a},async getNetworkTokenPrice(){const{networkAddress:t}=Bt.getParams(),n=(await Ot.fetchTokenPrice({addresses:[t]}).catch(()=>(Nn.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],r=n?.price.toString()||"0";be.tokensPriceMap[t]=parseFloat(r),be.networkTokenSymbol=n?.symbol||"",be.networkPrice=r},async getMyTokensWithBalance(t){const e=await gS.getMyTokensWithBalance(t),n=Gy.mapBalancesToSwapTokens(e);n&&(await Bt.getInitialGasPrice(),Bt.setBalances(n))},setBalances(t){const{networkAddress:e}=Bt.getParams(),n=K.state.activeCaipNetwork;if(!n)return;const r=t.find(i=>i.address===e);t.forEach(i=>{be.tokensPriceMap[i.address]=i.price||0}),be.myTokensWithBalance=t.filter(i=>i.address.startsWith(n.caipNetworkId)),be.networkBalanceInUSD=r?Ti.multiply(r.quantity.numeric,r.price).toString():"0"},async getInitialGasPrice(){const t=await Gy.fetchGasPrice();if(!t)return{gasPrice:null,gasPriceInUSD:null};switch(K.state?.activeCaipNetwork?.chainNamespace){case Te.CHAIN.SOLANA:return be.gasFee=t.standard??"0",be.gasPriceInUSD=Ti.multiply(t.standard,be.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(be.gasFee),gasPriceInUSD:Number(be.gasPriceInUSD)};case Te.CHAIN.EVM:default:const e=t.standard??"0",n=BigInt(e),r=BigInt(LJ),i=Gf.getGasPriceInUSD(be.networkPrice,r,n);return be.gasFee=e,be.gasPriceInUSD=i,{gasPrice:n,gasPriceInUSD:i}}},async swapTokens(){const t=K.getAccountData()?.address,e=be.sourceToken,n=be.toToken,r=Ti.bigNumber(be.sourceTokenAmount).gt(0);if(r||Bt.setToTokenAmount(""),!n||!e||be.loadingPrices||!r||!t)return;be.loadingQuote=!0;const i=Ti.bigNumber(be.sourceTokenAmount).times(10**e.decimals).round(0);try{const s=await Ot.fetchSwapQuote({userAddress:t,from:e.address,to:n.address,gasPrice:be.gasFee,amount:i.toString()});be.loadingQuote=!1;const o=s?.quotes?.[0]?.toAmount;if(!o){ds.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}const a=Ti.bigNumber(o).div(10**n.decimals).toString();Bt.setToTokenAmount(a),Bt.hasInsufficientToken(be.sourceTokenAmount,e.address)?be.inputError="Insufficient balance":(be.inputError=void 0,Bt.setTransactionDetails())}catch(s){const o=await Gy.handleSwapError(s);be.loadingQuote=!1,be.inputError=o||"Insufficient balance"}},async getTransaction(){const{fromCaipAddress:t,availableToSwap:e}=Bt.getParams(),n=be.sourceToken,r=be.toToken;if(!(!t||!e||!n||!r||be.loadingQuote))try{be.loadingBuildTransaction=!0;const i=await Gy.fetchSwapAllowance({userAddress:t,tokenAddress:n.address,sourceTokenAmount:be.sourceTokenAmount,sourceTokenDecimals:n.decimals});let s;return i?s=await Bt.createSwapTransaction():s=await Bt.createAllowanceTransaction(),be.loadingBuildTransaction=!1,be.fetchError=!1,s}catch{$e.goBack(),Nn.showError("Failed to check allowance"),be.loadingBuildTransaction=!1,be.approvalTransaction=void 0,be.swapTransaction=void 0,be.fetchError=!0;return}},async createAllowanceTransaction(){const{fromCaipAddress:t,sourceTokenAddress:e,toTokenAddress:n}=Bt.getParams();if(!(!t||!n)){if(!e)throw new Error("createAllowanceTransaction - No source token address found.");try{const r=await Ot.generateApproveCalldata({from:e,to:n,userAddress:t}),i=Le.getPlainAddress(r.tx.from);if(!i)throw new Error("SwapController:createAllowanceTransaction - address is required");const s={data:r.tx.data,to:i,gasPrice:BigInt(r.tx.eip155.gasPrice),value:BigInt(r.tx.value),toAmount:be.toTokenAmount};return be.swapTransaction=void 0,be.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{$e.goBack(),Nn.showError("Failed to create approval transaction"),be.approvalTransaction=void 0,be.swapTransaction=void 0,be.fetchError=!0;return}}},async createSwapTransaction(){const{networkAddress:t,fromCaipAddress:e,sourceTokenAmount:n}=Bt.getParams(),r=be.sourceToken,i=be.toToken;if(!e||!n||!r||!i)return;const s=Ne.parseUnits(n,r.decimals)?.toString();try{const o=await Ot.generateSwapCalldata({userAddress:e,from:r.address,to:i.address,amount:s,disableEstimate:!0}),a=r.address===t,c=BigInt(o.tx.eip155.gas),l=BigInt(o.tx.eip155.gasPrice),d=Le.getPlainAddress(o.tx.to);if(!d)throw new Error("SwapController:createSwapTransaction - address is required");const u={data:o.tx.data,to:d,gas:c,gasPrice:l,value:BigInt(a?s??"0":"0"),toAmount:be.toTokenAmount};return be.gasPriceInUSD=Gf.getGasPriceInUSD(be.networkPrice,c,l),be.approvalTransaction=void 0,be.swapTransaction=u,u}catch{$e.goBack(),Nn.showError("Failed to create transaction"),be.approvalTransaction=void 0,be.swapTransaction=void 0,be.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){Nn.showLoading("Approve limit increase in your wallet"),$e.replace("SwapPreview")},async sendTransactionForApproval(t){const{fromAddress:e,isAuthConnector:n}=Bt.getParams();be.loadingApprovalTransaction=!0,n?$e.pushTransactionStack({onSuccess:Bt.onEmbeddedWalletApprovalSuccess}):Nn.showLoading("Approve limit increase in your wallet");try{await Ne.sendTransaction({address:e,to:t.to,data:t.data,value:t.value,chainNamespace:Te.CHAIN.EVM}),await Bt.swapTokens(),await Bt.getTransaction(),be.approvalTransaction=void 0,be.loadingApprovalTransaction=!1}catch(i){const s=i;be.transactionError=s?.displayMessage,be.loadingApprovalTransaction=!1,Nn.showError(s?.displayMessage||"Transaction error"),At.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:K.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:Bt.state.sourceToken?.symbol||"",swapToToken:Bt.state.toToken?.symbol||"",swapFromAmount:Bt.state.sourceTokenAmount||"",swapToAmount:Bt.state.toTokenAmount||"",isSmartAccount:wo(Te.CHAIN.EVM)===lc.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(t){if(!t)return;const{fromAddress:e,toTokenAmount:n,isAuthConnector:r}=Bt.getParams();be.loadingTransaction=!0;const i=`Swapping ${be.sourceToken?.symbol} to ${Ti.formatNumberToLocalString(n,3)} ${be.toToken?.symbol}`,s=`Swapped ${be.sourceToken?.symbol} to ${Ti.formatNumberToLocalString(n,3)} ${be.toToken?.symbol}`;r?$e.pushTransactionStack({onSuccess(){$e.replace("Account"),Nn.showLoading(i),aC.resetState()}}):Nn.showLoading("Confirm transaction in your wallet");try{const o=[be.sourceToken?.address,be.toToken?.address].join(","),a=await Ne.sendTransaction({address:e,to:t.to,data:t.data,value:t.value,chainNamespace:Te.CHAIN.EVM});return be.loadingTransaction=!1,Nn.showSuccess(s),At.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:K.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:Bt.state.sourceToken?.symbol||"",swapToToken:Bt.state.toToken?.symbol||"",swapFromAmount:Bt.state.sourceTokenAmount||"",swapToAmount:Bt.state.toTokenAmount||"",isSmartAccount:wo(Te.CHAIN.EVM)===lc.ACCOUNT_TYPES.SMART_ACCOUNT}}),aC.resetState(),r||$e.replace("Account"),aC.getMyTokensWithBalance(o),a}catch(o){const a=o;be.transactionError=a?.displayMessage,be.loadingTransaction=!1,Nn.showError(a?.displayMessage||"Transaction error"),At.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:a?.displayMessage||a?.message||"Unknown",network:K.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:Bt.state.sourceToken?.symbol||"",swapToToken:Bt.state.toToken?.symbol||"",swapFromAmount:Bt.state.sourceTokenAmount||"",swapToAmount:Bt.state.toTokenAmount||"",isSmartAccount:wo(Te.CHAIN.EVM)===lc.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(t,e){return Gf.isInsufficientSourceTokenForSwap(t,e,be.myTokensWithBalance)},setTransactionDetails(){const{toTokenAddress:t,toTokenDecimals:e}=Bt.getParams();!t||!e||(be.gasPriceInUSD=Gf.getGasPriceInUSD(be.networkPrice,BigInt(be.gasFee),BigInt(LJ)),be.priceImpact=Gf.getPriceImpact({sourceTokenAmount:be.sourceTokenAmount,sourceTokenPriceInUSD:be.sourceTokenPriceInUSD,toTokenPriceInUSD:be.toTokenPriceInUSD,toTokenAmount:be.toTokenAmount}),be.maxSlippage=Gf.getMaxSlippage(be.slippage,be.toTokenAmount),be.providerFee=Gf.getProviderFee(be.sourceTokenAmount))}},Bt=Fa(aC),$l=mr({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),Pht={state:$l,subscribe(t){return Xi($l,()=>t($l))},subscribeKey(t,e){return Qi($l,t,e)},showTooltip({message:t,triggerRect:e,variant:n}){$l.open=!0,$l.message=t,$l.triggerRect=e,$l.variant=n},hide(){$l.open=!1,$l.message="",$l.triggerRect={width:0,height:0,top:0,left:0}}},Ev=Fa(Pht),BJ=2147483648,Oht={convertEVMChainIdToCoinType(t){if(t>=BJ)throw new Error("Invalid chainId");return(BJ|t)>>>0}},Oc=mr({suggestions:[],loading:!1}),Nht={state:Oc,subscribe(t){return Xi(Oc,()=>t(Oc))},subscribeKey(t,e){return Qi(Oc,t,e)},async resolveName(t){try{return await Ot.lookupEnsName(t)}catch(e){const n=e;throw new Error(n?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await Ot.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{Oc.loading=!0,Oc.suggestions=[];const e=await Ot.getEnsNameSuggestions(t);return Oc.suggestions=e.suggestions||[],Oc.suggestions}catch(e){const n=V6.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(n)}finally{Oc.loading=!1}},async getNamesForAddress(t){try{if(!K.state.activeCaipNetwork)return[];const n=Be.getEnsFromCacheForAddress(t);if(n)return n;const r=await Ot.reverseLookupEnsName({address:t});return Be.updateEnsCache({address:t,ens:r,timestamp:Date.now()}),r}catch(e){const n=V6.parseEnsApiError(e,"Error fetching names for address");throw new Error(n)}},async registerName(t){const e=K.state.activeCaipNetwork,n=K.getAccountData(e?.chainNamespace)?.address,r=De.getAuthConnector();if(!e)throw new Error("Network not found");if(!n||!r)throw new Error("Address or auth connector not found");Oc.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});$e.pushTransactionStack({onCancel(){$e.replace("RegisterAccountName")}});const s=await Ne.signMessage(i);Oc.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Oht.convertEVMChainIdToCoinType(Number(o));await Ot.registerEnsName({coinType:a,address:n,signature:s,message:i}),K.setAccountProp("profileName",t,e.chainNamespace),Be.updateEnsCache({address:n,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),$e.replace("RegisterAccountNameSuccess")}catch(i){const s=V6.parseEnsApiError(i,`Error registering name ${t}`);throw $e.replace("RegisterAccountName"),new Error(s)}finally{Oc.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},V6=Fa(Nht),Rht={asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"},Mht={asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"};var gT,UJ;function jht(){if(UJ)return gT;UJ=1;const t=U_();gT=i;const e=C().console||{},n={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:g,res:g,err:h};function r(w,_){return Array.isArray(w)?w.filter(function(P){return P!=="!stdSerializers.err"}):w===!0?Object.keys(_):!1}function i(w){w=w||{},w.browser=w.browser||{};const _=w.browser.transmit;if(_&&typeof _.send!="function")throw Error("pino: transmit option must have a send function");const T=w.browser.write||e;w.browser.write&&(w.browser.asObject=!0);const P=w.serializers||{},I=r(w.browser.serialize,P);let M=w.browser.serialize;Array.isArray(w.browser.serialize)&&w.browser.serialize.indexOf("!stdSerializers.err")>-1&&(M=!1);const R=["error","fatal","warn","info","debug","trace"];typeof T=="function"&&(T.error=T.fatal=T.warn=T.info=T.debug=T.trace=T),w.enabled===!1&&(w.level="silent");const O=w.level||"info",S=Object.create(T);S.log||(S.log=y),Object.defineProperty(S,"levelVal",{get:k}),Object.defineProperty(S,"level",{get:L,set:D});const A={transmit:_,serialize:I,asObject:w.browser.asObject,levels:R,timestamp:p(w)};S.levels=i.levels,S.level=O,S.setMaxListeners=S.getMaxListeners=S.emit=S.addListener=S.on=S.prependListener=S.once=S.prependOnceListener=S.removeListener=S.removeAllListeners=S.listeners=S.listenerCount=S.eventNames=S.write=S.flush=y,S.serializers=P,S._serialize=I,S._stdErrSerialize=M,S.child=N,_&&(S._logEvent=u());function k(){return this.level==="silent"?1/0:this.levels.values[this.level]}function L(){return this._level}function D(j){if(j!=="silent"&&!this.levels.values[j])throw Error("unknown level "+j);this._level=j,s(A,S,"error","log"),s(A,S,"fatal","error"),s(A,S,"warn","error"),s(A,S,"info","log"),s(A,S,"debug","log"),s(A,S,"trace","log")}function N(j,F){if(!j)throw new Error("missing bindings for child Pino");F=F||{},I&&j.serializers&&(F.serializers=j.serializers);const z=F.serializers;if(I&&z){var Z=Object.assign({},P,z),V=w.browser.serialize===!0?Object.keys(Z):I;delete j.serializers,c([j],V,Z,this._stdErrSerialize)}function q(Q){this._childLevel=(Q._childLevel|0)+1,this.error=l(Q,j,"error"),this.fatal=l(Q,j,"fatal"),this.warn=l(Q,j,"warn"),this.info=l(Q,j,"info"),this.debug=l(Q,j,"debug"),this.trace=l(Q,j,"trace"),Z&&(this.serializers=Z,this._serialize=V),_&&(this._logEvent=u([].concat(Q._logEvent.bindings,j)))}return q.prototype=this,new q(this)}return S}i.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},i.stdSerializers=n,i.stdTimeFunctions=Object.assign({},{nullTime:b,epochTime:x,unixTime:v,isoTime:E});function s(w,_,T,P){const I=Object.getPrototypeOf(_);_[T]=_.levelVal>_.levels.values[T]?y:I[T]?I[T]:e[T]||e[P]||y,o(w,_,T)}function o(w,_,T){!w.transmit&&_[T]===y||(_[T]=(function(P){return function(){const M=w.timestamp(),R=new Array(arguments.length),O=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var S=0;S<R.length;S++)R[S]=arguments[S];if(w.serialize&&!w.asObject&&c(R,this._serialize,this.serializers,this._stdErrSerialize),w.asObject?P.call(O,a(this,T,R,M)):P.apply(O,R),w.transmit){const A=w.transmit.level||_.level,k=i.levels.values[A],L=i.levels.values[T];if(L<k)return;d(this,{ts:M,methodLevel:T,methodValue:L,transmitValue:i.levels.values[w.transmit.level||_.level],send:w.transmit.send,val:_.levelVal},R)}}})(_[T]))}function a(w,_,T,P){w._serialize&&c(T,w._serialize,w.serializers,w._stdErrSerialize);const I=T.slice();let M=I[0];const R={};P&&(R.time=P),R.level=i.levels.values[_];let O=(w._childLevel|0)+1;if(O<1&&(O=1),M!==null&&typeof M=="object"){for(;O--&&typeof I[0]=="object";)Object.assign(R,I.shift());M=I.length?t(I.shift(),I):void 0}else typeof M=="string"&&(M=t(I.shift(),I));return M!==void 0&&(R.msg=M),R}function c(w,_,T,P){for(const I in w)if(P&&w[I]instanceof Error)w[I]=i.stdSerializers.err(w[I]);else if(typeof w[I]=="object"&&!Array.isArray(w[I]))for(const M in w[I])_&&_.indexOf(M)>-1&&M in T&&(w[I][M]=T[M](w[I][M]))}function l(w,_,T){return function(){const P=new Array(1+arguments.length);P[0]=_;for(var I=1;I<P.length;I++)P[I]=arguments[I-1];return w[T].apply(this,P)}}function d(w,_,T){const P=_.send,I=_.ts,M=_.methodLevel,R=_.methodValue,O=_.val,S=w._logEvent.bindings;c(T,w._serialize||Object.keys(w.serializers),w.serializers,w._stdErrSerialize===void 0?!0:w._stdErrSerialize),w._logEvent.ts=I,w._logEvent.messages=T.filter(function(A){return S.indexOf(A)===-1}),w._logEvent.level.label=M,w._logEvent.level.value=R,P(M,w._logEvent,O),w._logEvent=u(S)}function u(w){return{ts:0,messages:[],bindings:w||[],level:{label:"",value:0}}}function h(w){const _={type:w.constructor.name,msg:w.message,stack:w.stack};for(const T in w)_[T]===void 0&&(_[T]=w[T]);return _}function p(w){return typeof w.timestamp=="function"?w.timestamp:w.timestamp===!1?b:x}function g(){return{}}function m(w){return w}function y(){}function b(){return!1}function x(){return Date.now()}function v(){return Math.round(Date.now()/1e3)}function E(){return new Date(Date.now()).toISOString()}function C(){function w(_){return typeof _<"u"&&_}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return w(self)||w(window)||w(this)||{}}}return gT}jht();let I1=null;const Ca={getSIWX(){return _e.state.siwx},async initializeIfEnabled(t=K.getActiveCaipAddress()){const e=_e.state.siwx;if(!(e&&t))return;const[n,r,i]=t.split(":");if(K.checkIfSupportedNetwork(n,`${n}:${r}`))try{if(_e.state.remoteFeatures?.emailCapture){const o=K.getAccountData(n)?.user;await Ht.open({view:"DataCapture",data:{email:o?.email??void 0}});return}if(I1&&await I1,(await e.getSessions(`${n}:${r}`,i)).length)return;await Ht.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),At.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(s)}),await Ne._getClient()?.disconnect().catch(console.error),$e.reset("Connect"),Nn.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=_e.state.siwx,e=Le.getPlainAddress(K.getActiveCaipAddress()),n=x6(),r=Ne._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!n)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:n.caipNetworkId,accountAddress:e}),s=i.toString();De.getConnectorId(n.chainNamespace)===Te.CONNECTOR_ID.AUTH&&$e.pushTransactionStack({});const a=await r.signMessage(s);await t.addSession({data:i,message:s,signature:a}),K.setLastConnectedSIWECaipNetwork(n),Ht.close(),At.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){(!Ht.state.open||$e.state.view==="ApproveTransaction")&&await Ht.open({view:"SIWXSignMessage"}),Nn.showError("Error signing message"),At.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(i)}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){try{const t=this.getSIWX();if(t?.getRequired?.()){const n=K.getLastConnectedSIWECaipNetwork();if(n){const r=await t?.getSessions(n?.caipNetworkId,Le.getPlainAddress(K.getActiveCaipAddress())||"");r&&r.length>0?await K.switchActiveNetwork(n):await Ne.disconnect()}else await Ne.disconnect()}else Ht.close();Ht.close(),At.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getAllSessions(){const t=this.getSIWX(),e=K.getAllRequestedCaipNetworks(),n=[];return await Promise.all(e.map(async r=>{const i=await t?.getSessions(r.caipNetworkId,Le.getPlainAddress(K.getActiveCaipAddress())||"");i&&n.push(...i)})),n},async getSessions(t){const e=_e.state.siwx;let n=t?.address;if(!n){const i=K.getActiveCaipAddress();n=Le.getPlainAddress(i)}let r=t?.caipNetworkId;return r||(r=K.getActiveCaipNetwork()?.caipNetworkId),e&&n&&r?e.getSessions(r,n):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=$e.state.view==="ApproveTransaction",n=$e.state.view==="SIWXSignMessage";if(e||n)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:n,preferredAccountType:r,chainNamespace:i}){const s=Ca.getSIWX(),o=x6();if(!s||!i.includes(Te.CHAIN.EVM)||_e.state.remoteFeatures?.emailCapture){const u=await t.connect({chainId:e,socialUri:n,preferredAccountType:r});return{address:u.address,chainId:u.chainId,accounts:u.accounts}}const a=`${i}:${e}`,c=await s.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await t.connect({chainId:e,socialUri:n,siwxMessage:l,preferredAccountType:r});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await Ca.addEmbeddedWalletSession(l,d.message,d.signature),K.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,n){if(I1)return I1;const r=Ca.getSIWX();return r?(I1=r.addSession({data:t,message:e,signature:n}).finally(()=>{I1=null}),I1):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:n}){const r=Ca.getSIWX(),i=x6(),s=new Set(e.map(l=>l.split(":")[0]));if(!r||s.size!==1||!s.has("eip155"))return!1;const o=await r.createMessage({chainId:x6()?.caipNetworkId||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:n,chains:[o.chainId,...e.filter(l=>l!==o.chainId)]});Nn.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if(K.setAccountProp("connectedWalletInfo",c,Array.from(s)[0]),a?.auths?.length){const l=a.auths.map(d=>{const u=t.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud,version:d.p.version||o.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:u,signature:d.s.s,cacao:d}});try{await r.setSessions(l),i&&K.setLastConnectedSIWECaipNetwork(i),At.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Ca.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),At.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Ca.getSIWXEventProperties(d)}),await t.disconnect().catch(console.error),d}finally{Nn.hide()}}return!0},getSIWXEventProperties(t){const e=K.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:K.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:wo(e)===lc.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?Le.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}},rme={isUnsupportedChainView(){return $e.state.view==="UnsupportedChain"||$e.state.view==="SwitchNetwork"&&$e.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){Ht.shake();return}if(await Ca.isSIWXCloseDisabled()){Ht.shake();return}($e.state.view==="DataCapture"||$e.state.view==="DataCaptureOtpConfirm")&&Ne.disconnect(),Ht.close()}};var mT,FJ;function Dht(){if(FJ)return mT;FJ=1;const t=U_();mT=i;const e=C().console||{},n={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:g,res:g,err:h};function r(w,_){return Array.isArray(w)?w.filter(function(P){return P!=="!stdSerializers.err"}):w===!0?Object.keys(_):!1}function i(w){w=w||{},w.browser=w.browser||{};const _=w.browser.transmit;if(_&&typeof _.send!="function")throw Error("pino: transmit option must have a send function");const T=w.browser.write||e;w.browser.write&&(w.browser.asObject=!0);const P=w.serializers||{},I=r(w.browser.serialize,P);let M=w.browser.serialize;Array.isArray(w.browser.serialize)&&w.browser.serialize.indexOf("!stdSerializers.err")>-1&&(M=!1);const R=["error","fatal","warn","info","debug","trace"];typeof T=="function"&&(T.error=T.fatal=T.warn=T.info=T.debug=T.trace=T),w.enabled===!1&&(w.level="silent");const O=w.level||"info",S=Object.create(T);S.log||(S.log=y),Object.defineProperty(S,"levelVal",{get:k}),Object.defineProperty(S,"level",{get:L,set:D});const A={transmit:_,serialize:I,asObject:w.browser.asObject,levels:R,timestamp:p(w)};S.levels=i.levels,S.level=O,S.setMaxListeners=S.getMaxListeners=S.emit=S.addListener=S.on=S.prependListener=S.once=S.prependOnceListener=S.removeListener=S.removeAllListeners=S.listeners=S.listenerCount=S.eventNames=S.write=S.flush=y,S.serializers=P,S._serialize=I,S._stdErrSerialize=M,S.child=N,_&&(S._logEvent=u());function k(){return this.level==="silent"?1/0:this.levels.values[this.level]}function L(){return this._level}function D(j){if(j!=="silent"&&!this.levels.values[j])throw Error("unknown level "+j);this._level=j,s(A,S,"error","log"),s(A,S,"fatal","error"),s(A,S,"warn","error"),s(A,S,"info","log"),s(A,S,"debug","log"),s(A,S,"trace","log")}function N(j,F){if(!j)throw new Error("missing bindings for child Pino");F=F||{},I&&j.serializers&&(F.serializers=j.serializers);const z=F.serializers;if(I&&z){var Z=Object.assign({},P,z),V=w.browser.serialize===!0?Object.keys(Z):I;delete j.serializers,c([j],V,Z,this._stdErrSerialize)}function q(Q){this._childLevel=(Q._childLevel|0)+1,this.error=l(Q,j,"error"),this.fatal=l(Q,j,"fatal"),this.warn=l(Q,j,"warn"),this.info=l(Q,j,"info"),this.debug=l(Q,j,"debug"),this.trace=l(Q,j,"trace"),Z&&(this.serializers=Z,this._serialize=V),_&&(this._logEvent=u([].concat(Q._logEvent.bindings,j)))}return q.prototype=this,new q(this)}return S}i.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},i.stdSerializers=n,i.stdTimeFunctions=Object.assign({},{nullTime:b,epochTime:x,unixTime:v,isoTime:E});function s(w,_,T,P){const I=Object.getPrototypeOf(_);_[T]=_.levelVal>_.levels.values[T]?y:I[T]?I[T]:e[T]||e[P]||y,o(w,_,T)}function o(w,_,T){!w.transmit&&_[T]===y||(_[T]=(function(P){return function(){const M=w.timestamp(),R=new Array(arguments.length),O=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var S=0;S<R.length;S++)R[S]=arguments[S];if(w.serialize&&!w.asObject&&c(R,this._serialize,this.serializers,this._stdErrSerialize),w.asObject?P.call(O,a(this,T,R,M)):P.apply(O,R),w.transmit){const A=w.transmit.level||_.level,k=i.levels.values[A],L=i.levels.values[T];if(L<k)return;d(this,{ts:M,methodLevel:T,methodValue:L,transmitValue:i.levels.values[w.transmit.level||_.level],send:w.transmit.send,val:_.levelVal},R)}}})(_[T]))}function a(w,_,T,P){w._serialize&&c(T,w._serialize,w.serializers,w._stdErrSerialize);const I=T.slice();let M=I[0];const R={};P&&(R.time=P),R.level=i.levels.values[_];let O=(w._childLevel|0)+1;if(O<1&&(O=1),M!==null&&typeof M=="object"){for(;O--&&typeof I[0]=="object";)Object.assign(R,I.shift());M=I.length?t(I.shift(),I):void 0}else typeof M=="string"&&(M=t(I.shift(),I));return M!==void 0&&(R.msg=M),R}function c(w,_,T,P){for(const I in w)if(P&&w[I]instanceof Error)w[I]=i.stdSerializers.err(w[I]);else if(typeof w[I]=="object"&&!Array.isArray(w[I]))for(const M in w[I])_&&_.indexOf(M)>-1&&M in T&&(w[I][M]=T[M](w[I][M]))}function l(w,_,T){return function(){const P=new Array(1+arguments.length);P[0]=_;for(var I=1;I<P.length;I++)P[I]=arguments[I-1];return w[T].apply(this,P)}}function d(w,_,T){const P=_.send,I=_.ts,M=_.methodLevel,R=_.methodValue,O=_.val,S=w._logEvent.bindings;c(T,w._serialize||Object.keys(w.serializers),w.serializers,w._stdErrSerialize===void 0?!0:w._stdErrSerialize),w._logEvent.ts=I,w._logEvent.messages=T.filter(function(A){return S.indexOf(A)===-1}),w._logEvent.level.label=M,w._logEvent.level.value=R,P(M,w._logEvent,O),w._logEvent=u(S)}function u(w){return{ts:0,messages:[],bindings:w||[],level:{label:"",value:0}}}function h(w){const _={type:w.constructor.name,msg:w.message,stack:w.stack};for(const T in w)_[T]===void 0&&(_[T]=w[T]);return _}function p(w){return typeof w.timestamp=="function"?w.timestamp:w.timestamp===!1?b:x}function g(){return{}}function m(w){return w}function y(){}function b(){return!1}function x(){return Date.now()}function v(){return Math.round(Date.now()/1e3)}function E(){return new Date(Date.now()).toISOString()}function C(){function w(_){return typeof _<"u"&&_}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return w(self)||w(window)||w(this)||{}}}return mT}var Yy=Dht();const _8=gl(Yy),Lht={level:"info"},S8="custom_context",mF=1e3*1024;let Bht=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},zJ=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new Bht(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}},ime=class{constructor(e,n=mF){this.level=e??"error",this.levelValue=Yy.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new zJ(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===Yy.levels.values.error?console.error(e):n===Yy.levels.values.warn?console.warn(e):n===Yy.levels.values.debug?console.debug(e):n===Yy.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Oa({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new zJ(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Oa({extraMetadata:e})),new Blob(n,{type:"application/json"})}},Uht=class{constructor(e,n=mF){this.baseChunkLogger=new ime(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}},Fht=class{constructor(e,n=mF){this.baseChunkLogger=new ime(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var zht=Object.defineProperty,Wht=Object.defineProperties,Hht=Object.getOwnPropertyDescriptors,WJ=Object.getOwnPropertySymbols,Vht=Object.prototype.hasOwnProperty,qht=Object.prototype.propertyIsEnumerable,HJ=(t,e,n)=>e in t?zht(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,o7=(t,e)=>{for(var n in e||(e={}))Vht.call(e,n)&&HJ(t,n,e[n]);if(WJ)for(var n of WJ(e))qht.call(e,n)&&HJ(t,n,e[n]);return t},a7=(t,e)=>Wht(t,Hht(e));function mS(t){return a7(o7({},t),{level:t?.level||Lht.level})}function Zht(t,e=S8){return t[e]||""}function Kht(t,e,n=S8){return t[n]=e,t}function za(t,e=S8){let n="";return typeof t.bindings>"u"?n=Zht(t,e):n=t.bindings().context||"",n}function Ght(t,e,n=S8){const r=za(t,n);return r.trim()?`${r}/${e}`:e}function Qo(t,e,n=S8){const r=Ght(t,e,n),i=t.child({context:r});return Kht(i,r,n)}function Yht(t){var e,n;const r=new Uht((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:_8(a7(o7({},t.opts),{level:"trace",browser:a7(o7({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Jht(t){var e;const n=new Fht((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:_8(a7(o7({},t.opts),{level:"trace"}),n),chunkLoggerController:n}}function Xht(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Yht(t):Jht(t)}var Qht=Object.defineProperty,ept=(t,e,n)=>e in t?Qht(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,VJ=(t,e,n)=>ept(t,typeof e!="symbol"?e+"":e,n);let tpt=class extends xc{constructor(e){super(),this.opts=e,VJ(this,"protocol","wc"),VJ(this,"version",2)}};var npt=Object.defineProperty,rpt=(t,e,n)=>e in t?npt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ipt=(t,e,n)=>rpt(t,e+"",n);let spt=class extends xc{constructor(e,n){super(),this.core=e,this.logger=n,ipt(this,"records",new Map)}},opt=class{constructor(e,n){this.logger=e,this.core=n}},apt=class extends xc{constructor(e,n){super(),this.relayer=e,this.logger=n}},cpt=class extends xc{constructor(e){super()}},lpt=class{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}},dpt=class extends xc{constructor(e,n){super(),this.relayer=e,this.logger=n}},upt=class extends xc{constructor(e,n){super(),this.core=e,this.logger=n}},hpt=class{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}},ppt=class{constructor(e,n){this.projectId=e,this.logger=n}},fpt=class{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}};var gpt=Object.defineProperty,mpt=(t,e,n)=>e in t?gpt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qJ=(t,e,n)=>mpt(t,typeof e!="symbol"?e+"":e,n);let ypt=class{constructor(e){this.opts=e,qJ(this,"protocol","wc"),qJ(this,"version",2)}},wpt=class{constructor(e){this.client=e}};function s4(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function TM(t){return s4(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const sme="2.36.0";let yT={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${sme}`},yS=class PM extends Error{constructor(e,n={}){const r=n.cause instanceof PM?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof PM&&n.cause.docsPath||n.docsPath,s=yT.getDocsUrl?.({...n,docsPath:i}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...yT.version?[`Version: ${yT.version}`]:[]].join(`
|
|
422
422
|
`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=sme}walk(e){return ome(this,e)}};function ome(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?ome(t.cause,e):e?null:t}let ame=class extends yS{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}};function Pb(t,{dir:e,size:n=32}={}){return typeof t=="string"?bpt(t,{dir:e,size:n}):vpt(t,{dir:e,size:n})}function bpt(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new ame({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function vpt(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new ame({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s=e==="right";r[s?i:n-i-1]=t[s?i:t.length-i-1]}return r}let xpt=class extends yS{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${n} to ${e})`:`(above ${n})`}`,{name:"IntegerOutOfRangeError"})}},Ept=class extends yS{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed ${n} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Ob(t,{size:e}){if(TM(t)>e)throw new Ept({givenSize:TM(t),maxSize:e})}function OM(t,e={}){const{signed:n}=e;e.size&&Ob(t,{size:e.size});const r=BigInt(t);if(!n)return r;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return r<=s?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Cpt(t,e={}){return Number(OM(t,e))}const Apt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function NM(t,e={}){return typeof t=="number"||typeof t=="bigint"?lme(t,e):typeof t=="string"?$pt(t,e):typeof t=="boolean"?_pt(t,e):cme(t,e)}function _pt(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Ob(n,{size:e.size}),Pb(n,{size:e.size})):n}function cme(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=Apt[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(Ob(r,{size:e.size}),Pb(r,{dir:"right",size:e.size})):r}function lme(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new xpt({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:n,size:r,value:`${t}${c}`})}const a=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Pb(a,{size:r}):a}const Spt=new TextEncoder;function $pt(t,e={}){const n=Spt.encode(t);return cme(n,e)}const kpt=new TextEncoder;function Ipt(t,e={}){return typeof t=="number"||typeof t=="bigint"?Ppt(t,e):typeof t=="boolean"?Tpt(t,e):s4(t)?dme(t,e):ume(t,e)}function Tpt(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),typeof e.size=="number"?(Ob(n,{size:e.size}),Pb(n,{size:e.size})):n}const Zh={zero:48,nine:57,A:65,F:70,a:97,f:102};function ZJ(t){if(t>=Zh.zero&&t<=Zh.nine)return t-Zh.zero;if(t>=Zh.A&&t<=Zh.F)return t-(Zh.A-10);if(t>=Zh.a&&t<=Zh.f)return t-(Zh.a-10)}function dme(t,e={}){let n=t;e.size&&(Ob(n,{size:e.size}),n=Pb(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=ZJ(r.charCodeAt(a++)),l=ZJ(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new yS(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);s[o]=c*16+l}return s}function Ppt(t,e){const n=lme(t,e);return dme(n)}function ume(t,e={}){const n=kpt.encode(t);return typeof e.size=="number"?(Ob(n,{size:e.size}),Pb(n,{dir:"right",size:e.size})):n}const Xx=BigInt(2**32-1),KJ=BigInt(32);function Opt(t,e=!1){return e?{h:Number(t&Xx),l:Number(t>>KJ&Xx)}:{h:Number(t>>KJ&Xx)|0,l:Number(t&Xx)|0}}function Npt(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Opt(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Rpt=(t,e,n)=>t<<n|e>>>32-n,Mpt=(t,e,n)=>e<<n|t>>>32-n,jpt=(t,e,n)=>e<<n-32|t>>>64-n,Dpt=(t,e,n)=>t<<n-32|e>>>64-n,Iy=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function wS(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function o4(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Yp(t,...e){if(!wS(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function hme(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");o4(t.outputLen),o4(t.blockLen)}function Dw(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function pme(t,e){Yp(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Lpt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Lw(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function wT(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pd(t,e){return t<<32-e|t>>>e}const Bpt=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Upt(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Fpt(t){for(let e=0;e<t.length;e++)t[e]=Upt(t[e]);return t}const GJ=Bpt?t=>t:Fpt,fme=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zpt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function O2(t){if(Yp(t),fme)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=zpt[t[n]];return e}const Kh={_0:48,_9:57,A:65,F:70,a:97,f:102};function YJ(t){if(t>=Kh._0&&t<=Kh._9)return t-Kh._0;if(t>=Kh.A&&t<=Kh.F)return t-(Kh.A-10);if(t>=Kh.a&&t<=Kh.f)return t-(Kh.a-10)}function c7(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(fme)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=YJ(t.charCodeAt(s)),a=YJ(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Wpt(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bS(t){return typeof t=="string"&&(t=Wpt(t)),Yp(t),t}function h0(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Yp(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}let yF=class{};function gme(t){const e=r=>t().update(bS(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mme(t=32){if(Iy&&typeof Iy.getRandomValues=="function")return Iy.getRandomValues(new Uint8Array(t));if(Iy&&typeof Iy.randomBytes=="function")return Uint8Array.from(Iy.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Hpt=BigInt(0),Cv=BigInt(1),Vpt=BigInt(2),qpt=BigInt(7),Zpt=BigInt(256),Kpt=BigInt(113),yme=[],wme=[],bme=[];for(let t=0,e=Cv,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],yme.push(2*(5*r+n)),wme.push((t+1)*(t+2)/2%64);let i=Hpt;for(let s=0;s<7;s++)e=(e<<Cv^(e>>qpt)*Kpt)%Zpt,e&Vpt&&(i^=Cv<<(Cv<<BigInt(s))-Cv);bme.push(i)}const vme=Npt(bme,!0),Gpt=vme[0],Ypt=vme[1],JJ=(t,e,n)=>n>32?jpt(t,e,n):Rpt(t,e,n),XJ=(t,e,n)=>n>32?Dpt(t,e,n):Mpt(t,e,n);function Jpt(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],d=n[c+1],u=JJ(l,d,1)^n[a],h=XJ(l,d,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=wme[o],c=JJ(i,s,a),l=XJ(i,s,a),d=yme[o];i=t[d],s=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Gpt[r],t[1]^=Ypt[r]}Lw(n)}class wF extends yF{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,o4(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Lpt(this.state)}clone(){return this._cloneInto()}keccak(){GJ(this.state32),Jpt(this.state32,this.rounds),GJ(this.state32),this.posOut=0,this.pos=0}update(e){Dw(this),e=bS(e),Yp(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Dw(this,!1),Yp(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return o4(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(pme(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Lw(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new wF(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Xpt=(t,e,n)=>gme(()=>new wF(e,t,n)),Qpt=Xpt(1,136,256/8);function xme(t,e){const n=e||"hex",r=Qpt(s4(t,{strict:!1})?Ipt(t):t);return n==="bytes"?r:NM(r)}class eft extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const bT=new eft(8192);function tft(t,e){if(bT.has(`${t}.${e}`))return bT.get(`${t}.${e}`);const n=t.substring(2).toLowerCase(),r=xme(ume(n),"bytes"),i=n.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return bT.set(`${t}.${e}`,s),s}function nft(t){const e=xme(`0x${t.substring(4)}`).substring(26);return tft(`0x${e}`)}async function rft({hash:t,signature:e}){const n=s4(t)?t:NM(t),{secp256k1:r}=await Promise.resolve().then(()=>Hft);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:d,v:u,yParity:h}=e,p=Number(h??u),g=QJ(p);return new r.Signature(OM(l),OM(d)).addRecoveryBit(g)}const o=s4(e)?e:NM(e);if(TM(o)!==65)throw new Error("invalid signature length");const a=Cpt(`0x${o.slice(130)}`),c=QJ(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function QJ(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function ift({hash:t,signature:e}){return nft(await rft({hash:t,signature:e}))}function sft(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function oft(t,e,n){return t&e^~t&n}function aft(t,e,n){return t&e^t&n^e&n}let cft=class extends yF{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=wT(this.buffer)}update(e){Dw(this),e=bS(e),Yp(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=wT(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Dw(this),pme(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Lw(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;sft(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=wT(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Of=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lft=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Nf=new Uint32Array(64);let dft=class extends cft{constructor(e=32){super(64,e,8,!1),this.A=Of[0]|0,this.B=Of[1]|0,this.C=Of[2]|0,this.D=Of[3]|0,this.E=Of[4]|0,this.F=Of[5]|0,this.G=Of[6]|0,this.H=Of[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)Nf[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const h=Nf[u-15],p=Nf[u-2],g=Pd(h,7)^Pd(h,18)^h>>>3,m=Pd(p,17)^Pd(p,19)^p>>>10;Nf[u]=m+Nf[u-7]+g+Nf[u-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=Pd(a,6)^Pd(a,11)^Pd(a,25),p=d+h+oft(a,c,l)+lft[u]+Nf[u]|0,m=(Pd(r,2)^Pd(r,13)^Pd(r,22))+aft(r,i,s)|0;d=l,l=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+m|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,i,s,o,a,c,l,d)}roundClean(){Lw(Nf)}destroy(){this.set(0,0,0,0,0,0,0,0),Lw(this.buffer)}};const uft=gme(()=>new dft);let Eme=class extends yF{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,hme(e);const r=bS(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Lw(s)}update(e){return Dw(this),this.iHash.update(e),this}digestInto(e){Dw(this),Yp(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Cme=(t,e,n)=>new Eme(t,e).update(n).digest();Cme.create=(t,e)=>new Eme(t,e);const bF=BigInt(0),RM=BigInt(1);function l7(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function hg(t,e,n=""){const r=wS(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qx(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ame(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?bF:BigInt("0x"+t)}function vS(t){return Ame(O2(t))}function _me(t){return Yp(t),Ame(O2(Uint8Array.from(t).reverse()))}function vF(t,e){return c7(t.toString(16).padStart(e*2,"0"))}function Sme(t,e){return vF(t,e).reverse()}function ma(t,e,n){let r;if(typeof e=="string")try{r=c7(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(wS(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");return r.length,r}const vT=t=>typeof t=="bigint"&&bF<=t;function hft(t,e,n){return vT(t)&&vT(e)&&vT(n)&&e<=t&&t<n}function pft(t,e,n,r){if(!hft(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $me(t){let e;for(e=0;t>bF;t>>=RM,e+=1);return e}const $8=t=>(RM<<BigInt(t))-RM;function fft(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=p=>new Uint8Array(p),i=p=>Uint8Array.of(p);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...p)=>n(o,s,...p),d=(p=r(0))=>{o=l(i(0),p),s=l(),p.length!==0&&(o=l(i(1),p),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<e;){s=l();const m=s.slice();g.push(m),p+=s.length}return h0(...g)};return(p,g)=>{c(),d(p);let m;for(;!(m=g(u()));)d();return c(),m}}function xF(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function eX(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const $a=BigInt(0),Ho=BigInt(1),pg=BigInt(2),kme=BigInt(3),Ime=BigInt(4),Tme=BigInt(5),gft=BigInt(7),Pme=BigInt(8),mft=BigInt(9),Ome=BigInt(16);function Dl(t,e){const n=t%e;return n>=$a?n:e+n}function Nc(t,e,n){let r=t;for(;e-- >$a;)r*=r,r%=n;return r}function tX(t,e){if(t===$a)throw new Error("invert: expected non-zero number");if(e<=$a)throw new Error("invert: expected positive modulus, got "+e);let n=Dl(t,e),r=e,i=$a,s=Ho;for(;n!==$a;){const a=r/n,c=r%n,l=i-s*a;r=n,n=c,i=s,s=l}if(r!==Ho)throw new Error("invert: does not exist");return Dl(i,e)}function EF(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Nme(t,e){const n=(t.ORDER+Ho)/Ime,r=t.pow(e,n);return EF(t,r,e),r}function yft(t,e){const n=(t.ORDER-Tme)/Pme,r=t.mul(e,pg),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,pg),i),a=t.mul(s,t.sub(o,t.ONE));return EF(t,a,e),a}function wft(t){const e=k8(t),n=Rme(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+gft)/Ome;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,r);const u=a.mul(l,i),h=a.mul(l,s),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,g);const m=a.eql(a.sqr(d),c),y=a.cmov(l,d,m);return EF(a,y,c),y}}function Rme(t){if(t<kme)throw new Error("sqrt is not defined for small field");let e=t-Ho,n=0;for(;e%pg===$a;)e/=pg,n++;let r=pg;const i=k8(t);for(;nX(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Nme;let s=i.pow(r,e);const o=(e+Ho)/pg;return function(c,l){if(c.is0(l))return l;if(nX(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),h=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let g=1,m=c.sqr(h);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const y=Ho<<BigInt(d-g-1),b=c.pow(u,y);d=g,u=c.sqr(b),h=c.mul(h,u),p=c.mul(p,b)}return p}}function bft(t){return t%Ime===kme?Nme:t%Pme===Tme?yft:t%Ome===mft?wft(t):Rme(t)}const vft=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xft(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=vft.reduce((r,i)=>(r[i]="function",r),e);return xF(t,n),t}function Eft(t,e,n){if(n<$a)throw new Error("invalid exponent, negatives unsupported");if(n===$a)return t.ONE;if(n===Ho)return e;let r=t.ONE,i=e;for(;n>$a;)n&Ho&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ho;return r}function Mme(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function nX(t,e){const n=(t.ORDER-Ho)/pg,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function jme(t,e){e!==void 0&&o4(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function k8(t,e,n=!1,r={}){if(t<=$a)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=jme(t,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:$8(c),ZERO:$a,ONE:Ho,allowedLengths:a,create:h=>Dl(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return $a<=h&&h<t},is0:h=>h===$a,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&Ho)===Ho,neg:h=>Dl(-h,t),eql:(h,p)=>h===p,sqr:h=>Dl(h*h,t),add:(h,p)=>Dl(h+p,t),sub:(h,p)=>Dl(h-p,t),mul:(h,p)=>Dl(h*p,t),pow:(h,p)=>Eft(u,h,p),div:(h,p)=>Dl(h*tX(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>tX(h,t),sqrt:s||(h=>(d||(d=bft(t)),d(u,h))),toBytes:h=>n?Sme(h,l):vF(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const m=new Uint8Array(l);m.set(h,n?0:m.length-h.length),h=m}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let g=n?_me(h):vS(h);if(o&&(g=Dl(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>Mme(u,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(u)}function Dme(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Lme(t){const e=Dme(t);return e+Math.ceil(e/2)}function Cft(t,e,n=!1){const r=t.length,i=Dme(e),s=Lme(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?_me(t):vS(t),a=Dl(o,e-Ho)+Ho;return n?Sme(a,i):vF(a,i)}const Bw=BigInt(0),fg=BigInt(1);function d7(t,e){const n=e.negate();return t?n:e}function xT(t,e){const n=Mme(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Bme(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ET(t,e){Bme(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=$8(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function rX(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=fg);const l=e*r,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function Aft(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function _ft(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const CT=new WeakMap,Ume=new WeakMap;function AT(t){return Ume.get(t)||1}function iX(t){if(t!==Bw)throw new Error("invalid wNAF")}let Sft=class{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>Bw;)n&fg&&(r=r.add(i)),i=i.double(),n>>=fg;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=ET(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let l=1;l<i;l++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=ET(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=rX(r,a,o);r=c,d?s=s.add(d7(h,n[p])):i=i.add(d7(u,n[l]))}return iX(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=ET(e,this.bits);for(let o=0;o<s.windows&&r!==Bw;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=rX(r,o,s);if(r=a,!l){const u=n[c];i=i.add(d?u.negate():u)}}return iX(r),i}getPrecomputes(e,n,r){let i=CT.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),CT.set(n,i))),i}cached(e,n,r){const i=AT(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=AT(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Bme(n,this.bits),Ume.set(e,n),CT.delete(e)}hasCache(e){return AT(e)!==1}};function $ft(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Bw||r>Bw;)n&fg&&(s=s.add(i)),r&fg&&(o=o.add(i)),i=i.double(),n>>=fg,r>>=fg;return{p1:s,p2:o}}function kft(t,e,n,r){Aft(n,t),_ft(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=$me(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=$8(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let m=0;m<s;m++){const y=r[m],b=Number(y>>BigInt(p)&l);d[b]=d[b].add(n[m])}let g=o;for(let m=d.length-1,y=o;m>0;m--)y=y.add(d[m]),g=g.add(y);if(h=h.add(g),p!==0)for(let m=0;m<c;m++)h=h.double()}return h}function sX(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xft(e),e}else return k8(t,{isLE:n})}function Ift(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Bw))throw new Error(`CURVE.${c} must be positive bigint`)}const i=sX(e.p,n.Fp,r),s=sX(e.n,n.Fn,r),a=["Gx","Gy","a","b"];for(const c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}const oX=(t,e)=>(t+(t>=0?e:-e)/Fme)/e;function Tft(t,e,n){const[[r,i],[s,o]]=e,a=oX(o*t,n),c=oX(-i*t,n);let l=t-a*r-c*s,d=-a*i-c*o;const u=l<kp,h=d<kp;u&&(l=-l),h&&(d=-d);const p=$8(Math.ceil($me(n)/2))+N2;if(l<kp||l>=p||d<kp||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function MM(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function _T(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return l7(n.lowS,"lowS"),l7(n.prehash,"prehash"),n.format!==void 0&&MM(n.format),n}let Pft=class extends Error{constructor(e=""){super(e)}};const mp={Err:Pft,_tlv:{encode:(t,e)=>{const{Err:n}=mp;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Qx(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Qx(i.length/2|128):"";return Qx(t)+s+i+e},decode(t,e){const{Err:n}=mp;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=mp;if(t<kp)throw new e("integer: negative integers are not allowed");let n=Qx(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=mp;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return vS(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=mp,i=ma("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=mp,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},kp=BigInt(0),N2=BigInt(1),Fme=BigInt(2),eE=BigInt(3),Oft=BigInt(4);function d2(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=ma("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Nft(t,e={}){const n=Ift("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;xF(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Wme(r,i);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,O,S){const{x:A,y:k}=O.toAffine(),L=r.toBytes(A);if(l7(S,"isCompressed"),S){d();const D=!r.isOdd(k);return h0(zme(D),L)}else return h0(Uint8Array.of(4),L,r.toBytes(k))}function h(R){hg(R,void 0,"Point");const{publicKey:O,publicKeyUncompressed:S}=l,A=R.length,k=R[0],L=R.subarray(1);if(A===O&&(k===2||k===3)){const D=r.fromBytes(L);if(!r.isValid(D))throw new Error("bad point: is not on curve, wrong x");const N=m(D);let j;try{j=r.sqrt(N)}catch(Z){const V=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const F=r.isOdd(j);return(k&1)===1!==F&&(j=r.neg(j)),{x:D,y:j}}else if(A===S&&k===4){const D=r.BYTES,N=r.fromBytes(L.subarray(0,D)),j=r.fromBytes(L.subarray(D,D*2));if(!y(N,j))throw new Error("bad point: is not on curve");return{x:N,y:j}}else throw new Error(`bad point: got length ${A}, expected compressed=${O} or uncompressed=${S}`)}const p=e.toBytes||u,g=e.fromBytes||h;function m(R){const O=r.sqr(R),S=r.mul(O,R);return r.add(r.add(S,r.mul(R,s.a)),s.b)}function y(R,O){const S=r.sqr(O),A=m(R);return r.eql(S,A)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const b=r.mul(r.pow(s.a,eE),Oft),x=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(b,x)))throw new Error("bad curve params: a or b");function v(R,O,S=!1){if(!r.isValid(O)||S&&r.is0(O))throw new Error(`bad point coordinate ${R}`);return O}function E(R){if(!(R instanceof P))throw new Error("ProjectivePoint expected")}function C(R){if(!c||!c.basises)throw new Error("no endo");return Tft(R,c.basises,i.ORDER)}const w=eX((R,O)=>{const{X:S,Y:A,Z:k}=R;if(r.eql(k,r.ONE))return{x:S,y:A};const L=R.is0();O==null&&(O=L?r.ONE:r.inv(k));const D=r.mul(S,O),N=r.mul(A,O),j=r.mul(k,O);if(L)return{x:r.ZERO,y:r.ZERO};if(!r.eql(j,r.ONE))throw new Error("invZ was invalid");return{x:D,y:N}}),_=eX(R=>{if(R.is0()){if(e.allowInfinityPoint&&!r.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:O,y:S}=R.toAffine();if(!r.isValid(O)||!r.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(O,S))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function T(R,O,S,A,k){return S=new P(r.mul(S.X,R),S.Y,S.Z),O=d7(A,O),S=d7(k,S),O.add(S)}class P{constructor(O,S,A){this.X=v("x",O),this.Y=v("y",S,!0),this.Z=v("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(O){const{x:S,y:A}=O||{};if(!O||!r.isValid(S)||!r.isValid(A))throw new Error("invalid affine point");if(O instanceof P)throw new Error("projective point not allowed");return r.is0(S)&&r.is0(A)?P.ZERO:new P(S,A,r.ONE)}static fromBytes(O){const S=P.fromAffine(g(hg(O,void 0,"point")));return S.assertValidity(),S}static fromHex(O){return P.fromBytes(ma("pointHex",O))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(O=8,S=!0){return M.createCache(this,O),S||this.multiply(eE),this}assertValidity(){_(this)}hasEvenY(){const{y:O}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(O)}equals(O){E(O);const{X:S,Y:A,Z:k}=this,{X:L,Y:D,Z:N}=O,j=r.eql(r.mul(S,N),r.mul(L,k)),F=r.eql(r.mul(A,N),r.mul(D,k));return j&&F}negate(){return new P(this.X,r.neg(this.Y),this.Z)}double(){const{a:O,b:S}=s,A=r.mul(S,eE),{X:k,Y:L,Z:D}=this;let N=r.ZERO,j=r.ZERO,F=r.ZERO,z=r.mul(k,k),Z=r.mul(L,L),V=r.mul(D,D),q=r.mul(k,L);return q=r.add(q,q),F=r.mul(k,D),F=r.add(F,F),N=r.mul(O,F),j=r.mul(A,V),j=r.add(N,j),N=r.sub(Z,j),j=r.add(Z,j),j=r.mul(N,j),N=r.mul(q,N),F=r.mul(A,F),V=r.mul(O,V),q=r.sub(z,V),q=r.mul(O,q),q=r.add(q,F),F=r.add(z,z),z=r.add(F,z),z=r.add(z,V),z=r.mul(z,q),j=r.add(j,z),V=r.mul(L,D),V=r.add(V,V),z=r.mul(V,q),N=r.sub(N,z),F=r.mul(V,Z),F=r.add(F,F),F=r.add(F,F),new P(N,j,F)}add(O){E(O);const{X:S,Y:A,Z:k}=this,{X:L,Y:D,Z:N}=O;let j=r.ZERO,F=r.ZERO,z=r.ZERO;const Z=s.a,V=r.mul(s.b,eE);let q=r.mul(S,L),Q=r.mul(A,D),ee=r.mul(k,N),ie=r.add(S,A),se=r.add(L,D);ie=r.mul(ie,se),se=r.add(q,Q),ie=r.sub(ie,se),se=r.add(S,k);let me=r.add(L,N);return se=r.mul(se,me),me=r.add(q,ee),se=r.sub(se,me),me=r.add(A,k),j=r.add(D,N),me=r.mul(me,j),j=r.add(Q,ee),me=r.sub(me,j),z=r.mul(Z,se),j=r.mul(V,ee),z=r.add(j,z),j=r.sub(Q,z),z=r.add(Q,z),F=r.mul(j,z),Q=r.add(q,q),Q=r.add(Q,q),ee=r.mul(Z,ee),se=r.mul(V,se),Q=r.add(Q,ee),ee=r.sub(q,ee),ee=r.mul(Z,ee),se=r.add(se,ee),q=r.mul(Q,se),F=r.add(F,q),q=r.mul(me,se),j=r.mul(ie,j),j=r.sub(j,q),q=r.mul(ie,Q),z=r.mul(me,z),z=r.add(z,q),new P(j,F,z)}subtract(O){return this.add(O.negate())}is0(){return this.equals(P.ZERO)}multiply(O){const{endo:S}=e;if(!i.isValidNot0(O))throw new Error("invalid scalar: out of range");let A,k;const L=D=>M.cached(this,D,N=>xT(P,N));if(S){const{k1neg:D,k1:N,k2neg:j,k2:F}=C(O),{p:z,f:Z}=L(N),{p:V,f:q}=L(F);k=Z.add(q),A=T(S.beta,z,V,D,j)}else{const{p:D,f:N}=L(O);A=D,k=N}return xT(P,[A,k])[0]}multiplyUnsafe(O){const{endo:S}=e,A=this;if(!i.isValid(O))throw new Error("invalid scalar: out of range");if(O===kp||A.is0())return P.ZERO;if(O===N2)return A;if(M.hasCache(this))return this.multiply(O);if(S){const{k1neg:k,k1:L,k2neg:D,k2:N}=C(O),{p1:j,p2:F}=$ft(P,A,L,N);return T(S.beta,j,F,k,D)}else return M.unsafe(A,O)}multiplyAndAddUnsafe(O,S,A){const k=this.multiplyUnsafe(S).add(O.multiplyUnsafe(A));return k.is0()?void 0:k}toAffine(O){return w(this,O)}isTorsionFree(){const{isTorsionFree:O}=e;return o===N2?!0:O?O(P,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:O}=e;return o===N2?this:O?O(P,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(O=!0){return l7(O,"isCompressed"),this.assertValidity(),p(P,this,O)}toHex(O=!0){return O2(this.toBytes(O))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(O=!0){return this.toBytes(O)}_setWindowSize(O){this.precompute(O)}static normalizeZ(O){return xT(P,O)}static msm(O,S){return kft(P,i,O,S)}static fromPrivateKey(O){return P.BASE.multiply(d2(i,O))}}P.BASE=new P(s.Gx,s.Gy,r.ONE),P.ZERO=new P(r.ZERO,r.ONE,r.ZERO),P.Fp=r,P.Fn=i;const I=i.BITS,M=new Sft(P,e.endo?Math.ceil(I/2):I);return P.BASE.precompute(8),P}function zme(t){return Uint8Array.of(t?2:3)}function Wme(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Rft(t,e={}){const{Fn:n}=t,r=e.randomBytes||mme,i=Object.assign(Wme(t.Fp,n),{seed:Lme(n.ORDER)});function s(p){try{return!!d2(n,p)}catch{return!1}}function o(p,g){const{publicKey:m,publicKeyUncompressed:y}=i;try{const b=p.length;return g===!0&&b!==m||g===!1&&b!==y?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=r(i.seed)){return Cft(hg(p,i.seed,"seed"),n.ORDER)}function c(p,g=!0){return t.BASE.multiply(d2(n,p)).toBytes(g)}function l(p){const g=a(p);return{secretKey:g,publicKey:c(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:y}=i;if(n.allowedLengths||g===m)return;const b=ma("key",p).length;return b===m||b===y}function u(p,g,m=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const y=d2(n,p);return t.fromHex(g).multiply(y).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>d2(n,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function Mft(t,e,n={}){hme(e),xF(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||mme,i=n.hmac||((S,...A)=>Cme(e,S,h0(...A))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=Rft(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(S){const A=a>>N2;return S>A}function b(S,A){if(!o.isValidNot0(A))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return A}function x(S,A){MM(A);const k=p.signature,L=A==="compact"?k:A==="recovered"?k+1:void 0;return hg(S,L,`${A} signature`)}class v{constructor(A,k,L){this.r=b("r",A),this.s=b("s",k),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(A,k=m){x(A,k);let L;if(k==="der"){const{r:F,s:z}=mp.toSig(hg(A));return new v(F,z)}k==="recovered"&&(L=A[0],k="compact",A=A.subarray(1));const D=o.BYTES,N=A.subarray(0,D),j=A.subarray(D,D*2);return new v(o.fromBytes(N),o.fromBytes(j),L)}static fromHex(A,k){return this.fromBytes(c7(A),k)}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){const k=s.ORDER,{r:L,s:D,recovery:N}=this;if(N==null||![0,1,2,3].includes(N))throw new Error("recovery id invalid");if(a*Fme<k&&N>1)throw new Error("recovery id is ambiguous for h>1 curve");const F=N===2||N===3?L+a:L;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");const z=s.toBytes(F),Z=t.fromBytes(h0(zme((N&1)===0),z)),V=o.inv(F),q=C(ma("msgHash",A)),Q=o.create(-q*V),ee=o.create(D*V),ie=t.BASE.multiplyUnsafe(Q).add(Z.multiplyUnsafe(ee));if(ie.is0())throw new Error("point at infinify");return ie.assertValidity(),ie}hasHighS(){return y(this.s)}toBytes(A=m){if(MM(A),A==="der")return c7(mp.hexFromSig(this));const k=o.toBytes(this.r),L=o.toBytes(this.s);if(A==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return h0(Uint8Array.of(this.recovery),k,L)}return h0(k,L)}toHex(A){return O2(this.toBytes(A))}assertValidity(){}static fromCompact(A){return v.fromBytes(ma("sig",A),"compact")}static fromDER(A){return v.fromBytes(ma("sig",A),"der")}normalizeS(){return this.hasHighS()?new v(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return O2(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return O2(this.toBytes("compact"))}}const E=n.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");const k=vS(A),L=A.length*8-c;return L>0?k>>BigInt(L):k},C=n.bits2int_modN||function(A){return o.create(E(A))},w=$8(c);function _(S){return pft("num < 2^"+c,S,kp,w),o.toBytes(S)}function T(S,A){return hg(S,void 0,"message"),A?hg(e(S),void 0,"prehashed message"):S}function P(S,A,k){if(["recovered","canonical"].some(Q=>Q in k))throw new Error("sign() legacy options not supported");const{lowS:L,prehash:D,extraEntropy:N}=_T(k,g);S=T(S,D);const j=C(S),F=d2(o,A),z=[_(F),_(j)];if(N!=null&&N!==!1){const Q=N===!0?r(p.secretKey):N;z.push(ma("extraEntropy",Q))}const Z=h0(...z),V=j;function q(Q){const ee=E(Q);if(!o.isValidNot0(ee))return;const ie=o.inv(ee),se=t.BASE.multiply(ee).toAffine(),me=o.create(se.x);if(me===kp)return;const Ie=o.create(ie*o.create(V+me*F));if(Ie===kp)return;let Me=(se.x===me?0:2)|Number(se.y&N2),le=Ie;return L&&y(Ie)&&(le=o.neg(Ie),Me^=1),new v(me,le,Me)}return{seed:Z,k2sig:q}}function I(S,A,k={}){S=ma("message",S);const{seed:L,k2sig:D}=P(S,A,k);return fft(e.outputLen,o.BYTES,i)(L,D)}function M(S){let A;const k=typeof S=="string"||wS(S),L=!k&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!k&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)A=new v(S.r,S.s);else if(k){try{A=v.fromBytes(ma("sig",S),"der")}catch(D){if(!(D instanceof mp.Err))throw D}if(!A)try{A=v.fromBytes(ma("sig",S),"compact")}catch{return!1}}return A||!1}function R(S,A,k,L={}){const{lowS:D,prehash:N,format:j}=_T(L,g);if(k=ma("publicKey",k),A=T(ma("message",A),N),"strict"in L)throw new Error("options.strict was renamed to lowS");const F=j===void 0?M(S):v.fromBytes(ma("sig",S),j);if(F===!1)return!1;try{const z=t.fromBytes(k);if(D&&F.hasHighS())return!1;const{r:Z,s:V}=F,q=C(A),Q=o.inv(V),ee=o.create(q*Q),ie=o.create(Z*Q),se=t.BASE.multiplyUnsafe(ee).add(z.multiplyUnsafe(ie));return se.is0()?!1:o.create(se.x)===Z}catch{return!1}}function O(S,A,k={}){const{prehash:L}=_T(k,g);return A=T(A,L),v.fromBytes(S,"recovered").recoverPublicKey(A).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:I,verify:R,recoverPublicKey:O,Signature:v,hash:e})}function jft(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=k8(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function Dft(t){const{CURVE:e,curveOpts:n}=jft(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function Lft(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,jme(n.Fn.ORDER,n.Fn.BITS))})}function Bft(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Dft(t),s=Nft(e,n),o=Mft(s,r,i);return Lft(t,o)}function Uft(t,e){const n=r=>Bft({...t,hash:r});return{...n(e),create:n}}const CF={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fft={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},aX=BigInt(2);function zft(t){const e=CF.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=Nc(d,n,e)*d%e,h=Nc(u,n,e)*d%e,p=Nc(h,aX,e)*l%e,g=Nc(p,i,e)*p%e,m=Nc(g,s,e)*g%e,y=Nc(m,a,e)*m%e,b=Nc(y,c,e)*y%e,x=Nc(b,a,e)*m%e,v=Nc(x,n,e)*d%e,E=Nc(v,o,e)*g%e,C=Nc(E,r,e)*l%e,w=Nc(C,aX,e);if(!jM.eql(jM.sqr(w),t))throw new Error("Cannot find square root");return w}const jM=k8(CF.p,{sqrt:zft}),Wft=Uft({...CF,Fp:jM,lowS:!0,endo:Fft},uft),Hft=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:Wft},Symbol.toStringTag,{value:"Module"})),Vft=":";function Dp(t){const[e,n]=t.split(Vft);return{namespace:e,reference:n}}function Hme(t,e){return t.includes(":")?[t]:e.chains||[]}var qft=Object.defineProperty,Zft=Object.defineProperties,Kft=Object.getOwnPropertyDescriptors,cX=Object.getOwnPropertySymbols,Gft=Object.prototype.hasOwnProperty,Yft=Object.prototype.propertyIsEnumerable,DM=(t,e,n)=>e in t?qft(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lX=(t,e)=>{for(var n in e||(e={}))Gft.call(e,n)&&DM(t,n,e[n]);if(cX)for(var n of cX(e))Yft.call(e,n)&&DM(t,n,e[n]);return t},Jft=(t,e)=>Zft(t,Kft(e)),dX=(t,e,n)=>DM(t,typeof e!="symbol"?e+"":e,n);const Xft="ReactNative",uc={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Qft="js";function u7(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function d1(){return!As.getDocument()&&!!As.getNavigator()&&navigator.product===Xft}function e0t(){return d1()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="android"}function t0t(){return d1()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="ios"}function Nb(){return!u7()&&!!As.getNavigator()&&!!As.getDocument()}function I8(){return d1()?uc.reactNative:u7()?uc.node:Nb()?uc.browser:uc.unknown}function uX(){var t;try{return d1()&&typeof globalThis<"u"&&typeof globalThis?.Application<"u"?(t=globalThis.Application)==null?void 0:t.applicationId:void 0}catch{return}}function n0t(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function r0t(t){var e,n;const r=Vme();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),Jft(lX(lX({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function Vme(){return Whe.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function i0t(){if(I8()===uc.reactNative&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"){const{OS:n,Version:r}=globalThis.Platform;return[n,r].join("-")}const t=Bhe();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function s0t(){var t;const e=I8();return e===uc.browser?[e,((t=As.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function qme(t,e,n){const r=i0t(),i=s0t();return[[t,e].join("-"),[Qft,n].join("-"),r,i].join("/")}function o0t({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),d=qme(t,e,r),u={auth:i,ua:d,projectId:s,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=n0t(l[1]||"",u);return l[0]+"?"+h}function gg(t,e){return t.filter(n=>e.includes(n)).length===t.length}function LM(t){return Object.fromEntries(t.entries())}function BM(t){return new Map(Object.entries(t))}function z1(t=Ce.FIVE_MINUTES,e){const n=Ce.toMiliseconds(t||Ce.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},n),r=a,i=c})}}function Jd(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function Zme(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function a0t(t){return Zme("topic",t)}function c0t(t){return Zme("id",t)}function Kme(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function $i(t,e){return Ce.fromMiliseconds(Date.now()+Ce.toMiliseconds(t))}function qd(t){return Date.now()>=Ce.toMiliseconds(t)}function Zn(t,e){return`${t}${e?`:${e}`:""}`}function hu(t=[],e=[]){return[...new Set([...t,...e])]}async function l0t({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=d0t(s,t,e),a=I8();if(a===uc.browser){if(!((r=As.getDocument())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}u0t(o)}else a===uc.reactNative&&typeof globalThis?.Linking<"u"&&await globalThis.Linking.openURL(o)}catch(i){console.error(i)}}function d0t(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${g0t(r,!0)}`}else i=`${i}/wc?${r}`;return i}function u0t(t){let e="_self";f0t()?e="_top":(p0t()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function h0t(t,e){let n="";try{if(Nb()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function hX(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function pX(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function AF(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function p0t(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function f0t(){try{return window.self!==window.top}catch{return!1}}function g0t(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function Gme(t){return Buffer.from(t,"base64").toString("utf-8")}function m0t(t){return new Promise(e=>setTimeout(e,t))}let y0t=class{constructor({limit:e}){dX(this,"limit"),dX(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}};const tE=BigInt(2**32-1),fX=BigInt(32);function Yme(t,e=!1){return e?{h:Number(t&tE),l:Number(t>>fX&tE)}:{h:Number(t>>fX&tE)|0,l:Number(t&tE)|0}}function Jme(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Yme(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const gX=(t,e,n)=>t>>>n,mX=(t,e,n)=>t<<32-n|e>>>n,t0=(t,e,n)=>t>>>n|e<<32-n,n0=(t,e,n)=>t<<32-n|e>>>n,E6=(t,e,n)=>t<<64-n|e>>>n-32,C6=(t,e,n)=>t>>>n-32|e<<64-n,w0t=(t,e)=>e,b0t=(t,e)=>t,v0t=(t,e,n)=>t<<n|e>>>32-n,x0t=(t,e,n)=>e<<n|t>>>32-n,E0t=(t,e,n)=>e<<n-32|t>>>64-n,C0t=(t,e,n)=>t<<n-32|e>>>64-n;function jl(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const _F=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),SF=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,A0t=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),_0t=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,S0t=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),$0t=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Ty=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xS(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Jp(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ud(t,...e){if(!xS(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ES(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jp(t.outputLen),Jp(t.blockLen)}function V0(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function $F(t,e){ud(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function a4(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function al(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ST(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Od(t,e){return t<<32-e|t>>>e}const Xme=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qme(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const ip=Xme?t=>t:t=>Qme(t);function k0t(t){for(let e=0;e<t.length;e++)t[e]=Qme(t[e]);return t}const r0=Xme?t=>t:k0t,eye=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",I0t=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function R2(t){if(ud(t),eye)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=I0t[t[n]];return e}const Gh={_0:48,_9:57,A:65,F:70,a:97,f:102};function yX(t){if(t>=Gh._0&&t<=Gh._9)return t-Gh._0;if(t>=Gh.A&&t<=Gh.F)return t-(Gh.A-10);if(t>=Gh.a&&t<=Gh.f)return t-(Gh.a-10)}function h7(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(eye)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=yX(t.charCodeAt(s)),a=yX(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function tye(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ed(t){return typeof t=="string"&&(t=tye(t)),ud(t),t}function p0(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];ud(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class CS{}function T8(t){const e=r=>t().update(ed(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function T0t(t){const e=(r,i)=>t(i).update(ed(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Gm(t=32){if(Ty&&typeof Ty.getRandomValues=="function")return Ty.getRandomValues(new Uint8Array(t));if(Ty&&typeof Ty.randomBytes=="function")return Uint8Array.from(Ty.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const P0t=BigInt(0),Av=BigInt(1),O0t=BigInt(2),N0t=BigInt(7),R0t=BigInt(256),M0t=BigInt(113),nye=[],rye=[],iye=[];for(let t=0,e=Av,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],nye.push(2*(5*r+n)),rye.push((t+1)*(t+2)/2%64);let i=P0t;for(let s=0;s<7;s++)e=(e<<Av^(e>>N0t)*M0t)%R0t,e&O0t&&(i^=Av<<(Av<<BigInt(s))-Av);iye.push(i)}const sye=Jme(iye,!0),j0t=sye[0],D0t=sye[1],wX=(t,e,n)=>n>32?E0t(t,e,n):v0t(t,e,n),bX=(t,e,n)=>n>32?C0t(t,e,n):x0t(t,e,n);function L0t(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],d=n[c+1],u=wX(l,d,1)^n[a],h=bX(l,d,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=rye[o],c=wX(i,s,a),l=bX(i,s,a),d=nye[o];i=t[d],s=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=j0t[r],t[1]^=D0t[r]}al(n)}let B0t=class oye extends CS{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Jp(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=a4(this.state)}clone(){return this._cloneInto()}keccak(){r0(this.state32),L0t(this.state32,this.rounds),r0(this.state32),this.posOut=0,this.pos=0}update(e){V0(this),e=ed(e),ud(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){V0(this,!1),ud(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Jp(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($F(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,al(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new oye(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const U0t=(t,e,n)=>T8(()=>new B0t(e,t,n)),F0t=U0t(1,136,256/8);function z0t(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function W0t(t,e,n){return t&e^~t&n}function H0t(t,e,n){return t&e^t&n^e&n}let aye=class extends CS{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ST(this.buffer)}update(e){V0(this),e=ed(e),ud(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=ST(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){V0(this),$F(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,al(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;z0t(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=ST(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Rf=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),no=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ro=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),V0t=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Mf=new Uint32Array(64);class q0t extends aye{constructor(e=32){super(64,e,8,!1),this.A=Rf[0]|0,this.B=Rf[1]|0,this.C=Rf[2]|0,this.D=Rf[3]|0,this.E=Rf[4]|0,this.F=Rf[5]|0,this.G=Rf[6]|0,this.H=Rf[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)Mf[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const h=Mf[u-15],p=Mf[u-2],g=Od(h,7)^Od(h,18)^h>>>3,m=Od(p,17)^Od(p,19)^p>>>10;Mf[u]=m+Mf[u-7]+g+Mf[u-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=Od(a,6)^Od(a,11)^Od(a,25),p=d+h+W0t(a,c,l)+V0t[u]+Mf[u]|0,g=(Od(r,2)^Od(r,13)^Od(r,22))+H0t(r,i,s)|0;d=l,l=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,i,s,o,a,c,l,d)}roundClean(){al(Mf)}destroy(){this.set(0,0,0,0,0,0,0,0),al(this.buffer)}}const cye=Jme(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Z0t=cye[0],K0t=cye[1],jf=new Uint32Array(80),Df=new Uint32Array(80);let kF=class extends aye{constructor(e=64){super(128,e,16,!1),this.Ah=ro[0]|0,this.Al=ro[1]|0,this.Bh=ro[2]|0,this.Bl=ro[3]|0,this.Ch=ro[4]|0,this.Cl=ro[5]|0,this.Dh=ro[6]|0,this.Dl=ro[7]|0,this.Eh=ro[8]|0,this.El=ro[9]|0,this.Fh=ro[10]|0,this.Fl=ro[11]|0,this.Gh=ro[12]|0,this.Gl=ro[13]|0,this.Hh=ro[14]|0,this.Hl=ro[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:p,Gl:g,Hh:m,Hl:y}=this;return[e,n,r,i,s,o,a,c,l,d,u,h,p,g,m,y]}set(e,n,r,i,s,o,a,c,l,d,u,h,p,g,m,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=m|0,this.Hl=y|0}process(e,n){for(let v=0;v<16;v++,n+=4)jf[v]=e.getUint32(n),Df[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){const E=jf[v-15]|0,C=Df[v-15]|0,w=t0(E,C,1)^t0(E,C,8)^gX(E,C,7),_=n0(E,C,1)^n0(E,C,8)^mX(E,C,7),T=jf[v-2]|0,P=Df[v-2]|0,I=t0(T,P,19)^E6(T,P,61)^gX(T,P,6),M=n0(T,P,19)^C6(T,P,61)^mX(T,P,6),R=A0t(_,M,Df[v-7],Df[v-16]),O=_0t(R,w,I,jf[v-7],jf[v-16]);jf[v]=O|0,Df[v]=R|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:g,Gh:m,Gl:y,Hh:b,Hl:x}=this;for(let v=0;v<80;v++){const E=t0(u,h,14)^t0(u,h,18)^E6(u,h,41),C=n0(u,h,14)^n0(u,h,18)^C6(u,h,41),w=u&p^~u&m,_=h&g^~h&y,T=S0t(x,C,_,K0t[v],Df[v]),P=$0t(T,b,E,w,Z0t[v],jf[v]),I=T|0,M=t0(r,i,28)^E6(r,i,34)^E6(r,i,39),R=n0(r,i,28)^C6(r,i,34)^C6(r,i,39),O=r&s^r&a^s&a,S=i&o^i&c^o&c;b=m|0,x=y|0,m=p|0,y=g|0,p=u|0,g=h|0,{h:u,l:h}=jl(l|0,d|0,P|0,I|0),l=a|0,d=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const A=_F(I,R,S);r=SF(A,P,M,O),i=A|0}({h:r,l:i}=jl(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=jl(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=jl(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=jl(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=jl(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:g}=jl(this.Fh|0,this.Fl|0,p|0,g|0),{h:m,l:y}=jl(this.Gh|0,this.Gl|0,m|0,y|0),{h:b,l:x}=jl(this.Hh|0,this.Hl|0,b|0,x|0),this.set(r,i,s,o,a,c,l,d,u,h,p,g,m,y,b,x)}roundClean(){al(jf,Df)}destroy(){al(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class G0t extends kF{constructor(){super(48),this.Ah=no[0]|0,this.Al=no[1]|0,this.Bh=no[2]|0,this.Bl=no[3]|0,this.Ch=no[4]|0,this.Cl=no[5]|0,this.Dh=no[6]|0,this.Dl=no[7]|0,this.Eh=no[8]|0,this.El=no[9]|0,this.Fh=no[10]|0,this.Fl=no[11]|0,this.Gh=no[12]|0,this.Gl=no[13]|0,this.Hh=no[14]|0,this.Hl=no[15]|0}}const io=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Y0t extends kF{constructor(){super(32),this.Ah=io[0]|0,this.Al=io[1]|0,this.Bh=io[2]|0,this.Bl=io[3]|0,this.Ch=io[4]|0,this.Cl=io[5]|0,this.Dh=io[6]|0,this.Dl=io[7]|0,this.Eh=io[8]|0,this.El=io[9]|0,this.Fh=io[10]|0,this.Fl=io[11]|0,this.Gh=io[12]|0,this.Gl=io[13]|0,this.Hh=io[14]|0,this.Hl=io[15]|0}}const AS=T8(()=>new q0t),J0t=T8(()=>new kF),X0t=T8(()=>new G0t),Q0t=T8(()=>new Y0t),e1t=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Wi=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ut=new Uint32Array(32);function Lf(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=ut[2*t],l=ut[2*t+1],d=ut[2*e],u=ut[2*e+1],h=ut[2*n],p=ut[2*n+1],g=ut[2*r],m=ut[2*r+1],y=_F(c,d,o);l=SF(y,l,u,a),c=y|0,{Dh:m,Dl:g}={Dh:m^l,Dl:g^c},{Dh:m,Dl:g}={Dh:w0t(m,g),Dl:b0t(m)},{h:p,l:h}=jl(p,h,m,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:t0(u,d,24),Bl:n0(u,d,24)},ut[2*t]=c,ut[2*t+1]=l,ut[2*e]=d,ut[2*e+1]=u,ut[2*n]=h,ut[2*n+1]=p,ut[2*r]=g,ut[2*r+1]=m}function Bf(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=ut[2*t],l=ut[2*t+1],d=ut[2*e],u=ut[2*e+1],h=ut[2*n],p=ut[2*n+1],g=ut[2*r],m=ut[2*r+1],y=_F(c,d,o);l=SF(y,l,u,a),c=y|0,{Dh:m,Dl:g}={Dh:m^l,Dl:g^c},{Dh:m,Dl:g}={Dh:t0(m,g,16),Dl:n0(m,g,16)},{h:p,l:h}=jl(p,h,m,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:E6(u,d,63),Bl:C6(u,d,63)},ut[2*t]=c,ut[2*t+1]=l,ut[2*e]=d,ut[2*e+1]=u,ut[2*n]=h,ut[2*n+1]=p,ut[2*r]=g,ut[2*r+1]=m}function t1t(t,e={},n,r,i){if(Jp(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class n1t extends CS{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jp(e),Jp(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=a4(this.buffer)}update(e){V0(this),e=ed(e),ud(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(r0(i),this.compress(i,0,!1),r0(i),this.pos=0);const l=Math.min(n-this.pos,s-c),d=o+c;if(l===n&&!(d%4)&&c+l<s){const u=new Uint32Array(a,d,Math.floor((s-c)/4));r0(u);for(let h=0;c+n<s;h+=i.length,c+=n)this.length+=n,this.compress(u,h,!1);r0(u);continue}r.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){V0(this),$F(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,al(this.buffer.subarray(n)),r0(r),this.compress(r,0,!0),r0(r);const i=a4(e);this.get().forEach((s,o)=>i[o]=ip(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class r1t extends n1t{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Wi[0]|0,this.v0h=Wi[1]|0,this.v1l=Wi[2]|0,this.v1h=Wi[3]|0,this.v2l=Wi[4]|0,this.v2h=Wi[5]|0,this.v3l=Wi[6]|0,this.v3h=Wi[7]|0,this.v4l=Wi[8]|0,this.v4h=Wi[9]|0,this.v5l=Wi[10]|0,this.v5h=Wi[11]|0,this.v6l=Wi[12]|0,this.v6h=Wi[13]|0,this.v7l=Wi[14]|0,this.v7h=Wi[15]|0,t1t(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=ed(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=ed(s);const a=a4(s);this.v4l^=ip(a[0]),this.v4h^=ip(a[1]),this.v5l^=ip(a[2]),this.v5h^=ip(a[3])}if(i!==void 0){i=ed(i);const a=a4(i);this.v6l^=ip(a[0]),this.v6h^=ip(a[1]),this.v7l^=ip(a[2]),this.v7h^=ip(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:p,v6h:g,v7l:m,v7h:y}=this;return[e,n,r,i,s,o,a,c,l,d,u,h,p,g,m,y]}set(e,n,r,i,s,o,a,c,l,d,u,h,p,g,m,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=p|0,this.v6h=g|0,this.v7l=m|0,this.v7h=y|0}compress(e,n,r){this.get().forEach((c,l)=>ut[l]=c),ut.set(Wi,16);let{h:i,l:s}=Yme(BigInt(this.length));ut[24]=Wi[8]^s,ut[25]=Wi[9]^i,r&&(ut[28]=~ut[28],ut[29]=~ut[29]);let o=0;const a=e1t;for(let c=0;c<12;c++)Lf(0,4,8,12,e,n+2*a[o++]),Bf(0,4,8,12,e,n+2*a[o++]),Lf(1,5,9,13,e,n+2*a[o++]),Bf(1,5,9,13,e,n+2*a[o++]),Lf(2,6,10,14,e,n+2*a[o++]),Bf(2,6,10,14,e,n+2*a[o++]),Lf(3,7,11,15,e,n+2*a[o++]),Bf(3,7,11,15,e,n+2*a[o++]),Lf(0,5,10,15,e,n+2*a[o++]),Bf(0,5,10,15,e,n+2*a[o++]),Lf(1,6,11,12,e,n+2*a[o++]),Bf(1,6,11,12,e,n+2*a[o++]),Lf(2,7,8,13,e,n+2*a[o++]),Bf(2,7,8,13,e,n+2*a[o++]),Lf(3,4,9,14,e,n+2*a[o++]),Bf(3,4,9,14,e,n+2*a[o++]);this.v0l^=ut[0]^ut[16],this.v0h^=ut[1]^ut[17],this.v1l^=ut[2]^ut[18],this.v1h^=ut[3]^ut[19],this.v2l^=ut[4]^ut[20],this.v2h^=ut[5]^ut[21],this.v3l^=ut[6]^ut[22],this.v3h^=ut[7]^ut[23],this.v4l^=ut[8]^ut[24],this.v4h^=ut[9]^ut[25],this.v5l^=ut[10]^ut[26],this.v5h^=ut[11]^ut[27],this.v6l^=ut[12]^ut[28],this.v6h^=ut[13]^ut[29],this.v7l^=ut[14]^ut[30],this.v7h^=ut[15]^ut[31],al(ut)}destroy(){this.destroyed=!0,al(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const i1t=T0t(t=>new r1t(t)),s1t="https://rpc.walletconnect.org/v1";function lye(t){const e=`Ethereum Signed Message:
|